diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 300f6437ce..3a266f88b2 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -31,7 +31,7 @@ jobs: - name: Install SwiftFormat env: - SWIFTFORMAT_VERSION: 0.63.0 + SWIFTFORMAT_VERSION: 0.64.5 run: | # Pinned rather than using the runner image's preinstalled build, so an # image update cannot change the lint result without a commit here. diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fc4d65b8cb..6490d47743 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -25,9 +25,11 @@ jobs: - name: Test MeshCore run: | + # The 8 minute kill starts after the build, so compile time is not part of the test budget. + swift build --package-path MeshCore --build-tests run_tests() { rm -f "$RUNNER_TEMP/watchdog-fired" - swift test --package-path MeshCore --no-parallel & + swift test --package-path MeshCore --no-parallel --skip-build & TEST_PID=$! ( sleep 480 @@ -63,9 +65,11 @@ jobs: - name: Test MC1Services run: | + # The 8 minute kill starts after the build, so compile time is not part of the test budget. + swift build --package-path MC1Services --build-tests run_tests() { rm -f "$RUNNER_TEMP/watchdog-fired" - swift test --package-path MC1Services --no-parallel & + swift test --package-path MC1Services --no-parallel --skip-build & TEST_PID=$! ( sleep 480 diff --git a/.swiftformat b/.swiftformat index 193857fb2b..0a8cbbf13b 100644 --- a/.swiftformat +++ b/.swiftformat @@ -50,6 +50,7 @@ --disable wrapIfStatementBodies # single-line early returns and `if case` checks stay on one line --disable wrapIfExpressionBodies # same, for if-expression branches --disable redundantSwiftUIGroup # mis-parses Group(subviews:) into uncompilable code, and strips Groups whose modifiers must not reapply per-child +--disable repeatedGuard # consecutive guards with the same exit stay on their own lines # Leave file headers untouched --header ignore diff --git a/MC1/Extensions/ContactType+Display.swift b/MC1/Extensions/ContactType+Display.swift index e976c2ecf5..c3b447c936 100644 --- a/MC1/Extensions/ContactType+Display.swift +++ b/MC1/Extensions/ContactType+Display.swift @@ -8,6 +8,7 @@ extension ContactType { case .chat: L10n.Contacts.Contacts.NodeKind.contact case .repeater: L10n.Contacts.Contacts.NodeKind.repeater case .room: L10n.Contacts.Contacts.NodeKind.room + case .sensor: L10n.Contacts.Contacts.NodeKind.sensor } } @@ -16,6 +17,7 @@ extension ContactType { case .chat: "person.fill" case .repeater: "antenna.radiowaves.left.and.right" case .room: "person.3.fill" + case .sensor: "sensor" } } @@ -24,6 +26,7 @@ extension ContactType { case .chat: .blue case .repeater: .green case .room: .purple + case .sensor: .gray } } @@ -32,6 +35,7 @@ extension ContactType { case .chat: .contactChat case .repeater: .contactRepeater case .room: .contactRoom + case .sensor: .contactSensor } } } diff --git a/MC1/Extensions/Errors/Error+UserFacingMessage.swift b/MC1/Extensions/Errors/Error+UserFacingMessage.swift index 5df6f3fdd3..7d47c3271f 100644 --- a/MC1/Extensions/Errors/Error+UserFacingMessage.swift +++ b/MC1/Extensions/Errors/Error+UserFacingMessage.swift @@ -15,6 +15,9 @@ extension Error { case let error as AppBackupError: error.userFacingMessage case let error as BLEError: error.userFacingMessage case let error as ConnectionError: error.userFacingMessage + case let error as IdentityImportRecoveryRequired: + L10n.Settings.ConfigImport.identityOutcomeUnknown(error.recovery.sourceName) + case let error as ConnectionRequestFailure: error.underlying.userFacingMessage case let error as WiFiTransportError: error.userFacingMessage case let error as AccessorySetupKitError: error.userFacingMessage case let error as ContactServiceError: error.userFacingMessage diff --git a/MC1/Extensions/Errors/MessageServiceError+UserFacingMessage.swift b/MC1/Extensions/Errors/MessageServiceError+UserFacingMessage.swift index 2cafb9300b..dd12c79593 100644 --- a/MC1/Extensions/Errors/MessageServiceError+UserFacingMessage.swift +++ b/MC1/Extensions/Errors/MessageServiceError+UserFacingMessage.swift @@ -11,7 +11,7 @@ extension MessageServiceError { L10n.Localizable.Error.MessageService.contactNotFound case .channelNotFound: L10n.Localizable.Error.MessageService.channelNotFound - case .sendFailed: + case .sendFailed, .persistenceError: L10n.Localizable.Error.MessageService.sendFailed case .invalidRecipient: L10n.Localizable.Error.MessageService.invalidRecipient diff --git a/MC1/Extensions/Errors/RemoteNodeError+UserFacingMessage.swift b/MC1/Extensions/Errors/RemoteNodeError+UserFacingMessage.swift index 83aa272ca7..b42719eb79 100644 --- a/MC1/Extensions/Errors/RemoteNodeError+UserFacingMessage.swift +++ b/MC1/Extensions/Errors/RemoteNodeError+UserFacingMessage.swift @@ -5,6 +5,14 @@ extension RemoteNodeError { /// package-level `errorDescription` stays the developer-facing fallback. var userFacingMessage: String { switch self { + case .invalidPasswordLength: + L10n.Localizable.Error.RemoteNode.invalidPasswordLength(ProtocolLimits.maxRemotePasswordBytes) + case .invalidSensorSetting: + L10n.Localizable.Error.RemoteNode.invalidSensorSetting + case .sensorSettingRejected: + L10n.Localizable.Error.RemoteNode.sensorSettingRejected + case .sensorOutcomeUnknown: + L10n.Localizable.Error.RemoteNode.sensorOutcomeUnknown case .notConnected: L10n.Localizable.Error.RemoteNode.notConnected case .loginFailed: diff --git a/MC1/Extensions/IdentityImportRecovery+Presentation.swift b/MC1/Extensions/IdentityImportRecovery+Presentation.swift new file mode 100644 index 0000000000..f5a153cd40 --- /dev/null +++ b/MC1/Extensions/IdentityImportRecovery+Presentation.swift @@ -0,0 +1,12 @@ +import MC1Services + +extension IdentityImportRecovery { + var targetDescription: String { + switch capturedConnectionMethod { + case let .bluetooth(peripheralUUID, _): + "\(L10n.Settings.Bluetooth.header): \(peripheralUUID.uuidString)" + case let .wifi(host, port, _): + "\(L10n.Settings.Connection.Link.wifi): \(host):\(port)" + } + } +} diff --git a/MC1/Extensions/View+LiquidGlass.swift b/MC1/Extensions/View+LiquidGlass.swift index dd8bc8c07f..12edfdad77 100644 --- a/MC1/Extensions/View+LiquidGlass.swift +++ b/MC1/Extensions/View+LiquidGlass.swift @@ -80,13 +80,11 @@ extension View { } } -/// Drop-in replacement for `Menu` that works around an iPadOS 26 Liquid Glass bug -/// where toolbar Menus leave a ghost box after dismissal. -/// -/// On iOS 26+, renders the label as a plain view with an invisible interactive `Menu` -/// overlay, so the glass morph animation has nothing visible to ghost. -/// On earlier iOS versions, uses a standard `Menu`. +/// On iOS 26 the menu label is a clear rectangle under `colorMultiply(.clear)`. +/// The glass morph has no icon to follow, and dismissal leaves no leftover glass box. +/// `accessibilityLabel` names the menu; the visible label is hidden from VoiceOver. struct ToolbarMenu: View { + let accessibilityLabel: String @ViewBuilder let content: Content @ViewBuilder let label: LabelView @@ -105,9 +103,11 @@ struct ToolbarMenu: View { .contentShape(Rectangle()) } .colorMultiply(.clear) + .accessibilityLabel(accessibilityLabel) } } else { Menu { content } label: { label } + .accessibilityLabel(accessibilityLabel) } } } diff --git a/MC1/Intents/AppState+IntentRefresh.swift b/MC1/Intents/AppState+IntentRefresh.swift index 52efe48079..cfd11cc8a2 100644 --- a/MC1/Intents/AppState+IntentRefresh.swift +++ b/MC1/Intents/AppState+IntentRefresh.swift @@ -10,8 +10,7 @@ func shouldPublishRecipientIDs( currentRadioID: UUID?, fresh: Set ) -> Bool { - guard let capturedRadioID, capturedRadioID == currentRadioID else { return false } - guard fresh == captured else { return false } + guard let capturedRadioID, capturedRadioID == currentRadioID, fresh == captured else { return false } return captured != previous } @@ -44,8 +43,7 @@ extension AppState { fresh = [] } - guard !Task.isCancelled, connectionManager.services === expectedServices else { return } - guard shouldPublishRecipientIDs( + guard !Task.isCancelled, connectionManager.services === expectedServices, shouldPublishRecipientIDs( previous: lastPublishedRecipientIDs, capturedRadioID: capturedRadioID, captured: captured, diff --git a/MC1/Intents/SendMessageIntent+Routing.swift b/MC1/Intents/SendMessageIntent+Routing.swift index 90fdb4e2b5..55f1eacc47 100644 --- a/MC1/Intents/SendMessageIntent+Routing.swift +++ b/MC1/Intents/SendMessageIntent+Routing.swift @@ -62,7 +62,7 @@ extension SendMessageIntent { case .invalidRecipient, .contactNotFound, .channelNotFound: .invalidRecipient case .messageTooLong: .messageTooLong case let .sessionError(underlying): .sessionError(underlying) - case .sendFailed: .sendFailed + case .sendFailed, .persistenceError: .sendFailed } case let serviceError as ChannelServiceError: switch serviceError { diff --git a/MC1/Intents/SendMessageIntent.swift b/MC1/Intents/SendMessageIntent.swift index 39c3348546..3b5c871388 100644 --- a/MC1/Intents/SendMessageIntent.swift +++ b/MC1/Intents/SendMessageIntent.swift @@ -153,46 +153,23 @@ struct SendMessageIntent: AppIntent { let nodeNameByteCount = appState.connectedDevice?.nodeName.utf8.count ?? 0 try validate(message: message, for: recipient, nodeNameByteCount: nodeNameByteCount) - let pending: MessageDTO + let admission: ChatSendAdmission do { switch recipient { case let .contact(dto): - pending = try await services.messageService.createPendingMessage(text: message, to: dto) + admission = try await services.chatSendQueueService.enqueueDirectMessage(text: message, to: dto) case let .channel(dto): - pending = try await services.messageService.createPendingChannelMessage( + admission = try await services.chatSendQueueService.enqueueChannelMessage( text: message, - channelIndex: dto.index, - radioID: dto.radioID + to: dto, + localNodeName: appState.connectedDevice?.nodeName ) } } catch { throw mapToIntentError(error) } - do { - switch recipient { - case let .contact(dto): - try await services.chatSendQueueService.enqueueDM( - DirectMessageEnvelope(messageID: pending.id, contactID: dto.id) - ) - case let .channel(dto): - try await services.chatSendQueueService.enqueueChannel( - ChannelMessageEnvelope( - messageID: pending.id, - channelIndex: dto.index, - isResend: false, - messageText: pending.text, - messageTimestamp: pending.timestamp, - localNodeName: appState.connectedDevice?.nodeName - ) - ) - } - } catch { - // The row is already persisted as `.pending`, but the enqueue write - // failed so no `PendingSend` backs it and the drain never sends it. - // Mark it `.failed` so it surfaces a retry instead of hanging pending, - // the same recovery the chat send path performs. - _ = try? await services.dataStore.updateMessageStatusUnlessDelivered(id: pending.id, status: .failed) + if case let .enqueueFailed(_, error) = admission { throw mapToIntentError(error) } // A headless send never crosses the chat view model that an in-app send diff --git a/MC1/MC1App.swift b/MC1/MC1App.swift index 237a33c202..b401aa5e79 100644 --- a/MC1/MC1App.swift +++ b/MC1/MC1App.swift @@ -22,6 +22,7 @@ struct MC1App: App { private let pendingExternalURL = PendingExternalURL() init() { + MacSuspendLockMarker.markIfNeeded() OfflineMapNetwork.configure() // Register the bridge synchronously here: a background-launched intent // runs only `App.init` (no scene, no `.task`), so a deferred @@ -198,6 +199,7 @@ struct MC1App: App { } private func handleScenePhaseChange(from oldPhase: ScenePhase, to newPhase: ScenePhase) { + MacSuspendLockMarker.markIfNeeded() appState.logToolbarResumeProbe( source: "scenePhase", scene: "\(scenePhaseName(oldPhase))->\(scenePhaseName(newPhase))" diff --git a/MC1/Models/WhatsNew/WhatsNewCatalog.swift b/MC1/Models/WhatsNew/WhatsNewCatalog.swift index faedb99ea9..36d9dea39b 100644 --- a/MC1/Models/WhatsNew/WhatsNewCatalog.swift +++ b/MC1/Models/WhatsNew/WhatsNewCatalog.swift @@ -4,6 +4,32 @@ import Foundation /// release as one `WhatsNewRelease` plus its `L10n` strings; it presents once on upgrade. enum WhatsNewCatalog { static let releases: [WhatsNewRelease] = [ + WhatsNewRelease( + version: WhatsNewVersion(major: 1, minor: 7), + items: [ + WhatsNewItem( + symbol: "line.3.horizontal.decrease", + title: L10n.WhatsNew.WhatsNew.BlocksAndFilters.title, + description: L10n.WhatsNew.WhatsNew.BlocksAndFilters.description + ), + WhatsNewItem( + symbol: "paperplane", + title: L10n.WhatsNew.WhatsNew.DirectMessages.title, + description: L10n.WhatsNew.WhatsNew.DirectMessages.description + ), + WhatsNewItem( + symbol: "gauge.with.dots.needle.67percent", + title: L10n.WhatsNew.WhatsNew.NodeTelemetry.title, + description: L10n.WhatsNew.WhatsNew.NodeTelemetry.description + ), + WhatsNewItem( + symbol: "platter.filled.bottom.and.arrow.down.iphone", + title: L10n.WhatsNew.WhatsNew.LiveActivity.title, + description: L10n.WhatsNew.WhatsNew.LiveActivity.description + ) + ], + releaseNotesURL: URL(string: "https://github.com/Avi0n/MeshCoreOne/releases/tag/v1.7.0")! + ), WhatsNewRelease( version: WhatsNewVersion(major: 1, minor: 6), items: [ diff --git a/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index b84a3a5932..d5bd7fdd64 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -591,6 +591,14 @@ public enum L10n { } } public enum Message { + /// Location: MECPCatalog - Person count line in an MECP reading + public static func mecpPersonCount(_ p1: Int) -> String { + return L10n.tr("Chats", "chats.message.mecpPersonCount", p1, fallback: "%lld people") + } + /// Location: MessageVisibleBody.swift - VoiceOver prefix when the visible body is an MECP reading - %@ is the reading + public static func readingAccessibility(_ p1: Any) -> String { + return L10n.tr("Chats", "chats.message.readingAccessibility", String(describing: p1), fallback: "Reading: %@") + } /// Location: UnifiedMessageBubble.swift - VoiceOver prefix when the visible body is a translation - %@ is the translated text public static func translatedAccessibility(_ p1: Any) -> String { return L10n.tr("Chats", "chats.message.translatedAccessibility", String(describing: p1), fallback: "Translated: %@") @@ -698,6 +706,10 @@ public enum L10n { public static func hops(_ p1: Any) -> String { return L10n.tr("Chats", "chats.message.info.hops", String(describing: p1), fallback: "Hops: %@") } + /// Location: ActionsDetailsSection.swift - Stored MECP wire string under SNR. %@ is the original text + public static func mecp(_ p1: Any) -> String { + return L10n.tr("Chats", "chats.message.info.mecp", String(describing: p1), fallback: "MECP: %@") + } /// Location: ActionsDetailsSection.swift - Info row showing the raw uncorrected wire send time when the timestamp was corrected - %@ is formatted date public static func originalSendTime(_ p1: Any) -> String { return L10n.tr("Chats", "chats.message.info.originalSendTime", String(describing: p1), fallback: "Original send time: %@") @@ -1526,6 +1538,8 @@ public enum L10n { public static let repeaters = L10n.tr("Contacts", "contacts.discovery.segment.repeaters", fallback: "Repeaters") /// Location: DiscoveryView.swift - Purpose: Segment filter: Rooms public static let rooms = L10n.tr("Contacts", "contacts.discovery.segment.rooms", fallback: "Rooms") + /// Sensors + public static let sensors = L10n.tr("Contacts", "contacts.discovery.segment.sensors", fallback: "Sensors") } } public enum List { @@ -1598,6 +1612,12 @@ public enum L10n { /// Location: ContactsListView.swift - Purpose: No search results title public static let title = L10n.tr("Contacts", "contacts.list.empty.search.title", fallback: "No Results") } + public enum Sensors { + /// Sensors appear here when discovered on the mesh. + public static let description = L10n.tr("Contacts", "contacts.list.empty.sensors.description", fallback: "Sensors appear here when discovered on the mesh.") + /// No Sensors + public static let title = L10n.tr("Contacts", "contacts.list.empty.sensors.title", fallback: "No Sensors") + } } } public enum NodeKind { @@ -1611,6 +1631,8 @@ public enum L10n { public static let repeater = L10n.tr("Contacts", "contacts.nodeKind.repeater", fallback: "Repeater") /// Location: Multiple files - Purpose: Room contact type label public static let room = L10n.tr("Contacts", "contacts.nodeKind.room", fallback: "Room") + /// Sensor + public static let sensor = L10n.tr("Contacts", "contacts.nodeKind.sensor", fallback: "Sensor") } public enum PathDetail { /// Location: SavedPathDetailView.swift - Purpose: Average stat label @@ -2089,6 +2111,8 @@ public enum L10n { public static let repeaters = L10n.tr("Contacts", "contacts.segment.repeaters", fallback: "Repeaters") /// Location: ContactsViewModel.swift - Purpose: Rooms segment public static let rooms = L10n.tr("Contacts", "contacts.segment.rooms", fallback: "Rooms") + /// Sensors + public static let sensors = L10n.tr("Contacts", "contacts.segment.sensors", fallback: "Sensors") } public enum Share { /// Location: ContactQRShareSheet.swift - Purpose: Contact label in share text, %@ is contact name @@ -2647,8 +2671,14 @@ public enum L10n { public static let contactNotFound = L10n.tr("Localizable", "error.remoteNode.contactNotFound", fallback: "Contact not found in database") /// Location: RemoteNodeError+UserFacingMessage.swift - Keep-alive needs a direct path but the route is flood-routed public static let floodRouted = L10n.tr("Localizable", "error.remoteNode.floodRouted", fallback: "Keep-alive requires direct routing path") + /// Passwords must use no more than %d UTF-8 bytes. + public static func invalidPasswordLength(_ p1: Int) -> String { + return L10n.tr("Localizable", "error.remoteNode.invalidPasswordLength", p1, fallback: "Passwords must use no more than %d UTF-8 bytes.") + } /// Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node public static let invalidResponse = L10n.tr("Localizable", "error.remoteNode.invalidResponse", fallback: "Invalid response from remote node") + /// Use a nonempty key and value without whitespace. The complete command must fit within 160 UTF-8 bytes. + public static let invalidSensorSetting = L10n.tr("Localizable", "error.remoteNode.invalidSensorSetting", fallback: "Use a nonempty key and value without whitespace. The complete command must fit within 160 UTF-8 bytes.") /// Location: RemoteNodeError+UserFacingMessage.swift - Remote node login failed public static let loginFailed = L10n.tr("Localizable", "error.remoteNode.loginFailed", fallback: "Login failed.") /// Location: RemoteNodeError+UserFacingMessage.swift - No active connection to the mesh radio @@ -2663,6 +2693,10 @@ public enum L10n { public static let radioContactsFull = L10n.tr("Localizable", "error.remoteNode.radioContactsFull", fallback: "Your radio is out of contact slots. Remove a contact you no longer need, then retry sign-in.") /// Location: RemoteNodeError+UserFacingMessage.swift - Sending to the remote node failed public static let sendFailed = L10n.tr("Localizable", "error.remoteNode.sendFailed", fallback: "Failed to send.") + /// The change could not be verified. Reload settings before saving again. + public static let sensorOutcomeUnknown = L10n.tr("Localizable", "error.remoteNode.sensorOutcomeUnknown", fallback: "The change could not be verified. Reload settings before saving again.") + /// The sensor rejected this setting. + public static let sensorSettingRejected = L10n.tr("Localizable", "error.remoteNode.sensorSettingRejected", fallback: "The sensor rejected this setting.") /// Location: RemoteNodeError+UserFacingMessage.swift - No stored session for the remote node public static let sessionNotFound = L10n.tr("Localizable", "error.remoteNode.sessionNotFound", fallback: "Remote node session not found") /// Location: RemoteNodeError+UserFacingMessage.swift - Remote node request timed out @@ -2757,6 +2791,8 @@ public enum L10n { public static let repeater = L10n.tr("Localizable", "notifications.discovery.repeater", fallback: "New Repeater Discovered") /// Notification title when a new room is discovered on the mesh network public static let room = L10n.tr("Localizable", "notifications.discovery.room", fallback: "New Room Discovered") + /// New Sensor Discovered + public static let sensor = L10n.tr("Localizable", "notifications.discovery.sensor", fallback: "New Sensor Discovered") /// Fallback display name for a discovered contact with no advertised name public static let unknownContact = L10n.tr("Localizable", "notifications.discovery.unknownContact", fallback: "Unknown Contact") } @@ -2822,6 +2858,8 @@ public enum L10n { public static let repeater = L10n.tr("Map", "map.callout.nodeKind.repeater", fallback: "Repeater") /// Location: ContactCalloutContent.swift - Purpose: Display name for room in callout public static let room = L10n.tr("Map", "map.callout.nodeKind.room", fallback: "Room") + /// Sensor + public static let sensor = L10n.tr("Map", "map.callout.nodeKind.sensor", fallback: "Sensor") } } public enum Common { @@ -2835,6 +2873,8 @@ public enum L10n { public static let centerOnMyLocation = L10n.tr("Map", "map.controls.centerOnMyLocation", fallback: "Center on my location") /// Location: MapControlsToolbar.swift - Purpose: Map options menu toggle that clusters nearby pins public static let clusterNodes = L10n.tr("Map", "map.controls.clusterNodes", fallback: "Cluster nodes") + /// Contacts & Sensors + public static let contactsAndSensors = L10n.tr("Map", "map.controls.contactsAndSensors", fallback: "Contacts & Sensors") /// Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control public static let filter = L10n.tr("Map", "map.controls.filter", fallback: "Filter") /// Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults @@ -3039,6 +3079,8 @@ public enum L10n { public static let repeater = L10n.tr("Map", "map.nodeKind.repeater", fallback: "Repeater") /// Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type public static let room = L10n.tr("Map", "map.nodeKind.room", fallback: "Room") + /// Sensor + public static let sensor = L10n.tr("Map", "map.nodeKind.sensor", fallback: "Sensor") } public enum OfflineBadge { /// Label shown on map when device has no internet connection @@ -3084,8 +3126,6 @@ public enum L10n { public static let addDevice = L10n.tr("Onboarding", "deviceScan.addDevice", fallback: "Add Device") /// Location: DeviceScanView.swift - Message shown when device is already paired public static let alreadyPaired = L10n.tr("Onboarding", "deviceScan.alreadyPaired", fallback: "Your device is already paired") - /// Location: DeviceScanView.swift - Button label while connecting - public static let connecting = L10n.tr("Onboarding", "deviceScan.connecting", fallback: "Connecting...") /// Location: DeviceScanView.swift - Button to connect simulator (debug) public static let connectSimulator = L10n.tr("Onboarding", "deviceScan.connectSimulator", fallback: "Connect Simulator") /// Location: DeviceScanView.swift - Button to connect via WiFi @@ -3098,6 +3138,8 @@ public enum L10n { public static let deviceNotAppearing = L10n.tr("Onboarding", "deviceScan.deviceNotAppearing", fallback: "Help") /// Location: DeviceScanView.swift - "I don't have a device yet" tertiary public static let noDeviceYet = L10n.tr("Onboarding", "deviceScan.noDeviceYet", fallback: "I don't have a device yet") + /// Location: DeviceScanView.swift - Subtitle while bond-loss recovery is re-pairing + public static let rePairingSubtitle = L10n.tr("Onboarding", "deviceScan.rePairingSubtitle", fallback: "Power your radio on and disconnect it from all other apps and devices.") /// Location: DeviceScanView.swift - Button to retry connection after other-app conflict public static let retryConnection = L10n.tr("Onboarding", "deviceScan.retryConnection", fallback: "Retry Connection") /// Location: DeviceScanView.swift - Subtitle with pairing instructions @@ -3359,8 +3401,10 @@ public enum L10n { public static func errorPrefix(_ p1: Any) -> String { return L10n.tr("RemoteNodes", "remoteNodes.auth.errorPrefix", String(describing: p1), fallback: "Error: %@") } - /// Flood routing is slower and uses more network airtime. Use it when the known route does not work from your current location. A new route is learned automatically after login. - public static let floodFooter = L10n.tr("RemoteNodes", "remoteNodes.auth.floodFooter", fallback: "Flood routing is slower and uses more network airtime. Use it when the known route does not work from your current location. A new route is learned automatically after login.") + /// Footer when this sign-in will clear the saved route and use flood + public static let floodFooter = L10n.tr("RemoteNodes", "remoteNodes.auth.floodFooter", fallback: "This sign-in clears the saved route and uses flood. Flood routing is slower and uses more network airtime. A new route is learned if sign-in succeeds.") + /// Footer after this sign-in has cleared the saved route + public static let floodFooterCleared = L10n.tr("RemoteNodes", "remoteNodes.auth.floodFooterCleared", fallback: "The saved route is cleared. Sign-in is using flood. A new route is learned if sign-in succeeds.") /// No reply over the known route. Retrying with flood routing. public static let floodRetryStatus = L10n.tr("RemoteNodes", "remoteNodes.auth.floodRetryStatus", fallback: "No reply over the known route. Retrying with flood routing.") /// Location: NodeAuthenticationSheet.swift - Flood routing toggle @@ -3389,8 +3433,10 @@ public enum L10n { } /// Location: NodeAuthenticationSheet.swift - Path section header public static let path = L10n.tr("RemoteNodes", "remoteNodes.auth.path", fallback: "Path") - /// Location: NodeAuthenticationSheet.swift - Path section footer when stored path exists - public static let pathFooter = L10n.tr("RemoteNodes", "remoteNodes.auth.pathFooter", fallback: "Use the known route to this node, or switch to flood routing to let the network find a path.") + /// Footer when a timeout clears the route and retries by flood + public static let pathFooter = L10n.tr("RemoteNodes", "remoteNodes.auth.pathFooter", fallback: "If there is no reply, the route is cleared and sign-in tries once by flood.") + /// Footer when a timeout stops and leaves the route + public static let pathFooterKept = L10n.tr("RemoteNodes", "remoteNodes.auth.pathFooterKept", fallback: "If there is no reply, sign-in stops and the route stays.") /// Location: NodeAuthenticationSheet.swift - Path hop whose repeater is not known public static let pathHopUnknown = L10n.tr("RemoteNodes", "remoteNodes.auth.pathHopUnknown", fallback: "") /// Location: NodeAuthenticationSheet.swift - Remember password toggle @@ -3409,6 +3455,8 @@ public enum L10n { public static let typeRepeater = L10n.tr("RemoteNodes", "remoteNodes.auth.typeRepeater", fallback: "Repeater") /// Location: NodeAuthenticationSheet.swift - Room type value public static let typeRoom = L10n.tr("RemoteNodes", "remoteNodes.auth.typeRoom", fallback: "Room") + /// Sensor + public static let typeSensor = L10n.tr("RemoteNodes", "remoteNodes.auth.typeSensor", fallback: "Sensor") } public enum History { /// Location: NodeStatusHistoryView.swift - Time range picker @@ -3622,6 +3670,28 @@ public enum L10n { /// Location: RoomStatusView.swift - Navigation title public static let title = L10n.tr("RemoteNodes", "remoteNodes.roomStatus.title", fallback: "Room Status") } + public enum Sensor { + /// Sensor management requires administrator access. + public static let adminRequired = L10n.tr("RemoteNodes", "remoteNodes.sensor.adminRequired", fallback: "Sensor management requires administrator access.") + /// This sensor exposes no settings. + public static let empty = L10n.tr("RemoteNodes", "remoteNodes.sensor.empty", fallback: "This sensor exposes no settings.") + /// Send a reboot request to this sensor? + public static let rebootConfirmation = L10n.tr("RemoteNodes", "remoteNodes.sensor.rebootConfirmation", fallback: "Send a reboot request to this sensor?") + /// Reboot request sent. The sensor has not confirmed a restart. Authenticate again before sending more commands. + public static let rebootSent = L10n.tr("RemoteNodes", "remoteNodes.sensor.rebootSent", fallback: "Reboot request sent. The sensor has not confirmed a restart. Authenticate again before sending more commands.") + /// Reload + public static let reload = L10n.tr("RemoteNodes", "remoteNodes.sensor.reload", fallback: "Reload") + /// Changes affect the running sensor. Persistence across reboot depends on its firmware. + public static let runtimeOnly = L10n.tr("RemoteNodes", "remoteNodes.sensor.runtimeOnly", fallback: "Changes affect the running sensor. Persistence across reboot depends on its firmware.") + /// Save + public static let save = L10n.tr("RemoteNodes", "remoteNodes.sensor.save", fallback: "Save") + /// Setting verified. + public static let saved = L10n.tr("RemoteNodes", "remoteNodes.sensor.saved", fallback: "Setting verified.") + /// Sensor Management + public static let title = L10n.tr("RemoteNodes", "remoteNodes.sensor.title", fallback: "Sensor Management") + /// Value + public static let value = L10n.tr("RemoteNodes", "remoteNodes.sensor.value", fallback: "Value") + } public enum Settings { /// Location: RepeaterSettingsView.swift - Advert interval (0-hop) label public static let advertInterval0Hop = L10n.tr("RemoteNodes", "remoteNodes.settings.advertInterval0Hop", fallback: "Advert Interval (0-hop)") @@ -4426,6 +4496,12 @@ public enum L10n { public enum BleStatus { /// Accessibility label for BLE status indicator public static let accessibilityLabel = L10n.tr("Settings", "bleStatus.accessibilityLabel", fallback: "Bluetooth connection status") + /// Accessibility text combining a descriptive prefix and connection state or context; arguments may themselves contain a radio name and status + public static func accessibilityValue(_ p1: Any, _ p2: Any) -> String { + return L10n.tr("Settings", "bleStatus.accessibilityValue", String(describing: p1), String(describing: p2), fallback: "%1$@, %2$@") + } + /// Menu item to cancel the current connection request + public static let cancelConnection = L10n.tr("Settings", "bleStatus.cancelConnection", fallback: "Cancel Connection") /// Menu item to change the connected device public static let changeDevice = L10n.tr("Settings", "bleStatus.changeDevice", fallback: "Change Device") /// Menu item to disconnect from the current device @@ -4436,6 +4512,8 @@ public enum L10n { public static let sendFloodAdvert = L10n.tr("Settings", "bleStatus.sendFloodAdvert", fallback: "Send Flood Advert") /// Menu item to send a zero-hop advertisement public static let sendZeroHopAdvert = L10n.tr("Settings", "bleStatus.sendZeroHopAdvert", fallback: "Send Zero-Hop Advert") + /// Menu item to stop automatic reconnection until another explicit connection + public static let stopReconnecting = L10n.tr("Settings", "bleStatus.stopReconnecting", fallback: "Stop Reconnecting") public enum AccessibilityHint { /// Accessibility hint when connected public static let connected = L10n.tr("Settings", "bleStatus.accessibilityHint.connected", fallback: "Shows device connection options") @@ -4459,8 +4537,12 @@ public enum L10n { public static let disconnected = L10n.tr("Settings", "bleStatus.status.disconnected", fallback: "Disconnected") /// Status shown when device is ready public static let ready = L10n.tr("Settings", "bleStatus.status.ready", fallback: "Ready") + /// Status shown while reconnecting to the selected device + public static let reconnecting = L10n.tr("Settings", "bleStatus.status.reconnecting", fallback: "Reconnecting…") /// Status shown when device is syncing data public static let syncing = L10n.tr("Settings", "bleStatus.status.syncing", fallback: "Syncing") + /// Status shown while automatic reconnection remains enabled between attempts + public static let waitingToReconnect = L10n.tr("Settings", "bleStatus.status.waitingToReconnect", fallback: "Waiting to Reconnect") } } public enum Blocking { @@ -4481,6 +4563,10 @@ public enum L10n { } } } + public enum BlocksAndFilters { + /// Blocks & Filters + public static let title = L10n.tr("Settings", "blocksAndFilters.title", fallback: "Blocks & Filters") + } public enum Bluetooth { /// Button to change the device display name public static let changeDisplayName = L10n.tr("Settings", "bluetooth.changeDisplayName", fallback: "Change Display Name") @@ -4610,6 +4696,10 @@ public enum L10n { public static func channelCount(_ p1: Int) -> String { return L10n.tr("Settings", "configImport.channelCount", p1, fallback: "Will add/update %d channels on device") } + /// Interrupted identity import recovery + public static func confirmIdentityRecovery(_ p1: Any) -> String { + return L10n.tr("Settings", "configImport.confirmIdentityRecovery", String(describing: p1), fallback: "This will replace the identity of the radio reached at %@ using the private key in the selected file. The configuration import will not continue.") + } /// Confirmation alert message (param: device name) public static func confirmMessage(_ p1: Any) -> String { return L10n.tr("Settings", "configImport.confirmMessage", String(describing: p1), fallback: "This will merge the selected settings into %@. Existing channels and contacts will be updated or added.") @@ -4630,6 +4720,8 @@ public enum L10n { public static let confirmTitle = L10n.tr("Settings", "configImport.confirmTitle", fallback: "Apply Configuration?") /// Confirmation alert title (additive only) public static let confirmTitleAdd = L10n.tr("Settings", "configImport.confirmTitleAdd", fallback: "Add to Device?") + /// Confirmation alert title when retrying an interrupted identity import + public static let confirmTitleIdentityRecovery = L10n.tr("Settings", "configImport.confirmTitleIdentityRecovery", fallback: "Replace Radio Identity?") /// Confirmation alert title (overwrite settings) public static let confirmTitleOverwrite = L10n.tr("Settings", "configImport.confirmTitleOverwrite", fallback: "Overwrite Settings?") /// Contact count (param: integer) @@ -4644,6 +4736,14 @@ public enum L10n { public static func failedPartial(_ p1: Any) -> String { return L10n.tr("Settings", "configImport.failedPartial", String(describing: p1), fallback: "%@ Some settings may have already been written to the device. Review the device's configuration.") } + /// Interrupted identity import recovery + public static func identityOutcomeUnknown(_ p1: Any) -> String { + return L10n.tr("Settings", "configImport.identityOutcomeUnknown", String(describing: p1), fallback: "The connection was interrupted while importing the identity on %@. The radio may have changed identity. The configuration import was not completed.") + } + /// Interrupted identity import recovery + public static let identityRecoveryComplete = L10n.tr("Settings", "configImport.identityRecoveryComplete", fallback: "The identity was reapplied. The configuration import was not completed. Import the file again to apply its other settings.") + /// Interrupted identity import recovery + public static let identityRecoveryKeyRequired = L10n.tr("Settings", "configImport.identityRecoveryKeyRequired", fallback: "Select a configuration file containing the private key to retry identity import.") /// Import navigation row label public static let importConfig = L10n.tr("Settings", "configImport.importConfig", fallback: "Import Config") /// Import success @@ -4658,6 +4758,8 @@ public enum L10n { public static let proximityWarning = L10n.tr("Settings", "configImport.proximityWarning", fallback: "Keep devices close together during import") /// Radio settings change warning public static let radioWarning = L10n.tr("Settings", "configImport.radioWarning", fallback: "Changing radio settings will disconnect from the current mesh network") + /// Interrupted identity import recovery + public static let retryIdentityImport = L10n.tr("Settings", "configImport.retryIdentityImport", fallback: "Retry Identity Import") /// Select file button public static let selectFile = L10n.tr("Settings", "configImport.selectFile", fallback: "Select JSON File") /// Import progress: importing a channel (param: channel name) @@ -4844,8 +4946,6 @@ public enum L10n { public enum Device { /// Button to connect a device public static let connect = L10n.tr("Settings", "device.connect", fallback: "Connect Device") - /// Status shown when device is connected - public static let connected = L10n.tr("Settings", "device.connected", fallback: "Connected") /// Section header for device information public static let header = L10n.tr("Settings", "device.header", fallback: "Device") /// Footer shown when no device is connected @@ -4894,6 +4994,8 @@ public enum L10n { public static func firmwareVersionFormat(_ p1: Any) -> String { return L10n.tr("Settings", "deviceInfo.firmwareVersionFormat", String(describing: p1), fallback: "v%@") } + /// Heading above retained telemetry after a Device Info reload fails + public static let lastSuccessfulReading = L10n.tr("Settings", "deviceInfo.lastSuccessfulReading", fallback: "Last successful reading") /// Label for manufacturer public static let manufacturer = L10n.tr("Settings", "deviceInfo.manufacturer", fallback: "Manufacturer") /// Label for max channels capability @@ -4920,12 +5022,6 @@ public enum L10n { /// Section header for device capabilities public static let header = L10n.tr("Settings", "deviceInfo.capabilities.header", fallback: "Capabilities") } - public enum Connection { - /// Section header for connection status - public static let header = L10n.tr("Settings", "deviceInfo.connection.header", fallback: "Connection") - /// Label for connection status - public static let status = L10n.tr("Settings", "deviceInfo.connection.status", fallback: "Status") - } public enum Firmware { /// Section header for firmware information public static let header = L10n.tr("Settings", "deviceInfo.firmware.header", fallback: "Firmware") @@ -4940,6 +5036,10 @@ public enum L10n { /// Section header for power and storage public static let header = L10n.tr("Settings", "deviceInfo.powerStorage.header", fallback: "Power & Storage") } + public enum Telemetry { + /// Section header for Device Info telemetry + public static let header = L10n.tr("Settings", "deviceInfo.telemetry.header", fallback: "Node Telemetry") + } } public enum DeviceSelection { /// Fallback connection type description @@ -4960,6 +5060,8 @@ public enum L10n { public static let noPairedDevices = L10n.tr("Settings", "deviceSelection.noPairedDevices", fallback: "No Paired Devices") /// Section header for previously paired devices public static let previouslyPaired = L10n.tr("Settings", "deviceSelection.previouslyPaired", fallback: "Previously Paired") + /// Button title while this radio is being paired again + public static let rePairing = L10n.tr("Settings", "deviceSelection.rePairing", fallback: "Re-pairing...") /// Button to scan for Bluetooth devices public static let scanBluetooth = L10n.tr("Settings", "deviceSelection.scanBluetooth", fallback: "Scan for Bluetooth Device") /// Button to scan for new devices @@ -5012,6 +5114,8 @@ public enum L10n { public enum Diagnostics { /// Button to clear debug logs public static let clearLogs = L10n.tr("Settings", "diagnostics.clearLogs", fallback: "Clear Debug Logs") + /// Toggle to enable collecting local debug logs + public static let collectLogs = L10n.tr("Settings", "diagnostics.collectLogs", fallback: "Collect Debug Logs") /// Button to export debug logs public static let exportLogs = L10n.tr("Settings", "diagnostics.exportLogs", fallback: "Export Debug Logs") /// Footer explaining log export @@ -5027,15 +5131,37 @@ public enum L10n { /// Alert title for clear logs confirmation public static let title = L10n.tr("Settings", "diagnostics.alert.clear.title", fallback: "Clear Debug Logs") } + public enum Disable { + /// Button to confirm disabling collection + public static let confirm = L10n.tr("Settings", "diagnostics.alert.disable.confirm", fallback: "Disable Collection") + /// Alert message for disabling collection + public static let message = L10n.tr("Settings", "diagnostics.alert.disable.message", fallback: "This will delete all stored debug logs and stop collecting them. Exported log files will not be affected.") + /// Alert title for disabling collection + public static let title = L10n.tr("Settings", "diagnostics.alert.disable.title", fallback: "Disable Collection") + } } public enum Error { /// Error when export fails public static let exportFailed = L10n.tr("Settings", "diagnostics.error.exportFailed", fallback: "Failed to create export file") } + public enum Footer { + /// Footer shown when debug log collection is off + public static let disabled = L10n.tr("Settings", "diagnostics.footer.disabled", fallback: "Local debug logs are not collected.") + } } public enum DirectMessages { /// Picker label for number of acknowledgments public static let acknowledgments = L10n.tr("Settings", "directMessages.acknowledgments", fallback: "Acknowledgments") + /// Footer when Fall Back to Flood is off + public static let attemptsFooterOff = L10n.tr("Settings", "directMessages.attemptsFooterOff", fallback: "Attempts on Path stay on the known route, and the route is left in place. A contact with no known route is sent by flood.") + /// Footer when Fall Back to Flood is on + public static let attemptsFooterOn = L10n.tr("Settings", "directMessages.attemptsFooterOn", fallback: "The route is cleared after Attempts on Path. Flood Attempts are sent by flood after that. A contact with no known route is sent by flood.") + /// Picker label for attempts on the known route + public static let directAttempts = L10n.tr("Settings", "directMessages.directAttempts", fallback: "Attempts on Path") + /// Switch that clears the known route after the path attempts + public static let fallback = L10n.tr("Settings", "directMessages.fallback", fallback: "Fall Back to Flood") + /// Picker label for attempts sent by flood after the route is cleared + public static let floodAttempts = L10n.tr("Settings", "directMessages.floodAttempts", fallback: "Flood Attempts") /// Footer explaining the acknowledgments setting public static let footer = L10n.tr("Settings", "directMessages.footer", fallback: "Number of acknowledgments sent per direct message. Use 2 for better delivery confirmation over unreliable links.") /// Section header for direct message settings @@ -5330,6 +5456,8 @@ public enum L10n { public static let contactMessages = L10n.tr("Settings", "notifications.contactMessages", fallback: "Contact Messages") /// Label shown when notifications are disabled public static let disabled = L10n.tr("Settings", "notifications.disabled", fallback: "Notifications Disabled") + /// Companions & Sensors + public static let discoveryCompanionsAndSensors = L10n.tr("Settings", "notifications.discoveryCompanionsAndSensors", fallback: "Companions & Sensors") /// Toggle label for companion discovery notifications public static let discoveryContact = L10n.tr("Settings", "notifications.discoveryContact", fallback: "Companion") /// Toggle label for repeater discovery notifications @@ -5447,6 +5575,16 @@ public enum L10n { public static let topo = L10n.tr("Settings", "offlineMaps.layer.topo", fallback: "Topography") } } + public enum PathFallback { + /// Switch that clears the known route after a timeout + public static let fallback = L10n.tr("Settings", "pathFallback.fallback", fallback: "Fall Back to Flood") + /// Footer when path fallback is off + public static let footerOff = L10n.tr("Settings", "pathFallback.footerOff", fallback: "Sign-in, commands, and contact telemetry stay on the known route. If there is no reply, they stop and the route stays. Flood Routing on the sign-in screen clears that node's saved route.") + /// Footer when path fallback is on + public static let footerOn = L10n.tr("Settings", "pathFallback.footerOn", fallback: "Sign-in, repeater and room commands that expect a reply, and contact telemetry use the known route. If there is no reply, the route is cleared and tried once by flood.") + /// Section header for sign-in, command, and contact telemetry path fallback + public static let header = L10n.tr("Settings", "pathFallback.header", fallback: "Path Fallback") + } public enum PathHashMode { /// Footer explaining path hash mode tradeoff public static let footer = L10n.tr("Settings", "pathHashMode.footer", fallback: "Larger hashes reduce routing collisions but limit the maximum number of hops per path. Repeaters running firmware older than 1.14.0 will not repeat messages with a hash size greater than 1 byte.") @@ -5525,6 +5663,20 @@ public enum L10n { } } } + public enum RadioCleanup { + /// Radio data removed + public static let completed = L10n.tr("Settings", "radioCleanup.completed", fallback: "Radio data removed") + /// Hidden messages from this radio may still be on this installation. + public static let failed = L10n.tr("Settings", "radioCleanup.failed", fallback: "Hidden messages from this radio may still be on this installation.") + /// Try Radio Cleanup Again for %@ + public static func retryAccessibility(_ p1: Any) -> String { + return L10n.tr("Settings", "radioCleanup.retryAccessibility", String(describing: p1), fallback: "Try Radio Cleanup Again for %@") + } + /// Removing radio data + public static let running = L10n.tr("Settings", "radioCleanup.running", fallback: "Removing radio data") + /// Cleanup + public static let title = L10n.tr("Settings", "radioCleanup.title", fallback: "Cleanup") + } public enum RadioWiFi { /// Button that clears the radio's saved WiFi settings public static let clear = L10n.tr("Settings", "radioWiFi.clear", fallback: "Clear WiFi Settings") @@ -5593,6 +5745,8 @@ public enum L10n { public static let nameLength = L10n.tr("Settings", "radioWiFi.editor.nameLength", fallback: "A network name can be up to 32 bytes.") /// Editor footer when the password is too long public static let passwordLength = L10n.tr("Settings", "radioWiFi.editor.passwordLength", fallback: "A password can be up to 63 bytes.") + /// Editor footer when a credential contains a character the firmware cannot store + public static let unsupportedCharacter = L10n.tr("Settings", "radioWiFi.editor.unsupportedCharacter", fallback: "The network name or password contains a character this radio can't store.") } public enum Network { /// Shown when the radio has no saved network name @@ -5886,7 +6040,7 @@ public enum L10n { /// Export confirmation alert export button public static let export = L10n.tr("Settings", "settings.backup.export.alert.export", fallback: "Export") /// Export confirmation alert message - public static let message = L10n.tr("Settings", "settings.backup.export.alert.message", fallback: "This backup includes channel encryption keys, message history, your contact list, and the WiFi node's local network address and port. Store the exported file securely.") + public static let message = L10n.tr("Settings", "settings.backup.export.alert.message", fallback: "This backup includes channel encryption keys, message history, your contact list, and the WiFi node's local network address and port. The backup may also include GPS coordinates captured from radios. Store the exported file securely.") /// Export confirmation alert title public static let title = L10n.tr("Settings", "settings.backup.export.alert.title", fallback: "Security Notice") } @@ -6055,6 +6209,126 @@ public enum L10n { /// Description for trusted contacts toggle public static let trustedOnlyDescription = L10n.tr("Settings", "telemetry.trustedOnlyDescription", fallback: "Limit telemetry to selected contacts") } + public enum TextRules { + /// No Filter Rules + public static let empty = L10n.tr("Settings", "textRules.empty", fallback: "No Filter Rules") + /// Could not load filter rules. New messages won’t use filter rules until they can be loaded. + public static let loadFailed = L10n.tr("Settings", "textRules.loadFailed", fallback: "Could not load filter rules. New messages won’t use filter rules until they can be loaded.") + /// Loading Filter Rules… + public static let loading = L10n.tr("Settings", "textRules.loading", fallback: "Loading Filter Rules…") + /// Try Loading Filter Rules Again + public static let retryAccessibility = L10n.tr("Settings", "textRules.retryAccessibility", fallback: "Try Loading Filter Rules Again") + /// Filter Rules + public static let rules = L10n.tr("Settings", "textRules.rules", fallback: "Filter Rules") + /// %1$@ · %2$@ + public static func ruleSummary(_ p1: Any, _ p2: Any) -> String { + return L10n.tr("Settings", "textRules.ruleSummary", String(describing: p1), String(describing: p2), fallback: "%1$@ · %2$@") + } + /// Could not save filter rules. Try again. + public static let saveFailed = L10n.tr("Settings", "textRules.saveFailed", fallback: "Could not save filter rules. Try again.") + public enum Archive { + /// Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. + public static func caption(_ p1: Any, _ p2: Any, _ p3: Any) -> String { + return L10n.tr("Settings", "textRules.archive.caption", String(describing: p1), String(describing: p2), String(describing: p3), fallback: "%1$@ · “%2$@” · %3$@") + } + /// Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. + public static func captionWithoutChat(_ p1: Any, _ p2: Any) -> String { + return L10n.tr("Settings", "textRules.archive.captionWithoutChat", String(describing: p1), String(describing: p2), fallback: "“%1$@” · %2$@") + } + /// Chat + public static let chat = L10n.tr("Settings", "textRules.archive.chat", fallback: "Chat") + /// No Hidden Messages + public static let empty = L10n.tr("Settings", "textRules.archive.empty", fallback: "No Hidden Messages") + /// The latest %d hidden messages are kept on this device. They aren’t included in app backups. + public static func footer(_ p1: Int) -> String { + return L10n.tr("Settings", "textRules.archive.footer", p1, fallback: "The latest %d hidden messages are kept on this device. They aren’t included in app backups.") + } + /// %@: + public static func labelPrefix(_ p1: Any) -> String { + return L10n.tr("Settings", "textRules.archive.labelPrefix", String(describing: p1), fallback: "%@: ") + } + /// My Node + public static let myNode = L10n.tr("Settings", "textRules.archive.myNode", fallback: "My Node") + /// Rule + public static let rule = L10n.tr("Settings", "textRules.archive.rule", fallback: "Rule") + /// Time + public static let time = L10n.tr("Settings", "textRules.archive.time", fallback: "Time") + /// Recently Blocked + public static let title = L10n.tr("Settings", "textRules.archive.title", fallback: "Recently Blocked") + /// Unknown Conversation + public static let unknownConversation = L10n.tr("Settings", "textRules.archive.unknownConversation", fallback: "Unknown Conversation") + /// Unknown Radio + public static let unknownRadio = L10n.tr("Settings", "textRules.archive.unknownRadio", fallback: "Unknown Radio") + } + public enum Field { + /// Message + public static let message = L10n.tr("Settings", "textRules.field.message", fallback: "Message") + /// Message or Sender + public static let messageOrSender = L10n.tr("Settings", "textRules.field.messageOrSender", fallback: "Message or Sender") + /// Sender + public static let sender = L10n.tr("Settings", "textRules.field.sender", fallback: "Sender") + } + public enum Match { + /// Contains + public static let contains = L10n.tr("Settings", "textRules.match.contains", fallback: "Contains") + /// Whole Field + public static let wholeField = L10n.tr("Settings", "textRules.match.wholeField", fallback: "Whole Field") + /// Whole Message + public static let wholeMessage = L10n.tr("Settings", "textRules.match.wholeMessage", fallback: "Whole Message") + /// Whole Name + public static let wholeName = L10n.tr("Settings", "textRules.match.wholeName", fallback: "Whole Name") + } + public enum New { + /// Matches anywhere in the message, including inside a word. + public static let containsMessageFooter = L10n.tr("Settings", "textRules.new.containsMessageFooter", fallback: "Matches anywhere in the message, including inside a word.") + /// Matches the message or the sender’s name, including inside a word. Reactions from a matching sender are hidden too. + public static let containsMessageOrSenderFooter = L10n.tr("Settings", "textRules.new.containsMessageOrSenderFooter", fallback: "Matches the message or the sender’s name, including inside a word. Reactions from a matching sender are hidden too.") + /// Matches anywhere in the sender’s name, including inside a word. Reactions from that sender are hidden too. + public static let containsSenderFooter = L10n.tr("Settings", "textRules.new.containsSenderFooter", fallback: "Matches anywhere in the sender’s name, including inside a word. Reactions from that sender are hidden too.") + /// Look In + public static let lookIn = L10n.tr("Settings", "textRules.new.lookIn", fallback: "Look In") + /// Match + public static let match = L10n.tr("Settings", "textRules.new.match", fallback: "Match") + /// Word or phrase + public static let phrase = L10n.tr("Settings", "textRules.new.phrase", fallback: "Word or phrase") + /// New Rule + public static let title = L10n.tr("Settings", "textRules.new.title", fallback: "New Rule") + /// Matches only when the whole message is this phrase. + public static let wholeMessageFooter = L10n.tr("Settings", "textRules.new.wholeMessageFooter", fallback: "Matches only when the whole message is this phrase.") + /// Matches only when the whole message or the whole sender name is this phrase. Reactions from a matching sender are hidden too. + public static let wholeMessageOrSenderFooter = L10n.tr("Settings", "textRules.new.wholeMessageOrSenderFooter", fallback: "Matches only when the whole message or the whole sender name is this phrase. Reactions from a matching sender are hidden too.") + /// Matches only when the sender’s name is exactly this. Reactions from that sender are hidden too. + public static let wholeNameFooter = L10n.tr("Settings", "textRules.new.wholeNameFooter", fallback: "Matches only when the sender’s name is exactly this. Reactions from that sender are hidden too.") + } + public enum Selection { + /// Chats for %@ + public static func accessibilityChats(_ p1: Any) -> String { + return L10n.tr("Settings", "textRules.selection.accessibilityChats", String(describing: p1), fallback: "Chats for %@") + } + /// All + public static let all = L10n.tr("Settings", "textRules.selection.all", fallback: "All") + /// %d Chats + public static func count(_ p1: Int) -> String { + return L10n.tr("Settings", "textRules.selection.count", p1, fallback: "%d Chats") + } + /// All includes chats you join later. + public static let footer = L10n.tr("Settings", "textRules.selection.footer", fallback: "All includes chats you join later.") + /// None + public static let `none` = L10n.tr("Settings", "textRules.selection.none", fallback: "None") + } + public enum Types { + /// On includes every chat of that type, including chats you join later. + public static let footer = L10n.tr("Settings", "textRules.types.footer", fallback: "On includes every chat of that type, including chats you join later.") + /// Hashtag Channels + public static let hashtagChannel = L10n.tr("Settings", "textRules.types.hashtagChannel", fallback: "Hashtag Channels") + /// Use rules for + public static let header = L10n.tr("Settings", "textRules.types.header", fallback: "Use rules for") + /// Private Channels + public static let privateChannel = L10n.tr("Settings", "textRules.types.privateChannel", fallback: "Private Channels") + /// Public + public static let publicChannel = L10n.tr("Settings", "textRules.types.publicChannel", fallback: "Public") + } + } public enum TrustedContacts { /// Apply button label public static let apply = L10n.tr("Settings", "trustedContacts.apply", fallback: "Apply") @@ -6772,12 +7046,24 @@ public enum L10n { /// What's New v1.6 - Advanced map filters, title public static let title = L10n.tr("WhatsNew", "whatsNew.advancedMapFilters.title", fallback: "Advanced map filters") } + public enum BlocksAndFilters { + /// What's New v1.7 - Blocks and filters, description + public static let description = L10n.tr("WhatsNew", "whatsNew.blocksAndFilters.description", fallback: "Hide messages that match a word or phrase. A rule can look at the message, the sender's name, or both, and you choose which chats it applies to. Hidden messages can be seen in Recently Blocked under Settings > Blocks & Filters.") + /// What's New v1.7 - Blocks and filters, title + public static let title = L10n.tr("WhatsNew", "whatsNew.blocksAndFilters.title", fallback: "Blocks & Filters") + } public enum BluetoothAndWiFi { /// What's New v1.6 - Bluetooth and Wi-Fi, description public static let description = L10n.tr("WhatsNew", "whatsNew.bluetoothAndWiFi.description", fallback: "If a radio is on firmware 1.18 or later and paired over both Bluetooth and Wi-Fi, you can switch between them in Connect Device and in Settings > Connection.") /// What's New v1.6 - Bluetooth and Wi-Fi, title public static let title = L10n.tr("WhatsNew", "whatsNew.bluetoothAndWiFi.title", fallback: "Bluetooth and Wi-Fi") } + public enum DirectMessages { + /// What's New v1.7 - Direct messages, description + public static let description = L10n.tr("WhatsNew", "whatsNew.directMessages.description", fallback: "Direct messages now try the path 4 times, then flood 4 times. Change Attempts on Path, Flood Attempts, and Fall Back to Flood in Advanced Settings.") + /// What's New v1.7 - Direct messages, title + public static let title = L10n.tr("WhatsNew", "whatsNew.directMessages.title", fallback: "Direct messages") + } public enum FasterChatLoading { /// What's New v1.5 - Faster chat loading, description public static let description = L10n.tr("WhatsNew", "whatsNew.fasterChatLoading.description", fallback: "Opening a chat is up to 90%% faster.") @@ -6796,12 +7082,24 @@ public enum L10n { /// What's New v1.6 - iPhone Duo, title public static let title = L10n.tr("WhatsNew", "whatsNew.iPhoneDuo.title", fallback: "iPhone Duo") } + public enum LiveActivity { + /// What's New v1.7 - Live Activity, description + public static let description = L10n.tr("WhatsNew", "whatsNew.liveActivity.description", fallback: "Unread messages are more prominent and the packets per minute rate is easier to understand.") + /// What's New v1.7 - Live Activity, title + public static let title = L10n.tr("WhatsNew", "whatsNew.liveActivity.title", fallback: "Live Activity") + } public enum MoreChanges { /// What's New v1.6 - More changes, description public static let description = L10n.tr("WhatsNew", "whatsNew.moreChanges.description", fallback: "Tap \"See all new changes\" below to view the full list of bug fixes and other features.") /// What's New v1.6 - More changes, title public static let title = L10n.tr("WhatsNew", "whatsNew.moreChanges.title", fallback: "More changes") } + public enum NodeTelemetry { + /// What's New v1.7 - Node telemetry, description + public static let description = L10n.tr("WhatsNew", "whatsNew.nodeTelemetry.description", fallback: "Settings > Device Info shows telemetry from the node you are connected to.") + /// What's New v1.7 - Node telemetry, title + public static let title = L10n.tr("WhatsNew", "whatsNew.nodeTelemetry.title", fallback: "Node telemetry") + } public enum PathDetails { /// What's New v1.5 - Path Details feature, description public static let description = L10n.tr("WhatsNew", "whatsNew.pathDetails.description", fallback: "Path Map has moved into Path Details, which lists every extra incoming path. And Repeat Details on sent messages lists every repeat path your radio heard.") diff --git a/MC1/Resources/Localization/de.lproj/Chats.strings b/MC1/Resources/Localization/de.lproj/Chats.strings index 0180138cc1..cdedff3790 100644 --- a/MC1/Resources/Localization/de.lproj/Chats.strings +++ b/MC1/Resources/Localization/de.lproj/Chats.strings @@ -588,6 +588,12 @@ /* Location: UnifiedMessageBubble.swift - VoiceOver prefix when the visible body is a translation - %@ is the translated text */ "chats.message.translatedAccessibility" = "Übersetzt: %@"; +/* Location: MessageVisibleBody.swift - VoiceOver prefix when the visible body is an MECP reading - %@ is the reading */ +"chats.message.readingAccessibility" = "Lesung: %@"; + +/* Location: MECPCatalog - Person count line in an MECP reading */ +"chats.message.mecpPersonCount" = "%lld Personen"; + /* Location: UnifiedMessageBubble.swift - Context menu action to view repeat details */ "chats.message.action.repeatDetails" = "Wiederholungsdetails"; @@ -641,6 +647,9 @@ /* Location: UnifiedMessageBubble.swift - Context menu text showing SNR - %@ is formatted value */ "chats.message.info.snr" = "SNR: %@"; +/* Location: ActionsDetailsSection.swift - Stored MECP wire string under SNR. %@ is the original text */ +"chats.message.info.mecp" = "MECP: %@"; + /* Location: MessageActionsSheet.swift - Context menu text showing the radio region the message was flooded under - %@ is region name. "Flooded" is a domain term for mesh-broadcast across all nodes in a radio region. */ "chats.message.info.floodedUnder" = "Region: %@"; @@ -1106,8 +1115,8 @@ /* Location: MutedIndicator.swift - Accessibility label for mentions-only indicator */ "chats.row.mentionsOnly" = "Nur Erwähnungen"; -/* TODO: translate - Accessibility label for the row actions menu */ -"chats.row.actionsMenu.accessibilityLabel" = "Conversation actions"; +/* Accessibility label for the row actions menu */ +"chats.row.actionsMenu.accessibilityLabel" = "Aktionen der Unterhaltung"; // MARK: - Reaction Badges diff --git a/MC1/Resources/Localization/de.lproj/Chats.stringsdict b/MC1/Resources/Localization/de.lproj/Chats.stringsdict new file mode 100644 index 0000000000..535083736a --- /dev/null +++ b/MC1/Resources/Localization/de.lproj/Chats.stringsdict @@ -0,0 +1,22 @@ + + + + + chats.message.mecpPersonCount + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + lld + one + %lld Person + other + %lld Personen + + + + diff --git a/MC1/Resources/Localization/de.lproj/Contacts.strings b/MC1/Resources/Localization/de.lproj/Contacts.strings index 8a6fca7369..4c53e13650 100644 --- a/MC1/Resources/Localization/de.lproj/Contacts.strings +++ b/MC1/Resources/Localization/de.lproj/Contacts.strings @@ -44,6 +44,8 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Raum"; +"contacts.nodeKind.sensor" = "Sensor"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Entdeckt"; @@ -75,6 +77,8 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Räume"; +"contacts.segment.sensors" = "Sensoren"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "Knoten filtern"; @@ -168,9 +172,13 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "Keine Räume"; +"contacts.list.empty.sensors.title" = "Keine Sensoren"; + /* Location: ContactsListView.swift - Purpose: No rooms empty description */ "contacts.list.empty.rooms.description" = "Räume sind öffentliche Chat-Server im Mesh. Sie erscheinen hier, sobald sie entdeckt werden."; +"contacts.list.empty.sensors.description" = "Sensoren erscheinen hier, wenn sie im Mesh entdeckt werden."; + /* Location: ContactsListView.swift - Purpose: No search results title */ "contacts.list.empty.search.title" = "Keine Ergebnisse"; @@ -623,6 +631,8 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter - Rooms */ "contacts.discovery.segment.rooms" = "Räume"; +"contacts.discovery.segment.sensors" = "Sensoren"; + /* Location: DiscoverSegmentPicker.swift - Purpose: VoiceOver label for the Discovery segment filter picker (iOS 18 fallback) */ "contacts.discovery.segment.pickerLabel" = "Entdeckte Knoten filtern"; diff --git a/MC1/Resources/Localization/de.lproj/Localizable.strings b/MC1/Resources/Localization/de.lproj/Localizable.strings index a7a71ab38d..288f9ec984 100644 --- a/MC1/Resources/Localization/de.lproj/Localizable.strings +++ b/MC1/Resources/Localization/de.lproj/Localizable.strings @@ -142,6 +142,8 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "Neuer Raum entdeckt"; +"notifications.discovery.sensor" = "Neuer Sensor entdeckt"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -489,6 +491,14 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Ungültige Antwort vom Remote-Knoten"; +"error.remoteNode.sensorOutcomeUnknown" = "Die Änderung konnte nicht verifiziert werden. Lade die Einstellungen neu, bevor du erneut speicherst."; + +"error.remoteNode.sensorSettingRejected" = "Der Sensor hat diese Einstellung abgelehnt."; + +"error.remoteNode.invalidSensorSetting" = "Verwende einen Schlüssel und einen Wert, die nicht leer sind und keine Leerzeichen enthalten. Der vollständige Befehl muss in 160 UTF-8 Bytes passen."; + +"error.remoteNode.invalidPasswordLength" = "Passwörter dürfen höchstens %d UTF-8 Bytes lang sein."; + /* Location: RemoteNodeError+UserFacingMessage.swift - Remote node rejected the operation */ "error.remoteNode.permissionDenied" = "Zugriff verweigert"; diff --git a/MC1/Resources/Localization/de.lproj/Map.strings b/MC1/Resources/Localization/de.lproj/Map.strings index 60b0f2a676..e014fc6db2 100644 --- a/MC1/Resources/Localization/de.lproj/Map.strings +++ b/MC1/Resources/Localization/de.lproj/Map.strings @@ -40,6 +40,8 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Filter"; +"map.controls.contactsAndSensors" = "Kontakte & Sensoren"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Filter aktiv"; @@ -264,6 +266,8 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Raum"; +"map.nodeKind.sensor" = "Sensor"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -281,6 +285,8 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Raum"; +"map.callout.nodeKind.sensor" = "Sensor"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "Hinzufügen"; diff --git a/MC1/Resources/Localization/de.lproj/Onboarding.strings b/MC1/Resources/Localization/de.lproj/Onboarding.strings index ce77c47b92..6e582aafe4 100644 --- a/MC1/Resources/Localization/de.lproj/Onboarding.strings +++ b/MC1/Resources/Localization/de.lproj/Onboarding.strings @@ -69,6 +69,9 @@ /* Location: DeviceScanView.swift - Subtitle with pairing instructions */ "deviceScan.subtitle" = "Schalte dein Funkgerät ein, trenne es von allen anderen Apps und Geräten und tippe dann auf \"Gerät hinzufügen\"."; +/* Location: DeviceScanView.swift - Subtitle while bond-loss recovery is re-pairing */ +"deviceScan.rePairingSubtitle" = "Schalte dein Funkgerät ein und trenne es von allen anderen Apps und Geräten."; + /* Location: DeviceScanView.swift - Message shown when device is already paired */ "deviceScan.alreadyPaired" = "Dein Gerät ist bereits gekoppelt"; @@ -78,9 +81,6 @@ /* Location: DeviceScanView.swift - Button to continue after pairing */ "deviceScan.continue" = "Weiter"; -/* Location: DeviceScanView.swift - Button label while connecting */ -"deviceScan.connecting" = "Verbinde..."; - /* Location: DeviceScanView.swift - Button to connect simulator (debug) */ "deviceScan.connectSimulator" = "Simulator verbinden"; diff --git a/MC1/Resources/Localization/de.lproj/RemoteNodes.strings b/MC1/Resources/Localization/de.lproj/RemoteNodes.strings index c71ceb7f3e..2a11aa9bf0 100644 --- a/MC1/Resources/Localization/de.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/de.lproj/RemoteNodes.strings @@ -32,6 +32,8 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Repeater"; +"remoteNodes.auth.typeSensor" = "Sensor"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Authentifizierung"; @@ -62,10 +64,18 @@ /* Location: NodeAuthenticationSheet.swift - Flood routing toggle */ "remoteNodes.auth.floodRouting" = "Flood-Routing"; "remoteNodes.auth.floodRetryStatus" = "Keine Antwort über die bekannte Route. Neuer Versuch mit Flood-Routing."; -"remoteNodes.auth.floodFooter" = "Flood-Routing ist langsamer und beansprucht mehr Funkzeit im Netzwerk. Verwende es, wenn die bekannte Route an deinem aktuellen Standort nicht funktioniert. Nach der Anmeldung wird automatisch eine neue Route gelernt."; +/* Footer when this sign-in will clear the saved route and use flood */ +"remoteNodes.auth.floodFooter" = "Diese Anmeldung löscht die gespeicherte Route und sendet mit Flood. Flood-Routing ist langsamer und beansprucht mehr Funkzeit im Netzwerk. Eine neue Route wird nur gelernt, wenn die Anmeldung gelingt."; + +/* Footer after this sign-in has cleared the saved route */ +"remoteNodes.auth.floodFooterCleared" = "Die gespeicherte Route wurde gelöscht. Die Anmeldung sendet mit Flood. Eine neue Route wird nur gelernt, wenn die Anmeldung gelingt."; + + +/* Footer when a timeout clears the route and retries by flood */ +"remoteNodes.auth.pathFooter" = "Wenn keine Antwort kommt, wird die gespeicherte Route gelöscht und die Anmeldung versucht es einmal mit Flood."; -/* Location: NodeAuthenticationSheet.swift - Path section footer when stored path exists */ -"remoteNodes.auth.pathFooter" = "Verwende die bekannte Route zu diesem Knoten oder wechsle zu Flood-Routing, damit das Netzwerk einen Pfad findet."; +/* Footer when a timeout stops and leaves the route */ +"remoteNodes.auth.pathFooterKept" = "Wenn keine Antwort kommt, stoppt die Anmeldung und die gespeicherte Route bleibt erhalten."; /* Location: NodeAuthenticationSheet.swift - Path hop whose repeater is not known */ "remoteNodes.auth.pathHopUnknown" = ""; @@ -84,6 +94,26 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Repeater-Einstellungen"; +"remoteNodes.sensor.adminRequired" = "Die Sensorverwaltung erfordert Administratorzugriff."; + +"remoteNodes.sensor.saved" = "Einstellung verifiziert."; + +"remoteNodes.sensor.rebootSent" = "Neustart-Anfrage gesendet. Der Sensor hat einen Neustart nicht bestätigt. Melde dich erneut beim Sensor an, bevor du weitere Befehle sendest."; + +"remoteNodes.sensor.rebootConfirmation" = "Neustart-Anfrage an diesen Sensor senden?"; + +"remoteNodes.sensor.runtimeOnly" = "Änderungen betreffen den laufenden Sensor. Ob sie einen Neustart überdauern, hängt von seiner Firmware ab."; + +"remoteNodes.sensor.value" = "Wert"; + +"remoteNodes.sensor.save" = "Speichern"; + +"remoteNodes.sensor.reload" = "Neu laden"; + +"remoteNodes.sensor.empty" = "Dieser Sensor stellt keine Einstellungen bereit."; + +"remoteNodes.sensor.title" = "Sensorverwaltung"; + /* Location: RepeaterSettingsView.swift - Done button (used in multiple places) */ "remoteNodes.settings.done" = "Fertig"; diff --git a/MC1/Resources/Localization/de.lproj/Settings.strings b/MC1/Resources/Localization/de.lproj/Settings.strings index 2dc599399e..07922a1669 100644 --- a/MC1/Resources/Localization/de.lproj/Settings.strings +++ b/MC1/Resources/Localization/de.lproj/Settings.strings @@ -46,9 +46,6 @@ /* Section header for device information */ "device.header" = "Gerät"; -/* Status shown when device is connected */ -"device.connected" = "Verbunden"; - /* Footer shown when no device is connected */ "device.noDeviceConnected" = "Kein MeshCore-Gerät verbunden"; @@ -60,12 +57,6 @@ /* Navigation title for device info screen */ "deviceInfo.title" = "Geräteinfo"; -/* Section header for connection status */ -"deviceInfo.connection.header" = "Verbindung"; - -/* Label for connection status */ -"deviceInfo.connection.status" = "Status"; - /* Section header for power and storage */ "deviceInfo.powerStorage.header" = "Akku & Speicher"; @@ -111,6 +102,12 @@ /* Firmware version fallback format when no version string is reported - %@ is the numeric version code */ "deviceInfo.firmwareVersionFormat" = "v%@"; +/* Heading above retained telemetry after a Device Info reload fails */ +"deviceInfo.lastSuccessfulReading" = "Letzter erfolgreicher Sensormesswert"; + +/* Section header for Device Info telemetry */ +"deviceInfo.telemetry.header" = "Knoten-Telemetrie"; + /* Section header for identity information */ /* Label for public key */ "deviceInfo.publicKey" = "Öffentlicher Schlüssel"; @@ -180,6 +177,9 @@ /* Button to scan for Bluetooth devices */ "deviceSelection.scanBluetooth" = "Nach Bluetooth-Gerät suchen"; +/* Button title while this radio is being paired again */ +"deviceSelection.rePairing" = "Neu koppeln..."; + /* Trailing control on a previously paired row that still needs iPhone setup */ /* AI-translated - please verify with native speakers. */ "deviceSelection.setup" = "Einrichten"; @@ -746,6 +746,21 @@ /* Alert message for clear logs */ "diagnostics.alert.clear.message" = "Alle gespeicherten Debug-Protokolle werden gelöscht. Exportierte Protokolldateien bleiben unberührt."; +/* Toggle to enable collecting local debug logs */ +"diagnostics.collectLogs" = "Debug-Protokolle erfassen"; + +/* Footer shown when debug log collection is off */ +"diagnostics.footer.disabled" = "Lokale Debug-Protokolle werden nicht erfasst."; + +/* Alert title for disabling collection */ +"diagnostics.alert.disable.title" = "Erfassung deaktivieren"; + +/* Button to confirm disabling collection */ +"diagnostics.alert.disable.confirm" = "Erfassung deaktivieren"; + +/* Alert message for disabling collection */ +"diagnostics.alert.disable.message" = "Alle gespeicherten Debug-Protokolle werden gelöscht und die Erfassung wird beendet. Exportierte Protokolldateien bleiben unberührt."; + /* Error when export fails */ "diagnostics.error.exportFailed" = "Exportdatei konnte nicht erstellt werden"; @@ -754,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Chats"; +"blocksAndFilters.title" = "Blockierung & Filter"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -822,6 +839,8 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Companion"; +"notifications.discoveryCompanionsAndSensors" = "Companions & Sensoren"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Repeater"; @@ -983,6 +1002,9 @@ /* Editor footer when the password is too long */ "radioWiFi.editor.passwordLength" = "Ein Passwort kann bis zu 63 Bytes lang sein."; +/* Editor footer when a credential contains a character the firmware cannot store */ +"radioWiFi.editor.unsupportedCharacter" = "Der Netzwerkname oder das Passwort enthält ein Zeichen, das dieses Funkgerät nicht speichern kann."; + /* Button that clears the radio's saved WiFi settings */ "radioWiFi.clear" = "WLAN-Einstellungen löschen"; @@ -1148,6 +1170,35 @@ /* Footer explaining the acknowledgments setting */ "directMessages.footer" = "Anzahl der pro Direktnachricht gesendeten Bestätigungen. Verwende 2 für eine bessere Zustellbestätigung über unzuverlässige Verbindungen."; +/* Switch that clears the known route after the path attempts */ +"directMessages.fallback" = "Auf Flood zurückfallen"; + +/* Picker label for attempts on the known route */ +"directMessages.directAttempts" = "Versuche auf der Route"; + +/* Picker label for attempts sent by flood after the route is cleared */ +"directMessages.floodAttempts" = "Flood-Versuche"; + +/* Footer when Fall Back to Flood is on */ +"directMessages.attemptsFooterOn" = "Die gespeicherte Route wird nach „Versuche auf der Route“ gelöscht. Flood-Versuche werden danach mit Flood gesendet. Eine Nachricht an einen Kontakt ohne bekannte Route wird mit Flood gesendet."; + +/* Footer when Fall Back to Flood is off */ +"directMessages.attemptsFooterOff" = "Versuche auf der Route bleiben auf der bekannten Route, und die gespeicherte Route bleibt erhalten. Eine Nachricht an einen Kontakt ohne bekannte Route wird mit Flood gesendet."; + +// MARK: - Path Fallback + +/* Section header for sign-in, command, and contact telemetry path fallback */ +"pathFallback.header" = "Pfad-Fallback"; + +/* Switch that clears the known route after a timeout */ +"pathFallback.fallback" = "Auf Flood zurückfallen"; + +/* Footer when path fallback is on */ +"pathFallback.footerOn" = "Anmeldung, Befehle an einen Repeater oder einen Raum, die eine Antwort erwarten, und Telemetrie für einen Kontakt verwenden die bekannte Route. Wenn keine Antwort kommt, wird die gespeicherte Route gelöscht und einmal mit Flood versucht."; + +/* Footer when path fallback is off */ +"pathFallback.footerOff" = "Anmeldung, Befehle und Telemetrie für einen Kontakt bleiben auf der bekannten Route. Wenn keine Antwort kommt, stoppen sie und die gespeicherte Route bleibt erhalten. Wenn du auf dem Bildschirm zur Anmeldung Flood-Routing einschaltest, wird die gespeicherte Route dieses Knotens gelöscht."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ @@ -1162,12 +1213,24 @@ /* Menu item to disconnect from the current device */ "bleStatus.disconnect" = "Trennen"; +/* Menu item to stop automatic reconnection until another explicit connection */ +"bleStatus.stopReconnecting" = "Erneutes Verbinden stoppen"; + +/* Menu item to cancel the current connection request */ +"bleStatus.cancelConnection" = "Verbindung abbrechen"; + /* Status shown when device is disconnected */ "bleStatus.status.disconnected" = "Getrennt"; /* Status shown when device is connecting */ "bleStatus.status.connecting" = "Verbinde..."; +/* Status shown while reconnecting to the selected device */ +"bleStatus.status.reconnecting" = "Verbinde erneut..."; + +/* Status shown while automatic reconnection remains enabled between attempts */ +"bleStatus.status.waitingToReconnect" = "Warten auf erneute Verbindung"; + /* Status shown when device is connected but not ready */ "bleStatus.status.connected" = "Verbunden"; @@ -1180,6 +1243,9 @@ /* Accessibility label for BLE status indicator */ "bleStatus.accessibilityLabel" = "Bluetooth-Verbindungsstatus"; +/* TODO: translate - Accessibility text combining a descriptive prefix and connection state or context; arguments may themselves contain a radio name and status */ +"bleStatus.accessibilityValue" = "%1$@, %2$@"; + /* Accessibility hint when disconnected */ "bleStatus.accessibilityHint.disconnected" = "Doppeltippen, um Gerät zu verbinden"; @@ -1318,6 +1384,24 @@ /* Import failed after one or more settings were already written; %@ is the underlying error message */ "configImport.failedPartial" = "%@ Einige Einstellungen wurden möglicherweise bereits auf das Gerät geschrieben. Überprüfe die Konfiguration des Geräts."; +/* Interrupted identity import recovery */ +"configImport.identityOutcomeUnknown" = "Die Verbindung wurde beim Importieren der Identität auf %@ unterbrochen. Die Identität des Funkgeräts wurde möglicherweise geändert. Der Konfigurationsimport wurde nicht abgeschlossen."; + +/* Interrupted identity import recovery */ +"configImport.retryIdentityImport" = "Identitätsimport erneut versuchen"; + +/* Interrupted identity import recovery */ +"configImport.confirmIdentityRecovery" = "Dadurch wird die Identität des unter %@ erreichbaren Funkgeräts mit dem privaten Schlüssel aus der ausgewählten Datei ersetzt. Der Konfigurationsimport wird nicht fortgesetzt."; + +/* Confirmation alert title when retrying an interrupted identity import */ +"configImport.confirmTitleIdentityRecovery" = "Identität des Funkgeräts ersetzen?"; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryComplete" = "Die Identität wurde erneut angewendet. Der Konfigurationsimport wurde nicht abgeschlossen. Importiere die Datei erneut, um die anderen Einstellungen anzuwenden."; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryKeyRequired" = "Wähle eine Konfigurationsdatei mit dem privaten Schlüssel aus, um den Identitätsimport erneut zu versuchen."; + /* Import success */ "configImport.importSuccess" = "Konfiguration erfolgreich importiert"; @@ -1434,6 +1518,63 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "Das Anzeigen von Karten-Miniaturansichten lädt Kartenkacheln für die Koordinate von einem Drittanbieter-Server, was Ihre IP-Adresse offenlegen kann."; +// MARK: - Text Rules + +"textRules.rules" = "Filterregeln"; +"textRules.empty" = "Keine Filterregeln"; +"textRules.loading" = "Filterregeln werden geladen…"; +"textRules.loadFailed" = "Filterregeln konnten nicht geladen werden. Neue Nachrichten verwenden keine Filterregeln, bis die Regeln geladen werden können."; +"textRules.retryAccessibility" = "Filterregeln erneut laden"; +"textRules.saveFailed" = "Filterregeln konnten nicht gespeichert werden. Versuche es erneut."; +"textRules.new.title" = "Neue Regel"; +"textRules.new.phrase" = "Wort oder Text"; +"textRules.new.lookIn" = "Suchen in"; +"textRules.new.match" = "Übereinstimmung"; +"textRules.new.containsMessageFooter" = "Trifft überall in der Nachricht zu, auch innerhalb eines Wortes."; +"textRules.new.wholeMessageFooter" = "Trifft nur zu, wenn die ganze Nachricht dieser Text ist."; +"textRules.new.containsSenderFooter" = "Trifft überall im Namen des Absenders zu, auch innerhalb eines Wortes. Reaktionen von diesem Absender werden ebenfalls ausgeblendet."; +"textRules.new.wholeNameFooter" = "Trifft nur zu, wenn der Name des Absenders genau dieser Text ist. Reaktionen von diesem Absender werden ebenfalls ausgeblendet."; +"textRules.new.containsMessageOrSenderFooter" = "Trifft in der Nachricht oder im Namen des Absenders zu, auch innerhalb eines Wortes. Reaktionen eines zutreffenden Absenders werden ebenfalls ausgeblendet."; +"textRules.new.wholeMessageOrSenderFooter" = "Trifft nur zu, wenn die ganze Nachricht oder der ganze Name des Absenders dieser Text ist. Reaktionen eines zutreffenden Absenders werden ebenfalls ausgeblendet."; +"textRules.field.message" = "Nachricht"; +"textRules.field.sender" = "Absender"; +"textRules.field.messageOrSender" = "Nachricht oder Absender"; +"textRules.match.contains" = "Enthält"; +"textRules.match.wholeMessage" = "Ganze Nachricht"; +"textRules.match.wholeName" = "Ganzer Name"; +"textRules.match.wholeField" = "Ganzes Feld"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Regeln verwenden für"; +"textRules.types.footer" = "Ist er eingeschaltet, gilt er für jeden Chat dieses Typs, auch für Chats, denen du später beitrittst."; +"textRules.types.publicChannel" = "Öffentlich"; +"textRules.types.hashtagChannel" = "Hashtag-Kanäle"; +"textRules.types.privateChannel" = "Private Kanäle"; +"textRules.selection.all" = "Alle"; +"textRules.selection.none" = "Keine"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats für %@"; +"textRules.selection.footer" = "„Alle“ gilt auch für Chats, denen du später beitrittst."; +"textRules.archive.title" = "Zuletzt ausgeblendet"; +"textRules.archive.empty" = "Keine ausgeblendeten Nachrichten"; +"textRules.archive.footer" = "Die letzten %d ausgeblendeten Nachrichten bleiben auf diesem Gerät. Sie sind nicht in Sicherungen der App-Daten enthalten."; +"textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; +"textRules.archive.rule" = "Regel"; +"textRules.archive.chat" = "Chat"; +"textRules.archive.myNode" = "Mein Knoten"; +"textRules.archive.time" = "Zeit"; +"textRules.archive.unknownConversation" = "Unbekannte Unterhaltung"; +"textRules.archive.unknownRadio" = "Unbekanntes Funkgerät"; + +"radioCleanup.title" = "Bereinigung"; +"radioCleanup.running" = "Daten des Funkgeräts werden entfernt"; +"radioCleanup.failed" = "Ausgeblendete Nachrichten von diesem Funkgerät sind möglicherweise noch auf dieser Installation."; +"radioCleanup.completed" = "Daten des Funkgeräts entfernt"; +"radioCleanup.retryAccessibility" = "Bereinigung des Funkgeräts für %@ erneut versuchen"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ @@ -1978,7 +2119,7 @@ "settings.backup.export.alert.title" = "Sicherheitshinweis"; /* Export confirmation alert message */ -"settings.backup.export.alert.message" = "Diese Sicherung enthält Kanal-Verschlüsselungsschlüssel, den Nachrichtenverlauf, deine Kontaktliste sowie die lokale Netzwerkadresse und den Port des WLAN-Knotens. Bewahre die exportierte Datei sicher auf."; +"settings.backup.export.alert.message" = "Diese Sicherung enthält Kanal-Verschlüsselungsschlüssel, den Nachrichtenverlauf, deine Kontaktliste sowie die lokale Netzwerkadresse und den Port des WLAN-Knotens. Die Sicherung kann auch aufgezeichnete GPS-Koordinaten von Funkgeräten enthalten. Bewahre die exportierte Datei sicher auf."; /* Export confirmation alert export button */ "settings.backup.export.alert.export" = "Exportieren"; diff --git a/MC1/Resources/Localization/de.lproj/WhatsNew.strings b/MC1/Resources/Localization/de.lproj/WhatsNew.strings index e87ca4b012..2254feb3b6 100644 --- a/MC1/Resources/Localization/de.lproj/WhatsNew.strings +++ b/MC1/Resources/Localization/de.lproj/WhatsNew.strings @@ -65,3 +65,23 @@ "whatsNew.moreChanges.title" = "Weitere Änderungen"; /* What's New v1.6 - More changes, description */ "whatsNew.moreChanges.description" = "Tippe unten auf \"Alle neuen Änderungen anzeigen\", um die vollständige Liste der behobenen Fehler und der anderen Funktionen zu sehen."; + +/* What's New v1.7 - Direct messages, title */ +"whatsNew.directMessages.title" = "Direktnachrichten"; +/* What's New v1.7 - Direct messages, description */ +"whatsNew.directMessages.description" = "Direktnachrichten versuchen jetzt 4-mal die Route, danach 4-mal mit Flood. Ändere „Versuche auf der Route“, „Flood-Versuche“ und „Auf Flood zurückfallen“ in den Erweiterten Einstellungen."; + +/* What's New v1.7 - Blocks and filters, title */ +"whatsNew.blocksAndFilters.title" = "Blockierung & Filter"; +/* What's New v1.7 - Blocks and filters, description */ +"whatsNew.blocksAndFilters.description" = "Blende Nachrichten aus, die einem Wort oder Text entsprechen. Eine Regel kann in der Nachricht, im Namen des Absenders oder in beiden suchen, und du wählst, für welche Chats sie gilt. Ausgeblendete Nachrichten kannst du in „Zuletzt ausgeblendet“ unter Einstellungen > Blockierung & Filter sehen."; + +/* What's New v1.7 - Node telemetry, title */ +"whatsNew.nodeTelemetry.title" = "Knoten-Telemetrie"; +/* What's New v1.7 - Node telemetry, description */ +"whatsNew.nodeTelemetry.description" = "Einstellungen > Geräteinfo zeigt die Telemetrie des Knotens, mit dem du verbunden bist."; + +/* What's New v1.7 - Live Activity, title */ +"whatsNew.liveActivity.title" = "Live-Aktivität"; +/* What's New v1.7 - Live Activity, description */ +"whatsNew.liveActivity.description" = "Ungelesene Nachrichten sind auffälliger, und die Rate in Paketen pro Minute ist leichter zu verstehen."; diff --git a/MC1/Resources/Localization/en.lproj/Chats.strings b/MC1/Resources/Localization/en.lproj/Chats.strings index 66ca5bffff..c0c37d9f47 100644 --- a/MC1/Resources/Localization/en.lproj/Chats.strings +++ b/MC1/Resources/Localization/en.lproj/Chats.strings @@ -618,6 +618,12 @@ /* Location: UnifiedMessageBubble.swift - VoiceOver prefix when the visible body is a translation - %@ is the translated text */ "chats.message.translatedAccessibility" = "Translated: %@"; +/* Location: MessageVisibleBody.swift - VoiceOver prefix when the visible body is an MECP reading - %@ is the reading */ +"chats.message.readingAccessibility" = "Reading: %@"; + +/* Location: MECPCatalog - Person count line in an MECP reading */ +"chats.message.mecpPersonCount" = "%lld people"; + /* Location: UnifiedMessageBubble.swift - Context menu action to view repeat details */ "chats.message.action.repeatDetails" = "Repeat Details"; @@ -671,6 +677,9 @@ /* Location: UnifiedMessageBubble.swift - Context menu text showing SNR - %@ is formatted value */ "chats.message.info.snr" = "SNR: %@"; +/* Location: ActionsDetailsSection.swift - Stored MECP wire string under SNR. %@ is the original text */ +"chats.message.info.mecp" = "MECP: %@"; + /* Location: MessageActionsSheet.swift - Details row showing the radio region a flood-routed message was broadcast under - %@ is region name */ "chats.message.info.floodedUnder" = "Region: %@"; diff --git a/MC1/Resources/Localization/en.lproj/Chats.stringsdict b/MC1/Resources/Localization/en.lproj/Chats.stringsdict new file mode 100644 index 0000000000..7fc515f847 --- /dev/null +++ b/MC1/Resources/Localization/en.lproj/Chats.stringsdict @@ -0,0 +1,22 @@ + + + + + chats.message.mecpPersonCount + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + lld + one + %lld person + other + %lld people + + + + diff --git a/MC1/Resources/Localization/en.lproj/Contacts.strings b/MC1/Resources/Localization/en.lproj/Contacts.strings index 7bab8d8995..e608892f77 100644 --- a/MC1/Resources/Localization/en.lproj/Contacts.strings +++ b/MC1/Resources/Localization/en.lproj/Contacts.strings @@ -44,6 +44,8 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Room"; +"contacts.nodeKind.sensor" = "Sensor"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Discovered"; @@ -75,6 +77,8 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Rooms"; +"contacts.segment.sensors" = "Sensors"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "Filter nodes"; @@ -168,9 +172,13 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "No Rooms"; +"contacts.list.empty.sensors.title" = "No Sensors"; + /* Location: ContactsListView.swift - Purpose: No rooms empty description */ "contacts.list.empty.rooms.description" = "Rooms are public chat servers on the mesh. They'll appear here when discovered."; +"contacts.list.empty.sensors.description" = "Sensors appear here when discovered on the mesh."; + /* Location: ContactsListView.swift - Purpose: No search results title */ "contacts.list.empty.search.title" = "No Results"; @@ -623,6 +631,8 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter: Rooms */ "contacts.discovery.segment.rooms" = "Rooms"; +"contacts.discovery.segment.sensors" = "Sensors"; + /* Location: DiscoverSegmentPicker.swift - Purpose: VoiceOver label for the Discovery segment filter picker (iOS 18 fallback) */ "contacts.discovery.segment.pickerLabel" = "Filter discovered nodes"; diff --git a/MC1/Resources/Localization/en.lproj/Localizable.strings b/MC1/Resources/Localization/en.lproj/Localizable.strings index 709e9ce707..eada9250bb 100644 --- a/MC1/Resources/Localization/en.lproj/Localizable.strings +++ b/MC1/Resources/Localization/en.lproj/Localizable.strings @@ -151,6 +151,8 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "New Room Discovered"; +"notifications.discovery.sensor" = "New Sensor Discovered"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -496,6 +498,14 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Invalid response from remote node"; +"error.remoteNode.sensorOutcomeUnknown" = "The change could not be verified. Reload settings before saving again."; + +"error.remoteNode.sensorSettingRejected" = "The sensor rejected this setting."; + +"error.remoteNode.invalidSensorSetting" = "Use a nonempty key and value without whitespace. The complete command must fit within 160 UTF-8 bytes."; + +"error.remoteNode.invalidPasswordLength" = "Passwords must use no more than %d UTF-8 bytes."; + /* Location: RemoteNodeError+UserFacingMessage.swift - Remote node rejected the operation */ "error.remoteNode.permissionDenied" = "Permission denied"; diff --git a/MC1/Resources/Localization/en.lproj/Map.strings b/MC1/Resources/Localization/en.lproj/Map.strings index e115592118..23a5ae03ee 100644 --- a/MC1/Resources/Localization/en.lproj/Map.strings +++ b/MC1/Resources/Localization/en.lproj/Map.strings @@ -37,6 +37,8 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Filter"; +"map.controls.contactsAndSensors" = "Contacts & Sensors"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Filters active"; @@ -261,6 +263,8 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Room"; +"map.nodeKind.sensor" = "Sensor"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -278,6 +282,8 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Room"; +"map.callout.nodeKind.sensor" = "Sensor"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "Add"; diff --git a/MC1/Resources/Localization/en.lproj/Onboarding.strings b/MC1/Resources/Localization/en.lproj/Onboarding.strings index d8384eb031..044524782f 100644 --- a/MC1/Resources/Localization/en.lproj/Onboarding.strings +++ b/MC1/Resources/Localization/en.lproj/Onboarding.strings @@ -69,6 +69,9 @@ /* Location: DeviceScanView.swift - Subtitle with pairing instructions */ "deviceScan.subtitle" = "Power your radio on, disconnect it from all other apps and devices, then tap Add Device."; +/* Location: DeviceScanView.swift - Subtitle while bond-loss recovery is re-pairing */ +"deviceScan.rePairingSubtitle" = "Power your radio on and disconnect it from all other apps and devices."; + /* Location: DeviceScanView.swift - Message shown when device is already paired */ "deviceScan.alreadyPaired" = "Your device is already paired"; @@ -78,9 +81,6 @@ /* Location: DeviceScanView.swift - Button to continue after pairing */ "deviceScan.continue" = "Continue"; -/* Location: DeviceScanView.swift - Button label while connecting */ -"deviceScan.connecting" = "Connecting..."; - /* Location: DeviceScanView.swift - Button to connect simulator (debug) */ "deviceScan.connectSimulator" = "Connect Simulator"; diff --git a/MC1/Resources/Localization/en.lproj/RemoteNodes.strings b/MC1/Resources/Localization/en.lproj/RemoteNodes.strings index 263e19fefd..4841d5ff57 100644 --- a/MC1/Resources/Localization/en.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/en.lproj/RemoteNodes.strings @@ -32,6 +32,8 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Repeater"; +"remoteNodes.auth.typeSensor" = "Sensor"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Authentication"; @@ -62,10 +64,18 @@ /* Location: NodeAuthenticationSheet.swift - Flood routing toggle */ "remoteNodes.auth.floodRouting" = "Flood Routing"; "remoteNodes.auth.floodRetryStatus" = "No reply over the known route. Retrying with flood routing."; -"remoteNodes.auth.floodFooter" = "Flood routing is slower and uses more network airtime. Use it when the known route does not work from your current location. A new route is learned automatically after login."; -/* Location: NodeAuthenticationSheet.swift - Path section footer when stored path exists */ -"remoteNodes.auth.pathFooter" = "Use the known route to this node, or switch to flood routing to let the network find a path."; +/* Footer when this sign-in will clear the saved route and use flood */ +"remoteNodes.auth.floodFooter" = "This sign-in clears the saved route and uses flood. Flood routing is slower and uses more network airtime. A new route is learned if sign-in succeeds."; + +/* Footer after this sign-in has cleared the saved route */ +"remoteNodes.auth.floodFooterCleared" = "The saved route is cleared. Sign-in is using flood. A new route is learned if sign-in succeeds."; + +/* Footer when a timeout clears the route and retries by flood */ +"remoteNodes.auth.pathFooter" = "If there is no reply, the route is cleared and sign-in tries once by flood."; + +/* Footer when a timeout stops and leaves the route */ +"remoteNodes.auth.pathFooterKept" = "If there is no reply, sign-in stops and the route stays."; /* Location: NodeAuthenticationSheet.swift - Path hop whose repeater is not known */ "remoteNodes.auth.pathHopUnknown" = ""; @@ -84,6 +94,26 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Repeater Settings"; +"remoteNodes.sensor.adminRequired" = "Sensor management requires administrator access."; + +"remoteNodes.sensor.saved" = "Setting verified."; + +"remoteNodes.sensor.rebootSent" = "Reboot request sent. The sensor has not confirmed a restart. Authenticate again before sending more commands."; + +"remoteNodes.sensor.rebootConfirmation" = "Send a reboot request to this sensor?"; + +"remoteNodes.sensor.runtimeOnly" = "Changes affect the running sensor. Persistence across reboot depends on its firmware."; + +"remoteNodes.sensor.value" = "Value"; + +"remoteNodes.sensor.save" = "Save"; + +"remoteNodes.sensor.reload" = "Reload"; + +"remoteNodes.sensor.empty" = "This sensor exposes no settings."; + +"remoteNodes.sensor.title" = "Sensor Management"; + /* Location: RepeaterSettingsView.swift - Done button (used in multiple places) */ "remoteNodes.settings.done" = "Done"; diff --git a/MC1/Resources/Localization/en.lproj/Settings.strings b/MC1/Resources/Localization/en.lproj/Settings.strings index 392e51b1b5..ef21b80aa2 100644 --- a/MC1/Resources/Localization/en.lproj/Settings.strings +++ b/MC1/Resources/Localization/en.lproj/Settings.strings @@ -46,9 +46,6 @@ /* Section header for device information */ "device.header" = "Device"; -/* Status shown when device is connected */ -"device.connected" = "Connected"; - /* Footer shown when no device is connected */ "device.noDeviceConnected" = "No MeshCore device connected"; @@ -60,12 +57,6 @@ /* Navigation title for device info screen */ "deviceInfo.title" = "Device Info"; -/* Section header for connection status */ -"deviceInfo.connection.header" = "Connection"; - -/* Label for connection status */ -"deviceInfo.connection.status" = "Status"; - /* Section header for power and storage */ "deviceInfo.powerStorage.header" = "Power & Storage"; @@ -111,6 +102,12 @@ /* Firmware version fallback format when no version string is reported - %@ is the numeric version code */ "deviceInfo.firmwareVersionFormat" = "v%@"; +/* Heading above retained telemetry after a Device Info reload fails */ +"deviceInfo.lastSuccessfulReading" = "Last successful reading"; + +/* Section header for Device Info telemetry */ +"deviceInfo.telemetry.header" = "Node Telemetry"; + /* Section header for identity information */ /* Label for public key */ "deviceInfo.publicKey" = "Public Key"; @@ -165,6 +162,9 @@ /* Button to scan for Bluetooth devices */ "deviceSelection.scanBluetooth" = "Scan for Bluetooth Device"; +/* Button title while this radio is being paired again */ +"deviceSelection.rePairing" = "Re-pairing..."; + /* Trailing control on a previously paired row that still needs iPhone setup */ "deviceSelection.setup" = "Set Up"; @@ -735,6 +735,21 @@ /* Alert message for clear logs */ "diagnostics.alert.clear.message" = "This will delete all stored debug logs. Exported log files will not be affected."; +/* Toggle to enable collecting local debug logs */ +"diagnostics.collectLogs" = "Collect Debug Logs"; + +/* Footer shown when debug log collection is off */ +"diagnostics.footer.disabled" = "Local debug logs are not collected."; + +/* Alert title for disabling collection */ +"diagnostics.alert.disable.title" = "Disable Collection"; + +/* Button to confirm disabling collection */ +"diagnostics.alert.disable.confirm" = "Disable Collection"; + +/* Alert message for disabling collection */ +"diagnostics.alert.disable.message" = "This will delete all stored debug logs and stop collecting them. Exported log files will not be affected."; + /* Error when export fails */ "diagnostics.error.exportFailed" = "Failed to create export file"; @@ -743,6 +758,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Chats"; +"blocksAndFilters.title" = "Blocks & Filters"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -862,6 +879,8 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Companion"; +"notifications.discoveryCompanionsAndSensors" = "Companions & Sensors"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Repeater"; @@ -1023,6 +1042,9 @@ /* Editor footer when the password is too long */ "radioWiFi.editor.passwordLength" = "A password can be up to 63 bytes."; +/* Editor footer when a credential contains a character the firmware cannot store */ +"radioWiFi.editor.unsupportedCharacter" = "The network name or password contains a character this radio can't store."; + /* Button that clears the radio's saved WiFi settings */ "radioWiFi.clear" = "Clear WiFi Settings"; @@ -1188,6 +1210,35 @@ /* Footer explaining the acknowledgments setting */ "directMessages.footer" = "Number of acknowledgments sent per direct message. Use 2 for better delivery confirmation over unreliable links."; +/* Switch that clears the known route after the path attempts */ +"directMessages.fallback" = "Fall Back to Flood"; + +/* Picker label for attempts on the known route */ +"directMessages.directAttempts" = "Attempts on Path"; + +/* Picker label for attempts sent by flood after the route is cleared */ +"directMessages.floodAttempts" = "Flood Attempts"; + +/* Footer when Fall Back to Flood is on */ +"directMessages.attemptsFooterOn" = "The route is cleared after Attempts on Path. Flood Attempts are sent by flood after that. A contact with no known route is sent by flood."; + +/* Footer when Fall Back to Flood is off */ +"directMessages.attemptsFooterOff" = "Attempts on Path stay on the known route, and the route is left in place. A contact with no known route is sent by flood."; + +// MARK: - Path Fallback + +/* Section header for sign-in, command, and contact telemetry path fallback */ +"pathFallback.header" = "Path Fallback"; + +/* Switch that clears the known route after a timeout */ +"pathFallback.fallback" = "Fall Back to Flood"; + +/* Footer when path fallback is on */ +"pathFallback.footerOn" = "Sign-in, repeater and room commands that expect a reply, and contact telemetry use the known route. If there is no reply, the route is cleared and tried once by flood."; + +/* Footer when path fallback is off */ +"pathFallback.footerOff" = "Sign-in, commands, and contact telemetry stay on the known route. If there is no reply, they stop and the route stays. Flood Routing on the sign-in screen clears that node's saved route."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ @@ -1202,12 +1253,24 @@ /* Menu item to disconnect from the current device */ "bleStatus.disconnect" = "Disconnect"; +/* Menu item to stop automatic reconnection until another explicit connection */ +"bleStatus.stopReconnecting" = "Stop Reconnecting"; + +/* Menu item to cancel the current connection request */ +"bleStatus.cancelConnection" = "Cancel Connection"; + /* Status shown when device is disconnected */ "bleStatus.status.disconnected" = "Disconnected"; /* Status shown when device is connecting */ "bleStatus.status.connecting" = "Connecting..."; +/* Status shown while reconnecting to the selected device */ +"bleStatus.status.reconnecting" = "Reconnecting…"; + +/* Status shown while automatic reconnection remains enabled between attempts */ +"bleStatus.status.waitingToReconnect" = "Waiting to Reconnect"; + /* Status shown when device is connected but not ready */ "bleStatus.status.connected" = "Connected"; @@ -1220,6 +1283,9 @@ /* Accessibility label for BLE status indicator */ "bleStatus.accessibilityLabel" = "Bluetooth connection status"; +/* Accessibility text combining a descriptive prefix and connection state or context; arguments may themselves contain a radio name and status */ +"bleStatus.accessibilityValue" = "%1$@, %2$@"; + /* Accessibility hint when disconnected */ "bleStatus.accessibilityHint.disconnected" = "Double tap to connect device"; @@ -1323,6 +1389,24 @@ /* Import failed after one or more settings were already written; %@ is the underlying error message */ "configImport.failedPartial" = "%@ Some settings may have already been written to the device. Review the device's configuration."; +/* Interrupted identity import recovery */ +"configImport.identityOutcomeUnknown" = "The connection was interrupted while importing the identity on %@. The radio may have changed identity. The configuration import was not completed."; + +/* Interrupted identity import recovery */ +"configImport.retryIdentityImport" = "Retry Identity Import"; + +/* Interrupted identity import recovery */ +"configImport.confirmIdentityRecovery" = "This will replace the identity of the radio reached at %@ using the private key in the selected file. The configuration import will not continue."; + +/* Confirmation alert title when retrying an interrupted identity import */ +"configImport.confirmTitleIdentityRecovery" = "Replace Radio Identity?"; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryComplete" = "The identity was reapplied. The configuration import was not completed. Import the file again to apply its other settings."; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryKeyRequired" = "Select a configuration file containing the private key to retry identity import."; + /* Import success */ "configImport.importSuccess" = "Configuration imported successfully"; @@ -1422,6 +1506,63 @@ /* Validation error: no empty channel slot left (param: channel name) */ "configImport.error.noAvailableChannelSlot" = "No empty channel slot available for \"%@\""; +// MARK: - Text Rules + +"textRules.rules" = "Filter Rules"; +"textRules.empty" = "No Filter Rules"; +"textRules.loading" = "Loading Filter Rules…"; +"textRules.loadFailed" = "Could not load filter rules. New messages won’t use filter rules until they can be loaded."; +"textRules.retryAccessibility" = "Try Loading Filter Rules Again"; +"textRules.saveFailed" = "Could not save filter rules. Try again."; +"textRules.new.title" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"textRules.new.containsMessageFooter" = "Matches anywhere in the message, including inside a word."; +"textRules.new.wholeMessageFooter" = "Matches only when the whole message is this phrase."; +"textRules.new.containsSenderFooter" = "Matches anywhere in the sender’s name, including inside a word. Reactions from that sender are hidden too."; +"textRules.new.wholeNameFooter" = "Matches only when the sender’s name is exactly this. Reactions from that sender are hidden too."; +"textRules.new.containsMessageOrSenderFooter" = "Matches the message or the sender’s name, including inside a word. Reactions from a matching sender are hidden too."; +"textRules.new.wholeMessageOrSenderFooter" = "Matches only when the whole message or the whole sender name is this phrase. Reactions from a matching sender are hidden too."; +"textRules.field.message" = "Message"; +"textRules.field.sender" = "Sender"; +"textRules.field.messageOrSender" = "Message or Sender"; +"textRules.match.contains" = "Contains"; +"textRules.match.wholeMessage" = "Whole Message"; +"textRules.match.wholeName" = "Whole Name"; +"textRules.match.wholeField" = "Whole Field"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Use rules for"; +"textRules.types.footer" = "On includes every chat of that type, including chats you join later."; +"textRules.types.publicChannel" = "Public"; +"textRules.types.hashtagChannel" = "Hashtag Channels"; +"textRules.types.privateChannel" = "Private Channels"; +"textRules.selection.all" = "All"; +"textRules.selection.none" = "None"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats for %@"; +"textRules.selection.footer" = "All includes chats you join later."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"textRules.archive.footer" = "The latest %d hidden messages are kept on this device. They aren’t included in app backups."; +"textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; +"textRules.archive.rule" = "Rule"; +"textRules.archive.chat" = "Chat"; +"textRules.archive.myNode" = "My Node"; +"textRules.archive.time" = "Time"; +"textRules.archive.unknownConversation" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +"radioCleanup.title" = "Cleanup"; +"radioCleanup.running" = "Removing radio data"; +"radioCleanup.failed" = "Hidden messages from this radio may still be on this installation."; +"radioCleanup.completed" = "Radio data removed"; +"radioCleanup.retryAccessibility" = "Try Radio Cleanup Again for %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ @@ -1984,7 +2125,7 @@ "settings.backup.export.alert.title" = "Security Notice"; /* Export confirmation alert message */ -"settings.backup.export.alert.message" = "This backup includes channel encryption keys, message history, your contact list, and the WiFi node's local network address and port. Store the exported file securely."; +"settings.backup.export.alert.message" = "This backup includes channel encryption keys, message history, your contact list, and the WiFi node's local network address and port. The backup may also include GPS coordinates captured from radios. Store the exported file securely."; /* Export confirmation alert export button */ "settings.backup.export.alert.export" = "Export"; diff --git a/MC1/Resources/Localization/en.lproj/WhatsNew.strings b/MC1/Resources/Localization/en.lproj/WhatsNew.strings index bba2d6d7f8..edee7e0ca0 100644 --- a/MC1/Resources/Localization/en.lproj/WhatsNew.strings +++ b/MC1/Resources/Localization/en.lproj/WhatsNew.strings @@ -65,3 +65,23 @@ "whatsNew.moreChanges.title" = "More changes"; /* What's New v1.6 - More changes, description */ "whatsNew.moreChanges.description" = "Tap \"See all new changes\" below to view the full list of bug fixes and other features."; + +/* What's New v1.7 - Direct messages, title */ +"whatsNew.directMessages.title" = "Direct messages"; +/* What's New v1.7 - Direct messages, description */ +"whatsNew.directMessages.description" = "Direct messages now try the path 4 times, then flood 4 times. Change Attempts on Path, Flood Attempts, and Fall Back to Flood in Advanced Settings."; + +/* What's New v1.7 - Blocks and filters, title */ +"whatsNew.blocksAndFilters.title" = "Blocks & Filters"; +/* What's New v1.7 - Blocks and filters, description */ +"whatsNew.blocksAndFilters.description" = "Hide messages that match a word or phrase. A rule can look at the message, the sender's name, or both, and you choose which chats it applies to. Hidden messages can be seen in Recently Blocked under Settings > Blocks & Filters."; + +/* What's New v1.7 - Node telemetry, title */ +"whatsNew.nodeTelemetry.title" = "Node telemetry"; +/* What's New v1.7 - Node telemetry, description */ +"whatsNew.nodeTelemetry.description" = "Settings > Device Info shows telemetry from the node you are connected to."; + +/* What's New v1.7 - Live Activity, title */ +"whatsNew.liveActivity.title" = "Live Activity"; +/* What's New v1.7 - Live Activity, description */ +"whatsNew.liveActivity.description" = "Unread messages are more prominent and the packets per minute rate is easier to understand."; diff --git a/MC1/Resources/Localization/es.lproj/Chats.strings b/MC1/Resources/Localization/es.lproj/Chats.strings index 56fe333f2a..a5aaea9db5 100644 --- a/MC1/Resources/Localization/es.lproj/Chats.strings +++ b/MC1/Resources/Localization/es.lproj/Chats.strings @@ -588,6 +588,12 @@ /* Location: UnifiedMessageBubble.swift - VoiceOver prefix when the visible body is a translation - %@ is the translated text */ "chats.message.translatedAccessibility" = "Traducido: %@"; +/* Location: MessageVisibleBody.swift - VoiceOver prefix when the visible body is an MECP reading - %@ is the reading */ +"chats.message.readingAccessibility" = "Lectura: %@"; + +/* Location: MECPCatalog - Person count line in an MECP reading */ +"chats.message.mecpPersonCount" = "%lld personas"; + /* Location: UnifiedMessageBubble.swift - Context menu action to view repeat details */ "chats.message.action.repeatDetails" = "Detalles de repetición"; @@ -641,6 +647,9 @@ /* Location: UnifiedMessageBubble.swift - Context menu text showing SNR - %@ is formatted value */ "chats.message.info.snr" = "SNR: %@"; +/* Location: ActionsDetailsSection.swift - Stored MECP wire string under SNR. %@ is the original text */ +"chats.message.info.mecp" = "MECP: %@"; + /* Location: MessageActionsSheet.swift - Context menu text showing the radio region the message was flooded under - %@ is region name. "Flooded" is a domain term for mesh-broadcast across all nodes in a radio region. */ "chats.message.info.floodedUnder" = "Región: %@"; @@ -1147,8 +1156,8 @@ /* Location: ConversationRow.swift - Purpose: Mentions only indicator */ "chats.row.mentionsOnly" = "Solo menciones"; -/* TODO: translate - Accessibility label for the row actions menu */ -"chats.row.actionsMenu.accessibilityLabel" = "Conversation actions"; +/* Accessibility label for the row actions menu */ +"chats.row.actionsMenu.accessibilityLabel" = "Acciones de la conversación"; // MARK: - Reactions diff --git a/MC1/Resources/Localization/es.lproj/Chats.stringsdict b/MC1/Resources/Localization/es.lproj/Chats.stringsdict new file mode 100644 index 0000000000..7364394f0c --- /dev/null +++ b/MC1/Resources/Localization/es.lproj/Chats.stringsdict @@ -0,0 +1,22 @@ + + + + + chats.message.mecpPersonCount + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + lld + one + %lld persona + other + %lld personas + + + + diff --git a/MC1/Resources/Localization/es.lproj/Contacts.strings b/MC1/Resources/Localization/es.lproj/Contacts.strings index 26f868ded3..8e681c612d 100644 --- a/MC1/Resources/Localization/es.lproj/Contacts.strings +++ b/MC1/Resources/Localization/es.lproj/Contacts.strings @@ -44,6 +44,8 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Sala"; +"contacts.nodeKind.sensor" = "Sensor"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Descubierto"; @@ -75,6 +77,8 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Salas"; +"contacts.segment.sensors" = "Sensores"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "Filtrar nodos"; @@ -168,9 +172,13 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "Sin salas"; +"contacts.list.empty.sensors.title" = "Sin sensores"; + /* Location: ContactsListView.swift - Purpose: No rooms empty description */ "contacts.list.empty.rooms.description" = "Las salas son servidores de chat públicos en la red mesh. Aparecerán aquí cuando se descubran."; +"contacts.list.empty.sensors.description" = "Los sensores aparecen aquí cuando se descubren en la red mesh."; + /* Location: ContactsListView.swift - Purpose: No search results title */ "contacts.list.empty.search.title" = "Sin resultados"; @@ -623,6 +631,8 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter - Rooms */ "contacts.discovery.segment.rooms" = "Salas"; +"contacts.discovery.segment.sensors" = "Sensores"; + /* Location: DiscoverSegmentPicker.swift - Purpose: VoiceOver label for the Discovery segment filter picker (iOS 18 fallback) */ "contacts.discovery.segment.pickerLabel" = "Filtrar nodos descubiertos"; diff --git a/MC1/Resources/Localization/es.lproj/Localizable.strings b/MC1/Resources/Localization/es.lproj/Localizable.strings index 493ba21376..b57203ce83 100644 --- a/MC1/Resources/Localization/es.lproj/Localizable.strings +++ b/MC1/Resources/Localization/es.lproj/Localizable.strings @@ -145,6 +145,8 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "Nueva sala descubierta"; +"notifications.discovery.sensor" = "Nuevo sensor descubierto"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -493,6 +495,14 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Respuesta no válida del nodo remoto"; +"error.remoteNode.sensorOutcomeUnknown" = "No se pudo verificar el cambio. Recarga los ajustes antes de volver a guardar."; + +"error.remoteNode.sensorSettingRejected" = "El sensor rechazó este ajuste."; + +"error.remoteNode.invalidSensorSetting" = "Usa una clave y un valor no vacíos y sin espacios en blanco. El comando completo debe caber en 160 bytes UTF-8."; + +"error.remoteNode.invalidPasswordLength" = "Las contraseñas no deben usar más de %d bytes UTF-8."; + /* Location: RemoteNodeError+UserFacingMessage.swift - Remote node rejected the operation */ "error.remoteNode.permissionDenied" = "Permiso denegado"; diff --git a/MC1/Resources/Localization/es.lproj/Map.strings b/MC1/Resources/Localization/es.lproj/Map.strings index 36a2ad56c1..3b2f68fa0b 100644 --- a/MC1/Resources/Localization/es.lproj/Map.strings +++ b/MC1/Resources/Localization/es.lproj/Map.strings @@ -40,6 +40,8 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Filtrar"; +"map.controls.contactsAndSensors" = "Contactos y sensores"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Filtros activos"; @@ -264,6 +266,8 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Sala"; +"map.nodeKind.sensor" = "Sensor"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -281,6 +285,8 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Sala"; +"map.callout.nodeKind.sensor" = "Sensor"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "Añadir"; diff --git a/MC1/Resources/Localization/es.lproj/Onboarding.strings b/MC1/Resources/Localization/es.lproj/Onboarding.strings index b7bcc864f1..5b858161b2 100644 --- a/MC1/Resources/Localization/es.lproj/Onboarding.strings +++ b/MC1/Resources/Localization/es.lproj/Onboarding.strings @@ -69,6 +69,9 @@ /* Location: DeviceScanView.swift - Subtitle with pairing instructions */ "deviceScan.subtitle" = "Enciende tu radio, desconéctala de todas las demás apps y dispositivos y, a continuación, toca Añadir dispositivo."; +/* Location: DeviceScanView.swift - Subtitle while bond-loss recovery is re-pairing */ +"deviceScan.rePairingSubtitle" = "Enciende tu radio y desconéctala de todas las demás apps y dispositivos."; + /* Location: DeviceScanView.swift - Message shown when device is already paired */ "deviceScan.alreadyPaired" = "Tu dispositivo ya está emparejado"; @@ -78,9 +81,6 @@ /* Location: DeviceScanView.swift - Button to continue after pairing */ "deviceScan.continue" = "Continuar"; -/* Location: DeviceScanView.swift - Button label while connecting */ -"deviceScan.connecting" = "Conectando..."; - /* Location: DeviceScanView.swift - Button to connect simulator (debug) */ "deviceScan.connectSimulator" = "Conectar simulador"; diff --git a/MC1/Resources/Localization/es.lproj/RemoteNodes.strings b/MC1/Resources/Localization/es.lproj/RemoteNodes.strings index 2bb04362e6..3b678b3554 100644 --- a/MC1/Resources/Localization/es.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/es.lproj/RemoteNodes.strings @@ -32,6 +32,8 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Repetidor"; +"remoteNodes.auth.typeSensor" = "Sensor"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Autenticación"; @@ -62,10 +64,18 @@ /* Location: NodeAuthenticationSheet.swift - Flood routing toggle */ "remoteNodes.auth.floodRouting" = "Enrutamiento Flood"; "remoteNodes.auth.floodRetryStatus" = "Sin respuesta por la ruta conocida. Reintentando con enrutamiento flood."; -"remoteNodes.auth.floodFooter" = "El enrutamiento flood es más lento y consume más tiempo de aire de la red. Úsalo cuando la ruta conocida no funcione desde tu ubicación actual. Tras iniciar sesión se aprende automáticamente una nueva ruta."; +/* Footer when this sign-in will clear the saved route and use flood */ +"remoteNodes.auth.floodFooter" = "Al iniciar sesión se borra la ruta guardada y se usa enrutamiento flood. El enrutamiento flood es más lento y consume más tiempo de aire de la red. Solo se aprende una nueva ruta si se consigue iniciar sesión."; + +/* Footer after this sign-in has cleared the saved route */ +"remoteNodes.auth.floodFooterCleared" = "La ruta guardada se ha borrado. Se usa enrutamiento flood para iniciar sesión. Solo se aprende una nueva ruta si se consigue iniciar sesión."; + + +/* Footer when a timeout clears the route and retries by flood */ +"remoteNodes.auth.pathFooter" = "Si no hay respuesta, se borra la ruta y se intenta iniciar sesión una vez con enrutamiento flood."; -/* Location: NodeAuthenticationSheet.swift - Path section footer when stored path exists */ -"remoteNodes.auth.pathFooter" = "Usa la ruta conocida a este nodo o activa el enrutamiento flood para que la red encuentre un camino."; +/* Footer when a timeout stops and leaves the route */ +"remoteNodes.auth.pathFooterKept" = "Si no hay respuesta, se detiene el intento de iniciar sesión y la ruta se mantiene."; /* Location: NodeAuthenticationSheet.swift - Path hop whose repeater is not known */ "remoteNodes.auth.pathHopUnknown" = ""; @@ -84,6 +94,26 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Ajustes del repetidor"; +"remoteNodes.sensor.adminRequired" = "La gestión del sensor requiere acceso de administrador."; + +"remoteNodes.sensor.saved" = "Ajuste verificado."; + +"remoteNodes.sensor.rebootSent" = "Solicitud de reinicio enviada. El sensor no ha confirmado un reinicio. Vuelve a iniciar sesión antes de enviar más comandos."; + +"remoteNodes.sensor.rebootConfirmation" = "¿Enviar una solicitud de reinicio a este sensor?"; + +"remoteNodes.sensor.runtimeOnly" = "Los cambios afectan al sensor en funcionamiento. Conservarlos tras reiniciar depende de su firmware."; + +"remoteNodes.sensor.value" = "Valor"; + +"remoteNodes.sensor.save" = "Guardar"; + +"remoteNodes.sensor.reload" = "Recargar"; + +"remoteNodes.sensor.empty" = "Este sensor no expone ningún ajuste."; + +"remoteNodes.sensor.title" = "Gestión del sensor"; + /* Location: RepeaterSettingsView.swift - Done button (used in multiple places) */ "remoteNodes.settings.done" = "Listo"; diff --git a/MC1/Resources/Localization/es.lproj/Settings.strings b/MC1/Resources/Localization/es.lproj/Settings.strings index 7cc9ab4fdd..737abd5d2e 100644 --- a/MC1/Resources/Localization/es.lproj/Settings.strings +++ b/MC1/Resources/Localization/es.lproj/Settings.strings @@ -46,9 +46,6 @@ /* Section header for device information */ "device.header" = "Dispositivo"; -/* Status shown when device is connected */ -"device.connected" = "Conectado"; - /* Footer shown when no device is connected */ "device.noDeviceConnected" = "Ningún dispositivo MeshCore conectado"; @@ -60,12 +57,6 @@ /* Navigation title for device info screen */ "deviceInfo.title" = "Info del dispositivo"; -/* Section header for connection status */ -"deviceInfo.connection.header" = "Conexión"; - -/* Label for connection status */ -"deviceInfo.connection.status" = "Estado"; - /* Section header for power and storage */ "deviceInfo.powerStorage.header" = "Energía y almacenamiento"; @@ -111,6 +102,12 @@ /* Firmware version fallback format when no version string is reported - %@ is the numeric version code */ "deviceInfo.firmwareVersionFormat" = "v%@"; +/* Heading above retained telemetry after a Device Info reload fails */ +"deviceInfo.lastSuccessfulReading" = "Última lectura correcta"; + +/* Section header for Device Info telemetry */ +"deviceInfo.telemetry.header" = "Telemetría del nodo"; + /* Section header for identity information */ /* Label for public key */ "deviceInfo.publicKey" = "Clave pública"; @@ -165,6 +162,9 @@ /* Button to scan for Bluetooth devices */ "deviceSelection.scanBluetooth" = "Buscar dispositivo Bluetooth"; +/* Button title while this radio is being paired again */ +"deviceSelection.rePairing" = "Volviendo a emparejar..."; + /* Trailing control on a previously paired row that still needs iPhone setup */ /* AI-translated - please verify with native speakers. */ "deviceSelection.setup" = "Configurar"; @@ -746,6 +746,21 @@ /* Alert message for clear logs */ "diagnostics.alert.clear.message" = "Esto eliminará todos los registros de depuración almacenados. Los archivos de registro exportados no se verán afectados."; +/* Toggle to enable collecting local debug logs */ +"diagnostics.collectLogs" = "Recopilar registros de depuración"; + +/* Footer shown when debug log collection is off */ +"diagnostics.footer.disabled" = "No se recopilan registros de depuración locales."; + +/* Alert title for disabling collection */ +"diagnostics.alert.disable.title" = "Desactivar recopilación"; + +/* Button to confirm disabling collection */ +"diagnostics.alert.disable.confirm" = "Desactivar recopilación"; + +/* Alert message for disabling collection */ +"diagnostics.alert.disable.message" = "Esto eliminará todos los registros de depuración almacenados y dejará de recopilarlos. Los archivos de registro exportados no se verán afectados."; + /* Error when export fails */ "diagnostics.error.exportFailed" = "Error al crear archivo de exportación"; @@ -754,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Chats"; +"blocksAndFilters.title" = "Bloqueo y filtros"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -822,6 +839,8 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Acompañante"; +"notifications.discoveryCompanionsAndSensors" = "Acompañantes y sensores"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Repetidor"; @@ -983,6 +1002,9 @@ /* Editor footer when the password is too long */ "radioWiFi.editor.passwordLength" = "Una contraseña puede tener hasta 63 bytes."; +/* Editor footer when a credential contains a character the firmware cannot store */ +"radioWiFi.editor.unsupportedCharacter" = "El nombre de la red o la contraseña contiene un carácter que esta radio no puede almacenar."; + /* Button that clears the radio's saved WiFi settings */ "radioWiFi.clear" = "Borrar ajustes de WiFi"; @@ -1148,6 +1170,35 @@ /* Footer explaining the acknowledgments setting */ "directMessages.footer" = "Número de acuses de recibo enviados por mensaje directo. Usa 2 para una mejor confirmación de entrega en enlaces poco fiables."; +/* Switch that clears the known route after the path attempts */ +"directMessages.fallback" = "Recurrir al enrutamiento flood"; + +/* Picker label for attempts on the known route */ +"directMessages.directAttempts" = "Intentos en la ruta"; + +/* Picker label for attempts sent by flood after the route is cleared */ +"directMessages.floodAttempts" = "Intentos de flood"; + +/* Footer when Fall Back to Flood is on */ +"directMessages.attemptsFooterOn" = "La ruta se borra tras los Intentos en la ruta. Los Intentos de flood se envían después con enrutamiento flood. Un mensaje a un contacto sin ruta conocida se envía con enrutamiento flood."; + +/* Footer when Fall Back to Flood is off */ +"directMessages.attemptsFooterOff" = "Los Intentos en la ruta siguen en la ruta conocida y la ruta se mantiene. Un mensaje a un contacto sin ruta conocida se envía con enrutamiento flood."; + +// MARK: - Path Fallback + +/* Section header for sign-in, command, and contact telemetry path fallback */ +"pathFallback.header" = "Reserva de ruta"; + +/* Switch that clears the known route after a timeout */ +"pathFallback.fallback" = "Recurrir al enrutamiento flood"; + +/* Footer when path fallback is on */ +"pathFallback.footerOn" = "Iniciar sesión, los comandos a un Repetidor y a una Sala que esperan respuesta, y la telemetría del contacto usan la ruta conocida. Si no hay respuesta, se borra la ruta y se intenta una vez con enrutamiento flood."; + +/* Footer when path fallback is off */ +"pathFallback.footerOff" = "Iniciar sesión, los comandos y la telemetría del contacto siguen en la ruta conocida. Si no hay respuesta, se detienen y la ruta se mantiene. Activar Enrutamiento Flood en la pantalla para iniciar sesión borra la ruta guardada de ese nodo."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ @@ -1162,12 +1213,24 @@ /* Menu item to disconnect from the current device */ "bleStatus.disconnect" = "Desconectar"; +/* Menu item to stop automatic reconnection until another explicit connection */ +"bleStatus.stopReconnecting" = "Detener reconexión"; + +/* Menu item to cancel the current connection request */ +"bleStatus.cancelConnection" = "Cancelar conexión"; + /* Status shown when device is disconnected */ "bleStatus.status.disconnected" = "Desconectado"; /* Status shown when device is connecting */ "bleStatus.status.connecting" = "Conectando..."; +/* Status shown while reconnecting to the selected device */ +"bleStatus.status.reconnecting" = "Reconectando..."; + +/* Status shown while automatic reconnection remains enabled between attempts */ +"bleStatus.status.waitingToReconnect" = "Esperando reconexión"; + /* Status shown when device is connected but not ready */ "bleStatus.status.connected" = "Conectado"; @@ -1180,6 +1243,9 @@ /* Accessibility label for BLE status indicator */ "bleStatus.accessibilityLabel" = "Estado de conexión Bluetooth"; +/* TODO: translate - Accessibility text combining a descriptive prefix and connection state or context; arguments may themselves contain a radio name and status */ +"bleStatus.accessibilityValue" = "%1$@, %2$@"; + /* Accessibility hint when disconnected */ "bleStatus.accessibilityHint.disconnected" = "Toca dos veces para conectar dispositivo"; @@ -1318,6 +1384,24 @@ /* Import failed after one or more settings were already written; %@ is the underlying error message */ "configImport.failedPartial" = "%@ Es posible que algunos ajustes ya se hayan escrito en el dispositivo. Revisa la configuración del dispositivo."; +/* Interrupted identity import recovery */ +"configImport.identityOutcomeUnknown" = "Se interrumpió la conexión mientras se importaba la identidad en %@. Es posible que la radio haya cambiado de identidad. La importación de la configuración no se completó."; + +/* Interrupted identity import recovery */ +"configImport.retryIdentityImport" = "Reintentar importación de identidad"; + +/* Interrupted identity import recovery */ +"configImport.confirmIdentityRecovery" = "Esto reemplazará la identidad de la radio a la que se llegó en %@ usando la clave privada del archivo seleccionado. La importación de la configuración no continuará."; + +/* Confirmation alert title when retrying an interrupted identity import */ +"configImport.confirmTitleIdentityRecovery" = "¿Reemplazar la identidad de la radio?"; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryComplete" = "Se volvió a aplicar la identidad. La importación de la configuración no se completó. Importa el archivo de nuevo para aplicar los demás ajustes."; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryKeyRequired" = "Selecciona un archivo de configuración que contenga la clave privada para reintentar la importación de identidad."; + /* Import success */ "configImport.importSuccess" = "Configuración importada correctamente"; @@ -1434,6 +1518,63 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "Mostrar miniaturas del mapa descarga las teselas para la coordenada desde un servidor de terceros, lo que puede revelar tu dirección IP."; +// MARK: - Text Rules + +"textRules.rules" = "Reglas de filtro"; +"textRules.empty" = "Sin reglas de filtro"; +"textRules.loading" = "Cargando reglas de filtro…"; +"textRules.loadFailed" = "No se pudieron cargar las reglas de filtro. Hasta que se puedan cargar, los mensajes nuevos no se filtrarán."; +"textRules.retryAccessibility" = "Reintentar la carga de las reglas de filtro"; +"textRules.saveFailed" = "No se pudieron guardar las reglas de filtro. Inténtalo de nuevo."; +"textRules.new.title" = "Nueva regla"; +"textRules.new.phrase" = "Palabra o frase"; +"textRules.new.lookIn" = "Buscar en"; +"textRules.new.match" = "Coincidencia"; +"textRules.new.containsMessageFooter" = "Coincide en cualquier parte del mensaje, incluso dentro de una palabra."; +"textRules.new.wholeMessageFooter" = "Coincide solo cuando todo el mensaje es esta frase."; +"textRules.new.containsSenderFooter" = "Coincide en cualquier parte del nombre del remitente, incluso dentro de una palabra. Las reacciones de ese remitente también se ocultan."; +"textRules.new.wholeNameFooter" = "Coincide solo cuando el nombre del remitente es exactamente este. Las reacciones de ese remitente también se ocultan."; +"textRules.new.containsMessageOrSenderFooter" = "Coincide con el mensaje o con el nombre del remitente, incluso dentro de una palabra. Las reacciones de un remitente que coincida también se ocultan."; +"textRules.new.wholeMessageOrSenderFooter" = "Coincide solo cuando todo el mensaje o todo el nombre del remitente es esta frase. Las reacciones de un remitente que coincida también se ocultan."; +"textRules.field.message" = "Mensaje"; +"textRules.field.sender" = "Remitente"; +"textRules.field.messageOrSender" = "Mensaje o remitente"; +"textRules.match.contains" = "Contiene"; +"textRules.match.wholeMessage" = "Todo el mensaje"; +"textRules.match.wholeName" = "Todo el nombre"; +"textRules.match.wholeField" = "Todo el campo"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Usar reglas para"; +"textRules.types.footer" = "Cuando está activado, se incluyen todos los chats de ese tipo, incluso los chats a los que te unas más tarde."; +"textRules.types.publicChannel" = "Público"; +"textRules.types.hashtagChannel" = "Canales hashtag"; +"textRules.types.privateChannel" = "Canales privados"; +"textRules.selection.all" = "Todos"; +"textRules.selection.none" = "Ninguno"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats para %@"; +"textRules.selection.footer" = "Todos incluyen los chats a los que te unas más tarde."; +"textRules.archive.title" = "Mensajes ocultos recientes"; +"textRules.archive.empty" = "Sin mensajes ocultos"; +"textRules.archive.footer" = "Los %d mensajes ocultos más recientes se guardan en este dispositivo. No se incluyen en las copias de seguridad de la app."; +"textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; +"textRules.archive.rule" = "Regla"; +"textRules.archive.chat" = "Chat"; +"textRules.archive.myNode" = "Mi nodo"; +"textRules.archive.time" = "Hora"; +"textRules.archive.unknownConversation" = "Conversación desconocida"; +"textRules.archive.unknownRadio" = "Radio desconocida"; + +"radioCleanup.title" = "Limpieza"; +"radioCleanup.running" = "Eliminando datos de la radio"; +"radioCleanup.failed" = "Los mensajes ocultos de esta radio pueden seguir en esta instalación."; +"radioCleanup.completed" = "Datos de la radio eliminados"; +"radioCleanup.retryAccessibility" = "Reintentar la limpieza de la radio para %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ @@ -1978,7 +2119,7 @@ "settings.backup.export.alert.title" = "Aviso de seguridad"; /* Export confirmation alert message */ -"settings.backup.export.alert.message" = "Esta copia incluye claves de cifrado de canales, el historial de mensajes, tu lista de contactos y la dirección de red local y el puerto del nodo WiFi. Almacena el archivo exportado de forma segura."; +"settings.backup.export.alert.message" = "Esta copia incluye claves de cifrado de canales, el historial de mensajes, tu lista de contactos y la dirección de red local y el puerto del nodo WiFi. La copia también puede incluir coordenadas GPS obtenidas de las radios. Almacena el archivo exportado de forma segura."; /* Export confirmation alert export button */ "settings.backup.export.alert.export" = "Exportar"; diff --git a/MC1/Resources/Localization/es.lproj/WhatsNew.strings b/MC1/Resources/Localization/es.lproj/WhatsNew.strings index 557eadf8f0..60912ea9bb 100644 --- a/MC1/Resources/Localization/es.lproj/WhatsNew.strings +++ b/MC1/Resources/Localization/es.lproj/WhatsNew.strings @@ -65,3 +65,23 @@ "whatsNew.moreChanges.title" = "Más cambios"; /* What's New v1.6 - More changes, description */ "whatsNew.moreChanges.description" = "Toca \"Ver todos los cambios nuevos\" abajo para ver la lista completa de correcciones de errores y otras funciones."; + +/* What's New v1.7 - Direct messages, title */ +"whatsNew.directMessages.title" = "Mensajes directos"; +/* What's New v1.7 - Direct messages, description */ +"whatsNew.directMessages.description" = "Los mensajes directos ahora intentan la ruta 4 veces y luego hacen flood 4 veces. Cambia Intentos en la ruta, Intentos de flood y Recurrir al enrutamiento flood en Ajustes avanzados."; + +/* What's New v1.7 - Blocks and filters, title */ +"whatsNew.blocksAndFilters.title" = "Bloqueo y filtros"; +/* What's New v1.7 - Blocks and filters, description */ +"whatsNew.blocksAndFilters.description" = "Oculta los mensajes que coincidan con una palabra o frase. Una regla puede buscar en el mensaje, en el nombre del remitente o en ambos, y eliges a qué chats se aplica. Los mensajes ocultos se pueden ver en Mensajes ocultos recientes, en Ajustes > Bloqueo y filtros."; + +/* What's New v1.7 - Node telemetry, title */ +"whatsNew.nodeTelemetry.title" = "Telemetría del nodo"; +/* What's New v1.7 - Node telemetry, description */ +"whatsNew.nodeTelemetry.description" = "Ajustes > Info del dispositivo muestra la telemetría del nodo al que estás conectado."; + +/* What's New v1.7 - Live Activity, title */ +"whatsNew.liveActivity.title" = "Actividad en vivo"; +/* What's New v1.7 - Live Activity, description */ +"whatsNew.liveActivity.description" = "Los mensajes sin leer destacan más y la tasa de paquetes por minuto es más fácil de entender."; diff --git a/MC1/Resources/Localization/fr.lproj/Chats.strings b/MC1/Resources/Localization/fr.lproj/Chats.strings index f8c2aec2df..90ef8ad719 100644 --- a/MC1/Resources/Localization/fr.lproj/Chats.strings +++ b/MC1/Resources/Localization/fr.lproj/Chats.strings @@ -588,6 +588,12 @@ /* Location: UnifiedMessageBubble.swift - VoiceOver prefix when the visible body is a translation - %@ is the translated text */ "chats.message.translatedAccessibility" = "Traduit : %@"; +/* Location: MessageVisibleBody.swift - VoiceOver prefix when the visible body is an MECP reading - %@ is the reading */ +"chats.message.readingAccessibility" = "Lecture : %@"; + +/* Location: MECPCatalog - Person count line in an MECP reading */ +"chats.message.mecpPersonCount" = "%lld personnes"; + /* Location: UnifiedMessageBubble.swift - Context menu action to view repeat details */ "chats.message.action.repeatDetails" = "Détails des répétitions"; @@ -641,6 +647,9 @@ /* Location: UnifiedMessageBubble.swift - Context menu text showing SNR - %@ is formatted value */ "chats.message.info.snr" = "RSB : %@"; +/* Location: ActionsDetailsSection.swift - Stored MECP wire string under SNR. %@ is the original text */ +"chats.message.info.mecp" = "MECP : %@"; + /* Location: MessageActionsSheet.swift - Context menu text showing the radio region the message was flooded under - %@ is region name. "Flooded" is a domain term for mesh-broadcast across all nodes in a radio region. */ "chats.message.info.floodedUnder" = "Région : %@"; @@ -1147,8 +1156,8 @@ /* Location: ConversationRow.swift - Mentions only indicator */ "chats.row.mentionsOnly" = "Mentions uniquement"; -/* TODO: translate - Accessibility label for the row actions menu */ -"chats.row.actionsMenu.accessibilityLabel" = "Conversation actions"; +/* Accessibility label for the row actions menu */ +"chats.row.actionsMenu.accessibilityLabel" = "Actions de la conversation"; // MARK: - Reaction Badges & Actions diff --git a/MC1/Resources/Localization/fr.lproj/Chats.stringsdict b/MC1/Resources/Localization/fr.lproj/Chats.stringsdict new file mode 100644 index 0000000000..e1592b891c --- /dev/null +++ b/MC1/Resources/Localization/fr.lproj/Chats.stringsdict @@ -0,0 +1,22 @@ + + + + + chats.message.mecpPersonCount + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + lld + one + %lld personne + other + %lld personnes + + + + diff --git a/MC1/Resources/Localization/fr.lproj/Contacts.strings b/MC1/Resources/Localization/fr.lproj/Contacts.strings index 9776cc1875..e02d5c1162 100644 --- a/MC1/Resources/Localization/fr.lproj/Contacts.strings +++ b/MC1/Resources/Localization/fr.lproj/Contacts.strings @@ -44,6 +44,8 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Salon"; +"contacts.nodeKind.sensor" = "Capteur"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Découvert"; @@ -75,6 +77,8 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Salons"; +"contacts.segment.sensors" = "Capteurs"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "Filtrer les nœuds"; @@ -168,9 +172,13 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "Aucun salon"; +"contacts.list.empty.sensors.title" = "Aucun capteur"; + /* Location: ContactsListView.swift - Purpose: No rooms empty description */ "contacts.list.empty.rooms.description" = "Les salons sont des serveurs de discussion publics sur le maillage. Ils apparaîtront ici dès qu'ils seront découverts."; +"contacts.list.empty.sensors.description" = "Les capteurs apparaissent ici lorsqu'ils sont découverts sur le réseau mesh."; + /* Location: ContactsListView.swift - Purpose: No search results title */ "contacts.list.empty.search.title" = "Aucun résultat"; @@ -623,6 +631,8 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter - Rooms */ "contacts.discovery.segment.rooms" = "Salons"; +"contacts.discovery.segment.sensors" = "Capteurs"; + /* Location: DiscoverSegmentPicker.swift - Purpose: VoiceOver label for the Discovery segment filter picker (iOS 18 fallback) */ "contacts.discovery.segment.pickerLabel" = "Filtrer les nœuds découverts"; diff --git a/MC1/Resources/Localization/fr.lproj/Localizable.strings b/MC1/Resources/Localization/fr.lproj/Localizable.strings index 7e54bf7868..c6aabb5982 100644 --- a/MC1/Resources/Localization/fr.lproj/Localizable.strings +++ b/MC1/Resources/Localization/fr.lproj/Localizable.strings @@ -136,6 +136,8 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "Nouvelle salle découverte"; +"notifications.discovery.sensor" = "Nouveau capteur découvert"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -499,6 +501,14 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Réponse non valide du nœud distant"; +"error.remoteNode.sensorOutcomeUnknown" = "La modification n'a pas pu être vérifiée. Rechargez les réglages avant d'enregistrer de nouveau."; + +"error.remoteNode.sensorSettingRejected" = "Le capteur a refusé ce réglage."; + +"error.remoteNode.invalidSensorSetting" = "Utilisez une clé et une valeur non vides, sans caractère d'espacement. La commande complète doit tenir dans 160 octets UTF-8."; + +"error.remoteNode.invalidPasswordLength" = "Les mots de passe ne doivent pas dépasser %d octets UTF-8."; + /* Location: RemoteNodeError+UserFacingMessage.swift - Remote node rejected the operation */ "error.remoteNode.permissionDenied" = "Autorisation refusée"; diff --git a/MC1/Resources/Localization/fr.lproj/Map.strings b/MC1/Resources/Localization/fr.lproj/Map.strings index c2adc70f20..9d397b353a 100644 --- a/MC1/Resources/Localization/fr.lproj/Map.strings +++ b/MC1/Resources/Localization/fr.lproj/Map.strings @@ -40,6 +40,8 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Filtrer"; +"map.controls.contactsAndSensors" = "Contacts & Capteurs"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Filtres actifs"; @@ -264,6 +266,8 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Salon"; +"map.nodeKind.sensor" = "Capteur"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -281,6 +285,8 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Salon"; +"map.callout.nodeKind.sensor" = "Capteur"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "Ajouter"; diff --git a/MC1/Resources/Localization/fr.lproj/Onboarding.strings b/MC1/Resources/Localization/fr.lproj/Onboarding.strings index 6b23125a0c..f4d5fe1355 100644 --- a/MC1/Resources/Localization/fr.lproj/Onboarding.strings +++ b/MC1/Resources/Localization/fr.lproj/Onboarding.strings @@ -69,6 +69,9 @@ /* Location: DeviceScanView.swift - Subtitle with pairing instructions */ "deviceScan.subtitle" = "Allumez votre radio, déconnectez-la de toutes les autres applications et de tous les autres appareils, puis appuyez sur Ajouter un appareil."; +/* Location: DeviceScanView.swift - Subtitle while bond-loss recovery is re-pairing */ +"deviceScan.rePairingSubtitle" = "Allumez votre radio et déconnectez-la de toutes les autres applications et de tous les autres appareils."; + /* Location: DeviceScanView.swift - Message shown when device is already paired */ "deviceScan.alreadyPaired" = "Votre appareil est déjà associé"; @@ -78,9 +81,6 @@ /* Location: DeviceScanView.swift - Button to continue after pairing */ "deviceScan.continue" = "Continuer"; -/* Location: DeviceScanView.swift - Button label while connecting */ -"deviceScan.connecting" = "Connexion..."; - /* Location: DeviceScanView.swift - Button to connect simulator (debug) */ "deviceScan.connectSimulator" = "Connecter le simulateur"; diff --git a/MC1/Resources/Localization/fr.lproj/RemoteNodes.strings b/MC1/Resources/Localization/fr.lproj/RemoteNodes.strings index bf52ee12d1..cd015623e7 100644 --- a/MC1/Resources/Localization/fr.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/fr.lproj/RemoteNodes.strings @@ -32,6 +32,8 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Répéteur"; +"remoteNodes.auth.typeSensor" = "Capteur"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Authentification"; @@ -62,10 +64,18 @@ /* Location: NodeAuthenticationSheet.swift - Flood routing toggle */ "remoteNodes.auth.floodRouting" = "Routage Flood"; "remoteNodes.auth.floodRetryStatus" = "Aucune réponse par le chemin connu. Nouvelle tentative en routage flood."; -"remoteNodes.auth.floodFooter" = "Le routage flood est plus lent et consomme plus de temps d'antenne sur le réseau. Utilisez-le lorsque le chemin connu ne fonctionne pas depuis votre position actuelle. Un nouveau chemin est appris automatiquement après la connexion."; +/* Footer when this sign-in will clear the saved route and use flood */ +"remoteNodes.auth.floodFooter" = "Cette connexion efface le chemin enregistré et utilise le routage flood. Le routage flood est plus lent et consomme plus de temps d'antenne sur le réseau. Un nouveau chemin est appris seulement si la connexion réussit."; + +/* Footer after this sign-in has cleared the saved route */ +"remoteNodes.auth.floodFooterCleared" = "Le chemin enregistré est effacé. La connexion utilise le routage flood. Un nouveau chemin est appris seulement si la connexion réussit."; + + +/* Footer when a timeout clears the route and retries by flood */ +"remoteNodes.auth.pathFooter" = "S'il n'y a aucune réponse, le chemin est effacé et la connexion fait une seule tentative en routage flood."; -/* Location: NodeAuthenticationSheet.swift - Path section footer when stored path exists */ -"remoteNodes.auth.pathFooter" = "Utilisez le chemin connu vers ce nœud ou activez le routage flood pour laisser le réseau trouver un chemin."; +/* Footer when a timeout stops and leaves the route */ +"remoteNodes.auth.pathFooterKept" = "S'il n'y a aucune réponse, la connexion s'arrête et le chemin reste en place."; /* Location: NodeAuthenticationSheet.swift - Path hop whose repeater is not known */ "remoteNodes.auth.pathHopUnknown" = ""; @@ -84,6 +94,26 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Réglages du répéteur"; +"remoteNodes.sensor.adminRequired" = "La gestion du capteur nécessite un accès administrateur."; + +"remoteNodes.sensor.saved" = "Réglage vérifié."; + +"remoteNodes.sensor.rebootSent" = "Demande de redémarrage envoyée. Le capteur n'a pas confirmé le redémarrage. Authentifiez-vous de nouveau avant d'envoyer d'autres commandes."; + +"remoteNodes.sensor.rebootConfirmation" = "Envoyer une demande de redémarrage à ce capteur ?"; + +"remoteNodes.sensor.runtimeOnly" = "Les modifications s'appliquent au capteur en cours d'exécution. La conservation après redémarrage dépend de son micrologiciel."; + +"remoteNodes.sensor.value" = "Valeur"; + +"remoteNodes.sensor.save" = "Enregistrer"; + +"remoteNodes.sensor.reload" = "Recharger"; + +"remoteNodes.sensor.empty" = "Ce capteur n'expose aucun réglage."; + +"remoteNodes.sensor.title" = "Gestion du capteur"; + /* Location: RepeaterSettingsView.swift - Done button (used in multiple places) */ "remoteNodes.settings.done" = "Terminé"; diff --git a/MC1/Resources/Localization/fr.lproj/Settings.strings b/MC1/Resources/Localization/fr.lproj/Settings.strings index 8acf72b407..b496c99082 100644 --- a/MC1/Resources/Localization/fr.lproj/Settings.strings +++ b/MC1/Resources/Localization/fr.lproj/Settings.strings @@ -46,9 +46,6 @@ /* Section header for device information */ "device.header" = "Appareil"; -/* Status shown when device is connected */ -"device.connected" = "Connecté"; - /* Footer shown when no device is connected */ "device.noDeviceConnected" = "Aucun appareil MeshCore connecté"; @@ -60,12 +57,6 @@ /* Navigation title for device info screen */ "deviceInfo.title" = "Infos de l'appareil"; -/* Section header for connection status */ -"deviceInfo.connection.header" = "Connexion"; - -/* Label for connection status */ -"deviceInfo.connection.status" = "Statut"; - /* Section header for power and storage */ "deviceInfo.powerStorage.header" = "Batterie et stockage"; @@ -111,6 +102,12 @@ /* Firmware version fallback format when no version string is reported - %@ is the numeric version code */ "deviceInfo.firmwareVersionFormat" = "v%@"; +/* Heading above retained telemetry after a Device Info reload fails */ +"deviceInfo.lastSuccessfulReading" = "Dernière mesure réussie"; + +/* Section header for Device Info telemetry */ +"deviceInfo.telemetry.header" = "Télémétrie du nœud"; + /* Section header for identity information */ /* Label for public key */ "deviceInfo.publicKey" = "Clé publique"; @@ -165,6 +162,9 @@ /* Button to scan for Bluetooth devices */ "deviceSelection.scanBluetooth" = "Rechercher un appareil Bluetooth"; +/* Button title while this radio is being paired again */ +"deviceSelection.rePairing" = "Nouveau jumelage..."; + /* Trailing control on a previously paired row that still needs iPhone setup */ /* AI-translated - please verify with native speakers. */ "deviceSelection.setup" = "Configurer"; @@ -746,6 +746,21 @@ /* Alert message for clear logs */ "diagnostics.alert.clear.message" = "Cela supprimera tous les journaux de débogage stockés. Les fichiers de journaux exportés ne seront pas affectés."; +/* Toggle to enable collecting local debug logs */ +"diagnostics.collectLogs" = "Collecter les journaux de débogage"; + +/* Footer shown when debug log collection is off */ +"diagnostics.footer.disabled" = "Les journaux de débogage locaux ne sont pas collectés."; + +/* Alert title for disabling collection */ +"diagnostics.alert.disable.title" = "Désactiver la collecte"; + +/* Button to confirm disabling collection */ +"diagnostics.alert.disable.confirm" = "Désactiver la collecte"; + +/* Alert message for disabling collection */ +"diagnostics.alert.disable.message" = "Cela supprimera tous les journaux de débogage stockés et arrêtera leur collecte. Les fichiers de journaux exportés ne seront pas affectés."; + /* Error when export fails */ "diagnostics.error.exportFailed" = "Échec de la création du fichier d'exportation"; @@ -754,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Discussions"; +"blocksAndFilters.title" = "Blocage et filtres"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -822,6 +839,8 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Compagnon"; +"notifications.discoveryCompanionsAndSensors" = "Compagnons & Capteurs"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Répéteur"; @@ -983,6 +1002,9 @@ /* Editor footer when the password is too long */ "radioWiFi.editor.passwordLength" = "Un mot de passe peut contenir jusqu'à 63 octets."; +/* Editor footer when a credential contains a character the firmware cannot store */ +"radioWiFi.editor.unsupportedCharacter" = "Le nom du réseau ou le mot de passe contient un caractère que cette radio ne peut pas enregistrer."; + /* Button that clears the radio's saved WiFi settings */ "radioWiFi.clear" = "Effacer les réglages WiFi"; @@ -1148,6 +1170,35 @@ /* Footer explaining the acknowledgments setting */ "directMessages.footer" = "Nombre d'accusés de réception envoyés par message direct. Utilisez 2 pour une meilleure confirmation de livraison sur les liaisons peu fiables."; +/* Switch that clears the known route after the path attempts */ +"directMessages.fallback" = "Repli vers Flood"; + +/* Picker label for attempts on the known route */ +"directMessages.directAttempts" = "Tentatives sur le chemin"; + +/* Picker label for attempts sent by flood after the route is cleared */ +"directMessages.floodAttempts" = "Tentatives Flood"; + +/* Footer when Fall Back to Flood is on */ +"directMessages.attemptsFooterOn" = "Le chemin est effacé après les Tentatives sur le chemin. Les Tentatives Flood sont ensuite envoyées en routage flood. Un message à un contact sans chemin connu est envoyé en routage flood."; + +/* Footer when Fall Back to Flood is off */ +"directMessages.attemptsFooterOff" = "Les Tentatives sur le chemin restent sur le chemin connu, et le chemin reste en place. Un message à un contact sans chemin connu est envoyé en routage flood."; + +// MARK: - Path Fallback + +/* Section header for sign-in, command, and contact telemetry path fallback */ +"pathFallback.header" = "Repli du chemin"; + +/* Switch that clears the known route after a timeout */ +"pathFallback.fallback" = "Repli vers Flood"; + +/* Footer when path fallback is on */ +"pathFallback.footerOn" = "La connexion, les commandes de répéteur et de salon qui attendent une réponse, et la télémétrie du contact utilisent le chemin connu. S'il n'y a aucune réponse, le chemin est effacé et une seule tentative est envoyée en routage flood."; + +/* Footer when path fallback is off */ +"pathFallback.footerOff" = "La connexion, les commandes et la télémétrie du contact restent sur le chemin connu. S'il n'y a aucune réponse, elles s'arrêtent et le chemin reste en place. L'option Routage Flood, sur l'écran de connexion, efface le chemin enregistré de ce nœud."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ @@ -1162,12 +1213,24 @@ /* Menu item to disconnect from the current device */ "bleStatus.disconnect" = "Déconnecter"; +/* Menu item to stop automatic reconnection until another explicit connection */ +"bleStatus.stopReconnecting" = "Arrêter la reconnexion"; + +/* Menu item to cancel the current connection request */ +"bleStatus.cancelConnection" = "Annuler la connexion"; + /* Status shown when device is disconnected */ "bleStatus.status.disconnected" = "Déconnecté"; /* Status shown when device is connecting */ "bleStatus.status.connecting" = "Connexion..."; +/* Status shown while reconnecting to the selected device */ +"bleStatus.status.reconnecting" = "Reconnexion..."; + +/* Status shown while automatic reconnection remains enabled between attempts */ +"bleStatus.status.waitingToReconnect" = "En attente de reconnexion"; + /* Status shown when device is connected but not ready */ "bleStatus.status.connected" = "Connecté"; @@ -1180,6 +1243,9 @@ /* Accessibility label for BLE status indicator */ "bleStatus.accessibilityLabel" = "État de la connexion Bluetooth"; +/* TODO: translate - Accessibility text combining a descriptive prefix and connection state or context; arguments may themselves contain a radio name and status */ +"bleStatus.accessibilityValue" = "%1$@, %2$@"; + /* Accessibility hint when disconnected */ "bleStatus.accessibilityHint.disconnected" = "Touchez deux fois pour connecter l'appareil"; @@ -1318,6 +1384,24 @@ /* Import failed after one or more settings were already written; %@ is the underlying error message */ "configImport.failedPartial" = "%@ Certains paramètres ont peut-être déjà été écrits sur l'appareil. Vérifiez la configuration de l'appareil."; +/* Interrupted identity import recovery */ +"configImport.identityOutcomeUnknown" = "La connexion a été interrompue pendant l'importation de l'identité sur %@. La radio a peut-être changé d'identité. L'importation de la configuration n'a pas été terminée."; + +/* Interrupted identity import recovery */ +"configImport.retryIdentityImport" = "Réessayer l'importation de l'identité"; + +/* Interrupted identity import recovery */ +"configImport.confirmIdentityRecovery" = "Ceci remplacera l'identité de la radio atteinte à %@ à l'aide de la clé privée du fichier sélectionné. L'importation de la configuration ne se poursuivra pas."; + +/* Confirmation alert title when retrying an interrupted identity import */ +"configImport.confirmTitleIdentityRecovery" = "Remplacer l'identité de la radio ?"; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryComplete" = "L'identité a été réappliquée. L'importation de la configuration n'a pas été terminée. Importez à nouveau le fichier pour appliquer ses autres paramètres."; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryKeyRequired" = "Sélectionnez un fichier de configuration contenant la clé privée pour réessayer l'importation de l'identité."; + /* Import success */ "configImport.importSuccess" = "Configuration importée avec succès"; @@ -1434,6 +1518,63 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "L'affichage des vignettes de carte télécharge les tuiles pour la coordonnée depuis un serveur tiers, ce qui peut révéler votre adresse IP."; +// MARK: - Text Rules + +"textRules.rules" = "Règles de filtrage"; +"textRules.empty" = "Aucune règle de filtrage"; +"textRules.loading" = "Chargement des règles de filtrage…"; +"textRules.loadFailed" = "Impossible de charger les règles de filtrage. Les nouveaux messages ne les utiliseront pas jusqu’à ce qu’elles puissent être chargées."; +"textRules.retryAccessibility" = "Réessayer de charger les règles de filtrage"; +"textRules.saveFailed" = "Impossible d’enregistrer les règles de filtrage. Réessayez."; +"textRules.new.title" = "Nouvelle règle"; +"textRules.new.phrase" = "Mot ou texte"; +"textRules.new.lookIn" = "Chercher dans"; +"textRules.new.match" = "Correspondance"; +"textRules.new.containsMessageFooter" = "Ce texte correspond s’il figure n’importe où dans le message, y compris à l’intérieur d’un mot."; +"textRules.new.wholeMessageFooter" = "Ce texte ne correspond que si le message entier est ce texte."; +"textRules.new.containsSenderFooter" = "Ce texte correspond s’il figure n’importe où dans le nom de l’expéditeur, y compris à l’intérieur d’un mot. Les réactions de cet expéditeur sont aussi masquées."; +"textRules.new.wholeNameFooter" = "Ce texte ne correspond que si le nom de l’expéditeur est exactement ce texte. Les réactions de cet expéditeur sont aussi masquées."; +"textRules.new.containsMessageOrSenderFooter" = "Ce texte correspond s’il figure n’importe où dans le message ou n’importe où dans le nom de l’expéditeur, y compris à l’intérieur d’un mot. Les réactions d’un expéditeur dont le nom correspond sont aussi masquées."; +"textRules.new.wholeMessageOrSenderFooter" = "Ce texte ne correspond que si le message entier ou le nom entier de l’expéditeur est ce texte. Les réactions d’un expéditeur dont le nom correspond sont aussi masquées."; +"textRules.field.message" = "Message"; +"textRules.field.sender" = "Expéditeur"; +"textRules.field.messageOrSender" = "Message ou expéditeur"; +"textRules.match.contains" = "Contient"; +"textRules.match.wholeMessage" = "Message entier"; +"textRules.match.wholeName" = "Nom entier"; +"textRules.match.wholeField" = "Champ entier"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Utiliser les règles pour"; +"textRules.types.footer" = "Si cette option est activée, toutes les discussions de ce type sont incluses, y compris celles que vous rejoignez plus tard."; +"textRules.types.publicChannel" = "Public"; +"textRules.types.hashtagChannel" = "Canaux hashtag"; +"textRules.types.privateChannel" = "Canaux privés"; +"textRules.selection.all" = "Tous"; +"textRules.selection.none" = "Aucun"; +"textRules.selection.count" = "%d Messages"; +"textRules.selection.accessibilityChats" = "Messages pour %@"; +"textRules.selection.footer" = "Tous incluent les discussions que vous rejoignez plus tard."; +"textRules.archive.title" = "Masqués récemment"; +"textRules.archive.empty" = "Aucun message masqué"; +"textRules.archive.footer" = "Les %d derniers messages masqués sont conservés sur cet appareil. Ils ne sont pas inclus dans les sauvegardes des données de l’app."; +"textRules.archive.labelPrefix" = "%@ : "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; +"textRules.archive.rule" = "Règle"; +"textRules.archive.chat" = "Discussion"; +"textRules.archive.myNode" = "Mon nœud"; +"textRules.archive.time" = "Heure"; +"textRules.archive.unknownConversation" = "Conversation inconnue"; +"textRules.archive.unknownRadio" = "Radio inconnue"; + +"radioCleanup.title" = "Nettoyage"; +"radioCleanup.running" = "Suppression des données de la radio"; +"radioCleanup.failed" = "Les messages masqués de cette radio peuvent encore se trouver sur cette installation."; +"radioCleanup.completed" = "Données de la radio supprimées"; +"radioCleanup.retryAccessibility" = "Réessayer le nettoyage de la radio pour %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ @@ -1978,7 +2119,7 @@ "settings.backup.export.alert.title" = "Avis de sécurité"; /* Export confirmation alert message */ -"settings.backup.export.alert.message" = "Cette sauvegarde inclut les clés de chiffrement des canaux, l'historique des messages, votre liste de contacts ainsi que l'adresse réseau locale et le port du nœud WiFi. Conservez le fichier exporté en lieu sûr."; +"settings.backup.export.alert.message" = "Cette sauvegarde inclut les clés de chiffrement des canaux, l'historique des messages, votre liste de contacts ainsi que l'adresse réseau locale et le port du nœud WiFi. La sauvegarde peut également inclure des coordonnées GPS relevées sur les radios. Conservez le fichier exporté en lieu sûr."; /* Export confirmation alert export button */ "settings.backup.export.alert.export" = "Exporter"; diff --git a/MC1/Resources/Localization/fr.lproj/WhatsNew.strings b/MC1/Resources/Localization/fr.lproj/WhatsNew.strings index d30640a2c9..b17af76c4f 100644 --- a/MC1/Resources/Localization/fr.lproj/WhatsNew.strings +++ b/MC1/Resources/Localization/fr.lproj/WhatsNew.strings @@ -65,3 +65,23 @@ "whatsNew.moreChanges.title" = "Plus de changements"; /* What's New v1.6 - More changes, description */ "whatsNew.moreChanges.description" = "Appuyez sur \"Voir tous les nouveaux changements\" ci-dessous pour voir la liste complète des corrections de bogues et d'autres fonctionnalités."; + +/* What's New v1.7 - Direct messages, title */ +"whatsNew.directMessages.title" = "Messages directs"; +/* What's New v1.7 - Direct messages, description */ +"whatsNew.directMessages.description" = "Les messages directs tentent maintenant le chemin 4 fois, puis Flood 4 fois. Modifiez Tentatives sur le chemin, Tentatives Flood et Repli vers Flood dans Réglages avancés."; + +/* What's New v1.7 - Blocks and filters, title */ +"whatsNew.blocksAndFilters.title" = "Blocage et filtres"; +/* What's New v1.7 - Blocks and filters, description */ +"whatsNew.blocksAndFilters.description" = "Masquez les messages qui correspondent à un mot ou un texte. Une règle peut chercher dans le Message, l'Expéditeur ou les deux, et vous choisissez les discussions auxquelles elle s'applique. Les messages masqués sont visibles dans Masqués récemment, sous Réglages > Blocage et filtres."; + +/* What's New v1.7 - Node telemetry, title */ +"whatsNew.nodeTelemetry.title" = "Télémétrie du nœud"; +/* What's New v1.7 - Node telemetry, description */ +"whatsNew.nodeTelemetry.description" = "Réglages > Infos de l'appareil affiche la télémétrie du nœud auquel vous êtes connecté."; + +/* What's New v1.7 - Live Activity, title */ +"whatsNew.liveActivity.title" = "Activité en direct"; +/* What's New v1.7 - Live Activity, description */ +"whatsNew.liveActivity.description" = "Les messages non lus sont plus en évidence et le taux de paquets par minute est plus facile à comprendre."; diff --git a/MC1/Resources/Localization/it.lproj/Chats.strings b/MC1/Resources/Localization/it.lproj/Chats.strings index f1733ab33c..0e2d265262 100644 --- a/MC1/Resources/Localization/it.lproj/Chats.strings +++ b/MC1/Resources/Localization/it.lproj/Chats.strings @@ -338,8 +338,8 @@ /* Location: MutedIndicator.swift - Accessibility label for mentions-only indicator */ "chats.row.mentionsOnly" = "Solo menzioni"; -/* TODO: translate - Accessibility label for the row actions menu */ -"chats.row.actionsMenu.accessibilityLabel" = "Conversation actions"; +/* Accessibility label for the row actions menu */ +"chats.row.actionsMenu.accessibilityLabel" = "Azioni della conversazione"; // MARK: - Notification Level Picker @@ -620,6 +620,12 @@ /* Location: UnifiedMessageBubble.swift - VoiceOver prefix when the visible body is a translation - %@ is the translated text */ "chats.message.translatedAccessibility" = "Tradotto: %@"; +/* Location: MessageVisibleBody.swift - VoiceOver prefix when the visible body is an MECP reading - %@ is the reading */ +"chats.message.readingAccessibility" = "Lettura: %@"; + +/* Location: MECPCatalog - Person count line in an MECP reading */ +"chats.message.mecpPersonCount" = "%lld persone"; + /* Location: UnifiedMessageBubble.swift - Context menu action to view repeat details */ "chats.message.action.repeatDetails" = "Dettagli ripetizioni"; @@ -673,6 +679,9 @@ /* Location: UnifiedMessageBubble.swift - Context menu text showing SNR - %@ is formatted value */ "chats.message.info.snr" = "SNR: %@"; +/* Location: ActionsDetailsSection.swift - Stored MECP wire string under SNR. %@ is the original text */ +"chats.message.info.mecp" = "MECP: %@"; + /* Location: MessageActionsSheet.swift - Details row showing the radio region a flood-routed message was broadcast under - %@ is region name */ "chats.message.info.floodedUnder" = "Region: %@"; diff --git a/MC1/Resources/Localization/it.lproj/Chats.stringsdict b/MC1/Resources/Localization/it.lproj/Chats.stringsdict new file mode 100644 index 0000000000..0bfbe608ea --- /dev/null +++ b/MC1/Resources/Localization/it.lproj/Chats.stringsdict @@ -0,0 +1,22 @@ + + + + + chats.message.mecpPersonCount + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + lld + one + %lld persona + other + %lld persone + + + + diff --git a/MC1/Resources/Localization/it.lproj/Contacts.strings b/MC1/Resources/Localization/it.lproj/Contacts.strings index eb4480ea76..ee7bee946d 100644 --- a/MC1/Resources/Localization/it.lproj/Contacts.strings +++ b/MC1/Resources/Localization/it.lproj/Contacts.strings @@ -44,6 +44,8 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Stanza"; +"contacts.nodeKind.sensor" = "Sensore"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Scoperto"; @@ -75,6 +77,8 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Stanze"; +"contacts.segment.sensors" = "Sensori"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "Filtra nodi"; @@ -168,9 +172,13 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "Non ci sono stanze"; +"contacts.list.empty.sensors.title" = "Nessun sensore"; + /* Location: ContactsListView.swift - Purpose: No rooms empty description */ "contacts.list.empty.rooms.description" = "Le stanze sono server di chat pubblici sulla mesh. Compariranno qui quando verranno scoperte."; +"contacts.list.empty.sensors.description" = "I sensori compariranno qui quando verranno scoperti sulla mesh."; + /* Location: ContactsListView.swift - Purpose: No search results title */ "contacts.list.empty.search.title" = "Nessun risultato"; @@ -623,6 +631,8 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter: Rooms */ "contacts.discovery.segment.rooms" = "Stanze"; +"contacts.discovery.segment.sensors" = "Sensori"; + /* Location: DiscoverSegmentPicker.swift - Purpose: VoiceOver label for the Discovery segment filter picker (iOS 18 fallback) */ "contacts.discovery.segment.pickerLabel" = "Filtra nodi scoperti"; diff --git a/MC1/Resources/Localization/it.lproj/Localizable.strings b/MC1/Resources/Localization/it.lproj/Localizable.strings index e3dae28800..4fc094da5d 100644 --- a/MC1/Resources/Localization/it.lproj/Localizable.strings +++ b/MC1/Resources/Localization/it.lproj/Localizable.strings @@ -150,6 +150,8 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "Nuova stanza scoperta"; +"notifications.discovery.sensor" = "Nuovo sensore scoperto"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -495,6 +497,14 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Risposta non valida dal nodo remoto"; +"error.remoteNode.sensorOutcomeUnknown" = "Impossibile verificare la modifica. Ricarica le impostazioni prima di salvare di nuovo."; + +"error.remoteNode.sensorSettingRejected" = "Il sensore ha rifiutato questa impostazione."; + +"error.remoteNode.invalidSensorSetting" = "Usa una chiave e un valore non vuoti e senza spazi bianchi. Il comando completo deve stare entro 160 byte UTF-8."; + +"error.remoteNode.invalidPasswordLength" = "Le password devono usare al massimo %d byte UTF-8."; + /* Location: RemoteNodeError+UserFacingMessage.swift - Remote node rejected the operation */ "error.remoteNode.permissionDenied" = "Permesso negato"; diff --git a/MC1/Resources/Localization/it.lproj/Map.strings b/MC1/Resources/Localization/it.lproj/Map.strings index e4acab08b2..35f2722f85 100644 --- a/MC1/Resources/Localization/it.lproj/Map.strings +++ b/MC1/Resources/Localization/it.lproj/Map.strings @@ -37,6 +37,8 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Filtra"; +"map.controls.contactsAndSensors" = "Contatti e sensori"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Filtri attivi"; @@ -261,6 +263,8 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Stanza"; +"map.nodeKind.sensor" = "Sensore"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -278,6 +282,8 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Stanza"; +"map.callout.nodeKind.sensor" = "Sensore"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "Aggiungi"; diff --git a/MC1/Resources/Localization/it.lproj/Onboarding.strings b/MC1/Resources/Localization/it.lproj/Onboarding.strings index 8716e23aa0..eaad01e04e 100644 --- a/MC1/Resources/Localization/it.lproj/Onboarding.strings +++ b/MC1/Resources/Localization/it.lproj/Onboarding.strings @@ -69,6 +69,9 @@ /* Location: DeviceScanView.swift - Subtitle with pairing instructions */ "deviceScan.subtitle" = "Accendi la radio, scollegala da tutte le altre app e dispositivi, poi tocca Aggiungi dispositivo."; +/* Location: DeviceScanView.swift - Subtitle while bond-loss recovery is re-pairing */ +"deviceScan.rePairingSubtitle" = "Accendi la radio e scollegala da tutte le altre app e dispositivi."; + /* Location: DeviceScanView.swift - Message shown when device is already paired */ "deviceScan.alreadyPaired" = "Il tuo dispositivo è già associato"; @@ -78,9 +81,6 @@ /* Location: DeviceScanView.swift - Button to continue after pairing */ "deviceScan.continue" = "Continua"; -/* Location: DeviceScanView.swift - Button label while connecting */ -"deviceScan.connecting" = "Connessione..."; - /* Location: DeviceScanView.swift - Button to connect simulator (debug) */ "deviceScan.connectSimulator" = "Connetti simulatore"; diff --git a/MC1/Resources/Localization/it.lproj/RemoteNodes.strings b/MC1/Resources/Localization/it.lproj/RemoteNodes.strings index 029c601f4b..0df9a94fe1 100644 --- a/MC1/Resources/Localization/it.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/it.lproj/RemoteNodes.strings @@ -32,6 +32,8 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Ripetitore"; +"remoteNodes.auth.typeSensor" = "Sensore"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Autenticazione"; @@ -62,10 +64,18 @@ /* Location: NodeAuthenticationSheet.swift - Flood routing toggle */ "remoteNodes.auth.floodRouting" = "Routing flood"; "remoteNodes.auth.floodRetryStatus" = "Nessuna risposta sul percorso noto. Nuovo tentativo con routing flood."; -"remoteNodes.auth.floodFooter" = "Il routing flood è più lento e consuma più tempo in aria sulla rete. Usalo quando il percorso noto non funziona dalla tua posizione attuale. Dopo l'accesso viene appreso automaticamente un nuovo percorso."; +/* Footer when this sign-in will clear the saved route and use flood */ +"remoteNodes.auth.floodFooter" = "Questo accesso cancella il percorso salvato e usa il routing flood. Il routing flood è più lento e consuma più tempo in aria sulla rete. Un nuovo percorso viene appreso solo se l'accesso riesce."; + +/* Footer after this sign-in has cleared the saved route */ +"remoteNodes.auth.floodFooterCleared" = "Il percorso salvato è stato cancellato. L'accesso sta usando il routing flood. Un nuovo percorso viene appreso solo se l'accesso riesce."; + + +/* Footer when a timeout clears the route and retries by flood */ +"remoteNodes.auth.pathFooter" = "Se non c'è risposta, il percorso viene cancellato e l'accesso fa un solo tentativo con routing flood."; -/* Location: NodeAuthenticationSheet.swift - Path section footer when stored path exists */ -"remoteNodes.auth.pathFooter" = "Usa il percorso noto verso questo nodo, oppure attiva il routing flood per far trovare un percorso alla rete."; +/* Footer when a timeout stops and leaves the route */ +"remoteNodes.auth.pathFooterKept" = "Se non c'è risposta, l'accesso si ferma e il percorso resta."; /* Location: NodeAuthenticationSheet.swift - Path hop whose repeater is not known */ "remoteNodes.auth.pathHopUnknown" = ""; @@ -84,6 +94,26 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Impostazioni ripetitore"; +"remoteNodes.sensor.adminRequired" = "La gestione del sensore richiede l'accesso amministratore."; + +"remoteNodes.sensor.saved" = "Impostazione verificata."; + +"remoteNodes.sensor.rebootSent" = "Richiesta di riavvio inviata. Il sensore non ha confermato il riavvio. Accedi di nuovo prima di inviare altri comandi."; + +"remoteNodes.sensor.rebootConfirmation" = "Inviare una richiesta di riavvio a questo sensore?"; + +"remoteNodes.sensor.runtimeOnly" = "Le modifiche hanno effetto sul sensore in esecuzione. Se restano dopo il riavvio dipende dal suo firmware."; + +"remoteNodes.sensor.value" = "Valore"; + +"remoteNodes.sensor.save" = "Salva"; + +"remoteNodes.sensor.reload" = "Ricarica"; + +"remoteNodes.sensor.empty" = "Questo sensore non espone impostazioni."; + +"remoteNodes.sensor.title" = "Gestione sensore"; + /* Location: RepeaterSettingsView.swift - Done button (used in multiple places) */ "remoteNodes.settings.done" = "Fine"; diff --git a/MC1/Resources/Localization/it.lproj/Settings.strings b/MC1/Resources/Localization/it.lproj/Settings.strings index 0d08844501..241af1c628 100644 --- a/MC1/Resources/Localization/it.lproj/Settings.strings +++ b/MC1/Resources/Localization/it.lproj/Settings.strings @@ -46,9 +46,6 @@ /* Section header for device information */ "device.header" = "Dispositivo"; -/* Status shown when device is connected */ -"device.connected" = "Connesso"; - /* Footer shown when no device is connected */ "device.noDeviceConnected" = "Nessun dispositivo MeshCore connesso"; @@ -60,12 +57,6 @@ /* Navigation title for device info screen */ "deviceInfo.title" = "Info dispositivo"; -/* Section header for connection status */ -"deviceInfo.connection.header" = "Connessione"; - -/* Label for connection status */ -"deviceInfo.connection.status" = "Stato"; - /* Section header for power and storage */ "deviceInfo.powerStorage.header" = "Alimentazione e archiviazione"; @@ -111,6 +102,12 @@ /* Firmware version fallback format when no version string is reported - %@ is the numeric version code */ "deviceInfo.firmwareVersionFormat" = "v%@"; +/* Heading above retained telemetry after a Device Info reload fails */ +"deviceInfo.lastSuccessfulReading" = "Ultima lettura riuscita"; + +/* Section header for Device Info telemetry */ +"deviceInfo.telemetry.header" = "Telemetria del nodo"; + /* Section header for identity information */ /* Label for public key */ "deviceInfo.publicKey" = "Chiave pubblica"; @@ -165,6 +162,9 @@ /* Button to scan for Bluetooth devices */ "deviceSelection.scanBluetooth" = "Cerca dispositivo Bluetooth"; +/* Button title while this radio is being paired again */ +"deviceSelection.rePairing" = "Riassociazione…"; + /* Trailing control on a previously paired row that still needs iPhone setup */ /* AI-translated - please verify with native speakers. */ "deviceSelection.setup" = "Configura"; @@ -745,6 +745,21 @@ /* Alert message for clear logs */ "diagnostics.alert.clear.message" = "Questo eliminerà tutti i log di debug archiviati. I file di log già esportati non saranno interessati."; +/* Toggle to enable collecting local debug logs */ +"diagnostics.collectLogs" = "Raccogli log di debug"; + +/* Footer shown when debug log collection is off */ +"diagnostics.footer.disabled" = "I log di debug locali non vengono raccolti."; + +/* Alert title for disabling collection */ +"diagnostics.alert.disable.title" = "Disattiva raccolta"; + +/* Button to confirm disabling collection */ +"diagnostics.alert.disable.confirm" = "Disattiva raccolta"; + +/* Alert message for disabling collection */ +"diagnostics.alert.disable.message" = "Questo eliminerà tutti i log di debug archiviati e ne interromperà la raccolta. I file di log già esportati non saranno interessati."; + /* Error when export fails */ "diagnostics.error.exportFailed" = "Impossibile creare il file di esportazione"; @@ -753,6 +768,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Chat"; +"blocksAndFilters.title" = "Blocco e filtri"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -872,6 +889,8 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Companion"; +"notifications.discoveryCompanionsAndSensors" = "Companion e sensori"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Ripetitore"; @@ -1033,6 +1052,9 @@ /* Editor footer when the password is too long */ "radioWiFi.editor.passwordLength" = "La password può avere al massimo 63 byte."; +/* Editor footer when a credential contains a character the firmware cannot store */ +"radioWiFi.editor.unsupportedCharacter" = "Il nome della rete o la password contiene un carattere che questa radio non può memorizzare."; + /* Button that clears the radio's saved WiFi settings */ "radioWiFi.clear" = "Cancella impostazioni Wi‑Fi"; @@ -1198,6 +1220,35 @@ /* Footer explaining the acknowledgments setting */ "directMessages.footer" = "Numero di conferme inviate per messaggio diretto. Usa 2 per una conferma di consegna migliore su collegamenti inaffidabili."; +/* Switch that clears the known route after the path attempts */ +"directMessages.fallback" = "Ripiego sul routing flood"; + +/* Picker label for attempts on the known route */ +"directMessages.directAttempts" = "Tentativi sul percorso"; + +/* Picker label for attempts sent by flood after the route is cleared */ +"directMessages.floodAttempts" = "Tentativi con routing flood"; + +/* Footer when Fall Back to Flood is on */ +"directMessages.attemptsFooterOn" = "Il percorso viene cancellato dopo i Tentativi sul percorso. I Tentativi con routing flood vengono poi inviati con routing flood. Un messaggio a un contatto senza un percorso noto viene inviato con routing flood."; + +/* Footer when Fall Back to Flood is off */ +"directMessages.attemptsFooterOff" = "I Tentativi sul percorso restano sul percorso noto e il percorso resta. Un messaggio a un contatto senza un percorso noto viene inviato con routing flood."; + +// MARK: - Path Fallback + +/* Section header for sign-in, command, and contact telemetry path fallback */ +"pathFallback.header" = "Ripiego del percorso"; + +/* Switch that clears the known route after a timeout */ +"pathFallback.fallback" = "Ripiego sul routing flood"; + +/* Footer when path fallback is on */ +"pathFallback.footerOn" = "L’accesso, i comandi di ripetitore e di stanza in attesa di una risposta, e la telemetria del contatto usano il percorso noto. Se non c’è risposta, il percorso viene cancellato e si fa un solo tentativo con routing flood."; + +/* Footer when path fallback is off */ +"pathFallback.footerOff" = "L’accesso, i comandi e la telemetria del contatto restano sul percorso noto. Se non c’è risposta, si fermano e il percorso resta. Nella schermata di accesso, Routing flood cancella il percorso salvato di quel nodo."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ @@ -1212,12 +1263,24 @@ /* Menu item to disconnect from the current device */ "bleStatus.disconnect" = "Disconnetti"; +/* Menu item to stop automatic reconnection until another explicit connection */ +"bleStatus.stopReconnecting" = "Interrompi riconnessione"; + +/* Menu item to cancel the current connection request */ +"bleStatus.cancelConnection" = "Annulla connessione"; + /* Status shown when device is disconnected */ "bleStatus.status.disconnected" = "Disconnesso"; /* Status shown when device is connecting */ "bleStatus.status.connecting" = "Connessione…"; +/* Status shown while reconnecting to the selected device */ +"bleStatus.status.reconnecting" = "Riconnessione…"; + +/* Status shown while automatic reconnection remains enabled between attempts */ +"bleStatus.status.waitingToReconnect" = "In attesa di riconnessione"; + /* Status shown when device is connected but not ready */ "bleStatus.status.connected" = "Connesso"; @@ -1230,6 +1293,9 @@ /* Accessibility label for BLE status indicator */ "bleStatus.accessibilityLabel" = "Stato connessione Bluetooth"; +/* TODO: translate - Accessibility text combining a descriptive prefix and connection state or context; arguments may themselves contain a radio name and status */ +"bleStatus.accessibilityValue" = "%1$@, %2$@"; + /* Accessibility hint when disconnected */ "bleStatus.accessibilityHint.disconnected" = "Tocca due volte per connettere il dispositivo"; @@ -1333,6 +1399,24 @@ /* Import failed after one or more settings were already written; %@ is the underlying error message */ "configImport.failedPartial" = "%@ Alcune impostazioni potrebbero essere già state scritte sul dispositivo. Controlla la configurazione del dispositivo."; +/* Interrupted identity import recovery */ +"configImport.identityOutcomeUnknown" = "La connessione è stata interrotta durante l’importazione dell’identità su %@. La radio potrebbe aver cambiato identità. L’importazione della configurazione non è stata completata."; + +/* Interrupted identity import recovery */ +"configImport.retryIdentityImport" = "Riprova a importare l’identità"; + +/* Interrupted identity import recovery */ +"configImport.confirmIdentityRecovery" = "Questa operazione sostituirà l’identità della radio raggiungibile tramite %@ usando la chiave privata nel file selezionato. L’importazione della configurazione non continuerà."; + +/* Confirmation alert title when retrying an interrupted identity import */ +"configImport.confirmTitleIdentityRecovery" = "Sostituire l’identità della radio?"; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryComplete" = "L’identità è stata riapplicata. L’importazione della configurazione non è stata completata. Importa di nuovo il file per applicare le altre impostazioni."; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryKeyRequired" = "Seleziona un file di configurazione contenente la chiave privata per riprovare a importare l’identità."; + /* Import success */ "configImport.importSuccess" = "Configurazione importata correttamente"; @@ -1432,6 +1516,63 @@ /* Validation error: no empty channel slot left (param: channel name) */ "configImport.error.noAvailableChannelSlot" = "Nessuno slot canale libero disponibile per “%@”"; +// MARK: - Text Rules + +"textRules.rules" = "Regole di filtro"; +"textRules.empty" = "Nessuna regola di filtro"; +"textRules.loading" = "Caricamento delle regole di filtro…"; +"textRules.loadFailed" = "Impossibile caricare le regole di filtro. I nuovi messaggi non useranno le regole di filtro finché non sarà possibile caricarle."; +"textRules.retryAccessibility" = "Riprova a caricare le regole di filtro"; +"textRules.saveFailed" = "Impossibile salvare le regole di filtro. Riprova."; +"textRules.new.title" = "Nuova regola"; +"textRules.new.phrase" = "Parola o frase"; +"textRules.new.lookIn" = "Cerca in"; +"textRules.new.match" = "Corrispondenza"; +"textRules.new.containsMessageFooter" = "Corrisponde in qualsiasi punto del messaggio, anche all’interno di una parola."; +"textRules.new.wholeMessageFooter" = "Corrisponde solo quando l’intero messaggio è questa frase."; +"textRules.new.containsSenderFooter" = "Corrisponde in qualsiasi punto del nome del mittente, anche all’interno di una parola. Anche le reazioni di quel mittente vengono nascoste."; +"textRules.new.wholeNameFooter" = "Corrisponde solo quando il nome del mittente è esattamente questo. Anche le reazioni di quel mittente vengono nascoste."; +"textRules.new.containsMessageOrSenderFooter" = "Corrisponde in qualsiasi punto del messaggio o del nome del mittente, anche all’interno di una parola. Anche le reazioni di un mittente che corrisponde vengono nascoste."; +"textRules.new.wholeMessageOrSenderFooter" = "Corrisponde solo quando l’intero messaggio o l’intero nome del mittente è questa frase. Anche le reazioni di un mittente che corrisponde vengono nascoste."; +"textRules.field.message" = "Messaggio"; +"textRules.field.sender" = "Mittente"; +"textRules.field.messageOrSender" = "Messaggio o mittente"; +"textRules.match.contains" = "Contiene"; +"textRules.match.wholeMessage" = "Intero messaggio"; +"textRules.match.wholeName" = "Intero nome"; +"textRules.match.wholeField" = "Intero campo"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Usa le regole di filtro per"; +"textRules.types.footer" = "Se attivo, include tutte le chat di quel tipo, anche quelle a cui ti unisci in seguito."; +"textRules.types.publicChannel" = "Pubblico"; +"textRules.types.hashtagChannel" = "Canali hashtag"; +"textRules.types.privateChannel" = "Canali privati"; +"textRules.selection.all" = "Tutti"; +"textRules.selection.none" = "Nessuno"; +"textRules.selection.count" = "%d Chat"; +"textRules.selection.accessibilityChats" = "Chat per %@"; +"textRules.selection.footer" = "“Tutti” include le chat a cui ti unisci in seguito."; +"textRules.archive.title" = "Bloccati di recente"; +"textRules.archive.empty" = "Nessun messaggio nascosto"; +"textRules.archive.footer" = "Gli ultimi %d messaggi nascosti sono conservati su questo dispositivo. Non sono inclusi nei backup dell’app."; +"textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; +"textRules.archive.rule" = "Regola"; +"textRules.archive.chat" = "Chat"; +"textRules.archive.myNode" = "Il mio nodo"; +"textRules.archive.time" = "Ora"; +"textRules.archive.unknownConversation" = "Conversazione sconosciuta"; +"textRules.archive.unknownRadio" = "Radio sconosciuta"; + +"radioCleanup.title" = "Pulizia"; +"radioCleanup.running" = "Rimozione dei dati della radio"; +"radioCleanup.failed" = "I messaggi nascosti di questa radio potrebbero essere ancora in questa installazione."; +"radioCleanup.completed" = "Dati della radio rimossi"; +"radioCleanup.retryAccessibility" = "Riprova la pulizia della radio per %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ @@ -1976,7 +2117,7 @@ "settings.backup.export.alert.title" = "Avviso di sicurezza"; /* Export confirmation alert message */ -"settings.backup.export.alert.message" = "Questo backup include le chiavi di cifratura dei canali, la cronologia dei messaggi, l’elenco contatti e l’indirizzo di rete locale e la porta del nodo Wi‑Fi. Conserva il file esportato in modo sicuro."; +"settings.backup.export.alert.message" = "Questo backup include le chiavi di cifratura dei canali, la cronologia dei messaggi, l’elenco contatti e l’indirizzo di rete locale e la porta del nodo Wi‑Fi. Il backup può includere anche le coordinate GPS rilevate dalle radio. Conserva il file esportato in modo sicuro."; /* Export confirmation alert export button */ "settings.backup.export.alert.export" = "Esporta"; diff --git a/MC1/Resources/Localization/it.lproj/WhatsNew.strings b/MC1/Resources/Localization/it.lproj/WhatsNew.strings index 00dfaf155b..3f6a519ef3 100644 --- a/MC1/Resources/Localization/it.lproj/WhatsNew.strings +++ b/MC1/Resources/Localization/it.lproj/WhatsNew.strings @@ -65,3 +65,23 @@ "whatsNew.moreChanges.title" = "Altre modifiche"; /* What's New v1.6 - More changes, description */ "whatsNew.moreChanges.description" = "Tocca \"Vedi tutte le nuove modifiche\" qui sotto per vedere l'elenco completo delle correzioni di bug e delle altre funzionalità."; + +/* What's New v1.7 - Direct messages, title */ +"whatsNew.directMessages.title" = "Messaggi diretti"; +/* What's New v1.7 - Direct messages, description */ +"whatsNew.directMessages.description" = "I messaggi diretti ora provano il percorso 4 volte, poi 4 volte con routing flood. Cambia Tentativi sul percorso, Tentativi con routing flood e Ripiego sul routing flood in Impostazioni avanzate."; + +/* What's New v1.7 - Blocks and filters, title */ +"whatsNew.blocksAndFilters.title" = "Blocco e filtri"; +/* What's New v1.7 - Blocks and filters, description */ +"whatsNew.blocksAndFilters.description" = "Nascondi i messaggi che corrispondono a una parola o una frase. Una regola può cercare nel messaggio, nel nome del mittente o in entrambi, e scegli a quali chat si applica. I messaggi nascosti si vedono in Bloccati di recente in Impostazioni > Blocco e filtri."; + +/* What's New v1.7 - Node telemetry, title */ +"whatsNew.nodeTelemetry.title" = "Telemetria del nodo"; +/* What's New v1.7 - Node telemetry, description */ +"whatsNew.nodeTelemetry.description" = "Impostazioni > Info dispositivo mostra la telemetria del nodo a cui sei connesso."; + +/* What's New v1.7 - Live Activity, title */ +"whatsNew.liveActivity.title" = "Attività Live"; +/* What's New v1.7 - Live Activity, description */ +"whatsNew.liveActivity.description" = "I messaggi non letti sono più in evidenza e il tasso di pacchetti al minuto è più facile da capire."; diff --git a/MC1/Resources/Localization/ko.lproj/Chats.strings b/MC1/Resources/Localization/ko.lproj/Chats.strings index 62b7b44d80..0e6dab0dfa 100644 --- a/MC1/Resources/Localization/ko.lproj/Chats.strings +++ b/MC1/Resources/Localization/ko.lproj/Chats.strings @@ -338,8 +338,8 @@ /* Location: MutedIndicator.swift - Accessibility label for mentions-only indicator */ "chats.row.mentionsOnly" = "멘션만"; -/* TODO: translate - Accessibility label for the row actions menu */ -"chats.row.actionsMenu.accessibilityLabel" = "Conversation actions"; +/* Accessibility label for the row actions menu */ +"chats.row.actionsMenu.accessibilityLabel" = "대화 동작"; // MARK: - Notification Level Picker @@ -620,6 +620,12 @@ /* Location: UnifiedMessageBubble.swift - VoiceOver prefix when the visible body is a translation - %@ is the translated text */ "chats.message.translatedAccessibility" = "번역됨: %@"; +/* Location: MessageVisibleBody.swift - VoiceOver prefix when the visible body is an MECP reading - %@ is the reading */ +"chats.message.readingAccessibility" = "판독: %@"; + +/* Location: MECPCatalog - Person count line in an MECP reading */ +"chats.message.mecpPersonCount" = "%lld명"; + /* Location: UnifiedMessageBubble.swift - Context menu action to view repeat details */ "chats.message.action.repeatDetails" = "리피트 세부 정보"; @@ -673,6 +679,9 @@ /* Location: UnifiedMessageBubble.swift - Context menu text showing SNR - %@ is formatted value */ "chats.message.info.snr" = "SNR: %@"; +/* Location: ActionsDetailsSection.swift - Stored MECP wire string under SNR. %@ is the original text */ +"chats.message.info.mecp" = "MECP: %@"; + /* Location: MessageActionsSheet.swift - Details row showing the radio region a flood-routed message was broadcast under - %@ is region name */ "chats.message.info.floodedUnder" = "지역: %@"; diff --git a/MC1/Resources/Localization/ko.lproj/Chats.stringsdict b/MC1/Resources/Localization/ko.lproj/Chats.stringsdict new file mode 100644 index 0000000000..c86319ebf0 --- /dev/null +++ b/MC1/Resources/Localization/ko.lproj/Chats.stringsdict @@ -0,0 +1,20 @@ + + + + + chats.message.mecpPersonCount + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + lld + other + %lld명 + + + + diff --git a/MC1/Resources/Localization/ko.lproj/Contacts.strings b/MC1/Resources/Localization/ko.lproj/Contacts.strings index 8317fcc955..2da4d538fd 100644 --- a/MC1/Resources/Localization/ko.lproj/Contacts.strings +++ b/MC1/Resources/Localization/ko.lproj/Contacts.strings @@ -44,6 +44,8 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "룸"; +"contacts.nodeKind.sensor" = "센서"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "발견됨"; @@ -75,6 +77,8 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "룸"; +"contacts.segment.sensors" = "센서"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "노드 필터"; @@ -168,9 +172,13 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "룸 없음"; +"contacts.list.empty.sensors.title" = "센서 없음"; + /* Location: ContactsListView.swift - Purpose: No rooms empty description */ "contacts.list.empty.rooms.description" = "룸은 메시의 공개 채팅 서버입니다. 발견되면 여기에 표시됩니다."; +"contacts.list.empty.sensors.description" = "센서는 메시에서 발견되면 여기에 표시됩니다."; + /* Location: ContactsListView.swift - Purpose: No search results title */ "contacts.list.empty.search.title" = "결과 없음"; @@ -623,6 +631,8 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter: Rooms */ "contacts.discovery.segment.rooms" = "룸"; +"contacts.discovery.segment.sensors" = "센서"; + /* Location: DiscoverSegmentPicker.swift - Purpose: VoiceOver label for the Discovery segment filter picker (iOS 18 fallback) */ "contacts.discovery.segment.pickerLabel" = "발견된 노드 필터"; diff --git a/MC1/Resources/Localization/ko.lproj/Localizable.strings b/MC1/Resources/Localization/ko.lproj/Localizable.strings index 4e9566c123..f5c0105e41 100644 --- a/MC1/Resources/Localization/ko.lproj/Localizable.strings +++ b/MC1/Resources/Localization/ko.lproj/Localizable.strings @@ -150,6 +150,8 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "새 룸 발견"; +"notifications.discovery.sensor" = "새 센서 발견"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -495,6 +497,14 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "원격 노드의 응답이 잘못됨"; +"error.remoteNode.sensorOutcomeUnknown" = "변경을 확인하지 못했습니다. 다시 저장하기 전에 설정을 다시 불러오십시오."; + +"error.remoteNode.sensorSettingRejected" = "센서가 이 설정을 거부했습니다."; + +"error.remoteNode.invalidSensorSetting" = "공백 없는 비어 있지 않은 키와 값을 사용하십시오. 전체 명령은 160 UTF-8 바이트 이내여야 합니다."; + +"error.remoteNode.invalidPasswordLength" = "암호는 %d UTF-8 바이트를 넘을 수 없습니다."; + /* Location: RemoteNodeError+UserFacingMessage.swift - Remote node rejected the operation */ "error.remoteNode.permissionDenied" = "권한이 거부됨"; diff --git a/MC1/Resources/Localization/ko.lproj/Map.strings b/MC1/Resources/Localization/ko.lproj/Map.strings index 2bae1a1997..190e2ef7fc 100644 --- a/MC1/Resources/Localization/ko.lproj/Map.strings +++ b/MC1/Resources/Localization/ko.lproj/Map.strings @@ -37,6 +37,8 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "필터"; +"map.controls.contactsAndSensors" = "연락처 & 센서"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "필터 적용됨"; @@ -261,6 +263,8 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "룸"; +"map.nodeKind.sensor" = "센서"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -278,6 +282,8 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "룸"; +"map.callout.nodeKind.sensor" = "센서"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "추가"; diff --git a/MC1/Resources/Localization/ko.lproj/Onboarding.strings b/MC1/Resources/Localization/ko.lproj/Onboarding.strings index 10cbf6f03f..a0801a9c2c 100644 --- a/MC1/Resources/Localization/ko.lproj/Onboarding.strings +++ b/MC1/Resources/Localization/ko.lproj/Onboarding.strings @@ -69,6 +69,9 @@ /* Location: DeviceScanView.swift - Subtitle with pairing instructions */ "deviceScan.subtitle" = "무선 기기의 전원을 켜고 다른 모든 앱 및 기기와의 연결을 끊은 다음 기기 추가를 탭하십시오."; +/* Location: DeviceScanView.swift - Subtitle while bond-loss recovery is re-pairing */ +"deviceScan.rePairingSubtitle" = "무선 기기의 전원을 켜고 다른 모든 앱 및 기기와의 연결을 끊으십시오."; + /* Location: DeviceScanView.swift - Message shown when device is already paired */ "deviceScan.alreadyPaired" = "기기가 이미 페어링되어 있습니다"; @@ -78,9 +81,6 @@ /* Location: DeviceScanView.swift - Button to continue after pairing */ "deviceScan.continue" = "계속"; -/* Location: DeviceScanView.swift - Button label while connecting */ -"deviceScan.connecting" = "연결 중..."; - /* Location: DeviceScanView.swift - Button to connect simulator (debug) */ "deviceScan.connectSimulator" = "시뮬레이터 연결"; diff --git a/MC1/Resources/Localization/ko.lproj/RemoteNodes.strings b/MC1/Resources/Localization/ko.lproj/RemoteNodes.strings index 395d952034..9c0ef439a0 100644 --- a/MC1/Resources/Localization/ko.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/ko.lproj/RemoteNodes.strings @@ -32,6 +32,8 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "리피터"; +"remoteNodes.auth.typeSensor" = "센서"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "인증"; @@ -62,10 +64,18 @@ /* Location: NodeAuthenticationSheet.swift - Flood routing toggle */ "remoteNodes.auth.floodRouting" = "플러드 라우팅"; "remoteNodes.auth.floodRetryStatus" = "알려진 경로로 응답이 없습니다. 플러드 라우팅으로 다시 시도합니다."; -"remoteNodes.auth.floodFooter" = "플러드 라우팅은 더 느리고 네트워크 전송 시간을 더 많이 사용합니다. 현재 위치에서 알려진 경로가 작동하지 않을 때 사용하십시오. 로그인 후 새 경로를 자동으로 학습합니다."; +/* Footer when this sign-in will clear the saved route and use flood */ +"remoteNodes.auth.floodFooter" = "이번 로그인은 저장된 경로를 삭제하고 플러드 라우팅을 사용합니다. 플러드 라우팅은 더 느리고 네트워크 전송 시간을 더 많이 사용합니다. 로그인이 성공하면 새 경로를 학습합니다."; + +/* Footer after this sign-in has cleared the saved route */ +"remoteNodes.auth.floodFooterCleared" = "저장된 경로가 삭제되었습니다. 로그인이 플러드 라우팅을 사용 중입니다. 로그인이 성공하면 새 경로를 학습합니다."; + + +/* Footer when a timeout clears the route and retries by flood */ +"remoteNodes.auth.pathFooter" = "응답이 없으면 경로를 삭제하고 로그인을 플러드 라우팅으로 한 번 시도합니다."; -/* Location: NodeAuthenticationSheet.swift - Path section footer when stored path exists */ -"remoteNodes.auth.pathFooter" = "이 노드로 가는 알려진 경로를 사용하거나, 플러드 라우팅으로 전환하여 네트워크가 경로를 찾도록 하십시오."; +/* Footer when a timeout stops and leaves the route */ +"remoteNodes.auth.pathFooterKept" = "응답이 없으면 로그인이 중단되고 경로는 유지됩니다."; /* Location: NodeAuthenticationSheet.swift - Path hop whose repeater is not known */ "remoteNodes.auth.pathHopUnknown" = "<알 수 없음>"; @@ -84,6 +94,26 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "리피터 설정"; +"remoteNodes.sensor.adminRequired" = "센서 관리에는 관리자 접근 권한이 필요합니다."; + +"remoteNodes.sensor.saved" = "설정이 확인되었습니다."; + +"remoteNodes.sensor.rebootSent" = "재시동 요청을 보냈습니다. 센서가 다시 시작을 확인하지 않았습니다. 명령을 더 보내기 전에 다시 로그인하십시오."; + +"remoteNodes.sensor.rebootConfirmation" = "이 센서에 재시동 요청을 보내겠습니까?"; + +"remoteNodes.sensor.runtimeOnly" = "변경 사항은 실행 중인 센서에 적용됩니다. 재시동 후 유지 여부는 해당 펌웨어에 따라 다릅니다."; + +"remoteNodes.sensor.value" = "값"; + +"remoteNodes.sensor.save" = "저장"; + +"remoteNodes.sensor.reload" = "다시 불러오기"; + +"remoteNodes.sensor.empty" = "이 센서는 설정을 제공하지 않습니다."; + +"remoteNodes.sensor.title" = "센서 관리"; + /* Location: RepeaterSettingsView.swift - Done button (used in multiple places) */ "remoteNodes.settings.done" = "완료"; diff --git a/MC1/Resources/Localization/ko.lproj/Settings.strings b/MC1/Resources/Localization/ko.lproj/Settings.strings index bee41bda00..acf828eb9a 100644 --- a/MC1/Resources/Localization/ko.lproj/Settings.strings +++ b/MC1/Resources/Localization/ko.lproj/Settings.strings @@ -46,9 +46,6 @@ /* Section header for device information */ "device.header" = "기기"; -/* Status shown when device is connected */ -"device.connected" = "연결됨"; - /* Footer shown when no device is connected */ "device.noDeviceConnected" = "연결된 MeshCore 기기 없음"; @@ -60,12 +57,6 @@ /* Navigation title for device info screen */ "deviceInfo.title" = "기기 정보"; -/* Section header for connection status */ -"deviceInfo.connection.header" = "연결"; - -/* Label for connection status */ -"deviceInfo.connection.status" = "상태"; - /* Section header for power and storage */ "deviceInfo.powerStorage.header" = "전원 및 저장 공간"; @@ -111,6 +102,12 @@ /* Firmware version fallback format when no version string is reported - %@ is the numeric version code */ "deviceInfo.firmwareVersionFormat" = "v%@"; +/* Heading above retained telemetry after a Device Info reload fails */ +"deviceInfo.lastSuccessfulReading" = "마지막으로 성공한 측정값"; + +/* Section header for Device Info telemetry */ +"deviceInfo.telemetry.header" = "노드 텔레메트리"; + /* Section header for identity information */ /* Label for public key */ "deviceInfo.publicKey" = "공개 키"; @@ -165,6 +162,9 @@ /* Button to scan for Bluetooth devices */ "deviceSelection.scanBluetooth" = "Bluetooth 기기 검색"; +/* Button title while this radio is being paired again */ +"deviceSelection.rePairing" = "다시 페어링 중..."; + /* Trailing control on a previously paired row that still needs iPhone setup */ "deviceSelection.setup" = "설정"; @@ -735,6 +735,21 @@ /* Alert message for clear logs */ "diagnostics.alert.clear.message" = "저장된 모든 디버그 로그가 삭제됩니다. 내보낸 로그 파일에는 영향을 주지 않습니다."; +/* Toggle to enable collecting local debug logs */ +"diagnostics.collectLogs" = "디버그 로그 수집"; + +/* Footer shown when debug log collection is off */ +"diagnostics.footer.disabled" = "로컬 디버그 로그가 수집되지 않습니다."; + +/* Alert title for disabling collection */ +"diagnostics.alert.disable.title" = "디버그 로그 수집 끄기"; + +/* Button to confirm disabling collection */ +"diagnostics.alert.disable.confirm" = "끄기"; + +/* Alert message for disabling collection */ +"diagnostics.alert.disable.message" = "저장된 모든 디버그 로그가 삭제되고 수집이 중단됩니다. 내보낸 로그 파일에는 영향을 주지 않습니다."; + /* Error when export fails */ "diagnostics.error.exportFailed" = "내보내기 파일을 만들지 못함"; @@ -743,6 +758,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "채팅"; +"blocksAndFilters.title" = "차단 및 필터"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -862,6 +879,8 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "컴패니언"; +"notifications.discoveryCompanionsAndSensors" = "컴패니언 & 센서"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "리피터"; @@ -1023,6 +1042,9 @@ /* Editor footer when the password is too long */ "radioWiFi.editor.passwordLength" = "암호는 최대 63바이트입니다."; +/* Editor footer when a credential contains a character the firmware cannot store */ +"radioWiFi.editor.unsupportedCharacter" = "네트워크 이름 또는 암호에 이 무선 기기가 저장할 수 없는 문자가 포함되어 있습니다."; + /* Button that clears the radio's saved WiFi settings */ "radioWiFi.clear" = "Wi-Fi 설정 지우기"; @@ -1188,6 +1210,35 @@ /* Footer explaining the acknowledgments setting */ "directMessages.footer" = "다이렉트 메시지당 보내는 확인 응답 수입니다. 불안정한 링크에서 전달 확인을 개선하려면 2를 사용하십시오."; +/* Switch that clears the known route after the path attempts */ +"directMessages.fallback" = "플러드 라우팅으로 대체"; + +/* Picker label for attempts on the known route */ +"directMessages.directAttempts" = "경로 시도"; + +/* Picker label for attempts sent by flood after the route is cleared */ +"directMessages.floodAttempts" = "플러드 라우팅 시도"; + +/* Footer when Fall Back to Flood is on */ +"directMessages.attemptsFooterOn" = "경로 시도 후에 경로가 삭제됩니다. 그 후 플러드 라우팅 시도는 플러드 라우팅으로 전송됩니다. 알려진 경로가 없는 연락처에게 보내는 메시지는 플러드 라우팅으로 전송됩니다."; + +/* Footer when Fall Back to Flood is off */ +"directMessages.attemptsFooterOff" = "경로 시도는 알려진 경로로 전송되고 경로는 유지됩니다. 알려진 경로가 없는 연락처에게 보내는 메시지는 플러드 라우팅으로 전송됩니다."; + +// MARK: - Path Fallback + +/* Section header for sign-in, command, and contact telemetry path fallback */ +"pathFallback.header" = "경로 대체"; + +/* Switch that clears the known route after a timeout */ +"pathFallback.fallback" = "플러드 라우팅으로 대체"; + +/* Footer when path fallback is on */ +"pathFallback.footerOn" = "로그인, 리피터와 룸에 보내며 응답을 기다리는 명령, 연락처 텔레메트리는 알려진 경로를 사용합니다. 응답이 없으면 경로를 삭제하고 플러드 라우팅으로 한 번 시도합니다."; + +/* Footer when path fallback is off */ +"pathFallback.footerOff" = "로그인, 명령, 연락처 텔레메트리는 알려진 경로를 계속 사용합니다. 응답이 없으면 모두 중단되고 경로는 유지됩니다. 로그인 화면의 플러드 라우팅은 해당 노드의 저장된 경로를 삭제합니다."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ @@ -1202,12 +1253,24 @@ /* Menu item to disconnect from the current device */ "bleStatus.disconnect" = "연결 해제"; +/* Menu item to stop automatic reconnection until another explicit connection */ +"bleStatus.stopReconnecting" = "다시 연결 중지"; + +/* Menu item to cancel the current connection request */ +"bleStatus.cancelConnection" = "연결 취소"; + /* Status shown when device is disconnected */ "bleStatus.status.disconnected" = "연결 끊김"; /* Status shown when device is connecting */ "bleStatus.status.connecting" = "연결 중..."; +/* Status shown while reconnecting to the selected device */ +"bleStatus.status.reconnecting" = "다시 연결하는 중..."; + +/* Status shown while automatic reconnection remains enabled between attempts */ +"bleStatus.status.waitingToReconnect" = "다시 연결 대기 중"; + /* Status shown when device is connected but not ready */ "bleStatus.status.connected" = "연결됨"; @@ -1220,6 +1283,9 @@ /* Accessibility label for BLE status indicator */ "bleStatus.accessibilityLabel" = "Bluetooth 연결 상태"; +/* TODO: translate - Accessibility text combining a descriptive prefix and connection state or context; arguments may themselves contain a radio name and status */ +"bleStatus.accessibilityValue" = "%1$@, %2$@"; + /* Accessibility hint when disconnected */ "bleStatus.accessibilityHint.disconnected" = "기기를 연결하려면 이중 탭하십시오"; @@ -1323,6 +1389,24 @@ /* Import failed after one or more settings were already written; %@ is the underlying error message */ "configImport.failedPartial" = "%@ 일부 설정이 이미 기기에 기록되었을 수 있습니다. 기기의 구성을 검토하십시오."; +/* Interrupted identity import recovery */ +"configImport.identityOutcomeUnknown" = "%@에 ID를 가져오는 동안 연결이 중단되었습니다. 무선 기기의 ID가 변경되었을 수 있습니다. 구성 가져오기가 완료되지 않았습니다."; + +/* Interrupted identity import recovery */ +"configImport.retryIdentityImport" = "ID 가져오기 재시도"; + +/* Interrupted identity import recovery */ +"configImport.confirmIdentityRecovery" = "선택한 파일의 개인 키를 사용하여 %@을(를) 통해 연결되는 무선 기기의 ID를 교체합니다. 구성 가져오기는 계속되지 않습니다."; + +/* Confirmation alert title when retrying an interrupted identity import */ +"configImport.confirmTitleIdentityRecovery" = "무선 기기의 ID를 교체하겠습니까?"; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryComplete" = "ID가 다시 적용되었습니다. 구성 가져오기가 완료되지 않았습니다. 다른 설정을 적용하려면 파일을 다시 가져오십시오."; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryKeyRequired" = "ID 가져오기를 다시 시도하려면 개인 키가 포함된 구성 파일을 선택하십시오."; + /* Import success */ "configImport.importSuccess" = "구성을 가져왔습니다"; @@ -1422,6 +1506,63 @@ /* Validation error: no empty channel slot left (param: channel name) */ "configImport.error.noAvailableChannelSlot" = "\"%@\"에 사용할 빈 채널 슬롯이 없습니다"; +// MARK: - Text Rules + +"textRules.rules" = "필터 규칙"; +"textRules.empty" = "필터 규칙 없음"; +"textRules.loading" = "필터 규칙을 불러오는 중…"; +"textRules.loadFailed" = "필터 규칙을 불러올 수 없습니다. 불러올 수 있을 때까지 새 메시지는 필터 규칙을 사용하지 않습니다."; +"textRules.retryAccessibility" = "필터 규칙 다시 불러오기"; +"textRules.saveFailed" = "필터 규칙을 저장할 수 없습니다. 다시 시도하십시오."; +"textRules.new.title" = "새 규칙"; +"textRules.new.phrase" = "단어 또는 문구"; +"textRules.new.lookIn" = "검색 위치"; +"textRules.new.match" = "일치 방식"; +"textRules.new.containsMessageFooter" = "메시지 어디에서든, 단어 안에서도 일치합니다."; +"textRules.new.wholeMessageFooter" = "메시지 전체가 이 문구일 때만 일치합니다."; +"textRules.new.containsSenderFooter" = "발신자 이름 어디에서든, 단어 안에서도 일치합니다. 그 발신자의 반응도 숨겨집니다."; +"textRules.new.wholeNameFooter" = "발신자 이름이 정확히 이 문구일 때만 일치합니다. 그 발신자의 반응도 숨겨집니다."; +"textRules.new.containsMessageOrSenderFooter" = "메시지 또는 발신자 이름 어디에서든, 단어 안에서도 일치합니다. 일치하는 발신자의 반응도 숨겨집니다."; +"textRules.new.wholeMessageOrSenderFooter" = "메시지 전체 또는 발신자 이름 전체가 이 문구일 때만 일치합니다. 일치하는 발신자의 반응도 숨겨집니다."; +"textRules.field.message" = "메시지"; +"textRules.field.sender" = "발신자"; +"textRules.field.messageOrSender" = "메시지 또는 발신자"; +"textRules.match.contains" = "포함"; +"textRules.match.wholeMessage" = "메시지 전체"; +"textRules.match.wholeName" = "이름 전체"; +"textRules.match.wholeField" = "항목 전체"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "규칙 적용 대상"; +"textRules.types.footer" = "켜면 해당 유형의 모든 채팅이 포함됩니다. 나중에 참여하는 채팅도 포함됩니다."; +"textRules.types.publicChannel" = "공개"; +"textRules.types.hashtagChannel" = "해시태그 채널"; +"textRules.types.privateChannel" = "비공개 채널"; +"textRules.selection.all" = "전체"; +"textRules.selection.none" = "없음"; +"textRules.selection.count" = "%d개 채팅"; +"textRules.selection.accessibilityChats" = "%@에 대한 채팅"; +"textRules.selection.footer" = "전체는 나중에 참여하는 채팅도 포함합니다."; +"textRules.archive.title" = "최근 차단"; +"textRules.archive.empty" = "숨겨진 메시지 없음"; +"textRules.archive.footer" = "최근 숨겨진 메시지 %d개가 이 기기에 보관됩니다. 앱 백업에는 포함되지 않습니다."; +"textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; +"textRules.archive.rule" = "규칙"; +"textRules.archive.chat" = "채팅"; +"textRules.archive.myNode" = "내 노드"; +"textRules.archive.time" = "시간"; +"textRules.archive.unknownConversation" = "알 수 없는 대화"; +"textRules.archive.unknownRadio" = "알 수 없는 무선 기기"; + +"radioCleanup.title" = "정리"; +"radioCleanup.running" = "무선 기기 데이터 제거 중"; +"radioCleanup.failed" = "이 무선 기기의 숨겨진 메시지가 이 앱 설치에 남아 있을 수 있습니다."; +"radioCleanup.completed" = "무선 기기 데이터 제거됨"; +"radioCleanup.retryAccessibility" = "%@의 무선 기기 정리 다시 시도"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ @@ -1983,7 +2124,7 @@ "settings.backup.export.alert.title" = "보안 알림"; /* Export confirmation alert message */ -"settings.backup.export.alert.message" = "이 백업에는 채널 암호화 키, 메시지 기록, 연락처 목록, Wi-Fi 노드의 로컬 네트워크 주소와 포트가 포함됩니다. 내보낸 파일을 안전하게 보관하십시오."; +"settings.backup.export.alert.message" = "이 백업에는 채널 암호화 키, 메시지 기록, 연락처 목록, Wi-Fi 노드의 로컬 네트워크 주소와 포트가 포함됩니다. 무전기에서 수집한 GPS 좌표도 포함될 수 있습니다. 내보낸 파일을 안전하게 보관하십시오."; /* Export confirmation alert export button */ "settings.backup.export.alert.export" = "내보내기"; diff --git a/MC1/Resources/Localization/ko.lproj/WhatsNew.strings b/MC1/Resources/Localization/ko.lproj/WhatsNew.strings index a8bad8a99f..2477562bc3 100644 --- a/MC1/Resources/Localization/ko.lproj/WhatsNew.strings +++ b/MC1/Resources/Localization/ko.lproj/WhatsNew.strings @@ -64,3 +64,23 @@ "whatsNew.moreChanges.title" = "기타 변경 사항"; /* What's New v1.6 - More changes, description */ "whatsNew.moreChanges.description" = "아래의 \"모든 변경 사항 보기\"를 탭하면 버그 수정과 기타 기능의 전체 목록을 볼 수 있습니다."; + +/* What's New v1.7 - Direct messages, title */ +"whatsNew.directMessages.title" = "다이렉트 메시지"; +/* What's New v1.7 - Direct messages, description */ +"whatsNew.directMessages.description" = "다이렉트 메시지는 이제 경로를 4번 시도한 다음 플러드 라우팅을 4번 시도합니다. 고급 설정에서 경로 시도, 플러드 라우팅 시도 및 플러드 라우팅으로 대체를 변경할 수 있습니다."; + +/* What's New v1.7 - Blocks and filters, title */ +"whatsNew.blocksAndFilters.title" = "차단 및 필터"; +/* What's New v1.7 - Blocks and filters, description */ +"whatsNew.blocksAndFilters.description" = "단어 또는 문구와 일치하는 메시지는 숨겨집니다. 규칙은 메시지, 발신자 이름 또는 둘 다를 볼 수 있으며, 적용할 채팅을 선택할 수 있습니다. 숨겨진 메시지는 설정 > 차단 및 필터의 최근 차단에서 볼 수 있습니다."; + +/* What's New v1.7 - Node telemetry, title */ +"whatsNew.nodeTelemetry.title" = "노드 텔레메트리"; +/* What's New v1.7 - Node telemetry, description */ +"whatsNew.nodeTelemetry.description" = "연결된 노드의 텔레메트리가 설정 > 기기 정보에 표시됩니다."; + +/* What's New v1.7 - Live Activity, title */ +"whatsNew.liveActivity.title" = "실시간 현황"; +/* What's New v1.7 - Live Activity, description */ +"whatsNew.liveActivity.description" = "읽지 않은 메시지가 더 눈에 띄며, 분당 패킷 수가 더 이해하기 쉽습니다."; diff --git a/MC1/Resources/Localization/nl.lproj/Chats.strings b/MC1/Resources/Localization/nl.lproj/Chats.strings index f973d77f08..0d024d1a99 100644 --- a/MC1/Resources/Localization/nl.lproj/Chats.strings +++ b/MC1/Resources/Localization/nl.lproj/Chats.strings @@ -588,6 +588,12 @@ /* Location: UnifiedMessageBubble.swift - VoiceOver prefix when the visible body is a translation - %@ is the translated text */ "chats.message.translatedAccessibility" = "Vertaald: %@"; +/* Location: MessageVisibleBody.swift - VoiceOver prefix when the visible body is an MECP reading - %@ is the reading */ +"chats.message.readingAccessibility" = "Lezing: %@"; + +/* Location: MECPCatalog - Person count line in an MECP reading */ +"chats.message.mecpPersonCount" = "%lld personen"; + /* Location: UnifiedMessageBubble.swift - Context menu action to view repeat details */ "chats.message.action.repeatDetails" = "Herhalingsdetails"; @@ -641,6 +647,9 @@ /* Location: UnifiedMessageBubble.swift - Context menu text showing SNR - %@ is formatted value */ "chats.message.info.snr" = "SNR: %@"; +/* Location: ActionsDetailsSection.swift - Stored MECP wire string under SNR. %@ is the original text */ +"chats.message.info.mecp" = "MECP: %@"; + /* Location: MessageActionsSheet.swift - Context menu text showing the radio region the message was flooded under - %@ is region name. "Flooded" is a domain term for mesh-broadcast across all nodes in a radio region. */ "chats.message.info.floodedUnder" = "Regio: %@"; @@ -1147,8 +1156,8 @@ /* Location: ConversationRow.swift - Purpose: Mentions-only indicator */ "chats.row.mentionsOnly" = "Alleen vermeldingen"; -/* TODO: translate - Accessibility label for the row actions menu */ -"chats.row.actionsMenu.accessibilityLabel" = "Conversation actions"; +/* Accessibility label for the row actions menu */ +"chats.row.actionsMenu.accessibilityLabel" = "Gespreksacties"; // MARK: - Reaction Badges & Actions diff --git a/MC1/Resources/Localization/nl.lproj/Chats.stringsdict b/MC1/Resources/Localization/nl.lproj/Chats.stringsdict new file mode 100644 index 0000000000..94b5090c57 --- /dev/null +++ b/MC1/Resources/Localization/nl.lproj/Chats.stringsdict @@ -0,0 +1,22 @@ + + + + + chats.message.mecpPersonCount + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + lld + one + %lld persoon + other + %lld personen + + + + diff --git a/MC1/Resources/Localization/nl.lproj/Contacts.strings b/MC1/Resources/Localization/nl.lproj/Contacts.strings index 513b8f309a..fb42f7beab 100644 --- a/MC1/Resources/Localization/nl.lproj/Contacts.strings +++ b/MC1/Resources/Localization/nl.lproj/Contacts.strings @@ -44,6 +44,8 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Kamer"; +"contacts.nodeKind.sensor" = "Sensor"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Ontdekt"; @@ -75,6 +77,8 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Kamers"; +"contacts.segment.sensors" = "Sensoren"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "Nodes filteren"; @@ -168,9 +172,13 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "Geen kamers"; +"contacts.list.empty.sensors.title" = "Geen sensoren"; + /* Location: ContactsListView.swift - Purpose: No rooms empty description */ "contacts.list.empty.rooms.description" = "Kamers zijn openbare chatservers op het mesh-netwerk. Ze verschijnen hier zodra ze worden ontdekt."; +"contacts.list.empty.sensors.description" = "Sensoren verschijnen hier wanneer ze worden ontdekt op het mesh-netwerk."; + /* Location: ContactsListView.swift - Purpose: No search results title */ "contacts.list.empty.search.title" = "Geen resultaten"; @@ -623,6 +631,8 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter - Rooms */ "contacts.discovery.segment.rooms" = "Kamers"; +"contacts.discovery.segment.sensors" = "Sensoren"; + /* Location: DiscoverSegmentPicker.swift - Purpose: VoiceOver label for the Discovery segment filter picker (iOS 18 fallback) */ "contacts.discovery.segment.pickerLabel" = "Ontdekte nodes filteren"; diff --git a/MC1/Resources/Localization/nl.lproj/Localizable.strings b/MC1/Resources/Localization/nl.lproj/Localizable.strings index a176628f7b..c891d35545 100644 --- a/MC1/Resources/Localization/nl.lproj/Localizable.strings +++ b/MC1/Resources/Localization/nl.lproj/Localizable.strings @@ -137,6 +137,8 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "Nieuwe ruimte ontdekt"; +"notifications.discovery.sensor" = "Nieuwe sensor ontdekt"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -500,6 +502,14 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Ongeldig antwoord van de externe node"; +"error.remoteNode.sensorOutcomeUnknown" = "De wijziging kon niet worden geverifieerd. Laad de instellingen opnieuw voordat je opnieuw opslaat."; + +"error.remoteNode.sensorSettingRejected" = "De sensor heeft deze instelling geweigerd."; + +"error.remoteNode.invalidSensorSetting" = "Gebruik een sleutel en waarde die niet leeg zijn en geen witruimte bevatten. De volledige opdracht moet binnen 160 UTF-8 bytes passen."; + +"error.remoteNode.invalidPasswordLength" = "Wachtwoorden mogen niet meer dan %d UTF-8 bytes gebruiken."; + /* Location: RemoteNodeError+UserFacingMessage.swift - Remote node rejected the operation */ "error.remoteNode.permissionDenied" = "Toegang geweigerd"; diff --git a/MC1/Resources/Localization/nl.lproj/Map.strings b/MC1/Resources/Localization/nl.lproj/Map.strings index 2a8dd848af..dac6caec32 100644 --- a/MC1/Resources/Localization/nl.lproj/Map.strings +++ b/MC1/Resources/Localization/nl.lproj/Map.strings @@ -40,6 +40,8 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Filter"; +"map.controls.contactsAndSensors" = "Contacten & Sensoren"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Filters actief"; @@ -264,6 +266,8 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Kamer"; +"map.nodeKind.sensor" = "Sensor"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -281,6 +285,8 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Kamer"; +"map.callout.nodeKind.sensor" = "Sensor"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "Toevoegen"; diff --git a/MC1/Resources/Localization/nl.lproj/Onboarding.strings b/MC1/Resources/Localization/nl.lproj/Onboarding.strings index 7b1b6914aa..256392a408 100644 --- a/MC1/Resources/Localization/nl.lproj/Onboarding.strings +++ b/MC1/Resources/Localization/nl.lproj/Onboarding.strings @@ -69,6 +69,9 @@ /* Location: DeviceScanView.swift - Subtitle with pairing instructions */ "deviceScan.subtitle" = "Schakel je radio in, koppel deze los van alle andere apps en apparaten en tik vervolgens op Apparaat toevoegen."; +/* Location: DeviceScanView.swift - Subtitle while bond-loss recovery is re-pairing */ +"deviceScan.rePairingSubtitle" = "Schakel je radio in en koppel deze los van alle andere apps en apparaten."; + /* Location: DeviceScanView.swift - Message shown when device is already paired */ "deviceScan.alreadyPaired" = "Je apparaat is al gekoppeld"; @@ -78,9 +81,6 @@ /* Location: DeviceScanView.swift - Button to continue after pairing */ "deviceScan.continue" = "Doorgaan"; -/* Location: DeviceScanView.swift - Button label while connecting */ -"deviceScan.connecting" = "Verbinden..."; - /* Location: DeviceScanView.swift - Button to connect simulator (debug) */ "deviceScan.connectSimulator" = "Simulator verbinden"; diff --git a/MC1/Resources/Localization/nl.lproj/RemoteNodes.strings b/MC1/Resources/Localization/nl.lproj/RemoteNodes.strings index 4d5e0d9e89..cd2dd9b4ef 100644 --- a/MC1/Resources/Localization/nl.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/nl.lproj/RemoteNodes.strings @@ -32,6 +32,8 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Repeater"; +"remoteNodes.auth.typeSensor" = "Sensor"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Authenticatie"; @@ -62,10 +64,18 @@ /* Location: NodeAuthenticationSheet.swift - Flood routing toggle */ "remoteNodes.auth.floodRouting" = "Flood-routing"; "remoteNodes.auth.floodRetryStatus" = "Geen antwoord via de bekende route. Nieuwe poging met flood-routing."; -"remoteNodes.auth.floodFooter" = "Flood-routing is trager en gebruikt meer zendtijd op het netwerk. Gebruik het wanneer de bekende route op je huidige locatie niet werkt. Na het inloggen wordt automatisch een nieuwe route geleerd."; +/* Footer when this sign-in will clear the saved route and use flood */ +"remoteNodes.auth.floodFooter" = "Dit inloggen wist de opgeslagen route en gebruikt flood-routing. Flood-routing is trager en gebruikt meer zendtijd op het netwerk. Een nieuwe route wordt alleen geleerd als het inloggen lukt."; + +/* Footer after this sign-in has cleared the saved route */ +"remoteNodes.auth.floodFooterCleared" = "De opgeslagen route is gewist. Het inloggen gebruikt flood-routing. Een nieuwe route wordt alleen geleerd als het inloggen lukt."; + + +/* Footer when a timeout clears the route and retries by flood */ +"remoteNodes.auth.pathFooter" = "Als er geen antwoord komt, wordt de route gewist en doet het inloggen één poging met flood-routing."; -/* Location: NodeAuthenticationSheet.swift - Path section footer when stored path exists */ -"remoteNodes.auth.pathFooter" = "Gebruik de bekende route naar dit knooppunt of schakel over naar flood-routing om het netwerk een pad te laten vinden."; +/* Footer when a timeout stops and leaves the route */ +"remoteNodes.auth.pathFooterKept" = "Als er geen antwoord komt, stopt het inloggen en blijft de route staan."; /* Location: NodeAuthenticationSheet.swift - Path hop whose repeater is not known */ "remoteNodes.auth.pathHopUnknown" = ""; @@ -84,6 +94,26 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Repeater-instellingen"; +"remoteNodes.sensor.adminRequired" = "Sensorbeheer vereist beheerderstoegang."; + +"remoteNodes.sensor.saved" = "Instelling geverifieerd."; + +"remoteNodes.sensor.rebootSent" = "Herstartopdracht verzonden. De sensor heeft niet bevestigd dat hij is herstart. Log opnieuw in voordat je meer opdrachten verzendt."; + +"remoteNodes.sensor.rebootConfirmation" = "Een herstartopdracht naar deze sensor verzenden?"; + +"remoteNodes.sensor.runtimeOnly" = "Wijzigingen gelden voor de draaiende sensor. Of ze behouden blijven na herstart, hangt af van de firmware."; + +"remoteNodes.sensor.value" = "Waarde"; + +"remoteNodes.sensor.save" = "Opslaan"; + +"remoteNodes.sensor.reload" = "Opnieuw laden"; + +"remoteNodes.sensor.empty" = "Deze sensor biedt geen instellingen."; + +"remoteNodes.sensor.title" = "Sensorbeheer"; + /* Location: RepeaterSettingsView.swift - Done button (used in multiple places) */ "remoteNodes.settings.done" = "Klaar"; diff --git a/MC1/Resources/Localization/nl.lproj/Settings.strings b/MC1/Resources/Localization/nl.lproj/Settings.strings index 76b71eb1f5..1e1b124275 100644 --- a/MC1/Resources/Localization/nl.lproj/Settings.strings +++ b/MC1/Resources/Localization/nl.lproj/Settings.strings @@ -46,9 +46,6 @@ /* Section header for device information */ "device.header" = "Apparaat"; -/* Status shown when device is connected */ -"device.connected" = "Verbonden"; - /* Footer shown when no device is connected */ "device.noDeviceConnected" = "Geen MeshCore-apparaat verbonden"; @@ -60,12 +57,6 @@ /* Navigation title for device info screen */ "deviceInfo.title" = "Apparaatinfo"; -/* Section header for connection status */ -"deviceInfo.connection.header" = "Verbinding"; - -/* Label for connection status */ -"deviceInfo.connection.status" = "Status"; - /* Section header for power and storage */ "deviceInfo.powerStorage.header" = "Voeding en opslag"; @@ -111,6 +102,12 @@ /* Firmware version fallback format when no version string is reported - %@ is the numeric version code */ "deviceInfo.firmwareVersionFormat" = "v%@"; +/* Heading above retained telemetry after a Device Info reload fails */ +"deviceInfo.lastSuccessfulReading" = "Laatste geslaagde meting"; + +/* Section header for Device Info telemetry */ +"deviceInfo.telemetry.header" = "Knooppunttelemetrie"; + /* Section header for identity information */ /* Label for public key */ "deviceInfo.publicKey" = "Publieke sleutel"; @@ -165,6 +162,9 @@ /* Button to scan for Bluetooth devices */ "deviceSelection.scanBluetooth" = "Scannen naar Bluetooth-apparaat"; +/* Button title while this radio is being paired again */ +"deviceSelection.rePairing" = "Opnieuw koppelen..."; + /* Trailing control on a previously paired row that still needs iPhone setup */ /* AI-translated - please verify with native speakers. */ "deviceSelection.setup" = "Instellen"; @@ -746,6 +746,21 @@ /* Alert message for clear logs */ "diagnostics.alert.clear.message" = "Dit verwijdert alle opgeslagen debuglogboeken. Geëxporteerde logbestanden worden niet beïnvloed."; +/* Toggle to enable collecting local debug logs */ +"diagnostics.collectLogs" = "Debuglogboeken verzamelen"; + +/* Footer shown when debug log collection is off */ +"diagnostics.footer.disabled" = "Lokale debuglogboeken worden niet verzameld."; + +/* Alert title for disabling collection */ +"diagnostics.alert.disable.title" = "Verzamelen uitschakelen"; + +/* Button to confirm disabling collection */ +"diagnostics.alert.disable.confirm" = "Verzamelen uitschakelen"; + +/* Alert message for disabling collection */ +"diagnostics.alert.disable.message" = "Dit verwijdert alle opgeslagen debuglogboeken en stopt met het verzamelen ervan. Geëxporteerde logbestanden worden niet beïnvloed."; + /* Error when export fails */ "diagnostics.error.exportFailed" = "Kan exportbestand niet maken"; @@ -754,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Chats"; +"blocksAndFilters.title" = "Blokkering en filters"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -822,6 +839,8 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Companion"; +"notifications.discoveryCompanionsAndSensors" = "Companions & Sensoren"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Repeater"; @@ -983,6 +1002,9 @@ /* Editor footer when the password is too long */ "radioWiFi.editor.passwordLength" = "Een wachtwoord kan maximaal 63 bytes zijn."; +/* Editor footer when a credential contains a character the firmware cannot store */ +"radioWiFi.editor.unsupportedCharacter" = "De netwerknaam of het wachtwoord bevat een teken dat deze radio niet kan opslaan."; + /* Button that clears the radio's saved WiFi settings */ "radioWiFi.clear" = "Wifi-instellingen wissen"; @@ -1148,6 +1170,35 @@ /* Footer explaining the acknowledgments setting */ "directMessages.footer" = "Aantal bevestigingen dat per direct bericht wordt verstuurd. Gebruik 2 voor betere afleverbevestiging via onbetrouwbare verbindingen."; +/* Switch that clears the known route after the path attempts */ +"directMessages.fallback" = "Terugval op flood-routing"; + +/* Picker label for attempts on the known route */ +"directMessages.directAttempts" = "Pogingen op het pad"; + +/* Picker label for attempts sent by flood after the route is cleared */ +"directMessages.floodAttempts" = "Flood-pogingen"; + +/* Footer when Fall Back to Flood is on */ +"directMessages.attemptsFooterOn" = "De route wordt gewist na Pogingen op het pad. Flood-pogingen worden daarna met flood-routing verstuurd. Een bericht naar een contact zonder bekende route wordt met flood-routing verstuurd."; + +/* Footer when Fall Back to Flood is off */ +"directMessages.attemptsFooterOff" = "Pogingen op het pad blijven op de bekende route en de route blijft staan. Een bericht naar een contact zonder bekende route wordt met flood-routing verstuurd."; + +// MARK: - Path Fallback + +/* Section header for sign-in, command, and contact telemetry path fallback */ +"pathFallback.header" = "Padterugval"; + +/* Switch that clears the known route after a timeout */ +"pathFallback.fallback" = "Terugval op flood-routing"; + +/* Footer when path fallback is on */ +"pathFallback.footerOn" = "Inloggen, opdrachten aan een repeater en een kamer die op een antwoord wachten, en telemetrie van het contact gebruiken de bekende route. Als er geen antwoord komt, wordt de route gewist en wordt er één poging met flood-routing gedaan."; + +/* Footer when path fallback is off */ +"pathFallback.footerOff" = "Inloggen, opdrachten en telemetrie van het contact blijven op de bekende route. Als er geen antwoord komt, stoppen ze en blijft de route staan. Flood-routing op het inlogscherm wist de opgeslagen route van dat knooppunt."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ @@ -1162,12 +1213,24 @@ /* Menu item to disconnect from the current device */ "bleStatus.disconnect" = "Verbinding verbreken"; +/* Menu item to stop automatic reconnection until another explicit connection */ +"bleStatus.stopReconnecting" = "Stoppen met opnieuw verbinden"; + +/* Menu item to cancel the current connection request */ +"bleStatus.cancelConnection" = "Verbinding annuleren"; + /* Status shown when device is disconnected */ "bleStatus.status.disconnected" = "Niet verbonden"; /* Status shown when device is connecting */ "bleStatus.status.connecting" = "Verbinden..."; +/* Status shown while reconnecting to the selected device */ +"bleStatus.status.reconnecting" = "Opnieuw verbinden..."; + +/* Status shown while automatic reconnection remains enabled between attempts */ +"bleStatus.status.waitingToReconnect" = "Wachten om opnieuw te verbinden"; + /* Status shown when device is connected but not ready */ "bleStatus.status.connected" = "Verbonden"; @@ -1180,6 +1243,9 @@ /* Accessibility label for BLE status indicator */ "bleStatus.accessibilityLabel" = "Bluetooth-verbindingsstatus"; +/* TODO: translate - Accessibility text combining a descriptive prefix and connection state or context; arguments may themselves contain a radio name and status */ +"bleStatus.accessibilityValue" = "%1$@, %2$@"; + /* Accessibility hint when disconnected */ "bleStatus.accessibilityHint.disconnected" = "Dubbeltik om apparaat te verbinden"; @@ -1318,6 +1384,24 @@ /* Import failed after one or more settings were already written; %@ is the underlying error message */ "configImport.failedPartial" = "%@ Sommige instellingen zijn mogelijk al naar het apparaat geschreven. Controleer de configuratie van het apparaat."; +/* Interrupted identity import recovery */ +"configImport.identityOutcomeUnknown" = "De verbinding werd onderbroken tijdens het importeren van de identiteit op %@. De identiteit van de radio is mogelijk gewijzigd. Het importeren van de configuratie is niet voltooid."; + +/* Interrupted identity import recovery */ +"configImport.retryIdentityImport" = "Identiteit opnieuw importeren"; + +/* Interrupted identity import recovery */ +"configImport.confirmIdentityRecovery" = "Hiermee wordt de identiteit van de radio die op %@ is bereikt vervangen met behulp van de privésleutel in het geselecteerde bestand. Het importeren van de configuratie wordt niet voortgezet."; + +/* Confirmation alert title when retrying an interrupted identity import */ +"configImport.confirmTitleIdentityRecovery" = "Identiteit van de radio vervangen?"; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryComplete" = "De identiteit is opnieuw toegepast. Het importeren van de configuratie is niet voltooid. Importeer het bestand opnieuw om de overige instellingen toe te passen."; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryKeyRequired" = "Selecteer een configuratiebestand met de privésleutel om de identiteit opnieuw te importeren."; + /* Import success */ "configImport.importSuccess" = "Configuratie succesvol geïmporteerd"; @@ -1434,6 +1518,63 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "Het tonen van kaartminiaturen haalt kaarttegels voor de coördinaat op bij een externe server, waardoor uw IP-adres kan worden onthuld."; +// MARK: - Text Rules + +"textRules.rules" = "Filterregels"; +"textRules.empty" = "Geen filterregels"; +"textRules.loading" = "Filterregels laden…"; +"textRules.loadFailed" = "Filterregels konden niet worden geladen. Nieuwe berichten gebruiken geen filterregels totdat het laden lukt."; +"textRules.retryAccessibility" = "Filterregels opnieuw laden"; +"textRules.saveFailed" = "Kan filterregels niet opslaan. Probeer het opnieuw."; +"textRules.new.title" = "Nieuwe regel"; +"textRules.new.phrase" = "Woord of tekst"; +"textRules.new.lookIn" = "Zoeken in"; +"textRules.new.match" = "Overeenkomst"; +"textRules.new.containsMessageFooter" = "Komt ergens in het bericht overeen, ook binnen een woord."; +"textRules.new.wholeMessageFooter" = "Komt alleen overeen als het hele bericht deze tekst is."; +"textRules.new.containsSenderFooter" = "Komt ergens in de naam van de afzender overeen, ook binnen een woord. Reacties van die afzender worden ook verborgen."; +"textRules.new.wholeNameFooter" = "Komt alleen overeen als de naam van de afzender precies deze tekst is. Reacties van die afzender worden ook verborgen."; +"textRules.new.containsMessageOrSenderFooter" = "Komt in het bericht of in de naam van de afzender overeen, ook binnen een woord. Reacties van een overeenkomende afzender worden ook verborgen."; +"textRules.new.wholeMessageOrSenderFooter" = "Komt alleen overeen als het hele bericht of de hele naam van de afzender deze tekst is. Reacties van een overeenkomende afzender worden ook verborgen."; +"textRules.field.message" = "Bericht"; +"textRules.field.sender" = "Afzender"; +"textRules.field.messageOrSender" = "Bericht of afzender"; +"textRules.match.contains" = "Bevat"; +"textRules.match.wholeMessage" = "Heel bericht"; +"textRules.match.wholeName" = "Hele naam"; +"textRules.match.wholeField" = "Heel veld"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Regels gebruiken voor"; +"textRules.types.footer" = "Staat de schakelaar aan, dan geldt die voor elk gesprek van dat type, ook voor gesprekken waaraan je later deelneemt."; +"textRules.types.publicChannel" = "Openbaar"; +"textRules.types.hashtagChannel" = "Hashtag-kanalen"; +"textRules.types.privateChannel" = "Privékanalen"; +"textRules.selection.all" = "Alle"; +"textRules.selection.none" = "Geen"; +"textRules.selection.count" = "%d Chats"; +"textRules.selection.accessibilityChats" = "Chats voor %@"; +"textRules.selection.footer" = "Alle geldt ook voor gesprekken waaraan je later deelneemt."; +"textRules.archive.title" = "Onlangs geblokkeerd"; +"textRules.archive.empty" = "Geen verborgen berichten"; +"textRules.archive.footer" = "De laatste %d verborgen berichten worden op dit apparaat bewaard. Ze zijn niet in de app-data back-up opgenomen."; +"textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; +"textRules.archive.rule" = "Regel"; +"textRules.archive.chat" = "Gesprek"; +"textRules.archive.myNode" = "Mijn knooppunt"; +"textRules.archive.time" = "Tijd"; +"textRules.archive.unknownConversation" = "Onbekend gesprek"; +"textRules.archive.unknownRadio" = "Onbekende radio"; + +"radioCleanup.title" = "Opruimen"; +"radioCleanup.running" = "Gegevens van de radio verwijderen"; +"radioCleanup.failed" = "Verborgen berichten van deze radio staan mogelijk nog op deze installatie."; +"radioCleanup.completed" = "Gegevens van de radio verwijderd"; +"radioCleanup.retryAccessibility" = "Probeer het opruimen van de radio opnieuw voor %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ @@ -1978,7 +2119,7 @@ "settings.backup.export.alert.title" = "Beveiligingsmelding"; /* Export confirmation alert message */ -"settings.backup.export.alert.message" = "Deze back-up bevat kanaalversleutelingssleutels, de berichtgeschiedenis, je contactenlijst en het lokale netwerkadres en de poort van de WiFi-node. Bewaar het geëxporteerde bestand veilig."; +"settings.backup.export.alert.message" = "Deze back-up bevat kanaalversleutelingssleutels, de berichtgeschiedenis, je contactenlijst en het lokale netwerkadres en de poort van de WiFi-node. De back-up kan ook vastgelegde gps-coördinaten van radio's bevatten. Bewaar het geëxporteerde bestand veilig."; /* Export confirmation alert export button */ "settings.backup.export.alert.export" = "Exporteren"; diff --git a/MC1/Resources/Localization/nl.lproj/WhatsNew.strings b/MC1/Resources/Localization/nl.lproj/WhatsNew.strings index 73a2c97889..b4211cf9e5 100644 --- a/MC1/Resources/Localization/nl.lproj/WhatsNew.strings +++ b/MC1/Resources/Localization/nl.lproj/WhatsNew.strings @@ -65,3 +65,23 @@ "whatsNew.moreChanges.title" = "Meer wijzigingen"; /* What's New v1.6 - More changes, description */ "whatsNew.moreChanges.description" = "Tik op \"Bekijk alle nieuwe wijzigingen\" hieronder om de volledige lijst met opgeloste fouten en andere functies te zien."; + +/* What's New v1.7 - Direct messages, title */ +"whatsNew.directMessages.title" = "Directe berichten"; +/* What's New v1.7 - Direct messages, description */ +"whatsNew.directMessages.description" = "Directe berichten proberen het pad nu 4 keer en doen daarna 4 Flood-pogingen. Wijzig Pogingen op het pad, Flood-pogingen en Terugval op flood-routing in Geavanceerde instellingen."; + +/* What's New v1.7 - Blocks and filters, title */ +"whatsNew.blocksAndFilters.title" = "Blokkering en filters"; +/* What's New v1.7 - Blocks and filters, description */ +"whatsNew.blocksAndFilters.description" = "Verberg berichten die overeenkomen met een woord of tekst. Een regel kan zoeken in het bericht, de naam van de afzender of beide, en je kiest voor welke chats die geldt. Verborgen berichten kun je zien in Onlangs geblokkeerd onder Instellingen > Blokkering en filters."; + +/* What's New v1.7 - Node telemetry, title */ +"whatsNew.nodeTelemetry.title" = "Knooppunttelemetrie"; +/* What's New v1.7 - Node telemetry, description */ +"whatsNew.nodeTelemetry.description" = "Instellingen > Apparaatinfo toont de telemetrie van het knooppunt waarmee je verbonden bent."; + +/* What's New v1.7 - Live Activity, title */ +"whatsNew.liveActivity.title" = "Live Activity"; +/* What's New v1.7 - Live Activity, description */ +"whatsNew.liveActivity.description" = "Ongelezen berichten vallen meer op en de snelheid in pakketten per minuut is makkelijker te begrijpen."; diff --git a/MC1/Resources/Localization/pl.lproj/Chats.strings b/MC1/Resources/Localization/pl.lproj/Chats.strings index 7924b85a27..06d6dc8ad9 100644 --- a/MC1/Resources/Localization/pl.lproj/Chats.strings +++ b/MC1/Resources/Localization/pl.lproj/Chats.strings @@ -583,6 +583,12 @@ /* Location: UnifiedMessageBubble.swift - VoiceOver prefix when the visible body is a translation - %@ is the translated text */ "chats.message.translatedAccessibility" = "Przetłumaczono: %@"; +/* Location: MessageVisibleBody.swift - VoiceOver prefix when the visible body is an MECP reading - %@ is the reading */ +"chats.message.readingAccessibility" = "Odczyt: %@"; + +/* Location: MECPCatalog - Person count line in an MECP reading */ +"chats.message.mecpPersonCount" = "%lld osoby"; + /* Location: UnifiedMessageBubble.swift - Context menu action to view repeat details */ "chats.message.action.repeatDetails" = "Szczegóły powtórzeń"; @@ -636,6 +642,9 @@ /* Location: UnifiedMessageBubble.swift - Context menu text showing SNR - %@ is formatted value */ "chats.message.info.snr" = "SNR: %@"; +/* Location: ActionsDetailsSection.swift - Stored MECP wire string under SNR. %@ is the original text */ +"chats.message.info.mecp" = "MECP: %@"; + /* Location: MessageActionsSheet.swift - Context menu text showing the radio region the message was flooded under - %@ is region name. "Flooded" is a domain term for mesh-broadcast across all nodes in a radio region. */ "chats.message.info.floodedUnder" = "Region: %@"; @@ -1141,8 +1150,8 @@ /* Location: ConversationRow.swift - Purpose: Mentions-only indicator */ "chats.row.mentionsOnly" = "Tylko wzmianki"; -/* TODO: translate - Accessibility label for the row actions menu */ -"chats.row.actionsMenu.accessibilityLabel" = "Conversation actions"; +/* Accessibility label for the row actions menu */ +"chats.row.actionsMenu.accessibilityLabel" = "Akcje rozmowy"; // MARK: - Reactions diff --git a/MC1/Resources/Localization/pl.lproj/Chats.stringsdict b/MC1/Resources/Localization/pl.lproj/Chats.stringsdict new file mode 100644 index 0000000000..c7ed43aa20 --- /dev/null +++ b/MC1/Resources/Localization/pl.lproj/Chats.stringsdict @@ -0,0 +1,26 @@ + + + + + chats.message.mecpPersonCount + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + lld + one + %lld osoba + few + %lld osoby + many + %lld osób + other + %lld osoby + + + + diff --git a/MC1/Resources/Localization/pl.lproj/Contacts.strings b/MC1/Resources/Localization/pl.lproj/Contacts.strings index 489850b7fc..8460a483c9 100644 --- a/MC1/Resources/Localization/pl.lproj/Contacts.strings +++ b/MC1/Resources/Localization/pl.lproj/Contacts.strings @@ -44,6 +44,8 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Pokój"; +"contacts.nodeKind.sensor" = "Czujnik"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Odkryty"; @@ -75,6 +77,8 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Pokoje"; +"contacts.segment.sensors" = "Czujniki"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "Filtruj węzły"; @@ -168,9 +172,13 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "Brak pokoi"; +"contacts.list.empty.sensors.title" = "Brak czujników"; + /* Location: ContactsListView.swift - Purpose: No rooms empty description */ "contacts.list.empty.rooms.description" = "Pokoje to publiczne serwery czatu w sieci mesh. Pojawią się tutaj po wykryciu."; +"contacts.list.empty.sensors.description" = "Czujniki pojawią się tutaj po wykryciu w sieci mesh."; + /* Location: ContactsListView.swift - Purpose: No search results title */ "contacts.list.empty.search.title" = "Brak wyników"; @@ -623,6 +631,8 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter - Rooms */ "contacts.discovery.segment.rooms" = "Pokoje"; +"contacts.discovery.segment.sensors" = "Czujniki"; + /* Location: DiscoverSegmentPicker.swift - Purpose: VoiceOver label for the Discovery segment filter picker (iOS 18 fallback) */ "contacts.discovery.segment.pickerLabel" = "Filtruj odkryte węzły"; diff --git a/MC1/Resources/Localization/pl.lproj/Localizable.strings b/MC1/Resources/Localization/pl.lproj/Localizable.strings index 8e03bb4a5c..9ee2a3f37b 100644 --- a/MC1/Resources/Localization/pl.lproj/Localizable.strings +++ b/MC1/Resources/Localization/pl.lproj/Localizable.strings @@ -135,6 +135,8 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "Odkryto nowy pokój"; +"notifications.discovery.sensor" = "Odkryto nowy czujnik"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -498,6 +500,14 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Nieprawidłowa odpowiedź zdalnego węzła"; +"error.remoteNode.sensorOutcomeUnknown" = "Nie udało się zweryfikować zmiany. Odśwież ustawienia przed ponownym zapisaniem."; + +"error.remoteNode.sensorSettingRejected" = "Czujnik odrzucił to ustawienie."; + +"error.remoteNode.invalidSensorSetting" = "Użyj niepustego klucza i niepustej wartości bez białych znaków. Całe polecenie musi zmieścić się w 160 bajtach UTF-8."; + +"error.remoteNode.invalidPasswordLength" = "Hasła nie mogą mieć więcej niż %d bajtów UTF-8."; + /* Location: RemoteNodeError+UserFacingMessage.swift - Remote node rejected the operation */ "error.remoteNode.permissionDenied" = "Odmowa dostępu"; diff --git a/MC1/Resources/Localization/pl.lproj/Map.strings b/MC1/Resources/Localization/pl.lproj/Map.strings index 2b1c0ef887..788c4b7411 100644 --- a/MC1/Resources/Localization/pl.lproj/Map.strings +++ b/MC1/Resources/Localization/pl.lproj/Map.strings @@ -40,6 +40,8 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Filtr"; +"map.controls.contactsAndSensors" = "Kontakty i czujniki"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Filtry aktywne"; @@ -264,6 +266,8 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Pokój"; +"map.nodeKind.sensor" = "Czujnik"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -281,6 +285,8 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Pokój"; +"map.callout.nodeKind.sensor" = "Czujnik"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "Dodaj"; diff --git a/MC1/Resources/Localization/pl.lproj/Onboarding.strings b/MC1/Resources/Localization/pl.lproj/Onboarding.strings index cf24de7a0d..32147f1346 100644 --- a/MC1/Resources/Localization/pl.lproj/Onboarding.strings +++ b/MC1/Resources/Localization/pl.lproj/Onboarding.strings @@ -69,6 +69,9 @@ /* Location: DeviceScanView.swift - Subtitle with pairing instructions */ "deviceScan.subtitle" = "Włącz radio, odłącz je od wszystkich innych aplikacji i urządzeń, a następnie dotknij Dodaj urządzenie."; +/* Location: DeviceScanView.swift - Subtitle while bond-loss recovery is re-pairing */ +"deviceScan.rePairingSubtitle" = "Włącz radio i odłącz je od wszystkich innych aplikacji i urządzeń."; + /* Location: DeviceScanView.swift - Message shown when device is already paired */ "deviceScan.alreadyPaired" = "Twoje urządzenie jest już sparowane"; @@ -78,9 +81,6 @@ /* Location: DeviceScanView.swift - Button to continue after pairing */ "deviceScan.continue" = "Kontynuuj"; -/* Location: DeviceScanView.swift - Button label while connecting */ -"deviceScan.connecting" = "Łączenie..."; - /* Location: DeviceScanView.swift - Button to connect simulator (debug) */ "deviceScan.connectSimulator" = "Połącz symulator"; diff --git a/MC1/Resources/Localization/pl.lproj/RemoteNodes.strings b/MC1/Resources/Localization/pl.lproj/RemoteNodes.strings index 5aa84ff4c8..560c60dd12 100644 --- a/MC1/Resources/Localization/pl.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/pl.lproj/RemoteNodes.strings @@ -32,6 +32,8 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Przekaźnik"; +"remoteNodes.auth.typeSensor" = "Czujnik"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Uwierzytelnianie"; @@ -62,10 +64,18 @@ /* Location: NodeAuthenticationSheet.swift - Flood routing toggle */ "remoteNodes.auth.floodRouting" = "Routing flood"; "remoteNodes.auth.floodRetryStatus" = "Brak odpowiedzi znaną trasą. Ponawianie z routingiem flood."; -"remoteNodes.auth.floodFooter" = "Routing flood jest wolniejszy i zużywa więcej czasu antenowego sieci. Użyj go, gdy znana trasa nie działa w Twojej obecnej lokalizacji. Po zalogowaniu nowa trasa zostanie zapamiętana automatycznie."; +/* Footer when this sign-in will clear the saved route and use flood */ +"remoteNodes.auth.floodFooter" = "To logowanie usuwa zapisaną trasę i używa routingu flood. Routing flood jest wolniejszy i zużywa więcej czasu antenowego sieci. Nowa trasa zostanie zapamiętana, jeśli logowanie się powiedzie."; + +/* Footer after this sign-in has cleared the saved route */ +"remoteNodes.auth.floodFooterCleared" = "Zapisana trasa została usunięta. Logowanie używa routingu flood. Nowa trasa zostanie zapamiętana, jeśli logowanie się powiedzie."; + + +/* Footer when a timeout clears the route and retries by flood */ +"remoteNodes.auth.pathFooter" = "Jeśli brak odpowiedzi, trasa zostanie usunięta, a logowanie spróbuje raz routingiem flood."; -/* Location: NodeAuthenticationSheet.swift - Path section footer when stored path exists */ -"remoteNodes.auth.pathFooter" = "Użyj znanej trasy do tego węzła lub przełącz na routing flood, aby sieć sama znalazła ścieżkę."; +/* Footer when a timeout stops and leaves the route */ +"remoteNodes.auth.pathFooterKept" = "Jeśli brak odpowiedzi, logowanie się zatrzyma, a trasa pozostanie."; /* Location: NodeAuthenticationSheet.swift - Path hop whose repeater is not known */ "remoteNodes.auth.pathHopUnknown" = ""; @@ -84,6 +94,26 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Ustawienia przekaźnika"; +"remoteNodes.sensor.adminRequired" = "Zarządzanie czujnikiem wymaga dostępu administratora."; + +"remoteNodes.sensor.saved" = "Ustawienie zweryfikowane."; + +"remoteNodes.sensor.rebootSent" = "Polecenie ponownego uruchomienia wysłane. Czujnik nie potwierdził ponownego uruchomienia. Zaloguj się ponownie, zanim wyślesz kolejne polecenia."; + +"remoteNodes.sensor.rebootConfirmation" = "Wysłać polecenie ponownego uruchomienia do tego czujnika?"; + +"remoteNodes.sensor.runtimeOnly" = "Zmiany dotyczą działającego czujnika. To, czy zostaną zachowane po ponownym uruchomieniu, zależy od jego firmware'u."; + +"remoteNodes.sensor.value" = "Wartość"; + +"remoteNodes.sensor.save" = "Zapisz"; + +"remoteNodes.sensor.reload" = "Odśwież"; + +"remoteNodes.sensor.empty" = "Ten czujnik nie udostępnia żadnych ustawień."; + +"remoteNodes.sensor.title" = "Zarządzanie czujnikiem"; + /* Location: RepeaterSettingsView.swift - Done button (used in multiple places) */ "remoteNodes.settings.done" = "Gotowe"; diff --git a/MC1/Resources/Localization/pl.lproj/Settings.strings b/MC1/Resources/Localization/pl.lproj/Settings.strings index 2cef662aa7..3dfce5505a 100644 --- a/MC1/Resources/Localization/pl.lproj/Settings.strings +++ b/MC1/Resources/Localization/pl.lproj/Settings.strings @@ -46,9 +46,6 @@ /* Section header for device information */ "device.header" = "Urządzenie"; -/* Status shown when device is connected */ -"device.connected" = "Połączono"; - /* Footer shown when no device is connected */ "device.noDeviceConnected" = "Brak połączonego urządzenia MeshCore"; @@ -60,12 +57,6 @@ /* Navigation title for device info screen */ "deviceInfo.title" = "Informacje o urządzeniu"; -/* Section header for connection status */ -"deviceInfo.connection.header" = "Połączenie"; - -/* Label for connection status */ -"deviceInfo.connection.status" = "Status"; - /* Section header for power and storage */ "deviceInfo.powerStorage.header" = "Zasilanie i pamięć"; @@ -111,6 +102,12 @@ /* Firmware version fallback format when no version string is reported - %@ is the numeric version code */ "deviceInfo.firmwareVersionFormat" = "v%@"; +/* Heading above retained telemetry after a Device Info reload fails */ +"deviceInfo.lastSuccessfulReading" = "Ostatni udany odczyt"; + +/* Section header for Device Info telemetry */ +"deviceInfo.telemetry.header" = "Telemetria węzła"; + /* Section header for identity information */ /* Label for public key */ "deviceInfo.publicKey" = "Klucz publiczny"; @@ -165,6 +162,9 @@ /* Button to scan for Bluetooth devices */ "deviceSelection.scanBluetooth" = "Skanuj urządzenie Bluetooth"; +/* Button title while this radio is being paired again */ +"deviceSelection.rePairing" = "Ponowne parowanie..."; + /* Trailing control on a previously paired row that still needs iPhone setup */ /* AI-translated - please verify with native speakers. */ "deviceSelection.setup" = "Skonfiguruj"; @@ -746,6 +746,21 @@ /* Alert message for clear logs */ "diagnostics.alert.clear.message" = "Spowoduje to usunięcie wszystkich przechowywanych logów debugowania. Wyeksportowane pliki logów nie zostaną usunięte."; +/* Toggle to enable collecting local debug logs */ +"diagnostics.collectLogs" = "Zbieraj logi debugowania"; + +/* Footer shown when debug log collection is off */ +"diagnostics.footer.disabled" = "Lokalne logi debugowania nie są zbierane."; + +/* Alert title for disabling collection */ +"diagnostics.alert.disable.title" = "Wyłącz zbieranie"; + +/* Button to confirm disabling collection */ +"diagnostics.alert.disable.confirm" = "Wyłącz zbieranie"; + +/* Alert message for disabling collection */ +"diagnostics.alert.disable.message" = "Spowoduje to usunięcie wszystkich przechowywanych logów debugowania i zaprzestanie ich zbierania. Wyeksportowane pliki logów nie zostaną usunięte."; + /* Error when export fails */ "diagnostics.error.exportFailed" = "Nie udało się utworzyć pliku eksportu"; @@ -754,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Czaty"; +"blocksAndFilters.title" = "Blokowanie i filtry"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -822,6 +839,8 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Towarzysz"; +"notifications.discoveryCompanionsAndSensors" = "Towarzysze i czujniki"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Przekaźnik"; @@ -983,6 +1002,9 @@ /* Editor footer when the password is too long */ "radioWiFi.editor.passwordLength" = "Hasło może mieć do 63 bajtów."; +/* Editor footer when a credential contains a character the firmware cannot store */ +"radioWiFi.editor.unsupportedCharacter" = "Nazwa sieci lub hasło zawiera znak, którego to radio nie może zapisać."; + /* Button that clears the radio's saved WiFi settings */ "radioWiFi.clear" = "Wyczyść ustawienia WiFi"; @@ -1148,6 +1170,35 @@ /* Footer explaining the acknowledgments setting */ "directMessages.footer" = "Liczba potwierdzeń wysyłanych na wiadomość bezpośrednią. Użyj 2 dla lepszego potwierdzenia dostarczenia przez zawodne łącza."; +/* Switch that clears the known route after the path attempts */ +"directMessages.fallback" = "Zapasowo na routing flood"; + +/* Picker label for attempts on the known route */ +"directMessages.directAttempts" = "Próby na ścieżce"; + +/* Picker label for attempts sent by flood after the route is cleared */ +"directMessages.floodAttempts" = "Próby flood"; + +/* Footer when Fall Back to Flood is on */ +"directMessages.attemptsFooterOn" = "Gdy skończą się Próby na ścieżce, trasa zostanie usunięta. Próby flood są potem wysyłane routingiem flood. Wiadomość do kontaktu, który nie ma znanej trasy, jest wysyłana routingiem flood."; + +/* Footer when Fall Back to Flood is off */ +"directMessages.attemptsFooterOff" = "Próby na ścieżce zostają na znanej trasie, a trasa nie jest usuwana. Wiadomość do kontaktu, który nie ma znanej trasy, jest wysyłana routingiem flood."; + +// MARK: - Path Fallback + +/* Section header for sign-in, command, and contact telemetry path fallback */ +"pathFallback.header" = "Zapasowe przełączenie ścieżki"; + +/* Switch that clears the known route after a timeout */ +"pathFallback.fallback" = "Zapasowo na routing flood"; + +/* Footer when path fallback is on */ +"pathFallback.footerOn" = "Logowanie, polecenia do przekaźnika i pokoju, które czekają na odpowiedź, oraz telemetria kontaktu używają znanej trasy. Jeśli brak odpowiedzi, trasa zostanie usunięta i nastąpi jedna próba routingiem flood."; + +/* Footer when path fallback is off */ +"pathFallback.footerOff" = "Logowanie, polecenia i telemetria kontaktu zostają na znanej trasie. Jeśli brak odpowiedzi, zatrzymują się, a trasa pozostaje. Routing flood na ekranie logowania usuwa zapisaną trasę tego węzła."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ @@ -1162,12 +1213,24 @@ /* Menu item to disconnect from the current device */ "bleStatus.disconnect" = "Rozłącz"; +/* Menu item to stop automatic reconnection until another explicit connection */ +"bleStatus.stopReconnecting" = "Zatrzymaj ponowne łączenie"; + +/* Menu item to cancel the current connection request */ +"bleStatus.cancelConnection" = "Anuluj połączenie"; + /* Status shown when device is disconnected */ "bleStatus.status.disconnected" = "Rozłączono"; /* Status shown when device is connecting */ "bleStatus.status.connecting" = "Łączenie..."; +/* Status shown while reconnecting to the selected device */ +"bleStatus.status.reconnecting" = "Ponowne łączenie..."; + +/* Status shown while automatic reconnection remains enabled between attempts */ +"bleStatus.status.waitingToReconnect" = "Oczekiwanie na ponowne połączenie"; + /* Status shown when device is connected but not ready */ "bleStatus.status.connected" = "Połączono"; @@ -1180,6 +1243,9 @@ /* Accessibility label for BLE status indicator */ "bleStatus.accessibilityLabel" = "Status połączenia Bluetooth"; +/* TODO: translate - Accessibility text combining a descriptive prefix and connection state or context; arguments may themselves contain a radio name and status */ +"bleStatus.accessibilityValue" = "%1$@, %2$@"; + /* Accessibility hint when disconnected */ "bleStatus.accessibilityHint.disconnected" = "Stuknij dwukrotnie, aby połączyć urządzenie"; @@ -1318,6 +1384,24 @@ /* Import failed after one or more settings were already written; %@ is the underlying error message */ "configImport.failedPartial" = "%@ Część ustawień mogła już zostać zapisana na urządzeniu. Sprawdź konfigurację urządzenia."; +/* Interrupted identity import recovery */ +"configImport.identityOutcomeUnknown" = "Połączenie zostało przerwane podczas importowania tożsamości na %@. Tożsamość radia mogła się zmienić. Import konfiguracji nie został ukończony."; + +/* Interrupted identity import recovery */ +"configImport.retryIdentityImport" = "Ponów import tożsamości"; + +/* Interrupted identity import recovery */ +"configImport.confirmIdentityRecovery" = "To zastąpi tożsamość radia dostępnego pod %@ przy użyciu klucza prywatnego z wybranego pliku. Import konfiguracji nie będzie kontynuowany."; + +/* Confirmation alert title when retrying an interrupted identity import */ +"configImport.confirmTitleIdentityRecovery" = "Zastąpić tożsamość radia?"; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryComplete" = "Tożsamość została ponownie zastosowana. Import konfiguracji nie został ukończony. Zaimportuj plik ponownie, aby zastosować pozostałe ustawienia."; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryKeyRequired" = "Wybierz plik konfiguracji zawierający klucz prywatny, aby ponowić import tożsamości."; + /* Import success */ "configImport.importSuccess" = "Konfiguracja zaimportowana pomyślnie"; @@ -1434,6 +1518,63 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "Wyświetlanie miniatur mapy pobiera kafelki dla współrzędnych z serwera zewnętrznego, co może ujawnić Twój adres IP."; +// MARK: - Text Rules + +"textRules.rules" = "Reguły filtrowania"; +"textRules.empty" = "Brak reguł filtrowania"; +"textRules.loading" = "Ładowanie reguł filtrowania…"; +"textRules.loadFailed" = "Nie udało się załadować reguł filtrowania. Nowe wiadomości nie będą ich używać, dopóki reguły nie zostaną załadowane."; +"textRules.retryAccessibility" = "Spróbuj ponownie załadować reguły filtrowania"; +"textRules.saveFailed" = "Nie udało się zapisać reguł filtrowania. Spróbuj ponownie."; +"textRules.new.title" = "Nowa reguła"; +"textRules.new.phrase" = "Słowo lub tekst"; +"textRules.new.lookIn" = "Szukaj w"; +"textRules.new.match" = "Dopasowanie"; +"textRules.new.containsMessageFooter" = "Pasuje w dowolnym miejscu wiadomości, także wewnątrz słowa."; +"textRules.new.wholeMessageFooter" = "Pasuje tylko wtedy, gdy cała wiadomość jest tym tekstem."; +"textRules.new.containsSenderFooter" = "Pasuje w dowolnym miejscu nazwy nadawcy, także wewnątrz słowa. Reakcje od tego nadawcy są też ukryte."; +"textRules.new.wholeNameFooter" = "Pasuje tylko wtedy, gdy nazwa nadawcy jest dokładnie tym tekstem. Reakcje od tego nadawcy są też ukryte."; +"textRules.new.containsMessageOrSenderFooter" = "Pasuje w dowolnym miejscu wiadomości lub nazwy nadawcy, także wewnątrz słowa. Reakcje od pasującego nadawcy są też ukryte."; +"textRules.new.wholeMessageOrSenderFooter" = "Pasuje tylko wtedy, gdy cała wiadomość lub cała nazwa nadawcy jest tym tekstem. Reakcje od pasującego nadawcy są też ukryte."; +"textRules.field.message" = "Wiadomość"; +"textRules.field.sender" = "Nadawca"; +"textRules.field.messageOrSender" = "Wiadomość lub nadawca"; +"textRules.match.contains" = "Zawiera"; +"textRules.match.wholeMessage" = "Cała wiadomość"; +"textRules.match.wholeName" = "Cała nazwa"; +"textRules.match.wholeField" = "Całe pole"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Używaj reguł dla"; +"textRules.types.footer" = "Włączenie obejmuje wszystkie czaty tego typu, w tym te, do których dołączysz później."; +"textRules.types.publicChannel" = "Publiczny"; +"textRules.types.hashtagChannel" = "Kanały hashtagowe"; +"textRules.types.privateChannel" = "Kanały prywatne"; +"textRules.selection.all" = "Wszystkie"; +"textRules.selection.none" = "Żadne"; +"textRules.selection.count" = "%d Czaty"; +"textRules.selection.accessibilityChats" = "Czaty dla %@"; +"textRules.selection.footer" = "Wszystkie obejmują czaty, do których dołączysz później."; +"textRules.archive.title" = "Ostatnio zablokowane"; +"textRules.archive.empty" = "Brak ukrytych wiadomości"; +"textRules.archive.footer" = "To urządzenie przechowuje %d najnowszych ukrytych wiadomości. Kopia zapasowa danych aplikacji ich nie obejmuje."; +"textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; +"textRules.archive.rule" = "Reguła"; +"textRules.archive.chat" = "Czat"; +"textRules.archive.myNode" = "Mój węzeł"; +"textRules.archive.time" = "Czas"; +"textRules.archive.unknownConversation" = "Nieznana rozmowa"; +"textRules.archive.unknownRadio" = "Nieznane radio"; + +"radioCleanup.title" = "Czyszczenie"; +"radioCleanup.running" = "Usuwanie danych radia"; +"radioCleanup.failed" = "Ukryte wiadomości z tego radia mogą nadal być w tej instalacji."; +"radioCleanup.completed" = "Dane radia usunięte"; +"radioCleanup.retryAccessibility" = "Spróbuj ponownie wyczyścić radio dla %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ @@ -1978,7 +2119,7 @@ "settings.backup.export.alert.title" = "Informacja o bezpieczeństwie"; /* Export confirmation alert message */ -"settings.backup.export.alert.message" = "Ta kopia zapasowa zawiera klucze szyfrowania kanałów, historię wiadomości, listę kontaktów oraz lokalny adres sieciowy i port węzła WiFi. Przechowuj wyeksportowany plik w bezpiecznym miejscu."; +"settings.backup.export.alert.message" = "Ta kopia zapasowa zawiera klucze szyfrowania kanałów, historię wiadomości, listę kontaktów oraz lokalny adres sieciowy i port węzła WiFi. Kopia zapasowa może również zawierać zapisane współrzędne GPS radiotelefonów. Przechowuj wyeksportowany plik w bezpiecznym miejscu."; /* Export confirmation alert export button */ "settings.backup.export.alert.export" = "Eksportuj"; diff --git a/MC1/Resources/Localization/pl.lproj/WhatsNew.strings b/MC1/Resources/Localization/pl.lproj/WhatsNew.strings index 817428cb28..14ce4d7e07 100644 --- a/MC1/Resources/Localization/pl.lproj/WhatsNew.strings +++ b/MC1/Resources/Localization/pl.lproj/WhatsNew.strings @@ -65,3 +65,23 @@ "whatsNew.moreChanges.title" = "Więcej zmian"; /* What's New v1.6 - More changes, description */ "whatsNew.moreChanges.description" = "Stuknij \"Zobacz wszystkie nowe zmiany\" poniżej, aby zobaczyć pełną listę poprawek błędów i innych funkcji."; + +/* What's New v1.7 - Direct messages, title */ +"whatsNew.directMessages.title" = "Wiadomości bezpośrednie"; +/* What's New v1.7 - Direct messages, description */ +"whatsNew.directMessages.description" = "Wiadomości bezpośrednie wykonują teraz 4 próby na ścieżce, a potem 4 próby flood. Zmień Próby na ścieżce, Próby flood i Zapasowo na routing flood w Ustawieniach zaawansowanych."; + +/* What's New v1.7 - Blocks and filters, title */ +"whatsNew.blocksAndFilters.title" = "Blokowanie i filtry"; +/* What's New v1.7 - Blocks and filters, description */ +"whatsNew.blocksAndFilters.description" = "Możesz ukrywać wiadomości, które pasują do słowa lub tekstu. Reguła może szukać w polu Wiadomość, w polu Nadawca albo w obu polach, a Ty wybierasz, których czatów dotyczy. Ukryte wiadomości możesz zobaczyć w Ostatnio zablokowane w Ustawienia > Blokowanie i filtry."; + +/* What's New v1.7 - Node telemetry, title */ +"whatsNew.nodeTelemetry.title" = "Telemetria węzła"; +/* What's New v1.7 - Node telemetry, description */ +"whatsNew.nodeTelemetry.description" = "Ustawienia > Informacje o urządzeniu pokazują telemetrię z węzła, z którym masz połączenie."; + +/* What's New v1.7 - Live Activity, title */ +"whatsNew.liveActivity.title" = "Aktywność na żywo"; +/* What's New v1.7 - Live Activity, description */ +"whatsNew.liveActivity.description" = "Nieprzeczytane wiadomości są bardziej widoczne, a tempo pakietów na minutę jest łatwiejsze do zrozumienia."; diff --git a/MC1/Resources/Localization/pt.lproj/Chats.strings b/MC1/Resources/Localization/pt.lproj/Chats.strings index e924323a30..5fe68f006e 100644 --- a/MC1/Resources/Localization/pt.lproj/Chats.strings +++ b/MC1/Resources/Localization/pt.lproj/Chats.strings @@ -338,8 +338,8 @@ /* Location: MutedIndicator.swift - Accessibility label for mentions-only indicator */ "chats.row.mentionsOnly" = "Só menções"; -/* TODO: translate - Accessibility label for the row actions menu */ -"chats.row.actionsMenu.accessibilityLabel" = "Conversation actions"; +/* Accessibility label for the row actions menu */ +"chats.row.actionsMenu.accessibilityLabel" = "Ações da conversa"; // MARK: - Notification Level Picker @@ -620,6 +620,12 @@ /* Location: UnifiedMessageBubble.swift - VoiceOver prefix when the visible body is a translation - %@ is the translated text */ "chats.message.translatedAccessibility" = "Traduzido: %@"; +/* Location: MessageVisibleBody.swift - VoiceOver prefix when the visible body is an MECP reading - %@ is the reading */ +"chats.message.readingAccessibility" = "Leitura: %@"; + +/* Location: MECPCatalog - Person count line in an MECP reading */ +"chats.message.mecpPersonCount" = "%lld pessoas"; + /* Location: UnifiedMessageBubble.swift - Context menu action to view repeat details */ "chats.message.action.repeatDetails" = "Detalhes da retransmissão"; @@ -673,6 +679,9 @@ /* Location: UnifiedMessageBubble.swift - Context menu text showing SNR - %@ is formatted value */ "chats.message.info.snr" = "SNR: %@"; +/* Location: ActionsDetailsSection.swift - Stored MECP wire string under SNR. %@ is the original text */ +"chats.message.info.mecp" = "MECP: %@"; + /* Location: MessageActionsSheet.swift - Details row showing the radio region a flood-routed message was broadcast under - %@ is region name */ "chats.message.info.floodedUnder" = "Região: %@"; diff --git a/MC1/Resources/Localization/pt.lproj/Chats.stringsdict b/MC1/Resources/Localization/pt.lproj/Chats.stringsdict new file mode 100644 index 0000000000..7896e8bd63 --- /dev/null +++ b/MC1/Resources/Localization/pt.lproj/Chats.stringsdict @@ -0,0 +1,22 @@ + + + + + chats.message.mecpPersonCount + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + lld + one + %lld pessoa + other + %lld pessoas + + + + diff --git a/MC1/Resources/Localization/pt.lproj/Contacts.strings b/MC1/Resources/Localization/pt.lproj/Contacts.strings index 0ad38afff9..89f9e177b7 100644 --- a/MC1/Resources/Localization/pt.lproj/Contacts.strings +++ b/MC1/Resources/Localization/pt.lproj/Contacts.strings @@ -44,6 +44,8 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Sala"; +"contacts.nodeKind.sensor" = "Sensor"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Descoberto"; @@ -75,6 +77,8 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Salas"; +"contacts.segment.sensors" = "Sensores"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "Filtrar nós"; @@ -168,9 +172,13 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "Nenhuma sala"; +"contacts.list.empty.sensors.title" = "Nenhum sensor"; + /* Location: ContactsListView.swift - Purpose: No rooms empty description */ "contacts.list.empty.rooms.description" = "As salas são servidores de chat públicos na mesh. Aparecem aqui quando forem descobertas."; +"contacts.list.empty.sensors.description" = "Os sensores aparecem aqui quando forem descobertos na mesh."; + /* Location: ContactsListView.swift - Purpose: No search results title */ "contacts.list.empty.search.title" = "Nenhum resultado"; @@ -623,6 +631,8 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter: Rooms */ "contacts.discovery.segment.rooms" = "Salas"; +"contacts.discovery.segment.sensors" = "Sensores"; + /* Location: DiscoverSegmentPicker.swift - Purpose: VoiceOver label for the Discovery segment filter picker (iOS 18 fallback) */ "contacts.discovery.segment.pickerLabel" = "Filtrar nós descobertos"; diff --git a/MC1/Resources/Localization/pt.lproj/Localizable.strings b/MC1/Resources/Localization/pt.lproj/Localizable.strings index 07e43f5993..3523b0108b 100644 --- a/MC1/Resources/Localization/pt.lproj/Localizable.strings +++ b/MC1/Resources/Localization/pt.lproj/Localizable.strings @@ -150,6 +150,8 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "Nova sala descoberta"; +"notifications.discovery.sensor" = "Novo sensor descoberto"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -495,6 +497,14 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Resposta inválida do nó remoto"; +"error.remoteNode.sensorOutcomeUnknown" = "Não foi possível verificar a alteração. Recarregue as definições antes de guardar novamente."; + +"error.remoteNode.sensorSettingRejected" = "O sensor rejeitou esta definição."; + +"error.remoteNode.invalidSensorSetting" = "Use uma chave e um valor não vazios sem espaços em branco. O comando completo tem de caber em 160 bytes UTF-8."; + +"error.remoteNode.invalidPasswordLength" = "As palavras-passe não podem ter mais de %d bytes UTF-8."; + /* Location: RemoteNodeError+UserFacingMessage.swift - Remote node rejected the operation */ "error.remoteNode.permissionDenied" = "Permissão recusada"; diff --git a/MC1/Resources/Localization/pt.lproj/Map.strings b/MC1/Resources/Localization/pt.lproj/Map.strings index 96ca477f68..35c0c4ecd0 100644 --- a/MC1/Resources/Localization/pt.lproj/Map.strings +++ b/MC1/Resources/Localization/pt.lproj/Map.strings @@ -37,6 +37,8 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Filtrar"; +"map.controls.contactsAndSensors" = "Contactos e sensores"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Filtros ativos"; @@ -261,6 +263,8 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Sala"; +"map.nodeKind.sensor" = "Sensor"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -278,6 +282,8 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Sala"; +"map.callout.nodeKind.sensor" = "Sensor"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "Adicionar"; diff --git a/MC1/Resources/Localization/pt.lproj/Onboarding.strings b/MC1/Resources/Localization/pt.lproj/Onboarding.strings index dc2239b295..7904f39cd5 100644 --- a/MC1/Resources/Localization/pt.lproj/Onboarding.strings +++ b/MC1/Resources/Localization/pt.lproj/Onboarding.strings @@ -69,6 +69,9 @@ /* Location: DeviceScanView.swift - Subtitle with pairing instructions */ "deviceScan.subtitle" = "Ligue o rádio, desemparelhe-o de todas as outras apps e dispositivos e toque em Adicionar dispositivo."; +/* Location: DeviceScanView.swift - Subtitle while bond-loss recovery is re-pairing */ +"deviceScan.rePairingSubtitle" = "Ligue o rádio e desemparelhe-o de todas as outras apps e dispositivos."; + /* Location: DeviceScanView.swift - Message shown when device is already paired */ "deviceScan.alreadyPaired" = "O dispositivo já está emparelhado"; @@ -78,9 +81,6 @@ /* Location: DeviceScanView.swift - Button to continue after pairing */ "deviceScan.continue" = "Continuar"; -/* Location: DeviceScanView.swift - Button label while connecting */ -"deviceScan.connecting" = "A ligar..."; - /* Location: DeviceScanView.swift - Button to connect simulator (debug) */ "deviceScan.connectSimulator" = "Ligar simulador"; diff --git a/MC1/Resources/Localization/pt.lproj/RemoteNodes.strings b/MC1/Resources/Localization/pt.lproj/RemoteNodes.strings index 862457a4c7..552f4d40af 100644 --- a/MC1/Resources/Localization/pt.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/pt.lproj/RemoteNodes.strings @@ -32,6 +32,8 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Repetidor"; +"remoteNodes.auth.typeSensor" = "Sensor"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Autenticação"; @@ -62,10 +64,18 @@ /* Location: NodeAuthenticationSheet.swift - Flood routing toggle */ "remoteNodes.auth.floodRouting" = "Encaminhamento por difusão"; "remoteNodes.auth.floodRetryStatus" = "Sem resposta pela rota conhecida. A tentar novamente com encaminhamento por difusão."; -"remoteNodes.auth.floodFooter" = "O encaminhamento por difusão é mais lento e usa mais tempo de antena da rede. Utilize-o quando a rota conhecida não funcionar a partir da localização atual. Uma nova rota é aprendida automaticamente após iniciar sessão."; +/* Footer when this sign-in will clear the saved route and use flood */ +"remoteNodes.auth.floodFooter" = "Este início de sessão limpa a rota guardada e usa a difusão. O encaminhamento por difusão é mais lento e usa mais tempo de antena da rede. Uma nova rota é aprendida se iniciar sessão com sucesso."; + +/* Footer after this sign-in has cleared the saved route */ +"remoteNodes.auth.floodFooterCleared" = "A rota guardada foi apagada. O início de sessão está a usar a difusão. Uma nova rota é aprendida se iniciar sessão com sucesso."; + + +/* Footer when a timeout clears the route and retries by flood */ +"remoteNodes.auth.pathFooter" = "Se não houver resposta, a rota é apagada e o início de sessão tenta uma vez por difusão."; -/* Location: NodeAuthenticationSheet.swift - Path section footer when stored path exists */ -"remoteNodes.auth.pathFooter" = "Utilize a rota conhecida até este nó, ou mude para o encaminhamento por difusão e deixe que a rede encontre outra."; +/* Footer when a timeout stops and leaves the route */ +"remoteNodes.auth.pathFooterKept" = "Se não houver resposta, o início de sessão termina e a rota mantém-se."; /* Location: NodeAuthenticationSheet.swift - Path hop whose repeater is not known */ "remoteNodes.auth.pathHopUnknown" = ""; @@ -84,6 +94,26 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Definições do repetidor"; +"remoteNodes.sensor.adminRequired" = "A gestão do sensor requer acesso de administrador."; + +"remoteNodes.sensor.saved" = "Definição verificada."; + +"remoteNodes.sensor.rebootSent" = "Pedido de reinício enviado. O sensor não confirmou o reinício. Inicie sessão novamente antes de enviar mais comandos."; + +"remoteNodes.sensor.rebootConfirmation" = "Enviar um pedido de reinício para este sensor?"; + +"remoteNodes.sensor.runtimeOnly" = "As alterações afetam o sensor em execução. A persistência após o reinício depende do respetivo firmware."; + +"remoteNodes.sensor.value" = "Valor"; + +"remoteNodes.sensor.save" = "Guardar"; + +"remoteNodes.sensor.reload" = "Recarregar"; + +"remoteNodes.sensor.empty" = "Este sensor não expõe definições."; + +"remoteNodes.sensor.title" = "Gestão do sensor"; + /* Location: RepeaterSettingsView.swift - Done button (used in multiple places) */ "remoteNodes.settings.done" = "Concluído"; diff --git a/MC1/Resources/Localization/pt.lproj/Settings.strings b/MC1/Resources/Localization/pt.lproj/Settings.strings index 6f3dc4e662..d2b079d5a6 100644 --- a/MC1/Resources/Localization/pt.lproj/Settings.strings +++ b/MC1/Resources/Localization/pt.lproj/Settings.strings @@ -46,9 +46,6 @@ /* Section header for device information */ "device.header" = "Dispositivo"; -/* Status shown when device is connected */ -"device.connected" = "Ligado"; - /* Footer shown when no device is connected */ "device.noDeviceConnected" = "Nenhum dispositivo MeshCore ligado"; @@ -60,12 +57,6 @@ /* Navigation title for device info screen */ "deviceInfo.title" = "Sobre o dispositivo"; -/* Section header for connection status */ -"deviceInfo.connection.header" = "Ligação"; - -/* Label for connection status */ -"deviceInfo.connection.status" = "Estado"; - /* Section header for power and storage */ "deviceInfo.powerStorage.header" = "Energia e armazenamento"; @@ -111,6 +102,12 @@ /* Firmware version fallback format when no version string is reported - %@ is the numeric version code */ "deviceInfo.firmwareVersionFormat" = "v%@"; +/* Heading above retained telemetry after a Device Info reload fails */ +"deviceInfo.lastSuccessfulReading" = "Última leitura bem-sucedida"; + +/* Section header for Device Info telemetry */ +"deviceInfo.telemetry.header" = "Telemetria do nó"; + /* Section header for identity information */ /* Label for public key */ "deviceInfo.publicKey" = "Chave pública"; @@ -165,6 +162,9 @@ /* Button to scan for Bluetooth devices */ "deviceSelection.scanBluetooth" = "Procurar dispositivo Bluetooth"; +/* Button title while this radio is being paired again */ +"deviceSelection.rePairing" = "A emparelhar de novo…"; + /* Trailing control on a previously paired row that still needs iPhone setup */ /* AI-translated - please verify with native speakers. */ "deviceSelection.setup" = "Configurar"; @@ -745,6 +745,21 @@ /* Alert message for clear logs */ "diagnostics.alert.clear.message" = "Isto irá eliminar todos os registos de depuração armazenados. Os ficheiros de registo já exportados não serão afetados."; +/* Toggle to enable collecting local debug logs */ +"diagnostics.collectLogs" = "Recolher registos de depuração"; + +/* Footer shown when debug log collection is off */ +"diagnostics.footer.disabled" = "Os registos de depuração locais não são recolhidos."; + +/* Alert title for disabling collection */ +"diagnostics.alert.disable.title" = "Desativar recolha"; + +/* Button to confirm disabling collection */ +"diagnostics.alert.disable.confirm" = "Desativar recolha"; + +/* Alert message for disabling collection */ +"diagnostics.alert.disable.message" = "Isto irá eliminar todos os registos de depuração armazenados e parar de os recolher. Os ficheiros de registo já exportados não serão afetados."; + /* Error when export fails */ "diagnostics.error.exportFailed" = "Não foi possível criar o ficheiro de exportação"; @@ -753,6 +768,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Chats"; +"blocksAndFilters.title" = "Bloqueio e filtros"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -872,6 +889,8 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Contacto"; +"notifications.discoveryCompanionsAndSensors" = "Contactos e sensores"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Repetidor"; @@ -1033,6 +1052,9 @@ /* Editor footer when the password is too long */ "radioWiFi.editor.passwordLength" = "Uma palavra-passe pode ter até 63 bytes."; +/* Editor footer when a credential contains a character the firmware cannot store */ +"radioWiFi.editor.unsupportedCharacter" = "O nome da rede ou a palavra-passe contém um carácter que este rádio não consegue guardar."; + /* Button that clears the radio's saved WiFi settings */ "radioWiFi.clear" = "Limpar definições de Wi-Fi"; @@ -1198,6 +1220,35 @@ /* Footer explaining the acknowledgments setting */ "directMessages.footer" = "Número de confirmações enviadas por mensagem direta. Use 2 para melhor confirmação de entrega em ligações pouco fiáveis."; +/* Switch that clears the known route after the path attempts */ +"directMessages.fallback" = "Recorrer à difusão"; + +/* Picker label for attempts on the known route */ +"directMessages.directAttempts" = "Tentativas pela rota"; + +/* Picker label for attempts sent by flood after the route is cleared */ +"directMessages.floodAttempts" = "Tentativas por difusão"; + +/* Footer when Fall Back to Flood is on */ +"directMessages.attemptsFooterOn" = "A rota é apagada depois das «Tentativas pela rota». As «Tentativas por difusão» são enviadas por difusão a seguir. Uma mensagem para um contacto sem rota conhecida é enviada por difusão."; + +/* Footer when Fall Back to Flood is off */ +"directMessages.attemptsFooterOff" = "As «Tentativas pela rota» ficam na rota conhecida, e a rota mantém-se. Uma mensagem para um contacto sem rota conhecida é enviada por difusão."; + +// MARK: - Path Fallback + +/* Section header for sign-in, command, and contact telemetry path fallback */ +"pathFallback.header" = "Recurso da rota"; + +/* Switch that clears the known route after a timeout */ +"pathFallback.fallback" = "Recorrer à difusão"; + +/* Footer when path fallback is on */ +"pathFallback.footerOn" = "O início de sessão, os comandos de repetidor e de sala que esperam uma resposta, e a telemetria do contacto usam a rota conhecida. Se não houver resposta, a rota é apagada e tenta-se uma vez por difusão."; + +/* Footer when path fallback is off */ +"pathFallback.footerOff" = "O início de sessão, os comandos e a telemetria do contacto mantêm-se na rota conhecida. Se não houver resposta, terminam e a rota mantém-se. A opção «Encaminhamento por difusão» no ecrã de início de sessão limpa a rota guardada desse nó."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ @@ -1212,12 +1263,24 @@ /* Menu item to disconnect from the current device */ "bleStatus.disconnect" = "Desligar"; +/* Menu item to stop automatic reconnection until another explicit connection */ +"bleStatus.stopReconnecting" = "Parar de restabelecer a ligação"; + +/* Menu item to cancel the current connection request */ +"bleStatus.cancelConnection" = "Cancelar ligação"; + /* Status shown when device is disconnected */ "bleStatus.status.disconnected" = "Sem ligação"; /* Status shown when device is connecting */ "bleStatus.status.connecting" = "A ligar…"; +/* Status shown while reconnecting to the selected device */ +"bleStatus.status.reconnecting" = "A restabelecer ligação…"; + +/* Status shown while automatic reconnection remains enabled between attempts */ +"bleStatus.status.waitingToReconnect" = "A aguardar para restabelecer a ligação"; + /* Status shown when device is connected but not ready */ "bleStatus.status.connected" = "Ligado"; @@ -1230,6 +1293,9 @@ /* Accessibility label for BLE status indicator */ "bleStatus.accessibilityLabel" = "Estado da ligação Bluetooth"; +/* TODO: translate - Accessibility text combining a descriptive prefix and connection state or context; arguments may themselves contain a radio name and status */ +"bleStatus.accessibilityValue" = "%1$@, %2$@"; + /* Accessibility hint when disconnected */ "bleStatus.accessibilityHint.disconnected" = "Toque duas vezes para ligar o dispositivo"; @@ -1333,6 +1399,24 @@ /* Import failed after one or more settings were already written; %@ is the underlying error message */ "configImport.failedPartial" = "%@ Algumas definições podem já ter sido gravadas no dispositivo. Reveja a configuração do dispositivo."; +/* Interrupted identity import recovery */ +"configImport.identityOutcomeUnknown" = "A ligação foi interrompida durante a importação da identidade em %@. A identidade do rádio pode ter sido alterada. A importação da configuração não foi concluída."; + +/* Interrupted identity import recovery */ +"configImport.retryIdentityImport" = "Repetir importação da identidade"; + +/* Interrupted identity import recovery */ +"configImport.confirmIdentityRecovery" = "Isto irá substituir a identidade do rádio acessível através de %@ usando a chave privada do ficheiro selecionado. A importação da configuração não irá continuar."; + +/* Confirmation alert title when retrying an interrupted identity import */ +"configImport.confirmTitleIdentityRecovery" = "Substituir a identidade do rádio?"; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryComplete" = "A identidade foi reaplicada. A importação da configuração não foi concluída. Importe o ficheiro novamente para aplicar as outras definições."; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryKeyRequired" = "Selecione um ficheiro de configuração que contenha a chave privada para repetir a importação da identidade."; + /* Import success */ "configImport.importSuccess" = "Configuração importada com êxito"; @@ -1432,6 +1516,63 @@ /* Validation error: no empty channel slot left (param: channel name) */ "configImport.error.noAvailableChannelSlot" = "Nenhum slot de canal vazio disponível para \"%@\""; +// MARK: - Text Rules + +"textRules.rules" = "Regras de filtro"; +"textRules.empty" = "Nenhuma regra de filtro"; +"textRules.loading" = "A carregar regras de filtro…"; +"textRules.loadFailed" = "Não foi possível carregar as regras de filtro. As mensagens novas não vão usar regras de filtro até ser possível carregá-las."; +"textRules.retryAccessibility" = "Tentar carregar regras de filtro novamente"; +"textRules.saveFailed" = "Não foi possível guardar as regras de filtro. Tente novamente."; +"textRules.new.title" = "Nova regra"; +"textRules.new.phrase" = "Palavra ou frase"; +"textRules.new.lookIn" = "Pesquisar em"; +"textRules.new.match" = "Correspondência"; +"textRules.new.containsMessageFooter" = "Corresponde em qualquer parte da mensagem, incluindo dentro de uma palavra."; +"textRules.new.wholeMessageFooter" = "Só corresponde se a mensagem inteira for esta frase."; +"textRules.new.containsSenderFooter" = "Corresponde em qualquer parte do nome do remetente, incluindo dentro de uma palavra. As reações desse remetente também ficam ocultas."; +"textRules.new.wholeNameFooter" = "Só corresponde se o nome do remetente for exatamente este. As reações desse remetente também ficam ocultas."; +"textRules.new.containsMessageOrSenderFooter" = "Corresponde em qualquer parte da mensagem ou do nome do remetente, incluindo dentro de uma palavra. As reações de um remetente que corresponda também ficam ocultas."; +"textRules.new.wholeMessageOrSenderFooter" = "Só corresponde se a mensagem inteira ou o nome inteiro do remetente for esta frase. As reações de um remetente que corresponda também ficam ocultas."; +"textRules.field.message" = "Mensagem"; +"textRules.field.sender" = "Remetente"; +"textRules.field.messageOrSender" = "Mensagem ou remetente"; +"textRules.match.contains" = "Contém"; +"textRules.match.wholeMessage" = "Mensagem inteira"; +"textRules.match.wholeName" = "Nome inteiro"; +"textRules.match.wholeField" = "Campo inteiro"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Usar regras para"; +"textRules.types.footer" = "Quando ativado, inclui todas as conversas desse tipo, incluindo as conversas a que aderir mais tarde."; +"textRules.types.publicChannel" = "Público"; +"textRules.types.hashtagChannel" = "Canais hashtag"; +"textRules.types.privateChannel" = "Canais privados"; +"textRules.selection.all" = "Todos"; +"textRules.selection.none" = "Nenhum"; +"textRules.selection.count" = "%d conversas"; +"textRules.selection.accessibilityChats" = "Conversas para %@"; +"textRules.selection.footer" = "Todos incluem as conversas a que aderir mais tarde."; +"textRules.archive.title" = "Recentemente bloqueadas"; +"textRules.archive.empty" = "Nenhuma mensagem oculta"; +"textRules.archive.footer" = "As %d mensagens ocultas mais recentes são guardadas neste dispositivo. Não são incluídas no backup da app."; +"textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; +"textRules.archive.rule" = "Regra"; +"textRules.archive.chat" = "Conversa"; +"textRules.archive.myNode" = "O meu nó"; +"textRules.archive.time" = "Hora"; +"textRules.archive.unknownConversation" = "Conversa desconhecida"; +"textRules.archive.unknownRadio" = "Rádio desconhecido"; + +"radioCleanup.title" = "Limpeza"; +"radioCleanup.running" = "A remover dados do rádio"; +"radioCleanup.failed" = "As mensagens ocultas deste rádio ainda podem estar nesta instalação."; +"radioCleanup.completed" = "Dados do rádio removidos"; +"radioCleanup.retryAccessibility" = "Tentar novamente a limpeza do rádio para %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ @@ -1976,7 +2117,7 @@ "settings.backup.export.alert.title" = "Aviso de segurança"; /* Export confirmation alert message */ -"settings.backup.export.alert.message" = "Este backup inclui as chaves de encriptação dos canais, o histórico de mensagens, a lista de contactos, o endereço de rede local e a porta do nó Wi-Fi. Guarde o ficheiro exportado de forma segura."; +"settings.backup.export.alert.message" = "Este backup inclui as chaves de encriptação dos canais, o histórico de mensagens, a lista de contactos, o endereço de rede local e a porta do nó Wi-Fi. O backup também pode incluir coordenadas GPS registadas pelos rádios. Guarde o ficheiro exportado de forma segura."; /* Export confirmation alert export button */ "settings.backup.export.alert.export" = "Exportar"; diff --git a/MC1/Resources/Localization/pt.lproj/WhatsNew.strings b/MC1/Resources/Localization/pt.lproj/WhatsNew.strings index fbeb858280..1e7bd5f220 100644 --- a/MC1/Resources/Localization/pt.lproj/WhatsNew.strings +++ b/MC1/Resources/Localization/pt.lproj/WhatsNew.strings @@ -64,3 +64,23 @@ "whatsNew.moreChanges.title" = "Mais alterações"; /* What's New v1.6 - More changes, description */ "whatsNew.moreChanges.description" = "Toque em \"Ver todas as novas alterações\" abaixo para ver a lista completa de correções e outras funcionalidades."; + +/* What's New v1.7 - Direct messages, title */ +"whatsNew.directMessages.title" = "Mensagens diretas"; +/* What's New v1.7 - Direct messages, description */ +"whatsNew.directMessages.description" = "As mensagens diretas tentam agora pela rota 4 vezes e depois por difusão 4 vezes. Altere Tentativas pela rota, Tentativas por difusão e Recorrer à difusão em Definições avançadas."; + +/* What's New v1.7 - Blocks and filters, title */ +"whatsNew.blocksAndFilters.title" = "Bloqueio e filtros"; +/* What's New v1.7 - Blocks and filters, description */ +"whatsNew.blocksAndFilters.description" = "Oculte as mensagens que correspondam a uma palavra ou frase. Uma regra pode pesquisar na mensagem, no nome do remetente ou em ambos, e pode escolher as conversas a que se aplica. As mensagens ocultas podem ser vistas em Recentemente bloqueadas, em Definições > Bloqueio e filtros."; + +/* What's New v1.7 - Node telemetry, title */ +"whatsNew.nodeTelemetry.title" = "Telemetria do nó"; +/* What's New v1.7 - Node telemetry, description */ +"whatsNew.nodeTelemetry.description" = "Definições > Sobre o dispositivo mostra a telemetria do nó a que está ligado."; + +/* What's New v1.7 - Live Activity, title */ +"whatsNew.liveActivity.title" = "Atividade em tempo real"; +/* What's New v1.7 - Live Activity, description */ +"whatsNew.liveActivity.description" = "As mensagens por ler estão mais em destaque e a taxa de pacotes por minuto é mais fácil de perceber."; diff --git a/MC1/Resources/Localization/ru.lproj/Chats.strings b/MC1/Resources/Localization/ru.lproj/Chats.strings index 511be0eea7..24189747df 100644 --- a/MC1/Resources/Localization/ru.lproj/Chats.strings +++ b/MC1/Resources/Localization/ru.lproj/Chats.strings @@ -582,6 +582,12 @@ /* Location: UnifiedMessageBubble.swift - VoiceOver prefix when the visible body is a translation - %@ is the translated text */ "chats.message.translatedAccessibility" = "Переведено: %@"; +/* Location: MessageVisibleBody.swift - VoiceOver prefix when the visible body is an MECP reading - %@ is the reading */ +"chats.message.readingAccessibility" = "Чтение: %@"; + +/* Location: MECPCatalog - Person count line in an MECP reading */ +"chats.message.mecpPersonCount" = "%lld человека"; + /* Location: UnifiedMessageBubble.swift - Context menu action to view repeat details */ "chats.message.action.repeatDetails" = "Детали повторов"; @@ -635,6 +641,9 @@ /* Location: UnifiedMessageBubble.swift - Context menu text showing SNR - %@ is formatted value */ "chats.message.info.snr" = "SNR: %@"; +/* Location: ActionsDetailsSection.swift - Stored MECP wire string under SNR. %@ is the original text */ +"chats.message.info.mecp" = "MECP: %@"; + /* Location: MessageActionsSheet.swift - Context menu text showing the radio region the message was flooded under - %@ is region name. "Flooded" is a domain term for mesh-broadcast across all nodes in a radio region. */ "chats.message.info.floodedUnder" = "Регион: %@"; @@ -1138,8 +1147,8 @@ /* Location: ConversationRow.swift - Purpose: Mentions only indicator */ "chats.row.mentionsOnly" = "Только упоминания"; -/* TODO: translate - Accessibility label for the row actions menu */ -"chats.row.actionsMenu.accessibilityLabel" = "Conversation actions"; +/* Accessibility label for the row actions menu */ +"chats.row.actionsMenu.accessibilityLabel" = "Действия разговора"; // MARK: - Reactions diff --git a/MC1/Resources/Localization/ru.lproj/Chats.stringsdict b/MC1/Resources/Localization/ru.lproj/Chats.stringsdict new file mode 100644 index 0000000000..ba5c18c797 --- /dev/null +++ b/MC1/Resources/Localization/ru.lproj/Chats.stringsdict @@ -0,0 +1,26 @@ + + + + + chats.message.mecpPersonCount + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + lld + one + %lld человек + few + %lld человека + many + %lld человек + other + %lld человека + + + + diff --git a/MC1/Resources/Localization/ru.lproj/Contacts.strings b/MC1/Resources/Localization/ru.lproj/Contacts.strings index cf81edac5f..109d479924 100644 --- a/MC1/Resources/Localization/ru.lproj/Contacts.strings +++ b/MC1/Resources/Localization/ru.lproj/Contacts.strings @@ -44,6 +44,8 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Комната"; +"contacts.nodeKind.sensor" = "Датчик"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Обнаружен"; @@ -75,6 +77,8 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Комнаты"; +"contacts.segment.sensors" = "Датчики"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "Фильтр узлов"; @@ -168,9 +172,13 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "Нет комнат"; +"contacts.list.empty.sensors.title" = "Нет датчиков"; + /* Location: ContactsListView.swift - Purpose: No rooms empty description */ "contacts.list.empty.rooms.description" = "Комнаты — это публичные чат-серверы в сети mesh. Они появятся здесь после обнаружения."; +"contacts.list.empty.sensors.description" = "Датчики появляются здесь при обнаружении в сети mesh."; + /* Location: ContactsListView.swift - Purpose: No search results title */ "contacts.list.empty.search.title" = "Нет результатов"; @@ -623,6 +631,8 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter - Rooms */ "contacts.discovery.segment.rooms" = "Комнаты"; +"contacts.discovery.segment.sensors" = "Датчики"; + /* Location: DiscoverSegmentPicker.swift - Purpose: VoiceOver label for the Discovery segment filter picker (iOS 18 fallback) */ "contacts.discovery.segment.pickerLabel" = "Фильтр обнаруженных узлов"; diff --git a/MC1/Resources/Localization/ru.lproj/Localizable.strings b/MC1/Resources/Localization/ru.lproj/Localizable.strings index 1be31e750a..8b37ff2f84 100644 --- a/MC1/Resources/Localization/ru.lproj/Localizable.strings +++ b/MC1/Resources/Localization/ru.lproj/Localizable.strings @@ -134,6 +134,8 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "Обнаружена новая комната"; +"notifications.discovery.sensor" = "Обнаружен новый датчик"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -497,6 +499,14 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Недопустимый ответ удалённого узла"; +"error.remoteNode.sensorOutcomeUnknown" = "Изменение не удалось проверить. Обнови настройки перед повторным сохранением."; + +"error.remoteNode.sensorSettingRejected" = "Датчик отклонил эту настройку."; + +"error.remoteNode.invalidSensorSetting" = "Используй непустой ключ и значение без пробелов. Вся команда должна умещаться в 160 байт UTF-8."; + +"error.remoteNode.invalidPasswordLength" = "Пароли должны содержать не больше %d байт UTF-8."; + /* Location: RemoteNodeError+UserFacingMessage.swift - Remote node rejected the operation */ "error.remoteNode.permissionDenied" = "Доступ запрещён"; diff --git a/MC1/Resources/Localization/ru.lproj/Map.strings b/MC1/Resources/Localization/ru.lproj/Map.strings index 5b0032d6b6..107aa1f07e 100644 --- a/MC1/Resources/Localization/ru.lproj/Map.strings +++ b/MC1/Resources/Localization/ru.lproj/Map.strings @@ -40,6 +40,8 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Фильтр"; +"map.controls.contactsAndSensors" = "Контакты и датчики"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Фильтры активны"; @@ -264,6 +266,8 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Комната"; +"map.nodeKind.sensor" = "Датчик"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -281,6 +285,8 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Комната"; +"map.callout.nodeKind.sensor" = "Датчик"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "Добавить"; diff --git a/MC1/Resources/Localization/ru.lproj/Onboarding.strings b/MC1/Resources/Localization/ru.lproj/Onboarding.strings index e279579676..65b44e1d94 100644 --- a/MC1/Resources/Localization/ru.lproj/Onboarding.strings +++ b/MC1/Resources/Localization/ru.lproj/Onboarding.strings @@ -69,6 +69,9 @@ /* Location: DeviceScanView.swift - Subtitle with pairing instructions */ "deviceScan.subtitle" = "Включите рацию, отключите её от всех других приложений и устройств, а затем нажмите «Добавить устройство»."; +/* Location: DeviceScanView.swift - Subtitle while bond-loss recovery is re-pairing */ +"deviceScan.rePairingSubtitle" = "Включите рацию и отключите её от всех других приложений и устройств."; + /* Location: DeviceScanView.swift - Message shown when device is already paired */ "deviceScan.alreadyPaired" = "Ваше устройство уже сопряжено"; @@ -78,9 +81,6 @@ /* Location: DeviceScanView.swift - Button to continue after pairing */ "deviceScan.continue" = "Продолжить"; -/* Location: DeviceScanView.swift - Button label while connecting */ -"deviceScan.connecting" = "Подключение..."; - /* Location: DeviceScanView.swift - Button to connect simulator (debug) */ "deviceScan.connectSimulator" = "Подключить симулятор"; diff --git a/MC1/Resources/Localization/ru.lproj/RemoteNodes.strings b/MC1/Resources/Localization/ru.lproj/RemoteNodes.strings index 713049b1d4..b637623fba 100644 --- a/MC1/Resources/Localization/ru.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/ru.lproj/RemoteNodes.strings @@ -32,6 +32,8 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Ретранслятор"; +"remoteNodes.auth.typeSensor" = "Датчик"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Аутентификация"; @@ -62,10 +64,18 @@ /* Location: NodeAuthenticationSheet.swift - Flood routing toggle */ "remoteNodes.auth.floodRouting" = "Flood-маршрутизация"; "remoteNodes.auth.floodRetryStatus" = "Нет ответа по известному маршруту. Повторная попытка через flood-маршрутизацию."; -"remoteNodes.auth.floodFooter" = "Flood-маршрутизация медленнее и расходует больше эфирного времени сети. Используйте её, когда известный маршрут не работает в вашем текущем местоположении. После входа новый маршрут будет определён автоматически."; +/* Footer when this sign-in will clear the saved route and use flood */ +"remoteNodes.auth.floodFooter" = "Этот вход удаляет сохранённый маршрут и идёт через flood-маршрутизацию. Flood-маршрутизация медленнее и расходует больше эфирного времени сети. Новый маршрут будет определён, только если вход завершится успешно."; + +/* Footer after this sign-in has cleared the saved route */ +"remoteNodes.auth.floodFooterCleared" = "Сохранённый маршрут удалён. Вход идёт через flood-маршрутизацию. Новый маршрут будет определён, только если вход завершится успешно."; + + +/* Footer when a timeout clears the route and retries by flood */ +"remoteNodes.auth.pathFooter" = "Если ответа нет, маршрут удаляется, и вход делает одну попытку через flood-маршрутизацию."; -/* Location: NodeAuthenticationSheet.swift - Path section footer when stored path exists */ -"remoteNodes.auth.pathFooter" = "Используйте известный маршрут к этому узлу или переключитесь на flood-маршрутизацию, чтобы сеть нашла путь."; +/* Footer when a timeout stops and leaves the route */ +"remoteNodes.auth.pathFooterKept" = "Если ответа нет, вход прекращается, а маршрут не удаляется."; /* Location: NodeAuthenticationSheet.swift - Path hop whose repeater is not known */ "remoteNodes.auth.pathHopUnknown" = "<неизвестно>"; @@ -84,6 +94,26 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Настройки ретранслятора"; +"remoteNodes.sensor.adminRequired" = "Управление датчиком требует доступа администратора."; + +"remoteNodes.sensor.saved" = "Настройка проверена."; + +"remoteNodes.sensor.rebootSent" = "Запрос на перезагрузку отправлен. Датчик не подтвердил перезапуск. Войди в датчик снова, прежде чем отправлять ещё команды."; + +"remoteNodes.sensor.rebootConfirmation" = "Отправить запрос на перезагрузку этому датчику?"; + +"remoteNodes.sensor.runtimeOnly" = "Изменения действуют на работающий датчик. Сохранение после перезагрузки зависит от его прошивки."; + +"remoteNodes.sensor.value" = "Значение"; + +"remoteNodes.sensor.save" = "Сохранить"; + +"remoteNodes.sensor.reload" = "Обновить"; + +"remoteNodes.sensor.empty" = "У этого датчика нет настроек."; + +"remoteNodes.sensor.title" = "Управление датчиком"; + /* Location: RepeaterSettingsView.swift - Done button (used in multiple places) */ "remoteNodes.settings.done" = "Готово"; diff --git a/MC1/Resources/Localization/ru.lproj/Settings.strings b/MC1/Resources/Localization/ru.lproj/Settings.strings index 615f6852da..679a906b4d 100644 --- a/MC1/Resources/Localization/ru.lproj/Settings.strings +++ b/MC1/Resources/Localization/ru.lproj/Settings.strings @@ -46,9 +46,6 @@ /* Section header for device information */ "device.header" = "Устройство"; -/* Status shown when device is connected */ -"device.connected" = "Подключено"; - /* Footer shown when no device is connected */ "device.noDeviceConnected" = "Устройство MeshCore не подключено"; @@ -60,12 +57,6 @@ /* Navigation title for device info screen */ "deviceInfo.title" = "Информация об устройстве"; -/* Section header for connection status */ -"deviceInfo.connection.header" = "Подключение"; - -/* Label for connection status */ -"deviceInfo.connection.status" = "Статус"; - /* Section header for power and storage */ "deviceInfo.powerStorage.header" = "Питание и память"; @@ -111,6 +102,12 @@ /* Firmware version fallback format when no version string is reported - %@ is the numeric version code */ "deviceInfo.firmwareVersionFormat" = "v%@"; +/* Heading above retained telemetry after a Device Info reload fails */ +"deviceInfo.lastSuccessfulReading" = "Последние успешные показания"; + +/* Section header for Device Info telemetry */ +"deviceInfo.telemetry.header" = "Телеметрия узла"; + /* Section header for identity information */ /* Label for public key */ "deviceInfo.publicKey" = "Публичный ключ"; @@ -165,6 +162,9 @@ /* Button to scan for Bluetooth devices */ "deviceSelection.scanBluetooth" = "Поиск Bluetooth-устройств"; +/* Button title while this radio is being paired again */ +"deviceSelection.rePairing" = "Сопряжение заново..."; + /* Trailing control on a previously paired row that still needs iPhone setup */ /* AI-translated - please verify with native speakers. */ "deviceSelection.setup" = "Настроить"; @@ -746,6 +746,21 @@ /* Alert message for clear logs */ "diagnostics.alert.clear.message" = "Это удалит все сохранённые отладочные логи. Экспортированные файлы логов не будут затронуты."; +/* Toggle to enable collecting local debug logs */ +"diagnostics.collectLogs" = "Собирать отладочные логи"; + +/* Footer shown when debug log collection is off */ +"diagnostics.footer.disabled" = "Локальные отладочные логи не собираются."; + +/* Alert title for disabling collection */ +"diagnostics.alert.disable.title" = "Отключить сбор"; + +/* Button to confirm disabling collection */ +"diagnostics.alert.disable.confirm" = "Отключить сбор"; + +/* Alert message for disabling collection */ +"diagnostics.alert.disable.message" = "Это удалит все сохранённые отладочные логи и прекратит их сбор. Экспортированные файлы логов не будут затронуты."; + /* Error when export fails */ "diagnostics.error.exportFailed" = "Не удалось создать файл экспорта"; @@ -754,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Чаты"; +"blocksAndFilters.title" = "Блокировка и фильтры"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -822,6 +839,8 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Компаньон"; +"notifications.discoveryCompanionsAndSensors" = "Компаньоны и датчики"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Ретранслятор"; @@ -983,6 +1002,9 @@ /* Editor footer when the password is too long */ "radioWiFi.editor.passwordLength" = "Пароль может содержать до 63 байт."; +/* Editor footer when a credential contains a character the firmware cannot store */ +"radioWiFi.editor.unsupportedCharacter" = "Имя сети или пароль содержит символ, который это радио не может сохранить."; + /* Button that clears the radio's saved WiFi settings */ "radioWiFi.clear" = "Очистить настройки WiFi"; @@ -1148,6 +1170,35 @@ /* Footer explaining the acknowledgments setting */ "directMessages.footer" = "Количество подтверждений, отправляемых на каждое прямое сообщение. Используйте 2 для лучшего подтверждения доставки по ненадёжным каналам."; +/* Switch that clears the known route after the path attempts */ +"directMessages.fallback" = "Переход на flood-маршрутизацию"; + +/* Picker label for attempts on the known route */ +"directMessages.directAttempts" = "Попытки по маршруту"; + +/* Picker label for attempts sent by flood after the route is cleared */ +"directMessages.floodAttempts" = "Попытки flood-маршрутизации"; + +/* Footer when Fall Back to Flood is on */ +"directMessages.attemptsFooterOn" = "Маршрут удаляется после «Попытки по маршруту». После этого «Попытки flood-маршрутизации» отправляются через flood-маршрутизацию. Сообщение контакту без известного маршрута отправляется через flood-маршрутизацию."; + +/* Footer when Fall Back to Flood is off */ +"directMessages.attemptsFooterOff" = "«Попытки по маршруту» остаются на известном маршруте, и маршрут не удаляется. Сообщение контакту без известного маршрута отправляется через flood-маршрутизацию."; + +// MARK: - Path Fallback + +/* Section header for sign-in, command, and contact telemetry path fallback */ +"pathFallback.header" = "Запасной маршрут"; + +/* Switch that clears the known route after a timeout */ +"pathFallback.fallback" = "Переход на flood-маршрутизацию"; + +/* Footer when path fallback is on */ +"pathFallback.footerOn" = "Вход, команды ретрансляторам и комнатам, которые ждут ответа, и телеметрия контакта используют известный маршрут. Если ответа нет, маршрут удаляется, и делается одна попытка через flood-маршрутизацию."; + +/* Footer when path fallback is off */ +"pathFallback.footerOff" = "Вход, команды и телеметрия контакта остаются на известном маршруте. Если ответа нет, они прекращаются, а маршрут не удаляется. «Flood-маршрутизация» на экране входа удаляет сохранённый маршрут этого узла."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ @@ -1162,12 +1213,24 @@ /* Menu item to disconnect from the current device */ "bleStatus.disconnect" = "Отключить"; +/* Menu item to stop automatic reconnection until another explicit connection */ +"bleStatus.stopReconnecting" = "Остановить переподключение"; + +/* Menu item to cancel the current connection request */ +"bleStatus.cancelConnection" = "Отменить подключение"; + /* Status shown when device is disconnected */ "bleStatus.status.disconnected" = "Отключено"; /* Status shown when device is connecting */ "bleStatus.status.connecting" = "Подключение..."; +/* Status shown while reconnecting to the selected device */ +"bleStatus.status.reconnecting" = "Переподключение..."; + +/* Status shown while automatic reconnection remains enabled between attempts */ +"bleStatus.status.waitingToReconnect" = "Ожидание переподключения"; + /* Status shown when device is connected but not ready */ "bleStatus.status.connected" = "Подключено"; @@ -1180,6 +1243,9 @@ /* Accessibility label for BLE status indicator */ "bleStatus.accessibilityLabel" = "Статус Bluetooth-подключения"; +/* TODO: translate - Accessibility text combining a descriptive prefix and connection state or context; arguments may themselves contain a radio name and status */ +"bleStatus.accessibilityValue" = "%1$@, %2$@"; + /* Accessibility hint when disconnected */ "bleStatus.accessibilityHint.disconnected" = "Дважды коснитесь для подключения устройства"; @@ -1318,6 +1384,24 @@ /* Import failed after one or more settings were already written; %@ is the underlying error message */ "configImport.failedPartial" = "%@ Некоторые настройки могли быть уже записаны на устройство. Проверьте конфигурацию устройства."; +/* Interrupted identity import recovery */ +"configImport.identityOutcomeUnknown" = "Соединение было прервано во время импорта идентификации на %@. Идентификация радио могла измениться. Импорт конфигурации не был завершён."; + +/* Interrupted identity import recovery */ +"configImport.retryIdentityImport" = "Повторить импорт идентификации"; + +/* Interrupted identity import recovery */ +"configImport.confirmIdentityRecovery" = "Это заменит идентификацию радио, доступного через %@, с помощью закрытого ключа из выбранного файла. Импорт конфигурации не будет продолжен."; + +/* Confirmation alert title when retrying an interrupted identity import */ +"configImport.confirmTitleIdentityRecovery" = "Заменить идентификацию радио?"; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryComplete" = "Идентификация была применена повторно. Импорт конфигурации не был завершён. Импортируйте файл ещё раз, чтобы применить остальные настройки."; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryKeyRequired" = "Выберите файл конфигурации, содержащий закрытый ключ, чтобы повторить импорт идентификации."; + /* Import success */ "configImport.importSuccess" = "Конфигурация успешно импортирована"; @@ -1434,6 +1518,63 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "Отображение миниатюр карты загружает плитки для координаты со стороннего сервера, что может раскрыть ваш IP-адрес."; +// MARK: - Text Rules + +"textRules.rules" = "Правила фильтрации"; +"textRules.empty" = "Нет правил фильтрации"; +"textRules.loading" = "Загрузка правил фильтрации…"; +"textRules.loadFailed" = "Не удалось загрузить правила фильтрации. Новые сообщения не будут использовать эти правила, пока их не удастся загрузить."; +"textRules.retryAccessibility" = "Попробовать загрузить правила фильтрации ещё раз"; +"textRules.saveFailed" = "Не удалось сохранить правила фильтрации. Попробуй ещё раз."; +"textRules.new.title" = "Новое правило"; +"textRules.new.phrase" = "Слово или фраза"; +"textRules.new.lookIn" = "Искать в"; +"textRules.new.match" = "Совпадение"; +"textRules.new.containsMessageFooter" = "Совпадает в любом месте сообщения, в том числе внутри слова."; +"textRules.new.wholeMessageFooter" = "Совпадает, только если всё сообщение равно этой фразе."; +"textRules.new.containsSenderFooter" = "Совпадает в любом месте имени отправителя, в том числе внутри слова. Реакции от этого отправителя тоже скрыты."; +"textRules.new.wholeNameFooter" = "Совпадает, только если имя отправителя в точности такое. Реакции от этого отправителя тоже скрыты."; +"textRules.new.containsMessageOrSenderFooter" = "Совпадает в любом месте сообщения или имени отправителя, в том числе внутри слова. Если совпало имя, реакции этого отправителя тоже скрыты."; +"textRules.new.wholeMessageOrSenderFooter" = "Совпадает, только если всё сообщение или всё имя отправителя равно этой фразе. Если совпало имя, реакции этого отправителя тоже скрыты."; +"textRules.field.message" = "Сообщение"; +"textRules.field.sender" = "Отправитель"; +"textRules.field.messageOrSender" = "Сообщение или отправитель"; +"textRules.match.contains" = "Содержит"; +"textRules.match.wholeMessage" = "Всё сообщение"; +"textRules.match.wholeName" = "Всё имя"; +"textRules.match.wholeField" = "Всё поле"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Использовать правила для"; +"textRules.types.footer" = "Включённый переключатель охватывает все чаты этого типа, включая те, к которым ты присоединишься позже."; +"textRules.types.publicChannel" = "Публичный"; +"textRules.types.hashtagChannel" = "Хэштег-каналы"; +"textRules.types.privateChannel" = "Приватные каналы"; +"textRules.selection.all" = "Все"; +"textRules.selection.none" = "Нет"; +"textRules.selection.count" = "%d чатов"; +"textRules.selection.accessibilityChats" = "Чаты для %@"; +"textRules.selection.footer" = "«Все» включает чаты, к которым ты присоединишься позже."; +"textRules.archive.title" = "Недавно скрытые"; +"textRules.archive.empty" = "Нет скрытых сообщений"; +"textRules.archive.footer" = "Последние %d скрытых сообщений хранятся на этом устройстве. В резервную копию приложения они не входят."; +"textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; +"textRules.archive.rule" = "Правило"; +"textRules.archive.chat" = "Чат"; +"textRules.archive.myNode" = "Мой узел"; +"textRules.archive.time" = "Время"; +"textRules.archive.unknownConversation" = "Неизвестный разговор"; +"textRules.archive.unknownRadio" = "Неизвестное радио"; + +"radioCleanup.title" = "Очистка"; +"radioCleanup.running" = "Удаление данных радио"; +"radioCleanup.failed" = "Скрытые сообщения этого радио могут остаться на этой установке."; +"radioCleanup.completed" = "Данные радио удалены"; +"radioCleanup.retryAccessibility" = "Попробовать очистку радио ещё раз для %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ @@ -1978,7 +2119,7 @@ "settings.backup.export.alert.title" = "Предупреждение о безопасности"; /* Export confirmation alert message */ -"settings.backup.export.alert.message" = "Эта резервная копия содержит ключи шифрования каналов, историю сообщений, список контактов, а также локальный сетевой адрес и порт узла Wi-Fi. Храните экспортированный файл в надёжном месте."; +"settings.backup.export.alert.message" = "Эта резервная копия содержит ключи шифрования каналов, историю сообщений, список контактов, а также локальный сетевой адрес и порт узла Wi-Fi. Резервная копия также может содержать сохранённые GPS-координаты радиоустройств. Храните экспортированный файл в надёжном месте."; /* Export confirmation alert export button */ "settings.backup.export.alert.export" = "Экспортировать"; diff --git a/MC1/Resources/Localization/ru.lproj/WhatsNew.strings b/MC1/Resources/Localization/ru.lproj/WhatsNew.strings index b63778a7e1..58e0365dd3 100644 --- a/MC1/Resources/Localization/ru.lproj/WhatsNew.strings +++ b/MC1/Resources/Localization/ru.lproj/WhatsNew.strings @@ -65,3 +65,23 @@ "whatsNew.moreChanges.title" = "Другие изменения"; /* What's New v1.6 - More changes, description */ "whatsNew.moreChanges.description" = "Нажмите \"Смотреть все новые изменения\" ниже, чтобы увидеть полный список исправлений ошибок и других функций."; + +/* What's New v1.7 - Direct messages, title */ +"whatsNew.directMessages.title" = "Прямые сообщения"; +/* What's New v1.7 - Direct messages, description */ +"whatsNew.directMessages.description" = "Прямые сообщения теперь делают 4 попытки по маршруту, затем 4 попытки flood-маршрутизации. Измените «Попытки по маршруту», «Попытки flood-маршрутизации» и «Переход на flood-маршрутизацию» в «Расширенные настройки»."; + +/* What's New v1.7 - Blocks and filters, title */ +"whatsNew.blocksAndFilters.title" = "Блокировка и фильтры"; +/* What's New v1.7 - Blocks and filters, description */ +"whatsNew.blocksAndFilters.description" = "Скрывайте сообщения, которые совпадают со словом или фразой. Правило может проверять «Сообщение», «Отправитель» или и то, и другое, а вы выбираете, к каким чатам оно применяется. Скрытые сообщения можно увидеть в «Недавно скрытые» в «Настройки» > «Блокировка и фильтры»."; + +/* What's New v1.7 - Node telemetry, title */ +"whatsNew.nodeTelemetry.title" = "Телеметрия узла"; +/* What's New v1.7 - Node telemetry, description */ +"whatsNew.nodeTelemetry.description" = "«Настройки» > «Информация об устройстве» показывает телеметрию узла, к которому вы подключены."; + +/* What's New v1.7 - Live Activity, title */ +"whatsNew.liveActivity.title" = "Live Activity"; +/* What's New v1.7 - Live Activity, description */ +"whatsNew.liveActivity.description" = "Непрочитанные сообщения заметнее, а частота пакетов в минуту понятнее."; diff --git a/MC1/Resources/Localization/uk.lproj/Chats.strings b/MC1/Resources/Localization/uk.lproj/Chats.strings index 75dac1f8a4..522fcdb25f 100644 --- a/MC1/Resources/Localization/uk.lproj/Chats.strings +++ b/MC1/Resources/Localization/uk.lproj/Chats.strings @@ -582,6 +582,12 @@ /* Location: UnifiedMessageBubble.swift - VoiceOver prefix when the visible body is a translation - %@ is the translated text */ "chats.message.translatedAccessibility" = "Перекладено: %@"; +/* Location: MessageVisibleBody.swift - VoiceOver prefix when the visible body is an MECP reading - %@ is the reading */ +"chats.message.readingAccessibility" = "Читання: %@"; + +/* Location: MECPCatalog - Person count line in an MECP reading */ +"chats.message.mecpPersonCount" = "%lld людини"; + /* Location: UnifiedMessageBubble.swift - Context menu action to view repeat details */ "chats.message.action.repeatDetails" = "Деталі повторів"; @@ -635,6 +641,9 @@ /* Location: UnifiedMessageBubble.swift - Context menu text showing SNR - %@ is formatted value */ "chats.message.info.snr" = "SNR: %@"; +/* Location: ActionsDetailsSection.swift - Stored MECP wire string under SNR. %@ is the original text */ +"chats.message.info.mecp" = "MECP: %@"; + /* Location: MessageActionsSheet.swift - Context menu text showing the radio region the message was flooded under - %@ is region name. "Flooded" is a domain term for mesh-broadcast across all nodes in a radio region. */ "chats.message.info.floodedUnder" = "Регіон: %@"; @@ -1140,8 +1149,8 @@ /* Location: ConversationRow.swift - Purpose: Mentions-only indicator */ "chats.row.mentionsOnly" = "Лише згадки"; -/* TODO: translate - Accessibility label for the row actions menu */ -"chats.row.actionsMenu.accessibilityLabel" = "Conversation actions"; +/* Accessibility label for the row actions menu */ +"chats.row.actionsMenu.accessibilityLabel" = "Дії розмови"; // MARK: - Reactions diff --git a/MC1/Resources/Localization/uk.lproj/Chats.stringsdict b/MC1/Resources/Localization/uk.lproj/Chats.stringsdict new file mode 100644 index 0000000000..21ae8ca236 --- /dev/null +++ b/MC1/Resources/Localization/uk.lproj/Chats.stringsdict @@ -0,0 +1,26 @@ + + + + + chats.message.mecpPersonCount + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + lld + one + %lld людина + few + %lld людини + many + %lld людей + other + %lld людини + + + + diff --git a/MC1/Resources/Localization/uk.lproj/Contacts.strings b/MC1/Resources/Localization/uk.lproj/Contacts.strings index aaa2ae75a6..25ea9fb42e 100644 --- a/MC1/Resources/Localization/uk.lproj/Contacts.strings +++ b/MC1/Resources/Localization/uk.lproj/Contacts.strings @@ -44,6 +44,8 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Кімната"; +"contacts.nodeKind.sensor" = "Датчик"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Виявлений"; @@ -75,6 +77,8 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Кімнати"; +"contacts.segment.sensors" = "Датчики"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "Фільтр вузлів"; @@ -168,9 +172,13 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "Немає кімнат"; +"contacts.list.empty.sensors.title" = "Немає датчиків"; + /* Location: ContactsListView.swift - Purpose: No rooms empty description */ "contacts.list.empty.rooms.description" = "Кімнати — це публічні чат-сервери в mesh-мережі. Вони з'являться тут після виявлення."; +"contacts.list.empty.sensors.description" = "Датчики з'являються тут після виявлення в mesh-мережі."; + /* Location: ContactsListView.swift - Purpose: No search results title */ "contacts.list.empty.search.title" = "Немає результатів"; @@ -623,6 +631,8 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter - Rooms */ "contacts.discovery.segment.rooms" = "Кімнати"; +"contacts.discovery.segment.sensors" = "Датчики"; + /* Location: DiscoverSegmentPicker.swift - Purpose: VoiceOver label for the Discovery segment filter picker (iOS 18 fallback) */ "contacts.discovery.segment.pickerLabel" = "Фільтр виявлених вузлів"; diff --git a/MC1/Resources/Localization/uk.lproj/Localizable.strings b/MC1/Resources/Localization/uk.lproj/Localizable.strings index 571a835011..9cdfbac22c 100644 --- a/MC1/Resources/Localization/uk.lproj/Localizable.strings +++ b/MC1/Resources/Localization/uk.lproj/Localizable.strings @@ -137,6 +137,8 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "Виявлено нову кімнату"; +"notifications.discovery.sensor" = "Виявлено новий датчик"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -500,6 +502,14 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Неприпустима відповідь віддаленого вузла"; +"error.remoteNode.sensorOutcomeUnknown" = "Не вдалося перевірити зміну. Оновіть налаштування, перш ніж зберігати знову."; + +"error.remoteNode.sensorSettingRejected" = "Датчик відхилив це налаштування."; + +"error.remoteNode.invalidSensorSetting" = "Використовуйте непорожні ключ і значення без пробілів. Уся команда має вміститися в 160 байт UTF-8."; + +"error.remoteNode.invalidPasswordLength" = "Паролі мають містити не більше ніж %d байт UTF-8."; + /* Location: RemoteNodeError+UserFacingMessage.swift - Remote node rejected the operation */ "error.remoteNode.permissionDenied" = "Доступ заборонено"; diff --git a/MC1/Resources/Localization/uk.lproj/Map.strings b/MC1/Resources/Localization/uk.lproj/Map.strings index 6bae83870b..2df6cfce03 100644 --- a/MC1/Resources/Localization/uk.lproj/Map.strings +++ b/MC1/Resources/Localization/uk.lproj/Map.strings @@ -40,6 +40,8 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Фільтр"; +"map.controls.contactsAndSensors" = "Контакти і датчики"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Фільтри активні"; @@ -264,6 +266,8 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Кімната"; +"map.nodeKind.sensor" = "Датчик"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -281,6 +285,8 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Кімната"; +"map.callout.nodeKind.sensor" = "Датчик"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "Додати"; diff --git a/MC1/Resources/Localization/uk.lproj/Onboarding.strings b/MC1/Resources/Localization/uk.lproj/Onboarding.strings index 34ef6f5207..1cdb6c4033 100644 --- a/MC1/Resources/Localization/uk.lproj/Onboarding.strings +++ b/MC1/Resources/Localization/uk.lproj/Onboarding.strings @@ -69,6 +69,9 @@ /* Location: DeviceScanView.swift - Subtitle with pairing instructions */ "deviceScan.subtitle" = "Увімкніть рацію, від'єднайте її від усіх інших додатків і пристроїв, а потім торкніться «Додати пристрій»."; +/* Location: DeviceScanView.swift - Subtitle while bond-loss recovery is re-pairing */ +"deviceScan.rePairingSubtitle" = "Увімкніть рацію і від'єднайте її від усіх інших додатків і пристроїв."; + /* Location: DeviceScanView.swift - Message shown when device is already paired */ "deviceScan.alreadyPaired" = "Ваш пристрій вже сполучено"; @@ -78,9 +81,6 @@ /* Location: DeviceScanView.swift - Button to continue after pairing */ "deviceScan.continue" = "Продовжити"; -/* Location: DeviceScanView.swift - Button label while connecting */ -"deviceScan.connecting" = "Підключення..."; - /* Location: DeviceScanView.swift - Button to connect simulator (debug) */ "deviceScan.connectSimulator" = "Підключити симулятор"; diff --git a/MC1/Resources/Localization/uk.lproj/RemoteNodes.strings b/MC1/Resources/Localization/uk.lproj/RemoteNodes.strings index be7d1658e4..b6974cafc4 100644 --- a/MC1/Resources/Localization/uk.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/uk.lproj/RemoteNodes.strings @@ -32,6 +32,8 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Ретранслятор"; +"remoteNodes.auth.typeSensor" = "Датчик"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Автентифікація"; @@ -62,10 +64,18 @@ /* Location: NodeAuthenticationSheet.swift - Flood routing toggle */ "remoteNodes.auth.floodRouting" = "Flood-маршрутизація"; "remoteNodes.auth.floodRetryStatus" = "Немає відповіді за відомим маршрутом. Повторна спроба через flood-маршрутизацію."; -"remoteNodes.auth.floodFooter" = "Flood-маршрутизація повільніша та витрачає більше ефірного часу мережі. Використовуйте її, коли відомий маршрут не працює у вашому поточному місцезнаходженні. Після входу новий маршрут буде визначено автоматично."; +/* Footer when this sign-in will clear the saved route and use flood */ +"remoteNodes.auth.floodFooter" = "Цей вхід видаляє збережений маршрут і використовує flood-маршрутизацію. Flood-маршрутизація повільніша та витрачає більше ефірного часу мережі. Новий маршрут буде визначено, лише якщо вхід успішний."; + +/* Footer after this sign-in has cleared the saved route */ +"remoteNodes.auth.floodFooterCleared" = "Збережений маршрут видалено. Вхід використовує flood-маршрутизацію. Новий маршрут буде визначено, лише якщо вхід успішний."; + + +/* Footer when a timeout clears the route and retries by flood */ +"remoteNodes.auth.pathFooter" = "Якщо немає відповіді, маршрут видаляється, і вхід робить одну спробу через flood-маршрутизацію."; -/* Location: NodeAuthenticationSheet.swift - Path section footer when stored path exists */ -"remoteNodes.auth.pathFooter" = "Використовуйте відомий маршрут до цього вузла або перемкніться на flood-маршрутизацію, щоб мережа знайшла шлях."; +/* Footer when a timeout stops and leaves the route */ +"remoteNodes.auth.pathFooterKept" = "Якщо немає відповіді, вхід зупиняється, і маршрут залишається."; /* Location: NodeAuthenticationSheet.swift - Path hop whose repeater is not known */ "remoteNodes.auth.pathHopUnknown" = "<невідомо>"; @@ -84,6 +94,26 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Налаштування ретранслятора"; +"remoteNodes.sensor.adminRequired" = "Керування датчиком потребує доступу адміністратора."; + +"remoteNodes.sensor.saved" = "Налаштування перевірено."; + +"remoteNodes.sensor.rebootSent" = "Запит на перезавантаження надіслано. Датчик не підтвердив перезапуск. Увійди знову, перш ніж надсилати інші команди."; + +"remoteNodes.sensor.rebootConfirmation" = "Надіслати запит на перезавантаження цьому датчику?"; + +"remoteNodes.sensor.runtimeOnly" = "Зміни впливають на запущений датчик. Чи збережуться вони після перезавантаження, залежить від його прошивки."; + +"remoteNodes.sensor.value" = "Значення"; + +"remoteNodes.sensor.save" = "Зберегти"; + +"remoteNodes.sensor.reload" = "Оновити"; + +"remoteNodes.sensor.empty" = "Цей датчик не надає налаштувань."; + +"remoteNodes.sensor.title" = "Керування датчиком"; + /* Location: RepeaterSettingsView.swift - Done button (used in multiple places) */ "remoteNodes.settings.done" = "Готово"; diff --git a/MC1/Resources/Localization/uk.lproj/Settings.strings b/MC1/Resources/Localization/uk.lproj/Settings.strings index 807e23a4c4..e17dc50a5b 100644 --- a/MC1/Resources/Localization/uk.lproj/Settings.strings +++ b/MC1/Resources/Localization/uk.lproj/Settings.strings @@ -46,9 +46,6 @@ /* Section header for device information */ "device.header" = "Пристрій"; -/* Status shown when device is connected */ -"device.connected" = "Підключено"; - /* Footer shown when no device is connected */ "device.noDeviceConnected" = "Пристрій MeshCore не підключено"; @@ -60,12 +57,6 @@ /* Navigation title for device info screen */ "deviceInfo.title" = "Інформація про пристрій"; -/* Section header for connection status */ -"deviceInfo.connection.header" = "Підключення"; - -/* Label for connection status */ -"deviceInfo.connection.status" = "Статус"; - /* Section header for power and storage */ "deviceInfo.powerStorage.header" = "Живлення та пам'ять"; @@ -111,6 +102,12 @@ /* Firmware version fallback format when no version string is reported - %@ is the numeric version code */ "deviceInfo.firmwareVersionFormat" = "v%@"; +/* Heading above retained telemetry after a Device Info reload fails */ +"deviceInfo.lastSuccessfulReading" = "Останній успішний показник"; + +/* Section header for Device Info telemetry */ +"deviceInfo.telemetry.header" = "Телеметрія вузла"; + /* Section header for identity information */ /* Label for public key */ "deviceInfo.publicKey" = "Публічний ключ"; @@ -165,6 +162,9 @@ /* Button to scan for Bluetooth devices */ "deviceSelection.scanBluetooth" = "Пошук Bluetooth-пристроїв"; +/* Button title while this radio is being paired again */ +"deviceSelection.rePairing" = "Спарування заново..."; + /* Trailing control on a previously paired row that still needs iPhone setup */ /* AI-translated - please verify with native speakers. */ "deviceSelection.setup" = "Налаштувати"; @@ -746,6 +746,21 @@ /* Alert message for clear logs */ "diagnostics.alert.clear.message" = "Це видалить усі збережені журнали налагодження. Експортовані файли журналів не будуть зачеплені."; +/* Toggle to enable collecting local debug logs */ +"diagnostics.collectLogs" = "Збирати журнали налагодження"; + +/* Footer shown when debug log collection is off */ +"diagnostics.footer.disabled" = "Локальні журнали налагодження не збираються."; + +/* Alert title for disabling collection */ +"diagnostics.alert.disable.title" = "Вимкнути збір"; + +/* Button to confirm disabling collection */ +"diagnostics.alert.disable.confirm" = "Вимкнути збір"; + +/* Alert message for disabling collection */ +"diagnostics.alert.disable.message" = "Це видалить усі збережені журнали налагодження та припинить їх збір. Експортовані файли журналів не будуть зачеплені."; + /* Error when export fails */ "diagnostics.error.exportFailed" = "Не вдалося створити файл експорту"; @@ -754,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Чати"; +"blocksAndFilters.title" = "Блокування та фільтри"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -822,6 +839,8 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Компаньйон"; +"notifications.discoveryCompanionsAndSensors" = "Компаньйони і датчики"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Ретранслятор"; @@ -983,6 +1002,9 @@ /* Editor footer when the password is too long */ "radioWiFi.editor.passwordLength" = "Пароль може містити до 63 байт."; +/* Editor footer when a credential contains a character the firmware cannot store */ +"radioWiFi.editor.unsupportedCharacter" = "Назва мережі або пароль містить символ, який це радіо не може зберегти."; + /* Button that clears the radio's saved WiFi settings */ "radioWiFi.clear" = "Очистити налаштування WiFi"; @@ -1148,6 +1170,35 @@ /* Footer explaining the acknowledgments setting */ "directMessages.footer" = "Кількість підтверджень, що надсилаються на кожне особисте повідомлення. Використовуйте 2 для кращого підтвердження доставки через ненадійні з'єднання."; +/* Switch that clears the known route after the path attempts */ +"directMessages.fallback" = "Запасна flood-маршрутизація"; + +/* Picker label for attempts on the known route */ +"directMessages.directAttempts" = "Спроби за маршрутом"; + +/* Picker label for attempts sent by flood after the route is cleared */ +"directMessages.floodAttempts" = "Спроби flood-маршрутизації"; + +/* Footer when Fall Back to Flood is on */ +"directMessages.attemptsFooterOn" = "Після «Спроби за маршрутом» маршрут видаляється. Після цього «Спроби flood-маршрутизації» надсилаються через flood-маршрутизацію. Повідомлення для контакту без відомого маршруту надсилається через flood-маршрутизацію."; + +/* Footer when Fall Back to Flood is off */ +"directMessages.attemptsFooterOff" = "«Спроби за маршрутом» залишаються на відомому маршруті, і маршрут залишається. Повідомлення для контакту без відомого маршруту надсилається через flood-маршрутизацію."; + +// MARK: - Path Fallback + +/* Section header for sign-in, command, and contact telemetry path fallback */ +"pathFallback.header" = "Запасний маршрут"; + +/* Switch that clears the known route after a timeout */ +"pathFallback.fallback" = "Запасна flood-маршрутизація"; + +/* Footer when path fallback is on */ +"pathFallback.footerOn" = "Вхід, команди з очікуванням відповіді для ретранслятора та кімнати, а також телеметрія контакту використовують відомий маршрут. Якщо немає відповіді, маршрут видаляється, і вони роблять одну спробу через flood-маршрутизацію."; + +/* Footer when path fallback is off */ +"pathFallback.footerOff" = "Вхід, команди та телеметрія контакту залишаються на відомому маршруті. Якщо немає відповіді, вони зупиняються, і маршрут залишається. Flood-маршрутизація на екрані входу видаляє збережений маршрут цього вузла."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ @@ -1162,12 +1213,24 @@ /* Menu item to disconnect from the current device */ "bleStatus.disconnect" = "Відключитися"; +/* Menu item to stop automatic reconnection until another explicit connection */ +"bleStatus.stopReconnecting" = "Зупинити перепідключення"; + +/* Menu item to cancel the current connection request */ +"bleStatus.cancelConnection" = "Скасувати підключення"; + /* Status shown when device is disconnected */ "bleStatus.status.disconnected" = "Відключено"; /* Status shown when device is connecting */ "bleStatus.status.connecting" = "Підключення..."; +/* Status shown while reconnecting to the selected device */ +"bleStatus.status.reconnecting" = "Перепідключення..."; + +/* Status shown while automatic reconnection remains enabled between attempts */ +"bleStatus.status.waitingToReconnect" = "Очікування перепідключення"; + /* Status shown when device is connected but not ready */ "bleStatus.status.connected" = "Підключено"; @@ -1180,6 +1243,9 @@ /* Accessibility label for BLE status indicator */ "bleStatus.accessibilityLabel" = "Стан Bluetooth-підключення"; +/* TODO: translate - Accessibility text combining a descriptive prefix and connection state or context; arguments may themselves contain a radio name and status */ +"bleStatus.accessibilityValue" = "%1$@, %2$@"; + /* Accessibility hint when disconnected */ "bleStatus.accessibilityHint.disconnected" = "Подвійний дотик для підключення пристрою"; @@ -1318,6 +1384,24 @@ /* Import failed after one or more settings were already written; %@ is the underlying error message */ "configImport.failedPartial" = "%@ Деякі налаштування, можливо, вже було записано на пристрій. Перевірте конфігурацію пристрою."; +/* Interrupted identity import recovery */ +"configImport.identityOutcomeUnknown" = "З'єднання було перервано під час імпорту ідентифікації на %@. Ідентифікація радіо могла змінитися. Імпорт конфігурації не було завершено."; + +/* Interrupted identity import recovery */ +"configImport.retryIdentityImport" = "Повторити імпорт ідентифікації"; + +/* Interrupted identity import recovery */ +"configImport.confirmIdentityRecovery" = "Це замінить ідентифікацію радіо, доступного через %@, за допомогою закритого ключа з вибраного файлу. Імпорт конфігурації не буде продовжено."; + +/* Confirmation alert title when retrying an interrupted identity import */ +"configImport.confirmTitleIdentityRecovery" = "Замінити ідентифікацію радіо?"; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryComplete" = "Ідентифікацію застосовано повторно. Імпорт конфігурації не було завершено. Імпортуйте файл ще раз, щоб застосувати інші налаштування."; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryKeyRequired" = "Виберіть файл конфігурації із закритим ключем, щоб повторити імпорт ідентифікації."; + /* Import success */ "configImport.importSuccess" = "Конфігурацію успішно імпортовано"; @@ -1434,6 +1518,63 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "Відображення мініатюр карти завантажує плитки для координати зі стороннього сервера, що може розкрити вашу IP-адресу."; +// MARK: - Text Rules + +"textRules.rules" = "Правила фільтрації"; +"textRules.empty" = "Немає правил фільтрації"; +"textRules.loading" = "Завантаження правил фільтрації…"; +"textRules.loadFailed" = "Не вдалося завантажити правила фільтрації. Нові повідомлення не використовуватимуть правила фільтрації, доки їх не вдасться завантажити."; +"textRules.retryAccessibility" = "Спробувати завантажити правила фільтрації ще раз"; +"textRules.saveFailed" = "Не вдалося зберегти правила фільтрації. Спробуй ще раз."; +"textRules.new.title" = "Нове правило"; +"textRules.new.phrase" = "Слово або фраза"; +"textRules.new.lookIn" = "Шукати в"; +"textRules.new.match" = "Збіг"; +"textRules.new.containsMessageFooter" = "Збігається будь-де в повідомленні, зокрема всередині слова."; +"textRules.new.wholeMessageFooter" = "Збігається лише тоді, коли все повідомлення — ця фраза."; +"textRules.new.containsSenderFooter" = "Збігається будь-де в імені відправника, зокрема всередині слова. Реакції від цього відправника також приховано."; +"textRules.new.wholeNameFooter" = "Збігається лише тоді, коли ім'я відправника — точно ця фраза. Реакції від цього відправника також приховано."; +"textRules.new.containsMessageOrSenderFooter" = "Збігається будь-де в повідомленні або в імені відправника, зокрема всередині слова. Якщо збігається ім'я, реакції від цього відправника також приховано."; +"textRules.new.wholeMessageOrSenderFooter" = "Збігається лише тоді, коли все повідомлення або все ім'я відправника — ця фраза. Якщо збігається ім'я, реакції від цього відправника також приховано."; +"textRules.field.message" = "Повідомлення"; +"textRules.field.sender" = "Відправник"; +"textRules.field.messageOrSender" = "Повідомлення або відправник"; +"textRules.match.contains" = "Містить"; +"textRules.match.wholeMessage" = "Все повідомлення"; +"textRules.match.wholeName" = "Все ім'я"; +"textRules.match.wholeField" = "Все поле"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "Використовувати правила для"; +"textRules.types.footer" = "Коли увімкнено, це охоплює всі чати цього типу, зокрема ті, до яких ти приєднаєшся пізніше."; +"textRules.types.publicChannel" = "Публічний"; +"textRules.types.hashtagChannel" = "Хештег-канали"; +"textRules.types.privateChannel" = "Приватні канали"; +"textRules.selection.all" = "Усі"; +"textRules.selection.none" = "Немає"; +"textRules.selection.count" = "%d чатів"; +"textRules.selection.accessibilityChats" = "Чати для %@"; +"textRules.selection.footer" = "«Усі» охоплює чати, до яких ти приєднаєшся пізніше."; +"textRules.archive.title" = "Нещодавно приховані"; +"textRules.archive.empty" = "Немає прихованих повідомлень"; +"textRules.archive.footer" = "На цьому пристрої зберігаються останні %d прихованих повідомлень. Вони не входять до резервної копії застосунку."; +"textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "\U201C%1$@\U201D · %2$@"; +"textRules.archive.rule" = "Правило"; +"textRules.archive.chat" = "Чат"; +"textRules.archive.myNode" = "Мій вузол"; +"textRules.archive.time" = "Час"; +"textRules.archive.unknownConversation" = "Невідома розмова"; +"textRules.archive.unknownRadio" = "Невідоме радіо"; + +"radioCleanup.title" = "Очищення"; +"radioCleanup.running" = "Видалення даних радіо"; +"radioCleanup.failed" = "Приховані повідомлення з цього радіо можуть досі бути в цій інсталяції."; +"radioCleanup.completed" = "Дані радіо видалено"; +"radioCleanup.retryAccessibility" = "Спробувати очищення радіо ще раз для %@"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ @@ -1978,7 +2119,7 @@ "settings.backup.export.alert.title" = "Попередження про безпеку"; /* Export confirmation alert message */ -"settings.backup.export.alert.message" = "Ця резервна копія містить ключі шифрування каналів, історію повідомлень, список контактів, а також локальну мережеву адресу та порт вузла Wi-Fi. Зберігайте експортований файл у безпечному місці."; +"settings.backup.export.alert.message" = "Ця резервна копія містить ключі шифрування каналів, історію повідомлень, список контактів, а також локальну мережеву адресу та порт вузла Wi-Fi. Резервна копія також може містити збережені GPS-координати радіопристроїв. Зберігайте експортований файл у безпечному місці."; /* Export confirmation alert export button */ "settings.backup.export.alert.export" = "Експортувати"; diff --git a/MC1/Resources/Localization/uk.lproj/WhatsNew.strings b/MC1/Resources/Localization/uk.lproj/WhatsNew.strings index cb9e400c84..0fb1ea38b6 100644 --- a/MC1/Resources/Localization/uk.lproj/WhatsNew.strings +++ b/MC1/Resources/Localization/uk.lproj/WhatsNew.strings @@ -65,3 +65,23 @@ "whatsNew.moreChanges.title" = "Більше змін"; /* What's New v1.6 - More changes, description */ "whatsNew.moreChanges.description" = "Натисніть \"Переглянути всі нові зміни\" нижче, щоб побачити повний список виправлень помилок та інших функцій."; + +/* What's New v1.7 - Direct messages, title */ +"whatsNew.directMessages.title" = "Особисті повідомлення"; +/* What's New v1.7 - Direct messages, description */ +"whatsNew.directMessages.description" = "Особисті повідомлення тепер роблять 4 спроби за маршрутом, а потім 4 спроби flood-маршрутизації. Змініть «Спроби за маршрутом», «Спроби flood-маршрутизації» і «Запасна flood-маршрутизація» в «Розширені налаштування»."; + +/* What's New v1.7 - Blocks and filters, title */ +"whatsNew.blocksAndFilters.title" = "Блокування та фільтри"; +/* What's New v1.7 - Blocks and filters, description */ +"whatsNew.blocksAndFilters.description" = "Приховуйте повідомлення, які збігаються зі словом або фразою. Правило може шукати в «Повідомлення», в «Відправник» або в обох, і ви вибираєте, до яких чатів воно застосовується. Приховані повідомлення можна побачити в «Нещодавно приховані» в Налаштування > Блокування та фільтри."; + +/* What's New v1.7 - Node telemetry, title */ +"whatsNew.nodeTelemetry.title" = "Телеметрія вузла"; +/* What's New v1.7 - Node telemetry, description */ +"whatsNew.nodeTelemetry.description" = "Налаштування > Інформація про пристрій показує телеметрію вузла, до якого ви підключені."; + +/* What's New v1.7 - Live Activity, title */ +"whatsNew.liveActivity.title" = "Онлайн-активність"; +/* What's New v1.7 - Live Activity, description */ +"whatsNew.liveActivity.description" = "Непрочитані повідомлення тепер помітніші, а показник пакетів за хвилину легше зрозуміти."; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings b/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings index 5cfe69542b..ce4b3605fd 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings @@ -338,8 +338,8 @@ /* Location: MutedIndicator.swift - Accessibility label for mentions-only indicator */ "chats.row.mentionsOnly" = "仅提及"; -/* TODO: translate - Accessibility label for the row actions menu */ -"chats.row.actionsMenu.accessibilityLabel" = "Conversation actions"; +/* Accessibility label for the row actions menu */ +"chats.row.actionsMenu.accessibilityLabel" = "对话操作"; // MARK: - Notification Level Picker @@ -620,6 +620,12 @@ /* Location: UnifiedMessageBubble.swift - VoiceOver prefix when the visible body is a translation - %@ is the translated text */ "chats.message.translatedAccessibility" = "已翻译:%@"; +/* Location: MessageVisibleBody.swift - VoiceOver prefix when the visible body is an MECP reading - %@ is the reading */ +"chats.message.readingAccessibility" = "已解读:%@"; + +/* Location: MECPCatalog - Person count line in an MECP reading */ +"chats.message.mecpPersonCount" = "%lld 人"; + /* Location: UnifiedMessageBubble.swift - Context menu action to view repeat details */ "chats.message.action.repeatDetails" = "转发详情"; @@ -673,6 +679,9 @@ /* Location: UnifiedMessageBubble.swift - Context menu text showing SNR - %@ is formatted value */ "chats.message.info.snr" = "信噪比:%@"; +/* Location: ActionsDetailsSection.swift - Stored MECP wire string under SNR. %@ is the original text */ +"chats.message.info.mecp" = "MECP:%@"; + /* Location: MessageActionsSheet.swift - Context menu text showing the radio region the message was flooded under - %@ is region name. "Flooded" is a domain term for mesh-broadcast across all nodes in a radio region. */ "chats.message.info.floodedUnder" = "区域:%@"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Chats.stringsdict b/MC1/Resources/Localization/zh-Hans.lproj/Chats.stringsdict new file mode 100644 index 0000000000..2bde580a17 --- /dev/null +++ b/MC1/Resources/Localization/zh-Hans.lproj/Chats.stringsdict @@ -0,0 +1,20 @@ + + + + + chats.message.mecpPersonCount + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + lld + other + %lld 人 + + + + diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Contacts.strings b/MC1/Resources/Localization/zh-Hans.lproj/Contacts.strings index e215b4d858..b59790dbd8 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Contacts.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Contacts.strings @@ -44,6 +44,8 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "房间"; +"contacts.nodeKind.sensor" = "传感器"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "已发现"; @@ -75,6 +77,8 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "房间"; +"contacts.segment.sensors" = "传感器"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "筛选节点"; @@ -168,9 +172,13 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "无房间"; +"contacts.list.empty.sensors.title" = "无传感器"; + /* Location: ContactsListView.swift - Purpose: No rooms empty description */ "contacts.list.empty.rooms.description" = "房间是 Mesh 网络上的公共聊天服务器。发现后会显示在这里。"; +"contacts.list.empty.sensors.description" = "在 Mesh 网络上发现后,传感器会显示在这里。"; + /* Location: ContactsListView.swift - Purpose: No search results title */ "contacts.list.empty.search.title" = "无结果"; @@ -623,6 +631,8 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter: Rooms */ "contacts.discovery.segment.rooms" = "房间"; +"contacts.discovery.segment.sensors" = "传感器"; + /* Location: DiscoverSegmentPicker.swift - Purpose: VoiceOver label for the Discovery segment filter picker (iOS 18 fallback) */ "contacts.discovery.segment.pickerLabel" = "筛选发现的节点"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Localizable.strings b/MC1/Resources/Localization/zh-Hans.lproj/Localizable.strings index 81db72c76b..1a6dc102b0 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Localizable.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Localizable.strings @@ -151,6 +151,8 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "发现新房间"; +"notifications.discovery.sensor" = "发现新传感器"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -496,6 +498,14 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "远程节点响应无效"; +"error.remoteNode.sensorOutcomeUnknown" = "无法验证此更改。请重新加载设置后再保存。"; + +"error.remoteNode.sensorSettingRejected" = "传感器拒绝了此设置。"; + +"error.remoteNode.invalidSensorSetting" = "请使用不含空白字符的非空键和值。完整命令必须在 160 个 UTF-8 字节以内。"; + +"error.remoteNode.invalidPasswordLength" = "密码不得超过 %d 个 UTF-8 字节。"; + /* Location: RemoteNodeError+UserFacingMessage.swift - Remote node rejected the operation */ "error.remoteNode.permissionDenied" = "权限被拒绝"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Map.strings b/MC1/Resources/Localization/zh-Hans.lproj/Map.strings index f1fc58917e..a217ed8da6 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Map.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Map.strings @@ -39,6 +39,8 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "筛选"; +"map.controls.contactsAndSensors" = "联系人和传感器"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "已启用筛选"; @@ -263,6 +265,8 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "房间"; +"map.nodeKind.sensor" = "传感器"; + // MARK: - Contact Callout /* Location: MapView.swift ContactDetailSheet - Purpose: Button to view contact details */ @@ -280,6 +284,8 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "房间"; +"map.callout.nodeKind.sensor" = "传感器"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "添加"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Onboarding.strings b/MC1/Resources/Localization/zh-Hans.lproj/Onboarding.strings index 24fbc40527..3b7bb03a97 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Onboarding.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Onboarding.strings @@ -67,6 +67,9 @@ /* Location: DeviceScanView.swift - Subtitle with pairing instructions */ "deviceScan.subtitle" = "开启设备,断开它与所有其他应用和设备的连接,然后点击「添加设备」。"; +/* Location: DeviceScanView.swift - Subtitle while bond-loss recovery is re-pairing */ +"deviceScan.rePairingSubtitle" = "开启设备,断开它与所有其他应用和设备的连接。"; + /* Location: DeviceScanView.swift - Message shown when device is already paired */ "deviceScan.alreadyPaired" = "您的设备已配对"; @@ -76,9 +79,6 @@ /* Location: DeviceScanView.swift - Button to continue after pairing */ "deviceScan.continue" = "继续"; -/* Location: DeviceScanView.swift - Button label while connecting */ -"deviceScan.connecting" = "连接中..."; - /* Location: DeviceScanView.swift - Button to connect simulator (debug) */ "deviceScan.connectSimulator" = "连接模拟器"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/RemoteNodes.strings b/MC1/Resources/Localization/zh-Hans.lproj/RemoteNodes.strings index 74f6a0a7a9..09e73110d7 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/RemoteNodes.strings @@ -32,6 +32,8 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "转发节点"; +"remoteNodes.auth.typeSensor" = "传感器"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "身份验证"; @@ -62,10 +64,18 @@ /* Location: NodeAuthenticationSheet.swift - Flood routing toggle */ "remoteNodes.auth.floodRouting" = "泛洪路由"; "remoteNodes.auth.floodRetryStatus" = "已知路由无响应。正在改用泛洪路由重试。"; -"remoteNodes.auth.floodFooter" = "泛洪路由速度更慢,且占用更多网络空中时间。当已知路由在当前位置不可用时再使用。登录后会自动学习新路由。"; +/* Footer when this sign-in will clear the saved route and use flood */ +"remoteNodes.auth.floodFooter" = "此次登录会清除已保存的路由,并使用泛洪。泛洪路由速度更慢,且占用更多网络空中时间。登录成功后才会学习新路由。"; + +/* Footer after this sign-in has cleared the saved route */ +"remoteNodes.auth.floodFooterCleared" = "已保存的路由已清除。正在使用泛洪登录。登录成功后才会学习新路由。"; + + +/* Footer when a timeout clears the route and retries by flood */ +"remoteNodes.auth.pathFooter" = "如果没有回复,将清除路由,登录会以泛洪尝试一次。"; -/* Location: NodeAuthenticationSheet.swift - Path section footer when stored path exists */ -"remoteNodes.auth.pathFooter" = "使用已知路由到此节点,或切换到泛洪路由让网络自动寻找路径。"; +/* Footer when a timeout stops and leaves the route */ +"remoteNodes.auth.pathFooterKept" = "如果没有回复,登录会停止,路由将保留。"; /* Location: NodeAuthenticationSheet.swift - Path hop whose repeater is not known */ "remoteNodes.auth.pathHopUnknown" = "<未知>"; @@ -84,6 +94,26 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "转发节点设置"; +"remoteNodes.sensor.adminRequired" = "传感器管理需要管理员权限。"; + +"remoteNodes.sensor.saved" = "设置已验证。"; + +"remoteNodes.sensor.rebootSent" = "已发送重启请求。传感器尚未确认已重启。请重新登录后再发送更多命令。"; + +"remoteNodes.sensor.rebootConfirmation" = "是否向此传感器发送重启请求?"; + +"remoteNodes.sensor.runtimeOnly" = "更改会影响正在运行的传感器。重启后是否仍然有效取决于其固件。"; + +"remoteNodes.sensor.value" = "值"; + +"remoteNodes.sensor.save" = "保存"; + +"remoteNodes.sensor.reload" = "重新加载"; + +"remoteNodes.sensor.empty" = "此传感器没有设置。"; + +"remoteNodes.sensor.title" = "传感器管理"; + /* Location: RepeaterSettingsView.swift - Done button (used in multiple places) */ "remoteNodes.settings.done" = "完成"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings index f6fdeb8d8c..3ccefce9d7 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings @@ -46,9 +46,6 @@ /* Section header for device information */ "device.header" = "设备"; -/* Status shown when device is connected */ -"device.connected" = "已连接"; - /* Footer shown when no device is connected */ "device.noDeviceConnected" = "未连接 MeshCore 设备"; @@ -60,12 +57,6 @@ /* Navigation title for device info screen */ "deviceInfo.title" = "设备信息"; -/* Section header for connection status */ -"deviceInfo.connection.header" = "连接"; - -/* Label for connection status */ -"deviceInfo.connection.status" = "状态"; - /* Section header for power and storage */ "deviceInfo.powerStorage.header" = "电源和存储"; @@ -111,6 +102,12 @@ /* Firmware version fallback format when no version string is reported - %@ is the numeric version code */ "deviceInfo.firmwareVersionFormat" = "v%@"; +/* Heading above retained telemetry after a Device Info reload fails */ +"deviceInfo.lastSuccessfulReading" = "上次成功读数"; + +/* Section header for Device Info telemetry */ +"deviceInfo.telemetry.header" = "节点遥测数据"; + /* Section header for identity information */ /* Label for public key */ "deviceInfo.publicKey" = "查看公钥"; @@ -165,6 +162,9 @@ /* Button to scan for Bluetooth devices */ "deviceSelection.scanBluetooth" = "扫描蓝牙设备"; +/* Button title while this radio is being paired again */ +"deviceSelection.rePairing" = "重新配对中..."; + /* Trailing control on a previously paired row that still needs iPhone setup */ /* AI-translated - please verify with native speakers. */ "deviceSelection.setup" = "设置"; @@ -746,6 +746,21 @@ /* Alert message for clear logs */ "diagnostics.alert.clear.message" = "这将删除所有存储的调试日志。导出的日志文件不会受到影响。"; +/* Toggle to enable collecting local debug logs */ +"diagnostics.collectLogs" = "收集调试日志"; + +/* Footer shown when debug log collection is off */ +"diagnostics.footer.disabled" = "不收集本地调试日志。"; + +/* Alert title for disabling collection */ +"diagnostics.alert.disable.title" = "停用收集"; + +/* Button to confirm disabling collection */ +"diagnostics.alert.disable.confirm" = "停用收集"; + +/* Alert message for disabling collection */ +"diagnostics.alert.disable.message" = "这将删除所有存储的调试日志并停止收集。导出的日志文件不会受到影响。"; + /* Error when export fails */ "diagnostics.error.exportFailed" = "创建导出文件失败"; @@ -754,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "聊天"; +"blocksAndFilters.title" = "屏蔽与过滤"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -857,6 +874,8 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "伴侣节点"; +"notifications.discoveryCompanionsAndSensors" = "伴侣节点和传感器"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "中继器"; @@ -1018,6 +1037,9 @@ /* Editor footer when the password is too long */ "radioWiFi.editor.passwordLength" = "密码最多为 63 字节。"; +/* Editor footer when a credential contains a character the firmware cannot store */ +"radioWiFi.editor.unsupportedCharacter" = "网络名称或密码包含此无线电无法存储的字符。"; + /* Button that clears the radio's saved WiFi settings */ "radioWiFi.clear" = "清除 WiFi 设置"; @@ -1183,6 +1205,35 @@ /* Footer explaining the acknowledgments setting */ "directMessages.footer" = "每条私信发送的确认数量。在不可靠的链路上使用 2 以获得更好的送达确认。"; +/* Switch that clears the known route after the path attempts */ +"directMessages.fallback" = "回退到泛洪"; + +/* Picker label for attempts on the known route */ +"directMessages.directAttempts" = "路径尝试"; + +/* Picker label for attempts sent by flood after the route is cleared */ +"directMessages.floodAttempts" = "泛洪尝试"; + +/* Footer when Fall Back to Flood is on */ +"directMessages.attemptsFooterOn" = "完成“路径尝试”后,将清除路由。随后,“泛洪尝试”会以泛洪发送。没有已知路由的联系人,消息会以泛洪发送。"; + +/* Footer when Fall Back to Flood is off */ +"directMessages.attemptsFooterOff" = "“路径尝试”始终使用已知路由,路由将保留。没有已知路由的联系人,消息会以泛洪发送。"; + +// MARK: - Path Fallback + +/* Section header for sign-in, command, and contact telemetry path fallback */ +"pathFallback.header" = "路径回退"; + +/* Switch that clears the known route after a timeout */ +"pathFallback.fallback" = "回退到泛洪"; + +/* Footer when path fallback is on */ +"pathFallback.footerOn" = "登录、等待回复的转发节点命令和房间命令,以及联系人遥测,都使用已知路由。如果没有回复,将清除路由,并以泛洪尝试一次。"; + +/* Footer when path fallback is off */ +"pathFallback.footerOff" = "登录、命令和联系人遥测始终使用已知路由。如果没有回复,就会停止,路由将保留。登录界面上的“泛洪路由”会清除该节点已保存的路由。"; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ @@ -1197,12 +1248,24 @@ /* Menu item to disconnect from the current device */ "bleStatus.disconnect" = "断开连接"; +/* Menu item to stop automatic reconnection until another explicit connection */ +"bleStatus.stopReconnecting" = "停止重新连接"; + +/* Menu item to cancel the current connection request */ +"bleStatus.cancelConnection" = "取消连接"; + /* Status shown when device is disconnected */ "bleStatus.status.disconnected" = "已断开"; /* Status shown when device is connecting */ "bleStatus.status.connecting" = "连接中..."; +/* Status shown while reconnecting to the selected device */ +"bleStatus.status.reconnecting" = "正在重新连接..."; + +/* Status shown while automatic reconnection remains enabled between attempts */ +"bleStatus.status.waitingToReconnect" = "等待重新连接"; + /* Status shown when device is connected but not ready */ "bleStatus.status.connected" = "已连接"; @@ -1215,6 +1278,9 @@ /* Accessibility label for BLE status indicator */ "bleStatus.accessibilityLabel" = "蓝牙连接状态"; +/* TODO: translate - Accessibility text combining a descriptive prefix and connection state or context; arguments may themselves contain a radio name and status */ +"bleStatus.accessibilityValue" = "%1$@, %2$@"; + /* Accessibility hint when disconnected */ "bleStatus.accessibilityHint.disconnected" = "双击以连接设备"; @@ -1318,6 +1384,24 @@ /* Import failed after one or more settings were already written; %@ is the underlying error message */ "configImport.failedPartial" = "%@ 部分设置可能已写入设备。请检查设备的配置。"; +/* Interrupted identity import recovery */ +"configImport.identityOutcomeUnknown" = "向 %@ 导入身份时连接中断。无线电的身份可能已更改。配置导入未完成。"; + +/* Interrupted identity import recovery */ +"configImport.retryIdentityImport" = "重试身份导入"; + +/* Interrupted identity import recovery */ +"configImport.confirmIdentityRecovery" = "此操作将使用所选文件中的私钥,替换通过 %@ 连接的无线电的身份。配置导入不会继续。"; + +/* Confirmation alert title when retrying an interrupted identity import */ +"configImport.confirmTitleIdentityRecovery" = "替换无线电身份?"; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryComplete" = "身份已重新应用。配置导入未完成。请再次导入文件以应用其他设置。"; + +/* Interrupted identity import recovery */ +"configImport.identityRecoveryKeyRequired" = "请选择包含私钥的配置文件以重试身份导入。"; + /* Import success */ "configImport.importSuccess" = "配置导入成功"; @@ -1434,6 +1518,63 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "显示地图缩略图会从第三方服务器获取该坐标的地图图块,可能会暴露您的IP地址。"; +// MARK: - Text Rules + +"textRules.rules" = "过滤规则"; +"textRules.empty" = "没有过滤规则"; +"textRules.loading" = "正在加载过滤规则…"; +"textRules.loadFailed" = "无法加载过滤规则。在过滤规则加载成功之前,新消息不会使用过滤规则。"; +"textRules.retryAccessibility" = "重新加载过滤规则"; +"textRules.saveFailed" = "无法保存过滤规则。请重试。"; +"textRules.new.title" = "新规则"; +"textRules.new.phrase" = "词或文字"; +"textRules.new.lookIn" = "查找范围"; +"textRules.new.match" = "匹配"; +"textRules.new.containsMessageFooter" = "只要在消息中出现就会匹配,包括某个词的一部分。"; +"textRules.new.wholeMessageFooter" = "仅当整条消息就是这段文字时才会匹配。"; +"textRules.new.containsSenderFooter" = "只要在发送者名称中出现就会匹配,包括某个词的一部分。该发送者的表情反应也会被隐藏。"; +"textRules.new.wholeNameFooter" = "仅当发送者名称正好是这段文字时才会匹配。该发送者的表情反应也会被隐藏。"; +"textRules.new.containsMessageOrSenderFooter" = "只要在消息或发送者名称中出现就会匹配,包括某个词的一部分。发送者名称匹配时,其表情反应也会被隐藏。"; +"textRules.new.wholeMessageOrSenderFooter" = "仅当整条消息或发送者的整个名称就是这段文字时才会匹配。发送者名称匹配时,其表情反应也会被隐藏。"; +"textRules.field.message" = "消息"; +"textRules.field.sender" = "发送者"; +"textRules.field.messageOrSender" = "消息或发送者"; +"textRules.match.contains" = "包含"; +"textRules.match.wholeMessage" = "整条消息"; +"textRules.match.wholeName" = "整个名称"; +"textRules.match.wholeField" = "整个字段"; +"textRules.ruleSummary" = "%1$@ · %2$@"; +"textRules.types.header" = "将规则用于"; +"textRules.types.footer" = "开启后,该类型的所有聊天都会包括在内,包括您之后加入的聊天。"; +"textRules.types.publicChannel" = "公共"; +"textRules.types.hashtagChannel" = "标签频道"; +"textRules.types.privateChannel" = "私人频道"; +"textRules.selection.all" = "全部"; +"textRules.selection.none" = "无"; +"textRules.selection.count" = "%d 个聊天"; +"textRules.selection.accessibilityChats" = "%@的聊天"; +"textRules.selection.footer" = "“全部”会包括您之后加入的聊天。"; +"textRules.archive.title" = "最近隐藏的消息"; +"textRules.archive.empty" = "没有隐藏消息"; +"textRules.archive.footer" = "最近的 %d 条隐藏消息会保留在此设备上。这些消息不会包含在应用备份中。"; +"textRules.archive.labelPrefix" = "%@: "; +/* Recently Blocked row. %1$@ is the chat, %2$@ is the matched phrase, %3$@ is the rule summary. */ +"textRules.archive.caption" = "%1$@ · “%2$@” · %3$@"; +/* Recently Blocked row when the chat name is missing. %1$@ is the matched phrase, %2$@ is the rule summary. */ +"textRules.archive.captionWithoutChat" = "“%1$@” · %2$@"; +"textRules.archive.rule" = "规则"; +"textRules.archive.chat" = "聊天"; +"textRules.archive.myNode" = "我的节点"; +"textRules.archive.time" = "时间"; +"textRules.archive.unknownConversation" = "未知对话"; +"textRules.archive.unknownRadio" = "未知无线电"; + +"radioCleanup.title" = "清理"; +"radioCleanup.running" = "正在移除无线电数据"; +"radioCleanup.failed" = "此无线电的隐藏消息可能仍留在此应用安装中。"; +"radioCleanup.completed" = "无线电数据已移除"; +"radioCleanup.retryAccessibility" = "再次尝试清理 %@ 的无线电"; + // MARK: - Blocking Section /* Location: BlockingSection.swift - Purpose: Section header */ @@ -1978,7 +2119,7 @@ "settings.backup.export.alert.title" = "安全提示"; /* Export confirmation alert message */ -"settings.backup.export.alert.message" = "此备份包含频道加密密钥、消息历史、联系人列表以及 WiFi 节点的本地网络地址和端口。请妥善保管导出的文件。"; +"settings.backup.export.alert.message" = "此备份包含频道加密密钥、消息历史、联系人列表以及 WiFi 节点的本地网络地址和端口。此备份还可能包含已记录的电台 GPS 坐标。请妥善保管导出的文件。"; /* Export confirmation alert export button */ "settings.backup.export.alert.export" = "导出"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/WhatsNew.strings b/MC1/Resources/Localization/zh-Hans.lproj/WhatsNew.strings index d03b346e89..a697ee22fb 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/WhatsNew.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/WhatsNew.strings @@ -65,3 +65,23 @@ "whatsNew.moreChanges.title" = "更多变化"; /* What's New v1.6 - More changes, description */ "whatsNew.moreChanges.description" = "点击下方的\"查看全部新变化\"可查看错误修复和其他功能的完整列表。"; + +/* What's New v1.7 - Direct messages, title */ +"whatsNew.directMessages.title" = "私信"; +/* What's New v1.7 - Direct messages, description */ +"whatsNew.directMessages.description" = "私信现在会先沿路径尝试 4 次,然后泛洪 4 次。可在高级设置中更改路径尝试、泛洪尝试和回退到泛洪。"; + +/* What's New v1.7 - Blocks and filters, title */ +"whatsNew.blocksAndFilters.title" = "屏蔽与过滤"; +/* What's New v1.7 - Blocks and filters, description */ +"whatsNew.blocksAndFilters.description" = "可隐藏与一个词或一段文字匹配的消息。规则的查找范围可以是消息、发送者名称或两者,并可选择将规则用于哪些聊天。隐藏消息可在设置 > 屏蔽与过滤下的“最近隐藏的消息”中查看。"; + +/* What's New v1.7 - Node telemetry, title */ +"whatsNew.nodeTelemetry.title" = "节点遥测数据"; +/* What's New v1.7 - Node telemetry, description */ +"whatsNew.nodeTelemetry.description" = "设置 > 设备信息会显示当前所连接节点的遥测数据。"; + +/* What's New v1.7 - Live Activity, title */ +"whatsNew.liveActivity.title" = "实时活动"; +/* What's New v1.7 - Live Activity, description */ +"whatsNew.liveActivity.description" = "未读消息更醒目,每分钟的数据包速率更容易理解。"; diff --git a/MC1/Services/InlineImageCache.swift b/MC1/Services/InlineImageCache.swift index 0ed838055c..463e9c2ec1 100644 --- a/MC1/Services/InlineImageCache.swift +++ b/MC1/Services/InlineImageCache.swift @@ -100,6 +100,7 @@ actor InlineImageCache { /// Registers the persistence sink for successful probes. Held strongly; /// later calls overwrite the reference so each connection's store wins. func attachDimensionsStore(_ store: InlineImageDimensionsStore) { + guard !Task.isCancelled else { return } dimensionsStore = store } diff --git a/MC1/Services/LocationService.swift b/MC1/Services/LocationService.swift index 74f588cf8a..f6949ad3f3 100644 --- a/MC1/Services/LocationService.swift +++ b/MC1/Services/LocationService.swift @@ -196,14 +196,12 @@ final class LocationService: NSObject, CLLocationManagerDelegate { authorizationContinuation.resume(returning: status) } - if status == .denied || status == .restricted { - if let continuation = self.requestContinuation { - self.requestContinuation = nil - self.locationTimeoutTask?.cancel() - self.locationTimeoutTask = nil - self.isRequestingLocation = false - continuation.resume(throwing: LocationServiceError.notAuthorized(status)) - } + if status == .denied || status == .restricted, let continuation = self.requestContinuation { + self.requestContinuation = nil + self.locationTimeoutTask?.cancel() + self.locationTimeoutTask = nil + self.isRequestingLocation = false + continuation.resume(throwing: LocationServiceError.notAuthorized(status)) } } } diff --git a/MC1/Services/NotificationStringProviderImpl.swift b/MC1/Services/NotificationStringProviderImpl.swift index 6cbd8f44fe..5c86bdaf2e 100644 --- a/MC1/Services/NotificationStringProviderImpl.swift +++ b/MC1/Services/NotificationStringProviderImpl.swift @@ -11,6 +11,8 @@ struct NotificationStringProviderImpl: NotificationStringProvider { L10n.Localizable.Notifications.Discovery.repeater case .room: L10n.Localizable.Notifications.Discovery.room + case .sensor: + L10n.Localizable.Notifications.Discovery.sensor } } diff --git a/MC1/Settings.bundle/Acknowledgements.plist b/MC1/Settings.bundle/Acknowledgements.plist index 669fc91616..74413750e6 100644 --- a/MC1/Settings.bundle/Acknowledgements.plist +++ b/MC1/Settings.bundle/Acknowledgements.plist @@ -82,6 +82,14 @@ Type PSChildPaneSpecifier + + File + Packages/MECP + Title + MECP + Type + PSChildPaneSpecifier + StringsTable Acknowledgements diff --git a/MC1/Settings.bundle/Packages/MECP.plist b/MC1/Settings.bundle/Packages/MECP.plist new file mode 100644 index 0000000000..436f835a3e --- /dev/null +++ b/MC1/Settings.bundle/Packages/MECP.plist @@ -0,0 +1,411 @@ + + + + + PreferenceSpecifiers + + + FooterText + Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. + + + Type + PSGroupSpecifier + + + + diff --git a/MC1/State/AppConnectionWiringJob.swift b/MC1/State/AppConnectionWiringJob.swift new file mode 100644 index 0000000000..21f496426e --- /dev/null +++ b/MC1/State/AppConnectionWiringJob.swift @@ -0,0 +1,62 @@ +import Foundation + +@MainActor +final class AppConnectionWiringJob { + let id: UUID + let generation: UUID + private var worker: Task? + private var waiters: [UUID: CheckedContinuation] = [:] + private var isCancelled = false + private var isFinished = false + + #if DEBUG + var waitingCallerCount: Int { + waiters.count + } + #endif + + init(id: UUID, generation: UUID, operation: @escaping @MainActor () async -> Void) { + self.id = id + self.generation = generation + worker = Task { [weak self] in + guard let self else { return } + await operation() + isFinished = true + resumeAllWaiters() + worker = nil + } + } + + /// Native UI awaits can outlive cancellation. Retiring a caller must release + /// its connection worker while the guarded app operation finishes separately. + func wait() async { + let waiterID = UUID() + await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + if Task.isCancelled || isCancelled || isFinished { + continuation.resume() + } else { + waiters[waiterID] = continuation + } + } + } onCancel: { + Task { @MainActor [weak self] in + self?.waiters.removeValue(forKey: waiterID)?.resume() + } + } + } + + func cancel() { + isCancelled = true + worker?.cancel() + resumeAllWaiters() + } + + private func resumeAllWaiters() { + let pending = Array(waiters.values) + waiters.removeAll() + for waiter in pending { + waiter.resume() + } + } +} diff --git a/MC1/State/AppState+ChatPrefetch.swift b/MC1/State/AppState+ChatPrefetch.swift index c9c1bc9a47..a0c51de03a 100644 --- a/MC1/State/AppState+ChatPrefetch.swift +++ b/MC1/State/AppState+ChatPrefetch.swift @@ -17,23 +17,22 @@ extension AppState { /// live conversation view and the navigation-time prefetch so the two cannot /// drift into wiring different services. @MainActor - func makeChatViewModelDependencies() -> ChatViewModel.Dependencies { + func makeChatViewModelDependencies(radioID: UUID) -> ChatViewModel.Dependencies { ChatViewModel.Dependencies( - dataStore: { self.offlineDataStore }, - messageService: { self.services?.messageService }, - notificationService: { self.services?.notificationService }, - channelService: { self.services?.channelService }, - roomServerService: { self.services?.roomServerService }, - contactService: { self.services?.contactService }, - syncCoordinator: { self.syncCoordinator }, + dataStore: { self.currentRadioID == radioID ? self.offlineDataStore : nil }, + messageService: { self.connectionSnapshot(for: radioID)?.services.messageService }, + notificationService: { self.connectionSnapshot(for: radioID)?.services.notificationService }, + channelService: { self.connectionSnapshot(for: radioID)?.services.channelService }, + roomServerService: { self.connectionSnapshot(for: radioID)?.services.roomServerService }, + contactService: { self.connectionSnapshot(for: radioID)?.services.contactService }, + syncCoordinator: { self.connectionSnapshot(for: radioID)?.services.syncCoordinator }, connectionState: { self.connectionState }, - connectedDevice: { self.connectedDevice }, + connectedDevice: { self.connectionSnapshot(for: radioID)?.device }, currentRadioID: { self.currentRadioID }, - session: { self.services?.session }, - reactionService: { self.services?.reactionService }, - chatSendQueueService: { self.services?.chatSendQueueService }, - inlineImageDimensionsStore: { self.services?.inlineImageDimensionsStore }, - prefetchDataStore: { self.services?.dataStore } + reactionService: { self.connectionSnapshot(for: radioID)?.services.reactionService }, + chatSendQueueService: { self.connectionSnapshot(for: radioID)?.services.chatSendQueueService }, + inlineImageDimensionsStore: { self.connectionSnapshot(for: radioID)?.services.inlineImageDimensionsStore }, + prefetchDataStore: { self.connectionSnapshot(for: radioID)?.services.dataStore } ) } @@ -111,17 +110,8 @@ extension AppState { ) } - /// Warms the shared `ChatCoordinator` for `conversation` before its view is - /// pushed, so the conversation renders populated on the first frame instead of - /// popping in a frame after the push transition (the cold-open jump). The - /// coordinator persists in the registry, so a re-open reuses the warm entry — - /// this no-ops when it is already loaded. - /// - /// Fire-and-forget on a `ChatTimelinePrimer`: only the shared coordinator - /// (held by the registry) outlives the prime, and `ChatConversationView` - /// rebinds it on open. The prime deliberately skips notification - /// suppression, unread clearing, and flood-scope pushes — those belong to - /// the real open, not a speculative warm. + /// Primes a closed conversation for first-frame rendering. The registry keeps + /// the populated coordinator so `ChatConversationView` can reuse it on open. @MainActor func prefetchConversation(_ conversation: ChatConversationType, envInputs: EnvInputs) { guard let registry = ensureChatCoordinatorRegistry() else { return } diff --git a/MC1/State/AppState+ConnectionSource.swift b/MC1/State/AppState+ConnectionSource.swift new file mode 100644 index 0000000000..d6951e5204 --- /dev/null +++ b/MC1/State/AppState+ConnectionSource.swift @@ -0,0 +1,12 @@ +import Foundation +import MC1Services + +extension AppState { + func connectionSnapshot(for radioID: UUID) -> ConnectionSnapshot? { + guard let snapshot = connectionManager.currentConnection, + snapshot.device.radioID == radioID, + connectionManager.isCurrent(snapshot), + snapshot.services.isAcceptingRuntimeWork else { return nil } + return snapshot + } +} diff --git a/MC1/State/AppState+DeviceActions.swift b/MC1/State/AppState+DeviceActions.swift index c50b0359ea..bd916d5762 100644 --- a/MC1/State/AppState+DeviceActions.swift +++ b/MC1/State/AppState+DeviceActions.swift @@ -5,167 +5,13 @@ import MC1Services // MARK: - Device Actions extension AppState { - /// ASK Remove Accessory leaves the scene unable to present `showPicker`. - /// Retry once after a short delay in case `.active` already fired. - private static let freshPairingForegroundRetryDelay: Duration = .milliseconds(400) - - /// Start device scan/pairing - func startDeviceScan() { - // Hide disconnected pill when starting new connection - connectionUI.hideDisconnectedPill() - // Clear any previous pairing failure state - connectionUI.failedPairingDeviceID = nil - connectionUI.isBusy = true - connectionManager.isPairingFlowActive = true - - Task { - defer { - connectionUI.isBusy = false - if connectionUI.pendingSystemPairingSetup == nil, - connectionUI.queuedSystemPairingSetup == nil, - !connectionUI.shouldCompleteFreshPairingOnForeground { - connectionManager.isPairingFlowActive = false - } - } - await withPairingFlowErrorHandling { - let pending = try await connectionManager.systemAccessoriesMissingDeviceRecord() - if !pending.isEmpty { - if connectionUI.pendingSystemPairingSetup == nil { - connectionUI.pendingSystemPairingSetup = SystemPairingSetupPrompt( - accessories: pending.map { SystemPairedAccessory(id: $0.id, name: $0.name) } - ) - } - return - } - try await completeFreshPairing() - } - } - } - - func cancelSystemPairingSetup() { - connectionUI.pendingSystemPairingSetup = nil - connectionUI.queuedSystemPairingSetup = nil - connectionUI.shouldCompleteFreshPairingOnForeground = false - isFreshPairingForegroundRetry = false - connectionManager.isPairingFlowActive = false - } - - func handleSystemPairingSetupSheetDismissed() { - guard !isConfirmingSystemPairingSetup else { return } - guard connectionUI.pendingSystemPairingSetup == nil else { return } - cancelSystemPairingSetup() - } - - /// Forget the pending ASK accessories, then open the picker. Clears pending first so - /// iOS Remove Accessory is the only dialog; siblings do not re-prompt. - func confirmSystemPairingSetup() { - guard let prompt = connectionUI.pendingSystemPairingSetup else { return } - isConfirmingSystemPairingSetup = true - connectionManager.isPairingFlowActive = true - connectionUI.shouldShowPickerOnForeground = false - connectionUI.pendingSystemPairingSetup = nil - connectionUI.isBusy = true - Task { - defer { - connectionUI.isBusy = false - isConfirmingSystemPairingSetup = false - if !connectionUI.shouldCompleteFreshPairingOnForeground { - connectionManager.isPairingFlowActive = false - } - } - await withPairingFlowErrorHandling { - try await connectionManager.removeSystemAccessoriesMissingDeviceRecord(prompt.accessories.map(\.id)) - try await completeFreshPairing() - } - } - } - - private func completeFreshPairing() async throws { - if connectionState != .disconnected { - await disconnect(reason: .switchingDevice) - } - try await connectionManager.pairNewDevice() - await wireServicesIfConnected() - if !onboarding.hasCompletedOnboarding { - onboarding.onboardingPath.append(.region) - } - } - - private func withPairingFlowErrorHandling(_ work: () async throws -> Void) async { - do { - try await work() - } catch DevicePairingError.cancelled { - // Picker dismissed, or iOS Remove Accessory declined. Do not re-prompt. - connectionUI.shouldCompleteFreshPairingOnForeground = false - isFreshPairingForegroundRetry = false - } catch DevicePairingError.alreadyInProgress { - } catch DevicePairingError.pickerUnavailable { - handlePickerUnavailableAfterForget() - } catch let pairingError as PairingError { - connectionUI.presentFreshPairingFailure(pairingError) - } catch { - connectionUI.presentConnectionFailure(message: error.userFacingMessage) - } - } - - /// ASK rejected the picker because Remove Accessory still owns the scene. - /// Retry `pairNewDevice` on the next `.active` (and once after a short delay - /// if that transition already happened). A second rejection is a real failure. - private func handlePickerUnavailableAfterForget() { - if isFreshPairingForegroundRetry { - isFreshPairingForegroundRetry = false - connectionUI.shouldCompleteFreshPairingOnForeground = false - connectionManager.isPairingFlowActive = false - connectionUI.presentConnectionFailure( - message: L10n.Localizable.Error.AccessorySetup.pickerRestricted - ) - return - } - scheduleFreshPairingOnForeground() - } - - private func scheduleFreshPairingOnForeground() { - connectionUI.shouldCompleteFreshPairingOnForeground = true - connectionManager.isPairingFlowActive = true - Task { - try? await Task.sleep(for: Self.freshPairingForegroundRetryDelay) - await resumeFreshPairingIfNeeded() - } - } - - private func resumeFreshPairingIfNeeded() async { - guard connectionUI.shouldCompleteFreshPairingOnForeground else { return } - connectionUI.shouldCompleteFreshPairingOnForeground = false - isFreshPairingForegroundRetry = true - connectionUI.isBusy = true - connectionManager.isPairingFlowActive = true - defer { - connectionUI.isBusy = false - isFreshPairingForegroundRetry = false - if !connectionUI.shouldCompleteFreshPairingOnForeground { - connectionManager.isPairingFlowActive = false - } - } - await withPairingFlowErrorHandling { - try await completeFreshPairing() - } - } - - /// Remove a device that failed pairing (wrong PIN) and automatically retry - func removeFailedPairingAndRetry() { - guard let deviceID = connectionUI.failedPairingDeviceID else { return } - - Task { - await connectionManager.removeFailedPairing(deviceID: deviceID) - connectionUI.failedPairingDeviceID = nil - if connectionManager.hasSystemPairingRegistry { - // Remove Accessory can bounce the scene; wait for `.active`. - connectionUI.shouldShowPickerOnForeground = true - } else { - // No registry confirmation, so `.active` will not re-fire. - startDeviceScan() - } + func currentConnectionFailure(_ error: any Error) -> (any Error)? { + if error is CancellationError { return nil } + if let failure = error as? ConnectionRequestFailure { + guard connectionManager.isCurrent(failure), !(failure.underlying is CancellationError) else { return nil } + return failure.underlying } + return error } /// Retry connecting to the device that just failed without removing the bond. @@ -174,18 +20,26 @@ extension AppState { /// because the bond itself needs to be torn down before retrying. func retryFailedPairingConnect() async { guard let deviceID = connectionUI.failedPairingDeviceID else { return } - connectionUI.isBusy = true - defer { connectionUI.isBusy = false } - + let episodeID = connectionUI.pairingFailureEpisodeID + let actionID = connectionUI.beginConnectionAction() + defer { + connectionUI.finishConnectionAction(actionID) + } do { - try await connectionManager.connect(to: deviceID, forceReconnect: true) - connectionUI.failedPairingDeviceID = nil - await wireServicesIfConnected() - } catch BLEError.deviceConnectedToOtherApp { + let result = try await connectionManager.connect(to: deviceID, forceReconnect: true) + guard case let .operational(snapshot) = result, connectionManager.isCurrent(snapshot) else { return } + await wireServices(for: snapshot) + guard connectionManager.isCurrent(snapshot), connectionUI.pairingFailureEpisodeID == episodeID else { return } connectionUI.failedPairingDeviceID = nil - connectionUI.presentPairingFailure(.deviceConnectedToOtherApp(deviceID: deviceID)) } catch { - connectionUI.presentPairingFailure(.connectionFailed(deviceID: deviceID, underlying: error)) + guard connectionUI.pairingFailureEpisodeID == episodeID, + let failure = currentConnectionFailure(error) else { return } + if case BLEError.deviceConnectedToOtherApp = failure { + connectionUI.failedPairingDeviceID = nil + connectionUI.presentPairingFailure(.deviceConnectedToOtherApp(deviceID: deviceID)) + } else { + connectionUI.presentPairingFailure(.connectionFailed(deviceID: deviceID, underlying: failure)) + } } } @@ -200,27 +54,20 @@ extension AppState { // from the foreground reconnect instead of staying silenced from background. connectionManager.clearSurfacedAuthenticationFailure() - if connectionUI.shouldCompleteFreshPairingOnForeground { - Task { await resumeFreshPairingIfNeeded() } + if shouldCompleteFreshPairingOnForeground { + resumeFreshPairingIfNeeded() return } - if connectionUI.shouldShowPickerOnForeground, - connectionUI.pendingSystemPairingSetup == nil, - connectionUI.queuedSystemPairingSetup == nil { - connectionUI.shouldShowPickerOnForeground = false - startDeviceScan() - } - activeRecoveryFallbackTask?.cancel() activeRecoveryFallbackTask = Task { @MainActor [weak self] in guard let self else { return } try? await Task.sleep(for: .seconds(1)) - guard !Task.isCancelled else { return } - guard !connectionManager.shouldDeferOpportunisticReconnect, + guard !Task.isCancelled, + !connectionManager.shouldDeferOpportunisticReconnect, connectionUI.pendingSystemPairingSetup == nil, - connectionUI.queuedSystemPairingSetup == nil else { return } - guard connectionState == .disconnected, + connectionUI.queuedSystemPairingSetup == nil, + connectionState == .disconnected, connectionManager.lastConnectedDeviceID != nil else { return } logger.info("[BLE] Active fallback: disconnected after activation, running foreground reconciliation") @@ -232,11 +79,18 @@ extension AppState { /// - Parameter reason: The reason for disconnecting (for debugging) func disconnect(reason: DisconnectReason = .userInitiated) async { connectionLinkSwitch = nil - await connectionManager.disconnect(reason: reason) + let receipt = await connectionManager.disconnect(reason: reason) + guard connectionManager.isCurrent(receipt) else { return } + tearDownAppStateSessionState() await liveActivityManager.endActivity() - // Explicit disconnect does not fire onConnectionLost, so run the same - // per-session teardown the loss path performs in wireServicesIfConnected. + } + + func disconnect(requestID: UUID, reason: DisconnectReason = .statusMenuDisconnectTap) async { + guard let receipt = await connectionManager.disconnect(requestID: requestID, reason: reason), + connectionManager.isCurrent(receipt) else { return } + connectionLinkSwitch = nil tearDownAppStateSessionState() + await liveActivityManager.endActivity() } /// Asks the paired radio to cut power. The manager disconnects that link only @@ -265,34 +119,25 @@ extension AppState { tearDownAppStateSessionState() } - /// Connect to a device via WiFi/TCP - func connectViaWiFi(host: String, port: UInt16, forceFullSync: Bool = false) async throws { - // Hide disconnected pill when starting new connection - connectionUI.hideDisconnectedPill() - try await connectionManager.connectViaWiFi(host: host, port: port, forceFullSync: forceFullSync) - await wireServicesIfConnected() - } - - func connectViaBluetooth(peripheralID: UUID, forceFullSync: Bool = false) async throws { + /// Connect to a device via WiFi/TCP. + @discardableResult + func connectViaWiFi(host: String, port: UInt16, forceFullSync: Bool = false) async throws -> ConnectionResult { connectionUI.hideDisconnectedPill() - try await connectionManager.connectViaBluetooth(peripheralID: peripheralID, forceFullSync: forceFullSync) - await wireServicesIfConnected() + let result = try await connectionManager.connectViaWiFi(host: host, port: port, forceFullSync: forceFullSync) + if case let .operational(snapshot) = result { + await wireServices(for: snapshot) + } + return result } - /// Runs a transport switch. A throw is shown with the saved-device failure alert. - /// Returns whether the closure threw. @discardableResult - func switchTransport( - deviceID: UUID, - _ connect: @MainActor () async throws -> Void - ) async -> Bool { - do { - try await connect() - return false - } catch { - connectionUI.presentSavedDeviceConnectFailure(deviceID: deviceID, error: error) - return true + func connectViaBluetooth(peripheralID: UUID, forceFullSync: Bool = false) async throws -> ConnectionResult { + connectionUI.hideDisconnectedPill() + let result = try await connectionManager.connectViaBluetooth(peripheralID: peripheralID, forceFullSync: forceFullSync) + if case let .operational(snapshot) = result { + await wireServices(for: snapshot) } + return result } /// Starts one link switch. A declined start does not connect and does not change the token. @@ -310,10 +155,15 @@ extension AppState { ) else { return } connectionLinkSwitch = started - let threw = await switchTransport(deviceID: failureAlertDeviceID(started, target: target)) { - try await dial(started, to: target) + do { + let result = try await dial(started, to: target) + guard connectionManager.isCurrent(result) else { return } + applyConnectionLinkSwitchCompletion(token: token, threw: false) + } catch { + guard let failure = currentConnectionFailure(error) else { return } + connectionUI.presentSavedDeviceConnectFailure(deviceID: failureAlertDeviceID(started, target: target), error: failure) + applyConnectionLinkSwitchCompletion(token: token, threw: true) } - applyConnectionLinkSwitchCompletion(token: token, threw: threw) } /// Drops a finished record once a radio is connected, and drops a record for a different radio. @@ -351,14 +201,14 @@ extension AppState { } } - private func dial(_ record: ConnectionLinkSwitch, to target: TransportType) async throws { + private func dial(_ record: ConnectionLinkSwitch, to target: TransportType) async throws -> ConnectionResult { switch target { case .bluetooth: - guard let peripheralID = record.bluetoothPeripheralID else { return } - try await connectViaBluetooth(peripheralID: peripheralID) + guard let peripheralID = record.bluetoothPeripheralID else { return .cancelled } + return try await connectViaBluetooth(peripheralID: peripheralID) case .wifi: - guard let wifi = record.wifi, let host = wifi.displayHost else { return } - try await connectViaWiFi(host: host, port: wifi.port) + guard let wifi = record.wifi, let host = wifi.displayHost else { return .cancelled } + return try await connectViaWiFi(host: host, port: wifi.port) } } diff --git a/MC1/State/AppState+DeviceSelection.swift b/MC1/State/AppState+DeviceSelection.swift index ac0a2e6ace..fc210346d9 100644 --- a/MC1/State/AppState+DeviceSelection.swift +++ b/MC1/State/AppState+DeviceSelection.swift @@ -30,7 +30,8 @@ extension AppState { do { try await connect(queued.target) } catch { - connectionUI.presentSavedDeviceConnectFailure(deviceID: queued.device.id, error: error) + guard let failure = currentConnectionFailure(error) else { return } + connectionUI.presentSavedDeviceConnectFailure(deviceID: queued.device.id, error: failure) } } return diff --git a/MC1/State/AppState+FreshPairing.swift b/MC1/State/AppState+FreshPairing.swift new file mode 100644 index 0000000000..fa417d3bef --- /dev/null +++ b/MC1/State/AppState+FreshPairing.swift @@ -0,0 +1,241 @@ +import Foundation +import MC1Services + +extension AppState { + /// ASK Remove Accessory can temporarily prevent the scene from presenting `showPicker`. + /// Retry once after a short delay in case `.active` already fired. + private static let freshPairingForegroundRetryDelay: Duration = .milliseconds(400) + + func startDeviceScan() { + guard !isRecoveringPairing else { return } + let (operation, previous) = beginFreshPairingOperation(source: .explicitSwitch) + connectionUI.hideDisconnectedPill() + connectionUI.failedPairingDeviceID = nil + freshPairingTask = Task { + defer { finishFreshPairingWork(operation.actionID, attempt: .initial) } + await withPairingFlowErrorHandling(actionID: operation.actionID) { + let pending = try await connectionManager.systemAccessoriesMissingDeviceRecord() + guard ownsFreshPairingOperation(operation.actionID), + operation.requestID == connectionManager.connectionRequestID else { return } + if !pending.isEmpty { + freshPairingOperation?.phase = .awaitingConfirmation + if connectionUI.pendingSystemPairingSetup == nil { + connectionUI.pendingSystemPairingSetup = SystemPairingSetupPrompt( + accessories: pending.map { SystemPairedAccessory(id: $0.id, name: $0.name) } + ) + } + return + } + await previous?.value + try await completeFreshPairing(actionID: operation.actionID) + } + } + } + + func cancelSystemPairingSetup() { + connectionUI.pendingSystemPairingSetup = nil + connectionUI.queuedSystemPairingSetup = nil + cancelFreshPairingOperation() + } + + func handleSystemPairingSetupSheetDismissed() { + guard freshPairingOperation?.isConfirmingSystemPairingSetup != true, + connectionUI.pendingSystemPairingSetup == nil else { return } + cancelSystemPairingSetup() + } + + /// Forget the pending ASK accessories, then open the picker. Clears pending first so + /// iOS Remove Accessory is the only dialog; siblings do not re-prompt. + func confirmSystemPairingSetup() { + guard let prompt = connectionUI.pendingSystemPairingSetup else { return } + let (operation, previous) = beginFreshPairingOperation(source: .systemPairingSetup) + connectionUI.pendingSystemPairingSetup = nil + freshPairingTask = Task { + defer { finishFreshPairingWork(operation.actionID, attempt: .initial) } + await withPairingFlowErrorHandling(actionID: operation.actionID) { + try await connectionManager.removeSystemAccessoriesMissingDeviceRecord(prompt.accessories.map(\.id)) + await previous?.value + try await completeFreshPairing(actionID: operation.actionID) + } + } + } + + private func beginFreshPairingOperation( + source: FreshPairingOperation.Source + ) -> (FreshPairingOperation, Task?) { + let previous = freshPairingTask + previous?.cancel() + freshPairingForegroundRetryTask?.cancel() + freshPairingForegroundRetryTask = nil + let operation = FreshPairingOperation( + actionID: connectionUI.beginConnectionAction(), source: source, requestID: connectionManager.connectionRequestID + ) + freshPairingOperation = operation + connectionManager.isPairingFlowActive = true + return (operation, previous) + } + + private func ownsFreshPairingOperation(_ actionID: UUID) -> Bool { + freshPairingOperation?.actionID == actionID && connectionUI.isCurrentConnectionAction(actionID) + } + + private func finishFreshPairingWork(_ actionID: UUID, attempt: FreshPairingOperation.Attempt) { + guard freshPairingOperation?.actionID == actionID else { return } + // The retry claims the operation before joining the initial worker. + if attempt == .initial, freshPairingOperation?.isForegroundRetry == true { return } + if ownsFreshPairingOperation(actionID), + shouldCompleteFreshPairingOnForeground || connectionUI.pendingSystemPairingSetup != nil { + if !shouldCompleteFreshPairingOnForeground { + freshPairingOperation?.phase = .awaitingConfirmation + } + connectionUI.isBusy = false + return + } + finishFreshPairingOperation(actionID) + } + + private func finishFreshPairingOperation(_ actionID: UUID) { + guard freshPairingOperation?.actionID == actionID else { return } + freshPairingOperation = nil + freshPairingForegroundRetryTask?.cancel() + freshPairingForegroundRetryTask = nil + connectionManager.isPairingFlowActive = false + connectionUI.finishConnectionAction(actionID) + } + + func cancelFreshPairingOperation() { + freshPairingTask?.cancel() + freshPairingForegroundRetryTask?.cancel() + if let operation = freshPairingOperation { + finishFreshPairingOperation(operation.actionID) + } else { + connectionManager.isPairingFlowActive = false + } + } + + /// Stops an onboarding scan. Disconnects only a request this scan already + /// admitted, and stays busy until that attempt releases. + func cancelDeviceScanAttempt() { + let pairingRequestID = connectionManager.admittedPairingRequestID + let pairingTask = freshPairingTask + guard pairingTask != nil || pairingRequestID != nil || freshPairingOperation != nil else { return } + cancelFreshPairingOperation() + let actionID = connectionUI.beginConnectionAction() + Task { + if let pairingRequestID { + await disconnect(requestID: pairingRequestID, reason: .userInitiated) + } + await pairingTask?.value + connectionUI.finishConnectionAction(actionID) + } + } + + private func completeFreshPairing(actionID: UUID) async throws { + guard ownsFreshPairingOperation(actionID), !Task.isCancelled, + freshPairingOperation?.requestID == connectionManager.connectionRequestID else { return } + let result = try await connectionManager.pairNewDevice() + guard ownsFreshPairingOperation(actionID), !Task.isCancelled, + case let .operational(snapshot) = result, connectionManager.isCurrent(snapshot) else { return } + freshPairingOperation?.requestID = snapshot.requestID + await wireServices(for: snapshot) + guard ownsFreshPairingOperation(actionID), connectionManager.isCurrent(snapshot) else { return } + if !onboarding.hasCompletedOnboarding { + onboarding.onboardingPath.append(.region) + } + } + + private func withPairingFlowErrorHandling(actionID: UUID, _ work: () async throws -> Void) async { + do { + try await work() + } catch { + guard ownsFreshPairingOperation(actionID), let failure = currentConnectionFailure(error) else { return } + if !(error is ConnectionRequestFailure), freshPairingOperation?.requestID != connectionManager.connectionRequestID { + return + } + switch failure { + case DevicePairingError.cancelled: + break + case DevicePairingError.alreadyInProgress: + connectionUI.presentConnectionFailure(message: failure.userFacingMessage) + case DevicePairingError.pickerUnavailable: + if freshPairingOperation?.isForegroundRetry == true { + connectionUI.presentConnectionFailure(message: L10n.Localizable.Error.AccessorySetup.pickerRestricted) + } else { + scheduleFreshPairingOnForeground(actionID: actionID) + } + case let pairingError as PairingError: + connectionUI.presentFreshPairingFailure(pairingError) + default: + connectionUI.presentConnectionFailure(message: failure.userFacingMessage) + } + } + } + + private func scheduleFreshPairingOnForeground(actionID: UUID) { + guard ownsFreshPairingOperation(actionID), + freshPairingOperation?.requestID == connectionManager.connectionRequestID else { return } + freshPairingOperation?.phase = .awaitingForegroundRetry + freshPairingForegroundRetryTask?.cancel() + freshPairingForegroundRetryTask = Task { + try? await Task.sleep(for: Self.freshPairingForegroundRetryDelay) + guard !Task.isCancelled, freshPairingOperation?.actionID == actionID else { return } + resumeFreshPairingIfNeeded() + } + } + + func resumeFreshPairingIfNeeded() { + guard shouldCompleteFreshPairingOnForeground, let operation = freshPairingOperation else { return } + guard ownsFreshPairingOperation(operation.actionID), + operation.requestID == connectionManager.connectionRequestID else { + finishFreshPairingOperation(operation.actionID) + return + } + freshPairingForegroundRetryTask?.cancel() + freshPairingForegroundRetryTask = nil + let previous = freshPairingTask + connectionUI.isBusy = true + freshPairingOperation?.phase = .running(.foregroundRetry) + freshPairingTask = Task { + await previous?.value + defer { finishFreshPairingWork(operation.actionID, attempt: .foregroundRetry) } + await withPairingFlowErrorHandling(actionID: operation.actionID) { + try await completeFreshPairing(actionID: operation.actionID) + } + } + } + + /// Remove the failed Bluetooth association, then pair while the removal receipt is current. + @discardableResult + func removeFailedPairingAndRetry() -> Task? { + guard !isRecoveringPairing, let deviceID = connectionUI.failedPairingDeviceID else { return nil } + let episodeID = connectionUI.pairingFailureEpisodeID + let (operation, previous) = beginFreshPairingOperation(source: .bondLossRecovery) + connectionUI.hideDisconnectedPill() + let task = Task { + defer { finishFreshPairingWork(operation.actionID, attempt: .initial) } + await withPairingFlowErrorHandling(actionID: operation.actionID) { + let result: ConnectionRemovalResult + do { + result = try await connectionManager.removeFailedPairing(deviceID: deviceID) + } catch { + guard ownsFreshPairingOperation(operation.actionID), + connectionUI.pairingFailureEpisodeID == episodeID, + let failure = currentConnectionFailure(error) else { return } + connectionUI.connectionFailedMessage = failure.userFacingMessage + connectionUI.showingConnectionFailedAlert = true + return + } + guard ownsFreshPairingOperation(operation.actionID), + connectionUI.pairingFailureEpisodeID == episodeID, + connectionUI.failedPairingDeviceID == deviceID, + case let .removed(receipt) = result, connectionManager.isCurrent(receipt) else { return } + freshPairingOperation?.requestID = receipt.requestID + connectionUI.failedPairingDeviceID = nil + await previous?.value + try await completeFreshPairing(actionID: operation.actionID) + } + } + freshPairingTask = task + return task + } +} diff --git a/MC1/State/AppState+Wiring.swift b/MC1/State/AppState+Wiring.swift index 7a4ec8aece..517183b509 100644 --- a/MC1/State/AppState+Wiring.swift +++ b/MC1/State/AppState+Wiring.swift @@ -8,23 +8,26 @@ extension AppState { /// (actors don't participate in SwiftUI's observation system). /// Message events are ignored here; `MessageEventDispatcher` owns them. /// Re-subscribes per connection because `ServiceContainer` is rebuilt. - func wireSyncDataEvents(services: ServiceContainer) { + func wireSyncDataEvents(snapshot: ConnectionSnapshot) { let store = connectionManager.persistenceStore - wireSyncDataEvents(services: services, nodesContactExists: { id in + wireSyncDataEvents(snapshot: snapshot, nodesContactExists: { id in try await store.fetchContact(id: id) != nil }) } func wireSyncDataEvents( - services: ServiceContainer, + snapshot: ConnectionSnapshot, nodesContactExists: @escaping @MainActor (UUID) async throws -> Bool ) { + let context = ConnectionCallbackContext(snapshot) + let services = snapshot.services + guard context.isCurrent(connectionManager) else { return } syncDataEventsTask?.cancel() let events = services.syncCoordinator.dataEvents() let serviceID = ObjectIdentifier(services) syncDataEventsTask = Task { [weak self] in for await event in events { - guard let self else { return } + guard let self, !Task.isCancelled, context.isCurrent(connectionManager) else { return } switch event { case .contactsChanged: contactsVersion += 1 @@ -38,22 +41,25 @@ extension AppState { } } - /// Updates connectedDevice from the settings stream of this container. - /// Events are ignored once `services` no longer points at that container. - func wireSettingsEventStream(services: ServiceContainer) async { - settingsEventsTask?.cancel() + /// Consume settings service event stream. + /// Updates connectedDevice when settings are changed via SettingsService. + func wireSettingsEventStream(snapshot: ConnectionSnapshot) async { + let context = ConnectionCallbackContext(snapshot) + let services = snapshot.services + guard context.isCurrent(connectionManager) else { return } let events = await services.settingsService.events() - let producer = services + guard !Task.isCancelled, context.isCurrent(connectionManager) else { return } + settingsEventsTask?.cancel() settingsEventsTask = Task { [weak self] in for await event in events { - guard let self, self.connectionManager.services === producer else { return } + guard let self, !Task.isCancelled, context.isCurrent(connectionManager) else { return } switch event { case let .nameUpdated(name): await self.connectionManager.applyNodeName(name) case let .coordinatesUpdated(latitude, longitude): await self.connectionManager.applyCoordinates(latitude: latitude, longitude: longitude) case let .deviceObserved(info): - await self.connectionManager.applyDeviceObservation(info, from: producer) + await self.connectionManager.applyDeviceObservation(info, from: services) case let .radioUpdated(change): await self.connectionManager.applyRadio(change) case let .txPowerUpdated(power): @@ -61,29 +67,21 @@ extension AppState { case let .otherParamsUpdated(intent): await self.connectionManager.applyOtherParams(intent) case let .autoAddConfigUpdated(config): - await MainActor.run { - self.connectionManager.updateAutoAddConfig(config) - // Clear storage full flag when overwrite oldest is enabled - if config.bitmask & AutoAddConfig.overwriteOldestBit != 0 { - self.connectionUI.isNodeStorageFull = false - } + self.connectionManager.updateAutoAddConfig(config) + // Clear storage full flag when overwrite oldest is enabled. + if config.bitmask & AutoAddConfig.overwriteOldestBit != 0 { + self.connectionUI.isNodeStorageFull = false } case let .clientRepeatUpdated(enabled): - await MainActor.run { - self.connectionManager.updateClientRepeat(enabled) - } + self.connectionManager.updateClientRepeat(enabled) case let .pathHashModeUpdated(mode): - await MainActor.run { - self.connectionManager.updatePathHashMode(mode) - } + self.connectionManager.updatePathHashMode(mode) case let .allowedRepeatFreqUpdated(ranges): - await MainActor.run { - self.connectionManager.allowedRepeatFreqRanges = ranges - } + self.connectionManager.allowedRepeatFreqRanges = ranges case let .defaultFloodScopeUpdated(name): - await MainActor.run { - self.connectionManager.updateDefaultFloodScopeName(name) - } + self.connectionManager.updateDefaultFloodScopeName(name) + case .radioWiFiChanged: + radioWiFiSettingsRevision &+= 1 } } } @@ -92,27 +90,35 @@ extension AppState { /// Wire device update and contact change callbacks. /// Updates connectedDevice when local device settings (like OCV) are changed via DeviceService, /// and handles contact updates/deletions for real-time Discover page updates. - func wireDeviceUpdateCallbacks(services: ServiceContainer) async { + func wireDeviceUpdateCallbacks(snapshot: ConnectionSnapshot) async { + let context = ConnectionCallbackContext(snapshot) + let services = snapshot.services + guard context.isCurrent(connectionManager) else { return } await services.deviceService.setDeviceUpdateCallback { [weak self] deviceDTO in await MainActor.run { - self?.connectionManager.updateDevice(with: deviceDTO) + guard let self, context.isCurrent(self.connectionManager) else { return } + self.connectionManager.updateDevice(with: deviceDTO) } } - // Contact updates bump contactsVersion for real-time Discover page - // updates; contact-deleted cleanup removes notifications and refreshes - // the badge when the device auto-deletes a contact via 0x8F. - // Re-subscribes per connection because ServiceContainer is rebuilt. + guard !Task.isCancelled, context.isCurrent(connectionManager) else { return } + + // Re-subscribe per connection to refresh Discover and apply committed deletions + // to the current selection and badge after captured notification cleanup. advertisementEventsTask?.cancel() let advertisementEvents = services.advertisementService.events() - // ConnectionManager nils `services` before `tearDown` yields `.contactDeletedCleanup`. - // Capture `notificationService` so `removeDeliveredNotifications` still runs. let notificationService = services.notificationService advertisementEventsTask = Task { [weak self] in for await event in advertisementEvents { - guard let self else { return } + guard let self, !Task.isCancelled, context.isCurrent(connectionManager) else { return } switch event { - case .contactUpdated: + case let .contactUpdated(contact, scope): + if let contact, let scope { + let store = connectionManager.persistenceStore + guard await (try? store.currentDirectMessageContact(contact, scope: scope)) != nil, + scope.isCurrent else { continue } + guard !Task.isCancelled, context.isCurrent(connectionManager) else { return } + } contactsVersion += 1 PersistentLogger(subsystem: "com.mc1", category: "discover-trace") .debug("B4 contactUpdated bump contactsVersion=\(contactsVersion)") @@ -122,11 +128,11 @@ extension AppState { if let selected = navigation.selectedContact, contactIDs.contains(selected.id) { navigation.clearSelectedContact(matching: selected.id) } - await notificationService.removeDeliveredNotifications( - forContactIDs: Set(contactIDs) - ) if !contactIDs.isEmpty { - await notificationService.updateBadgeCount() + await notificationService.updateBadgeCount { [weak self] in + guard let self else { return false } + return context.isCurrent(connectionManager) + } } case .newContactDiscovered, .nodeStorageFullChanged, .pathDiscoveryResponse, .pathDiscoveryWriteFailed, .traceResponse, @@ -142,12 +148,16 @@ extension AppState { /// Wire the message event streams. Delegates to `MessageEventDispatcher`, /// which subscribes to the service event streams and fans them out to /// `messageEventStream` and `sessionStateChangeCount`. - func wireMessageEvents(services: ServiceContainer) { - messageEventDispatcher.wire(services: services) + func wireMessageEvents(snapshot: ConnectionSnapshot) { + guard connectionManager.isCurrent(snapshot) else { return } + messageEventDispatcher.wire(snapshot: snapshot) } /// Wire Live Activity callbacks for RX freshness, battery, and connection lifecycle. - func wireLiveActivityCallbacks(services: ServiceContainer) async { + func wireLiveActivityCallbacks(snapshot: ConnectionSnapshot) async { + let context = ConnectionCallbackContext(snapshot) + let services = snapshot.services + guard context.isCurrent(connectionManager) else { return } // Every received RF packet refreshes Live Activity freshness and may // trigger an overdue battery read. Re-subscribes per connection // because ServiceContainer is rebuilt. @@ -155,11 +165,12 @@ extension AppState { let rxLogEntries = services.rxLogService.entryStream() rxLogEventsTask = Task { [weak self] in for await _ in rxLogEntries { - guard let self else { return } + guard let self, !Task.isCancelled, context.isCurrent(connectionManager) else { return } await liveActivityManager.handlePacketReceived() + guard !Task.isCancelled, context.isCurrent(connectionManager) else { return } if liveActivityManager.hasActiveActivity { await batteryMonitor.fetchBatteryIfOverdue( - services: self.services, device: connectedDevice + services: services, device: snapshot.device ) } } @@ -167,21 +178,25 @@ extension AppState { batteryMonitor.onBatteryChanged = { [weak self] battery in Task { @MainActor [weak self] in - await self?.liveActivityManager.handleBatteryChanged(battery: battery) + guard let self, context.isCurrent(connectionManager) else { return } + await liveActivityManager.handleBatteryChanged(battery: battery) } } - let device = connectedDevice + let device = snapshot.device let ocvArray = batteryMonitor.activeBatteryOCVArray(for: device) let unreadCount = await totalUnreadCount(from: services) - if let device { - await liveActivityManager.handleConnectionReady( - device: device, - ocvArray: ocvArray, - unreadCount: unreadCount - ) - } + guard !Task.isCancelled, context.isCurrent(connectionManager) else { return } + await liveActivityManager.handleConnectionReady( + device: device, + ocvArray: ocvArray, + unreadCount: unreadCount, + isCurrent: { [weak self] in + guard let self else { return false } + return context.isCurrent(connectionManager) + } + ) } /// `Activity.request` only succeeds in the foreground, so a `startActivity` @@ -195,15 +210,23 @@ extension AppState { guard connectionState.isConnected, liveActivityManager.isEnabled, !liveActivityManager.hasActiveActivity, - let device = connectedDevice, - let services else { return } + let snapshot = connectionManager.currentConnection, + connectionManager.isCurrent(snapshot) else { return } + let device = snapshot.device + let services = snapshot.services + let context = ConnectionCallbackContext(snapshot) let ocvArray = batteryMonitor.activeBatteryOCVArray(for: device) let unreadCount = await totalUnreadCount(from: services) + guard connectionManager.isCurrent(snapshot) else { return } await liveActivityManager.handleConnectionReady( device: device, ocvArray: ocvArray, - unreadCount: unreadCount + unreadCount: unreadCount, + isCurrent: { [weak self] in + guard let self else { return false } + return context.isCurrent(connectionManager) + } ) } diff --git a/MC1/State/AppState.swift b/MC1/State/AppState.swift index b12ae588cf..8c5e5d320a 100644 --- a/MC1/State/AppState.swift +++ b/MC1/State/AppState.swift @@ -219,6 +219,14 @@ final class AppState { return connectionManager.persistenceStore } + var textRulesPreference: TextRulesPreference? { + connectionManager.textRulesPreference + } + + var isTextRulesLoading: Bool { + connectionManager.isTextRulesLoading + } + /// Sole lazy factory for the process-lifetime registry. Bound to the /// process store; `wireServicesIfConnected` neither creates nor rebinds it. func ensureChatCoordinatorRegistry() -> ChatCoordinatorRegistry? { @@ -291,12 +299,17 @@ final class AppState { /// Connection UI state (status pills, sync activity, alerts, pairing) let connectionUI: ConnectionUIState - /// True while `confirmSystemPairingSetup` is in flight so sheet `onDismiss` does not cancel the flow. - var isConfirmingSystemPairingSetup = false + var freshPairingOperation: FreshPairingOperation? + var freshPairingTask: Task? + var freshPairingForegroundRetryTask: Task? - /// True while the foreground retry of `completeFreshPairing` is running, so a - /// second `pickerUnavailable` is presented instead of rescheduled. - var isFreshPairingForegroundRetry = false + var shouldCompleteFreshPairingOnForeground: Bool { + freshPairingOperation?.phase == .awaitingForegroundRetry + } + + var isRecoveringPairing: Bool { + freshPairingOperation?.source == .bondLossRecovery + } /// Battery monitoring (polling, thresholds, low-battery notifications) let batteryMonitor = BatteryMonitor() @@ -304,9 +317,7 @@ final class AppState { /// Live Activity lifecycle (start/update/stop on Lock Screen and Dynamic Island) let liveActivityManager = LiveActivityManager() - /// Task chain that serializes BLE lifecycle transitions across scene-phase changes. - /// Do not cancel this task externally -- cancelling breaks the serialization - /// guarantee because Task.value returns immediately on cancellation. + /// Task chain that joins each BLE lifecycle transition before starting the next. var bleLifecycleTransitionTask: Task? /// Fallback task that re-runs foreground recovery shortly after activation when the @@ -329,6 +340,10 @@ final class AppState { /// Task consuming SettingsService event stream, canceled on disconnect var settingsEventsTask: Task? + private var connectionWiringJob: AppConnectionWiringJob? + private var wiredConnectionGeneration: UUID? + var radioWiFiSettingsRevision: UInt64 = 0 + /// Task consuming SyncCoordinator's data event stream, canceled on disconnect var syncDataEventsTask: Task? @@ -344,12 +359,13 @@ final class AppState { var bleBecomeActiveOverride: (@MainActor () async -> Void)? /// Parks power-off cleanup at the Live Activity await. Nil uses the real activity end. var powerOffEndActivityOverride: (@MainActor () async -> Void)? + var connectionWiringAfterCallbacks: (@MainActor (ConnectionSnapshot) async -> Void)? #endif // MARK: - Onboarding State /// Onboarding state (completion flag, navigation path) - let onboarding = OnboardingState() + let onboarding: OnboardingState // MARK: - What's New @@ -391,7 +407,7 @@ final class AppState { let remoteAdminWorkspaces = RemoteAdminWorkspaces() /// Tracks the device ID for CLI state - reset CLI when device changes - private var lastConnectedDeviceIDForCLI: UUID? + private var lastWiredDevice: (deviceID: UUID, radioID: UUID)? // MARK: - Status Pill @@ -400,6 +416,9 @@ final class AppState { if connectionUI.syncFailedPillVisible { return .failed(message: L10n.Localizable.StatusPill.syncFailed) } + let activity = connectionManager.connectionActivity + if activity?.phase == .reconnecting { return .reconnecting } + if activity?.phase == .waitingToReconnect { return .waitingToReconnect } if connectionState == .connected || connectionState == .syncing, connectionUI.currentSyncPhase == .messages, connectionUI.showMessageSyncPill { return .syncingMessages @@ -440,6 +459,7 @@ final class AppState { ) { self.defaults = defaults self.conversationUnreadOperations = conversationUnreadOperations + onboarding = OnboardingState(defaults: defaults) draftStore = DraftStore(defaults: defaults) let store = StoreService() @@ -451,6 +471,7 @@ final class AppState { ?? ConnectionManager(modelContainer: modelContainer, defaults: defaults) connectionUI = injectedConnectionUI ?? ConnectionUIState() connectionUI.hasSystemPairingRegistry = connectionManager.hasSystemPairingRegistry + batteryMonitor.configure(connectionManager: connectionManager) let bootstrapBuffer = DebugLogBuffer(dataStore: connectionManager.persistenceStore) bootstrapDebugLogBuffer = bootstrapBuffer @@ -483,17 +504,18 @@ final class AppState { connectionManager.appStateProvider = AppStateProviderImpl() // Wire connection ready callback - automatically updates UI when connection completes - connectionManager.onConnectionReady = { [weak self] in - await self?.wireServicesIfConnected() + connectionManager.onConnectionReady = { [weak self] snapshot in + await self?.wireServices(for: snapshot) } - connectionManager.onConnectionBecameUsable = { [weak self] in - self?.connectionUI.showReadyToastBriefly() + connectionManager.onConnectionBecameUsable = { [weak self] snapshot in + guard let self, connectionManager.isCurrent(snapshot) else { return } + connectionUI.showReadyToastBriefly() } // Wire connection lost callback - updates UI when connection is lost - connectionManager.onConnectionLost = { [weak self] in - await self?.wireServicesIfConnected() + connectionManager.onConnectionLost = { [weak self] receipt in + await self?.handleConnectionLoss(receipt) } connectionManager.onLastConnectedDeviceCleared = { [weak self] in @@ -505,8 +527,11 @@ final class AppState { // Wire auto-reconnect entry callback - reflects an out-of-range drop on the // Live Activity immediately, while connectionState is still .connecting. - connectionManager.onAutoReconnectStarted = { [weak self] in - await self?.liveActivityManager.handleConnectionLost() + connectionManager.onAutoReconnectStarted = { [weak self] receipt in + guard let self, connectionManager.isCurrent(receipt) else { return } + await liveActivityManager.handleConnectionLost { [weak self] in + self?.connectionManager.isCurrent(receipt) ?? false + } } // Wire background auth-failure callback - surfaces guided pairing-failure @@ -520,8 +545,14 @@ final class AppState { } // Wire device synced callback - runs after sync completes and state is .ready - connectionManager.onDeviceSynced = { [weak self] hasCleanRecipientData in - await self?.handleDeviceSynced(hasCleanRecipientData: hasCleanRecipientData) + connectionManager.onDeviceSynced = { [weak self] snapshot, hasCleanRecipientData in + guard let self, connectionManager.isCurrent(snapshot) else { return } + await handleDeviceSynced(hasCleanRecipientData: hasCleanRecipientData) + } + + connectionManager.onResyncFailed = { [weak self] snapshot in + guard let self, connectionManager.isCurrent(snapshot) else { return } + connectionUI.showSyncFailedPill() } loadPersistedRegionSelection() @@ -546,6 +577,7 @@ final class AppState { /// listener, which otherwise leaks across a before-first-unlock `AppState` swap. /// Connection teardown stays on `ConnectionManager`. func shutdown() { + cancelFreshPairingOperation() cancelStaleNodeCleanup() flushChatDrafts() for editor in chatDraftEditors.values { @@ -589,6 +621,9 @@ final class AppState { /// Cancels event tasks; the coordinator registry stays so an open chat /// keeps its timeline. func tearDownAppStateSessionState() { + connectionWiringJob?.cancel() + connectionWiringJob = nil + wiredConnectionGeneration = nil cancelStaleNodeCleanup() settingsEventsTask?.cancel() settingsEventsTask = nil @@ -642,122 +677,164 @@ final class AppState { remoteAdminWorkspaces.reset() } - /// Wire services-dependent callbacks after a successful connection. + /// Reuses the installed connection; a loss receipt owns disconnect cleanup. func wireServicesIfConnected() async { - reconcileConnectionLinkSwitch() - guard let services else { - tearDownAppStateSessionState() - syncCoordinator = nil - connectionUI.handleDisconnect( - connectionState: connectionState, - lastConnectedDeviceID: connectionManager.lastConnectedDeviceID, - shouldSuppressDisconnectedPill: connectionManager.shouldSuppressDisconnectedPill - ) - batteryMonitor.stop() - batteryMonitor.clearThresholds() - await liveActivityManager.handleConnectionLost() - lastBumpedServicesID = nil + guard let snapshot = connectionManager.currentConnection else { return } + await wireServices(for: snapshot) + } + + func wireServices(for snapshot: ConnectionSnapshot) async { + guard !Task.isCancelled, connectionManager.isCurrent(snapshot) else { return } + if wiredConnectionGeneration == snapshot.generation { + await restartLiveActivityIfMissing() + return + } + if let job = connectionWiringJob, job.generation == snapshot.generation { + await job.wait() return } + connectionWiringJob?.cancel() + let jobID = UUID() + let job = AppConnectionWiringJob(id: jobID, generation: snapshot.generation) { [weak self] in + guard let self else { return } + defer { + if connectionWiringJob?.id == jobID { connectionWiringJob = nil } + } + guard !Task.isCancelled, connectionManager.isCurrent(snapshot) else { return } + await performConnectionWiring(snapshot) + guard !Task.isCancelled, connectionManager.isCurrent(snapshot) else { return } + wiredConnectionGeneration = snapshot.generation + } + connectionWiringJob = job + await job.wait() + } - // Reset transient sync UI before wiring awaits so a replacement connection - // cannot inherit activity, phase, or a Ready timer. + func handleConnectionLoss(_ receipt: ConnectionLossReceipt) async { + guard connectionManager.isCurrent(receipt) else { return } + reconcileConnectionLinkSwitch() + tearDownAppStateSessionState() + syncCoordinator = nil + connectionUI.handleDisconnect( + connectionState: connectionState, + lastConnectedDeviceID: connectionManager.lastConnectedDeviceID, + shouldSuppressDisconnectedPill: connectionManager.shouldSuppressDisconnectedPill + ) + batteryMonitor.stop() + batteryMonitor.clearThresholds() + lastBumpedServicesID = nil + // Refresh the active timeline from storage to pick up status changes made during retirement. + bumpServicesVersion() + await liveActivityManager.handleConnectionLost { [weak self] in + self?.connectionManager.isCurrent(receipt) ?? false + } + } + + private func performConnectionWiring(_ snapshot: ConnectionSnapshot) async { + let context = ConnectionCallbackContext(snapshot) + let services = snapshot.services + guard !Task.isCancelled, context.isCurrent(connectionManager) else { return } + reconcileConnectionLinkSwitch() if syncCoordinator !== services.syncCoordinator { connectionUI.resetSyncState() syncCoordinator = services.syncCoordinator } - - // The link is up, so drop any pairing-failure alert latched while - // backgrounded before it can present over a working connection. connectionUI.clearPairingFailure() + await connectionUI.wireCallbacks(snapshot: snapshot, connectionManager: connectionManager) + #if DEBUG + await connectionWiringAfterCallbacks?(snapshot) + #endif + guard !Task.isCancelled, context.isCurrent(connectionManager) else { return } - // Wire ConnectionUI callbacks (sync activity, node storage, pills, VoiceOver) - // Must be set before onConnectionEstablished to avoid a race condition - await connectionUI.wireCallbacks( - syncCoordinator: services.syncCoordinator, - advertisementService: services.advertisementService, - contactService: services.contactService, - connectionManager: connectionManager - ) - - // On a device switch onConnectionLost doesn't fire, so the disconnect teardown that - // resets per-radio UI state is skipped. Reset the CLI and every per-radio detail selection - // here so neither carries the previous radio's state into the new session. - if let newDeviceID = connectedDevice?.id, - let oldDeviceID = lastConnectedDeviceIDForCLI, - newDeviceID != oldDeviceID { + if let previous = lastWiredDevice, + snapshot.device.id != previous.deviceID || snapshot.device.radioID != previous.radioID { resetRadioScopedToolWorkspaces() navigation.clearPerRadioSelection(preservingConnection: connectionLinkSwitch?.target != nil) } - lastConnectedDeviceIDForCLI = connectedDevice?.id + lastWiredDevice = (snapshot.device.id, snapshot.device.radioID) tracePathViewModel?.reattachIfWaiting() nodeDiscoveryViewModel?.reattachIfWaiting() + let radioID = snapshot.device.radioID await remoteAdminWorkspaces.rebind( - repeaterAdminService: { services.repeaterAdminService }, - roomAdminService: { services.roomAdminService }, - contactService: { services.contactService }, - nodeSnapshotService: { services.nodeSnapshotService }, - deviceHashSize: { [weak self] in self?.connectedDevice?.hashSize } + radioID: radioID, + repeaterAdminService: { [weak self] in + guard let self, context.isCurrent(self.connectionManager) else { return nil } + return self.connectionSnapshot(for: radioID)?.services.repeaterAdminService + }, + roomAdminService: { [weak self] in + guard let self, context.isCurrent(self.connectionManager) else { return nil } + return self.connectionSnapshot(for: radioID)?.services.roomAdminService + }, + contactService: { [weak self] in + guard let self, context.isCurrent(self.connectionManager) else { return nil } + return self.connectionSnapshot(for: radioID)?.services.contactService + }, + nodeSnapshotService: { [weak self] in + guard let self, context.isCurrent(self.connectionManager) else { return nil } + return self.connectionSnapshot(for: radioID)?.services.nodeSnapshotService + }, + deviceHashSize: { [weak self] in + guard let self, context.isCurrent(self.connectionManager) else { return nil } + return self.connectionSnapshot(for: radioID)?.device.hashSize + }, + remoteNodeService: { [weak self] in + guard let self, context.isCurrent(self.connectionManager) else { return nil } + return self.connectionSnapshot(for: radioID)?.services.remoteNodeService + }, + dataStore: { [weak self] in self?.offlineDataStore }, + connectionState: { [weak self] in self?.connectionState ?? .disconnected }, + isCurrent: { [weak self] in + guard let self else { return false } + return !Task.isCancelled && context.isCurrent(self.connectionManager) + } ) - - // Process-wide inline image cache learns where to persist probed dims. + guard !Task.isCancelled, context.isCurrent(connectionManager) else { return } await InlineImageCache.shared.attachDimensionsStore(services.inlineImageDimensionsStore) - - // Demo mode ships an inline image whose bytes are embedded offline; pre-seed the - // process-wide cache so the seeded DM renders it without a network fetch. - if connectedDevice?.id == MockDataProvider.simulatorDeviceID { + guard !Task.isCancelled, context.isCurrent(connectionManager) else { return } + if snapshot.device.id == MockDataProvider.simulatorDeviceID { DemoInlineImageSeeder.seed() } - wireSyncDataEvents(services: services) - await wireSettingsEventStream(services: services) - await wireDeviceUpdateCallbacks(services: services) - wireMessageEvents(services: services) - await wireLiveActivityCallbacks(services: services) - + wireSyncDataEvents(snapshot: snapshot) + await wireSettingsEventStream(snapshot: snapshot) + guard !Task.isCancelled, context.isCurrent(connectionManager) else { return } + await wireDeviceUpdateCallbacks(snapshot: snapshot) + guard !Task.isCancelled, context.isCurrent(connectionManager) else { return } + wireMessageEvents(snapshot: snapshot) + await wireLiveActivityCallbacks(snapshot: snapshot) + guard !Task.isCancelled, context.isCurrent(connectionManager) else { return } await services.channelService.setSlotOccupantChangedHandler { [weak self] radioID, indices in - await self?.handleChannelSlotOccupantChanged(radioID: radioID, indices: indices) + await MainActor.run { + guard let self else { return } + self.handleChannelSlotOccupantChanged(radioID: radioID, indices: indices) + } } + guard !Task.isCancelled, context.isCurrent(connectionManager) else { return } - // Bump the version (which drives `.task(id:)` reloads in chat, tools, and - // room views) only when the services container actually changed. A single - // connect both fires `onConnectionReady` and is followed by an explicit - // `wireServicesIfConnected()` call, and the Live Activity toggle re-wires the - // same container — none of those are a services change, so they must not - // trigger a reload. let servicesID = ObjectIdentifier(services) if lastBumpedServicesID != servicesID { lastBumpedServicesID = servicesID servicesVersion += 1 } - - // Set up notification center delegate, wire localized strings, then register categories UNUserNotificationCenter.current().delegate = services.notificationService services.notificationService.setStringProvider(NotificationStringProviderImpl()) await services.notificationService.setup() - - // Configure badge count callback + guard !Task.isCancelled, context.isCurrent(connectionManager) else { return } + let capturedRadioID = snapshot.device.radioID services.notificationService.getBadgeCount = { [weak self, dataStore = services.dataStore] in - let radioID = await MainActor.run { self?.currentRadioID } - guard let radioID else { - return (contacts: 0, channels: 0, rooms: 0) - } - do { - return try await dataStore.getTotalUnreadCounts(radioID: radioID) - } catch { - return (contacts: 0, channels: 0, rooms: 0) + let radioID = await MainActor.run { + guard let self, context.isCurrent(self.connectionManager) else { return UUID?.none } + return capturedRadioID } + guard let radioID else { return (contacts: 0, channels: 0, rooms: 0) } + return await (try? dataStore.getTotalUnreadCounts(radioID: radioID)) ?? (contacts: 0, channels: 0, rooms: 0) } - - // Seed the badge from persisted unread messages now that the callback is wired; otherwise - // badgeCount stays 0 until a message arrives or a chat opens and recomputes it. - await services.notificationService.updateBadgeCount() - - // Configure notification interaction handlers + await services.notificationService.updateBadgeCount { [weak self] in + guard let self else { return false } + return context.isCurrent(connectionManager) + } + guard !Task.isCancelled, context.isCurrent(connectionManager) else { return } configureNotificationHandlers() - - // Defer battery bootstrap so connection setup is not blocked by device request timeouts. - batteryMonitor.start(services: services, device: connectedDevice) + batteryMonitor.start(services: services, device: snapshot.device) } // MARK: - Stale Node Cleanup diff --git a/MC1/State/BatteryMonitor.swift b/MC1/State/BatteryMonitor.swift index 65ee464b77..eba6475dd6 100644 --- a/MC1/State/BatteryMonitor.swift +++ b/MC1/State/BatteryMonitor.swift @@ -8,6 +8,22 @@ import OSLog @MainActor final class BatteryMonitor { private let logger = Logger(subsystem: "com.mc1", category: "BatteryMonitor") + private weak var connectionManager: ConnectionManager? + + func configure(connectionManager: ConnectionManager) { + self.connectionManager = connectionManager + } + + private func context(for services: ServiceContainer) -> ConnectionCallbackContext? { + guard let connectionManager, let snapshot = connectionManager.currentConnection, + snapshot.services === services, connectionManager.isCurrent(snapshot) else { return nil } + return ConnectionCallbackContext(snapshot) + } + + private func isCurrent(_ context: ConnectionCallbackContext) -> Bool { + guard let connectionManager else { return false } + return !Task.isCancelled && context.isCurrent(connectionManager) + } /// Current device battery info (nil if not fetched or disconnected) var deviceBattery: BatteryInfo? @@ -39,16 +55,20 @@ final class BatteryMonitor { /// Fetch device battery level on demand func fetchDeviceBattery(services: ServiceContainer?, device: DeviceDTO?) async { - guard let settingsService = services?.settingsService else { return } + guard let services, let context = context(for: services) else { return } + let settingsService = services.settingsService do { - deviceBattery = try await settingsService.getBattery() + let battery = try await settingsService.getBattery() + guard isCurrent(context) else { return } + deviceBattery = battery lastSuccessfulFetchDate = .now if let battery = deviceBattery { onBatteryChanged?(battery) } await checkBatteryThresholds(device: device, services: services) } catch { + guard isCurrent(context) else { return } deviceBattery = nil } } @@ -66,23 +86,28 @@ final class BatteryMonitor { /// Start battery monitoring for a newly connected device. /// Defers bootstrap so connection setup is not blocked by device request timeouts. func start(services: ServiceContainer, device: DeviceDTO?) { + guard let context = context(for: services) else { return } + stop() bootstrapTask = Task { @MainActor [weak self] in guard let self else { return } do { - deviceBattery = try await services.settingsService.getBattery() + let battery = try await services.settingsService.getBattery() + guard isCurrent(context) else { return } + deviceBattery = battery lastSuccessfulFetchDate = .now if let battery = deviceBattery { onBatteryChanged?(battery) } } catch { + guard isCurrent(context) else { return } logger.debug("Deferred battery bootstrap failed: \(error.localizedDescription, privacy: .public)") deviceBattery = nil } - guard !Task.isCancelled else { return } - + guard isCurrent(context) else { return } await initializeBatteryThresholds(device: device, services: services) + guard isCurrent(context) else { return } startRefreshLoop(services: services, device: device) } } @@ -103,12 +128,13 @@ final class BatteryMonitor { /// Check for battery thresholds crossed while app was backgrounded. /// Posts a single notification if any thresholds were missed. func checkMissedBatteryThreshold(device: DeviceDTO?, services: ServiceContainer?) async { - guard let device, - let settingsService = services?.settingsService, - let notificationService = services?.notificationService else { return } - + guard let device, let services, let context = context(for: services) else { return } + let settingsService = services.settingsService + let notificationService = services.notificationService do { - deviceBattery = try await settingsService.getBattery() + let battery = try await settingsService.getBattery() + guard isCurrent(context) else { return } + deviceBattery = battery if let battery = deviceBattery { onBatteryChanged?(battery) } @@ -138,6 +164,7 @@ final class BatteryMonitor { /// Restart the battery refresh loop (e.g., returning to foreground) func startRefreshLoop(services: ServiceContainer, device: DeviceDTO?) { + guard let context = context(for: services) else { return } batteryRefreshTask?.cancel() batteryRefreshTask = Task { [weak self] in while true { @@ -146,7 +173,7 @@ final class BatteryMonitor { } catch { break } - guard let self else { break } + guard let self, isCurrent(context) else { break } await fetchDeviceBattery(services: services, device: device) } } diff --git a/MC1/State/ChatDraftEditor.swift b/MC1/State/ChatDraftEditor.swift index 6e1212b7cf..66aa0c42fd 100644 --- a/MC1/State/ChatDraftEditor.swift +++ b/MC1/State/ChatDraftEditor.swift @@ -38,8 +38,7 @@ final class ChatDraftEditor { /// An empty reply is consumed and does not change `text`. A retired editor returns /// before consuming so the reply stays for the replacement conversation. func importPendingReply(consuming consume: () -> String?) { - guard !isRetired else { return } - guard let reply = consume() else { return } + guard !isRetired, let reply = consume() else { return } if reply.isEmpty { return } setText(reply) } diff --git a/MC1/State/ConnectionActivity+Presentation.swift b/MC1/State/ConnectionActivity+Presentation.swift new file mode 100644 index 0000000000..cebc296152 --- /dev/null +++ b/MC1/State/ConnectionActivity+Presentation.swift @@ -0,0 +1,27 @@ +import MC1Services + +extension ConnectionActivity { + var statusTitle: String { + switch phase { + case .connecting: L10n.Settings.BleStatus.Status.connecting + case .reconnecting: L10n.Settings.BleStatus.Status.reconnecting + case .waitingToReconnect: L10n.Settings.BleStatus.Status.waitingToReconnect + case .connected: L10n.Settings.BleStatus.Status.connected + case .syncing: L10n.Settings.BleStatus.Status.syncing + case .ready: L10n.Settings.BleStatus.Status.ready + } + } + + var stopTitle: String { + switch phase { + case .connecting: L10n.Settings.BleStatus.cancelConnection + case .reconnecting, .waitingToReconnect: L10n.Settings.BleStatus.stopReconnecting + case .connected, .syncing, .ready: L10n.Settings.BleStatus.disconnect + } + } + + var accessibilityValue: String { + guard let targetName else { return statusTitle } + return L10n.Settings.BleStatus.accessibilityValue(targetName, statusTitle) + } +} diff --git a/MC1/State/ConnectionCallbackContext.swift b/MC1/State/ConnectionCallbackContext.swift new file mode 100644 index 0000000000..e55a7f2f9f --- /dev/null +++ b/MC1/State/ConnectionCallbackContext.swift @@ -0,0 +1,19 @@ +import Foundation +import MC1Services + +/// Captures connection ownership without retaining the services that store a callback. +struct ConnectionCallbackContext: Sendable { + let generation: UUID + let requestID: UUID + + @MainActor + init(_ snapshot: ConnectionSnapshot) { + generation = snapshot.generation + requestID = snapshot.requestID + } + + @MainActor + func isCurrent(_ manager: ConnectionManager) -> Bool { + manager.isCurrent(generation: generation, requestID: requestID) + } +} diff --git a/MC1/State/ConnectionUIState.swift b/MC1/State/ConnectionUIState.swift index 1c77604d68..8c8eda533d 100644 --- a/MC1/State/ConnectionUIState.swift +++ b/MC1/State/ConnectionUIState.swift @@ -74,7 +74,11 @@ final class ConnectionUIState { var pairingFailureKind: PairingFailureKind? /// Device ID that failed pairing (wrong PIN) - for recovery UI - var failedPairingDeviceID: UUID? + var failedPairingDeviceID: UUID? { + didSet { pairingFailureEpisodeID = UUID() } + } + + private(set) var pairingFailureEpisodeID = UUID() /// Device ID that triggered "connected to other app" warning - alert shown when non-nil var otherAppWarningDeviceID: UUID? @@ -82,6 +86,7 @@ final class ConnectionUIState { /// User-initiated connect in flight (scan, retry, simulator). /// Distinct from `isPairingInProgress` and `isPairingFlowActive`. var isBusy = false + private var connectionActionID: UUID? /// Whether the device's node storage is full (set by 0x90 push, cleared on delete/overwrite) var isNodeStorageFull = false @@ -94,13 +99,6 @@ final class ConnectionUIState { /// Re-subscribed per connection in `wireCallbacks`; cancelled on disconnect. private var nodeDeletedEventsTask: Task? - /// Flag indicating ASK picker should be shown when app returns to foreground - var shouldShowPickerOnForeground = false - - /// Forget succeeded but ASK rejected `showPicker` (`pickerRestricted`). Retry - /// `pairNewDevice` on the next `.active` scene, not `startDeviceScan`. - var shouldCompleteFreshPairingOnForeground = false - /// ASK-authorized radios with no `Device` row. Non-nil presents `SystemPairingSetupSheet`. var pendingSystemPairingSetup: SystemPairingSetupPrompt? @@ -137,6 +135,25 @@ final class ConnectionUIState { queuedSystemPairingSetup = prompt } + func beginConnectionAction() -> UUID { + let id = UUID() + connectionActionID = id + isBusy = true + return id + } + + func isCurrentConnectionAction(_ id: UUID) -> Bool { + connectionActionID == id + } + + @discardableResult + func finishConnectionAction(_ id: UUID) -> Bool { + guard isCurrentConnectionAction(id) else { return false } + connectionActionID = nil + isBusy = false + return true + } + // MARK: - Ready Toast Methods /// Shows "Ready" toast pill for 2 seconds @@ -242,7 +259,7 @@ final class ConnectionUIState { private func updateSyncPhase( _ phase: SyncPhase?, connectionManager: ConnectionManager, - syncCoordinator: SyncCoordinator + context: ConnectionCallbackContext ) { currentSyncPhase = phase guard phase == .messages, !syncFailedPillVisible, @@ -252,10 +269,10 @@ final class ConnectionUIState { } // Repeated phase updates keep the original deadline so they cannot postpone the label. guard messageSyncPillTask == nil, !showMessageSyncPill else { return } - messageSyncPillTask = Task { [weak self, weak connectionManager, weak syncCoordinator, clock] in + messageSyncPillTask = Task { [weak self, weak connectionManager, clock] in try? await clock.sleep(for: Self.messageSyncPillDelay) - guard !Task.isCancelled, let self, let connectionManager, let syncCoordinator, - connectionManager.services?.syncCoordinator === syncCoordinator, + guard !Task.isCancelled, let self, let connectionManager, + context.isCurrent(connectionManager), currentSyncPhase == .messages, !syncFailedPillVisible, connectionManager.connectionState == .connected || connectionManager.connectionState == .syncing else { return } showMessageSyncPill = true @@ -302,47 +319,47 @@ final class ConnectionUIState { /// Wires ConnectionUI-related callbacks on the sync coordinator and services. func wireCallbacks( - syncCoordinator: SyncCoordinator, - advertisementService: AdvertisementService, - contactService: ContactService, + snapshot: ConnectionSnapshot, connectionManager: ConnectionManager ) async { + let context = ConnectionCallbackContext(snapshot) + guard context.isCurrent(connectionManager) else { return } + let syncCoordinator = snapshot.services.syncCoordinator + let advertisementService = snapshot.services.advertisementService + let contactService = snapshot.services.contactService hideDisconnectedPill() announceConnectionState(L10n.Localizable.Accessibility.Connection.deviceReconnected) // Activity tracks contacts/channels and on-demand work; phase identifies message catch-up. await syncCoordinator.setSyncActivityCallbacks( - onStarted: { @MainActor [weak self, weak connectionManager, weak syncCoordinator] in - guard let self, let connectionManager, let syncCoordinator, - connectionManager.services?.syncCoordinator === syncCoordinator else { return } + onStarted: { @MainActor [weak self, weak connectionManager] in + guard let self, let connectionManager, + context.isCurrent(connectionManager) else { return } syncActivityCount += 1 }, - onEnded: { @MainActor [weak self, weak connectionManager, weak syncCoordinator] succeeded in - guard let self, let connectionManager, let syncCoordinator, - connectionManager.services?.syncCoordinator === syncCoordinator else { return } + onEnded: { @MainActor [weak self, weak connectionManager] succeeded in + guard let self, let connectionManager, + context.isCurrent(connectionManager) else { return } endSyncActivity(succeeded: succeeded, connectionState: connectionManager.connectionState) }, - onPhaseChanged: { @MainActor [weak self, weak connectionManager, weak syncCoordinator] phase in - guard let self, let connectionManager, let syncCoordinator, - connectionManager.services?.syncCoordinator === syncCoordinator else { return } - updateSyncPhase(phase, connectionManager: connectionManager, syncCoordinator: syncCoordinator) + onPhaseChanged: { @MainActor [weak self, weak connectionManager] phase in + guard let self, let connectionManager, + context.isCurrent(connectionManager) else { return } + updateSyncPhase(phase, connectionManager: connectionManager, context: context) } ) - // Resync failed callback for "Sync Failed" pill - connectionManager.onResyncFailed = { [weak self] in - self?.showSyncFailedPill() - } + guard !Task.isCancelled, context.isCurrent(connectionManager) else { return } // Node storage full events (0x90 contactsFull or 0x8F contactDeleted push). // Subscribed synchronously so the registration is live before // onConnectionEstablished can emit storage events. nodeStorageEventsTask?.cancel() let advertisementEvents = advertisementService.events() - nodeStorageEventsTask = Task { [weak self] in + nodeStorageEventsTask = Task { [weak self, weak connectionManager] in for await event in advertisementEvents { - guard let self else { return } + guard let self, let connectionManager, !Task.isCancelled, context.isCurrent(connectionManager) else { return } if case let .nodeStorageFullChanged(isFull) = event { isNodeStorageFull = isFull } @@ -354,9 +371,9 @@ final class ConnectionUIState { // before a delete can emit. nodeDeletedEventsTask?.cancel() let contactEvents = contactService.events() - nodeDeletedEventsTask = Task { [weak self] in + nodeDeletedEventsTask = Task { [weak self, weak connectionManager] in for await event in contactEvents { - guard let self else { return } + guard let self, let connectionManager, !Task.isCancelled, context.isCurrent(connectionManager) else { return } if case .nodeDeleted = event { isNodeStorageFull = false } diff --git a/MC1/State/FreshPairingOperation+Attempt.swift b/MC1/State/FreshPairingOperation+Attempt.swift new file mode 100644 index 0000000000..83c63ce1ce --- /dev/null +++ b/MC1/State/FreshPairingOperation+Attempt.swift @@ -0,0 +1,6 @@ +extension FreshPairingOperation { + enum Attempt: Equatable { + case initial + case foregroundRetry + } +} diff --git a/MC1/State/FreshPairingOperation+Phase.swift b/MC1/State/FreshPairingOperation+Phase.swift new file mode 100644 index 0000000000..db1f25fdb7 --- /dev/null +++ b/MC1/State/FreshPairingOperation+Phase.swift @@ -0,0 +1,7 @@ +extension FreshPairingOperation { + enum Phase: Equatable { + case running(Attempt) + case awaitingConfirmation + case awaitingForegroundRetry + } +} diff --git a/MC1/State/FreshPairingOperation+Source.swift b/MC1/State/FreshPairingOperation+Source.swift new file mode 100644 index 0000000000..9f5bae451b --- /dev/null +++ b/MC1/State/FreshPairingOperation+Source.swift @@ -0,0 +1,7 @@ +extension FreshPairingOperation { + enum Source { + case explicitSwitch + case systemPairingSetup + case bondLossRecovery + } +} diff --git a/MC1/State/FreshPairingOperation.swift b/MC1/State/FreshPairingOperation.swift new file mode 100644 index 0000000000..61fb12a38a --- /dev/null +++ b/MC1/State/FreshPairingOperation.swift @@ -0,0 +1,23 @@ +import Foundation + +struct FreshPairingOperation { + let actionID: UUID + let source: Source + var requestID: UUID? + var phase: Phase + + init(actionID: UUID, source: Source, requestID: UUID?) { + self.actionID = actionID + self.source = source + self.requestID = requestID + phase = .running(.initial) + } + + var isConfirmingSystemPairingSetup: Bool { + source == .systemPairingSetup && phase == .running(.initial) + } + + var isForegroundRetry: Bool { + phase == .running(.foregroundRetry) + } +} diff --git a/MC1/State/LiveActivityManager.swift b/MC1/State/LiveActivityManager.swift index 046fd6829d..a5bc17a0e4 100644 --- a/MC1/State/LiveActivityManager.swift +++ b/MC1/State/LiveActivityManager.swift @@ -22,6 +22,7 @@ final class LiveActivityManager { var connectedRadioIDProvider: (@MainActor () -> UUID?)? private var currentActivity: Activity? + private var lifecycleGeneration = UUID() private var decayTimer: Task? private var disconnectTimer: Task? private var enablementTask: Task? @@ -35,7 +36,10 @@ final class LiveActivityManager { static let decayInterval: TimeInterval = 15 static let packetWindowSeconds: TimeInterval = 60 static let secondsPerMinute: TimeInterval = 60 - static let connectedStaleInterval: TimeInterval = 30 + /// `displayedPacketRate` shows 0 past this date. It matches `packetWindowSeconds` + /// because `handleEnterBackground` stops the decay timer. + static let connectedStaleInterval: TimeInterval = packetWindowSeconds + static let staleRefreshLeadTime: TimeInterval = connectedStaleInterval / 2 static let disconnectGracePeriod: TimeInterval = 300 static let updateInterval: TimeInterval = 15 @@ -97,8 +101,12 @@ final class LiveActivityManager { func handleConnectionReady( device: DeviceDTO, ocvArray: [Int], - unreadCount: Int + unreadCount: Int, + isCurrent: @escaping @MainActor () -> Bool ) async { + guard isCurrent() else { return } + let generation = UUID() + lifecycleGeneration = generation self.ocvArray = ocvArray // If reconnecting to same device within grace period, restore connected state @@ -116,6 +124,7 @@ final class LiveActivityManager { unreadCount: unreadCount, disconnectedDate: .some(nil) ) + guard lifecycleGeneration == generation, isCurrent() else { return } startDecayTimer() startObservingActivityState() return @@ -123,20 +132,26 @@ final class LiveActivityManager { // If reconnecting to a different device, end the old activity first if currentActivity != nil { - await endActivity() + let activities = detachActivities() + await endActivities(activities) + guard lifecycleGeneration == generation, isCurrent() else { return } } await startActivity( deviceName: device.nodeName, radioID: device.radioID, - unreadCount: unreadCount + unreadCount: unreadCount, + generation: generation, + isCurrent: isCurrent ) + guard lifecycleGeneration == generation, isCurrent() else { return } startDecayTimer() } - func handleConnectionLost() async { - guard currentActivity != nil else { return } - + func handleConnectionLost(isCurrent: @escaping @MainActor () -> Bool) async { + guard isCurrent(), let activity = currentActivity else { return } + let generation = UUID() + lifecycleGeneration = generation stopDecayTimer() recentPacketTimestamps = [] clearPendingUpdate() @@ -148,16 +163,25 @@ final class LiveActivityManager { disconnectedDate: .some(.now) ) + guard lifecycleGeneration == generation, currentActivity?.id == activity.id, isCurrent() else { return } disconnectTimer?.cancel() disconnectTimer = Task { [weak self] in try? await Task.sleep(for: .seconds(Self.disconnectGracePeriod)) - guard !Task.isCancelled else { return } - await self?.endActivity() + guard !Task.isCancelled, let self, + lifecycleGeneration == generation, currentActivity?.id == activity.id, isCurrent() else { return } + await endActivity() } } func handleEnterBackground() { stopDecayTimer() + // `throttleTask` pauses while suspended, so the coalesced rate is published here. + guard pendingUpdate != nil else { return } + Task { + await BackgroundTaskRunner.live.run(named: "FlushLiveActivity") { + await flushPendingUpdate() + } + } } func handleReturnToForeground() { @@ -177,13 +201,17 @@ final class LiveActivityManager { } func handleBatteryChanged(battery: BatteryInfo) async { + let generation = lifecycleGeneration let percent = battery.percentage(using: ocvArray) await scheduleUpdate(battery: .some(percent)) + guard lifecycleGeneration == generation else { return } await flushPendingUpdate() } func handleUnreadCountChanged(unreadCount: Int) async { + let generation = lifecycleGeneration await scheduleUpdate(unreadCount: unreadCount) + guard lifecycleGeneration == generation else { return } await flushPendingUpdate() } @@ -197,6 +225,7 @@ final class LiveActivityManager { // MARK: - App relaunch recovery func recoverExistingActivity() async { + let generation = lifecycleGeneration let allActivities = Activity.activities // Clean up ended/dismissed activities still visible per their dismissal policy. @@ -215,6 +244,7 @@ final class LiveActivityManager { await orphan.end(nil, dismissalPolicy: .immediate) } + guard lifecycleGeneration == generation else { return } currentActivity = activeOrStale.first guard let activity = currentActivity else { return } @@ -226,7 +256,7 @@ final class LiveActivityManager { // branch will restore connected state once auto-reconnect lands. if activity.content.state.isConnected { logger.info("Recovered Live Activity in cached connected state — forcing re-validation as disconnected") - await handleConnectionLost() + await handleConnectionLost { [weak self] in self?.currentActivity?.id == activity.id } return } @@ -243,8 +273,9 @@ final class LiveActivityManager { if remaining > 0 { disconnectTimer = Task { [weak self] in try? await Task.sleep(for: .seconds(remaining)) - guard !Task.isCancelled else { return } - await self?.endActivity() + guard !Task.isCancelled, let self, + lifecycleGeneration == generation, currentActivity?.id == activity.id else { return } + await endActivity() } } else { await endActivity() @@ -291,8 +322,11 @@ final class LiveActivityManager { private func startActivity( deviceName: String, radioID: UUID?, - unreadCount: Int + unreadCount: Int, + generation: UUID, + isCurrent: @escaping @MainActor () -> Bool ) async { + guard lifecycleGeneration == generation, isCurrent() else { return } guard ActivityAuthorizationInfo().areActivitiesEnabled else { logger.warning("Cannot start Live Activity: not authorized") return @@ -314,6 +348,7 @@ final class LiveActivityManager { await activity.end(nil, dismissalPolicy: .immediate) } + guard lifecycleGeneration == generation, isCurrent() else { return } guard !Activity.activities.contains(where: { $0.activityState == .active || $0.activityState == .stale }) else { @@ -353,7 +388,8 @@ final class LiveActivityManager { guard let activity = currentActivity else { return } stateObservationTask = Task { [weak self] in for await state in activity.activityStateUpdates { - guard let self else { break } + guard let self, !Task.isCancelled, currentActivity?.id == activity.id else { break } + let generation = lifecycleGeneration switch state { case .ended: let lastState = activity.content.state @@ -373,10 +409,19 @@ final class LiveActivityManager { // Don't resurrect a "connected" LA from cached state — // only restart when the radio is actually connected. + guard lifecycleGeneration == generation, currentActivity == nil else { return } let isCurrentlyConnected = connectionStateProvider?() ?? false - if isCurrentlyConnected { + if isCurrentlyConnected, connectedRadioIDProvider?() == radioID { logger.info("System ended Live Activity, restarting (radio still connected)") - await startActivity(deviceName: deviceName, radioID: radioID, unreadCount: lastState.unreadCount) + await startActivity( + deviceName: deviceName, + radioID: radioID, + unreadCount: lastState.unreadCount, + generation: generation, + isCurrent: { [weak self] in + self?.connectedRadioIDProvider?() == radioID && (self?.connectionStateProvider?() ?? false) + } + ) startDecayTimer() } else { logger.info("System ended Live Activity, not restarting (radio disconnected)") @@ -397,7 +442,9 @@ final class LiveActivityManager { // disconnected (we missed a notification somewhere). // Force the disconnect path instead of refreshing. logger.warning("Stale Live Activity cached connected but radio disconnected — forcing handleConnectionLost") - await handleConnectionLost() + await handleConnectionLost { [weak self] in + self?.currentActivity?.id == activity.id && !(self?.connectionStateProvider?() ?? false) + } } else if !currentState.isConnected, let activityRadioID = activity.attributes.radioID, let connectedRadioID = connectedRadioIDProvider?(), @@ -412,6 +459,7 @@ final class LiveActivityManager { recentPacketTimestamps = [] clearPendingUpdate() await updateActivity(isConnected: true, disconnectedDate: .some(nil)) + guard lifecycleGeneration == generation, currentActivity?.id == activity.id else { return } startDecayTimer() } else if currentState.isConnected, currentState.packetsPerMinute > 0 { logger.debug("Live Activity stale with active rate, resetting to 0") @@ -502,7 +550,8 @@ final class LiveActivityManager { unreadCount: Int? = nil, disconnectedDate: Date?? = nil ) async { - guard let current = currentActivity?.content.state else { return } + guard let activity = currentActivity else { return } + let current = activity.content.state let state = MeshStatusAttributes.ContentState( isConnected: isConnected ?? current.isConnected, batteryPercent: battery ?? current.batteryPercent, @@ -510,19 +559,41 @@ final class LiveActivityManager { unreadCount: unreadCount ?? current.unreadCount, disconnectedDate: disconnectedDate ?? current.disconnectedDate ) + let now = Date.now let staleDate: Date? = if state.isConnected, state.packetsPerMinute > 0 { - Date.now.addingTimeInterval(Self.connectedStaleInterval) + now.addingTimeInterval(Self.connectedStaleInterval) } else { - Calendar.current.date(byAdding: .minute, value: 5, to: .now) + Calendar.current.date(byAdding: .minute, value: 5, to: now) } + // Republish unchanged content before its stale date. `displayedPacketRate` shows 0 after that. + guard Self.shouldPublishUpdate( + current: current, + proposed: state, + currentStaleDate: activity.content.staleDate, + now: now, + refreshLeadTime: Self.staleRefreshLeadTime + ) else { return } let content = ActivityContent(state: state, staleDate: staleDate) - await currentActivity?.update(content) + await activity.update(content) + } + + static func shouldPublishUpdate( + current: MeshStatusAttributes.ContentState, + proposed: MeshStatusAttributes.ContentState, + currentStaleDate: Date?, + now: Date, + refreshLeadTime: TimeInterval + ) -> Bool { + if current != proposed { return true } + guard let currentStaleDate else { return true } + return currentStaleDate.timeIntervalSince(now) <= refreshLeadTime } /// Checks whether the current activity reference is still valid. /// If the activity was ended while suspended (and `activityStateUpdates` didn't fire), this catches it. func validateActivityState() async { guard let activity = currentActivity else { return } + let generation = lifecycleGeneration switch activity.activityState { case .ended: let lastState = activity.content.state @@ -535,10 +606,19 @@ final class LiveActivityManager { clearActivityReference() await activity.end(nil, dismissalPolicy: .immediate) + guard lifecycleGeneration == generation, currentActivity == nil else { return } let isCurrentlyConnected = connectionStateProvider?() ?? false - if isCurrentlyConnected { + if isCurrentlyConnected, connectedRadioIDProvider?() == radioID { logger.info("Detected ended Live Activity on foreground, restarting (radio still connected)") - await startActivity(deviceName: deviceName, radioID: radioID, unreadCount: lastState.unreadCount) + await startActivity( + deviceName: deviceName, + radioID: radioID, + unreadCount: lastState.unreadCount, + generation: generation, + isCurrent: { [weak self] in + self?.connectedRadioIDProvider?() == radioID && (self?.connectionStateProvider?() ?? false) + } + ) startDecayTimer() } else { logger.info("Detected ended Live Activity on foreground, not restarting (radio disconnected)") @@ -555,17 +635,21 @@ final class LiveActivityManager { } func endActivity() async { - stopDecayTimer() - stateObservationTask?.cancel() - stateObservationTask = nil - disconnectTimer?.cancel() - disconnectTimer = nil - clearPendingUpdate() - recentPacketTimestamps = [] - for activity in Activity.activities { + lifecycleGeneration = UUID() + let activities = detachActivities() + await endActivities(activities) + } + + private func detachActivities() -> [Activity] { + let activities = Activity.activities + clearActivityReference() + return activities + } + + private func endActivities(_ activities: [Activity]) async { + for activity in activities { await activity.end(nil, dismissalPolicy: .immediate) } - currentActivity = nil logger.info("Ended Live Activity") } } diff --git a/MC1/State/MessageEvent.swift b/MC1/State/MessageEvent.swift index fbb3790548..b927812884 100644 --- a/MC1/State/MessageEvent.swift +++ b/MC1/State/MessageEvent.swift @@ -8,9 +8,11 @@ import MC1Services /// exhaustively (no `default`) so a new case becomes a compile error /// rather than a silent skip. enum MessageEvent: Equatable { - case directMessageReceived(message: MessageDTO, contact: ContactDTO) - case channelMessageReceived(message: MessageDTO, channelIndex: UInt8) - case roomMessageReceived(message: RoomMessageDTO, sessionID: UUID) + case directMessageReceived(message: MessageDTO, contact: ContactDTO, scope: ReceiveScope) + case channelMessageReceived( + message: MessageDTO, channelIndex: UInt8, scope: ReceiveScope + ) + case roomMessageReceived(message: RoomMessageDTO, sessionID: UUID, roomID: UUID? = nil, scope: ReceiveScope) /// Fired when a message's status resolves to .sent or .delivered for an /// original (non-resend) send. `roundTripTime` is supplied only when firmware /// reports it (.delivered via end-to-end ACK); .sent transitions and diff --git a/MC1/State/MessageEventDispatcher.swift b/MC1/State/MessageEventDispatcher.swift index 2d16bbcf35..bcc37cedc5 100644 --- a/MC1/State/MessageEventDispatcher.swift +++ b/MC1/State/MessageEventDispatcher.swift @@ -22,14 +22,18 @@ final class MessageEventDispatcher { /// Stream-consuming tasks, cancelled on re-wire and on disconnect. /// Each consumed stream also ends when its `ServiceContainer` is torn down. private var tasks: [Task] = [] + private var context: ConnectionCallbackContext? init(appState: AppState, stream: MessageEventStream) { self.appState = appState self.stream = stream } - func wire(services: ServiceContainer) { + func wire(snapshot: ConnectionSnapshot) { + guard let appState, appState.connectionManager.isCurrent(snapshot) else { return } cancelAll() + context = ConnectionCallbackContext(snapshot) + let services = snapshot.services wireSyncCoordinator(services.syncCoordinator) wireHeardRepeats(services.heardRepeatsService) wireRxLogRegionUpdates(services.rxLogService) @@ -45,29 +49,46 @@ final class MessageEventDispatcher { task.cancel() } tasks.removeAll() + context = nil } private func wireSyncCoordinator(_ syncCoordinator: SyncCoordinator) { + guard let context else { return } let events = syncCoordinator.dataEvents() let task = Task { [weak appState, stream] in for await event in events { + guard let appState, !Task.isCancelled, context.isCurrent(appState.connectionManager) else { return } switch event { - case let .directMessageReceived(message, contact): - stream.send(.directMessageReceived(message: message, contact: contact)) + case let .directMessageReceived(message, contact, scope): + let store = appState.connectionManager.persistenceStore + guard await (try? store.currentDirectMessageContact(contact, scope: scope)) != nil, + scope.isCurrent else { continue } + guard !Task.isCancelled, context.isCurrent(appState.connectionManager) else { return } + stream.send(.directMessageReceived(message: message, contact: contact, scope: scope)) // Keep a closed conversation's warm coordinator current so a reopen // renders the new tail on the first frame (no-op when open or cold). - appState?.ensureChatPrewarmRefresher().noteDirectMessage(contact: contact) - case let .channelMessageReceived(message, channelIndex): - stream.send(.channelMessageReceived(message: message, channelIndex: channelIndex)) - appState?.ensureChatPrewarmRefresher().noteChannelMessage( + appState.ensureChatPrewarmRefresher().noteDirectMessage(contact: contact) + case let .channelMessageReceived(message, channelIndex, scope): + guard scope.isCurrent else { continue } + stream.send(.channelMessageReceived( + message: message, channelIndex: channelIndex, scope: scope + )) + appState.ensureChatPrewarmRefresher().noteChannelMessage( radioID: message.radioID, channelIndex: channelIndex ) - case let .roomMessageReceived(message): - stream.send(.roomMessageReceived(message: message, sessionID: message.sessionID)) - case let .reactionReceived(messageID, summary): + case let .roomMessageReceived(message, roomID, scope): + guard scope.isCurrent else { continue } + stream.send(.roomMessageReceived(message: message, sessionID: message.sessionID, roomID: roomID, scope: scope)) + case let .reactionReceived(messageID, summary, scope, contact): + if let scope, let contact { + let store = appState.connectionManager.persistenceStore + guard await (try? store.currentDirectMessageContact(contact, scope: scope)) != nil, + scope.isCurrent else { continue } + guard !Task.isCancelled, context.isCurrent(appState.connectionManager) else { return } + } stream.send(.reactionReceived(messageID: messageID, summary: summary)) - await appState?.handleReactionNotification(messageID: messageID) + await appState.handleReactionNotification(messageID: messageID) case .contactsChanged, .conversationsChanged: break } @@ -77,9 +98,11 @@ final class MessageEventDispatcher { } private func wireHeardRepeats(_ heardRepeatsService: HeardRepeatsService) { + guard let context else { return } let events = heardRepeatsService.events() - let task = Task { [stream] in + let task = Task { [weak appState, stream] in for await event in events { + guard let appState, !Task.isCancelled, context.isCurrent(appState.connectionManager) else { return } stream.send(.heardRepeatRecorded(messageID: event.messageID, count: event.count)) } } @@ -87,9 +110,11 @@ final class MessageEventDispatcher { } private func wireRxLogRegionUpdates(_ rxLogService: RxLogService) { + guard let context else { return } let events = rxLogService.regionUpdateEvents() - let task = Task { [stream] in + let task = Task { [weak appState, stream] in for await messageIDs in events { + guard let appState, !Task.isCancelled, context.isCurrent(appState.connectionManager) else { return } guard !messageIDs.isEmpty else { continue } stream.send(.messagesRegionUpdated(messageIDs: messageIDs)) } @@ -98,12 +123,14 @@ final class MessageEventDispatcher { } private func wireRemoteNode(_ remoteNodeService: RemoteNodeService) { + guard let context else { return } let events = remoteNodeService.events() let task = Task { [weak appState] in for await event in events { + guard let appState, !Task.isCancelled, context.isCurrent(appState.connectionManager) else { return } switch event { case .sessionStateChanged: - appState?.handleSessionStateChange() + appState.handleSessionStateChange() } } } @@ -111,9 +138,11 @@ final class MessageEventDispatcher { } private func wireRoomServer(_ roomServerService: RoomServerService) { + guard let context else { return } let events = roomServerService.events() let task = Task { [weak appState, stream] in for await event in events { + guard let appState, !Task.isCancelled, context.isCurrent(appState.connectionManager) else { return } switch event { case let .statusUpdated(messageID, status): if status == .failed { @@ -122,7 +151,7 @@ final class MessageEventDispatcher { stream.send(.roomMessageStatusUpdated(messageID: messageID)) } case .connectionRecovered: - appState?.handleSessionStateChange() + appState.handleSessionStateChange() } } } @@ -130,9 +159,11 @@ final class MessageEventDispatcher { } private func wireMessageService(_ messageService: MessageService) { + guard let context else { return } let events = messageService.statusEvents() - let task = Task { [stream] in + let task = Task { [weak appState, stream] in for await event in events { + guard let appState, !Task.isCancelled, context.isCurrent(appState.connectionManager) else { return } switch event { case let .statusResolved(messageID, status, roundTripTime): stream.send(.messageStatusResolved(messageID: messageID, status: status, roundTripTime: roundTripTime)) @@ -144,6 +175,8 @@ final class MessageEventDispatcher { stream.send(.routingChanged(contactID: contactID, isFlood: isFlood)) case let .failed(messageID): stream.send(.messageFailed(messageID: messageID)) + case let .reactionAccepted(messageID, summary): + stream.send(.reactionReceived(messageID: messageID, summary: summary)) } } } diff --git a/MC1/State/RemoteAdminWorkspaces.swift b/MC1/State/RemoteAdminWorkspaces.swift index b78deda908..2c902462a5 100644 --- a/MC1/State/RemoteAdminWorkspaces.swift +++ b/MC1/State/RemoteAdminWorkspaces.swift @@ -1,7 +1,7 @@ import Foundation import MC1Services -/// Repeater and room admin models, kept until the radio resets. +/// Sensor, repeater, and room admin models, kept until the radio resets. @MainActor final class RemoteAdminWorkspaces { struct RepeaterModels { @@ -18,12 +18,19 @@ final class RemoteAdminWorkspaces { fileprivate let session: RemoteNodeSessionDTO } + struct SensorModels { + let settings: SensorSettingsViewModel + let cli: NodeCLIViewModel + fileprivate let session: RemoteNodeSessionDTO + } + private struct Key: Hashable { var radioID: UUID var publicKey: Data } private var repeaters: [Key: RepeaterModels] = [:] + private var sensors: [Key: SensorModels] = [:] private var rooms: [Key: RoomModels] = [:] func repeater(for session: RemoteNodeSessionDTO) -> RepeaterModels { @@ -56,6 +63,32 @@ final class RemoteAdminWorkspaces { return created } + func sensor(for session: RemoteNodeSessionDTO) -> SensorModels { + let key = Key(radioID: session.radioID, publicKey: session.publicKey) + if let existing = sensors[key] { return existing } + let created = SensorModels(settings: SensorSettingsViewModel(), cli: NodeCLIViewModel(), session: session) + sensors[key] = created + return created + } + + @discardableResult + func configureSensor( + for session: RemoteNodeSessionDTO, + remoteNodeService: @escaping @MainActor () -> RemoteNodeService?, + dataStore: @escaping @MainActor () -> PersistenceStore?, + connectionState: @escaping @MainActor () -> DeviceConnectionState + ) -> SensorModels { + let models = sensor(for: session) + if !models.settings.isBound(to: remoteNodeService()) { models.cli.reset() } + models.settings.configure(session: session, remoteNodeService: remoteNodeService, + dataStore: dataStore, connectionState: connectionState) + models.cli.configure(sessionName: session.name, remoteTarget: .sensor) { [weak settings = models.settings] command, timeout in + guard let settings else { throw RemoteNodeError.notConnected } + return try await settings.sendRawCommand(command, timeout: timeout) + } + return models + } + func reset() { for models in repeaters.values { models.settings.reset() @@ -67,23 +100,39 @@ final class RemoteAdminWorkspaces { models.status.reset() models.cli.reset() } + for models in sensors.values { + models.settings.reset() + models.cli.reset() + } + sensors.removeAll() repeaters.removeAll() rooms.removeAll() } /// Same-device ready. Rebinds providers on the models that are still live. func rebind( + radioID: UUID, repeaterAdminService: @escaping @MainActor () -> RepeaterAdminService?, roomAdminService: @escaping @MainActor () -> RoomAdminService?, contactService: @escaping @MainActor () -> ContactService?, nodeSnapshotService: @escaping @MainActor () -> NodeSnapshotService?, - deviceHashSize: @escaping @MainActor () -> Int? + deviceHashSize: @escaping @MainActor () -> Int?, + remoteNodeService: @escaping @MainActor () -> RemoteNodeService?, + dataStore: @escaping @MainActor () -> PersistenceStore?, + connectionState: @escaping @MainActor () -> DeviceConnectionState, + isCurrent: @MainActor () -> Bool ) async { - for models in repeaters.values { + guard isCurrent() else { return } + for models in sensors.values where models.session.radioID == radioID { + configureSensor(for: models.session, remoteNodeService: remoteNodeService, + dataStore: dataStore, connectionState: connectionState) + } + for models in repeaters.values where models.session.radioID == radioID { await models.settings.configure( repeaterAdminService: repeaterAdminService, session: models.session ) + guard isCurrent() else { return } models.status.configure( repeaterAdminService: repeaterAdminService, contactService: contactService, @@ -91,6 +140,7 @@ final class RemoteAdminWorkspaces { deviceHashSize: deviceHashSize ) await models.status.registerHandlers() + guard isCurrent() else { return } if let send = models.settings.makeNodeCLISendClosure(session: models.session) { models.cli.configure( sessionName: models.session.name, @@ -99,17 +149,19 @@ final class RemoteAdminWorkspaces { ) } } - for models in rooms.values { + for models in rooms.values where models.session.radioID == radioID { await models.settings.configure( roomAdminService: roomAdminService, session: models.session ) + guard isCurrent() else { return } models.status.configure( roomAdminService: roomAdminService, contactService: contactService, nodeSnapshotService: nodeSnapshotService ) await models.status.registerHandlers() + guard isCurrent() else { return } if let send = models.settings.makeNodeCLISendClosure(session: models.session) { models.cli.configure( sessionName: models.session.name, diff --git a/MC1/State/StatusPillState.swift b/MC1/State/StatusPillState.swift index 8486ca5c04..ae9adfce2a 100644 --- a/MC1/State/StatusPillState.swift +++ b/MC1/State/StatusPillState.swift @@ -4,6 +4,8 @@ import SwiftUI enum StatusPillState: Hashable { case hidden case connecting + case reconnecting + case waitingToReconnect case syncing case syncingMessages case ready @@ -16,18 +18,30 @@ enum StatusPillState: Hashable { case .syncing: L10n.Localizable.Common.Status.syncing case .syncingMessages: L10n.Localizable.Common.Status.syncingMessages case .connecting: L10n.Localizable.Common.Status.connecting + case .reconnecting: L10n.Settings.BleStatus.Status.reconnecting + case .waitingToReconnect: L10n.Settings.BleStatus.Status.waitingToReconnect case .ready: L10n.Localizable.Common.Status.ready case .disconnected: L10n.Localizable.Common.Status.disconnected case .hidden: "" } } + /// Hidden and disconnected keep the connecting label. A blank title or the disconnect warning would look like pairing had stopped. + var busyProgressTitle: String { + switch self { + case .hidden, .disconnected: + L10n.Localizable.Common.Status.connecting + default: + displayText + } + } + var systemImageName: String { switch self { case .failed: "exclamationmark.triangle.fill" - case .disconnected: "exclamationmark.triangle" + case .disconnected, .waitingToReconnect: "exclamationmark.triangle" case .ready: "checkmark.circle" - case .connecting, .syncing, .syncingMessages: "arrow.trianglehead.2.clockwise" + case .connecting, .reconnecting, .syncing, .syncingMessages: "arrow.trianglehead.2.clockwise" case .hidden: "" } } @@ -39,7 +53,7 @@ enum StatusPillState: Hashable { var textColor: Color { if isFailure { return .red } - if case .disconnected = self { return .orange } + if self == .disconnected || self == .waitingToReconnect { return .orange } return .primary } } diff --git a/MC1/Utilities/BackgroundTaskRunner.swift b/MC1/Utilities/BackgroundTaskRunner.swift new file mode 100644 index 0000000000..c2ae27efde --- /dev/null +++ b/MC1/Utilities/BackgroundTaskRunner.swift @@ -0,0 +1,36 @@ +import UIKit + +/// Holds a background task open while `run` executes so the system does not suspend the +/// process mid-write. A SQLite lock held at suspension terminates the app with `0xdead10cc`. +@MainActor +struct BackgroundTaskRunner { + typealias Begin = @MainActor (_ name: String, _ onExpiration: @escaping @MainActor () -> Void) -> UIBackgroundTaskIdentifier + typealias End = @MainActor (UIBackgroundTaskIdentifier) -> Void + + let begin: Begin + let end: End + + static let live = BackgroundTaskRunner( + begin: { name, onExpiration in + UIApplication.shared.beginBackgroundTask(withName: name, expirationHandler: onExpiration) + }, + end: { UIApplication.shared.endBackgroundTask($0) } + ) + + private final class Assertion { + var identifier = UIBackgroundTaskIdentifier.invalid + } + + func run(named name: String, operation: () async -> Void) async { + let assertion = Assertion() + let end = end + let release: @MainActor () -> Void = { + guard assertion.identifier != .invalid else { return } + end(assertion.identifier) + assertion.identifier = .invalid + } + assertion.identifier = begin(name, release) + await operation() + release() + } +} diff --git a/MC1/Utilities/ChannelJoinFloodScopeApplier.swift b/MC1/Utilities/ChannelJoinFloodScopeApplier.swift index 7abf8ebd27..d174065b69 100644 --- a/MC1/Utilities/ChannelJoinFloodScopeApplier.swift +++ b/MC1/Utilities/ChannelJoinFloodScopeApplier.swift @@ -2,10 +2,7 @@ import Foundation import MC1Services import OSLog -/// Best-effort local flood-scope preference after a channel join from URL/QR. -/// -/// Does not touch session flood scope (global). That is applied when the -/// conversation loads via `ChatViewModel.syncFloodScope`. +/// Saves the flood-scope preference from a join link for later channel sends. enum ChannelJoinFloodScopeApplier { /// Persists `.region(name)` when `regionScope` is non-empty after normalization. /// On store failure, logs and returns the original channel so the radio join diff --git a/MC1/Utilities/MacSuspendLockMarker.swift b/MC1/Utilities/MacSuspendLockMarker.swift new file mode 100644 index 0000000000..c4486992fc --- /dev/null +++ b/MC1/Utilities/MacSuspendLockMarker.swift @@ -0,0 +1,52 @@ +import Darwin +import Foundation +import os + +private let logger = Logger(subsystem: "com.mc1", category: "MacSuspendLockMarker") + +/// Marks Metal's `archiveUsage.db/lock.mdb` so RunningBoard can suspend an iOS app on Mac. +/// A held lock outside the container is fatal unless the file has the suspend attribute. +enum MacSuspendLockMarker { + static let attributeName = "com.apple.runningboard.can-suspend-locked" + private static let markerByte: UInt8 = 0xFF + private static let markerLength = 1 + private static let attributePosition: UInt32 = 0 + private static let attributeOptions: Int32 = 0 + private static let cachePathCapacity = 1024 + private static let metalDirectoryName = "com.apple.metal" + private static let archiveDatabaseDirectoryName = "archiveUsage.db" + private static let lockFileName = "lock.mdb" + + static func markIfNeeded() { + guard ProcessInfo.processInfo.isiOSAppOnMac else { return } + guard let cacheDirectory = darwinUserCacheDirectory() else { return } + guard let bundleIdentifier = Bundle.main.bundleIdentifier else { return } + let lockURL = metalArchiveLockURL(cacheDirectory: cacheDirectory, bundleIdentifier: bundleIdentifier) + markLockFile(at: lockURL) + } + + static func metalArchiveLockURL(cacheDirectory: String, bundleIdentifier: String) -> URL { + URL(fileURLWithPath: cacheDirectory, isDirectory: true) + .appendingPathComponent(bundleIdentifier, isDirectory: true) + .appendingPathComponent(metalDirectoryName, isDirectory: true) + .appendingPathComponent(archiveDatabaseDirectoryName, isDirectory: true) + .appendingPathComponent(lockFileName) + } + + static func markLockFile(at url: URL) { + let path = url.path + guard FileManager.default.fileExists(atPath: path) else { return } + var marker = markerByte + let result = setxattr(path, attributeName, &marker, markerLength, attributePosition, attributeOptions) + guard result != 0 else { return } + let error = errno + logger.error("Metal lock marker failed: \(error, privacy: .public)") + } + + private static func darwinUserCacheDirectory() -> String? { + var buffer = [CChar](repeating: 0, count: cachePathCapacity) + let length = confstr(_CS_DARWIN_USER_CACHE_DIR, &buffer, buffer.count) + guard length > 1, length <= buffer.count else { return nil } + return String(cString: buffer) + } +} diff --git a/MC1/Views/Chats/ChatConversationMessagesContent.swift b/MC1/Views/Chats/ChatConversationMessagesContent.swift index f421d412d2..7ee183b9a9 100644 --- a/MC1/Views/Chats/ChatConversationMessagesContent.swift +++ b/MC1/Views/Chats/ChatConversationMessagesContent.swift @@ -25,7 +25,7 @@ struct ChatConversationMessagesContent: View { /// Whether the timeline is ready to show and, if so, the "New Messages" /// divider id it opens scrolled to (nil opens at the bottom). - let firstSnapshotDecision: ChatInitialScrollPolicy.FirstSnapshotDecision + let firstSnapshotDecision: ChatOpenAnchorState.FirstSnapshotDecision /// Fired once the tiled view has consumed the presented divider target, so the /// owner can retire it and a later `.id` rebuild won't re-jump to the divider. @@ -94,7 +94,8 @@ struct ChatConversationMessagesContent: View { initialScrollTargetID: initialScrollTargetID, onLoadOlder: { await viewModel.loadOlderMessages() }, onInitialTargetConsumed: onDividerTargetConsumed, - sizeCache: appState.chatSizeCache + sizeCache: appState.chatSizeCache, + accessibilityHeadingIDs: viewModel.items.filter(\.grouping.showDayDivider).map(\.id) ) .overlay { incomingAvatarFlight.overlay() diff --git a/MC1/Views/Chats/ChatConversationType.swift b/MC1/Views/Chats/ChatConversationType.swift index 646b4de5e2..dd704274a4 100644 --- a/MC1/Views/Chats/ChatConversationType.swift +++ b/MC1/Views/Chats/ChatConversationType.swift @@ -43,19 +43,19 @@ enum ChatConversationType { // MARK: - Private Helpers - /// Resolves the region name shown as the channel header subtitle. Delegates to - /// ``ChannelFloodScopeResolver`` so the header matches the FloodScope actually pushed to the radio. private func effectiveRegionName( for channel: ChannelDTO, deviceDefaultFloodScopeName: String? ) -> String? { - let resolved = ChannelFloodScopeResolver.resolve( - channelFloodScope: channel.floodScope, - deviceDefaultFloodScopeName: deviceDefaultFloodScopeName, - supportsUnscopedFloodSend: false - ) - if case let .scope(.region(name)) = resolved { return name } - return nil + switch channel.floodScope { + case .inherit: + guard let name = deviceDefaultFloodScopeName, !name.isEmpty else { return nil } + return name + case .allRegions: + return nil + case let .region(name): + return name + } } var conversationID: UUID { diff --git a/MC1/Views/Chats/ChatConversationView.swift b/MC1/Views/Chats/ChatConversationView.swift index 86297b327c..9f905e7658 100644 --- a/MC1/Views/Chats/ChatConversationView.swift +++ b/MC1/Views/Chats/ChatConversationView.swift @@ -383,7 +383,7 @@ struct ChatConversationView: View { } chatViewModel.configure( - dependencies: appState.makeChatViewModelDependencies(), + dependencies: appState.makeChatViewModelDependencies(radioID: conversationType.radioID), onNavigateToMap: { appState.navigation.navigateToMap(coordinate: $0) }, linkPreviewCache: linkPreviewCache, chatCoordinatorRegistry: appState.ensureChatCoordinatorRegistry(), @@ -536,7 +536,7 @@ struct ChatConversationView: View { private func refreshChannel() async throws { guard case let .channel(channel) = conversationType else { return } guard let dataStore = appState.offlineDataStore else { throw ConnectionError.notConnected } - guard let updated = try await dataStore.fetchChannel(id: channel.id) else { + guard let updated = try await dataStore.fetchChannelForInfo(id: channel.id) else { throw PersistenceStoreError.channelNotFound } try Task.checkCancellation() @@ -675,7 +675,7 @@ struct ChatConversationView: View { case .copy: handleCopy(for: message) case .translate: - presentSystemTranslation(text: message.text) + presentSystemTranslation(text: MECPCatalog.displayText(message.text)) case .sendAgain: handleSendAgain(for: message) case .blockSender: diff --git a/MC1/Views/Chats/ChatsListModifiers.swift b/MC1/Views/Chats/ChatsListModifiers.swift index 0d1ac45c98..5c4d186290 100644 --- a/MC1/Views/Chats/ChatsListModifiers.swift +++ b/MC1/Views/Chats/ChatsListModifiers.swift @@ -58,7 +58,6 @@ struct ChatsListModifiers: ViewModifier { connectionState: { appState.connectionState }, connectedDevice: { appState.connectedDevice }, currentRadioID: { appState.currentRadioID }, - session: { appState.services?.session }, reactionService: { appState.services?.reactionService }, chatSendQueueService: { appState.services?.chatSendQueueService }, inlineImageDimensionsStore: { nil }, diff --git a/MC1/Views/Chats/Components/BubbleFooterRow.swift b/MC1/Views/Chats/Components/BubbleFooterRow.swift index 2c73cf2e87..8756b462cb 100644 --- a/MC1/Views/Chats/Components/BubbleFooterRow.swift +++ b/MC1/Views/Chats/Components/BubbleFooterRow.swift @@ -293,8 +293,8 @@ private struct BubbleStatusFooter: View { case .retrying: HStack(spacing: 3) { spinner - if footer.maxRetryAttempts > 0 { - Text("\(footer.retryAttempt + 1)/\(footer.maxRetryAttempts)") + if let progress = footer.sendAttemptProgress { + Text("\(progress.attempt)/\(progress.total)") .font(.caption2) } } @@ -377,12 +377,18 @@ enum MessageStatusText { case .failed: return L10n.Chats.Chats.Message.Status.failed case .retrying: - let displayAttempt = footer.retryAttempt + 1 - let maxAttempts = footer.maxRetryAttempts - if maxAttempts > 0 { - return L10n.Chats.Chats.Message.Status.retryingAttempt(displayAttempt, maxAttempts) + if let progress = footer.sendAttemptProgress { + return L10n.Chats.Chats.Message.Status.retryingAttempt(progress.attempt, progress.total) } return L10n.Chats.Chats.Message.Status.retrying } } } + +private extension MessageFooter { + var sendAttemptProgress: (attempt: Int, total: Int)? { + guard maxRetryAttempts > 0 else { return nil } + // The retry index starts at zero and the retry budget excludes the initial send. + return (retryAttempt + 2, maxRetryAttempts + 1) + } +} diff --git a/MC1/Views/Chats/Components/BubbleFragmentStack.swift b/MC1/Views/Chats/Components/BubbleFragmentStack.swift index f7b9cab32a..2f3d3d9206 100644 --- a/MC1/Views/Chats/Components/BubbleFragmentStack.swift +++ b/MC1/Views/Chats/Components/BubbleFragmentStack.swift @@ -31,7 +31,9 @@ struct BubbleFragmentStack: View, Equatable { @Environment(\.dynamicTypeSize) private var dynamicTypeSize nonisolated static func == (lhs: BubbleFragmentStack, rhs: BubbleFragmentStack) -> Bool { - lhs.item == rhs.item && lhs.bubbleColor == rhs.bubbleColor && lhs.timeColor == rhs.timeColor + lhs.item == rhs.item + && lhs.bubbleColor == rhs.bubbleColor + && lhs.timeColor == rhs.timeColor } private var hasFooter: Bool { @@ -51,13 +53,12 @@ struct BubbleFragmentStack: View, Equatable { if case let .disabled(url) = layout.inlineImage?.state { url } else { nil } } - /// Showing uses the translated string as plain `Text` so mention/hashtag runs are not applied. - private func translationBody(_ textPayload: MessageTextPayload) -> Text { - if case let .showing(translated, _) = textPayload.translation?.phase { - Text(translated) - } else { - Text(textPayload.formatted ?? AttributedString(textPayload.raw)) + /// Plain `Text` when the visible body replaces the stored string, so mention runs stay off. + private func messageBody(_ textPayload: MessageTextPayload, plainText: String?) -> Text { + if let plainText { + return Text(plainText) } + return Text(textPayload.formatted ?? AttributedString(textPayload.raw)) } var body: some View { @@ -69,17 +70,18 @@ struct BubbleFragmentStack: View, Equatable { // self-sizing hosting cell without a resolvable intrinsic width, which // SwiftUI surfaces as a fatal "invalid reuse after initialization failure". VStack(alignment: item.envelope.isOutgoing ? .trailing : .leading, spacing: 2) { - if let chrome = layout.textPayload?.translation { - BubbleTranslationControl( - phase: chrome.phase, - onTap: { callbacks.onTranslationAction?() } - ) - } if let textPayload = layout.textPayload { + let visible = MessageVisibleBody(stored: textPayload.raw, translation: textPayload.translation) + if let chrome = visible.translation { + BubbleTranslationControl( + phase: chrome.phase, + onTap: { callbacks.onTranslationAction?() } + ) + } // Native `Text`: the precomputed `formatted` string already carries every run's color, // underline, bold, and `.link`, so link taps route through the injected `\.openURL` and // Dynamic Type scales for free. `foregroundStyle` colors the raw fallback when unformatted. - translationBody(textPayload) + messageBody(textPayload, plainText: visible.plainText) .font(.body) .foregroundStyle(textPayload.baseColor.swiftUIColor) } diff --git a/MC1/Views/Chats/Components/ChatBottomChrome.swift b/MC1/Views/Chats/Components/ChatBottomChrome.swift index 2132e4e190..f04029f060 100644 --- a/MC1/Views/Chats/Components/ChatBottomChrome.swift +++ b/MC1/Views/Chats/Components/ChatBottomChrome.swift @@ -2,13 +2,14 @@ import SwiftUI struct ChatBottomChrome: View { let canvas: Color + var homeInset: CGFloat @ViewBuilder var content: () -> Content var body: some View { VStack(spacing: 0) { content() .chatKeyboardLiftPadding() - ChatWindowBottomInset() + ChatWindowBottomInset(height: homeInset) } .chatComposeBarFade(canvas: canvas) } diff --git a/MC1/Views/Chats/Components/ChatBottomChromeModifier.swift b/MC1/Views/Chats/Components/ChatBottomChromeModifier.swift index 5a3b087883..b39208605f 100644 --- a/MC1/Views/Chats/Components/ChatBottomChromeModifier.swift +++ b/MC1/Views/Chats/Components/ChatBottomChromeModifier.swift @@ -13,6 +13,7 @@ extension View { private struct ChatBottomChromeModifier: ViewModifier { @Environment(\.scenePhase) private var scenePhase @State private var lift: CGFloat = 0 + @State private var homeInset: CGFloat = 0 let canvas: Color let chrome: Chrome @@ -25,11 +26,16 @@ private struct ChatBottomChromeModifier: ViewModifier { var transaction = Transaction(animation: nil) transaction.disablesAnimations = true withTransaction(transaction) { lift = next } + }, + onHomeInsetChange: { next in + guard next != homeInset else { return } + homeInset = next } ) .frame(maxWidth: .infinity, maxHeight: .infinity) .ignoresSafeArea([.container, .keyboard], edges: .vertical) .environment(\.chatKeyboardLift, scenePhase == .active ? lift : 0) + .environment(\.chatWindowHomeInset, homeInset) } private struct Host: UIViewControllerRepresentable { @@ -55,10 +61,11 @@ private struct ChatBottomChromeModifier: ViewModifier { struct Root: View { let canvas: Color let chrome: Chrome + var homeInset: CGFloat let environment: EnvironmentValues var body: some View { - ChatBottomChrome(canvas: canvas) { + ChatBottomChrome(canvas: canvas, homeInset: homeInset) { chrome } .environment(\.chatKeyboardLift, 0) @@ -71,23 +78,27 @@ private struct ChatBottomChromeModifier: ViewModifier { let chrome: Chrome let isActive: Bool let onLiftChange: @MainActor (CGFloat) -> Void + let onHomeInsetChange: @MainActor (CGFloat) -> Void func makeUIViewController(context: Context) -> Controller { Controller( timeline: TimelineRoot(timeline: timeline, chromeHeight: 0, topInset: 0, environment: context.environment), - root: Root(canvas: canvas, chrome: chrome, environment: context.environment) + root: Root(canvas: canvas, chrome: chrome, homeInset: 0, environment: context.environment) ) } func updateUIViewController(_ controller: Controller, context: Context) { controller.onLiftChange = onLiftChange + controller.onHomeInsetChange = onHomeInsetChange controller.isCompact = context.environment.horizontalSizeClass == .compact controller.isSceneActive = isActive withTransaction(context.transaction) { controller.timelineHost.rootView = TimelineRoot( timeline: timeline, chromeHeight: controller.chromeHeight, topInset: controller.topInset, environment: context.environment ) - controller.hosted.rootView = Root(canvas: canvas, chrome: chrome, environment: context.environment) + controller.hosted.rootView = Root( + canvas: canvas, chrome: chrome, homeInset: controller.homeInset, environment: context.environment + ) } controller.refreshActivity() } @@ -100,6 +111,7 @@ private struct ChatBottomChromeModifier: ViewModifier { let timelineHost: UIHostingController let hosted: UIHostingController var onLiftChange: @MainActor (CGFloat) -> Void = { _ in } + var onHomeInsetChange: @MainActor (CGFloat) -> Void = { _ in } var isCompact = false var isSceneActive = false @@ -111,8 +123,14 @@ private struct ChatBottomChromeModifier: ViewModifier { private var popGestures: [UIGestureRecognizer] = [] private(set) var chromeHeight: CGFloat = 0 private(set) var topInset: CGFloat = 0 + /// Home-indicator height requested from the window and written into the chrome. + private(set) var homeInset: CGFloat = 0 + /// Spacer height already laid out in the chrome. + /// The keyboard offset follows it so the pill stays above the keyboard while that spacer is still short. + private var appliedHomeInset: CGFloat = 0 private var lift: CGFloat = 0 private var hasQueuedLiftReport = false + private var hasQueuedHomeInsetReport = false private var isVisible = false init(timeline: TimelineRoot, root: Root) { @@ -212,6 +230,7 @@ private struct ChatBottomChromeModifier: ViewModifier { override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() + syncHomeInset() let restingInset = isCompact ? 0 : view.safeAreaInsets.bottom updateKeyboardLimit() restingLimit.constant = -restingInset @@ -262,7 +281,49 @@ private struct ChatBottomChromeModifier: ViewModifier { } private var keyboardHomeInset: CGFloat { - isCompact ? view.window?.safeAreaInsets.bottom ?? 0 : 0 + appliedHomeInset + } + + /// Home-indicator inset from the window. The view inset can include the tab bar while it hides. + private func windowHomeInset() -> CGFloat { + guard isCompact, let window = view.window else { return 0 } + return window.safeAreaInsets.bottom + } + + private func syncHomeInset() { + let live = windowHomeInset() + if live != homeInset { + homeInset = live + var root = hosted.rootView + root.homeInset = live + var transaction = Transaction(animation: nil) + transaction.disablesAnimations = true + withTransaction(transaction) { hosted.rootView = root } + reportHomeInset() + } + let hosts = bottomInsetHosts(in: hosted.view) + appliedHomeInset = hosts.map(\.reservedHeight).max() ?? 0 + } + + private func reportHomeInset() { + guard !hasQueuedHomeInsetReport else { return } + hasQueuedHomeInsetReport = true + DispatchQueue.main.async { [weak self] in + guard let self else { return } + hasQueuedHomeInsetReport = false + onHomeInsetChange(homeInset) + } + } + + private func bottomInsetHosts(in root: UIView) -> [ChatWindowBottomInsetHost] { + var found: [ChatWindowBottomInsetHost] = [] + if let host = root as? ChatWindowBottomInsetHost { + found.append(host) + } + for child in root.subviews { + found.append(contentsOf: bottomInsetHosts(in: child)) + } + return found } func deactivate() { diff --git a/MC1/Views/Chats/Components/ChatComposerTextView.swift b/MC1/Views/Chats/Components/ChatComposerTextView.swift index e35ac3dd07..c0a837ff6c 100644 --- a/MC1/Views/Chats/Components/ChatComposerTextView.swift +++ b/MC1/Views/Chats/Components/ChatComposerTextView.swift @@ -38,7 +38,6 @@ struct ChatComposerTextView: UIViewRepresentable { textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) proxy.textView = textView - textView.accessibilityHint = L10n.Chats.Chats.Input.accessibilityHint textView.applyComposerAccessibility(isEncrypted: isEncrypted) return textView } @@ -46,7 +45,6 @@ struct ChatComposerTextView: UIViewRepresentable { func updateUIView(_ textView: ChatComposerUITextView, context: Context) { context.coordinator.parent = self textView.onSend = onSend - textView.applyComposerAccessibility(isEncrypted: isEncrypted) if textView.text != text { if text.isEmpty { @@ -55,6 +53,7 @@ struct ChatComposerTextView: UIViewRepresentable { textView.text = text } } + textView.applyComposerAccessibility(isEncrypted: isEncrypted) // Become first responder once per token increment. There is no resign // path, so native dismissal is left untouched. @@ -115,7 +114,7 @@ final class ChatComposerUITextView: UITextView { var onSend: (() -> Bool)? /// UITextView reports its text as `accessibilityValue` when that property is left unset. - /// Leave it unset so encryption status stays on the label. + /// Leave it unset so the entered text stays readable by character and word. private var accessibilityValueIsUnset = true override var accessibilityValue: String? { @@ -126,12 +125,20 @@ final class ChatComposerUITextView: UITextView { } } + /// The empty field speaks its name, encryption status, and hint. + /// Text clears those so VoiceOver speaks the draft. func applyComposerAccessibility(isEncrypted: Bool) { - let status = isEncrypted - ? L10n.Chats.Chats.Input.encrypted - : L10n.Chats.Chats.Input.notEncrypted - accessibilityLabel = "\(L10n.Chats.Chats.Input.accessibilityLabel), \(status)" - // accessibilityValue stays nil. UITextView speaks the field text through that property. + let hasText = !text.isEmpty + if hasText { + accessibilityLabel = nil + accessibilityHint = nil + } else { + let status = isEncrypted + ? L10n.Chats.Chats.Input.encrypted + : L10n.Chats.Chats.Input.notEncrypted + accessibilityLabel = "\(L10n.Chats.Chats.Input.accessibilityLabel), \(status)" + accessibilityHint = L10n.Chats.Chats.Input.accessibilityHint + } accessibilityValue = nil } diff --git a/MC1/Views/Chats/Components/ChatInitialScrollPolicy.swift b/MC1/Views/Chats/Components/ChatInitialScrollPolicy.swift deleted file mode 100644 index 572faa40aa..0000000000 --- a/MC1/Views/Chats/Components/ChatInitialScrollPolicy.swift +++ /dev/null @@ -1,36 +0,0 @@ -import Foundation - -/// Pure decisions governing the chat list's first snapshot when a conversation -/// opens: whether to hand the library its first items yet, and which item to -/// open scrolled to (the "New Messages" divider). -enum ChatInitialScrollPolicy { - /// The library's one-shot initial positioning is spent by the first non-empty - /// snapshot it receives, so the timeline must stay withheld until the snapshot - /// on screen is the one it should position on. - enum FirstSnapshotDecision: Equatable { - /// Keep the timeline off screen; a divider target is expected but its - /// flag-bearing item is not yet among the current items. - case withhold - /// Show the timeline, opening scrolled to `target` (nil opens at the bottom). - case present(target: UUID?) - } - - /// Withholds a new unread open until its baked divider is in the current items. - /// A terminal populate without a divider presents at the bottom. - static func firstSnapshotDecision( - hasConsumed: Bool, - unreadCount: Int, - initialLoadSettled: Bool, - dividerMessageID: UUID?, - dividerRowOnScreen: Bool - ) -> FirstSnapshotDecision { - guard !hasConsumed, unreadCount > 0 else { return .present(target: nil) } - if let dividerMessageID { - // Present only when the flag-bearing row is on screen: id membership - // alone can be a prior bake without the flag, and presenting that spends - // the one-shot before a later rebake grows a row under the input bar. - return dividerRowOnScreen ? .present(target: dividerMessageID) : .withhold - } - return initialLoadSettled ? .present(target: nil) : .withhold - } -} diff --git a/MC1/Views/Chats/Components/ChatInputBar.swift b/MC1/Views/Chats/Components/ChatInputBar.swift index 63e86327ce..28fc7a25b4 100644 --- a/MC1/Views/Chats/Components/ChatInputBar.swift +++ b/MC1/Views/Chats/Components/ChatInputBar.swift @@ -88,6 +88,11 @@ struct ChatInputBar: View { .sensoryFeedback(.start, trigger: sendInvocationCounter) .animation(.smooth(duration: 0.28), value: canSend) .animation(.smooth(duration: 0.28), value: shouldShowCharacterCount) + .onChange(of: isEncrypted) { wasEncrypted, isEncrypted in + // A draft has no label, so a change to cleartext is spoken on its own. + guard wasEncrypted, !isEncrypted, !text.isEmpty else { return } + UIAccessibility.post(notification: .announcement, argument: L10n.Chats.Chats.Input.notEncrypted) + } } private var sendAccessibilityLabel: String { diff --git a/MC1/Views/Chats/Components/ChatScrollConstants.swift b/MC1/Views/Chats/Components/ChatScrollConstants.swift index 7e3ec892f4..82940ea267 100644 --- a/MC1/Views/Chats/Components/ChatScrollConstants.swift +++ b/MC1/Views/Chats/Components/ChatScrollConstants.swift @@ -1,14 +1,17 @@ import CoreGraphics +import Foundation /// Tuning constants for the chat scroll surface. enum ChatScrollConstants { - /// Distance from the bottom (in points) at or below which the list is treated - /// as resting at the visual bottom, hiding the scroll-to-bottom button and - /// re-enabling auto-scroll on append. + /// Distance from the bottom, in points, at or below which the list counts as resting there. + /// That hides the scroll-to-bottom button and turns append-follow back on. static let bottomDetectionThreshold: CGFloat = 40 - /// Hosted tests find the overlay button by identifier. iOS 26 Liquid Glass - /// does not put the VoiceOver label on `UIView.accessibilityLabel` without - /// VoiceOver running. + /// Hosted tests find the overlay button by this identifier. + /// Liquid Glass does not expose its VoiceOver label until VoiceOver is running. static let scrollToBottomButtonIdentifier = "chat.scrollToBottom" + + static func messageAccessibilityIdentifier(_ id: UUID) -> String { + "chat.message.\(id.uuidString)" + } } diff --git a/MC1/Views/Chats/Components/ChatTiledView.swift b/MC1/Views/Chats/Components/ChatTiledView.swift index 6023a00e9d..2959fb0ef5 100644 --- a/MC1/Views/Chats/Components/ChatTiledView.swift +++ b/MC1/Views/Chats/Components/ChatTiledView.swift @@ -41,6 +41,10 @@ struct ChatTiledView: V /// unchanged items. Nil measures on each open. var sizeCache: TiledSizeCache? + var accessibilityHeadingIDs: [UUID] + + @Environment(\.accessibilityVoiceOverEnabled) private var voiceOverEnabled + @Environment(\.accessibilityReduceMotion) private var reduceMotion @Environment(\.appTheme) private var appTheme @Environment(\.colorScheme) private var colorScheme @Environment(\.colorSchemeContrast) private var colorSchemeContrast @@ -70,7 +74,8 @@ struct ChatTiledView: V initialScrollTargetID: Item.ID? = nil, onLoadOlder: (@MainActor @Sendable () async -> Void)? = nil, onInitialTargetConsumed: (() -> Void)? = nil, - sizeCache: TiledSizeCache? = nil + sizeCache: TiledSizeCache? = nil, + accessibilityHeadingIDs: [UUID] = [] ) { self.items = items self.cellContent = cellContent @@ -86,6 +91,7 @@ struct ChatTiledView: V self.onLoadOlder = onLoadOlder self.onInitialTargetConsumed = onInitialTargetConsumed self.sizeCache = sizeCache + self.accessibilityHeadingIDs = accessibilityHeadingIDs // Defer append-follow while an initial target is positioning so incoming messages cannot displace it. _scrollPosition = State(initialValue: TiledScrollPosition( autoScrollsToBottomOnAppend: scrollTargetID == nil && initialScrollTargetID == nil, @@ -101,6 +107,11 @@ struct ChatTiledView: V return TiledView(items: items, scrollPosition: $scrollPosition) { item in ChatTiledCell(item: item, host: host) } + .accessibilityItemIdentifier { ChatScrollConstants.messageAccessibilityIdentifier($0) } + .accessibilityHeadings(accessibilityHeadingIDs) { + scrollPosition.cancel() + scrollPosition.autoScrollsToBottomOnAppend = false + } .sizeCache(sizeCache) .prependLoader(onLoadOlder.map { load in .loader(perform: load) { @@ -157,7 +168,11 @@ struct ChatTiledView: V /// Jump to the bottom on explicit user requests; scrollToBottomRequest preserves history when away from bottom. private func scrollUserToBottom() { - scrollPosition.scrollTo(edge: .bottom) + scrollPosition.scrollTo( + edge: .bottom, + animated: !reduceMotion, + focusBottomAccessibilityElement: voiceOverEnabled + ) } /// Rebuild on theme or appearance changes because the library does not reconfigure environment-only cell updates. diff --git a/MC1/Views/Chats/Components/ChatWindowBottomInset.swift b/MC1/Views/Chats/Components/ChatWindowBottomInset.swift index e7ad74a0be..f8d92b1f9a 100644 --- a/MC1/Views/Chats/Components/ChatWindowBottomInset.swift +++ b/MC1/Views/Chats/Components/ChatWindowBottomInset.swift @@ -1,58 +1,52 @@ import SwiftUI import UIKit -/// Use the window home-indicator inset on compact layouts. -/// Descendant insets can briefly include the tab bar while it hides. +/// Reserves the window home-indicator inset on compact layouts. +/// The chrome supplies the height. A descendant inset can include the tab bar while it hides. struct ChatWindowBottomInset: View { + private let heightOverride: CGFloat? + @Environment(\.chatWindowHomeInset) private var homeInset @Environment(\.horizontalSizeClass) private var horizontalSizeClass + init() { + heightOverride = nil + } + + init(height: CGFloat) { + heightOverride = height + } + + private var height: CGFloat { + heightOverride ?? homeInset + } + var body: some View { - if horizontalSizeClass == .compact { - Representable() - .fixedSize(horizontal: false, vertical: true) + if horizontalSizeClass == .compact, height > 0 { + Representable(height: height) + .frame(height: height) .allowsHitTesting(false) .accessibilityHidden(true) } } private struct Representable: UIViewRepresentable { - func makeUIView(context: Context) -> Host { - let host = Host() - host.seedHeight = ChatKeyboardLift.keyWindow()?.safeAreaInsets.bottom + var height: CGFloat + + func makeUIView(context: Context) -> ChatWindowBottomInsetHost { + let host = ChatWindowBottomInsetHost() + host.isUserInteractionEnabled = false + host.accessibilityElementsHidden = true + host.reservedHeight = height return host } - func updateUIView(_ uiView: Host, context: Context) {} - - final class Host: UIView { - var seedHeight: CGFloat? - private var appliedHeight: CGFloat? - - override var intrinsicContentSize: CGSize { - CGSize(width: UIView.noIntrinsicMetric, height: resolvedHeight) - } - - override func didMoveToWindow() { - super.didMoveToWindow() - invalidateIfNeeded() - } - - override func safeAreaInsetsDidChange() { - super.safeAreaInsetsDidChange() - // The view inset changes when the tab bar hides. The window inset does not. - invalidateIfNeeded() - } - - private var resolvedHeight: CGFloat { - window?.safeAreaInsets.bottom ?? seedHeight ?? 0 - } - - private func invalidateIfNeeded() { - let height = resolvedHeight - guard height != appliedHeight else { return } - appliedHeight = height - invalidateIntrinsicContentSize() - } + func updateUIView(_ uiView: ChatWindowBottomInsetHost, context: Context) { + uiView.reservedHeight = height } } } + +extension EnvironmentValues { + /// Window home-indicator inset reserved under the compact composer and mention list. + @Entry var chatWindowHomeInset: CGFloat = 0 +} diff --git a/MC1/Views/Chats/Components/ChatWindowBottomInsetHost.swift b/MC1/Views/Chats/Components/ChatWindowBottomInsetHost.swift new file mode 100644 index 0000000000..27777916f8 --- /dev/null +++ b/MC1/Views/Chats/Components/ChatWindowBottomInsetHost.swift @@ -0,0 +1,15 @@ +import UIKit + +/// The chrome reads this view's height for the keyboard offset. +final class ChatWindowBottomInsetHost: UIView { + var reservedHeight: CGFloat = 0 { + didSet { + guard reservedHeight != oldValue else { return } + invalidateIntrinsicContentSize() + } + } + + override var intrinsicContentSize: CGSize { + CGSize(width: UIView.noIntrinsicMetric, height: reservedHeight) + } +} diff --git a/MC1/Views/Chats/Components/MessageBubbleView.swift b/MC1/Views/Chats/Components/MessageBubbleView.swift index ff64da6f03..4b78146e21 100644 --- a/MC1/Views/Chats/Components/MessageBubbleView.swift +++ b/MC1/Views/Chats/Components/MessageBubbleView.swift @@ -48,6 +48,7 @@ struct MessageBubbleView: View, Equatable { .font(.caption) .foregroundStyle(.secondary) .accessibilityLabel(L10n.Chats.Chats.Message.unavailableAccessibility) + .accessibilityIdentifier(ChatScrollConstants.messageAccessibilityIdentifier(item.id)) } } } diff --git a/MC1/Views/Chats/Components/MessageDayDividerView.swift b/MC1/Views/Chats/Components/MessageDayDividerView.swift index 7f6a66bacb..52615886f4 100644 --- a/MC1/Views/Chats/Components/MessageDayDividerView.swift +++ b/MC1/Views/Chats/Components/MessageDayDividerView.swift @@ -1,21 +1,24 @@ import SwiftUI -/// Day separator shown once per calendar day in chat history. Rendered as a -/// centered, lined divider (matching `NewMessagesDividerView`) carrying the full -/// calendar date — e.g. "10 June 2026" — so each day's first message is clearly -/// anchored in time now that the per-cluster time marker lives inside the bubble. +/// Full calendar date shown once per day, matching `NewMessagesDividerView`. +/// The date is a heading, the rules are hidden from VoiceOver, and the text wraps. struct MessageDayDividerView: View { let date: Date var body: some View { - HStack { + let label = date.formatted(.dateTime.day().month(.wide).year()) + return HStack { VStack { Divider() } - Text(date.formatted(.dateTime.day().month(.wide).year())) + .accessibilityHidden(true) + Text(label) .font(.caption2) .fontWeight(.semibold) .foregroundStyle(.secondary) - .fixedSize() + .fixedSize(horizontal: false, vertical: true) + .multilineTextAlignment(.center) + .accessibilityAddTraits(.isHeader) VStack { Divider() } + .accessibilityHidden(true) } .padding(.vertical, 4) } diff --git a/MC1/Views/Chats/Components/MessagePathArrival.swift b/MC1/Views/Chats/Components/MessagePathArrival.swift index 017fd586c5..860dfef7ab 100644 --- a/MC1/Views/Chats/Components/MessagePathArrival.swift +++ b/MC1/Views/Chats/Components/MessagePathArrival.swift @@ -11,9 +11,9 @@ struct MessagePathArrival: Identifiable, Equatable, Hashable, Sendable { let receivedAt: Date let isFirst: Bool - /// Hop count decoded from `pathLength` (lower 6 bits). - var hopCount: Int { - decodePathLen(pathLength)?.hopCount ?? Int(pathLength & 63) + /// Hop count from a path-length byte `decodePathLen` accepts. A rejected byte, including 0xFF, has none. + var hopCount: Int? { + decodePathLen(pathLength)?.hopCount } /// Empty path bytes with hop count 0 is a 0-hop arrival, not missing path data. diff --git a/MC1/Views/Chats/Components/MessagePathArrivalCapsules.swift b/MC1/Views/Chats/Components/MessagePathArrivalCapsules.swift index 0a0bf790ce..29efe1852e 100644 --- a/MC1/Views/Chats/Components/MessagePathArrivalCapsules.swift +++ b/MC1/Views/Chats/Components/MessagePathArrivalCapsules.swift @@ -109,14 +109,21 @@ struct MessagePathArrivalCapsules: View { } private func title(for arrival: MessagePathArrival) -> String { - let hops = arrival.hopCount == 1 - ? L10n.Chats.Chats.Repeats.Hop.singular - : L10n.Chats.Chats.Repeats.Hop.plural(arrival.hopCount) - guard let snr = arrival.snr else { return hops } + let hopText: String? = if let hopCount = arrival.hopCount { + hopCount == 1 + ? L10n.Chats.Chats.Repeats.Hop.singular + : L10n.Chats.Chats.Repeats.Hop.plural(hopCount) + } else { + nil + } + guard let snr = arrival.snr else { + return hopText ?? L10n.Chats.Chats.Path.Unavailable.title + } let snrText = snr.formatted(.number.precision(.fractionLength(1))) + " " + L10n.RemoteNodes.RemoteNodes.Status.snrBadgeUnit - return "\(hops) · \(snrText)" + guard let hopText else { return snrText } + return "\(hopText) · \(snrText)" } private func subtitle(for arrival: MessagePathArrival) -> String { diff --git a/MC1/Views/Chats/Components/MessagePathDetailBlock.swift b/MC1/Views/Chats/Components/MessagePathDetailBlock.swift index 1cd52d8464..aeebba86cc 100644 --- a/MC1/Views/Chats/Components/MessagePathDetailBlock.swift +++ b/MC1/Views/Chats/Components/MessagePathDetailBlock.swift @@ -2,7 +2,7 @@ import CoreLocation import MC1Services import SwiftUI -/// Capsules, compact preview map, hop list, and expand-to-full-map sheet. +/// Outgoing repeat rows or incoming arrival paths and maps. struct MessagePathDetailBlock: View { private static let expandedContentTopPadding: CGFloat = 8 private static let outgoingDisclosureSymbol = "arrow.triangle.branch" @@ -15,6 +15,7 @@ struct MessagePathDetailBlock: View { let message: MessageDTO let arrivals: [MessagePathArrival] + let repeats: [MessageRepeatDTO]? let pathViewModel: MessagePathViewModel @Binding var isDetailExpanded: Bool @@ -44,6 +45,7 @@ struct MessagePathDetailBlock: View { proxy.size.width } action: { containerWidth = $0 } .task(id: prefetchID) { + guard !message.isOutgoing else { return } await pathViewModel.prefetchPreviews( message: message, arrivals: arrivals, @@ -124,24 +126,33 @@ struct MessagePathDetailBlock: View { private var expandedContent: some View { VStack(alignment: .leading, spacing: 12) { - if arrivals.count > 1 { - MessagePathArrivalCapsules( - arrivals: arrivals, - selectedID: selectedBinding, - reduceMotion: reduceMotion - ) - } - - previewMap - - if let selectedArrival { - MessagePathContent( - message: message, - arrival: selectedArrival, - viewModel: pathViewModel, - receiverName: appState.connectedDevice?.nodeName ?? L10n.Chats.Chats.Path.Receiver.you, + if message.isOutgoing { + RepeatDetailsContent( + repeats: pathViewModel.isLoading ? nil : repeats, + contacts: pathViewModel.contacts, + discoveredNodes: pathViewModel.discoveredRepeaters, userLocation: appState.bestAvailableLocation ) + } else { + if arrivals.count > 1 { + MessagePathArrivalCapsules( + arrivals: arrivals, + selectedID: selectedBinding, + reduceMotion: reduceMotion + ) + } + + previewMap + + if let selectedArrival { + MessagePathContent( + message: message, + arrival: selectedArrival, + viewModel: pathViewModel, + receiverName: appState.connectedDevice?.nodeName ?? L10n.Chats.Chats.Path.Receiver.you, + userLocation: appState.bestAvailableLocation + ) + } } } } diff --git a/MC1/Views/Chats/Components/MessagePathMapView.swift b/MC1/Views/Chats/Components/MessagePathMapView.swift index 207a1e0d84..f603fdf66d 100644 --- a/MC1/Views/Chats/Components/MessagePathMapView.swift +++ b/MC1/Views/Chats/Components/MessagePathMapView.swift @@ -44,11 +44,13 @@ struct MessagePathMapView: View { let cameraRegion: MKCoordinateRegion? let locatedCount: Int let selectedCoordinates: [CLLocationCoordinate2D] - let hopCount: Int + let hopCount: Int? let isDistanceIncomplete: Bool /// Endpoint pins alone are not a path. A single hop pin with skipped hops is a shortcut, not the path. + /// A path-length byte that did not decode has no hop geometry. var showsPathMap: Bool { + guard let hopCount else { return false } if hopCount == 0 { return locatedCount >= 1 } let placedHopCount = points.filter { $0.pinStyle == .repeaterHop }.count if placedHopCount == 0 { return false } @@ -89,9 +91,10 @@ struct MessagePathMapView: View { if canvas.showsPathMap { ToolbarItem(placement: .principal) { PathDistanceBanner( - hopCount: canvas.hopCount, + hopCount: canvas.hopCount ?? 0, totalPathDistance: canvas.selectedCoordinates.totalDistance(), - isDistanceIncomplete: canvas.isDistanceIncomplete + isDistanceIncomplete: canvas.isDistanceIncomplete, + showsHopCount: canvas.hopCount != nil ) } } @@ -121,13 +124,13 @@ struct MessagePathMapView: View { } private var pathMapUnavailableTitle: String { - canvas.hopCount == 0 + (canvas.hopCount ?? 0) == 0 ? L10n.Chats.Chats.Path.Unavailable.title : L10n.Chats.Chats.Path.Unplaceable.title } private var pathMapUnavailableDescription: String { - canvas.hopCount == 0 + (canvas.hopCount ?? 0) == 0 ? L10n.Chats.Chats.Path.Unavailable.description : L10n.Chats.Chats.Path.Unplaceable.description } @@ -343,7 +346,7 @@ struct MessagePathMapView: View { var lines: [MapLine] = [] var selectedCoordinates: [CLLocationCoordinate2D] = [] - var selectedHopCount = 0 + var selectedHopCount: Int? var isDistanceIncomplete = false if let selectedArrival = arrivals.first(where: { $0.id == selected }) { diff --git a/MC1/Views/Chats/Components/MessageVisibleBody.swift b/MC1/Views/Chats/Components/MessageVisibleBody.swift new file mode 100644 index 0000000000..b87b644a44 --- /dev/null +++ b/MC1/Views/Chats/Components/MessageVisibleBody.swift @@ -0,0 +1,49 @@ +import MC1Services +import SwiftUI + +/// The body a bubble draws and speaks for one stored string. +/// A reading replaces the stored text and hides Translation chrome. +/// A showing translation replaces the stored text and keeps its chrome. +struct MessageVisibleBody: Equatable { + /// Plain body. Nil means draw the formatted stored text. + let plainText: String? + /// Chrome to show. Nil for a reading, and when none was resolved. + let translation: MessageTranslationChrome? + let spokenText: String + + init(stored: String, translation: MessageTranslationChrome?) { + if let reading = MECPCatalog.reading(stored) { + plainText = reading + self.translation = nil + spokenText = L10n.Chats.Chats.Message.readingAccessibility( + reading.replacingOccurrences(of: "\n", with: " ") + ) + } else { + self.translation = translation + switch translation?.phase { + case let .showing(translated, _): + plainText = translated + spokenText = L10n.Chats.Chats.Message.translatedAccessibility(translated) + case .inProgress: + plainText = nil + spokenText = "\(stored), \(L10n.Chats.Chats.Message.Action.translating)" + case .offer, nil: + plainText = nil + spokenText = stored + } + } + } + + /// `MECP: ` when `storedText` decodes. Nil otherwise. + static func detailLine(storedText: String) -> String? { + guard MECPCatalog.reading(storedText) != nil else { return nil } + return L10n.Chats.Chats.Message.Info.mecp(storedText) + } + + @ViewBuilder + static func detailRow(storedText: String) -> some View { + if let line = detailLine(storedText: storedText) { + ActionInfoRow(text: line) + } + } +} diff --git a/MC1/Views/Chats/Components/RepeatRowView.swift b/MC1/Views/Chats/Components/RepeatRowView.swift index 19ba4a3484..3ebe80d44a 100644 --- a/MC1/Views/Chats/Components/RepeatRowView.swift +++ b/MC1/Views/Chats/Components/RepeatRowView.swift @@ -46,10 +46,10 @@ struct RepeatRowView: View { } } .padding(.vertical, 4) - // .combine would swallow FallbackMatchIndicatorView; .contain keeps the popover a rotor stop. + // Containment keeps the possible-match button accessible apart from the repeat row. .accessibilityElement(children: resolution.isFallback ? .contain : .combine) .accessibilityLabel(L10n.Chats.Chats.Repeats.Row.accessibility(resolution.displayName)) - .accessibilityValue(L10n.Chats.Chats.Repeats.Row.accessibilityValue(signalQuality, repeatEntry.snrFormatted, repeatEntry.rssiFormatted)) + .accessibilityValue(accessibilityValueText) } /// NeighborNameResolver, not RepeaterResolver.bestMatch: only the former reports `.fallback`. @@ -99,6 +99,14 @@ struct RepeatRowView: View { snrQuality.localizedLabel } + private var accessibilityValueText: String { + [ + L10n.Chats.Chats.Path.Hop.nodeId(repeatEntry.repeaterHashFormatted), + hopCountText, + L10n.Chats.Chats.Repeats.Row.accessibilityValue(signalQuality, repeatEntry.snrFormatted, repeatEntry.rssiFormatted) + ].joined(separator: ", ") + } + private var hopCountText: String { let count = repeatEntry.hopCount return count == 1 ? L10n.Chats.Chats.Repeats.Hop.singular : L10n.Chats.Chats.Repeats.Hop.plural(count) diff --git a/MC1/Views/Chats/Components/UnifiedMessageBubble.swift b/MC1/Views/Chats/Components/UnifiedMessageBubble.swift index bb521a2c45..7c92569d5c 100644 --- a/MC1/Views/Chats/Components/UnifiedMessageBubble.swift +++ b/MC1/Views/Chats/Components/UnifiedMessageBubble.swift @@ -171,6 +171,7 @@ struct UnifiedMessageBubble: View, Equatable { } } } + .accessibilityIdentifier(ChatScrollConstants.messageAccessibilityIdentifier(message.id)) .messageBubbleLongPressEffect(isPressing: isLongPressing, trigger: longPressTrigger) if !item.envelope.isOutgoing { @@ -356,14 +357,10 @@ struct UnifiedMessageBubble: View, Equatable { } } } - switch layout.textPayload?.translation?.phase { - case let .showing(translated, _): - label += L10n.Chats.Chats.Message.translatedAccessibility(translated) - case .inProgress: - label += "\(message.text), \(L10n.Chats.Chats.Message.Action.translating)" - default: - label += message.text - } + label += MessageVisibleBody( + stored: message.text, + translation: layout.textPayload?.translation + ).spokenText if item.envelope.isOutgoing { label += ", \(MessageStatusText.text(for: item.footer))" } diff --git a/MC1/Views/Chats/NewChatView.swift b/MC1/Views/Chats/NewChatView.swift index adc82dcfb1..fc3d8cc2e0 100644 --- a/MC1/Views/Chats/NewChatView.swift +++ b/MC1/Views/Chats/NewChatView.swift @@ -13,7 +13,7 @@ struct NewChatView: View { @State private var isLoading = false private var filteredContacts: [ContactDTO] { - let eligible = contacts.filter { !$0.isBlocked && $0.type != .repeater && $0.type != .room } + let eligible = contacts.filter { !$0.isBlocked && $0.type == .chat } guard !searchText.isEmpty else { return eligible } return eligible.filter { contact in contact.displayName.localizedStandardContains(searchText) @@ -90,7 +90,7 @@ struct NewChatView: View { contact.isFloodRouted ? L10n.Chats.Chats.ConnectionStatus.floodRouting : L10n.Chats.Chats.NewChat.ContactType.direct case .repeater: L10n.Chats.Chats.NewChat.ContactType.repeater - case .room: + case .room, .sensor: "" } } diff --git a/MC1/Views/Chats/Reactions/Sections/ActionsDetailsSection.swift b/MC1/Views/Chats/Reactions/Sections/ActionsDetailsSection.swift index f034f7056b..0bbe5a1015 100644 --- a/MC1/Views/Chats/Reactions/Sections/ActionsDetailsSection.swift +++ b/MC1/Views/Chats/Reactions/Sections/ActionsDetailsSection.swift @@ -26,6 +26,7 @@ struct ActionsDetailsSection: View { MessagePathDetailBlock( message: message, arrivals: arrivals, + repeats: repeats, pathViewModel: pathViewModel, isDetailExpanded: $isDetailExpanded ) @@ -68,6 +69,8 @@ private struct ActionsOutgoingDetailsRows: View { : L10n.Chats.Chats.Message.Repeat.plural ActionInfoRow(text: L10n.Chats.Chats.Message.Info.heardRepeats(message.heardRepeats, word)) } + + MessageVisibleBody.detailRow(storedText: message.text) } } @@ -76,13 +79,15 @@ private struct ActionsIncomingDetailsRows: View { let arrivalCount: Int var body: some View { - let hopsText = L10n.Chats.Chats.Message.Info.hops(hopCountFormatted(message)) - ActionInfoRow( - text: arrivalCount > 1 - ? "\(hopsText) · \(L10n.Chats.Chats.Path.Arrival.first)" - : hopsText, - icon: "arrowshape.bounce.right" - ) + if let hopLabel = IncomingHopDetail.hopLabel(for: message) { + let hopsText = L10n.Chats.Chats.Message.Info.hops(hopLabel) + ActionInfoRow( + text: arrivalCount > 1 + ? "\(hopsText) · \(L10n.Chats.Chats.Path.Arrival.first)" + : hopsText, + icon: "arrowshape.bounce.right" + ) + } if let hashSize = message.pathHashSizeIfKnown { ActionInfoRow(text: L10n.Chats.Chats.Message.Info.pathHash(hashSize)) @@ -130,17 +135,22 @@ private struct ActionsIncomingDetailsRows: View { : snrText ) } + + MessageVisibleBody.detailRow(storedText: message.text) } private func snrFormatted(_ snr: Double) -> String { let quality = SNRQuality(snr: snr).localizedLabel return "\(snr.formatted(.number.precision(.fractionLength(1)))) dB (\(quality))" } +} - private func hopCountFormatted(_ message: MessageDTO) -> String { +enum IncomingHopDetail { + static func hopLabel(for message: MessageDTO) -> String? { if message.isDirectRouted { return L10n.Chats.Chats.Message.Hops.direct } - return "\(message.hopCount)" + guard let hopCount = message.hopCount else { return nil } + return "\(hopCount)" } } diff --git a/MC1/Views/Chats/Reactions/Sections/ActionsPreviewHeader.swift b/MC1/Views/Chats/Reactions/Sections/ActionsPreviewHeader.swift index c34e86984b..cb944522c3 100644 --- a/MC1/Views/Chats/Reactions/Sections/ActionsPreviewHeader.swift +++ b/MC1/Views/Chats/Reactions/Sections/ActionsPreviewHeader.swift @@ -33,7 +33,7 @@ struct ActionsPreviewHeader: View { } } - Text(message.text) + Text(MECPCatalog.displayText(message.text)) .font(.subheadline) .foregroundStyle(.secondary) .lineLimit(dynamicTypeSize.isAccessibilitySize ? 2 : 1) diff --git a/MC1/Views/Chats/Room/RoomAuthenticationSheet.swift b/MC1/Views/Chats/Room/RoomAuthenticationSheet.swift index b990a1513e..0d44c4da1c 100644 --- a/MC1/Views/Chats/Room/RoomAuthenticationSheet.swift +++ b/MC1/Views/Chats/Room/RoomAuthenticationSheet.swift @@ -31,11 +31,16 @@ struct RoomAuthenticationSheet: View { } } .task { - contact = try? await appState.services?.dataStore.fetchContact( + defer { isLoading = false } + guard let source = appState.connectionSnapshot(for: session.radioID) else { return } + let context = ConnectionCallbackContext(source) + let fetched = try? await source.services.dataStore.fetchContact( radioID: session.radioID, publicKey: session.publicKey ) - isLoading = false + guard !Task.isCancelled, context.isCurrent(appState.connectionManager), + source.services.isAcceptingRuntimeWork else { return } + contact = fetched } } } diff --git a/MC1/Views/Chats/Sheets/ChannelInfoSheet.swift b/MC1/Views/Chats/Sheets/ChannelInfoSheet.swift index d52bef832b..878f8f40f4 100644 --- a/MC1/Views/Chats/Sheets/ChannelInfoSheet.swift +++ b/MC1/Views/Chats/Sheets/ChannelInfoSheet.swift @@ -136,7 +136,9 @@ struct ChannelInfoSheet: View { isClearingMessages: isClearingMessages, isDeleting: isDeleting, showingClearMessagesConfirmation: $showingClearMessagesConfirmation, - showingDeleteConfirmation: $showingDeleteConfirmation + showingDeleteConfirmation: $showingDeleteConfirmation, + onClearMessages: clearMessages, + onDelete: deleteChannel ) } .themedCanvas(theme) @@ -177,34 +179,6 @@ struct ChannelInfoSheet: View { } } } - .confirmationDialog( - L10n.Chats.Chats.ChannelInfo.ClearMessagesConfirm.title, - isPresented: $showingClearMessagesConfirmation, - titleVisibility: .visible - ) { - Button(L10n.Chats.Chats.ChannelInfo.clearMessagesButton, role: .destructive) { - Task { - await clearMessages() - } - } - Button(L10n.Chats.Chats.Common.cancel, role: .cancel) {} - } message: { - Text(L10n.Chats.Chats.ChannelInfo.ClearMessagesConfirm.message) - } - .confirmationDialog( - L10n.Chats.Chats.ChannelInfo.DeleteConfirm.title, - isPresented: $showingDeleteConfirmation, - titleVisibility: .visible - ) { - Button(L10n.Chats.Chats.ChannelInfo.deleteButton, role: .destructive) { - Task { - await deleteChannel() - } - } - Button(L10n.Chats.Chats.Common.cancel, role: .cancel) {} - } message: { - Text(L10n.Chats.Chats.ChannelInfo.DeleteConfirm.message) - } .sensoryFeedback(.success, trigger: copyHapticTrigger) } @@ -310,21 +284,6 @@ struct ChannelInfoSheet: View { } catch { logger.error("Failed to save flood scope: \(error.localizedDescription)") selectedFloodScope = previous - return - } - - if let session = appState.services?.session { - let resolved = ChannelFloodScopeResolver.resolve( - channelFloodScope: scope, - deviceDefaultFloodScopeName: appState.connectedDevice?.defaultFloodScopeName, - supportsUnscopedFloodSend: appState.connectedDevice?.supportsUnscopedFloodSend ?? false - ) - switch resolved { - case .unscoped: - try? await session.setFloodScopeUnscoped() - case let .scope(scope): - try? await session.setFloodScope(scope) - } } } @@ -516,6 +475,8 @@ private struct ChannelInfoActionsSection: View { let isDeleting: Bool @Binding var showingClearMessagesConfirmation: Bool @Binding var showingDeleteConfirmation: Bool + let onClearMessages: () async -> Void + let onDelete: () async -> Void var body: some View { Section { @@ -531,6 +492,14 @@ private struct ChannelInfoActionsSection: View { } } .disabled(isActionInProgress) + .anchoredDestructiveConfirm( + L10n.Chats.Chats.ChannelInfo.ClearMessagesConfirm.title, + isPresented: $showingClearMessagesConfirmation, + message: L10n.Chats.Chats.ChannelInfo.ClearMessagesConfirm.message, + confirmTitle: L10n.Chats.Chats.ChannelInfo.clearMessagesButton + ) { + Task { await onClearMessages() } + } Button(role: .destructive) { showingDeleteConfirmation = true @@ -544,6 +513,14 @@ private struct ChannelInfoActionsSection: View { } } .disabled(isActionInProgress) + .anchoredDestructiveConfirm( + L10n.Chats.Chats.ChannelInfo.DeleteConfirm.title, + isPresented: $showingDeleteConfirmation, + message: L10n.Chats.Chats.ChannelInfo.DeleteConfirm.message, + confirmTitle: L10n.Chats.Chats.ChannelInfo.deleteButton + ) { + Task { await onDelete() } + } } footer: { Text(L10n.Chats.Chats.ChannelInfo.deleteFooter) } @@ -716,6 +693,34 @@ private struct ChannelInfoRegionPickerContent: View { } } +private extension View { + /// A Mac confirmation dialog is a popover and can dismiss without running its confirm action, so Mac uses an alert. + @ViewBuilder + func anchoredDestructiveConfirm( + _ title: String, + isPresented: Binding, + message: String, + confirmTitle: String, + onConfirm: @escaping () -> Void + ) -> some View { + if ProcessInfo.processInfo.isiOSAppOnMac { + alert(title, isPresented: isPresented) { + Button(confirmTitle, role: .destructive, action: onConfirm) + Button(L10n.Chats.Chats.Common.cancel, role: .cancel) {} + } message: { + Text(message) + } + } else { + confirmationDialog(title, isPresented: isPresented, titleVisibility: .visible) { + Button(confirmTitle, role: .destructive, action: onConfirm) + Button(L10n.Chats.Chats.Common.cancel, role: .cancel) {} + } message: { + Text(message) + } + } + } +} + #Preview { ChannelInfoSheet( channel: ChannelDTO(from: Channel( diff --git a/MC1/Views/Chats/Timeline/ChatOpenAnchorState.swift b/MC1/Views/Chats/Timeline/ChatOpenAnchorState.swift new file mode 100644 index 0000000000..6236ed7e7f --- /dev/null +++ b/MC1/Views/Chats/Timeline/ChatOpenAnchorState.swift @@ -0,0 +1,56 @@ +import Foundation + +/// Captures one open's unread count and keeps Populate completion from replaying a consumed Anchor. +struct ChatOpenAnchorState: Equatable { + /// The list spends its initial positioning on its first non-empty snapshot, + /// so an unread open waits until the current divider-bearing row is ready. + enum FirstSnapshotDecision: Equatable { + case withhold + /// A nil target opens at the bottom. + case present(target: UUID?) + } + + private enum Phase { + case pendingPopulate + case populateSettled + case consumed + } + + private let unreadCount: Int + private var phase = Phase.pendingPopulate + + init(unreadCount: Int) { + self.unreadCount = unreadCount + } + + var hasUnread: Bool { + unreadCount > 0 + } + + mutating func completePopulate(_ outcome: ChatTimelinePopulator.Outcome) { + guard phase == .pendingPopulate else { return } + switch outcome { + case .loaded, .unavailable, .failed: + phase = .populateSettled + case .cancelled: + break + } + } + + mutating func consumeAnchor() { + phase = .consumed + } + + func firstSnapshot( + dividerMessageID: UUID?, + dividerRowOnScreen: Bool + ) -> FirstSnapshotDecision { + guard hasUnread, phase != .consumed else { return .present(target: nil) } + if let dividerMessageID { + // Membership alone can come from a prior Bake. Wait for the flag-bearing + // row before spending the list's one-shot initial positioning. + return dividerRowOnScreen ? .present(target: dividerMessageID) : .withhold + } + return phase == .populateSettled ? .present(target: nil) : .withhold + } +} diff --git a/MC1/Views/Chats/Timeline/ChatTimeline+Paging.swift b/MC1/Views/Chats/Timeline/ChatTimeline+Paging.swift index 55f8745988..2635853c10 100644 --- a/MC1/Views/Chats/Timeline/ChatTimeline+Paging.swift +++ b/MC1/Views/Chats/Timeline/ChatTimeline+Paging.swift @@ -4,34 +4,33 @@ import MC1Services extension ChatTimeline { // MARK: - Populate - /// Populates the coordinator for `conversation` and bakes render items. - /// Returns `.unavailable` when unbound. - /// `populateMode` selects first-page replacement or an in-place window refresh; see `ChatPopulateMode`. + /// Populates and bakes the first page or refreshes the loaded window. + /// Returns `.unavailable` when no writer or data store is available. func open( _ conversation: ChatConversationType, reactions: ReactionIndexing?, - populateMode: ChatPopulateMode + populateMode: ChatPopulateMode, + includingSortDate: Date? = nil ) async -> ChatTimelinePopulator.Outcome { guard !Task.isCancelled else { return .cancelled } self.conversation = conversation - // Cancelled attempts preserve readiness so an unresolved open waits - // for its retry to resolve the anchor. - var shouldSettleInitialLoad = true + let boundWriter = writer + var outcome = ChatTimelinePopulator.Outcome.unavailable defer { - if shouldSettleInitialLoad { initialLoadSettled = true } + if self.writer === boundWriter { completePopulate(outcome) } } - guard let writer else { return .unavailable } - // Interactive opens staged with no unread have already presented at the - // bottom; pre-latch so a fresher store unread count cannot bake a late - // divider that grows a presented row. Primes carry no anchor and skip it. - if role == .interactive, openUnreadCount == 0 { + guard let writer = boundWriter else { return outcome } + // A zero-unread interactive open already presents at the bottom. + // Freeze its divider before Populate can see a newer unread count. + if role == .interactive, !openAnchorState.hasUnread { bake.dividerComputed = true } #if DEBUG if let error = testPopulateError { writer.beginLoading() writer.markLoaded() - return .failed(error) + outcome = .failed(error) + return outcome } coordinator?.testPopulateFetchError = testPopulateFetchError #endif @@ -41,19 +40,18 @@ extension ChatTimeline { scope: indexing.scope ) } - guard let coordinator else { return .unavailable } - let outcome: ChatTimelinePopulator.Outcome + guard let coordinator else { return outcome } do { outcome = try await writer.performWindowOperation { try Task.checkCancellation() - // Compute the anchor inside the lane. An earlier loadOlder would - // extend the window; an enqueue-time anchor would truncate it. + guard writer.isCurrent, self.writer === writer else { throw CancellationError() } + // Read the oldest date inside the lane so Populate preserves history + // fetched by an earlier page operation. let refreshWindow = populateMode == .refreshWindow && coordinator.conversationID == conversation.coordinatorID && coordinator.renderState.phase == .loaded - && !coordinator.messages.isEmpty let anchorSortDate: Date? = refreshWindow - ? coordinator.messages.map(\.sortDate).min() + ? [coordinator.messages.map(\.sortDate).min(), includingSortDate].compactMap(\.self).min() : nil return await ChatTimelinePopulator.populate( conversation, @@ -63,17 +61,14 @@ extension ChatTimeline { envInputs: envInputs, senderTables: senderTablesProvider, postApply: postApply, - anchorSortDate: anchorSortDate + anchorSortDate: anchorSortDate, + isCurrent: { self.writer === writer && self.coordinator === coordinator && writer.isCurrent } ) } } catch is CancellationError { - shouldSettleInitialLoad = false - return .cancelled + outcome = .cancelled } catch { - return .failed(error) - } - if case .cancelled = outcome { - shouldSettleInitialLoad = false + outcome = .failed(error) } if case .loaded = outcome, let context, diff --git a/MC1/Views/Chats/Timeline/ChatTimeline.swift b/MC1/Views/Chats/Timeline/ChatTimeline.swift index 2e6c3bd1e2..60195d4da7 100644 --- a/MC1/Views/Chats/Timeline/ChatTimeline.swift +++ b/MC1/Views/Chats/Timeline/ChatTimeline.swift @@ -2,21 +2,11 @@ import Foundation import MC1Services import OSLog -/// Per-conversation assembly module. Owns the bake state, the write -/// capability, and the populate → divider → filter → write → bake ordering, -/// so callers get `open`/`rebake` verbs instead of hand-sequencing raw -/// writer mutations. -/// -/// Role-parameterized: the interactive conversation (`ChatViewModel`) and the -/// speculative warm (`ChatTimelinePrimer`) drive one implementation, differing -/// only in the `ChatWriterRole` they bind with and the hooks they supply. -/// The writer/generation anti-clobber machinery stays in `ChatCoordinator`; -/// this module consumes it. +/// Assembles one conversation's timeline and owns Populate and Bake ordering. +/// Writer authority stays with ChatCoordinator for interactive opens and Prime. @Observable @MainActor final class ChatTimeline { - /// Reaction-indexing inputs for `open`. The row-rebake hook is this - /// timeline's own; callers supply only what varies. struct ReactionIndexing { let service: ReactionService let scope: ReactionIndexScope @@ -38,31 +28,18 @@ final class ChatTimeline { /// safe pre-`configure`) or `bind` (with write capability). private(set) var coordinator: ChatCoordinator? - /// Write capability minted by the last successful `bind`; nil when unbound - /// or when a `.prime` bind was denied. Stale writers no-op at the - /// coordinator, so holding one across a supersede is safe. + /// The last bound write capability; stale writers no-op at the coordinator. @ObservationIgnored private(set) var writer: ChatTimelineWriter? /// Environment-derived inputs baked into every `MessageItem`. var envInputs: EnvInputs = .default - /// Conversation this timeline is assembling. Captured by `stageOpen` and - /// `open`; owners that refresh its DTO assign it directly. Paging fetches - /// key off its IDs, which are stable across DTO refreshes. + /// DTO refreshes keep the same conversation IDs, so paging can use the latest value. @ObservationIgnored var conversation: ChatConversationType? - /// Unread count captured when the open was staged, before any clearing - /// side effect runs. Gates whether the open expects a divider at all. - private(set) var openUnreadCount = 0 - - /// Whether the view has consumed the one-shot open positioning. - private(set) var anchorConsumed = false - - /// Set after a terminal populate so opens without a divider can present. - /// Cancellation leaves the latch unchanged until a retry finishes. - var initialLoadSettled = false + private(set) var openAnchorState = ChatOpenAnchorState(unreadCount: 0) #if DEBUG /// When set, `open` returns populate's failure contract without a process-global hook. @@ -87,8 +64,7 @@ final class ChatTimeline { @ObservationIgnored var senderTablesProvider: @MainActor () -> ChatSenderTables = { .empty } - /// Runs after each full-timeline bake applies (the interactive owner's - /// legacy preview decode); nil for primes. + /// Runs after a full-timeline Bake applies; Prime leaves it nil. @ObservationIgnored var postApply: (@MainActor () -> Void)? @@ -120,22 +96,14 @@ final class ChatTimeline { // MARK: - Binding - /// Attaches the shared coordinator for reads only, so a warm conversation - /// renders on the first frame before the load task binds. Never touches the - /// writer slot or hooks, so it is safe from view `init`, where transient - /// instances may be created and discarded. + /// Exposes cached messages before binding without claiming writer authority, + /// so transient view instances cannot displace a live owner. func attach(_ coordinator: ChatCoordinator) { self.coordinator = coordinator } - /// Claims the coordinator's writer slot for this timeline's role and - /// installs the rebake hooks as one atomic act. Returns false when the - /// bind was denied (a `.prime` against a live interactive owner); the - /// coordinator stays attached for reads either way. - /// - /// Hooks capture this timeline weakly: when the owning view model or - /// primer is discarded, the timeline goes with it and a late invalidation - /// no-ops; the next open's full rebuild repairs the items. + /// Claims this timeline's writer role and installs weakly captured Bake hooks. + /// A denied Prime retains read access; hooks no-op when their owner is gone. @discardableResult func bind( _ coordinator: ChatCoordinator, @@ -160,10 +128,8 @@ final class ChatTimeline { return writer != nil } - /// Vacates the coordinator's writer slot so arrival-time prime refreshes - /// can service this conversation while it is off screen; the next `bind` - /// reclaims it. Deallocation is not a substitute: SwiftUI can keep a - /// popped destination's state alive. + /// Releases writer authority for Prime while off screen, because SwiftUI can + /// retain a popped destination's state beyond its visible lifetime. func releaseWriter() { if let coordinator { coordinator.releaseWriter(owner: self) @@ -172,9 +138,7 @@ final class ChatTimeline { } #if DEBUG - /// Test seam: adopts an externally minted writer/coordinator pair so - /// suites can bind with a chosen role and custom hooks, mirroring - /// pre-bind states `bind` cannot produce (e.g. a stale prime holder). + /// Adopts a writer with custom hooks so tests can represent a stale holder. func adoptForTesting(coordinator: ChatCoordinator, writer: ChatTimelineWriter?) { self.coordinator = coordinator self.writer = writer @@ -187,16 +151,13 @@ final class ChatTimeline { /// and there are messages to rebake. Idempotent on no-change. func applyEnvInputs(_ new: EnvInputs) { guard envInputs != new else { return } - // When the network transitions from unavailable to available, drop the - // sticky map-snapshot failures so renders that failed during the outage - // retry on the next rebuild. Without this, an offline-pack miss stays - // poisoned until a memory warning evicts the failed set. + // Retry cached map-snapshot failures when the network returns, rather than + // waiting for memory pressure to evict failures from the outage. if envInputs.isOffline, !new.isOffline { MapSnapshotStore.shared.clearFailures() } envInputs = new - // The environment feeds every formatting input, so its cached output is - // now stale for all rows and must be rebuilt under the new appearance. + // Cached formatting depends on the environment, so every row must be rebuilt. bake.formattedTextCache.removeAll() guard !messages.isEmpty else { return } rebakeAll() @@ -204,34 +165,28 @@ final class ChatTimeline { // MARK: - Open anchor - /// Stages a conversation for opening: captures the unread count the - /// anchor decision keys on and resets the per-open latches and divider so - /// the anchor can only come from this session's bake, never one a shared - /// coordinator carries over from a previous open. + /// Captures this open's unread count and resets its divider so the Anchor cannot + /// come from a previous open's cached rows. func stageOpen(_ conversation: ChatConversationType) { self.conversation = conversation - openUnreadCount = conversation.unreadCount - anchorConsumed = false - initialLoadSettled = false + openAnchorState = ChatOpenAnchorState(unreadCount: conversation.unreadCount) bake.newMessagesDividerMessageID = nil bake.dividerComputed = false } - /// First-snapshot decision for the staged open; see - /// `ChatInitialScrollPolicy`. `bake` is not observable, but its divider - /// only moves alongside a coordinator mutation, so the observable - /// `itemIndexByID` read and the latch properties re-evaluate this whenever - /// a decision input has changed. - var firstSnapshot: ChatInitialScrollPolicy.FirstSnapshotDecision { + func completePopulate(_ outcome: ChatTimelinePopulator.Outcome) { + openAnchorState.completePopulate(outcome) + } + + /// Bake's divider changes alongside coordinator mutations, so observing the + /// current items and open state keeps this decision current. + var firstSnapshot: ChatOpenAnchorState.FirstSnapshotDecision { let dividerMessageID = bake.newMessagesDividerMessageID let dividerRowOnScreen = dividerMessageID.flatMap { id -> Bool? in guard let index = itemIndexByID[id], items.indices.contains(index) else { return nil } return items[index].grouping.showNewMessagesDivider } ?? false - return ChatInitialScrollPolicy.firstSnapshotDecision( - hasConsumed: anchorConsumed, - unreadCount: openUnreadCount, - initialLoadSettled: initialLoadSettled, + return openAnchorState.firstSnapshot( dividerMessageID: dividerMessageID, dividerRowOnScreen: dividerRowOnScreen ) @@ -240,6 +195,6 @@ final class ChatTimeline { /// Marks the one-shot open positioning as spent. Called when the view's /// list has positioned on the anchor; later snapshots present freely. func consumeAnchor() { - anchorConsumed = true + openAnchorState.consumeAnchor() } } diff --git a/MC1/Views/Chats/ViewModel/ChatMessageBakeState+ItemBuild.swift b/MC1/Views/Chats/ViewModel/ChatMessageBakeState+ItemBuild.swift index 51a6a9e4e8..797f4f6f80 100644 --- a/MC1/Views/Chats/ViewModel/ChatMessageBakeState+ItemBuild.swift +++ b/MC1/Views/Chats/ViewModel/ChatMessageBakeState+ItemBuild.swift @@ -174,6 +174,16 @@ extension ChatMessageBakeState { isMapPreviewReady = MapSnapshotStore.shared.isResolved(request) } + let translation: MessageTranslationChrome? = if message.isOutgoing || !envInputs.translationOffersEnabled { + nil + } else { + MessageTranslationChrome.resolved( + detected: detectedLanguages[message.id], + phase: translationPhases[message.id], + preferredLanguageCode: envInputs.preferredLanguageCode, + text: message.text + ) + } let senderResolution = senderResolutionFor(message, senderTables: senderTables) let incomingAvatar: IncomingAvatarIdentity? = if flags.isClusterEnd { IncomingAvatarIdentity.resolve( @@ -212,13 +222,7 @@ extension ChatMessageBakeState { showNewMessagesDivider: message.id == newMessagesDividerMessageID, showDayDivider: flags.showDayDivider, incomingAvatar: incomingAvatar, - translation: message.isOutgoing || !envInputs.translationOffersEnabled - ? nil - : MessageTranslationChrome.resolved( - detected: detectedLanguages[message.id], - phase: translationPhases[message.id], - preferredLanguageCode: envInputs.preferredLanguageCode - ) + translation: translation ) } diff --git a/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift b/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift index caaa6d23d5..73f9a16765 100644 --- a/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift +++ b/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift @@ -33,7 +33,8 @@ enum ChatTimelinePopulator { envInputs: EnvInputs, senderTables: @MainActor () -> ChatSenderTables, postApply: (@MainActor () -> Void)?, - anchorSortDate: Date? + anchorSortDate: Date?, + isCurrent: @MainActor () -> Bool ) async -> Outcome { writer.beginLoading() @@ -79,6 +80,7 @@ enum ChatTimelinePopulator { await writer.testPopulateAfterFetchHook?() #endif try Task.checkCancellation() + guard isCurrent() else { throw CancellationError() } var fetchedMessages = window.messages let unfilteredCount = fetchedMessages.count @@ -161,7 +163,7 @@ enum ChatTimelinePopulator { channelIndex: channel.index, senderName: senderName, text: message.text, - timestamp: message.timestamp + timestamp: message.reactionTimestamp ) for pending in pendingMatches { @@ -206,7 +208,8 @@ enum ChatTimelinePopulator { reactionDTO, reactionService: reactionService, dataStore: dataStore, - writer: writer + writer: writer, + directMessage: pending.directMessage ) } } @@ -217,7 +220,8 @@ enum ChatTimelinePopulator { _ reaction: ReactionDTO, reactionService: ReactionService, dataStore: DataStore, - writer: ChatTimelineWriter + writer: ChatTimelineWriter, + directMessage: (scope: ReceiveScope, contact: ContactDTO)? = nil ) async { let exists = try? await dataStore.reactionExists( messageID: reaction.messageID, @@ -228,7 +232,8 @@ enum ChatTimelinePopulator { if let result = await reactionService.persistReactionAndUpdateSummary( reaction, - using: dataStore + using: dataStore, + directMessage: directMessage ) { writer.enqueueReload(messageID: result.messageID) } diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+Channels.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+Channels.swift index f0ab08b9a7..3dd07fc6dd 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+Channels.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+Channels.swift @@ -4,11 +4,8 @@ import MC1Services extension ChatViewModel { // MARK: - Channel Messages - /// Load messages for a channel: marks it active, syncs the device flood scope, - /// populates the coordinator, then clears unread state. Delegates coordinator - /// population to `primeInitialChannelMessages(for:)`; the unread/badge/notify - /// side effects here run only when that load succeeded. - /// `populateMode` selects first-page replacement or an in-place window refresh; see `ChatPopulateMode`. + /// Populates the active channel before clearing unread state so a failed load + /// preserves unread markers. func loadChannelMessages(for channel: ChannelDTO, populateMode: ChatPopulateMode) async { guard !Task.isCancelled else { return } let dataStore = dataStore @@ -20,12 +17,6 @@ extension ChatViewModel { ) let loaded = await primeInitialChannelMessages(for: channel, populateMode: populateMode) - guard !Task.isCancelled else { return } - - // Push the device flood scope after populating the timeline. A device - // command, so it runs only on real channel open — never during prefetch. - await syncFloodScope(for: channel) - guard loaded, !Task.isCancelled else { return } // Clear unread count and mention badge, then notify UI to refresh chat list. @@ -48,13 +39,8 @@ extension ChatViewModel { } } - /// Populates the bound coordinator for `channel` and builds its render - /// items and mention senders — with no notification, flood-scope, - /// unread-clearing, or badge side effects. Safe to run before navigation to - /// warm the coordinator so the channel renders populated on the first frame - /// instead of popping in after the push transition. `loadChannelMessages` - /// layers the open-time side effects on top. - /// `populateMode` selects first-page replacement or an in-place window refresh; see `ChatPopulateMode`. + /// Populates the channel timeline and builds mention senders for the first frame. + /// Notification, unread, and badge changes belong to `loadChannelMessages`. @discardableResult func primeInitialChannelMessages(for channel: ChannelDTO, populateMode: ChatPopulateMode) async -> Bool { // Clear preview state only when switching away from a previously loaded @@ -67,7 +53,6 @@ extension ChatViewModel { if isConversationSwitch { clearPreviewState() timeline.stageOpen(.channel(channel)) - lastSetRegionScope = .unknown } currentChannel = channel @@ -110,38 +95,6 @@ extension ChatViewModel { return didLoad } - /// Pushes the device's session-scoped flood key to match the effective scope - /// for `channel`. The effective scope combines the per-channel preference with - /// the device-level default — `.inherit` means "fall through to the default". - /// A no-op when the desired scope already matches the last one pushed. - private func syncFloodScope(for channel: ChannelDTO) async { - let deviceDefault = connectedDeviceProvider()?.defaultFloodScopeName - let desiredState: ChatViewModel.RegionScopeState = .pushed( - channel.floodScope, - deviceDefault: deviceDefault - ) - guard lastSetRegionScope != desiredState, let session = sessionProvider() else { return } - - let resolved = ChannelFloodScopeResolver.resolve( - channelFloodScope: channel.floodScope, - deviceDefaultFloodScopeName: deviceDefault, - supportsUnscopedFloodSend: connectedDeviceProvider()?.supportsUnscopedFloodSend ?? false - ) - do { - switch resolved { - case .unscoped: - try await session.setFloodScopeUnscoped() - case let .scope(scope): - try await session.setFloodScope(scope) - } - lastSetRegionScope = desiredState - } catch is CancellationError { - // Benign: a superseding load (reconnect / conversation switch) cancelled this one. - } catch { - logger.error("Failed to set flood scope: \(error.localizedDescription)") - } - } - // MARK: - Channel Actions /// Creates a pending channel Message for the service-owned send queue. @@ -150,39 +103,30 @@ extension ChatViewModel { func sendChannelMessage(text: String) async -> Bool { guard !text.isEmpty else { return true } guard let channel = currentChannel, - let messageService else { + let queue = chatSendQueueServiceProvider() else { sendErrorMessage = L10n.Chats.Chats.Alert.UnableToSend.message return false } errorMessage = nil - let message: MessageDTO do { - message = try await messageService.createPendingChannelMessage( + let admission = try await queue.enqueueChannelMessage( text: text, - channelIndex: channel.index, - radioID: channel.radioID - ) - appendMessageIfNew(message) - schedulePrefetchForMessage(message, isChannelMessage: true) + to: channel, + localNodeName: connectedDeviceProvider()?.nodeName + ) { message in + self.appendMessageIfNew(message) + self.schedulePrefetchForMessage(message, isChannelMessage: true) + } + if case let .enqueueFailed(message, error) = admission { + await presentLocalEnqueueFailure(messageID: message.id, error: error) + } + } catch ChatSendQueueServiceError.notConnected { + sendErrorMessage = L10n.Chats.Chats.Alert.UnableToSend.message + return false } catch { errorMessage = error.userFacingMessage - return true - } - - let envelope = ChannelMessageEnvelope( - messageID: message.id, - channelIndex: channel.index, - isResend: false, - messageText: message.text, - messageTimestamp: message.timestamp, - localNodeName: connectedDeviceProvider()?.nodeName - ) - do { - try await enqueueChannel(envelope) - } catch { - await recordLocalEnqueueFailure(messageID: message.id, error: error) } return true } diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+ConversationCache.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+ConversationCache.swift index 8e125b629c..505b7a5d28 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+ConversationCache.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+ConversationCache.swift @@ -30,7 +30,7 @@ extension ChatViewModel { /// do, so a delete animates once while reload-driven recomputes stay unanimated. func recomputeSnapshot() { let contactConversations = conversations - .filter { $0.type != .repeater && !$0.isBlocked && !pendingRemovalIDs.contains($0.id) } + .filter { $0.type != .repeater && $0.type != .sensor && !$0.isBlocked && !pendingRemovalIDs.contains($0.id) } .map { Conversation.direct($0) } let channelConversations = channels .filter { (!$0.name.isEmpty || $0.hasSecret) && !pendingRemovalIDs.contains($0.id) } diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+ConversationList.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+ConversationList.swift index fdc7049c96..b1d10f065b 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+ConversationList.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+ConversationList.swift @@ -365,7 +365,8 @@ extension ChatViewModel { /// Get the cached last-message preview text for a conversation, keyed by its id. func lastMessagePreview(id: UUID) -> String? { - lastMessageCache[id]?.text + guard let text = lastMessageCache[id]?.text else { return nil } + return MECPCatalog.displayText(text) } /// Load last message previews for all conversations. diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift index e57951e0e9..4cb6a130f9 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift @@ -11,15 +11,19 @@ extension ChatViewModel { /// Incoming messages are inserted in event order before their previews load. func handle(_ event: MessageEvent) async { switch event { - case let .directMessageReceived(message, contact): + case let .directMessageReceived(message, contact, scope): guard let current = currentContact, current.id == contact.id else { return } + guard let dataStore, + await (try? dataStore.currentDirectMessageContact(contact, scope: scope)) != nil, + scope.isCurrent, currentContact?.id == contact.id else { return } admitIncomingMessage(message, isChannelMessage: false) recordIncomingMentionIfNeeded(message) - case let .channelMessageReceived(message, channelIndex): + case let .channelMessageReceived(message, channelIndex, scope): guard let channel = currentChannel, channel.index == channelIndex, - message.radioID == channel.radioID else { return } + message.radioID == channel.radioID, + scope.isCurrent else { return } admitIncomingMessage(message, isChannelMessage: true) recordIncomingMentionIfNeeded(message) @@ -46,7 +50,7 @@ extension ChatViewModel { case let .messageFailed(messageID): timeline.enqueueReload(messageID: messageID) - await markFailedSendSeenIfCurrent(messageID: messageID) + await handleMessageFailure(messageID: messageID) case let .heardRepeatRecorded(messageID, _), let .reactionReceived(messageID, _): @@ -73,25 +77,63 @@ extension ChatViewModel { contactRefreshSignal &+= 1 } - /// Local enqueue/retry threw before the send queue could emit `.messageFailed`. - /// Writes `.failed` (which resets `failureSeen`) then marks the open thread - /// seen so the list badge does not reappear on pop-back. + private func handleMessageFailure(messageID: UUID) async { + let writer = timelineWriter + let coordinator = self.coordinator + guard let dataStore, let message = try? await dataStore.fetchMessage(id: messageID) else { + return + } + + let isReaction = message.isOutgoing && (message.contactID != nil + ? ReactionParser.parseDM(message.text) != nil + : ReactionParser.parse(message.text) != nil) + if isReaction { + let isCurrentConversation = currentContact.map { + message.radioID == $0.radioID && message.contactID == $0.id + } == true || currentChannel.map { + message.radioID == $0.radioID && message.channelIndex == $0.index + } == true + guard !Task.isCancelled, let writer, writer === timelineWriter, writer.isCurrent, + message.status == .failed, isCurrentConversation else { return } + if messagesByID[messageID] == nil { + guard let conversation = timeline.conversation else { return } + let outcome = await timeline.open( + conversation, reactions: nil, populateMode: .refreshWindow, includingSortDate: message.sortDate + ) + guard !Task.isCancelled, writer === timelineWriter, writer.isCurrent else { return } + guard case .loaded = outcome else { + sendErrorMessage = L10n.Chats.Chats.Alert.UnableToSend.message + return + } + await coordinator?.buildItemsTask?.value + guard !Task.isCancelled, writer === timelineWriter, writer.isCurrent else { return } + } + guard messagesByID[messageID]?.status == .failed else { return } + sendErrorMessage = L10n.Chats.Chats.Alert.UnableToSend.message + } + + await markFailedSendSeenIfCurrent(message: message) + } + + /// Persists retry enqueue failures before presentation because the queue emits no failure event. func recordLocalEnqueueFailure(messageID: UUID, error: Error) async { - logger.error("enqueue failed for messageID=\(messageID, privacy: .public): \(String(describing: error))") _ = try? await dataStore?.updateMessageStatusUnlessDelivered(id: messageID, status: .failed) + await presentLocalEnqueueFailure(messageID: messageID, error: error) + } + + func presentLocalEnqueueFailure(messageID: UUID, error: Error) async { + logger.error("enqueue failed for messageID=\(messageID, privacy: .public): \(String(describing: error))") timeline.applyStatusUpdate(messageID: messageID, status: .failed) + await handleMessageFailure(messageID: messageID) sendErrorMessage = Self.copyForEnqueueFailure(error) - await markFailedSendSeenIfCurrent(messageID: messageID) } - /// A fail that lands while this thread is open is already on screen; mark it - /// seen so the list badge does not reappear on pop-back. - private func markFailedSendSeenIfCurrent(messageID: UUID) async { - guard let dataStore, let message = try? await dataStore.fetchMessage(id: messageID) else { - return - } + /// Marks Failed-send seen in the open Conversation so its list badge stays cleared. + private func markFailedSendSeenIfCurrent(message: MessageDTO) async { + guard let dataStore else { return } do { - if let contact = currentContact, message.contactID == contact.id { + if let contact = currentContact, + message.radioID == contact.radioID, message.contactID == contact.id { try await dataStore.markFailedSendsSeen(contactID: contact.id) syncCoordinator?.notifyConversationsChanged() } else if let channel = currentChannel, diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+MessageActions.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+MessageActions.swift index d883738670..63be19ec1e 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+MessageActions.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+MessageActions.swift @@ -2,6 +2,8 @@ import MC1Services import SwiftUI extension ChatViewModel { + private static let singleMessageDeletionCount = 1 + // MARK: - Message Actions /// Retry sending a failed direct message through the persistent send @@ -20,15 +22,18 @@ extension ChatViewModel { defer { retryInFlight = false } guard let contact = currentContact, - let dataStore else { - logger.warning("retryMessage: missing currentContact or dataStore") + let dataStore = dataStoreForDMRetry(to: contact) else { + logger.warning("retryMessage: DM persistence is unavailable") return } errorMessage = nil errorBannerMessage = nil - let envelope = DirectMessageEnvelope(messageID: message.id, contactID: contact.id) + let envelope = DirectMessageEnvelope( + messageID: message.id, contactID: contact.id, + isSingleAttempt: message.reactionTargetMessageID != nil + ) let dto = PendingSendDTO(envelope: envelope, radioID: contact.radioID) do { @@ -83,12 +88,15 @@ extension ChatViewModel { // debounces via retryInFlight, sendAgain via actions-sheet dismissal — // extracting a shared body would lose that distinction. guard let contact = currentContact, - let dataStore else { - logger.warning("sendAgain (DM): missing currentContact or dataStore") + let dataStore = dataStoreForDMRetry(to: contact) else { + logger.warning("sendAgain (DM): DM persistence is unavailable") return } - let envelope = DirectMessageEnvelope(messageID: message.id, contactID: contact.id, isResend: true) + let envelope = DirectMessageEnvelope( + messageID: message.id, contactID: contact.id, isResend: true, + isSingleAttempt: message.reactionTargetMessageID != nil + ) let dto = PendingSendDTO(envelope: envelope, radioID: contact.radioID) do { @@ -119,10 +127,7 @@ extension ChatViewModel { guard connectionStateProvider() == .ready, let dataStore else { return } do { - try await dataStore.deleteMessage(id: message.id) - - // Remove from all local collections - timeline.removeMessage(message.id) + let deletedCount = try await dataStore.deleteMessageAndCount(id: message.id) // Clean up preview state for deleted message cleanupPreviewState(for: message.id) @@ -137,6 +142,15 @@ extension ChatViewModel { try await dataStore.recomputeContactLastMessageDate(contactID: currentContact.id) syncCoordinator?.notifyConversationsChanged() } + + // Cascaded wire rows can be hidden, so refetch the window to reconcile paging too. + if deletedCount > Self.singleMessageDeletionCount, let conversation = timeline.conversation { + if case let .failed(error) = await timeline.open(conversation, reactions: nil, populateMode: .refreshWindow) { + throw error + } + } else { + timeline.removeMessage(message.id) + } } catch { errorMessage = error.userFacingMessage } @@ -165,4 +179,13 @@ extension ChatViewModel { } await notificationService?.updateBadgeCount() } + + private func dataStoreForDMRetry(to contact: ContactDTO) -> DataStore? { + guard currentRadioIDProvider() == contact.radioID, + let dataStore, + connectionStateProvider() == .disconnected || chatSendQueueServiceProvider() != nil else { + return nil + } + return dataStore + } } diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+Messages.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+Messages.swift index a13b58b25a..de6d6981c5 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+Messages.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+Messages.swift @@ -155,29 +155,27 @@ extension ChatViewModel { func sendMessage(text: String) async -> Bool { guard !text.isEmpty else { return true } guard let contact = currentContact, - let messageService else { + let queue = chatSendQueueServiceProvider() else { sendErrorMessage = L10n.Chats.Chats.Alert.UnableToSend.message return false } errorMessage = nil - let message: MessageDTO do { - message = try await messageService.createPendingMessage(text: text, to: contact) - appendMessageIfNew(message) - schedulePrefetchForMessage(message, isChannelMessage: false) - syncCoordinator?.notifyConversationsChanged() + let admission = try await queue.enqueueDirectMessage(text: text, to: contact) { message in + self.appendMessageIfNew(message) + self.schedulePrefetchForMessage(message, isChannelMessage: false) + self.syncCoordinator?.notifyConversationsChanged() + } + if case let .enqueueFailed(message, error) = admission { + await presentLocalEnqueueFailure(messageID: message.id, error: error) + } + } catch ChatSendQueueServiceError.notConnected { + sendErrorMessage = L10n.Chats.Chats.Alert.UnableToSend.message + return false } catch { errorMessage = error.userFacingMessage - return true - } - - let envelope = DirectMessageEnvelope(messageID: message.id, contactID: contact.id) - do { - try await enqueueDM(envelope) - } catch { - await recordLocalEnqueueFailure(messageID: message.id, error: error) } return true } diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+Reactions.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+Reactions.swift index 902a96327b..d9766539ab 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+Reactions.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+Reactions.swift @@ -1,4 +1,3 @@ -import Foundation import MC1Services extension ChatViewModel { @@ -6,161 +5,22 @@ extension ChatViewModel { /// Send a reaction emoji to a message (channel or DM) func sendReaction(emoji: String, to message: MessageDTO) async { - guard reactionServiceProvider() != nil, - messageService != nil, - let dataStore else { + guard let queue = chatSendQueueServiceProvider(), + let localNodeName = connectedDeviceProvider()?.nodeName else { + sendErrorMessage = L10n.Chats.Chats.Alert.UnableToSend.message return } - // Prevent duplicate sends from rapid taps let reactionKey = "\(message.id)-\(emoji)" - guard !inFlightReactions.contains(reactionKey) else { - logger.debug("Reaction \(emoji) already in flight for message \(message.id), ignoring") - return - } + guard !inFlightReactions.contains(reactionKey) else { return } inFlightReactions.insert(reactionKey) defer { inFlightReactions.remove(reactionKey) } - let localNodeName = connectedDeviceProvider()?.nodeName ?? "Me" - - // Check if user already reacted with this emoji - if let alreadyReacted = try? await dataStore.reactionExists( - messageID: message.id, - senderName: localNodeName, - emoji: emoji - ), alreadyReacted { - logger.debug("User already reacted with \(emoji), ignoring") - return - } - - // Handle channel vs DM - if let channelIndex = message.channelIndex { - await sendChannelReaction( - emoji: emoji, - to: message, - channelIndex: channelIndex, - localNodeName: localNodeName - ) - } else if let contactID = message.contactID { - await sendDMReaction( - emoji: emoji, - to: message, - contactID: contactID, - localNodeName: localNodeName - ) - } - } - - private func sendChannelReaction( - emoji: String, - to message: MessageDTO, - channelIndex: UInt8, - localNodeName: String - ) async { - guard let reactionService = reactionServiceProvider(), - let messageService, - let dataStore else { return } - - // Determine target sender name - let targetSenderName: String - if message.isOutgoing { - targetSenderName = localNodeName - } else { - guard let senderName = message.senderNodeName else { return } - targetSenderName = senderName - } - - let reactionText = reactionService.buildReactionText( - emoji: emoji, - targetSender: targetSenderName, - targetText: message.text, - targetTimestamp: message.reactionTimestamp - ) - - do { - _ = try await messageService.sendChannelMessage( - text: reactionText, - channelIndex: channelIndex, - radioID: message.radioID - ) - - // Optimistic local update - let messageHash = ReactionParser.generateMessageHash( - text: message.text, - timestamp: message.reactionTimestamp - ) - let reactionDTO = ReactionDTO( - messageID: message.id, - emoji: emoji, - senderName: localNodeName, - messageHash: messageHash, - rawText: reactionText, - channelIndex: channelIndex, - radioID: message.radioID - ) - if await reactionService.persistReactionAndUpdateSummary( - reactionDTO, - using: dataStore - ) != nil { - timeline.enqueueReload(messageID: message.id) - } - } catch { - logger.error("Failed to send channel reaction: \(error)") - errorMessage = error.userFacingMessage - } - } - - private func sendDMReaction( - emoji: String, - to message: MessageDTO, - contactID: UUID, - localNodeName: String - ) async { - guard let reactionService = reactionServiceProvider(), - let messageService, - let dataStore else { return } - - // Fetch the contact for sending - guard let contact = try? await dataStore.fetchContact(id: contactID) else { - logger.error("Failed to fetch contact for DM reaction") - return - } - - let reactionText = reactionService.buildDMReactionText( - emoji: emoji, - targetText: message.text, - targetTimestamp: message.reactionTimestamp - ) do { - // Send as DM to the contact - _ = try await messageService.sendDirectMessage( - text: reactionText, - to: contact - ) - - // Optimistic local update - let messageHash = ReactionParser.generateMessageHash( - text: message.text, - timestamp: message.reactionTimestamp - ) - let reactionDTO = ReactionDTO( - messageID: message.id, - emoji: emoji, - senderName: localNodeName, - messageHash: messageHash, - rawText: reactionText, - contactID: contactID, - radioID: message.radioID - ) - if await reactionService.persistReactionAndUpdateSummary( - reactionDTO, - using: dataStore - ) != nil { - timeline.enqueueReload(messageID: message.id) - } + _ = try await queue.enqueueReaction(to: message, emoji: emoji, senderName: localNodeName) } catch { - logger.error("Failed to send DM reaction: \(error)") - errorMessage = error.userFacingMessage + logger.error("Failed to queue reaction: \(error)") + sendErrorMessage = Self.copyForEnqueueFailure(error) } } } diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+SendQueues.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+SendQueues.swift index afb96ae930..1cd89f7bca 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+SendQueues.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+SendQueues.swift @@ -2,21 +2,7 @@ import Foundation import MC1Services extension ChatViewModel { - /// Route a DM enqueue through the service-owned send queue. The - /// service persists the row and drives the drain. Throws - /// `.notConnected` if the connection has been torn down between the - /// optimistic DB write and this call, or `.persistFailed` if the - /// SwiftData write fails. The caller's catch flips the message to - /// `.failed` and surfaces the error. - func enqueueDM(_ envelope: DirectMessageEnvelope) async throws { - guard let queue = chatSendQueueServiceProvider() else { - throw ChatSendQueueServiceError.notConnected - } - try await queue.enqueueDM(envelope) - } - - /// Route a channel enqueue through the service-owned send queue. - /// See `enqueueDM` for the error contract. + /// Queues a channel retry; the caller repairs and presents an enqueue failure. func enqueueChannel(_ envelope: ChannelMessageEnvelope) async throws { guard let queue = chatSendQueueServiceProvider() else { throw ChatSendQueueServiceError.notConnected diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel.swift b/MC1/Views/Chats/ViewModel/ChatViewModel.swift index fc02735771..e915d88be1 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel.swift @@ -8,14 +8,6 @@ import UIKit @Observable @MainActor final class ChatViewModel { - /// Tracks the last flood scope we pushed to the device for the current channel. - /// Keyed by the input pair (per-channel preference, device default) so that a - /// change in either triggers a fresh push next time `loadChannelMessages` runs. - enum RegionScopeState: Equatable { - case unknown - case pushed(ChannelFloodScope, deviceDefault: String?) - } - /// Identifies an incoming self-mention with a per-mention sequence number so /// `.onChange(of:)` fires for consecutive mentions of the same message. /// `Equatable` is auto-synthesised from `UUID` + `UInt64`; adding a non-Equatable @@ -115,9 +107,6 @@ final class ChatViewModel { // MARK: - Conversation Cache Storage - /// Tracks the last region scope sent to the device via setFloodScope. - @ObservationIgnored var lastSetRegionScope: RegionScopeState = .unknown - /// Per-conversation assembly module owning the bake state, write /// capability, and populate/bake ordering. Bound by `configure(...)` once /// the conversation identity is known. Always present; inert (no @@ -328,7 +317,6 @@ final class ChatViewModel { var connectionState: @MainActor () -> DeviceConnectionState var connectedDevice: @MainActor () -> DeviceDTO? var currentRadioID: @MainActor () -> UUID? - var session: @MainActor () -> MeshCoreSession? var reactionService: @MainActor () -> ReactionService? var chatSendQueueService: @MainActor () -> ChatSendQueueService? var inlineImageDimensionsStore: @MainActor () -> InlineImageDimensionsStore? @@ -373,7 +361,6 @@ final class ChatViewModel { @ObservationIgnored var connectionStateProvider: @MainActor () -> DeviceConnectionState = { .disconnected } @ObservationIgnored var connectedDeviceProvider: @MainActor () -> DeviceDTO? = { nil } @ObservationIgnored var currentRadioIDProvider: @MainActor () -> UUID? = { nil } - @ObservationIgnored var sessionProvider: @MainActor () -> MeshCoreSession? = { nil } @ObservationIgnored var reactionServiceProvider: @MainActor () -> ReactionService? = { nil } @ObservationIgnored var chatSendQueueServiceProvider: @MainActor () -> ChatSendQueueService? = { nil } @@ -458,13 +445,11 @@ final class ChatViewModel { connectionStateProvider = dependencies.connectionState connectedDeviceProvider = dependencies.connectedDevice currentRadioIDProvider = dependencies.currentRadioID - sessionProvider = dependencies.session reactionServiceProvider = dependencies.reactionService chatSendQueueServiceProvider = dependencies.chatSendQueueService bake.bindInlineImageDimensionsStore(dependencies.inlineImageDimensionsStore) prefetchDataStoreProvider = dependencies.prefetchDataStore self.onNavigateToMap = onNavigateToMap - lastSetRegionScope = .unknown if let linkPreviewCache { self.linkPreviewCache = linkPreviewCache configurePrefetcher( diff --git a/MC1/Views/Components/BLEStatusIndicatorView.swift b/MC1/Views/Components/BLEStatusIndicatorView.swift index e4aff28020..d95015f0e7 100644 --- a/MC1/Views/Components/BLEStatusIndicatorView.swift +++ b/MC1/Views/Components/BLEStatusIndicatorView.swift @@ -9,6 +9,7 @@ private let logger = Logger(subsystem: "com.mc1", category: "BLEStatus") /// Shows connection state via color-coded icon with menu details struct BLEStatusIndicatorView: View { @Environment(\.appState) private var appState + @Environment(\.accessibilityReduceMotion) private var reduceMotion @State private var showingDeviceSelection = false @State private var isSendingAdvert = false @State private var successFeedbackTrigger = false @@ -21,12 +22,12 @@ struct BLEStatusIndicatorView: View { /// rebuilds the hosted toolbar item mid-update and trips a graph re-entrancy crash /// on iOS 26. Varying only the label and menu content by value updates it in place. var body: some View { - ToolbarMenu { + ToolbarMenu(accessibilityLabel: accessibilityLabel) { menuContent } label: { // Overflow uses the title; iconOnly keeps the bar glyph-only. Label { - Text(L10n.Settings.BleStatus.accessibilityLabel) + Text(accessibilityLabel) } icon: { StatusIcon(iconName: iconName, iconColor: iconColor, isAnimating: isAnimating) } @@ -34,12 +35,9 @@ struct BLEStatusIndicatorView: View { .tint(iconColor) } .popoverTip(deviceMenuTip) - .dynamicTypeSize(...DynamicTypeSize.xLarge) .sensoryFeedback(.success, trigger: successFeedbackTrigger) .sensoryFeedback(.error, trigger: errorFeedbackTrigger) - .accessibilityLabel(L10n.Settings.BleStatus.accessibilityLabel) - .accessibilityValue(statusTitle) - .accessibilityHint(accessibilityHint) + .accessibilityHint(L10n.Settings.BleStatus.AccessibilityHint.connected) .onChange(of: appState.connectedDevice != nil, initial: true) { _, isConnected in DeviceMenuTip.isConnected = isConnected } @@ -56,14 +54,14 @@ struct BLEStatusIndicatorView: View { @ViewBuilder private var menuContent: some View { - if let device = appState.connectedDevice { - Section { - if device.clientRepeat { - Label(L10n.Settings.BleStatus.repeatModeActive, systemImage: "repeat") - .foregroundStyle(AppColors.Radio.repeatMode) - } - VStack(alignment: .leading) { - Label(device.nodeName, systemImage: "antenna.radiowaves.left.and.right") + if let activity = appState.connectionManager.connectionActivity { + let isConnected = appState.connectionState.isConnected + Section(activity.accessibilityValue) { + if let device = appState.connectedDevice { + if device.clientRepeat { + Label(L10n.Settings.BleStatus.repeatModeActive, systemImage: "repeat") + .foregroundStyle(AppColors.Radio.repeatMode) + } if let battery = appState.batteryMonitor.deviceBattery { let ocvArray = appState.batteryMonitor.activeBatteryOCVArray(for: appState.connectedDevice) Label( @@ -72,51 +70,54 @@ struct BLEStatusIndicatorView: View { ) .font(.caption) .foregroundStyle(.secondary) + .tint(.secondary) } } - .foregroundStyle(.secondary) - .tint(.secondary) - Button { - showingDeviceSelection = true - } label: { - Label(L10n.Settings.BleStatus.changeDevice, systemImage: "flipphone") + if isConnected { + changeDeviceButton } - Button(role: .destructive) { + Button(role: isConnected ? .destructive : nil) { logger.info("Disconnect tapped in BLE status menu") Task { - await appState.disconnect(reason: .statusMenuDisconnectTap) + await appState.disconnect(requestID: activity.requestID, reason: .statusMenuDisconnectTap) } } label: { - Label(L10n.Settings.BleStatus.disconnect, systemImage: "eject") + Label(activity.stopTitle, systemImage: "eject") } - .tint(Color(.systemRed)) - } + .tint(isConnected ? Color(.systemRed) : nil) - Section { - Button { - sendAdvert(flood: false) - } label: { - Label(L10n.Settings.BleStatus.sendZeroHopAdvert, systemImage: "dot.radiowaves.right") + if !isConnected { + changeDeviceButton } - .radioDisabled(for: appState.connectionState, or: isSendingAdvert) - .accessibilityHint(L10n.Settings.BleStatus.SendZeroHopAdvert.hint) + } - Button { - sendAdvert(flood: true) - } label: { - Label(L10n.Settings.BleStatus.sendFloodAdvert, systemImage: "dot.radiowaves.left.and.right") + if appState.connectedDevice != nil { + Section { + Button { + sendAdvert(flood: false) + } label: { + Label(L10n.Settings.BleStatus.sendZeroHopAdvert, systemImage: "dot.radiowaves.right") + } + .radioDisabled(for: appState.connectionState, or: isSendingAdvert) + .accessibilityHint(L10n.Settings.BleStatus.SendZeroHopAdvert.hint) + + Button { + sendAdvert(flood: true) + } label: { + Label(L10n.Settings.BleStatus.sendFloodAdvert, systemImage: "dot.radiowaves.left.and.right") + } + .radioDisabled(for: appState.connectionState, or: isSendingAdvert) + .accessibilityHint(L10n.Settings.BleStatus.SendFloodAdvert.hint) } - .radioDisabled(for: appState.connectionState, or: isSendingAdvert) - .accessibilityHint(L10n.Settings.BleStatus.SendFloodAdvert.hint) - } - Section { - Button { - appState.navigation.navigateToSetting(.advanced) - } label: { - Label(L10n.Settings.AdvancedSettings.title, systemImage: "gearshape") + Section { + Button { + appState.navigation.navigateToSetting(.advanced) + } label: { + Label(L10n.Settings.AdvancedSettings.title, systemImage: "gearshape") + } } } } else { @@ -128,10 +129,17 @@ struct BLEStatusIndicatorView: View { } } - private var accessibilityHint: String { - appState.connectedDevice != nil - ? L10n.Settings.BleStatus.AccessibilityHint.connected - : L10n.Settings.BleStatus.AccessibilityHint.disconnected + private var changeDeviceButton: some View { + Button { + showingDeviceSelection = true + } label: { + Label(L10n.Settings.BleStatus.changeDevice, systemImage: "flipphone") + } + } + + private var accessibilityLabel: String { + let value = appState.connectionManager.connectionActivity?.accessibilityValue ?? statusTitle + return L10n.Settings.BleStatus.accessibilityValue(L10n.Settings.BleStatus.accessibilityLabel, value) } // MARK: - Computed Properties @@ -160,11 +168,12 @@ struct BLEStatusIndicatorView: View { } private var isAnimating: Bool { - appState.connectionState == .connecting + appState.connectionState == .connecting && !reduceMotion } private var statusTitle: String { - switch appState.connectionState { + if let activity = appState.connectionManager.connectionActivity { return activity.statusTitle } + return switch appState.connectionState { case .disconnected: L10n.Settings.BleStatus.Status.disconnected case .connecting: diff --git a/MC1/Views/Components/GlassFilterBar.swift b/MC1/Views/Components/GlassFilterBar.swift index 3b68a0fd69..993c4a8e6e 100644 --- a/MC1/Views/Components/GlassFilterBar.swift +++ b/MC1/Views/Components/GlassFilterBar.swift @@ -66,6 +66,7 @@ struct GlassFilterBar: View let pickerLabel: String let title: @Sendable (Filter) -> String var size: Size = .regular + var filters: [Filter]? @Namespace private var glassNamespace @Environment(\.accessibilityReduceMotion) private var reduceMotion @@ -108,7 +109,7 @@ struct GlassFilterBar: View private var pillsRow: some View { GlassEffectContainer(spacing: pillSpacing) { HStack(spacing: pillSpacing) { - ForEach(Filter.allCases, id: \.self) { filter in + ForEach(filters ?? Array(Filter.allCases), id: \.self) { filter in pill(for: filter) } } @@ -154,7 +155,7 @@ struct GlassFilterBar: View private var segmentedFallback: some View { Picker(pickerLabel, selection: $selection) { - ForEach(Filter.allCases, id: \.self) { filter in + ForEach(filters ?? Array(Filter.allCases), id: \.self) { filter in Text(title(filter)).tag(filter) } } diff --git a/MC1/Views/Components/MapControlsToolbar.swift b/MC1/Views/Components/MapControlsToolbar.swift index a7c758ed13..425499b88e 100644 --- a/MC1/Views/Components/MapControlsToolbar.swift +++ b/MC1/Views/Components/MapControlsToolbar.swift @@ -97,7 +97,7 @@ struct MapControlsToolbar: View { Toggle(isOn: toggleBinding(state, \.showChat) { $0.setShowChat($1, host: host) }) { - Text(L10n.Contacts.Contacts.Segment.contacts) + Text(L10n.Map.Map.Controls.contactsAndSensors) } .disabled(state.wrappedValue.favoritesOnly) Toggle(isOn: toggleBinding(state, \.showRepeater) { diff --git a/MC1/Views/Components/NodeAvatar.swift b/MC1/Views/Components/NodeAvatar.swift index c617ebf406..4da88d943d 100644 --- a/MC1/Views/Components/NodeAvatar.swift +++ b/MC1/Views/Components/NodeAvatar.swift @@ -1,8 +1,7 @@ import MC1Services import SwiftUI -/// Avatar view for remote nodes (room servers and repeaters). All repeaters share one theme color, -/// all room servers share another — distinct per category, fixed per theme. +/// Remote node avatar. Repeaters and room servers use category colors; sensors use neutral gray. struct NodeAvatar: View { @Environment(\.appTheme) private var theme @Environment(\.colorScheme) private var colorScheme @@ -25,6 +24,8 @@ struct NodeAvatar: View { private var iconName: String { switch role { + case .sensor: + "sensor" case .roomServer: "door.left.hand.closed" case .repeater: @@ -37,7 +38,7 @@ struct NodeAvatar: View { } private var fill: Color { - theme.categoryAvatarColor(category, colorScheme: colorScheme, contrast: colorSchemeContrast) + role == .sensor ? Color.gray : theme.categoryAvatarColor(category, colorScheme: colorScheme, contrast: colorSchemeContrast) } private var glyph: Color { diff --git a/MC1/Views/Components/PairingRecoveryStatus.swift b/MC1/Views/Components/PairingRecoveryStatus.swift new file mode 100644 index 0000000000..f322e853eb --- /dev/null +++ b/MC1/Views/Components/PairingRecoveryStatus.swift @@ -0,0 +1,12 @@ +import SwiftUI + +struct PairingRecoveryStatus: View { + var body: some View { + HStack { + ProgressView().controlSize(.small) + Text(L10n.Settings.DeviceSelection.rePairing) + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(L10n.Settings.DeviceSelection.rePairing) + } +} diff --git a/MC1/Views/Components/SyncingPillView.swift b/MC1/Views/Components/SyncingPillView.swift index d1c7cc94b0..6457cfe3b2 100644 --- a/MC1/Views/Components/SyncingPillView.swift +++ b/MC1/Views/Components/SyncingPillView.swift @@ -2,6 +2,8 @@ import SwiftUI /// A pill-shaped indicator that appears at the top of the app during sync and connection operations struct SyncingPillView: View { + @Environment(\.accessibilityReduceMotion) private var reduceMotion + let state: StatusPillState var onDisconnectedTap: (() -> Void)? @@ -45,15 +47,15 @@ struct SyncingPillView: View { case .failed: Image(systemName: "exclamationmark.triangle.fill") .foregroundStyle(.red) - case .disconnected: + case .disconnected, .waitingToReconnect: Image(systemName: "exclamationmark.triangle") .foregroundStyle(.orange) case .ready: Image(systemName: "checkmark.circle") .foregroundStyle(.green) - case .connecting, .syncing, .syncingMessages: + case .connecting, .reconnecting, .syncing, .syncingMessages: Image(systemName: "arrow.trianglehead.2.clockwise") - .symbolEffect(.rotate, isActive: true) + .symbolEffect(.rotate, isActive: !reduceMotion) case .hidden: EmptyView() } diff --git a/MC1/Views/Contacts/ContactActionsSection.swift b/MC1/Views/Contacts/ContactActionsSection.swift index 66199cbeb4..176fb769a0 100644 --- a/MC1/Views/Contacts/ContactActionsSection.swift +++ b/MC1/Views/Contacts/ContactActionsSection.swift @@ -48,7 +48,7 @@ struct ContactActionsSection: View { onRowPosition: nil ) - case .repeater: + case .repeater, .sensor: NodeActionRows( contact: currentContact, pingLabel: L10n.Contacts.Contacts.Detail.ping, diff --git a/MC1/Views/Contacts/ContactAddConfirmationContent.swift b/MC1/Views/Contacts/ContactAddConfirmationContent.swift index bff150df22..1c9d2e8be3 100644 --- a/MC1/Views/Contacts/ContactAddConfirmationContent.swift +++ b/MC1/Views/Contacts/ContactAddConfirmationContent.swift @@ -92,6 +92,12 @@ struct ContactAddConfirmationContent: View { role: .repeater, size: Constants.identityGlyphSize ) + case .sensor: + NodeAvatar( + publicKey: contactResult.publicKey, + role: .sensor, + size: Constants.identityGlyphSize + ) case .room: NodeAvatar( publicKey: contactResult.publicKey, diff --git a/MC1/Views/Contacts/ContactDetailAvatarView.swift b/MC1/Views/Contacts/ContactDetailAvatarView.swift index 7cd58009d7..65194075f3 100644 --- a/MC1/Views/Contacts/ContactDetailAvatarView.swift +++ b/MC1/Views/Contacts/ContactDetailAvatarView.swift @@ -2,9 +2,13 @@ import MC1Services import SwiftUI struct ContactDetailAvatarView: View { + private static let avatarSize: CGFloat = 150 let contact: ContactDTO let isSavingAvatar: Bool @Binding var showSourceMenu: Bool + let onChoosePhoto: () -> Void + let onChooseFile: () -> Void + let onRemovePhoto: () -> Void var body: some View { if contact.type == .chat { @@ -12,11 +16,11 @@ struct ContactDetailAvatarView: View { showSourceMenu = true } label: { ZStack { - ContactAvatar(contact: contact, size: 150) + ContactAvatar(contact: contact, size: Self.avatarSize) if isSavingAvatar { Circle() .fill(.black.opacity(0.4)) - .frame(width: 150, height: 150) + .frame(width: Self.avatarSize, height: Self.avatarSize) ProgressView() .tint(.white) } @@ -26,12 +30,26 @@ struct ContactDetailAvatarView: View { .buttonStyle(.plain) .disabled(isSavingAvatar) .accessibilityLabel(accessibilityLabel) + .confirmationDialog( + L10n.Contacts.Contacts.Detail.Avatar.chooseSource, + isPresented: $showSourceMenu, + titleVisibility: .visible + ) { + Button(L10n.Contacts.Contacts.Detail.Avatar.choosePhoto, action: onChoosePhoto) + Button(L10n.Contacts.Contacts.Detail.Avatar.chooseFile, action: onChooseFile) + if contact.avatarImageData != nil { + Button(L10n.Contacts.Contacts.Detail.Avatar.removePhoto, role: .destructive, action: onRemovePhoto) + } + Button(L10n.Contacts.Contacts.Common.cancel, role: .cancel) {} + } } else { switch contact.type { case .repeater: - NodeAvatar(publicKey: contact.publicKey, role: .repeater, size: 150) + NodeAvatar(publicKey: contact.publicKey, role: .repeater, size: Self.avatarSize) case .room: - NodeAvatar(publicKey: contact.publicKey, role: .roomServer, size: 150) + NodeAvatar(publicKey: contact.publicKey, role: .roomServer, size: Self.avatarSize) + case .sensor: + NodeAvatar(publicKey: contact.publicKey, role: .sensor, size: Self.avatarSize) case .chat: EmptyView() } @@ -56,6 +74,6 @@ struct ContactDetailAvatarView: View { .foregroundStyle(.white, .gray) } } - .frame(width: 150, height: 150) + .frame(width: Self.avatarSize, height: Self.avatarSize) } } diff --git a/MC1/Views/Contacts/ContactDetailContent.swift b/MC1/Views/Contacts/ContactDetailContent.swift index c794b517ee..40dacaffce 100644 --- a/MC1/Views/Contacts/ContactDetailContent.swift +++ b/MC1/Views/Contacts/ContactDetailContent.swift @@ -30,7 +30,10 @@ struct ContactDetailContent: View { contactTypeLabel: state.contactTypeLabel, measuredHeight: $headerHeight, isSavingAvatar: state.isSavingAvatar, - showAvatarSourceMenu: $state.showAvatarSourceMenu, + showAvatarSourceMenu: avatarSourceMenuPresented, + onChoosePhoto: { state.showAvatarPhotosPicker = true }, + onChooseFile: { state.showAvatarFileImporter = true }, + onRemovePhoto: { state.removeAvatarPhoto() }, onRowPosition: recordRowPosition ) @@ -137,6 +140,16 @@ struct ContactDetailContent: View { state.rendererRevision == rendererRevision && state.rendererID == rendererID && state.hasPresentationOwnership } + private var avatarSourceMenuPresented: Binding { + Binding( + get: { isCurrentRenderer && state.showAvatarSourceMenu }, + set: { value in + guard isCurrentRenderer else { return } + state.showAvatarSourceMenu = value + } + ) + } + private func restoredSection(_ saved: ContactDetailState.ScrollSection) -> ContactDetailState.ScrollSection { if saved == .location, !state.currentContact.hasLocation { return .outPath } if saved == .danger, state.isVContact, state.currentContact.type != .chat { return .technical } @@ -159,8 +172,7 @@ struct ContactDetailContent: View { } private func updateVisibleSection() { - guard isCurrentRenderer else { return } - guard let section = visibleSection else { return } + guard isCurrentRenderer, let section = visibleSection else { return } if !restoredScroll { guard section == restorationTarget else { return } restoredScroll = true diff --git a/MC1/Views/Contacts/ContactDetailPresenter+Sheets.swift b/MC1/Views/Contacts/ContactDetailPresenter+Sheets.swift index 71340f0233..b25ebdd8b9 100644 --- a/MC1/Views/Contacts/ContactDetailPresenter+Sheets.swift +++ b/MC1/Views/Contacts/ContactDetailPresenter+Sheets.swift @@ -24,10 +24,15 @@ extension ContactDetailPresenter { NodeAuthenticationSheet( contact: state.currentContact, role: role, + requireAdmin: false, customTitle: L10n.Contacts.Contacts.Detail.telemetryAccess ) { session in guard state.accepts(context) else { return } - state.pendingSheet = state.currentContact.type == .room ? .roomStatus(session) : .repeaterStatus(session) + switch session.role { + case .roomServer: state.pendingSheet = .roomStatus(session) + case .repeater: state.pendingSheet = .repeaterStatus(session) + case .sensor: state.pendingSheet = .nodeTelemetry(state.currentContact) + } state.pendingSheetContext = context state.activeSheet = nil } @@ -37,16 +42,7 @@ extension ContactDetailPresenter { if let role = RemoteNodeRole(contactType: state.currentContact.type) { let context = state.operationContext NodeAuthenticationSheet(contact: state.currentContact, role: role) { session in - guard state.accepts(context) else { return } - if session.isAdmin { - state.pendingSheet = .adminSettings(session) - } else if session.isRoom { - state.pendingSheet = .roomStatus(session) - } else { - state.pendingSheet = .repeaterStatus(session) - } - state.pendingSheetContext = context - state.activeSheet = nil + state.queueAdminSheet(for: session, context: context) } .presentationSizing(.page) } @@ -72,10 +68,10 @@ extension ContactDetailPresenter { case let .adminSettings(session): NavigationStack { Group { - if session.isRoom { - RoomSettingsView(session: session) - } else { - RepeaterSettingsView(session: session) + switch session.role { + case .roomServer: RoomSettingsView(session: session) + case .repeater: RepeaterSettingsView(session: session) + case .sensor: SensorSettingsView(session: session) } } .toolbar { diff --git a/MC1/Views/Contacts/ContactDetailPresenter.swift b/MC1/Views/Contacts/ContactDetailPresenter.swift index 79588cfc71..bce0b3dfb2 100644 --- a/MC1/Views/Contacts/ContactDetailPresenter.swift +++ b/MC1/Views/Contacts/ContactDetailPresenter.swift @@ -33,18 +33,6 @@ struct ContactDetailPresenter: ViewModifier { } message: { Text(L10n.Contacts.Contacts.Detail.Alert.ClearMessages.message(state?.currentContact.displayName ?? "")) } - .confirmationDialog( - L10n.Contacts.Contacts.Detail.Avatar.chooseSource, - isPresented: binding(\.showAvatarSourceMenu, fallback: false), - titleVisibility: .visible - ) { - Button(L10n.Contacts.Contacts.Detail.Avatar.choosePhoto) { state?.showAvatarPhotosPicker = true } - Button(L10n.Contacts.Contacts.Detail.Avatar.chooseFile) { state?.showAvatarFileImporter = true } - if state?.currentContact.avatarImageData != nil { - Button(L10n.Contacts.Contacts.Detail.Avatar.removePhoto, role: .destructive) { state?.removeAvatarPhoto() } - } - Button(L10n.Contacts.Contacts.Common.cancel, role: .cancel) {} - } .photosPicker( isPresented: binding(\.showAvatarPhotosPicker, fallback: false), selection: binding(\.avatarPickerItem, fallback: nil), diff --git a/MC1/Views/Contacts/ContactDetailState+Actions.swift b/MC1/Views/Contacts/ContactDetailState+Actions.swift index 49f055ea94..77e85f9146 100644 --- a/MC1/Views/Contacts/ContactDetailState+Actions.swift +++ b/MC1/Views/Contacts/ContactDetailState+Actions.swift @@ -7,9 +7,29 @@ extension ContactDetailState { func presentPendingSheet() { defer { pendingSheet = nil; pendingSheetContext = nil } guard let context = pendingSheetContext, accepts(context), let next = pendingSheet else { return } + if case let .adminSettings(session) = next, !matchesCurrentContact(session) { return } activeSheet = next } + func queueAdminSheet(for session: RemoteNodeSessionDTO, context: OperationContext) { + guard accepts(context), matchesCurrentContact(session) else { return } + guard !session.isSensor || (session.isConnected && session.isAdmin) else { return } + if session.isAdmin { + pendingSheet = .adminSettings(session) + } else if session.isRoom { + pendingSheet = .roomStatus(session) + } else { + pendingSheet = .repeaterStatus(session) + } + pendingSheetContext = context + activeSheet = nil + } + + private func matchesCurrentContact(_ session: RemoteNodeSessionDTO) -> Bool { + session.publicKey == currentContact.publicKey && session.radioID == currentContact.radioID + && session.role == RemoteNodeRole(contactType: currentContact.type) + } + func showTelemetry() { guard hasPresentationOwnership else { return } activeSheet = currentContact.type == .chat ? .nodeTelemetry(currentContact) : .nodeAuth diff --git a/MC1/Views/Contacts/ContactProfileSection.swift b/MC1/Views/Contacts/ContactProfileSection.swift index 700ef517bf..51bb421013 100644 --- a/MC1/Views/Contacts/ContactProfileSection.swift +++ b/MC1/Views/Contacts/ContactProfileSection.swift @@ -7,6 +7,9 @@ struct ContactProfileSection: View { @Binding var measuredHeight: CGFloat let isSavingAvatar: Bool @Binding var showAvatarSourceMenu: Bool + let onChoosePhoto: () -> Void + let onChooseFile: () -> Void + let onRemovePhoto: () -> Void let onRowPosition: (ContactDetailRowPosition.Measurement) -> Void var body: some View { @@ -15,7 +18,10 @@ struct ContactProfileSection: View { ContactDetailAvatarView( contact: currentContact, isSavingAvatar: isSavingAvatar, - showSourceMenu: $showAvatarSourceMenu + showSourceMenu: $showAvatarSourceMenu, + onChoosePhoto: onChoosePhoto, + onChooseFile: onChooseFile, + onRemovePhoto: onRemovePhoto ) VStack(spacing: 4) { diff --git a/MC1/Views/Contacts/ContactRowView.swift b/MC1/Views/Contacts/ContactRowView.swift index a77f5e7d2e..bc6b1f4c95 100644 --- a/MC1/Views/Contacts/ContactRowView.swift +++ b/MC1/Views/Contacts/ContactRowView.swift @@ -3,6 +3,7 @@ import MC1Services import SwiftUI struct ContactRowView: View { + private static let avatarSize: CGFloat = 44 @Environment(\.appState) private var appState let contact: ContactDTO let timestamp: UInt32? @@ -105,11 +106,13 @@ struct ContactRowView: View { private var avatarView: some View { switch contact.type { case .chat: - ContactAvatar(contact: contact, size: 44) + ContactAvatar(contact: contact, size: Self.avatarSize) case .repeater: - NodeAvatar(publicKey: contact.publicKey, role: .repeater, size: 44) + NodeAvatar(publicKey: contact.publicKey, role: .repeater, size: Self.avatarSize) case .room: - NodeAvatar(publicKey: contact.publicKey, role: .roomServer, size: 44) + NodeAvatar(publicKey: contact.publicKey, role: .roomServer, size: Self.avatarSize) + case .sensor: + NodeAvatar(publicKey: contact.publicKey, role: .sensor, size: Self.avatarSize) } } diff --git a/MC1/Views/Contacts/ContactsEmptyView.swift b/MC1/Views/Contacts/ContactsEmptyView.swift index 7ae607b409..13ce146ee1 100644 --- a/MC1/Views/Contacts/ContactsEmptyView.swift +++ b/MC1/Views/Contacts/ContactsEmptyView.swift @@ -23,6 +23,12 @@ struct ContactsEmptyView: View { systemImage: "antenna.radiowaves.left.and.right", description: Text(L10n.Contacts.Contacts.List.Empty.Repeaters.description) ) + case .sensors: + ContentUnavailableView( + L10n.Contacts.Contacts.List.Empty.Sensors.title, + systemImage: "sensor", + description: Text(L10n.Contacts.Contacts.List.Empty.Sensors.description) + ) case .rooms: ContentUnavailableView( L10n.Contacts.Contacts.List.Empty.Rooms.title, diff --git a/MC1/Views/Contacts/ContactsViewModel.swift b/MC1/Views/Contacts/ContactsViewModel.swift index 59d7735998..1c85766ef1 100644 --- a/MC1/Views/Contacts/ContactsViewModel.swift +++ b/MC1/Views/Contacts/ContactsViewModel.swift @@ -8,6 +8,7 @@ enum NodeSegment: String, CaseIterable { case contacts case repeaters case rooms + case sensors var localizedTitle: String { switch self { @@ -15,6 +16,7 @@ enum NodeSegment: String, CaseIterable { case .contacts: L10n.Contacts.Contacts.Segment.contacts case .repeaters: L10n.Contacts.Contacts.Segment.repeaters case .rooms: L10n.Contacts.Contacts.Segment.rooms + case .sensors: L10n.Contacts.Contacts.Segment.sensors } } } @@ -416,6 +418,8 @@ final class ContactsViewModel { result = result.filter { $0.type == .repeater } case .rooms: result = result.filter { $0.type == .room } + case .sensors: + result = result.filter { $0.type == .sensor } } } else { // Filter by search text only diff --git a/MC1/Views/Contacts/DiscoveryPresenter.swift b/MC1/Views/Contacts/DiscoveryPresenter.swift index 41e3f6606d..2800bcfdbf 100644 --- a/MC1/Views/Contacts/DiscoveryPresenter.swift +++ b/MC1/Views/Contacts/DiscoveryPresenter.swift @@ -46,19 +46,5 @@ struct DiscoveryPresenter: ViewModifier { get: { state?.viewModel.errorMessage }, set: { state?.viewModel.errorMessage = $0 } ), title: L10n.Contacts.Contacts.Common.error) - .confirmationDialog( - L10n.Contacts.Contacts.Discovery.Clear.title, - isPresented: Binding( - get: { state?.showClearConfirmation ?? false }, - set: { state?.showClearConfirmation = $0 } - ), - titleVisibility: .visible - ) { - Button(L10n.Contacts.Contacts.Discovery.Clear.confirm, role: .destructive) { - state?.clearAll() - } - } message: { - Text(L10n.Contacts.Contacts.Discovery.Clear.message) - } } } diff --git a/MC1/Views/Contacts/DiscoveryView.swift b/MC1/Views/Contacts/DiscoveryView.swift index a900e80a09..e3bd2c5705 100644 --- a/MC1/Views/Contacts/DiscoveryView.swift +++ b/MC1/Views/Contacts/DiscoveryView.swift @@ -62,7 +62,8 @@ struct DiscoveryView: View { ToolbarItem(placement: .automatic) { DiscoveryMoreMenu( isEmpty: viewModel.discoveredNodes.isEmpty, - showClearConfirmation: $state.showClearConfirmation + showClearConfirmation: clearConfirmationPresented, + onClear: { state.clearAll() } ) } } @@ -87,6 +88,16 @@ struct DiscoveryView: View { } } + private var clearConfirmationPresented: Binding { + Binding( + get: { state.rendererRevision == rendererRevision && state.showClearConfirmation }, + set: { value in + guard state.rendererRevision == rendererRevision else { return } + state.showClearConfirmation = value + } + ) + } + private var filterHeader: some View { @Bindable var state = state return DiscoverSegmentPicker(selection: $state.selectedSegment, isSearching: isSearching) @@ -194,6 +205,7 @@ private enum DiscoveryListLayout { // MARK: - Node Row private struct DiscoveryNodeRow: View { + private static let avatarSize: CGFloat = 44 @Environment(\.appState) private var appState let node: DiscoveredNodeDTO let isAdded: Bool @@ -289,11 +301,13 @@ private struct DiscoveryNodeRow: View { private var avatarView: some View { switch node.nodeType { case .chat: - ContactAvatar(name: node.name, size: 44) + ContactAvatar(name: node.name, size: Self.avatarSize) case .repeater: - NodeAvatar(publicKey: node.publicKey, role: .repeater, size: 44) + NodeAvatar(publicKey: node.publicKey, role: .repeater, size: Self.avatarSize) case .room: - NodeAvatar(publicKey: node.publicKey, role: .roomServer, size: 44) + NodeAvatar(publicKey: node.publicKey, role: .roomServer, size: Self.avatarSize) + case .sensor: + NodeAvatar(publicKey: node.publicKey, role: .sensor, size: Self.avatarSize) } } @@ -302,6 +316,7 @@ private struct DiscoveryNodeRow: View { case .chat: L10n.Contacts.Contacts.NodeKind.chat case .repeater: L10n.Contacts.Contacts.NodeKind.repeater case .room: L10n.Contacts.Contacts.NodeKind.room + case .sensor: L10n.Contacts.Contacts.NodeKind.sensor } } @@ -365,6 +380,7 @@ private struct DiscoverySortMenu: View { private struct DiscoveryMoreMenu: View { let isEmpty: Bool @Binding var showClearConfirmation: Bool + let onClear: () -> Void var body: some View { Menu { @@ -378,6 +394,15 @@ private struct DiscoveryMoreMenu: View { Label(L10n.Contacts.Contacts.Discovery.menu, systemImage: "ellipsis.circle") } .liquidGlassSecondaryButtonStyle() + .confirmationDialog( + L10n.Contacts.Contacts.Discovery.Clear.title, + isPresented: $showClearConfirmation, + titleVisibility: .visible + ) { + Button(L10n.Contacts.Contacts.Discovery.Clear.confirm, role: .destructive, action: onClear) + } message: { + Text(L10n.Contacts.Contacts.Discovery.Clear.message) + } } } diff --git a/MC1/Views/Contacts/DiscoveryViewModel.swift b/MC1/Views/Contacts/DiscoveryViewModel.swift index e928b3a21e..387591088a 100644 --- a/MC1/Views/Contacts/DiscoveryViewModel.swift +++ b/MC1/Views/Contacts/DiscoveryViewModel.swift @@ -8,6 +8,7 @@ enum DiscoverSegment: String, CaseIterable { case contacts case repeaters case rooms + case sensors var localizedTitle: String { switch self { @@ -15,6 +16,7 @@ enum DiscoverSegment: String, CaseIterable { case .contacts: L10n.Contacts.Contacts.Discovery.Segment.contacts case .repeaters: L10n.Contacts.Contacts.Discovery.Segment.repeaters case .rooms: L10n.Contacts.Contacts.Discovery.Segment.rooms + case .sensors: L10n.Contacts.Contacts.Discovery.Segment.sensors } } } @@ -247,6 +249,8 @@ final class DiscoveryViewModel { result = result.filter { $0.nodeType == .repeater } case .rooms: result = result.filter { $0.nodeType == .room } + case .sensors: + result = result.filter { $0.nodeType == .sensor } } } else { let query = searchText.lowercased() diff --git a/MC1/Views/Contacts/NodeActionRows.swift b/MC1/Views/Contacts/NodeActionRows.swift index dbb42eac2b..dc407782f8 100644 --- a/MC1/Views/Contacts/NodeActionRows.swift +++ b/MC1/Views/Contacts/NodeActionRows.swift @@ -21,7 +21,7 @@ struct NodeActionRows: View { .modifier(ContactDetailRowPosition(section: .actions, onPosition: onRowPosition)) ContactSavedHistoryLink( - route: ContactRoute.TelemetryHistory(publicKey: contact.publicKey, radioID: contact.radioID), + route: ContactRoute.TelemetryHistory(publicKey: contact.publicKey, radioID: contact.radioID, showNeighbors: contact.type != .sensor), nodesRoute: historyRoute ) @@ -30,20 +30,22 @@ struct NodeActionRows: View { } .radioDisabled(for: connectionState) - Button(action: onPing) { - HStack { - Label(pingLabel, systemImage: "wave.3.right") - if isPinging { - Spacer() - ProgressView() + if contact.type != .sensor { + Button(action: onPing) { + HStack { + Label(pingLabel, systemImage: "wave.3.right") + if isPinging { + Spacer() + ProgressView() + } } } - } - .disabled(isPinging) - .radioDisabled(for: connectionState) + .disabled(isPinging) + .radioDisabled(for: connectionState) - if let result = pingResult { - PingResultRow(result: result) + if let result = pingResult { + PingResultRow(result: result) + } } } } diff --git a/MC1/Views/MainTabView.swift b/MC1/Views/MainTabView.swift index f656c25859..f7f3ed9d8a 100644 --- a/MC1/Views/MainTabView.swift +++ b/MC1/Views/MainTabView.swift @@ -1,3 +1,4 @@ +import MC1Services import SwiftUI /// Keeps tab state alive while Nodes replaces navigation containers during resizing. @@ -43,11 +44,10 @@ struct MainTabView: View { .onChange(of: appState.connectedDevice) { _, newDevice in // Status-menu disconnect does not fire onConnectionLost; radio-to-radio // switches use clearPerRadioSelection instead. - if newDevice == nil { - appState.navigation.clearPerDeviceSelection( - preservingConnection: appState.connectionLinkSwitch?.target != nil - ) - } + clearDeviceSettingsIfImportEnded(device: newDevice) + } + .onChange(of: appState.connectionManager.identityRebuildUnpublished) { _, _ in + clearDeviceSettingsIfImportEnded(device: appState.connectedDevice) } .sheet(isPresented: $showingDeviceSelection, onDismiss: { appState.handleDeviceSelectionSheetDismissed() @@ -57,4 +57,12 @@ struct MainTabView: View { .presentationDragIndicator(.visible) } } + + /// `identityRebuildUnpublished` is not a disconnect, so a nil device keeps the open route. + private func clearDeviceSettingsIfImportEnded(device: DeviceDTO?) { + guard device == nil, !appState.connectionManager.identityRebuildUnpublished else { return } + appState.navigation.clearPerDeviceSelection( + preservingConnection: appState.connectionLinkSwitch?.target != nil + ) + } } diff --git a/MC1/Views/Map/ContactCalloutContent.swift b/MC1/Views/Map/ContactCalloutContent.swift index 3e50b0592d..40bf7cedd6 100644 --- a/MC1/Views/Map/ContactCalloutContent.swift +++ b/MC1/Views/Map/ContactCalloutContent.swift @@ -67,6 +67,8 @@ struct ContactCalloutContent: View { L10n.Map.Map.Callout.NodeKind.repeater case .room: L10n.Map.Map.Callout.NodeKind.room + case .sensor: + L10n.Map.Map.Callout.NodeKind.sensor } } } diff --git a/MC1/Views/Map/ContactDetailSheet.swift b/MC1/Views/Map/ContactDetailSheet.swift index 95b91fdd5d..179c95bdd7 100644 --- a/MC1/Views/Map/ContactDetailSheet.swift +++ b/MC1/Views/Map/ContactDetailSheet.swift @@ -38,6 +38,8 @@ struct ContactDetailSheet: View { @State private var activeSheet: ActiveSheet? @State private var pendingSheet: ActiveSheet? + @State private var pendingSheetContext: ContactDetailState.OperationContext? + @State private var hasPresentationOwnership = true @State private var isPinging = false @State private var pingResult: PingResult? @State private var showingDeleteAlert = false @@ -123,7 +125,7 @@ struct ContactDetailSheet: View { // Actions section Section { switch contact.type { - case .repeater: + case .repeater, .sensor: Button { activeSheet = .telemetryAuth } label: { @@ -138,7 +140,14 @@ struct ContactDetailSheet: View { } .radioDisabled(for: appState.connectionState) - pingButton + if contact.type == .sensor { + ContactSavedHistoryLink( + route: ContactRoute.TelemetryHistory(publicKey: contact.publicKey, radioID: contact.radioID, showNeighbors: false), + nodesRoute: nil + ) + } else { + pingButton + } case .room: Button { @@ -212,12 +221,16 @@ struct ContactDetailSheet: View { .sheet(item: $activeSheet, onDismiss: presentPendingSheet) { sheet in switch sheet { case .telemetryAuth: + let context = operationContext if let role = RemoteNodeRole(contactType: contact.type) { NodeAuthenticationSheet( contact: contact, role: role, + requireAdmin: false, customTitle: L10n.Map.Map.Detail.Action.telemetryAccessTitle ) { session in + guard accepts(context), session.isConnected else { return } + pendingSheetContext = context pendingSheet = .telemetryStatus(session) activeSheet = nil } @@ -225,11 +238,18 @@ struct ContactDetailSheet: View { } case let .telemetryStatus(session): - RepeaterStatusView(session: session) + if session.isSensor { + NodeTelemetryView(contact: contact) + } else { + RepeaterStatusView(session: session) + } case .adminAuth: + let context = operationContext if let role = RemoteNodeRole(contactType: contact.type) { NodeAuthenticationSheet(contact: contact, role: role) { session in + guard accepts(context), !session.isSensor || (session.isConnected && session.isAdmin) else { return } + pendingSheetContext = context pendingSheet = .adminSettings(session) activeSheet = nil } @@ -238,20 +258,28 @@ struct ContactDetailSheet: View { case let .adminSettings(session): NavigationStack { - RepeaterSettingsView(session: session) - .toolbar { - ToolbarItem(placement: .confirmationAction) { - Button(L10n.Map.Map.Common.done) { - activeSheet = nil - } + Group { + if session.isSensor { + SensorSettingsView(session: session) + } else { + RepeaterSettingsView(session: session) + } + } + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button(L10n.Map.Map.Common.done) { + activeSheet = nil } } + } } .presentationSizing(.page) case .roomJoin: + let context = operationContext if let role = RemoteNodeRole(contactType: contact.type) { NodeAuthenticationSheet(contact: contact, role: role) { session in + guard accepts(context) else { return } activeSheet = nil dismiss() appState.navigation.navigateToRoom(with: session) @@ -271,6 +299,13 @@ struct ContactDetailSheet: View { } message: { Text(L10n.Contacts.Contacts.Detail.Alert.Delete.message(contact.displayName)) } + .onAppear { hasPresentationOwnership = true } + .onDisappear { hasPresentationOwnership = false; pendingSheet = nil; pendingSheetContext = nil } + .onChange(of: appState.servicesVersion) { _, _ in + activeSheet = nil + pendingSheet = nil + pendingSheetContext = nil + } .errorAlert($errorMessage) } } @@ -350,11 +385,18 @@ struct ContactDetailSheet: View { // MARK: - Sheet Management + private var operationContext: ContactDetailState.OperationContext { + .init(servicesVersion: appState.servicesVersion, radioID: appState.connectedDevice?.radioID) + } + + private func accepts(_ context: ContactDetailState.OperationContext) -> Bool { + hasPresentationOwnership && !Task.isCancelled && operationContext == context + } + private func presentPendingSheet() { - if let next = pendingSheet { - pendingSheet = nil - activeSheet = next - } + defer { pendingSheet = nil; pendingSheetContext = nil } + guard let context = pendingSheetContext, accepts(context), let next = pendingSheet else { return } + activeSheet = next } // MARK: - Computed Properties @@ -367,6 +409,8 @@ struct ContactDetailSheet: View { L10n.Map.Map.NodeKind.repeater case .room: L10n.Map.Map.NodeKind.room + case .sensor: + L10n.Map.Map.NodeKind.sensor } } } diff --git a/MC1/Views/Map/DiscoveredNodeCalloutContent.swift b/MC1/Views/Map/DiscoveredNodeCalloutContent.swift index 6af0a8ec99..02d1c13987 100644 --- a/MC1/Views/Map/DiscoveredNodeCalloutContent.swift +++ b/MC1/Views/Map/DiscoveredNodeCalloutContent.swift @@ -65,6 +65,8 @@ struct DiscoveredNodeCalloutContent: View { L10n.Map.Map.Callout.NodeKind.repeater case .room: L10n.Map.Map.Callout.NodeKind.room + case .sensor: + L10n.Map.Map.Callout.NodeKind.sensor } } } diff --git a/MC1/Views/Map/MC1MapView+Layers.swift b/MC1/Views/Map/MC1MapView+Layers.swift index c8c1368a12..b22137e2fe 100644 --- a/MC1/Views/Map/MC1MapView+Layers.swift +++ b/MC1/Views/Map/MC1MapView+Layers.swift @@ -480,6 +480,7 @@ extension MC1MapView.Coordinator { case .contactChat: "pin-chat" case .contactRepeater: "pin-repeater" case .contactRoom: "pin-room" + case .contactSensor: "pin-sensor" case .repeater: "pin-repeater" case .repeaterRingBlue: "pin-repeater-ring-blue" case .repeaterRingGreen: "pin-repeater-ring-green" diff --git a/MC1/Views/Map/MapFilter.swift b/MC1/Views/Map/MapFilter.swift index c4bb972b14..0e718a8a1d 100644 --- a/MC1/Views/Map/MapFilter.swift +++ b/MC1/Views/Map/MapFilter.swift @@ -227,7 +227,7 @@ struct MapFilterState: Sendable, Equatable, Codable { func allowsContactType(_ type: ContactType) -> Bool { if favoritesOnly { return true } switch type { - case .chat: return showChat + case .chat, .sensor: return showChat case .repeater: return showRepeater case .room: return showRoom } diff --git a/MC1/Views/Map/MapPoint.swift b/MC1/Views/Map/MapPoint.swift index 7942790b82..1ba300af4a 100644 --- a/MC1/Views/Map/MapPoint.swift +++ b/MC1/Views/Map/MapPoint.swift @@ -11,6 +11,7 @@ struct MapPoint: Identifiable, Equatable { case contactChat case contactRepeater case contactRoom + case contactSensor case repeater case repeaterRingBlue case repeaterRingGreen diff --git a/MC1/Views/Map/MapSnapshotRenderer.swift b/MC1/Views/Map/MapSnapshotRenderer.swift index f96d629224..ac8f2e282f 100644 --- a/MC1/Views/Map/MapSnapshotRenderer.swift +++ b/MC1/Views/Map/MapSnapshotRenderer.swift @@ -141,6 +141,10 @@ final class MapSnapshotRenderer: MapSnapshotRendering { /// A / B / hop names match `MC1MapView`; anything else uses the dropped pin. private static func spriteName(for point: MapPoint) -> String { switch point.pinStyle { + case .contactChat: "pin-chat" + case .contactRepeater: "pin-repeater" + case .contactRoom: "pin-room" + case .contactSensor: "pin-sensor" case .pointA: "pin-point-a" case .pointB: "pin-point-b" case .repeaterHop: diff --git a/MC1/Views/Map/PinSpriteRenderer.swift b/MC1/Views/Map/PinSpriteRenderer.swift index 75b31b50ed..4e2a29b26e 100644 --- a/MC1/Views/Map/PinSpriteRenderer.swift +++ b/MC1/Views/Map/PinSpriteRenderer.swift @@ -198,6 +198,8 @@ enum PinSpriteRenderer { iconName: "person.fill", text: nil, ringColor: nil, renderStyle: .standard), SpriteSpec(name: "pin-repeater", circleColor: .systemCyan, iconName: "antenna.radiowaves.left.and.right", text: nil, ringColor: nil, renderStyle: .standard), + SpriteSpec(name: "pin-sensor", circleColor: .systemGray, + iconName: "sensor", text: nil, ringColor: nil, renderStyle: .standard), SpriteSpec(name: "pin-room", circleColor: UIColor(red: 1, green: 136 / 255, blue: 0, alpha: 1), iconName: "person.3.fill", text: nil, ringColor: nil, renderStyle: .standard), diff --git a/MC1/Views/Onboarding/DeviceScanView.swift b/MC1/Views/Onboarding/DeviceScanView.swift index 2f42bc018b..533ff671af 100644 --- a/MC1/Views/Onboarding/DeviceScanView.swift +++ b/MC1/Views/Onboarding/DeviceScanView.swift @@ -2,7 +2,11 @@ import MC1Services import SwiftUI struct DeviceScanView: View { + private static let busyLabelLineLimit = 2 + private static let busyLabelMinimumScale: CGFloat = 0.8 + @Environment(\.appState) private var appState + @Environment(\.accessibilityReduceMotion) private var reduceMotion @State private var showTroubleshooting = false @State private var showingWiFiConnection = false @State private var showingNoDeviceSheet = false @@ -12,6 +16,7 @@ struct DeviceScanView: View { @State private var didInitiatePairing = false @State private var showDemoModeAlert = false @State private var otherAppDeviceID: UUID? + @State private var directConnectionAttempt: Task? private var demoModeManager = DemoModeManager.shared private var hasConnectedDevice: Bool { @@ -32,7 +37,7 @@ struct DeviceScanView: View { ) if !hasConnectedDevice { - Text(L10n.Onboarding.DeviceScan.subtitle) + Text(appState.isRecoveringPairing ? L10n.Onboarding.DeviceScan.rePairingSubtitle : L10n.Onboarding.DeviceScan.subtitle) .font(.body) .foregroundStyle(.secondary) .multilineTextAlignment(.center) @@ -126,47 +131,77 @@ struct DeviceScanView: View { @ViewBuilder private var primaryCTA: some View { - #if targetEnvironment(simulator) - Button { connectSimulator() } label: { ctaLabel(systemImage: "laptopcomputer.and.iphone", - text: L10n.Onboarding.DeviceScan.connectSimulator) } - .liquidGlassProminentButtonStyle() - .disabled(appState.connectionUI.isBusy) - #else - if demoModeManager.isEnabled { - Button { connectSimulator() } label: { ctaLabel(systemImage: "play.circle.fill", - text: L10n.Onboarding.DeviceScan.continueDemo) } - .liquidGlassProminentButtonStyle() - .disabled(appState.connectionUI.isBusy) - } else if let deviceID = otherAppDeviceID { - Button { retryConnection(deviceID: deviceID) } label: { ctaLabel(systemImage: "arrow.clockwise.circle.fill", - text: L10n.Onboarding.DeviceScan.retryConnection) } - .liquidGlassProminentButtonStyle() - .disabled(appState.connectionUI.isBusy) - } else { - Button { startPairing() } label: { ctaLabel(systemImage: "plus.circle.fill", - text: L10n.Onboarding.DeviceScan.addDevice) } + if appState.isRecoveringPairing { + PairingRecoveryStatus() + .font(.headline) + .frame(maxWidth: .infinity) + .padding() + } else { + #if targetEnvironment(simulator) + Button { connectSimulator() } label: { ctaLabel(systemImage: "laptopcomputer.and.iphone", + text: L10n.Onboarding.DeviceScan.connectSimulator) } .liquidGlassProminentButtonStyle() .disabled(appState.connectionUI.isBusy) - } - #endif + .accessibilityAddTraits(appState.connectionUI.isBusy ? .updatesFrequently : []) + #else + if demoModeManager.isEnabled { + Button { connectSimulator() } label: { ctaLabel(systemImage: "play.circle.fill", + text: L10n.Onboarding.DeviceScan.continueDemo) } + .liquidGlassProminentButtonStyle() + .disabled(appState.connectionUI.isBusy) + .accessibilityAddTraits(appState.connectionUI.isBusy ? .updatesFrequently : []) + } else if let deviceID = otherAppDeviceID { + Button { retryConnection(deviceID: deviceID) } label: { ctaLabel(systemImage: "arrow.clockwise.circle.fill", + text: L10n.Onboarding.DeviceScan.retryConnection) } + .liquidGlassProminentButtonStyle() + .disabled(appState.connectionUI.isBusy) + .accessibilityAddTraits(appState.connectionUI.isBusy ? .updatesFrequently : []) + } else { + Button { startPairing() } label: { ctaLabel(systemImage: "plus.circle.fill", + text: L10n.Onboarding.DeviceScan.addDevice) } + .liquidGlassProminentButtonStyle() + .disabled(appState.connectionUI.isBusy) + .accessibilityAddTraits(appState.connectionUI.isBusy ? .updatesFrequently : []) + } + #endif + } } @ViewBuilder private var secondaryButtons: some View { - Button(L10n.Onboarding.DeviceScan.connectViaWifi) { showingWiFiConnection = true } + if appState.connectionUI.isBusy { + Button(action: cancelInProgressConnection) { + Text(L10n.Localizable.Common.cancel) + } .font(.subheadline) .foregroundStyle(.secondary) + } else { + Button { showingWiFiConnection = true } label: { + Text(L10n.Onboarding.DeviceScan.connectViaWifi) + } + .font(.subheadline) + .foregroundStyle(.secondary) + } Button(L10n.Onboarding.DeviceScan.deviceNotAppearing) { showTroubleshooting = true } .font(.subheadline) .foregroundStyle(.secondary) } + private var busyTitle: String { + appState.statusPillState.busyProgressTitle + } + private func ctaLabel(systemImage: String, text: String) -> some View { HStack(spacing: 8) { if appState.connectionUI.isBusy { ProgressView().controlSize(.small) - Text(L10n.Onboarding.DeviceScan.connecting) + Text(busyTitle) + .lineLimit(Self.busyLabelLineLimit) + .multilineTextAlignment(.center) + .minimumScaleFactor(Self.busyLabelMinimumScale) + .contentTransition(reduceMotion ? .identity : .opacity) + .animation(reduceMotion ? nil : .default, value: busyTitle) } else { Image(systemName: systemImage) Text(text) @@ -175,6 +210,10 @@ struct DeviceScanView: View { .font(.headline) .frame(maxWidth: .infinity) .padding() + .onChange(of: busyTitle) { _, newTitle in + guard appState.connectionUI.isBusy, newTitle != L10n.Localizable.Common.Status.connecting else { return } + appState.connectionUI.announceConnectionState(newTitle) + } } private func startPairing() { @@ -182,31 +221,54 @@ struct DeviceScanView: View { appState.startDeviceScan() } + private func cancelInProgressConnection() { + let directRequestID = directConnectionAttempt == nil + ? nil + : appState.connectionManager.connectionActivity?.requestID + directConnectionAttempt?.cancel() + directConnectionAttempt = nil + appState.cancelDeviceScanAttempt() + guard let directRequestID else { return } + Task { await appState.disconnect(requestID: directRequestID, reason: .userInitiated) } + } + private func retryConnection(deviceID: UUID) { - appState.connectionUI.isBusy = true - Task { @MainActor in - defer { appState.connectionUI.isBusy = false } + let actionID = appState.connectionUI.beginConnectionAction() + directConnectionAttempt?.cancel() + directConnectionAttempt = Task { @MainActor in + guard appState.connectionUI.isCurrentConnectionAction(actionID) else { return } + defer { appState.connectionUI.finishConnectionAction(actionID) } do { - try await appState.connectionManager.connect(to: deviceID, forceReconnect: true) - await appState.wireServicesIfConnected() + let result = try await appState.connectionManager.connect(to: deviceID, forceReconnect: true) + guard !Task.isCancelled, + case let .operational(snapshot) = result, appState.connectionManager.isCurrent(snapshot) else { return } + await appState.wireServices(for: snapshot) + guard !Task.isCancelled, appState.connectionManager.isCurrent(snapshot) else { return } appState.onboarding.onboardingPath.append(.region) } catch { - appState.connectionUI.presentSavedDeviceConnectFailure(deviceID: deviceID, error: error) + guard !Task.isCancelled, let failure = appState.currentConnectionFailure(error) else { return } + appState.connectionUI.presentSavedDeviceConnectFailure(deviceID: deviceID, error: failure) } } } private func connectSimulator() { - appState.connectionUI.isBusy = true + let actionID = appState.connectionUI.beginConnectionAction() didInitiatePairing = true - Task { @MainActor in - defer { appState.connectionUI.isBusy = false } + directConnectionAttempt?.cancel() + directConnectionAttempt = Task { @MainActor in + guard appState.connectionUI.isCurrentConnectionAction(actionID) else { return } + defer { appState.connectionUI.finishConnectionAction(actionID) } do { - try await appState.connectionManager.simulatorConnect() - await appState.wireServicesIfConnected() + let result = try await appState.connectionManager.simulatorConnect() + guard !Task.isCancelled, + case let .operational(snapshot) = result, appState.connectionManager.isCurrent(snapshot) else { return } + await appState.wireServices(for: snapshot) + guard !Task.isCancelled, appState.connectionManager.isCurrent(snapshot) else { return } appState.onboarding.onboardingPath.append(.region) } catch { - appState.connectionUI.presentConnectionFailure(message: error.userFacingMessage) + guard !Task.isCancelled, let failure = appState.currentConnectionFailure(error) else { return } + appState.connectionUI.presentConnectionFailure(message: failure.userFacingMessage) } } } diff --git a/MC1/Views/Onboarding/NoDeviceSheet.swift b/MC1/Views/Onboarding/NoDeviceSheet.swift index 497a00a4a8..3ebdf6b519 100644 --- a/MC1/Views/Onboarding/NoDeviceSheet.swift +++ b/MC1/Views/Onboarding/NoDeviceSheet.swift @@ -28,6 +28,7 @@ struct NoDeviceSheet: View { VStack(spacing: OnboardingMetrics.mediumSpacing) { Button { dismissTrigger.toggle() + appState.cancelDeviceScanAttempt() appState.completeOnboarding() dismiss() } label: { diff --git a/MC1/Views/Onboarding/WiFiConnectionSheet.swift b/MC1/Views/Onboarding/WiFiConnectionSheet.swift index ca3eabb513..db95bd213b 100644 --- a/MC1/Views/Onboarding/WiFiConnectionSheet.swift +++ b/MC1/Views/Onboarding/WiFiConnectionSheet.swift @@ -154,18 +154,22 @@ struct WiFiConnectionSheet: View { Task { do { - try await appState.connectViaWiFi( + let result = try await appState.connectViaWiFi( host: WiFiAddressFields.normalizedHost(ipAddress), port: portNumber, forceFullSync: true ) - await appState.wireServicesIfConnected() + guard case let .operational(snapshot) = result, appState.connectionManager.isCurrent(snapshot) else { + isConnecting = false + return + } dismiss() // Navigate directly to radio settings appState.onboarding.onboardingPath.append(.region) } catch { - errorMessage = error.userFacingMessage isConnecting = false + guard let failure = appState.currentConnectionFailure(error) else { return } + errorMessage = failure.userFacingMessage } } } diff --git a/MC1/Views/RemoteNodes/NodeAuthPathViewModel.swift b/MC1/Views/RemoteNodes/NodeAuthPathViewModel.swift index 6fb97100ed..3b56b2e47d 100644 --- a/MC1/Views/RemoteNodes/NodeAuthPathViewModel.swift +++ b/MC1/Views/RemoteNodes/NodeAuthPathViewModel.swift @@ -14,7 +14,8 @@ final class NodeAuthPathViewModel { contact: ContactDTO, services: ServiceContainer?, radioID: UUID, - userLocation: CLLocation? + userLocation: CLLocation?, + isCurrent: @MainActor () -> Bool ) async { guard let services else { hops = [] @@ -23,7 +24,9 @@ final class NodeAuthPathViewModel { do { let contacts = try await services.dataStore.fetchContacts(radioID: radioID) + guard !Task.isCancelled, isCurrent() else { return } let discoveredNodes = try await services.dataStore.fetchDiscoveredNodes(radioID: radioID) + guard !Task.isCancelled, isCurrent() else { return } hops = NeighborNameResolver.resolvePath( contact.pathHops, @@ -32,6 +35,7 @@ final class NodeAuthPathViewModel { userLocation: userLocation ) } catch { + guard !Task.isCancelled, isCurrent() else { return } logger.error("Failed to resolve path hops: \(error.localizedDescription)") hops = [] } diff --git a/MC1/Views/RemoteNodes/NodeAuthenticationSheet.swift b/MC1/Views/RemoteNodes/NodeAuthenticationSheet.swift index 6696c70619..7d78ea03c3 100644 --- a/MC1/Views/RemoteNodes/NodeAuthenticationSheet.swift +++ b/MC1/Views/RemoteNodes/NodeAuthenticationSheet.swift @@ -4,7 +4,7 @@ import SwiftUI private let logger = Logger(subsystem: "com.mc1", category: "NodeAuthenticationSheet") -/// Reusable password entry sheet for both room servers and repeaters +/// Reusable password entry sheet for remote nodes struct NodeAuthenticationSheet: View { @Environment(\.appState) private var appState @Environment(\.appTheme) private var theme @@ -12,6 +12,7 @@ struct NodeAuthenticationSheet: View { let contact: ContactDTO let role: RemoteNodeRole + let requireAdmin: Bool /// When true, hides the Node Details section (used when re-joining known rooms from chat list) let hideNodeDetails: Bool /// Optional custom title. If nil, uses default based on role ("Join Room" or "Admin Access") @@ -35,18 +36,22 @@ struct NodeAuthenticationSheet: View { @State private var countdownTask: Task? @State private var authenticationTask: Task? - private let maxPasswordLength = 15 + @State private var authEpoch = Epoch() + + private let maxPasswordBytes = ProtocolLimits.maxRemotePasswordBytes init( contact: ContactDTO, role: RemoteNodeRole, hideNodeDetails: Bool = false, + requireAdmin: Bool = true, customTitle: String? = nil, onSuccess: @escaping (RemoteNodeSessionDTO) -> Void ) { self.contact = contact self.role = role self.hideNodeDetails = hideNodeDetails + self.requireAdmin = requireAdmin self.customTitle = customTitle self.onSuccess = onSuccess _useFloodRouting = State(initialValue: contact.isFloodRouted) @@ -67,33 +72,37 @@ struct NodeAuthenticationSheet: View { .toolbar { ToolbarItem(placement: .cancellationAction) { Button(L10n.RemoteNodes.RemoteNodes.Auth.cancel) { - authenticationTask?.cancel() + cancelAuthentication() dismiss() } } } .task { - if let remoteNodeService = appState.services?.remoteNodeService, - let saved = await remoteNodeService.retrievePassword(forContact: contact) { + guard let source = appState.connectionSnapshot(for: contact.radioID) else { return } + let context = ConnectionCallbackContext(source) + if let saved = await source.services.remoteNodeService.retrievePassword(forContact: contact) { + guard accepts(context), password.isEmpty, !isAuthenticating else { return } password = saved hasSavedPassword = true } } .task { guard !contact.isFloodRouted, contact.pathHopCount > 0, - let radioID = appState.connectedDevice?.radioID else { return } + let source = appState.connectionSnapshot(for: contact.radioID) else { return } + let context = ConnectionCallbackContext(source) await pathViewModel.load( contact: contact, - services: appState.services, - radioID: radioID, - userLocation: appState.bestAvailableLocation + services: source.services, + radioID: contact.radioID, + userLocation: appState.bestAvailableLocation, + isCurrent: { accepts(context) } ) } .sensoryFeedback(.error, trigger: errorMessage) - .onDisappear { - authenticationTask?.cancel() - cleanupCountdownState() + .onChange(of: appState.connectionManager.currentConnection?.generation) { _, _ in + cancelAuthentication() } + .onDisappear { cancelAuthentication() } } } @@ -113,8 +122,7 @@ struct NodeAuthenticationSheet: View { errorMessage: $errorMessage, authSecondsRemaining: $authSecondsRemaining, isRetryingViaFlood: isRetryingViaFlood, - role: role, - maxPasswordLength: maxPasswordLength + maxPasswordBytes: maxPasswordBytes ) } @@ -122,6 +130,8 @@ struct NodeAuthenticationSheet: View { PathSection( contact: contact, useFloodRouting: $useFloodRouting, + routeCleared: didResetPath, + isAuthenticating: isAuthenticating, pathViewModel: pathViewModel ) } @@ -136,35 +146,46 @@ struct NodeAuthenticationSheet: View { // MARK: - Authentication + private func cancelAuthentication() { + authEpoch.bump() + authenticationTask?.cancel() + authenticationTask = nil + isAuthenticating = false + isRetryingViaFlood = false + cleanupCountdownState() + } + private func authenticate() { - // Clear any previous error + guard password.utf8.count <= maxPasswordBytes else { + errorMessage = RemoteNodeError.invalidPasswordLength.userFacingMessage + return + } + guard let source = appState.connectionSnapshot(for: contact.radioID) else { + errorMessage = RemoteNodeError.notConnected.userFacingMessage + return + } + let context = ConnectionCallbackContext(source) + let submittedPassword = password + let submittedRememberPassword = rememberPassword + cancelAuthentication() + let ticket = authEpoch.ticket() errorMessage = nil isAuthenticating = true - isRetryingViaFlood = false - authenticationTask?.cancel() - cleanupCountdownState() authenticationTask = Task { do { - guard let device = appState.connectedDevice else { - throw RemoteNodeError.notConnected - } - - guard let services = appState.services else { - throw RemoteNodeError.notConnected - } + guard accepts(context, ticket: ticket) else { return } + let services = source.services - // Reset the firmware's stored path so the login packet is flood-routed. - // Only needed once per session — subsequent retries skip the BLE round-trip. - // Once any reset has run, the radio's path is gone regardless of what - // this sheet's contact snapshot says, so later attempts are flood. + // Once any reset has run, later attempts flood-route even if this contact snapshot still has a path. let pathLength: UInt8 if useFloodRouting && !contact.isFloodRouted && !didResetPath { try await services.contactService.resetPath( - radioID: device.radioID, + radioID: contact.radioID, publicKey: contact.publicKey ) didResetPath = true + guard accepts(context, ticket: ticket) else { return } pathLength = PacketBuilder.floodPathSentinel } else if useFloodRouting || didResetPath { pathLength = PacketBuilder.floodPathSentinel @@ -172,41 +193,45 @@ struct NodeAuthenticationSheet: View { pathLength = contact.outPathLength } - // MeshCore repeaters and rooms only support 15-character passwords, truncate if needed - let passwordToUse = password.count > maxPasswordLength - ? String(password.prefix(maxPasswordLength)) - : password - let session: RemoteNodeSessionDTO do { session = try await performLogin( services: services, - device: device, - password: passwordToUse, + context: context, + password: submittedPassword, + rememberPassword: submittedRememberPassword, + ticket: ticket, pathLength: pathLength ) - } catch RemoteNodeError.timeout where pathLength != PacketBuilder.floodPathSentinel { - // The stored route produced no reply; clear it and let the network - // find a path, mirroring what the flood toggle would have done. - await MainActor.run { - isRetryingViaFlood = true - cleanupCountdownState() + } catch RemoteNodeError.timeout { + guard accepts(context, ticket: ticket) else { return } + guard RemoteFloodFallback.isEnabled(), + pathLength != PacketBuilder.floodPathSentinel else { + throw RemoteNodeError.timeout } + // The stored route produced no reply. Clear it and let the network find a path. + isRetryingViaFlood = true + cleanupCountdownState() try await services.contactService.resetPath( - radioID: device.radioID, + radioID: contact.radioID, publicKey: contact.publicKey ) didResetPath = true + useFloodRouting = true + guard accepts(context, ticket: ticket) else { return } session = try await performLogin( services: services, - device: device, - password: passwordToUse, + context: context, + password: submittedPassword, + rememberPassword: submittedRememberPassword, + ticket: ticket, pathLength: PacketBuilder.floodPathSentinel ) } + guard accepts(context, ticket: ticket) else { return } - // Delete saved password if user unchecked "Remember Password" - if hasSavedPassword, !rememberPassword { + // Sensor login handles its own credential update. + if role != .sensor, hasSavedPassword, !submittedRememberPassword { do { try await services.remoteNodeService.deletePassword(forContact: contact) } catch { @@ -214,35 +239,26 @@ struct NodeAuthenticationSheet: View { } } - await MainActor.run { - authenticationTask = nil - isRetryingViaFlood = false - cleanupCountdownState() - dismiss() - onSuccess(session) - } + guard accepts(context, ticket: ticket) else { return } + authenticationTask = nil + isRetryingViaFlood = false + cleanupCountdownState() + dismiss() + onSuccess(session) } catch is CancellationError { - await MainActor.run { - authenticationTask = nil - isRetryingViaFlood = false - cleanupCountdownState() - isAuthenticating = false - } + guard accepts(context, ticket: ticket) else { return } + cancelAuthentication() } catch RemoteNodeError.timeout { - await MainActor.run { - authenticationTask = nil - isRetryingViaFlood = false - cleanupCountdownState() - errorMessage = L10n.RemoteNodes.RemoteNodes.Status.requestTimedOut - isAuthenticating = false - } + guard accepts(context, ticket: ticket) else { return } + cancelAuthentication() + errorMessage = L10n.RemoteNodes.RemoteNodes.Status.requestTimedOut } catch { - await MainActor.run { - authenticationTask = nil - isRetryingViaFlood = false - cleanupCountdownState() + guard accepts(context, ticket: ticket) else { return } + cancelAuthentication() + if role == .sensor, requireAdmin, case RemoteNodeError.permissionDenied = error { + errorMessage = L10n.RemoteNodes.RemoteNodes.Sensor.adminRequired + } else { errorMessage = error.userFacingMessage - isAuthenticating = false } } } @@ -250,32 +266,42 @@ struct NodeAuthenticationSheet: View { private func performLogin( services: ServiceContainer, - device: DeviceDTO, + context: ConnectionCallbackContext, password: String, + rememberPassword: Bool, + ticket: Epoch.Ticket, pathLength: UInt8 ) async throws -> RemoteNodeSessionDTO { - // Callback to start countdown when firmware timeout is known let onTimeoutKnown: @Sendable (Int) async -> Void = { [self] seconds in await MainActor.run { + guard accepts(context, ticket: ticket) else { return } authTimeoutSeconds = seconds authStartTime = Date.now authSecondsRemaining = seconds - startCountdownTask() + startCountdownTask(context: context, ticket: ticket) } } - if role == .roomServer { + guard accepts(context, ticket: ticket) else { throw CancellationError() } + switch role { + case .roomServer: return try await services.roomServerService.joinRoom( - radioID: device.radioID, + radioID: contact.radioID, contact: contact, password: password, rememberPassword: rememberPassword, pathLength: pathLength, onTimeoutKnown: onTimeoutKnown ) - } else { + case .sensor: + return try await services.remoteNodeService.connectSensor( + radioID: contact.radioID, contact: contact, password: password, + rememberPassword: rememberPassword, requireAdmin: requireAdmin, + pathLength: pathLength, onTimeoutKnown: onTimeoutKnown + ) + case .repeater: return try await services.repeaterAdminService.connectAsAdmin( - radioID: device.radioID, + radioID: contact.radioID, contact: contact, password: password, rememberPassword: rememberPassword, @@ -285,11 +311,17 @@ struct NodeAuthenticationSheet: View { } } + private func accepts(_ context: ConnectionCallbackContext, ticket: Epoch.Ticket? = nil) -> Bool { + !Task.isCancelled && context.isCurrent(appState.connectionManager) + && appState.connectionSnapshot(for: contact.radioID) != nil + && (ticket?.isCurrent(in: authEpoch) ?? true) + } + // MARK: - Countdown private static let countdownTickInterval: Duration = .seconds(1) - private func startCountdownTask() { + private func startCountdownTask(context: ConnectionCallbackContext, ticket: Epoch.Ticket) { countdownTask = Task { while !Task.isCancelled, let timeout = authTimeoutSeconds, let startTime = authStartTime { do { @@ -297,6 +329,7 @@ struct NodeAuthenticationSheet: View { } catch { break } + guard accepts(context, ticket: ticket) else { return } let elapsed = Date.now.timeIntervalSince(startTime) let remaining = max(0, timeout - Int(elapsed)) @@ -320,6 +353,14 @@ struct NodeAuthenticationSheet: View { // MARK: - Node Details Section private struct NodeDetailsSection: View { + private var typeLabel: String { + switch role { + case .roomServer: L10n.RemoteNodes.RemoteNodes.Auth.typeRoom + case .repeater: L10n.RemoteNodes.RemoteNodes.Auth.typeRepeater + case .sensor: L10n.RemoteNodes.RemoteNodes.Auth.typeSensor + } + } + @Environment(\.appTheme) private var theme let displayName: String let role: RemoteNodeRole @@ -327,7 +368,7 @@ private struct NodeDetailsSection: View { var body: some View { Section { LabeledContent(L10n.RemoteNodes.RemoteNodes.Auth.name, value: displayName) - LabeledContent(L10n.RemoteNodes.RemoteNodes.Auth.type, value: role == .roomServer ? L10n.RemoteNodes.RemoteNodes.Auth.typeRoom : L10n.RemoteNodes.RemoteNodes.Auth.typeRepeater) + LabeledContent(L10n.RemoteNodes.RemoteNodes.Auth.type, value: typeLabel) } header: { Text(L10n.RemoteNodes.RemoteNodes.Auth.nodeDetails) } @@ -349,8 +390,7 @@ private struct AuthenticationSection: View { @Binding var errorMessage: String? @Binding var authSecondsRemaining: Int? let isRetryingViaFlood: Bool - let role: RemoteNodeRole - let maxPasswordLength: Int + let maxPasswordBytes: Int var body: some View { Section { @@ -366,8 +406,8 @@ private struct AuthenticationSection: View { Label(errorMessage, systemImage: "exclamationmark.circle.fill") .foregroundStyle(.orange) .accessibilityLabel(L10n.RemoteNodes.RemoteNodes.Auth.errorPrefix(errorMessage)) - } else if password.count > maxPasswordLength { - Text(role == .repeater ? L10n.RemoteNodes.RemoteNodes.Auth.passwordTooLongRepeaters(maxPasswordLength) : L10n.RemoteNodes.RemoteNodes.Auth.passwordTooLongRooms(maxPasswordLength)) + } else if password.utf8.count > maxPasswordBytes { + Text(L10n.Localizable.Error.RemoteNode.invalidPasswordLength(maxPasswordBytes)) } else if isRetryingViaFlood { VStack(alignment: .leading, spacing: 2) { Text(L10n.RemoteNodes.RemoteNodes.Auth.floodRetryStatus) @@ -407,19 +447,36 @@ private struct AuthenticationSection: View { private struct PathSection: View { @Environment(\.appTheme) private var theme + @AppStorage(AppStorageKey.remoteFloodFallback.rawValue) + private var remoteFloodFallback = AppStorageKey.defaultRemoteFloodFallback let contact: ContactDTO @Binding var useFloodRouting: Bool + let routeCleared: Bool + let isAuthenticating: Bool let pathViewModel: NodeAuthPathViewModel @State private var isPathExpanded = false - private var hasStoredPath: Bool { - !contact.isFloodRouted + private var choice: SignInPathFooter { + signInPathFooter( + hasStoredRoute: !contact.isFloodRouted, + floodRouting: useFloodRouting, + routeCleared: routeCleared, + fallbackEnabled: remoteFloodFallback, + isAuthenticating: isAuthenticating + ) + } + + private var floodRoutingBinding: Binding { + if choice.canChangeFloodRouting { + return $useFloodRouting + } + return .constant(choice.showsFloodRoutingOn) } var body: some View { Section { - if hasStoredPath, !useFloodRouting { + if choice.showsSavedHops { if !pathViewModel.hops.isEmpty { DisclosureGroup(isExpanded: $isPathExpanded) { ForEach(pathViewModel.hops) { hop in @@ -431,7 +488,7 @@ private struct PathSection: View { } else { NodePathSummaryLabel(contact: contact) } - } else if !hasStoredPath { + } else if choice.showsNoRouteLabel { Label { Text(L10n.RemoteNodes.RemoteNodes.Auth.noRouteSet) .foregroundStyle(.secondary) @@ -443,22 +500,17 @@ private struct PathSection: View { .accessibilityHidden(true) } - Toggle(L10n.RemoteNodes.RemoteNodes.Auth.floodRouting, isOn: $useFloodRouting) - .disabled(!hasStoredPath) - .accessibilityHint(hasStoredPath ? "" : L10n.RemoteNodes.RemoteNodes.Auth.noRouteFooter) + Toggle(L10n.RemoteNodes.RemoteNodes.Auth.floodRouting, isOn: floodRoutingBinding) + .disabled(!choice.canChangeFloodRouting) + .accessibilityHint(choice.canChangeFloodRouting ? "" : choice.message) } header: { Text(L10n.RemoteNodes.RemoteNodes.Auth.path) } footer: { - if !hasStoredPath { - Text(L10n.RemoteNodes.RemoteNodes.Auth.noRouteFooter) - } else if useFloodRouting { - Text(L10n.RemoteNodes.RemoteNodes.Auth.floodFooter) - } else { - Text(L10n.RemoteNodes.RemoteNodes.Auth.pathFooter) - } + Text(choice.message) } .themedRowBackground(theme) .animation(.default, value: useFloodRouting) + .animation(.default, value: routeCleared) } } diff --git a/MC1/Views/RemoteNodes/NodeCLIView.swift b/MC1/Views/RemoteNodes/NodeCLIView.swift index e712d9e317..d9afe6ca07 100644 --- a/MC1/Views/RemoteNodes/NodeCLIView.swift +++ b/MC1/Views/RemoteNodes/NodeCLIView.swift @@ -17,7 +17,7 @@ struct NodeCLIView: View { tabSuggestions: viewModel.tabSuggestions, tabSelectionIndex: viewModel.tabSelectionIndex, isWaitingForResponse: viewModel.isWaitingForResponse, - canCancelCommand: CLICommandCancel.allows( + canCancelCommand: viewModel.canCancelCurrentCommand && CLICommandCancel.allows( isWaiting: viewModel.isWaitingForResponse, powerOffActive: false, powerOffCanStillPreventSend: true diff --git a/MC1/Views/RemoteNodes/NodeCLIViewModel.swift b/MC1/Views/RemoteNodes/NodeCLIViewModel.swift index 783e1426f7..1d23a0e1c2 100644 --- a/MC1/Views/RemoteNodes/NodeCLIViewModel.swift +++ b/MC1/Views/RemoteNodes/NodeCLIViewModel.swift @@ -32,10 +32,17 @@ final class NodeCLIViewModel { private var sendRawCommand: (@MainActor (_ command: String, _ timeout: Duration) async throws -> String)? private var currentCommandTask: Task? private var hasConfigured = false + private var sensorSubmissionPending = false + + var canCancelCurrentCommand: Bool { + isWaitingForResponse && !sensorSubmissionPending + } + private var commandEpoch = Epoch() func reset() { commandEpoch.bump() + sensorSubmissionPending = false currentCommandTask?.cancel() currentCommandTask = nil outputLines.removeAll() @@ -95,6 +102,7 @@ final class NodeCLIViewModel { let cmd = parts[0].lowercased() let args = parts.count > 1 ? parts[1] : "" + sensorSubmissionPending = remoteTarget == .sensor && RemoteCLINoReplyCommand.sensorCommand(transmitted) != nil isWaitingForResponse = true // Compared with `currentCommandTask` so a newer command stays waiting. var task: Task! @@ -109,7 +117,7 @@ final class NodeCLIViewModel { /// Radio CLI sends the submitted line. Help, clear, and the other targets keep the trimmed line. private func transmittedLine(original: String, normalized: String) -> String { - guard remoteTarget == .radio else { return normalized } + guard remoteTarget == .radio || remoteTarget == .sensor else { return normalized } let parts = normalized.split(separator: " ", maxSplits: 1).map(String.init) let verb = parts[0].lowercased() let args = parts.count > 1 ? parts[1] : "" @@ -120,6 +128,7 @@ final class NodeCLIViewModel { } func cancelCurrentCommand() { + guard !sensorSubmissionPending else { return } // A reply already in hand must not print after cancel. commandEpoch.bump() currentCommandTask?.cancel() @@ -133,6 +142,7 @@ final class NodeCLIViewModel { private func clearWaitingIfCurrent(_ task: Task) { guard currentCommandTask == task else { return } currentCommandTask = nil + sensorSubmissionPending = false isWaitingForResponse = false } @@ -158,13 +168,13 @@ final class NodeCLIViewModel { } else { appendOutput(response, type: .response) } - } catch RemoteNodeError.timeout { + } catch RemoteNodeError.timeout where remoteTarget != .sensor { guard ticket.isCurrent(in: commandEpoch) else { return } appendOutput(sentLine, type: .success) } catch is CancellationError { } catch { guard ticket.isCurrent(in: commandEpoch) else { return } - appendOutput(error.localizedDescription, type: .error) + appendOutput(error.userFacingMessage, type: .error) } return } @@ -179,7 +189,7 @@ final class NodeCLIViewModel { appendOutput(L10n.RemoteNodes.RemoteNodes.NodeCli.radioNoReply(sessionName), type: .error) } catch { guard ticket.isCurrent(in: commandEpoch) else { return } - appendOutput(error.localizedDescription, type: .error) + appendOutput(error.userFacingMessage, type: .error) } } @@ -187,6 +197,12 @@ final class NodeCLIViewModel { /// A radio matches the whole command, including case. private func noReplySentLine(for command: String) -> String? { switch remoteTarget { + case .sensor: + switch RemoteCLINoReplyCommand.sensorCommand(command) { + case .reboot: L10n.RemoteNodes.RemoteNodes.Sensor.rebootSent + case .powerOff: L10n.RemoteNodes.RemoteNodes.NodeCli.powerOffSent + case nil: nil + } case .repeater, .room: switch RemoteCLINoReplyCommand(command) { case .reboot: @@ -214,7 +230,9 @@ final class NodeCLIViewModel { appendOutput(L10n.RemoteNodes.RemoteNodes.NodeCli.helpHeader, type: .response) appendOutput(L10n.RemoteNodes.RemoteNodes.NodeCli.helpHelp, type: .response) appendOutput(L10n.RemoteNodes.RemoteNodes.NodeCli.helpClear, type: .response) - appendOutput(L10n.RemoteNodes.RemoteNodes.NodeCli.helpClearStats, type: .response) + if remoteTarget != .sensor { + appendOutput(L10n.RemoteNodes.RemoteNodes.NodeCli.helpClearStats, type: .response) + } appendOutput(L10n.RemoteNodes.RemoteNodes.NodeCli.helpReboot, type: .response) appendOutput(L10n.RemoteNodes.RemoteNodes.NodeCli.helpPassthrough, type: .response) } diff --git a/MC1/Views/RemoteNodes/NodeManagementTab.swift b/MC1/Views/RemoteNodes/NodeManagementTab.swift index dce0c4baba..40cb41574d 100644 --- a/MC1/Views/RemoteNodes/NodeManagementTab.swift +++ b/MC1/Views/RemoteNodes/NodeManagementTab.swift @@ -1,6 +1,6 @@ import Foundation -/// Top-of-page segments on the repeater/room admin management page. +/// Top-of-page segments on node management pages. /// No raw value: the selection is in-memory `@State`, never persisted, so /// `CaseIterable` (with the synthesized `Hashable`) is all the picker needs. enum NodeManagementTab: CaseIterable { diff --git a/MC1/Views/RemoteNodes/NodeManagementTabPicker.swift b/MC1/Views/RemoteNodes/NodeManagementTabPicker.swift index 044a883361..560e3ae392 100644 --- a/MC1/Views/RemoteNodes/NodeManagementTabPicker.swift +++ b/MC1/Views/RemoteNodes/NodeManagementTabPicker.swift @@ -1,9 +1,10 @@ import SwiftUI -/// Pinned glass segment switcher for the repeater/room admin management page; +/// Pinned glass segment switcher for node management pages; /// floating Liquid Glass pills on iOS 26, a segmented `Picker` on iOS 18. struct NodeManagementTabPicker: View { @Binding var selection: NodeManagementTab + var tabs: [NodeManagementTab] = Array(NodeManagementTab.allCases) var body: some View { GlassFilterBar( @@ -11,7 +12,8 @@ struct NodeManagementTabPicker: View { isSearching: false, pickerLabel: L10n.RemoteNodes.RemoteNodes.Settings.Tab.picker, title: { $0.label }, - size: .large + size: .large, + filters: tabs ) } } diff --git a/MC1/Views/RemoteNodes/NodeStatusRoute.swift b/MC1/Views/RemoteNodes/NodeStatusRoute.swift index edae7f292c..14c6ab6be1 100644 --- a/MC1/Views/RemoteNodes/NodeStatusRoute.swift +++ b/MC1/Views/RemoteNodes/NodeStatusRoute.swift @@ -11,11 +11,11 @@ enum NodeStatusRoute: Hashable { case locationMap(fix: NodeLocationFix, name: String?) } +@MainActor extension View { /// Registers the `NodeStatusRoute` destinations on the enclosing navigation stack, /// resolving each route against the host's `NodeStatusViewModel`. Apply to the `List` /// hosting the shared status sections, not to rows inside it. - @MainActor func nodeStatusDestinations(helper: NodeStatusViewModel) -> some View { navigationDestination(for: NodeStatusRoute.self) { route in switch route { @@ -30,22 +30,27 @@ extension View { fetchSnapshots: helper.fetchHistory ) case let .locationMap(fix, name): - NodeLocationMapView( - points: [MapPoint( - id: UUID(), - coordinate: fix.coordinate, - pinStyle: .locationFixLatest, - label: name, - isClusterable: false, - hopIndex: nil, - badgeText: nil - )], - lines: [], - reports: [:], - title: L10n.RemoteNodes.RemoteNodes.Status.locationMapTitle, - initialSelectionID: nil - ) + nodeLocationMap(fix: fix, name: name) } } } } + +@MainActor +func nodeLocationMap(fix: NodeLocationFix, name: String?) -> some View { + NodeLocationMapView( + points: [MapPoint( + id: UUID(), + coordinate: fix.coordinate, + pinStyle: .locationFixLatest, + label: name, + isClusterable: false, + hopIndex: nil, + badgeText: nil + )], + lines: [], + reports: [:], + title: L10n.RemoteNodes.RemoteNodes.Status.locationMapTitle, + initialSelectionID: nil + ) +} diff --git a/MC1/Views/RemoteNodes/NodeStatusViewModel.swift b/MC1/Views/RemoteNodes/NodeStatusViewModel.swift index 36a2934650..90aa36e044 100644 --- a/MC1/Views/RemoteNodes/NodeStatusViewModel.swift +++ b/MC1/Views/RemoteNodes/NodeStatusViewModel.swift @@ -30,11 +30,6 @@ final class NodeStatusViewModel { session?.publicKey ?? directPublicKey } - /// 6-byte prefix for response matching. - var effectivePublicKeyPrefix: Data? { - session?.publicKeyPrefix ?? directPublicKey?.prefix(6) - } - /// Last received status var status: RemoteNodeStatus? @@ -273,62 +268,26 @@ final class NodeStatusViewModel { // MARK: - Telemetry Response Handling func handleTelemetryResponse(_ response: TelemetryResponse) async { - guard let expectedPrefix = effectivePublicKeyPrefix, - response.publicKeyPrefix == expectedPrefix else { + guard let nodePublicKey = effectivePublicKey, + let reading = TelemetryReading.accepted(from: response, expectedPublicKey: nodePublicKey) else { return } telemetry = response - cachedDataPoints = response.dataPoints.filter { $0.channel != 0 } + cachedDataPoints = reading.dataPoints isLoadingTelemetry = false telemetryLoaded = true telemetrySectionError = nil - let entries: [TelemetrySnapshotEntry] = cachedDataPoints.compactMap { dp in - let numericValue: Double? = switch dp.value { - case let .float(value): - value - case let .integer(value): - Double(value) - default: - nil - } - guard let value = numericValue else { return nil } - return TelemetrySnapshotEntry(channel: Int(dp.channel), type: dp.typeName, value: value) - } - - let location = currentLocationFix - - guard !entries.isEmpty || location != nil, - let nodeSnapshotService, - let nodePublicKey = effectivePublicKey else { return } + guard !reading.entries.isEmpty || reading.location != nil, + let nodeSnapshotService else { return } _ = await nodeSnapshotService.recordSnapshot( nodePublicKey: nodePublicKey, - telemetry: entries.isEmpty ? nil : entries, - location: location + telemetry: reading.entries.isEmpty ? nil : reading.entries, + location: reading.location ) } - // MARK: - Telemetry Grouping - - var hasMultipleChannels: Bool { - let channels = Set(cachedDataPoints.map(\.channel)) - return channels.count > 1 - } - - var groupedDataPoints: [(channel: UInt8, dataPoints: [LPPDataPoint])] { - Dictionary(grouping: cachedDataPoints, by: \.channel) - .sorted { $0.key < $1.key } - .map { (channel: $0.key, dataPoints: $0.value) } - } - - /// The node's reported location from the last telemetry response, or nil when it - /// reports no plottable coordinate. A node without a current GPS lock still reports - /// its last known or manually set position. Drives the live "View on Map" affordance. - var currentLocationFix: NodeLocationFix? { - NodeLocationFix.primaryFix(from: cachedDataPoints) - } - // MARK: - Display Formatters static let emDash = "—" @@ -492,8 +451,7 @@ final class NodeStatusViewModel { /// Load OCV settings for a contact by public key. Skips reload if already loaded. func loadOCVSettings(publicKey: Data, radioID: UUID) async { - guard contactID == nil else { return } - guard let contactService else { return } + guard contactID == nil, let contactService else { return } do { if let contact = try await contactService.getContact(radioID: radioID, publicKey: publicKey) { diff --git a/MC1/Views/RemoteNodes/NodeTelemetryView.swift b/MC1/Views/RemoteNodes/NodeTelemetryView.swift index 56d4a4dad4..d7296543f0 100644 --- a/MC1/Views/RemoteNodes/NodeTelemetryView.swift +++ b/MC1/Views/RemoteNodes/NodeTelemetryView.swift @@ -9,10 +9,14 @@ struct NodeTelemetryView: View { let contact: ContactDTO @State private var viewModel = NodeTelemetryViewModel() + private var connectionState: DeviceConnectionState { + appState.connectionSnapshot(for: contact.radioID) == nil ? .disconnected : appState.connectionState + } + var body: some View { NavigationStack { List { - NodeTelemetryDisclosureSection(helper: viewModel.helper, connectionState: appState.connectionState) { + NodeTelemetryDisclosureSection(helper: viewModel.helper, connectionState: connectionState) { await viewModel.requestTelemetry() } } @@ -31,22 +35,23 @@ struct NodeTelemetryView: View { } .labelStyle(.iconOnly) .radioDisabled( - for: appState.connectionState, + for: connectionState, or: viewModel.helper.isLoadingTelemetry ) } } .task { + let radioID = contact.radioID viewModel.configure( - binaryProtocolService: { appState.services?.binaryProtocolService }, - contactService: { appState.services?.contactService }, - nodeSnapshotService: { appState.services?.nodeSnapshotService }, + binaryProtocolService: { appState.connectionSnapshot(for: radioID)?.services.binaryProtocolService }, + contactService: { appState.connectionSnapshot(for: radioID)?.services.contactService }, + nodeSnapshotService: { appState.connectionSnapshot(for: radioID)?.services.nodeSnapshotService }, contact: contact ) viewModel.helper.telemetryExpanded = true - if let radioID = appState.connectedDevice?.radioID { + if appState.connectionSnapshot(for: radioID) != nil { await viewModel.helper.loadOCVSettings( publicKey: contact.publicKey, radioID: radioID diff --git a/MC1/Views/RemoteNodes/Repeaters/RepeaterSettingsView.swift b/MC1/Views/RemoteNodes/Repeaters/RepeaterSettingsView.swift index e352f5e316..5133dd5f9a 100644 --- a/MC1/Views/RemoteNodes/Repeaters/RepeaterSettingsView.swift +++ b/MC1/Views/RemoteNodes/Repeaters/RepeaterSettingsView.swift @@ -39,7 +39,7 @@ struct RepeaterSettingsView: View { contacts: contacts, discoveredNodes: discoveredNodes, userLocation: appState.bestAvailableLocation, - connectedDeviceID: appState.connectedDevice?.radioID, + connectedDeviceID: appState.connectionSnapshot(for: session.radioID)?.device.radioID, routePathContact: routeContact ) } @@ -55,24 +55,29 @@ struct RepeaterSettingsView: View { } } .task(id: appState.servicesVersion) { + guard let source = appState.connectionSnapshot(for: session.radioID) else { return } + let context = ConnectionCallbackContext(source) let models = appState.remoteAdminWorkspaces.repeater(for: session) viewModel = models.settings statusViewModel = models.status cliViewModel = models.cli await viewModel.configure( - repeaterAdminService: { appState.services?.repeaterAdminService }, + repeaterAdminService: { appState.connectionSnapshot(for: session.radioID)?.services.repeaterAdminService }, session: session ) + guard !Task.isCancelled, context.isCurrent(appState.connectionManager), + source.services.isAcceptingRuntimeWork else { return } if let send = viewModel.makeNodeCLISendClosure(session: session) { cliViewModel.configure(sessionName: session.name, remoteTarget: .repeater, sendRawCommand: send) } // Loaded up front (not just on Telemetry reveal) so the Settings-tab route section can // resolve hop hashes to repeater names. - if let radioID = appState.connectedDevice?.radioID, - let dataStore = appState.services?.dataStore { - contacts = await (try? dataStore.fetchContacts(radioID: radioID)) ?? [] - discoveredNodes = await (try? dataStore.fetchDiscoveredNodes(radioID: radioID)) ?? [] - } + let loadedContacts = await (try? source.services.dataStore.fetchContacts(radioID: session.radioID)) ?? [] + let loadedDiscovered = await (try? source.services.dataStore.fetchDiscoveredNodes(radioID: session.radioID)) ?? [] + guard !Task.isCancelled, context.isCurrent(appState.connectionManager), + source.services.isAcceptingRuntimeWork else { return } + contacts = loadedContacts + discoveredNodes = loadedDiscovered await refreshRouteContact() } .onChange(of: appState.contactsVersion) { @@ -87,14 +92,14 @@ struct RepeaterSettingsView: View { // telemetryConfigured because a segment switch recreates only the content subtree, // so this must not re-run or duplicate handler registration. statusViewModel.configure( - repeaterAdminService: { appState.services?.repeaterAdminService }, - contactService: { appState.services?.contactService }, - nodeSnapshotService: { appState.services?.nodeSnapshotService }, - deviceHashSize: { appState.connectedDevice?.hashSize } + repeaterAdminService: { appState.connectionSnapshot(for: session.radioID)?.services.repeaterAdminService }, + contactService: { appState.connectionSnapshot(for: session.radioID)?.services.contactService }, + nodeSnapshotService: { appState.connectionSnapshot(for: session.radioID)?.services.nodeSnapshotService }, + deviceHashSize: { appState.connectionSnapshot(for: session.radioID)?.device.hashSize } ) Task { await statusViewModel.registerHandlers() - if let radioID = appState.connectedDevice?.radioID { + if let radioID = appState.connectionSnapshot(for: session.radioID)?.device.radioID { await statusViewModel.helper.loadOCVSettings(publicKey: session.publicKey, radioID: radioID) } } @@ -209,11 +214,14 @@ struct RepeaterSettingsView: View { } private func refreshRouteContact() async { - guard let dataStore = appState.services?.dataStore else { return } - if let updated = await (try? dataStore.fetchContact( + guard let source = appState.connectionSnapshot(for: session.radioID) else { return } + let context = ConnectionCallbackContext(source) + if let updated = await (try? source.services.dataStore.fetchContact( radioID: session.radioID, publicKey: session.publicKey )).flatMap(\.self) { + guard !Task.isCancelled, context.isCurrent(appState.connectionManager), + source.services.isAcceptingRuntimeWork else { return } routeContact = updated } } diff --git a/MC1/Views/RemoteNodes/Repeaters/RepeaterSettingsViewModel.swift b/MC1/Views/RemoteNodes/Repeaters/RepeaterSettingsViewModel.swift index ee84447344..eb2241ff87 100644 --- a/MC1/Views/RemoteNodes/Repeaters/RepeaterSettingsViewModel.swift +++ b/MC1/Views/RemoteNodes/Repeaters/RepeaterSettingsViewModel.swift @@ -126,6 +126,7 @@ final class RepeaterSettingsViewModel { self.helper.handleCommonLateResponse(message.text) } } + guard !Task.isCancelled else { return } // Detached so configure returns immediately and the node CLI send // closure wires without waiting on the owner-info round-trip (matches diff --git a/MC1/Views/RemoteNodes/Repeaters/RepeaterStatusView.swift b/MC1/Views/RemoteNodes/Repeaters/RepeaterStatusView.swift index 561a689b21..e7899e0bb8 100644 --- a/MC1/Views/RemoteNodes/Repeaters/RepeaterStatusView.swift +++ b/MC1/Views/RemoteNodes/Repeaters/RepeaterStatusView.swift @@ -23,7 +23,7 @@ struct RepeaterStatusView: View { contacts: contacts, discoveredNodes: discoveredNodes, userLocation: appState.bestAvailableLocation, - connectedDeviceID: appState.connectedDevice?.radioID, + connectedDeviceID: appState.connectionSnapshot(for: session.radioID)?.device.radioID, routePathContact: routeContact ) .navigationTitle(L10n.RemoteNodes.RemoteNodes.Status.title) @@ -46,23 +46,27 @@ struct RepeaterStatusView: View { } } .task(id: appState.servicesVersion) { + guard let source = appState.connectionSnapshot(for: session.radioID) else { return } + let context = ConnectionCallbackContext(source) viewModel = appState.remoteAdminWorkspaces.repeater(for: session).status viewModel.configure( - repeaterAdminService: { appState.services?.repeaterAdminService }, - contactService: { appState.services?.contactService }, - nodeSnapshotService: { appState.services?.nodeSnapshotService }, - deviceHashSize: { appState.connectedDevice?.hashSize } + repeaterAdminService: { appState.connectionSnapshot(for: session.radioID)?.services.repeaterAdminService }, + contactService: { appState.connectionSnapshot(for: session.radioID)?.services.contactService }, + nodeSnapshotService: { appState.connectionSnapshot(for: session.radioID)?.services.nodeSnapshotService }, + deviceHashSize: { appState.connectionSnapshot(for: session.radioID)?.device.hashSize } ) await viewModel.registerHandlers() + guard !Task.isCancelled, context.isCurrent(appState.connectionManager), + source.services.isAcceptingRuntimeWork else { return } // Pre-load OCV settings and contacts for neighbor matching - if let radioID = appState.connectedDevice?.radioID { - await viewModel.helper.loadOCVSettings(publicKey: session.publicKey, radioID: radioID) - if let dataStore = appState.services?.dataStore { - contacts = await (try? dataStore.fetchContacts(radioID: radioID)) ?? [] - discoveredNodes = await (try? dataStore.fetchDiscoveredNodes(radioID: radioID)) ?? [] - } - } + await viewModel.helper.loadOCVSettings(publicKey: session.publicKey, radioID: session.radioID) + let loadedContacts = await (try? source.services.dataStore.fetchContacts(radioID: session.radioID)) ?? [] + let loadedDiscovered = await (try? source.services.dataStore.fetchDiscoveredNodes(radioID: session.radioID)) ?? [] + guard !Task.isCancelled, context.isCurrent(appState.connectionManager), + source.services.isAcceptingRuntimeWork else { return } + contacts = loadedContacts + discoveredNodes = loadedDiscovered await refreshRouteContact() } .onChange(of: appState.contactsVersion) { @@ -76,11 +80,14 @@ struct RepeaterStatusView: View { } private func refreshRouteContact() async { - guard let dataStore = appState.services?.dataStore else { return } - if let updated = await (try? dataStore.fetchContact( + guard let source = appState.connectionSnapshot(for: session.radioID) else { return } + let context = ConnectionCallbackContext(source) + if let updated = await (try? source.services.dataStore.fetchContact( radioID: session.radioID, publicKey: session.publicKey )).flatMap(\.self) { + guard !Task.isCancelled, context.isCurrent(appState.connectionManager), + source.services.isAcceptingRuntimeWork else { return } routeContact = updated } } diff --git a/MC1/Views/RemoteNodes/Rooms/RoomConversationView.swift b/MC1/Views/RemoteNodes/Rooms/RoomConversationView.swift index 11a519e3ab..95b64d0a13 100644 --- a/MC1/Views/RemoteNodes/Rooms/RoomConversationView.swift +++ b/MC1/Views/RemoteNodes/Rooms/RoomConversationView.swift @@ -63,6 +63,18 @@ struct RoomConversationView: View { onTitleTap: { showingRoomInfo = true } ) .toolbar { + ToolbarItem(placement: .primaryAction) { + if viewModel.isRefreshing { + ProgressView(L10n.RemoteNodes.RemoteNodes.Status.refresh) + .labelsHidden() + } else { + Button(L10n.RemoteNodes.RemoteNodes.Status.refresh, systemImage: "arrow.clockwise") { + let room = session + Task { await viewModel.refreshMessages(for: room) } + } + .disabled(!session.isConnected || appState.connectionSnapshot(for: session.radioID) == nil) + } + } if #unavailable(iOS 26) { ToolbarItem(placement: .primaryAction) { Button(L10n.RemoteNodes.RemoteNodes.Room.infoTitle, systemImage: "info.circle") { @@ -102,30 +114,15 @@ struct RoomConversationView: View { } } .task { + let radioID = session.radioID viewModel.configure( - roomServerService: { appState.services?.roomServerService }, - dataStore: { appState.services?.dataStore }, - syncCoordinator: { appState.syncCoordinator }, - notificationService: { appState.services?.notificationService } + roomServerService: { appState.connectionSnapshot(for: radioID)?.services.roomServerService }, + dataStore: { appState.connectionSnapshot(for: radioID)?.services.dataStore }, + syncCoordinator: { appState.connectionSnapshot(for: radioID)?.services.syncCoordinator }, + notificationService: { appState.connectionSnapshot(for: radioID)?.services.notificationService } ) chatViewModel.configure( - dependencies: ChatViewModel.Dependencies( - dataStore: { appState.offlineDataStore }, - messageService: { appState.services?.messageService }, - notificationService: { appState.services?.notificationService }, - channelService: { appState.services?.channelService }, - roomServerService: { appState.services?.roomServerService }, - contactService: { appState.services?.contactService }, - syncCoordinator: { appState.syncCoordinator }, - connectionState: { appState.connectionState }, - connectedDevice: { appState.connectedDevice }, - currentRadioID: { appState.currentRadioID }, - session: { appState.services?.session }, - reactionService: { appState.services?.reactionService }, - chatSendQueueService: { appState.services?.chatSendQueueService }, - inlineImageDimensionsStore: { nil }, - prefetchDataStore: { nil } - ), + dependencies: appState.makeChatViewModelDependencies(radioID: radioID), onNavigateToMap: { appState.navigation.navigateToMap(coordinate: $0) }, linkPreviewCache: nil, chatCoordinatorRegistry: nil, @@ -175,7 +172,8 @@ struct RoomConversationView: View { } .task(id: appState.servicesVersion) { // Reassert the active room when servicesVersion changes because reconnect replaces NotificationService. - appState.services?.notificationService.setActiveConversation(roomSessionID: session.id) + appState.connectionSnapshot(for: session.radioID)?.services.notificationService.setActiveConversation(roomSessionID: session.id) + await startSessionKeepAlive() } .task { for await event in appState.messageEventStream.events() { @@ -191,10 +189,7 @@ struct RoomConversationView: View { } } .task(id: session.isConnected) { - guard session.isConnected else { return } - await appState.services?.remoteNodeService.startSessionKeepAlive( - sessionID: session.id, publicKey: session.publicKey - ) + await startSessionKeepAlive() } .onChange(of: session.isConnected) { _, isConnected in if isConnected { @@ -208,34 +203,40 @@ struct RoomConversationView: View { // Re-clear the tray: notifications usually arrive while // backgrounded with this room already on screen. Task { - await appState.services?.notificationService - .removeDeliveredNotifications(forRoomSessionID: session.id) - await appState.services?.notificationService.updateBadgeCount() - } - if session.isConnected { - Task { - await appState.services?.remoteNodeService.startSessionKeepAlive( - sessionID: session.id, publicKey: session.publicKey - ) + guard let source = appState.connectionSnapshot(for: session.radioID) else { return } + let context = ConnectionCallbackContext(source) + await source.services.notificationService.removeDeliveredNotifications(forRoomSessionID: session.id) + guard !Task.isCancelled, context.isCurrent(appState.connectionManager), + source.services.isAcceptingRuntimeWork else { return } + await source.services.notificationService.updateBadgeCount { + context.isCurrent(appState.connectionManager) && source.services.isAcceptingRuntimeWork } } + Task { await startSessionKeepAlive() } } } .onDisappear { viewModel.cancelPendingTranslation() // Only clear if this room still owns the active slot; a newer room's // .task may have already claimed it before this view tears down. - if appState.services?.notificationService.activeRoomSessionID == session.id { - appState.services?.notificationService.activeRoomSessionID = nil + let source = appState.connectionSnapshot(for: session.radioID) + if source?.services.notificationService.activeRoomSessionID == session.id { + source?.services.notificationService.activeRoomSessionID = nil } Task { - await appState.services?.remoteNodeService.stopSessionKeepAlive( + await source?.services.remoteNodeService.stopSessionKeepAlive( sessionID: session.id ) } } } + private func startSessionKeepAlive() async { + guard session.isConnected, + let source = appState.connectionSnapshot(for: session.radioID) else { return } + await source.services.remoteNodeService.startSessionKeepAlive(sessionID: session.id, publicKey: session.publicKey) + } + private var connectionStatus: String { if session.isConnected { return session.permissionLevel.localizedName @@ -315,7 +316,7 @@ extension RoomConversationView { case .copy: UIPasteboard.general.string = viewModel.displayedText(for: message) case .translate: - presentSystemTranslation(text: message.text) + presentSystemTranslation(text: MECPCatalog.displayText(message.text)) case .reply: handleReply(for: message) case .sendDM: diff --git a/MC1/Views/RemoteNodes/Rooms/RoomConversationViewModel+Translation.swift b/MC1/Views/RemoteNodes/Rooms/RoomConversationViewModel+Translation.swift index d831436605..b855381fa8 100644 --- a/MC1/Views/RemoteNodes/Rooms/RoomConversationViewModel+Translation.swift +++ b/MC1/Views/RemoteNodes/Rooms/RoomConversationViewModel+Translation.swift @@ -146,7 +146,8 @@ extension RoomConversationViewModel { if let chrome = MessageTranslationChrome.resolved( detected: detectedLanguages[message.id], phase: translationPhases[message.id], - preferredLanguageCode: preferredLanguageCode + preferredLanguageCode: preferredLanguageCode, + text: message.text ) { translations[message.id] = chrome } diff --git a/MC1/Views/RemoteNodes/Rooms/RoomConversationViewModel.swift b/MC1/Views/RemoteNodes/Rooms/RoomConversationViewModel.swift index ef974c471a..7bc352729d 100644 --- a/MC1/Views/RemoteNodes/Rooms/RoomConversationViewModel.swift +++ b/MC1/Views/RemoteNodes/Rooms/RoomConversationViewModel.swift @@ -55,6 +55,7 @@ final class RoomConversationViewModel { /// Whether a message is being sent var isSending = false + private(set) var isRefreshing = false // MARK: - Dependencies @@ -185,6 +186,21 @@ final class RoomConversationViewModel { isSending = false } + func refreshMessages(for room: RemoteNodeSessionDTO) async { + guard !isRefreshing, let roomServerService else { return } + isRefreshing = true + errorMessage = nil + defer { isRefreshing = false } + + do { + try await roomServerService.refreshMessages(for: room) + } catch is CancellationError { + return + } catch { + errorMessage = error.userFacingMessage + } + } + /// Refresh session state from database func refreshSession() async { guard let session, let dataStore else { return } @@ -202,11 +218,13 @@ final class RoomConversationViewModel { guard let session else { return } switch event { - case let .roomMessageReceived(message, sessionID): + case let .roomMessageReceived(message, sessionID, roomID, scope): // Optimistic append first so the message list sees the new count // immediately for unread tracking, then coalesce the reload so a // burst of incoming room messages triggers one DB sync, not N. - guard sessionID == session.id else { return } + guard sessionID == session.id, + roomID == nil || roomID == session.textRulesID, + scope.isCurrent else { return } appendMessageIfNew(message) scheduleCoalescedReload() diff --git a/MC1/Views/RemoteNodes/Rooms/RoomMessageActionsSheet.swift b/MC1/Views/RemoteNodes/Rooms/RoomMessageActionsSheet.swift index 1cb1a9de7d..bd5d7e1224 100644 --- a/MC1/Views/RemoteNodes/Rooms/RoomMessageActionsSheet.swift +++ b/MC1/Views/RemoteNodes/Rooms/RoomMessageActionsSheet.swift @@ -50,7 +50,7 @@ struct RoomMessageActionsSheet: View { .font(.subheadline) .foregroundStyle(.secondary) } - Text(message.text) + Text(MECPCatalog.displayText(message.text)) .font(.subheadline) .foregroundStyle(.secondary) .lineLimit(dynamicTypeSize.isAccessibilitySize ? 2 : 1) @@ -127,6 +127,7 @@ struct RoomMessageActionsSheet: View { message.createdAt.formatted(date: .abbreviated, time: .standard) )) ActionInfoRow(text: message.localizedStatusText) + MessageVisibleBody.detailRow(storedText: message.text) } @ViewBuilder @@ -139,6 +140,8 @@ struct RoomMessageActionsSheet: View { if let roundTripTime = message.roundTripTime { ActionInfoRow(text: L10n.Chats.Chats.Message.Info.roundTrip(Int(roundTripTime))) } + + MessageVisibleBody.detailRow(storedText: message.text) } } diff --git a/MC1/Views/RemoteNodes/Rooms/RoomMessageBubble.swift b/MC1/Views/RemoteNodes/Rooms/RoomMessageBubble.swift index f342955195..14dc7f41a2 100644 --- a/MC1/Views/RemoteNodes/Rooms/RoomMessageBubble.swift +++ b/MC1/Views/RemoteNodes/Rooms/RoomMessageBubble.swift @@ -44,11 +44,12 @@ struct RoomMessageBubble: View { } .accessibilityElement(children: .combine) .accessibilityLabel(accessibilityMessageLabel) + .accessibilityIdentifier(ChatScrollConstants.messageAccessibilityIdentifier(message.id)) .accessibilityAction { onLongPress?(message) } .accessibilityActions { - if let chrome = translation { + if let chrome = visibleBody.translation { switch chrome.phase { case .offer: Button(L10n.Chats.Chats.Message.Action.translate) { @@ -85,15 +86,12 @@ struct RoomMessageBubble: View { TimestampView(date: message.date) } + private var visibleBody: MessageVisibleBody { + MessageVisibleBody(stored: message.text, translation: translation) + } + var accessibilityMessageLabel: String { - let body: String = switch translation?.phase { - case let .showing(translated, _): - L10n.Chats.Chats.Message.translatedAccessibility(translated) - case .inProgress: - "\(message.text), \(L10n.Chats.Chats.Message.Action.translating)" - default: - message.text - } + let body = visibleBody.spokenText if isFromSelf { return "\(body), \(message.accessibilityStatusLabel)" } @@ -136,7 +134,7 @@ struct RoomMessageBubble: View { showAvatar: showAvatar, highContrast: colorSchemeContrast == .increased, formattedBodyText: formattedBodyText, - translation: translation, + visibleBody: visibleBody, onTranslationAction: onTranslationAction ) .messageBubbleLongPressGesture( @@ -180,7 +178,7 @@ private struct BubbleContent: View { let showAvatar: Bool let highContrast: Bool let formattedBodyText: AttributedString - var translation: MessageTranslationChrome? + let visibleBody: MessageVisibleBody var onTranslationAction: (() -> Void)? @Environment(\.appTheme) private var theme @@ -228,7 +226,7 @@ private struct BubbleContent: View { private var messageBox: some View { VStack(alignment: isFromSelf ? .trailing : .leading, spacing: 2) { - if let chrome = translation { + if let chrome = visibleBody.translation { BubbleTranslationControl( phase: chrome.phase, onTap: { onTranslationAction?() } @@ -244,8 +242,8 @@ private struct BubbleContent: View { @ViewBuilder private var messageBody: some View { - if case let .showing(translated, _) = translation?.phase { - Text(translated) + if let plainText = visibleBody.plainText { + Text(plainText) .font(.body) .foregroundStyle(textColor) } else { diff --git a/MC1/Views/RemoteNodes/Rooms/RoomSettingsView.swift b/MC1/Views/RemoteNodes/Rooms/RoomSettingsView.swift index 70d90bd4c6..3b1170e704 100644 --- a/MC1/Views/RemoteNodes/Rooms/RoomSettingsView.swift +++ b/MC1/Views/RemoteNodes/Rooms/RoomSettingsView.swift @@ -29,7 +29,7 @@ struct RoomSettingsView: View { viewModel: statusViewModel, session: session, connectionState: appState.connectionState, - connectedDeviceID: appState.connectedDevice?.radioID + connectedDeviceID: appState.connectionSnapshot(for: session.radioID)?.device.radioID ) } } @@ -44,14 +44,18 @@ struct RoomSettingsView: View { } } .task(id: appState.servicesVersion) { + guard let source = appState.connectionSnapshot(for: session.radioID) else { return } + let context = ConnectionCallbackContext(source) let models = appState.remoteAdminWorkspaces.room(for: session) viewModel = models.settings statusViewModel = models.status cliViewModel = models.cli await viewModel.configure( - roomAdminService: { appState.services?.roomAdminService }, + roomAdminService: { appState.connectionSnapshot(for: session.radioID)?.services.roomAdminService }, session: session ) + guard !Task.isCancelled, context.isCurrent(appState.connectionManager), + source.services.isAcceptingRuntimeWork else { return } if let send = viewModel.makeNodeCLISendClosure(session: session) { cliViewModel.configure(sessionName: session.name, remoteTarget: .room, sendRawCommand: send) } @@ -65,13 +69,13 @@ struct RoomSettingsView: View { // because a segment switch recreates only the content subtree, so this must not // re-run or duplicate handler registration. statusViewModel.configure( - roomAdminService: { appState.services?.roomAdminService }, - contactService: { appState.services?.contactService }, - nodeSnapshotService: { appState.services?.nodeSnapshotService } + roomAdminService: { appState.connectionSnapshot(for: session.radioID)?.services.roomAdminService }, + contactService: { appState.connectionSnapshot(for: session.radioID)?.services.contactService }, + nodeSnapshotService: { appState.connectionSnapshot(for: session.radioID)?.services.nodeSnapshotService } ) Task { await statusViewModel.registerHandlers() - if let radioID = appState.connectedDevice?.radioID { + if let radioID = appState.connectionSnapshot(for: session.radioID)?.device.radioID { await statusViewModel.helper.loadOCVSettings(publicKey: session.publicKey, radioID: radioID) } } diff --git a/MC1/Views/RemoteNodes/Rooms/RoomSettingsViewModel.swift b/MC1/Views/RemoteNodes/Rooms/RoomSettingsViewModel.swift index 85e29f7a44..cd741f1af2 100644 --- a/MC1/Views/RemoteNodes/Rooms/RoomSettingsViewModel.swift +++ b/MC1/Views/RemoteNodes/Rooms/RoomSettingsViewModel.swift @@ -105,6 +105,7 @@ final class RoomSettingsViewModel { self.helper.handleCommonLateResponse(message.text) } } + guard !Task.isCancelled else { return } if !didScheduleDeviceInfo, !helper.deviceInfoLoaded, !helper.isLoadingDeviceInfo { didScheduleDeviceInfo = true diff --git a/MC1/Views/RemoteNodes/Rooms/RoomStatusView.swift b/MC1/Views/RemoteNodes/Rooms/RoomStatusView.swift index c65c659c01..5ca4d80f50 100644 --- a/MC1/Views/RemoteNodes/Rooms/RoomStatusView.swift +++ b/MC1/Views/RemoteNodes/Rooms/RoomStatusView.swift @@ -15,7 +15,7 @@ struct RoomStatusView: View { viewModel: viewModel, session: session, connectionState: appState.connectionState, - connectedDeviceID: appState.connectedDevice?.radioID + connectedDeviceID: appState.connectionSnapshot(for: session.radioID)?.device.radioID ) .navigationTitle(L10n.RemoteNodes.RemoteNodes.RoomStatus.title) .navigationBarTitleDisplayMode(.inline) @@ -37,16 +37,20 @@ struct RoomStatusView: View { } } .task(id: appState.servicesVersion) { + guard let source = appState.connectionSnapshot(for: session.radioID) else { return } + let context = ConnectionCallbackContext(source) viewModel = appState.remoteAdminWorkspaces.room(for: session).status viewModel.configure( - roomAdminService: { appState.services?.roomAdminService }, - contactService: { appState.services?.contactService }, - nodeSnapshotService: { appState.services?.nodeSnapshotService } + roomAdminService: { appState.connectionSnapshot(for: session.radioID)?.services.roomAdminService }, + contactService: { appState.connectionSnapshot(for: session.radioID)?.services.contactService }, + nodeSnapshotService: { appState.connectionSnapshot(for: session.radioID)?.services.nodeSnapshotService } ) await viewModel.registerHandlers() + guard !Task.isCancelled, context.isCurrent(appState.connectionManager), + source.services.isAcceptingRuntimeWork else { return } // Pre-load OCV settings - if let radioID = appState.connectedDevice?.radioID { + if let radioID = appState.connectionSnapshot(for: session.radioID)?.device.radioID { await viewModel.helper.loadOCVSettings(publicKey: session.publicKey, radioID: radioID) } } diff --git a/MC1/Views/RemoteNodes/Sensors/SensorSettingsContent.swift b/MC1/Views/RemoteNodes/Sensors/SensorSettingsContent.swift new file mode 100644 index 0000000000..816606fa3e --- /dev/null +++ b/MC1/Views/RemoteNodes/Sensors/SensorSettingsContent.swift @@ -0,0 +1,95 @@ +import MC1Services +import SwiftUI + +struct SensorSettingsContent: View { + @Environment(\.appTheme) private var theme + @Bindable var viewModel: SensorSettingsViewModel + let cliViewModel: NodeCLIViewModel + @State private var tab: NodeManagementTab = .settings + @State private var showRebootConfirmation = false + @State private var reloadTask: Task? + + var body: some View { + ZStack { + if tab == .cli { + NodeCLIView(viewModel: cliViewModel) + .disabled(!viewModel.isAuthorized || viewModel.isLoading || (viewModel.isMutating && !cliViewModel.isWaitingForResponse)) + } else { + settingsForm + } + } + .navigationTitle(L10n.RemoteNodes.RemoteNodes.Sensor.title) + .navigationBarTitleDisplayMode(.inline) + .safeAreaInset(edge: .top, spacing: 0) { + NodeManagementTabPicker(selection: $tab, tabs: [.settings, .cli]) + .pinnedFilterHeaderBackground(theme) + } + .task(id: viewModel.isAuthorized) { + if viewModel.isAuthorized { await viewModel.loadIfNeeded() } + } + .onDisappear { reloadTask?.cancel(); reloadTask = nil } + .errorAlert($viewModel.errorMessage) + } + + private var settingsForm: some View { + Form { + if viewModel.isMutating { + Section { ProgressView().frame(maxWidth: .infinity) } + } + if viewModel.requiresReload { + Section { Text(L10n.Localizable.Error.RemoteNode.sensorOutcomeUnknown).foregroundStyle(.secondary) } + } + if let status = viewModel.statusMessage { + Section { Text(status).foregroundStyle(.secondary) } + } + if !viewModel.isAuthorized { + Section { Text(L10n.RemoteNodes.RemoteNodes.Sensor.adminRequired).foregroundStyle(.secondary) } + } + Section { + if viewModel.isLoading { + ProgressView() + .frame(maxWidth: .infinity) + } else if viewModel.hasLoaded, viewModel.settings.isEmpty { + Text(L10n.RemoteNodes.RemoteNodes.Sensor.empty) + .foregroundStyle(.secondary) + } + ForEach(viewModel.settings) { setting in + VStack(alignment: .leading) { + Text(setting.key) + .font(.headline) + TextField(L10n.RemoteNodes.RemoteNodes.Sensor.value, text: $viewModel[draft: setting.key]) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .accessibilityLabel(setting.key) + Button(L10n.RemoteNodes.RemoteNodes.Sensor.save) { viewModel.save(setting.key) } + .disabled(!viewModel.canSave(setting.key)) + } + } + Button(L10n.RemoteNodes.RemoteNodes.Sensor.reload) { + reloadTask = Task { await viewModel.reload() } + } + .disabled(!viewModel.canSend) + } footer: { + Text(L10n.RemoteNodes.RemoteNodes.Sensor.runtimeOnly) + } + Section { + Button(L10n.RemoteNodes.RemoteNodes.Settings.reboot, role: .destructive) { + showRebootConfirmation = true + } + .disabled(!viewModel.canSend) + .confirmationDialog( + L10n.RemoteNodes.RemoteNodes.Sensor.rebootConfirmation, + isPresented: $showRebootConfirmation, + titleVisibility: .visible + ) { + Button(L10n.RemoteNodes.RemoteNodes.Settings.reboot, role: .destructive) { + showRebootConfirmation = false + viewModel.reboot() + } + Button(L10n.Contacts.Contacts.Common.cancel, role: .cancel) {} + } + } + } + .themedCanvas(theme) + } +} diff --git a/MC1/Views/RemoteNodes/Sensors/SensorSettingsView.swift b/MC1/Views/RemoteNodes/Sensors/SensorSettingsView.swift new file mode 100644 index 0000000000..772576df7a --- /dev/null +++ b/MC1/Views/RemoteNodes/Sensors/SensorSettingsView.swift @@ -0,0 +1,28 @@ +import MC1Services +import SwiftUI + +struct SensorSettingsView: View { + @Environment(\.appState) private var appState + let session: RemoteNodeSessionDTO + @State private var models: RemoteAdminWorkspaces.SensorModels? + + var body: some View { + Group { + if let models { + SensorSettingsContent(viewModel: models.settings, cliViewModel: models.cli) + } else { + ProgressView() + } + } + .task(id: appState.servicesVersion) { + let radioID = session.radioID + guard appState.connectionSnapshot(for: radioID) != nil else { return } + models = appState.remoteAdminWorkspaces.configureSensor( + for: session, + remoteNodeService: { [weak appState] in appState?.connectionSnapshot(for: radioID)?.services.remoteNodeService }, + dataStore: { [weak appState] in appState?.offlineDataStore }, + connectionState: { [weak appState] in appState?.connectionState ?? .disconnected } + ) + } + } +} diff --git a/MC1/Views/RemoteNodes/Sensors/SensorSettingsViewModel.swift b/MC1/Views/RemoteNodes/Sensors/SensorSettingsViewModel.swift new file mode 100644 index 0000000000..8763e7282d --- /dev/null +++ b/MC1/Views/RemoteNodes/Sensors/SensorSettingsViewModel.swift @@ -0,0 +1,244 @@ +import MC1Services +import SwiftUI + +@Observable +@MainActor +final class SensorSettingsViewModel { + private(set) var settings: [SensorSetting] = [] + private(set) var isLoading = false + private(set) var isMutating = false + private(set) var hasLoaded = false + private(set) var requiresReload = false + private(set) var currentSession: RemoteNodeSessionDTO? + private(set) var statusMessage: String? + var errorMessage: String? + + private var drafts: [String: String] = [:] + private var draftRevisions: [String: UInt] = [:] + private var session: RemoteNodeSessionDTO? + private var boundServiceID: ObjectIdentifier? + private var remoteNodeServiceProvider: @MainActor () -> RemoteNodeService? = { nil } + private var dataStoreProvider: @MainActor () -> PersistenceStore? = { nil } + private var connectionStateProvider: @MainActor () -> DeviceConnectionState = { .disconnected } + private var remoteNodeService: RemoteNodeService? { + remoteNodeServiceProvider() + } + + private var dataStore: PersistenceStore? { + dataStoreProvider() + } + + private var connectionState: DeviceConnectionState { + connectionStateProvider() + } + + private var epoch = Epoch() + private var loadEpoch = Epoch() + private var observationTask: Task? + private var mutationTask: Task? + + subscript(draft key: String) -> String { + get { drafts[key] ?? "" } + set { + drafts[key] = newValue + draftRevisions[key, default: 0] &+= 1 + } + } + + var isAuthorized: Bool { + connectionState == .ready && remoteNodeService.map(ObjectIdentifier.init) == boundServiceID + && currentSession?.isConnected == true && currentSession?.isAdmin == true + } + + var canSend: Bool { + isAuthorized && !isLoading && !isMutating + } + + func canSave(_ key: String) -> Bool { + canSend && hasLoaded && !requiresReload && settings.contains { $0.key == key && $0.value != self[draft: key] } + } + + func isBound(to service: RemoteNodeService?) -> Bool { + service.map(ObjectIdentifier.init) == boundServiceID + } + + func configure( + session: RemoteNodeSessionDTO, + remoteNodeService: @escaping @MainActor () -> RemoteNodeService?, + dataStore: @escaping @MainActor () -> PersistenceStore?, + connectionState: @escaping @MainActor () -> DeviceConnectionState + ) { + remoteNodeServiceProvider = remoteNodeService + dataStoreProvider = dataStore + connectionStateProvider = connectionState + let service = remoteNodeService() + guard self.session?.id != session.id || !isBound(to: service) else { return } + cancelOwnedWork() + self.session = session + boundServiceID = service.map(ObjectIdentifier.init) + guard let service else { return } + let ticket = epoch.ticket() + let events = service.events() + observationTask = Task { [weak self] in + await self?.refreshSession(service: service, ticket: ticket) + for await event in events { + guard let self, ticket.isCurrent(in: epoch), !Task.isCancelled else { return } + if case let .sessionStateChanged(id, connected) = event, id == session.id { + if !connected { currentSession = nil } + await refreshSession(service: service, ticket: ticket) + } + } + guard let self, ticket.isCurrent(in: epoch) else { return } + currentSession = nil + } + } + + private func refreshSession(service: RemoteNodeService, ticket: Epoch.Ticket) async { + guard let session, let dataStore else { return } + let updated = try? await dataStore.fetchRemoteNodeSession(id: session.id) + guard ticket.isCurrent(in: epoch), !Task.isCancelled, remoteNodeService === service else { return } + guard let updated, updated.isSensor, updated.radioID == session.radioID, + updated.publicKey == session.publicKey else { + currentSession = nil + return + } + currentSession = updated + } + + func loadIfNeeded() async { + guard !hasLoaded else { return } + await reload() + } + + func reload() async { + guard canSend, let service = remoteNodeService, let session else { return } + let ticket = loadEpoch.ticket() + let operation = epoch.ticket() + let revisions = draftRevisions + let baselines = Dictionary(uniqueKeysWithValues: settings.map { ($0.key, $0.value) }) + isLoading = true + errorMessage = nil + defer { if ticket.isCurrent(in: loadEpoch) { isLoading = false } } + do { + let loaded = try await service.fetchSensorSettings(sessionID: session.id) + try Task.checkCancellation() + guard ticket.isCurrent(in: loadEpoch), operation.isCurrent(in: epoch), remoteNodeService === service else { return } + for setting in loaded { + if drafts[setting.key] == nil + || (drafts[setting.key] == baselines[setting.key] && draftRevisions[setting.key] == revisions[setting.key]) { + drafts[setting.key] = setting.value + } + } + settings = loaded + hasLoaded = true + requiresReload = false + } catch is CancellationError { + } catch { + guard ticket.isCurrent(in: loadEpoch), operation.isCurrent(in: epoch), !Task.isCancelled else { return } + errorMessage = error.userFacingMessage + } + } + + func save(_ key: String) { + guard canSave(key), let setting = settings.first(where: { $0.key == key }) else { return } + let value = self[draft: key] + do { _ = try setting.command(setting: value) } catch { + errorMessage = error.userFacingMessage + return + } + startMutation(.save(setting, value)) + } + + func reboot() { + startMutation(.reboot) + } + + private enum Mutation { + case save(SensorSetting, String) + case reboot + } + + private func startMutation(_ mutation: Mutation) { + guard canSend, let service = remoteNodeService, let session else { return } + let ticket = epoch.ticket() + isMutating = true + errorMessage = nil + statusMessage = nil + mutationTask = Task { [weak self] in + guard let self else { return } + defer { + if ticket.isCurrent(in: epoch) { isMutating = false; mutationTask = nil } + } + do { + switch mutation { + case let .save(setting, value): + let verified = try await service.setSensorSetting(sessionID: session.id, setting: setting, value: value) + try Task.checkCancellation() + guard ticket.isCurrent(in: epoch), remoteNodeService === service else { return } + if let index = settings.firstIndex(where: { $0.key == verified.key }) { settings[index] = verified } + statusMessage = L10n.RemoteNodes.RemoteNodes.Sensor.saved + case .reboot: + try await service.rebootSensor(sessionID: session.id) + try Task.checkCancellation() + guard ticket.isCurrent(in: epoch), remoteNodeService === service else { return } + currentSession = nil + statusMessage = L10n.RemoteNodes.RemoteNodes.Sensor.rebootSent + } + } catch is CancellationError { + } catch { + guard ticket.isCurrent(in: epoch), !Task.isCancelled else { return } + if case RemoteNodeError.sensorOutcomeUnknown = error { requiresReload = true } + errorMessage = error.userFacingMessage + } + } + } + + func sendRawCommand(_ command: String, timeout: Duration) async throws -> String { + guard canSend, let service = remoteNodeService, let session else { throw RemoteNodeError.notConnected } + let ticket = epoch.ticket() + isMutating = true + defer { if ticket.isCurrent(in: epoch) { isMutating = false } } + do { + let response = try await service.sendRawCLICommand(sessionID: session.id, command: command, timeout: timeout) + try Task.checkCancellation() + guard ticket.isCurrent(in: epoch), remoteNodeService === service else { throw CancellationError() } + if let noReply = RemoteCLINoReplyCommand.sensorCommand(command) { + currentSession = nil + statusMessage = noReply == .reboot + ? L10n.RemoteNodes.RemoteNodes.Sensor.rebootSent : L10n.RemoteNodes.RemoteNodes.NodeCli.powerOffSent + } + return response + } catch { + guard ticket.isCurrent(in: epoch), !Task.isCancelled else { throw CancellationError() } + if case RemoteNodeError.timeout = error { requiresReload = true } + if case RemoteNodeError.sessionError = error { requiresReload = true } + throw error + } + } + + private func cancelOwnedWork() { + epoch.bump() + loadEpoch.bump() + mutationTask?.cancel() + mutationTask = nil + observationTask?.cancel() + observationTask = nil + if isMutating { requiresReload = true } + isMutating = false + isLoading = false + hasLoaded = false + currentSession = nil + } + + func reset() { + cancelOwnedWork() + settings = [] + drafts = [:] + draftRevisions = [:] + session = nil + boundServiceID = nil + requiresReload = false + statusMessage = nil + errorMessage = nil + } +} diff --git a/MC1/Views/RemoteNodes/SharedNodeStatusViews.swift b/MC1/Views/RemoteNodes/SharedNodeStatusViews.swift index 0036bd4daf..3d48ede682 100644 --- a/MC1/Views/RemoteNodes/SharedNodeStatusViews.swift +++ b/MC1/Views/RemoteNodes/SharedNodeStatusViews.swift @@ -270,10 +270,42 @@ struct NodeBatteryCurveDisclosureSection: View { // MARK: - Telemetry Disclosure Section -struct NodeTelemetryDisclosureSection: View { +@MainActor +protocol TelemetryDisclosurePresenting: AnyObject, Observable { + var telemetryExpanded: Bool { get set } + var isLoadingTelemetry: Bool { get } + var telemetrySectionError: String? { get } + var telemetry: TelemetryResponse? { get } + var cachedDataPoints: [LPPDataPoint] { get } + var ocvValues: [Int] { get } + var telemetryLoaded: Bool { get } +} + +extension TelemetryDisclosurePresenting { + var hasMultipleChannels: Bool { + Set(cachedDataPoints.map(\.channel)).count > 1 + } + + var groupedDataPoints: [(channel: UInt8, dataPoints: [LPPDataPoint])] { + Dictionary(grouping: cachedDataPoints, by: \.channel) + .sorted { $0.key < $1.key } + .map { (channel: $0.key, dataPoints: $0.value) } + } + + var currentLocationFix: NodeLocationFix? { + NodeLocationFix.primaryFix(from: cachedDataPoints) + } +} + +extension NodeStatusViewModel: TelemetryDisclosurePresenting {} + +struct NodeTelemetryDisclosureSection: View { @Environment(\.appTheme) private var theme - @Bindable var helper: NodeStatusViewModel + @Bindable var helper: Model let connectionState: DeviceConnectionState + let historyRoute: Route + let mapRoute: @MainActor (NodeLocationFix) -> Route + let isDeviceInfo: Bool let onRequestTelemetry: () async -> Void var body: some View { @@ -285,48 +317,13 @@ struct NodeTelemetryDisclosureSection: View { ProgressView() Spacer() } + } else if isDeviceInfo { + deviceInfoContent } else if let errorMessage = helper.telemetrySectionError, helper.telemetry == nil { - Text(errorMessage) - .foregroundStyle(.orange) + telemetryError(errorMessage) } else if helper.telemetry != nil { - if helper.cachedDataPoints.isEmpty { - Text(L10n.RemoteNodes.RemoteNodes.Status.noSensorData) - .foregroundStyle(.secondary) - } else if helper.hasMultipleChannels { - ForEach(helper.groupedDataPoints, id: \.channel) { group in - Section { - ForEach(Array(group.dataPoints.enumerated()), id: \.offset) { index, dataPoint in - NodeTelemetryRow( - dataPoint: dataPoint, - ocvArray: helper.ocvValues, - label: telemetryLabel(for: dataPoint, at: index, in: group.dataPoints) - ) - } - } header: { - Text(L10n.RemoteNodes.RemoteNodes.Status.channel(Int(group.channel))) - .fontWeight(.semibold) - } - } - } else { - ForEach(Array(helper.cachedDataPoints.enumerated()), id: \.offset) { index, dataPoint in - NodeTelemetryRow( - dataPoint: dataPoint, - ocvArray: helper.ocvValues, - label: telemetryLabel(for: dataPoint, at: index, in: helper.cachedDataPoints) - ) - } - } - - if let fix = helper.currentLocationFix { - NavigationLink(value: NodeStatusRoute.locationMap(fix: fix, name: helper.session?.name)) { - Label(L10n.RemoteNodes.RemoteNodes.Status.viewOnMap, systemImage: "map") - } - .accessibilityLabel(L10n.RemoteNodes.RemoteNodes.Status.Accessibility.viewLocationOnMap) - } - - NavigationLink(value: NodeStatusRoute.telemetryHistory) { - Text(L10n.RemoteNodes.RemoteNodes.History.title) - } + readingContent + historyLink } else { Text(L10n.RemoteNodes.RemoteNodes.Status.noTelemetryData) .foregroundStyle(.secondary) @@ -352,9 +349,104 @@ struct NodeTelemetryDisclosureSection: View { } } } + + if isDeviceInfo { + historyLink + } + } header: { + if isDeviceInfo { + Text(L10n.Settings.DeviceInfo.Telemetry.header) + } } footer: { Text(L10n.RemoteNodes.RemoteNodes.Status.telemetryFooter) } .themedRowBackground(theme) } + + @ViewBuilder + private var deviceInfoContent: some View { + if let errorMessage = helper.telemetrySectionError { + telemetryError(errorMessage) + if helper.telemetry != nil { + Text(L10n.Settings.DeviceInfo.lastSuccessfulReading) + .font(.headline) + .accessibilityAddTraits(.isHeader) + } + } else if helper.telemetry == nil { + Text(L10n.RemoteNodes.RemoteNodes.Status.noTelemetryData) + .foregroundStyle(.secondary) + } + + if helper.telemetry != nil { + readingContent + } + } + + @ViewBuilder + private var readingContent: some View { + if helper.cachedDataPoints.isEmpty { + Text(L10n.RemoteNodes.RemoteNodes.Status.noSensorData) + .foregroundStyle(.secondary) + } else if helper.hasMultipleChannels { + ForEach(helper.groupedDataPoints, id: \.channel) { group in + Section { + ForEach(Array(group.dataPoints.enumerated()), id: \.offset) { index, dataPoint in + NodeTelemetryRow( + dataPoint: dataPoint, + ocvArray: helper.ocvValues, + label: telemetryLabel(for: dataPoint, at: index, in: group.dataPoints) + ) + } + } header: { + Text(L10n.RemoteNodes.RemoteNodes.Status.channel(Int(group.channel))) + .fontWeight(.semibold) + } + } + } else { + ForEach(Array(helper.cachedDataPoints.enumerated()), id: \.offset) { index, dataPoint in + NodeTelemetryRow( + dataPoint: dataPoint, + ocvArray: helper.ocvValues, + label: telemetryLabel(for: dataPoint, at: index, in: helper.cachedDataPoints) + ) + } + } + + if let fix = helper.currentLocationFix { + NavigationLink(value: mapRoute(fix)) { + Label(L10n.RemoteNodes.RemoteNodes.Status.viewOnMap, systemImage: "map") + } + .accessibilityLabel(L10n.RemoteNodes.RemoteNodes.Status.Accessibility.viewLocationOnMap) + } + } + + private var historyLink: some View { + NavigationLink(value: historyRoute) { + Text(L10n.RemoteNodes.RemoteNodes.History.title) + } + } + + private func telemetryError(_ message: String) -> some View { + Text(message) + .foregroundStyle(.orange) + } +} + +extension NodeTelemetryDisclosureSection where Model == NodeStatusViewModel, Route == NodeStatusRoute { + init( + helper: NodeStatusViewModel, + connectionState: DeviceConnectionState, + onRequestTelemetry: @escaping () async -> Void + ) { + self.init( + helper: helper, + connectionState: connectionState, + historyRoute: .telemetryHistory, + mapRoute: { fix in + .locationMap(fix: fix, name: helper.session?.name) + }, + isDeviceInfo: false, + onRequestTelemetry: onRequestTelemetry + ) + } } diff --git a/MC1/Views/RemoteNodes/SignInPathFooter.swift b/MC1/Views/RemoteNodes/SignInPathFooter.swift new file mode 100644 index 0000000000..2012344070 --- /dev/null +++ b/MC1/Views/RemoteNodes/SignInPathFooter.swift @@ -0,0 +1,53 @@ +struct SignInPathFooter: Equatable { + let message: String + let showsSavedHops: Bool + let showsNoRouteLabel: Bool + let showsFloodRoutingOn: Bool + let canChangeFloodRouting: Bool +} + +func signInPathFooter( + hasStoredRoute: Bool, + floodRouting: Bool, + routeCleared: Bool, + fallbackEnabled: Bool, + isAuthenticating: Bool +) -> SignInPathFooter { + if routeCleared { + return SignInPathFooter( + message: L10n.RemoteNodes.RemoteNodes.Auth.floodFooterCleared, + showsSavedHops: false, + showsNoRouteLabel: false, + showsFloodRoutingOn: true, + canChangeFloodRouting: false + ) + } + if !hasStoredRoute { + return SignInPathFooter( + message: L10n.RemoteNodes.RemoteNodes.Auth.noRouteFooter, + showsSavedHops: false, + showsNoRouteLabel: true, + showsFloodRoutingOn: floodRouting, + canChangeFloodRouting: false + ) + } + let canChangeFloodRouting = !isAuthenticating + if floodRouting { + return SignInPathFooter( + message: L10n.RemoteNodes.RemoteNodes.Auth.floodFooter, + showsSavedHops: false, + showsNoRouteLabel: false, + showsFloodRoutingOn: true, + canChangeFloodRouting: canChangeFloodRouting + ) + } + return SignInPathFooter( + message: fallbackEnabled + ? L10n.RemoteNodes.RemoteNodes.Auth.pathFooter + : L10n.RemoteNodes.RemoteNodes.Auth.pathFooterKept, + showsSavedHops: true, + showsNoRouteLabel: false, + showsFloodRoutingOn: false, + canChangeFloodRouting: canChangeFloodRouting + ) +} diff --git a/MC1/Views/RemoteNodes/TelemetryReading.swift b/MC1/Views/RemoteNodes/TelemetryReading.swift new file mode 100644 index 0000000000..5821760043 --- /dev/null +++ b/MC1/Views/RemoteNodes/TelemetryReading.swift @@ -0,0 +1,34 @@ +import Foundation +import MC1Services + +/// A telemetry response accepted for one public key, with channel 0 removed. +struct TelemetryReading { + private static let publicKeyPrefixSize = 6 + private static let ignoredChannel: UInt8 = 0 + + let dataPoints: [LPPDataPoint] + let entries: [TelemetrySnapshotEntry] + let location: NodeLocationFix? + + static func accepted(from response: TelemetryResponse, expectedPublicKey: Data) -> TelemetryReading? { + guard response.publicKeyPrefix == expectedPublicKey.prefix(publicKeyPrefixSize) else { return nil } + let dataPoints = response.dataPoints.filter { $0.channel != ignoredChannel } + let entries: [TelemetrySnapshotEntry] = dataPoints.compactMap { point in + let numericValue: Double? = switch point.value { + case let .float(value): + value + case let .integer(value): + Double(value) + default: + nil + } + guard let numericValue else { return nil } + return TelemetrySnapshotEntry(channel: Int(point.channel), type: point.typeName, value: numericValue) + } + return TelemetryReading( + dataPoints: dataPoints, + entries: entries, + location: NodeLocationFix.primaryFix(from: dataPoints) + ) + } +} diff --git a/MC1/Views/Settings/AdvancedSettingsView.swift b/MC1/Views/Settings/AdvancedSettingsView.swift index 3ca19bbb39..b36a748201 100644 --- a/MC1/Views/Settings/AdvancedSettingsView.swift +++ b/MC1/Views/Settings/AdvancedSettingsView.swift @@ -9,6 +9,7 @@ struct AdvancedSettingsView: View { let descendantPath: [SettingsSubpage] let requestRegionAdd: SettingsEditorPresentation.RegionRequest + let configImport: NodeConfigImportViewModel @State private var selectedOCVPreset: OCVPreset = .liIon @State private var ocvValues: [Int] = OCVPreset.liIon.ocvArray @@ -37,6 +38,8 @@ struct AdvancedSettingsView: View { // Direct Messages Settings DirectMessagesSettingsSection() + PathFallbackSettingsSection() + // Battery Curve BatteryCurveSection( availablePresets: OCVPreset.selectablePresets, @@ -65,7 +68,7 @@ struct AdvancedSettingsView: View { } .themedCanvas(theme) .environment(discovery) - .settingsSubpageDestinations(regions: discovery, requestRegionAdd: requestRegionAdd) + .settingsSubpageDestinations(regions: discovery, requestRegionAdd: requestRegionAdd, configImport: configImport) .sheet(isPresented: $showingImportKeySheet) { ImportKeySheet() } @@ -108,12 +111,19 @@ struct AdvancedSettingsView: View { discovery.noteRegionsChanged() } .onChange(of: appState.connectedDevice) { _, newDevice in - if newDevice == nil { - dismiss() - } + dismissAdvancedIfImportEnded(device: newDevice) + } + .onChange(of: appState.connectionManager.identityRebuildUnpublished) { _, _ in + dismissAdvancedIfImportEnded(device: appState.connectedDevice) } } + /// `identityRebuildUnpublished` is not a disconnect, so a nil device keeps this page. + private func dismissAdvancedIfImportEnded(device: DeviceDTO?) { + guard device == nil, !appState.connectionManager.identityRebuildUnpublished else { return } + dismiss() + } + /// Advanced and Manage Regions share one run. Another push, another tab, or another root cancels it. private var discoveryWorkflowActive: Bool { guard appState.navigation.selectedTab == AppTab.settings.rawValue, diff --git a/MC1/Views/Settings/BlocksAndFiltersSettingsView.swift b/MC1/Views/Settings/BlocksAndFiltersSettingsView.swift new file mode 100644 index 0000000000..86a0bc65ec --- /dev/null +++ b/MC1/Views/Settings/BlocksAndFiltersSettingsView.swift @@ -0,0 +1,136 @@ +import MC1Services +import SwiftUI + +struct BlocksAndFiltersSettingsView: View { + @Environment(\.appState) private var appState + @Environment(\.appTheme) private var theme + @State private var isAddingRule = false + @State private var inventory: [TextRulesPreference.Conversation] = [] + @State private var errorMessage: String? + + var body: some View { + let preference = appState.textRulesPreference + List { + BlockingSection() + rulesSection(preference?.rules) + + if let preference { + typesSection(preference) + } + } + .themedCanvas(theme) + .settingsSubpageDestinations() + .navigationTitle(L10n.Settings.BlocksAndFilters.title) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .primaryAction) { + Button(L10n.Settings.TextRules.New.title, systemImage: "plus") { + isAddingRule = true + } + .disabled(preference == nil) + } + } + .sheet(isPresented: $isAddingRule) { + NewTextRuleSheet() + } + .errorAlert($errorMessage) + .task { + do { + inventory = try await appState.connectionManager.persistenceStore.textRulesConversations() + } catch { + errorMessage = L10n.Localizable.Common.Error.failedToLoad + } + } + } + + private func rulesSection(_ rules: [TextRulesPreference.Rule]?) -> some View { + Section { + if let rules { + if rules.isEmpty { + Text(L10n.Settings.TextRules.empty) + .foregroundStyle(.secondary) + } + ForEach(rules) { rule in + VStack(alignment: .leading) { + Text(verbatim: rule.phrase) + Text(verbatim: rule.summary) + .font(.subheadline) + .foregroundStyle(.secondary) + } + .accessibilityElement(children: .combine) + .swipeActions { + Button(L10n.Localizable.Common.delete, systemImage: "trash", role: .destructive) { + delete(rule) + } + } + .accessibilityAction(named: Text(L10n.Localizable.Common.delete)) { + delete(rule) + } + } + } else { + TextRulesLoadNotice() + } + } header: { + Text(L10n.Settings.TextRules.rules) + } + .themedRowBackground(theme) + } + + private func typesSection(_ preference: TextRulesPreference) -> some View { + Section { + ForEach(TextRulesPreference.Kind.allCases, id: \.self) { kind in + let selection = preference.selection(for: kind) + Toggle(kind.title, isOn: Binding(get: { selection.isOn }, set: { isOn in + updatePreference { $0.setSelection(isOn ? .all : .off, for: kind) } + })) + if selection.isOn { + let value = summary(for: kind, selection: selection) + NavigationLink(value: SettingsSubpage.textRuleChats(kind)) { + LabeledContent(L10n.Settings.ChatSettings.title, value: value) + } + .accessibilityLabel(L10n.Settings.TextRules.Selection.accessibilityChats(kind.title)) + .accessibilityValue(Text(verbatim: value)) + } + } + } header: { + Text(L10n.Settings.TextRules.Types.header) + } footer: { + Text(L10n.Settings.TextRules.Types.footer) + } + .themedRowBackground(theme) + } + + private func summary(for kind: TextRulesPreference.Kind, selection: TextRulesPreference.Selection) -> String { + if selection == .all { return L10n.Settings.TextRules.Selection.all } + let names = inventory.filter { $0.kind == kind && selection.includes($0.key) }.map(\.name) + switch names.count { + case 0: return L10n.Settings.TextRules.Selection.none + case 1...2: return names.formatted(.list(type: .and)) + default: return L10n.Settings.TextRules.Selection.count(names.count) + } + } + + private func delete(_ rule: TextRulesPreference.Rule) { + updatePreference { $0.removeRule(id: rule.id) } + } + + private func updatePreference(_ update: (inout TextRulesPreference) -> Void) { + do { + try appState.connectionManager.updateTextRules(update) + } catch { + errorMessage = L10n.Settings.TextRules.saveFailed + } + } +} + +extension TextRulesPreference.Kind { + var title: String { + switch self { + case .publicChannel: L10n.Settings.TextRules.Types.publicChannel + case .hashtagChannel: L10n.Settings.TextRules.Types.hashtagChannel + case .privateChannel: L10n.Settings.TextRules.Types.privateChannel + case .directMessage: L10n.Settings.DirectMessages.header + case .room: L10n.Chats.Chats.Filter.rooms + } + } +} diff --git a/MC1/Views/Settings/ChatSettingsView.swift b/MC1/Views/Settings/ChatSettingsView.swift index 21f20f939a..07741593ed 100644 --- a/MC1/Views/Settings/ChatSettingsView.swift +++ b/MC1/Views/Settings/ChatSettingsView.swift @@ -19,10 +19,9 @@ struct ChatSettingsView: View { LinkPreviewSettingsSection() MapPreviewSettingsSection() MessagesSettingsSection() - BlockingSection() + RadioCleanupSection() } .themedCanvas(theme) - .settingsSubpageDestinations() .navigationTitle(L10n.Settings.ChatSettings.title) .navigationBarTitleDisplayMode(.inline) } diff --git a/MC1/Views/Settings/ConnectionSettingsView.swift b/MC1/Views/Settings/ConnectionSettingsView.swift index d719447cc4..d401f0c400 100644 --- a/MC1/Views/Settings/ConnectionSettingsView.swift +++ b/MC1/Views/Settings/ConnectionSettingsView.swift @@ -38,13 +38,7 @@ struct ConnectionSettingsView: View { settingsService: { appState.services?.settingsService }, connectionState: { appState.connectionState }, connectedDevice: { appState.connectedDevice }, - currentTransportType: { appState.connectionManager.currentTransportType }, - reboot: { - guard let settingsService = appState.services?.settingsService else { - throw SettingsServiceError.notConnected - } - try await settingsService.reboot() - } + currentTransportType: { appState.connectionManager.currentTransportType } ) await radioWiFi.noteSessionReadiness() } @@ -89,7 +83,8 @@ struct ConnectionSettingsView: View { private var radioWiFiRefreshID: RadioWiFiRefreshID { RadioWiFiRefreshID( service: (appState.services?.settingsService).map(ObjectIdentifier.init), - isReady: appState.connectionState == .ready + isReady: appState.connectionState == .ready, + settingsRevision: appState.radioWiFiSettingsRevision ) } @@ -106,6 +101,7 @@ struct ConnectionSettingsView: View { private struct RadioWiFiRefreshID: Equatable { var service: ObjectIdentifier? var isReady: Bool + var settingsRevision: UInt64 } } diff --git a/MC1/Views/Settings/ConnectionWiFiPage.swift b/MC1/Views/Settings/ConnectionWiFiPage.swift index d737f6b777..b01913aac7 100644 --- a/MC1/Views/Settings/ConnectionWiFiPage.swift +++ b/MC1/Views/Settings/ConnectionWiFiPage.swift @@ -26,7 +26,10 @@ struct ConnectionWiFiPage: View { .sheet(isPresented: $showingWiFiEditSheet) { WiFiEditSheet() } - .sheet(isPresented: $radioWiFi.editorOpen) { + .sheet(isPresented: Binding( + get: { radioWiFi.editorOpen }, + set: { if !$0 { Task { await radioWiFi.closeEditor() } } } + )) { RadioWiFiEditSheet(viewModel: radioWiFi) } } diff --git a/MC1/Views/Settings/DeviceInfoTelemetryViewModel.swift b/MC1/Views/Settings/DeviceInfoTelemetryViewModel.swift new file mode 100644 index 0000000000..941623ff9a --- /dev/null +++ b/MC1/Views/Settings/DeviceInfoTelemetryViewModel.swift @@ -0,0 +1,198 @@ +import MC1Services +import SwiftUI + +@Observable +@MainActor +final class DeviceInfoTelemetryViewModel: TelemetryDisclosurePresenting { + struct ReadyScope: Equatable { + let binaryProtocolService: BinaryProtocolService + let presentationRevision: Int + let rootNavigationGeneration: Int + + static func == (lhs: ReadyScope, rhs: ReadyScope) -> Bool { + lhs.binaryProtocolService === rhs.binaryProtocolService + && lhs.presentationRevision == rhs.presentationRevision + && lhs.rootNavigationGeneration == rhs.rootNavigationGeneration + } + } + + private(set) var telemetry: TelemetryResponse? + private(set) var cachedDataPoints: [LPPDataPoint] = [] + private(set) var isLoadingTelemetry = false + private(set) var telemetryLoaded = false + var telemetryExpanded = false + private(set) var telemetrySectionError: String? + private(set) var displayName: String? + private(set) var ocvValues: [Int] = [] + + var mapLabel: String? { + guard let displayName else { return nil } + let trimmed = displayName.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? nil : trimmed + } + + private var deviceProvider: (@MainActor () -> DeviceDTO?)? + private var readyScopeProvider: (@MainActor () -> ReadyScope?)? + private var nodeSnapshotServiceProvider: (@MainActor () -> NodeSnapshotService?)? + + private var device: DeviceDTO? { + deviceProvider?() + } + + private var readyScope: ReadyScope? { + readyScopeProvider?() + } + + private var nodeSnapshotService: NodeSnapshotService? { + nodeSnapshotServiceProvider?() + } + + private struct InflightRequest { + let token: UUID + let deviceID: UUID + let radioID: UUID + let publicKey: Data + let scope: ReadyScope + } + + private var requestToken: UUID? + private var boundDeviceID: UUID? + private var boundRadioID: UUID? + private var boundPublicKey: Data? + private var boundServiceIdentity: ObjectIdentifier? + private var boundPresentationRevision: Int? + private var boundRootNavigationGeneration: Int? + + func configure( + device: @escaping @MainActor () -> DeviceDTO?, + readyScope: @escaping @MainActor () -> ReadyScope?, + nodeSnapshotService: @escaping @MainActor () -> NodeSnapshotService? + ) { + deviceProvider = device + readyScopeProvider = readyScope + nodeSnapshotServiceProvider = nodeSnapshotService + } + + func synchronizePresentation() { + let currentDevice = device + let currentScope = readyScope + let serviceIdentity = currentScope.map { ObjectIdentifier($0.binaryProtocolService) } + displayName = currentDevice?.nodeName + ocvValues = currentDevice?.activeOCVArray ?? [] + let sameDevice = currentDevice?.id == boundDeviceID + && currentDevice?.radioID == boundRadioID + && currentDevice?.publicKey == boundPublicKey + let sameScope = serviceIdentity == boundServiceIdentity + && currentScope?.presentationRevision == boundPresentationRevision + && currentScope?.rootNavigationGeneration == boundRootNavigationGeneration + guard !sameDevice || !sameScope else { return } + + requestToken = nil + telemetry = nil + cachedDataPoints = [] + isLoadingTelemetry = false + telemetryLoaded = false + telemetrySectionError = nil + telemetryExpanded = false + boundDeviceID = currentDevice?.id + boundRadioID = currentDevice?.radioID + boundPublicKey = currentDevice?.publicKey + boundServiceIdentity = serviceIdentity + boundPresentationRevision = currentScope?.presentationRevision + boundRootNavigationGeneration = currentScope?.rootNavigationGeneration + } + + func loadTelemetry() async { + synchronizePresentation() + guard requestToken == nil, + let scope = readyScope, + let current = device, + current.publicKey.count == ProtocolLimits.publicKeySize else { return } + + let inflight = InflightRequest( + token: UUID(), + deviceID: current.id, + radioID: current.radioID, + publicKey: current.publicKey, + scope: scope + ) + requestToken = inflight.token + isLoadingTelemetry = true + telemetrySectionError = nil + await perform(inflight) + } + + func fetchHistory() async -> [NodeStatusSnapshotDTO] { + guard let service = nodeSnapshotService, + let current = device, + current.publicKey.count == ProtocolLimits.publicKeySize else { return [] } + return await service.fetchSelfTelemetry( + radioID: current.radioID, + nodePublicKey: current.publicKey + ) + } + + private func perform(_ inflight: InflightRequest) async { + do { + let response = try await inflight.scope.binaryProtocolService.getSelfTelemetry() + try Task.checkCancellation() + await apply(response, inflight: inflight) + } catch is CancellationError { + finish(inflight) + } catch { + guard stillCurrent(inflight) else { return } + telemetrySectionError = Self.message(for: error) + finish(inflight) + } + } + + private func apply(_ response: TelemetryResponse, inflight: InflightRequest) async { + guard stillCurrent(inflight) else { return } + guard let reading = TelemetryReading.accepted(from: response, expectedPublicKey: inflight.publicKey) else { + finish(inflight) + return + } + telemetry = response + cachedDataPoints = reading.dataPoints + telemetryLoaded = true + telemetrySectionError = nil + + let entries = reading.entries.isEmpty ? nil : reading.entries + if entries != nil || reading.location != nil, let service = nodeSnapshotService { + _ = await service.recordSelfTelemetry( + deviceID: inflight.deviceID, + radioID: inflight.radioID, + nodePublicKey: inflight.publicKey, + telemetry: entries, + location: reading.location + ) + } + finish(inflight) + } + + /// Recheck readiness because reconnect can retain the Device and service. + private func stillCurrent(_ inflight: InflightRequest) -> Bool { + guard requestToken == inflight.token, + readyScope == inflight.scope, + let current = device, + current.id == inflight.deviceID, + current.radioID == inflight.radioID, + current.publicKey == inflight.publicKey else { + return false + } + return true + } + + private func finish(_ inflight: InflightRequest) { + guard requestToken == inflight.token else { return } + requestToken = nil + isLoadingTelemetry = false + } + + private static func message(for error: Error) -> String { + if case BinaryProtocolError.sessionError(MeshCoreError.timeout) = error { + return L10n.Localizable.Error.MeshCore.timeout + } + return error.userFacingMessage + } +} diff --git a/MC1/Views/Settings/DeviceInfoView.swift b/MC1/Views/Settings/DeviceInfoView.swift index ea2d0cdc2f..c4b59fa901 100644 --- a/MC1/Views/Settings/DeviceInfoView.swift +++ b/MC1/Views/Settings/DeviceInfoView.swift @@ -19,6 +19,7 @@ struct DeviceInfoView: View { @State private var errorMessage: String? @State private var retryAlert = RetryAlertState() @State private var isSaving = false + @State private var telemetryModel = DeviceInfoTelemetryViewModel() var body: some View { List { @@ -79,26 +80,7 @@ struct DeviceInfoView: View { } .themedRowBackground(theme) - // Connection status - Section { - HStack { - Label( - L10n.Settings.DeviceInfo.Connection.status, - systemImage: "antenna.radiowaves.left.and.right" - ) - Spacer() - HStack(spacing: 4) { - Circle() - .fill(.green) - .frame(width: 8, height: 8) - Text(L10n.Settings.Device.connected) - .foregroundStyle(.secondary) - } - } - } header: { - Text(L10n.Settings.DeviceInfo.Connection.header) - } - .themedRowBackground(theme) + telemetrySection(for: device) // Battery and storage Section { @@ -213,13 +195,18 @@ struct DeviceInfoView: View { } } .themedCanvas(theme) - .settingsSubpageDestinations() + .settingsSubpageDestinations(deviceInfoTelemetry: telemetryModel) .navigationTitle(L10n.Settings.DeviceInfo.title) .errorAlert($errorMessage) .retryAlert(retryAlert) .refreshable { await appState.batteryMonitor.fetchDeviceBattery(services: appState.services, device: appState.connectedDevice) } + .onAppear { bindTelemetry() } + .onChange(of: telemetryPresentation) { _, _ in + // A child push can hide Device Info without invalidating its request. + telemetryModel.synchronizePresentation() + } .task { deviceInfoLogger.info("DeviceInfoView: appeared, connectedDevice=\(appState.connectedDevice != nil)") await appState.batteryMonitor.fetchDeviceBattery(services: appState.services, device: appState.connectedDevice) @@ -235,6 +222,71 @@ struct DeviceInfoView: View { } } + private struct TelemetryPresentation: Equatable { + let connectionReady: Bool + let showsDeviceInfo: Bool + let presentationRevision: Int + let rootNavigationGeneration: Int + let deviceID: UUID? + let radioID: UUID? + let publicKey: Data? + let nodeName: String? + let ocvValues: [Int] + let serviceIdentity: ObjectIdentifier? + } + + private var telemetryPresentation: TelemetryPresentation { + let device = appState.connectedDevice + return TelemetryPresentation( + connectionReady: appState.connectionState == .ready, + showsDeviceInfo: appState.navigation.selectedSetting == .deviceInfo, + presentationRevision: appState.navigation.settingsPresentationRevision, + rootNavigationGeneration: appState.navigation.settingsRootNavigationGeneration, + deviceID: device?.id, + radioID: device?.radioID, + publicKey: device?.publicKey, + nodeName: device?.nodeName, + ocvValues: device?.activeOCVArray ?? [], + serviceIdentity: appState.services.map { ObjectIdentifier($0.binaryProtocolService) } + ) + } + + private func telemetrySection(for device: DeviceDTO) -> some View { + NodeTelemetryDisclosureSection( + helper: telemetryModel, + connectionState: appState.connectionState, + historyRoute: SettingsSubpage.deviceInfoTelemetryHistory(publicKey: device.publicKey), + mapRoute: { fix in + SettingsSubpage.deviceInfoLocationMap( + publicKey: device.publicKey, + fix: fix, + name: telemetryModel.mapLabel + ) + }, + isDeviceInfo: true, + onRequestTelemetry: { await telemetryModel.loadTelemetry() } + ) + } + + private func bindTelemetry() { + let appState = appState + telemetryModel.configure( + device: { appState.connectedDevice }, + readyScope: { + guard appState.connectionState == .ready, + appState.navigation.selectedSetting == .deviceInfo, + let service = appState.services?.binaryProtocolService else { return nil } + return DeviceInfoTelemetryViewModel.ReadyScope( + binaryProtocolService: service, + presentationRevision: appState.navigation.settingsPresentationRevision, + rootNavigationGeneration: appState.navigation.settingsRootNavigationGeneration + ) + }, + nodeSnapshotService: { appState.services?.nodeSnapshotService } + ) + telemetryModel.synchronizePresentation() + } + /// Firmware reports storage in binary kilobytes. private static let bytesPerKilobyte = 1024 diff --git a/MC1/Views/Settings/DeviceSelectionSheet.swift b/MC1/Views/Settings/DeviceSelectionSheet.swift index 57454da8e3..8dedbef174 100644 --- a/MC1/Views/Settings/DeviceSelectionSheet.swift +++ b/MC1/Views/Settings/DeviceSelectionSheet.swift @@ -4,14 +4,8 @@ import SwiftUI private let logger = Logger(subsystem: "com.mc1", category: "DeviceSelectionSheet") -/// Filters saved `Device` rows to those the user can actually reach from this phone. -/// -/// A backup restore inserts "shadow" `Device` rows: their Bluetooth connection methods -/// were stripped by `cleanedForImport()` and their `id` is a fresh `UUID` that isn't -/// registered with AccessorySetupKit on this phone. Those rows stay in SwiftData so -/// `ConnectionManager.buildServicesAndSaveDevice` can reconcile them by `publicKey` -/// when the user later pairs the radio, but they must not appear in the picker until -/// then — they look like saved devices but no tap can connect them. +/// Includes only Device records reachable through this phone's connection methods. +/// Imported records remain available for public-key reconciliation until the radio is paired. enum DeviceSelectionFilter { static func isConnectable(_ device: DeviceDTO, pairedAccessoryIDs: Set, hasSystemPairingRegistry: Bool = true) -> Bool { if device.connectionMethods.contains(where: \.isWiFi) { return true } @@ -80,14 +74,16 @@ struct DeviceSelectionSheet: View { onConnect: { connectToDevice($0, target: $1) }, onDelete: { deleteDevice($0) }, onSetup: { setupAccessory($0) }, - onScanForNew: { scanForNewDevice() } + onScanForNew: { scanForNewDevice() }, + isRecoveringPairing: appState.isRecoveringPairing ) } private func makeEmptyStateView() -> some View { EmptyStateView( showingWiFiConnection: $showingWiFiConnection, - onScanForNew: { scanForNewDevice() } + onScanForNew: { scanForNewDevice() }, + isRecoveringPairing: appState.isRecoveringPairing ) } @@ -128,10 +124,8 @@ struct DeviceSelectionSheet: View { var connectedElsewhere: Set = [] for device in result.connectable { - if case let .bluetooth(peripheralID) = device.savedDeviceConnectTarget { - if await appState.connectionManager.isDeviceConnectedToOtherApp(peripheralID) { - connectedElsewhere.insert(device.id) - } + if case let .bluetooth(peripheralID) = device.savedDeviceConnectTarget, await appState.connectionManager.isDeviceConnectedToOtherApp(peripheralID) { + connectedElsewhere.insert(device.id) } } devicesConnectedElsewhere = connectedElsewhere @@ -186,6 +180,7 @@ private struct DeviceListView: View { let onDelete: (DeviceDTO) -> Void let onSetup: (SystemPairedAccessory) -> Void let onScanForNew: () -> Void + let isRecoveringPairing: Bool var body: some View { List { @@ -261,10 +256,14 @@ private struct DeviceListView: View { .themedRowBackground(theme) Section { - Button { - onScanForNew() - } label: { - Label(L10n.Settings.DeviceSelection.scanBluetooth, systemImage: "antenna.radiowaves.left.and.right") + if isRecoveringPairing { + PairingRecoveryStatus() + } else { + Button { + onScanForNew() + } label: { + Label(L10n.Settings.DeviceSelection.scanBluetooth, systemImage: "antenna.radiowaves.left.and.right") + } } Button { @@ -292,6 +291,7 @@ private struct DeviceListView: View { private struct EmptyStateView: View { @Binding var showingWiFiConnection: Bool let onScanForNew: () -> Void + let isRecoveringPairing: Bool var body: some View { ContentUnavailableView { @@ -301,13 +301,17 @@ private struct EmptyStateView: View { Text(L10n.Settings.DeviceSelection.noPairedDescription) VStack(spacing: 12) { - Button( - L10n.Settings.DeviceSelection.scanForDevices, - systemImage: "antenna.radiowaves.left.and.right" - ) { - onScanForNew() + if isRecoveringPairing { + PairingRecoveryStatus() + } else { + Button( + L10n.Settings.DeviceSelection.scanForDevices, + systemImage: "antenna.radiowaves.left.and.right" + ) { + onScanForNew() + } + .liquidGlassProminentButtonStyle() } - .liquidGlassProminentButtonStyle() Button(L10n.Settings.DeviceSelection.connectViaWifi, systemImage: "wifi.circle") { showingWiFiConnection = true diff --git a/MC1/Views/Settings/NodeConfig/NodeConfigImportRecoveryList.swift b/MC1/Views/Settings/NodeConfig/NodeConfigImportRecoveryList.swift new file mode 100644 index 0000000000..710ce6c698 --- /dev/null +++ b/MC1/Views/Settings/NodeConfig/NodeConfigImportRecoveryList.swift @@ -0,0 +1,55 @@ +import MC1Services +import SwiftUI + +struct NodeConfigImportRecoveryList: View { + @Environment(\.appTheme) private var theme + @Bindable var viewModel: NodeConfigImportViewModel + let recovery: IdentityImportRecovery + + var body: some View { + List { + Section { + Text(recovery.sourceName) + Text(recovery.targetDescription) + .font(.footnote) + if !viewModel.identityRecoveryComplete { + Label(L10n.Settings.ConfigImport.privateKeyWarning, systemImage: "exclamationmark.shield") + .foregroundStyle(.orange) + } + } + .themedRowBackground(theme) + + if viewModel.identityRecoveryComplete { + Section { + Label(L10n.Settings.ConfigImport.identityRecoveryComplete, systemImage: "checkmark.circle.fill") + } + .themedRowBackground(theme) + } else if viewModel.isApplying { + Section { + ProgressView() + Button(L10n.Localizable.Common.cancel, role: .cancel) { viewModel.cancelImport() } + } + .themedRowBackground(theme) + } else { + Section { + Button(L10n.Settings.ConfigImport.selectFile) { viewModel.showFilePicker = true } + .disabled(viewModel.isParsing) + if viewModel.isParsing { ProgressView() } + Button(L10n.Settings.ConfigImport.retryIdentityImport) { viewModel.prepareConfirmation() } + .disabled(viewModel.isParsing) + } + .themedRowBackground(theme) + } + + if let errorMessage = viewModel.errorMessage { + Section { + Label(errorMessage, systemImage: "exclamationmark.triangle") + .foregroundStyle(.red) + } + .themedRowBackground(theme) + } + } + .themedCanvas(theme) + .navigationTitle(L10n.Settings.ConfigImport.retryIdentityImport) + } +} diff --git a/MC1/Views/Settings/NodeConfig/NodeConfigImportState+Application.swift b/MC1/Views/Settings/NodeConfig/NodeConfigImportState+Application.swift new file mode 100644 index 0000000000..5caee800df --- /dev/null +++ b/MC1/Views/Settings/NodeConfig/NodeConfigImportState+Application.swift @@ -0,0 +1,10 @@ +import Foundation +import MC1Services + +extension NodeConfigImportState { + struct Application { + let id = UUID() + let confirmation: Confirmation + var progress: ImportProgress? + } +} diff --git a/MC1/Views/Settings/NodeConfig/NodeConfigImportState+Confirmation.swift b/MC1/Views/Settings/NodeConfig/NodeConfigImportState+Confirmation.swift new file mode 100644 index 0000000000..26561b2701 --- /dev/null +++ b/MC1/Views/Settings/NodeConfig/NodeConfigImportState+Confirmation.swift @@ -0,0 +1,21 @@ +import Foundation +import MC1Services + +extension NodeConfigImportState { + enum Confirmation { + case config(Preview) + case recovery(IdentityImportRecovery, input: Input, privateKey: Data) + + var input: Input { + switch self { + case let .config(preview): preview.input + case let .recovery(_, input, _): input + } + } + + var recovery: IdentityImportRecovery? { + guard case let .recovery(summary, _, _) = self else { return nil } + return summary + } + } +} diff --git a/MC1/Views/Settings/NodeConfig/NodeConfigImportState+Input.swift b/MC1/Views/Settings/NodeConfig/NodeConfigImportState+Input.swift new file mode 100644 index 0000000000..2371e36251 --- /dev/null +++ b/MC1/Views/Settings/NodeConfig/NodeConfigImportState+Input.swift @@ -0,0 +1,11 @@ +import Foundation +import MC1Services + +extension NodeConfigImportState { + struct Input { + let id: UUID + let config: MeshCoreNodeConfig + var source: NodeConfigImportViewModel.ImportSource? + var channelsWouldOverwrite = false + } +} diff --git a/MC1/Views/Settings/NodeConfig/NodeConfigImportState+Preview.swift b/MC1/Views/Settings/NodeConfig/NodeConfigImportState+Preview.swift new file mode 100644 index 0000000000..635a330189 --- /dev/null +++ b/MC1/Views/Settings/NodeConfig/NodeConfigImportState+Preview.swift @@ -0,0 +1,11 @@ +import Foundation +import MC1Services + +extension NodeConfigImportState { + struct Preview { + let id = UUID() + var input: Input + let source: NodeConfigImportViewModel.ImportSource + let sections: ConfigSections + } +} diff --git a/MC1/Views/Settings/NodeConfig/NodeConfigImportState.swift b/MC1/Views/Settings/NodeConfig/NodeConfigImportState.swift new file mode 100644 index 0000000000..fafa3b3b00 --- /dev/null +++ b/MC1/Views/Settings/NodeConfig/NodeConfigImportState.swift @@ -0,0 +1,50 @@ +import Foundation +import MC1Services + +enum NodeConfigImportState { + case selectingFile + case preview(Input) + case recovery(IdentityImportRecovery, input: Input?) + case preparing(Preview) + case confirming(Confirmation) + case applying(Application) + case completed(Application) + case failed(Application) + case interrupted(Application, IdentityImportRecovery) + + var input: Input? { + switch self { + case .selectingFile: nil + case let .preview(input), let .recovery(_, input?): input + case .recovery(_, nil): nil + case let .preparing(preview): preview.input + case let .confirming(confirmation): confirmation.input + case let .applying(application), let .completed(application), let .failed(application), let .interrupted(application, _): + application.confirmation.input + } + } + + var recovery: IdentityImportRecovery? { + switch self { + case let .recovery(summary, _), let .interrupted(_, summary): summary + case let .confirming(confirmation): confirmation.recovery + case let .applying(application), let .completed(application), let .failed(application): + application.confirmation.recovery + case .selectingFile, .preview, .preparing: nil + } + } + + var application: Application? { + switch self { + case let .applying(application), let .completed(application), let .failed(application), let .interrupted(application, _): + application + default: nil + } + } + + var editable: Self { + if let recovery { return .recovery(recovery, input: input) } + if let input { return .preview(input) } + return .selectingFile + } +} diff --git a/MC1/Views/Settings/NodeConfig/NodeConfigImportView.swift b/MC1/Views/Settings/NodeConfig/NodeConfigImportView.swift index 483d7c9dd2..8fb0fa5ed3 100644 --- a/MC1/Views/Settings/NodeConfig/NodeConfigImportView.swift +++ b/MC1/Views/Settings/NodeConfig/NodeConfigImportView.swift @@ -2,18 +2,19 @@ import MC1Services import SwiftUI struct NodeConfigImportView: View { - @Environment(\.appState) private var appState - @State private var viewModel = NodeConfigImportViewModel() + @Bindable var viewModel: NodeConfigImportViewModel var body: some View { Group { - if let config = viewModel.importedConfig { + if let recovery = viewModel.recovery { + NodeConfigImportRecoveryList(viewModel: viewModel, recovery: recovery) + } else if let config = viewModel.importedConfig { ImportPreviewList(viewModel: viewModel, config: config) } else { SelectFileList(viewModel: viewModel) } } - .navigationTitle(L10n.Settings.ConfigImport.title) + .navigationTitle(viewModel.recovery == nil ? L10n.Settings.ConfigImport.title : L10n.Settings.ConfigImport.retryIdentityImport) .onDisappear { viewModel.handleDismissal() } .fileImporter( isPresented: $viewModel.showFilePicker, @@ -22,7 +23,7 @@ struct NodeConfigImportView: View { switch result { case let .success(url): viewModel.parseFile(at: url) - Task { await viewModel.loadCurrentDeviceState(settingsService: appState.services?.settingsService) } + Task { await viewModel.loadCurrentDeviceState() } case let .failure(error): viewModel.errorMessage = error.userFacingMessage } @@ -31,16 +32,12 @@ struct NodeConfigImportView: View { viewModel.confirmTitle, isPresented: $viewModel.showConfirmation ) { - Button(viewModel.applyButtonLabel) { - viewModel.applyConfig( - nodeConfigService: appState.services?.nodeConfigService, - settingsService: appState.services?.settingsService, - radioID: appState.connectedDevice?.radioID - ) + Button(viewModel.applyButtonLabel, role: viewModel.confirmButtonRole) { + viewModel.applyConfig() } - Button(L10n.Localizable.Common.cancel, role: .cancel) {} + Button(L10n.Localizable.Common.cancel, role: .cancel) { viewModel.cancelConfirmation() } } message: { - Text(viewModel.confirmMessage(deviceName: appState.connectedDevice?.nodeName ?? L10n.Settings.ConfigImport.thisDevice)) + Text(viewModel.confirmMessage) } } } @@ -270,7 +267,6 @@ private struct ContactsSection: View { private struct ApplySection: View { @Environment(\.appTheme) private var theme - @Environment(\.appState) private var appState @Bindable var viewModel: NodeConfigImportViewModel var body: some View { @@ -287,7 +283,7 @@ private struct ApplySection: View { } } else if !viewModel.importComplete { Button(viewModel.applyButtonLabel) { - viewModel.prepareConfirmation(nodeConfigService: appState.services?.nodeConfigService) + viewModel.prepareConfirmation() } .disabled(viewModel.isPreparingConfirmation) } diff --git a/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+Application.swift b/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+Application.swift new file mode 100644 index 0000000000..0a4dcbb3f6 --- /dev/null +++ b/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+Application.swift @@ -0,0 +1,117 @@ +import Foundation +import MC1Services +import OSLog + +extension NodeConfigImportViewModel { + func prepareConfirmation() { + guard !isPreparingConfirmation, !isApplying, !isParsing else { return } + if recovery != nil { + prepareRecoveryConfirmation() + return + } + guard var input = state.input, let service = nodeConfigService, + let snapshot = connectionManager?.currentConnection, + connectedDevice?.id == snapshot.device.id else { return } + let source = ImportSource(snapshot) + guard input.source == nil || input.source == source else { return } + input.source = source + let preview = NodeConfigImportState.Preview(input: input, source: source, sections: sections) + state = .preparing(preview) + showConfirmation = false + errorMessage = nil + previewTask = Task { + defer { + if case let .preparing(current) = state, current.id == preview.id { state = .preview(input) } + } + do { + let result = try await service.previewImport(input.config, sections: preview.sections) + guard !Task.isCancelled, case let .preparing(current) = state, current.id == preview.id, + sections == preview.sections, + connectionManager?.isCurrent(generation: source.generation, requestID: source.requestID) == true else { return } + var confirmed = preview + confirmed.input.channelsWouldOverwrite = result.channelsOverwriteExisting + state = .confirming(.config(confirmed)) + showConfirmation = true + } catch is CancellationError { + return + } catch { + guard case let .preparing(current) = state, current.id == preview.id else { return } + errorMessage = error.userFacingMessage + logger.error("Import preview failed: \(error.localizedDescription)") + } + } + } + + func cancelConfirmation() { + if case .confirming = state { state = state.editable } + showConfirmation = false + } + + func applyConfig() { + guard let confirmation else { return } + cancelConfirmation() + switch confirmation { + case let .recovery(summary, input, key): + applyIdentityRecovery(summary, input: input, privateKey: key) + case let .config(preview): + guard inputID == preview.input.id, sections == preview.sections, + connectionManager?.isCurrent(generation: preview.source.generation, requestID: preview.source.requestID) == true, + let service = nodeConfigService else { return } + applyConfiguration(confirmation, preview: preview, service: service) + } + } + + private func applyConfiguration( + _ confirmation: NodeConfigImportState.Confirmation, preview: NodeConfigImportState.Preview, service: NodeConfigService + ) { + let application = NodeConfigImportState.Application(confirmation: confirmation) + state = .applying(application) + errorMessage = nil + importTask = Task { + let (progressStream, progressContinuation) = AsyncStream.makeStream(of: ImportProgress.self) + let consumer = Task { @MainActor in + for await progress in progressStream { + guard case var .applying(current) = state, current.id == application.id else { continue } + current.progress = progress + state = .applying(current) + } + } + do { + try await service.importConfig(preview.input.config, sections: preview.sections, radioID: preview.source.radioID) { + progressContinuation.yield($0) + } + progressContinuation.finish() + await consumer.value + if connectedDevice?.id == preview.source.deviceID, let settingsService { + try? await settingsService.refreshDeviceInfo() + } + guard case let .applying(current) = state, current.id == application.id else { return } + state = .completed(current) + try? await Task.sleep(for: Timing.resultDisplay) + guard !Task.isCancelled, case let .completed(current) = state, current.id == application.id else { return } + resetToFileSelection() + } catch { + progressContinuation.finish() + await consumer.value + guard case let .applying(current) = state, current.id == application.id else { return } + state = .failed(current) + if let interrupted = error as? IdentityImportRecoveryRequired { + retainInterruptedInput(interrupted.recovery, application: current) + } else if error is CancellationError { + errorMessage = Self.cancellationMessage(didApplyAnyWrite: didApplyAnyWrite) + } else { + errorMessage = Self.failureMessage(for: error, didApplyAnyWrite: didApplyAnyWrite) + logger.error("Import failed: \(error.localizedDescription)") + } + } + } + } + + func cancelImport() { + importTask?.cancel() + } + + private enum Timing { + static let resultDisplay: Duration = .seconds(1.5) + } +} diff --git a/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+FileInput.swift b/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+FileInput.swift new file mode 100644 index 0000000000..630af92af4 --- /dev/null +++ b/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+FileInput.swift @@ -0,0 +1,111 @@ +import Foundation +import MC1Services +import OSLog + +extension NodeConfigImportViewModel { + /// File reads can wait on iCloud Drive, so decoding stays off the main actor. + func parseFile(at url: URL) { + guard !isApplying else { return } + retireInputWork() + state = state.editable + errorMessage = nil + let taskID = UUID() + currentParseID = taskID + let selectedRecovery = recovery + let source = connectionManager?.currentConnection.map { ImportSource($0) } + let didAccessSecurityScope = url.startAccessingSecurityScopedResource() + parseTask = Task.detached(priority: .userInitiated) { [weak self, url, didAccessSecurityScope] in + defer { + if didAccessSecurityScope { url.stopAccessingSecurityScopedResource() } + } + do { + let data = try Data(contentsOf: url, options: .mappedIfSafe) + try Task.checkCancellation() + let config = try JSONDecoder().decode(MeshCoreNodeConfig.self, from: data) + try Task.checkCancellation() + await self?.applyParseSuccess(config, for: taskID, recovery: selectedRecovery, source: source) + } catch is CancellationError { + return + } catch { + await self?.applyParseFailure(error, for: taskID) + } + } + } + + private func applyParseSuccess( + _ config: MeshCoreNodeConfig, for taskID: UUID, recovery: IdentityImportRecovery?, source: ImportSource? + ) { + guard currentParseID == taskID, self.recovery?.receiptID == recovery?.receiptID else { return } + currentParseID = nil + acceptInput(config, source: source) + } + + func acceptInput(_ config: MeshCoreNodeConfig, source: ImportSource?) { + guard !isApplying else { return } + retireInputWork() + let input = NodeConfigImportState.Input(id: UUID(), config: config, source: source) + if let recovery { + state = .recovery(recovery, input: input) + } else { + state = .preview(input) + } + errorMessage = nil + sections.nodeIdentity = config.name != nil || config.publicKey != nil || config.privateKey != nil + sections.radioSettings = config.radioSettings != nil + sections.positionSettings = config.positionSettings != nil && !(config.positionSettings?.isZero ?? true) + sections.otherSettings = config.otherSettings != nil + sections.channels = config.channels != nil + sections.contacts = config.contacts != nil + } + + private func applyParseFailure(_ error: Error, for taskID: UUID) { + guard currentParseID == taskID else { return } + currentParseID = nil + errorMessage = error.userFacingMessage + logger.error("Failed to parse config: \(error.localizedDescription)") + } + + func loadCurrentDeviceState() async { + guard recovery == nil, let settingsService, + let source = connectionManager?.currentConnection else { return } + do { + let info = try await settingsService.getSelfInfo() + guard connectionManager?.isCurrent(source) == true else { return } + currentName = info.name + currentRadio = NodeConfigService.buildRadioSettings(from: info) + currentPosition = MeshCoreNodeConfig.PositionSettings(latitude: String(info.latitude), longitude: String(info.longitude)) + } catch { + logger.error("Failed to load device state: \(error.localizedDescription)") + } + } + + func handleDismissal() { + retireInputWork() + showFilePicker = false + guard !isApplying else { return } + if let inputReceiptID, + connectionManager?.identityImportRecoveries.contains(where: { $0.receiptID == inputReceiptID }) == true { + return + } + resetToFileSelection() + } + + func retireInputWork() { + currentParseID = nil + parseTask?.cancel() + if case .preparing = state { state = state.editable } + previewTask?.cancel() + cancelConfirmation() + } + + func resetToFileSelection() { + guard !isApplying else { return } + retireInputWork() + state = .selectingFile + errorMessage = nil + sections = ConfigSections() + currentName = nil + currentRadio = nil + currentPosition = nil + } +} diff --git a/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+Presentation.swift b/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+Presentation.swift new file mode 100644 index 0000000000..3a3037e1b0 --- /dev/null +++ b/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+Presentation.swift @@ -0,0 +1,144 @@ +import MC1Services +import SwiftUI + +extension NodeConfigImportViewModel { + var importedConfig: MeshCoreNodeConfig? { + state.input?.config + } + + var inputID: UUID? { + state.input?.id + } + + var inputSource: ImportSource? { + state.input?.source + } + + var inputReceiptID: UUID? { + state.input == nil ? nil : recovery?.receiptID + } + + var recovery: IdentityImportRecovery? { + state.recovery + } + + var isParsing: Bool { + currentParseID != nil + } + + var isPreparingConfirmation: Bool { + if case .preparing = state { return true } + return false + } + + var isApplying: Bool { + if case .applying = state { return true } + return false + } + + var importComplete: Bool { + if case .completed = state { return recovery == nil } + return false + } + + var identityRecoveryComplete: Bool { + if case .completed = state { return recovery != nil } + return false + } + + var confirmation: NodeConfigImportState.Confirmation? { + guard case let .confirming(confirmation) = state else { return nil } + return confirmation + } + + var didApplyAnyWrite: Bool { + state.application?.progress != nil + } + + var applyProgress: Double { + guard let progress = state.application?.progress else { return 0 } + return Double(progress.current) / Double(max(1, progress.total)) + } + + var applyStepDescription: String { + state.application?.progress.map { Self.description(for: $0.step) } ?? "" + } + + private var hasOverwriteSections: Bool { + let selectedSections: ConfigSections = if case let .config(preview) = confirmation { + preview.sections + } else { + sections + } + return selectedSections.radioSettings || selectedSections.nodeIdentity || selectedSections.positionSettings + || selectedSections.otherSettings || (selectedSections.channels && state.input?.channelsWouldOverwrite == true) + } + + private var hasAdditiveSections: Bool { + if case let .config(preview) = confirmation { + return preview.sections.channels || preview.sections.contacts + } + return sections.channels || sections.contacts + } + + var confirmTitle: String { + if recovery != nil { return L10n.Settings.ConfigImport.confirmTitleIdentityRecovery } + switch (hasOverwriteSections, hasAdditiveSections) { + case (false, true): return L10n.Settings.ConfigImport.confirmTitleAdd + case (true, false): return L10n.Settings.ConfigImport.confirmTitleOverwrite + default: return L10n.Settings.ConfigImport.confirmTitle + } + } + + var confirmButtonRole: ButtonRole? { + recovery == nil ? nil : .destructive + } + + /// The recovery sheet stays up while the identity write is in flight, so its result stays visible. + var recoverySheetDismissalDisabled: Bool { + recovery != nil && isApplying + } + + var applyButtonLabel: String { + if recovery != nil { return L10n.Settings.ConfigImport.retryIdentityImport } + switch (hasOverwriteSections, hasAdditiveSections) { + case (false, true): return L10n.Settings.ConfigImport.applyButtonAdd + case (true, false): return L10n.Settings.ConfigImport.applyButtonOverwrite + default: return L10n.Settings.ConfigImport.applyButton + } + } + + var confirmMessage: String { + if case let .recovery(summary, _, _) = confirmation { + return L10n.Settings.ConfigImport.confirmIdentityRecovery("\(summary.sourceName) (\(summary.targetDescription))") + } + guard case let .config(preview) = confirmation else { return "" } + switch (hasOverwriteSections, hasAdditiveSections) { + case (false, true): return L10n.Settings.ConfigImport.confirmMessageAdd(preview.source.name) + case (true, false): return L10n.Settings.ConfigImport.confirmMessageOverwrite(preview.source.name) + case (true, true): return L10n.Settings.ConfigImport.confirmMessageMixed(preview.source.name) + default: return L10n.Settings.ConfigImport.confirmMessage(preview.source.name) + } + } + + static func description(for step: ImportStep) -> String { + switch step { + case .position: L10n.Settings.ConfigImport.stepPosition + case .otherParameters: L10n.Settings.ConfigImport.stepOtherParameters + case .privateKey: L10n.Settings.ConfigImport.stepPrivateKey + case .nodeName: L10n.Settings.ConfigImport.stepNodeName + case .radioParameters: L10n.Settings.ConfigImport.stepRadioParameters + case .txPower: L10n.Settings.ConfigImport.stepTxPower + case let .channel(name): L10n.Settings.ConfigImport.stepChannel(name) + case let .contact(name): L10n.Settings.ConfigImport.stepContact(name) + } + } + + static func cancellationMessage(didApplyAnyWrite: Bool) -> String { + didApplyAnyWrite ? L10n.Settings.ConfigImport.cancelledPartial : L10n.Settings.ConfigImport.cancelled + } + + static func failureMessage(for error: Error, didApplyAnyWrite: Bool) -> String { + didApplyAnyWrite ? L10n.Settings.ConfigImport.failedPartial(error.userFacingMessage) : error.userFacingMessage + } +} diff --git a/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+Recovery.swift b/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+Recovery.swift new file mode 100644 index 0000000000..bb56572fd6 --- /dev/null +++ b/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+Recovery.swift @@ -0,0 +1,82 @@ +import Foundation +import MC1Services + +extension NodeConfigImportViewModel { + func beginImport() { + guard !isApplying else { return } + let source = connectionManager?.currentConnection.map { ImportSource($0) } + if recovery != nil || inputSource != source { + resetToFileSelection() + } + } + + @discardableResult + func beginRecovery(_ summary: IdentityImportRecovery) -> Bool { + guard !isApplying, let current = connectionManager?.prepareIdentityImportRecovery(receiptID: summary.receiptID) else { + return false + } + retireInputWork() + if inputReceiptID != current.receiptID { + resetToFileSelection() + } + state = .recovery(current, input: state.input) + errorMessage = L10n.Settings.ConfigImport.identityOutcomeUnknown(current.sourceName) + return true + } + + func prepareRecoveryConfirmation() { + guard let recovery, let manager = connectionManager, + let current = manager.prepareIdentityImportRecovery(receiptID: recovery.receiptID) else { return } + guard inputReceiptID == current.receiptID, let input = state.input, let key = validatedRecoveryKey else { + errorMessage = L10n.Settings.ConfigImport.identityRecoveryKeyRequired + showFilePicker = true + return + } + state = .confirming(.recovery(current, input: input, privateKey: key)) + showConfirmation = true + } + + var validatedRecoveryKey: Data? { + guard let hex = importedConfig?.privateKey, hex.allSatisfy(\.isHexDigit), + let key = Data(hexString: hex), key.count == ProtocolLimits.privateKeySize else { return nil } + return key + } + + func applyIdentityRecovery(_ summary: IdentityImportRecovery, input: NodeConfigImportState.Input, privateKey: Data) { + guard inputID == input.id, inputReceiptID == summary.receiptID, let manager = connectionManager, + manager.prepareIdentityImportRecovery(receiptID: summary.receiptID) == summary else { return } + let application = NodeConfigImportState.Application(confirmation: .recovery(summary, input: input, privateKey: privateKey)) + state = .applying(application) + errorMessage = nil + importTask = Task { + do { + let result = try await manager.retryIdentityImport(confirmation: summary, privateKey: privateKey) + guard case let .applying(current) = state, current.id == application.id else { return } + if case .operational = result, manager.isCurrent(result) { + state = .completed(current) + } else { + state = .failed(current) + if manager.identityImportRecoveries.contains(where: { $0.receiptID == summary.receiptID }) { + errorMessage = L10n.Settings.ConfigImport.identityOutcomeUnknown(summary.sourceName) + } + } + } catch { + guard case let .applying(current) = state, current.id == application.id else { return } + state = .failed(current) + if let interrupted = error as? IdentityImportRecoveryRequired { + retainInterruptedInput(interrupted.recovery, application: current) + } else if error is CancellationError { + errorMessage = L10n.Settings.ConfigImport.identityOutcomeUnknown(summary.sourceName) + } else { + errorMessage = error.userFacingMessage + } + } + } + } + + func retainInterruptedInput(_ summary: IdentityImportRecovery, application: NodeConfigImportState.Application) { + guard inputID == application.confirmation.input.id else { return } + state = .interrupted(application, summary) + errorMessage = L10n.Settings.ConfigImport.identityOutcomeUnknown(summary.sourceName) + } +} diff --git a/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel.swift b/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel.swift index 3e4c30b886..a56a551ca1 100644 --- a/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel.swift +++ b/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel.swift @@ -5,314 +5,63 @@ import SwiftUI @Observable @MainActor final class NodeConfigImportViewModel { - // Parse state - var importedConfig: MeshCoreNodeConfig? + struct ImportSource: Equatable, Sendable { + let generation: UUID + let requestID: UUID + let deviceID: UUID + let radioID: UUID + let name: String + + @MainActor + init(_ snapshot: ConnectionSnapshot) { + generation = snapshot.generation + requestID = snapshot.requestID + deviceID = snapshot.device.id + radioID = snapshot.device.radioID + name = snapshot.device.nodeName + } + } + + var state: NodeConfigImportState = .selectingFile var errorMessage: String? var showFilePicker = false - var isParsing = false - - /// Section selection + // Alert dismissal can precede its action; apply and cancel consume the confirmation payload. + var showConfirmation = false var sections = ConfigSections() - - // Current device state for diff var currentName: String? var currentRadio: MeshCoreNodeConfig.RadioSettings? var currentPosition: MeshCoreNodeConfig.PositionSettings? - - // Apply state - var isApplying = false - var applyProgress: Double = 0 - var applyStepDescription = "" - var importComplete = false - var showConfirmation = false - var isPreparingConfirmation = false - - /// Set from a non-destructive ``NodeConfigService/previewImport(_:sections:)`` pass before the - /// confirmation alert. True when at least one selected channel would replace an already-configured - /// slot, so the channels section is not purely additive and the confirmation copy must say so. - private var channelsWouldOverwrite = false - - /// True once the import has reported progress, i.e. at least one destructive write reached the - /// device. Distinguishes "cancelled before anything changed" from "cancelled mid-write." - private var didApplyAnyWrite = false - - private var importTask: Task? - - /// Handle for the in-flight file parse, plus the ID guard that lets a newer parse - /// (or a dismissal) invalidate a stale result that raced past cancellation. - private var parseTask: Task? - private var currentParseID: UUID? - - /// Handle for the in-flight preview, which does a real BLE round-trip via `previewImport`. - /// Stored so it can be cancelled if the user leaves the screen or supersedes it. - private var previewTask: Task? - - private let logger = Logger(subsystem: "com.mc1", category: "NodeConfigImportVM") - - // MARK: - Dynamic confirmation text - - private var hasOverwriteSections: Bool { - sections.radioSettings || sections.nodeIdentity || sections.positionSettings - || sections.otherSettings || (sections.channels && channelsWouldOverwrite) - } - - private var hasAdditiveSections: Bool { - sections.channels || sections.contacts - } - - var confirmTitle: String { - switch (hasOverwriteSections, hasAdditiveSections) { - case (false, true): L10n.Settings.ConfigImport.confirmTitleAdd - case (true, false): L10n.Settings.ConfigImport.confirmTitleOverwrite - default: L10n.Settings.ConfigImport.confirmTitle - } - } - - var applyButtonLabel: String { - switch (hasOverwriteSections, hasAdditiveSections) { - case (false, true): L10n.Settings.ConfigImport.applyButtonAdd - case (true, false): L10n.Settings.ConfigImport.applyButtonOverwrite - default: L10n.Settings.ConfigImport.applyButton - } - } - - func confirmMessage(deviceName: String) -> String { - switch (hasOverwriteSections, hasAdditiveSections) { - case (false, true): L10n.Settings.ConfigImport.confirmMessageAdd(deviceName) - case (true, false): L10n.Settings.ConfigImport.confirmMessageOverwrite(deviceName) - case (true, true): L10n.Settings.ConfigImport.confirmMessageMixed(deviceName) - default: L10n.Settings.ConfigImport.confirmMessage(deviceName) - } - } - - /// Parse a JSON file from a security-scoped URL. The read and decode run detached - /// because the URL can point at an undownloaded iCloud Drive file, where a - /// synchronous read on the main actor blocks the UI for the whole download. - func parseFile(at url: URL) { - parseTask?.cancel() - isParsing = true - errorMessage = nil - let taskID = UUID() - currentParseID = taskID - let didAccessSecurityScope = url.startAccessingSecurityScopedResource() - - parseTask = Task.detached(priority: .userInitiated) { [weak self, url, didAccessSecurityScope] in - defer { - if didAccessSecurityScope { - url.stopAccessingSecurityScopedResource() - } - } - do { - // .mappedIfSafe lets the OS page-cache the read rather than - // copying the whole file into the heap. - let data = try Data(contentsOf: url, options: .mappedIfSafe) - try Task.checkCancellation() - let config = try JSONDecoder().decode(MeshCoreNodeConfig.self, from: data) - try Task.checkCancellation() - await self?.applyParseSuccess(config, for: taskID) - } catch is CancellationError { - // The new invocation or the dismissal owns the parse state; don't clobber it. - return - } catch { - await self?.applyParseFailure(error, for: taskID) - } - } - } - - private func applyParseSuccess(_ config: MeshCoreNodeConfig, for taskID: UUID) { - guard currentParseID == taskID else { return } - isParsing = false - importedConfig = config - errorMessage = nil - - // Auto-select only sections present in the file - sections.nodeIdentity = config.name != nil || config.publicKey != nil || config.privateKey != nil - sections.radioSettings = config.radioSettings != nil - sections.positionSettings = config.positionSettings != nil && !(config.positionSettings?.isZero ?? true) - sections.otherSettings = config.otherSettings != nil - sections.channels = config.channels != nil - sections.contacts = config.contacts != nil - } - - private func applyParseFailure(_ error: Error, for taskID: UUID) { - guard currentParseID == taskID else { return } - isParsing = false - errorMessage = error.userFacingMessage - logger.error("Failed to parse config: \(error.localizedDescription)") - } - - /// Load current device values for diff display. A nil service mirrors a disconnected state. - func loadCurrentDeviceState(settingsService: SettingsService?) async { - guard let settingsService else { return } - do { - let selfInfo = try await settingsService.getSelfInfo() - currentName = selfInfo.name - currentRadio = NodeConfigService.buildRadioSettings(from: selfInfo) - currentPosition = MeshCoreNodeConfig.PositionSettings( - latitude: String(selfInfo.latitude), - longitude: String(selfInfo.longitude) - ) - } catch { - logger.error("Failed to load device state: \(error.localizedDescription)") - } - } - - /// Runs the non-destructive planner to classify the import (overwrite vs additive) and reject a - /// malformed config up front, then presents the confirmation alert. Surfacing a planner error here - /// means a poison file is caught before the user even confirms, and before any write. - func prepareConfirmation(nodeConfigService: NodeConfigService?) { - guard !isPreparingConfirmation, !isApplying else { return } - guard let config = importedConfig, - let service = nodeConfigService else { return } - - errorMessage = nil - isPreparingConfirmation = true - previewTask = Task { - defer { isPreparingConfirmation = false } - do { - let preview = try await service.previewImport(config, sections: sections) - // If the user left the screen while the round-trip was in flight, the dismissal has - // already reset the UI; presenting the confirmation now would pop an alert over a - // stale, off-screen state, so honour the cancellation even when the BLE call won the - // race and returned before observing it. - guard !Task.isCancelled else { return } - channelsWouldOverwrite = preview.channelsOverwriteExisting - errorMessage = nil - showConfirmation = true - } catch is CancellationError { - // The user left the screen mid-preview — leave the UI untouched. - } catch { - errorMessage = error.userFacingMessage - logger.error("Import preview failed: \(error.localizedDescription)") - } - } - } - - /// Apply the imported config to the device. Nil parameters mirror a disconnected state. - func applyConfig(nodeConfigService: NodeConfigService?, settingsService: SettingsService?, radioID: UUID?) { - guard !isApplying else { return } - guard let config = importedConfig, - let service = nodeConfigService, - let radioID else { return } - - isApplying = true - applyProgress = 0 - errorMessage = nil - importComplete = false - didApplyAnyWrite = false - - importTask = Task { - // Deliver progress through one stream consumed in order on the main actor, so updates - // can't race or arrive out of sequence the way a per-update `Task { @MainActor }` would. - let (progressStream, progressContinuation) = AsyncStream.makeStream(of: ImportProgress.self) - let consumer = Task { @MainActor in - for await progress in progressStream { - didApplyAnyWrite = true - applyProgress = Double(progress.current) / Double(max(1, progress.total)) - applyStepDescription = Self.description(for: progress.step) - } - } - - do { - try await service.importConfig( - config, - sections: sections, - radioID: radioID - ) { progress in - progressContinuation.yield(progress) - } - progressContinuation.finish() - await consumer.value - // Refresh cached device state so Settings UI reflects imported values - if let settingsService { - try? await settingsService.refreshDeviceInfo() - } - isApplying = false - importComplete = true - try? await Task.sleep(for: .seconds(1.5)) - guard !Task.isCancelled else { return } - resetToFileSelection() - } catch is CancellationError { - progressContinuation.finish() - await consumer.value - isApplying = false - // "No progress reported" means no destructive write landed, so the device is untouched. - errorMessage = Self.cancellationMessage(didApplyAnyWrite: didApplyAnyWrite) - } catch { - progressContinuation.finish() - await consumer.value - isApplying = false - errorMessage = Self.failureMessage(for: error, didApplyAnyWrite: didApplyAnyWrite) - logger.error("Import failed: \(error.localizedDescription)") - } - } - } - - func cancelImport() { - importTask?.cancel() - } - - /// Called when the screen goes away. Cancels any pending preview round-trip and, unless a - /// destructive import is in flight, resets back to the file picker so re-entering the screen - /// starts fresh instead of re-showing a stale preview or error. An in-flight import is left - /// running with its progress state intact: it is a destructive, safety-critical operation with - /// its own explicit cancel control, so a transient view disappearance must neither abort it - /// mid-write nor hide its result from a user who returns. - func handleDismissal() { - parseTask?.cancel() - currentParseID = nil - previewTask?.cancel() - guard !isApplying else { return } - resetToFileSelection() - } - - /// Maps a service-layer ``ImportStep`` to a localized progress description, keeping `L10n` - /// in the app layer so the service stays localization-free. - private static func description(for step: ImportStep) -> String { - switch step { - case .position: L10n.Settings.ConfigImport.stepPosition - case .otherParameters: L10n.Settings.ConfigImport.stepOtherParameters - case .privateKey: L10n.Settings.ConfigImport.stepPrivateKey - case .nodeName: L10n.Settings.ConfigImport.stepNodeName - case .radioParameters: L10n.Settings.ConfigImport.stepRadioParameters - case .txPower: L10n.Settings.ConfigImport.stepTxPower - case let .channel(name): L10n.Settings.ConfigImport.stepChannel(name) - case let .contact(name): L10n.Settings.ConfigImport.stepContact(name) - } - } - - /// Localized message for a cancelled import; distinguishes a clean cancel from one where a - /// destructive write already landed on the device. - static func cancellationMessage(didApplyAnyWrite: Bool) -> String { - didApplyAnyWrite - ? L10n.Settings.ConfigImport.cancelledPartial - : L10n.Settings.ConfigImport.cancelled - } - - /// Localized message for a failed import; distinguishes a clean failure from one where a - /// destructive write already landed. - static func failureMessage(for error: Error, didApplyAnyWrite: Bool) -> String { - didApplyAnyWrite - ? L10n.Settings.ConfigImport.failedPartial(error.userFacingMessage) - : error.userFacingMessage - } - - /// Reset to the initial file-selection state so the user can import another file. - private func resetToFileSelection() { - importedConfig = nil - errorMessage = nil - isParsing = false - sections = ConfigSections() - currentName = nil - currentRadio = nil - currentPosition = nil - applyProgress = 0 - applyStepDescription = "" - importComplete = false - isApplying = false - isPreparingConfirmation = false - showConfirmation = false - channelsWouldOverwrite = false - didApplyAnyWrite = false + var importTask: Task? + var parseTask: Task? + var currentParseID: UUID? + var previewTask: Task? + var connectionManager: ConnectionManager? + let logger = Logger(subsystem: "com.mc1", category: "NodeConfigImportVM") + + private var nodeConfigServiceProvider: @MainActor () -> NodeConfigService? = { nil } + private var settingsServiceProvider: @MainActor () -> SettingsService? = { nil } + private var connectedDeviceProvider: @MainActor () -> DeviceDTO? = { nil } + var nodeConfigService: NodeConfigService? { + nodeConfigServiceProvider() + } + + var settingsService: SettingsService? { + settingsServiceProvider() + } + + var connectedDevice: DeviceDTO? { + connectedDeviceProvider() + } + + func configure( + nodeConfigService: @escaping @MainActor () -> NodeConfigService?, + settingsService: @escaping @MainActor () -> SettingsService?, + connectedDevice: @escaping @MainActor () -> DeviceDTO?, + connectionManager: ConnectionManager + ) { + nodeConfigServiceProvider = nodeConfigService + settingsServiceProvider = settingsService + connectedDeviceProvider = connectedDevice + self.connectionManager = connectionManager } } diff --git a/MC1/Views/Settings/PresetLocationPolicy.swift b/MC1/Views/Settings/PresetLocationPolicy.swift index 9b0c62bac9..b4670a24c5 100644 --- a/MC1/Views/Settings/PresetLocationPolicy.swift +++ b/MC1/Views/Settings/PresetLocationPolicy.swift @@ -57,13 +57,13 @@ enum PresetLocationPolicy { static func useMyLocationAction(status: CLAuthorizationStatus) -> UseMyLocationAction { switch status { case .authorizedWhenInUse, .authorizedAlways: - return .resolve + .resolve case .notDetermined: - return .waitForAuthorization + .waitForAuthorization case .denied, .restricted: - return .openSettings + .openSettings @unknown default: - return .openSettings + .openSettings } } @@ -72,13 +72,13 @@ enum PresetLocationPolicy { ) -> AfterAuthorizationWait { switch status { case .authorizedWhenInUse, .authorizedAlways: - return .resolve + .resolve case .denied, .restricted: - return .openSettings + .openSettings case .notDetermined: - return .none + .none @unknown default: - return .openSettings + .openSettings } } diff --git a/MC1/Views/Settings/Sections/BlockingSection.swift b/MC1/Views/Settings/Sections/BlockingSection.swift index 6fa72ba518..57af729850 100644 --- a/MC1/Views/Settings/Sections/BlockingSection.swift +++ b/MC1/Views/Settings/Sections/BlockingSection.swift @@ -1,12 +1,32 @@ import MC1Services import SwiftUI -/// Settings section for managing blocked channel users and contacts. struct BlockingSection: View { @Environment(\.appTheme) private var theme + @Environment(\.appState) private var appState + @State private var recentlyBlockedCount: Int? var body: some View { Section { + NavigationLink(value: SettingsSubpage.recentlyBlocked) { + HStack { + TintedLabel(L10n.Settings.TextRules.Archive.title, systemImage: "tray") + Spacer() + if let recentlyBlockedCount { + Text(recentlyBlockedCount, format: .number) + .foregroundStyle(.secondary) + } + } + } + .task { + let store = appState.connectionManager.persistenceStore + let changes = store.recentlyBlockedUpdates() + await refreshRecentlyBlockedCount(from: store) + for await _ in changes { + await refreshRecentlyBlockedCount(from: store) + } + } + NavigationLink(value: SettingsSubpage.blockedChannelSenders) { TintedLabel(L10n.Settings.Blocking.channelSenders, systemImage: "person.crop.circle.badge.xmark") } @@ -19,4 +39,10 @@ struct BlockingSection: View { } .themedRowBackground(theme) } + + private func refreshRecentlyBlockedCount(from store: PersistenceStore) async { + if let count = try? await store.recentlyBlockedCount() { + recentlyBlockedCount = count + } + } } diff --git a/MC1/Views/Settings/Sections/DangerZoneSection.swift b/MC1/Views/Settings/Sections/DangerZoneSection.swift index b093309168..e5a21096b9 100644 --- a/MC1/Views/Settings/Sections/DangerZoneSection.swift +++ b/MC1/Views/Settings/Sections/DangerZoneSection.swift @@ -35,6 +35,21 @@ struct DangerZoneSection: View { } label: { Label(L10n.Settings.DangerZone.forgetDevice, systemImage: "trash") } + .confirmationDialog( + L10n.Settings.DangerZone.Dialog.Forget.title, + isPresented: $viewModel.showingForgetConfirmation, + titleVisibility: .visible + ) { + Button(L10n.Settings.DangerZone.Dialog.Forget.keepData, role: .destructive) { + forgetDevice(deleteData: false) + } + Button(L10n.Settings.DangerZone.Dialog.Forget.deleteAll, role: .destructive) { + forgetDevice(deleteData: true) + } + Button(L10n.Localizable.Common.cancel, role: .cancel) {} + } message: { + Text(L10n.Settings.DangerZone.Dialog.Forget.message) + } Button(role: .destructive) { viewModel.showingResetAlert = true @@ -62,21 +77,6 @@ struct DangerZoneSection: View { connectionManager: appState.connectionManager ) } - .confirmationDialog( - L10n.Settings.DangerZone.Dialog.Forget.title, - isPresented: $viewModel.showingForgetConfirmation, - titleVisibility: .visible - ) { - Button(L10n.Settings.DangerZone.Dialog.Forget.keepData, role: .destructive) { - forgetDevice(deleteData: false) - } - Button(L10n.Settings.DangerZone.Dialog.Forget.deleteAll, role: .destructive) { - forgetDevice(deleteData: true) - } - Button(L10n.Localizable.Common.cancel, role: .cancel) {} - } message: { - Text(L10n.Settings.DangerZone.Dialog.Forget.message) - } .alert(L10n.Settings.DangerZone.Alert.Reset.title, isPresented: $viewModel.showingResetAlert) { Button(L10n.Localizable.Common.cancel, role: .cancel) {} Button(L10n.Settings.DangerZone.Alert.Reset.confirm, role: .destructive) { diff --git a/MC1/Views/Settings/Sections/DangerZoneViewModel.swift b/MC1/Views/Settings/Sections/DangerZoneViewModel.swift index 5d0977d68b..9a44a4f190 100644 --- a/MC1/Views/Settings/Sections/DangerZoneViewModel.swift +++ b/MC1/Views/Settings/Sections/DangerZoneViewModel.swift @@ -16,6 +16,7 @@ final class DangerZoneViewModel { var removeResult: String? private var removeTask: Task? + private var removalOperationID: UUID? // MARK: - Dependencies @@ -31,8 +32,6 @@ final class DangerZoneViewModel { private var connectionManager: ConnectionManager? - /// Grace period for the radio to reboot after a factory reset before local cleanup. - private static let resetRebootGracePeriod: Duration = .seconds(1) /// How long the transient "Removed" confirmation stays on the button label. private static let removeSuccessDisplayDuration: Duration = .seconds(1.5) @@ -52,14 +51,18 @@ final class DangerZoneViewModel { /// Returns true when the device was forgotten and the hosting page should dismiss. func forgetDevice(deleteData: Bool) async -> Bool { - guard let connectionManager else { return false } + guard let connectionManager, let context = connectionManager.captureCurrentRemoval() else { return false } + let operationID = UUID() + removalOperationID = operationID + defer { if removalOperationID == operationID { removalOperationID = nil } } do { - try await connectionManager.forgetDevice(deleteData: deleteData) - return true - } catch DevicePairingError.cancelled { + let result = try await connectionManager.forgetDevice(context, deleteData: deleteData) + guard removalOperationID == operationID, case let .removed(receipt) = result else { return false } + return connectionManager.isCurrent(receipt) + } catch is CancellationError { return false } catch { - errorMessage = error.userFacingMessage + if removalOperationID == operationID { errorMessage = error.userFacingMessage } return false } } @@ -67,28 +70,34 @@ final class DangerZoneViewModel { /// Returns true when the reset flow finished and the hosting page should dismiss. /// A nil service or device ID mirrors a disconnected state. func factoryReset() async -> Bool { - guard let settingsService, - let deviceID = connectedDevice?.id, - let connectionManager else { + guard settingsService != nil, + connectedDevice != nil, + let connectionManager, + let context = connectionManager.captureCurrentRemoval() else { errorMessage = L10n.Settings.DangerZone.Error.servicesUnavailable return false } + let operationID = UUID() + removalOperationID = operationID isResetting = true - defer { isResetting = false } + defer { + if removalOperationID == operationID { + isResetting = false + removalOperationID = nil + } + } - // Send reset command. The device typically reboots before responding, - // so a timeout/connection error here is expected, not a failure. do { - try await settingsService.factoryReset() - try await Task.sleep(for: Self.resetRebootGracePeriod) + let result = try await connectionManager.factoryResetAndEraseRadio(context) + guard removalOperationID == operationID, case let .removed(receipt) = result else { return false } + return connectionManager.isCurrent(receipt) + } catch is CancellationError { + return false } catch { - // Expected: device reboots before sending OK response + if removalOperationID == operationID { errorMessage = error.userFacingMessage } + return false } - - // Always clean up: remove from ASK, disconnect, delete from SwiftData - await connectionManager.forgetDevice(id: deviceID) - return true } func fetchUnfavoritedCount() async { diff --git a/MC1/Views/Settings/Sections/DiagnosticsSection.swift b/MC1/Views/Settings/Sections/DiagnosticsSection.swift index b2d47ca363..b552306499 100644 --- a/MC1/Views/Settings/Sections/DiagnosticsSection.swift +++ b/MC1/Views/Settings/Sections/DiagnosticsSection.swift @@ -7,34 +7,57 @@ struct DiagnosticsSection: View { @Environment(\.appTheme) private var theme @Binding var exportedFile: ExportedLogFile? let isSidebar: Bool + @AppStorage(AppStorageKey.collectDebugLogs.rawValue) private var collectLogs = false @State private var isExporting = false @State private var showingClearLogsAlert = false - @State private var errorMessage: String? + @State private var showingDisableCollectionAlert = false + @State private var presentedErrorMessage: String? + /// Same text as `presentedErrorMessage`, kept here so it stays readable after `disableCollection(using:)` suspends. + private let errorRecord = ErrorRecord() + + var errorMessage: String? { + errorRecord.text + } + + @MainActor + private final class ErrorRecord { + var text: String? + } var body: some View { Section { - Button { - exportLogs() - } label: { - HStack { - TintedLabel(L10n.Settings.Diagnostics.exportLogs, systemImage: "square.and.arrow.up") - Spacer() - if isExporting { - ProgressView() + Toggle(isOn: collectionBinding) { + TintedLabel(L10n.Settings.Diagnostics.collectLogs, systemImage: "doc.text.magnifyingglass") + } + + if collectLogs { + Button { + exportLogs() + } label: { + HStack { + TintedLabel(L10n.Settings.Diagnostics.exportLogs, systemImage: "square.and.arrow.up") + Spacer() + if isExporting { + ProgressView() + } } } - } - .disabled(isExporting) + .disabled(isExporting) - Button(role: .destructive) { - showingClearLogsAlert = true - } label: { - Label(L10n.Settings.Diagnostics.clearLogs, systemImage: "trash") + Button(role: .destructive) { + showingClearLogsAlert = true + } label: { + Label(L10n.Settings.Diagnostics.clearLogs, systemImage: "trash") + } } } header: { Text(L10n.Settings.Diagnostics.header) } footer: { - Text(L10n.Settings.Diagnostics.footer) + if collectLogs { + Text(L10n.Settings.Diagnostics.footer) + } else { + Text(L10n.Settings.Diagnostics.Footer.disabled) + } } .themedRowBackground(theme, flatten: isSidebar) .alert(L10n.Settings.Diagnostics.Alert.Clear.title, isPresented: $showingClearLogsAlert) { @@ -45,7 +68,48 @@ struct DiagnosticsSection: View { } message: { Text(L10n.Settings.Diagnostics.Alert.Clear.message) } - .errorAlert($errorMessage) + .alert(L10n.Settings.Diagnostics.Alert.Disable.title, isPresented: $showingDisableCollectionAlert) { + Button(L10n.Localizable.Common.cancel, role: .cancel) {} + Button(L10n.Settings.Diagnostics.Alert.Disable.confirm, role: .destructive) { + let dataStore = appState.connectionManager.persistenceStore + Task { await disableCollection(using: dataStore) } + } + } message: { + Text(L10n.Settings.Diagnostics.Alert.Disable.message) + } + .errorAlert($presentedErrorMessage) + } + + /// Off raises the confirm alert and does not write the key. On calls `enableCollection`, which leaves the key false while a disable is in progress. + private var collectionBinding: Binding { + Binding( + get: { collectLogs }, + set: { setCollectionEnabled($0) } + ) + } + + func setCollectionEnabled(_ isOn: Bool) { + if isOn { + DebugLogBuffer.enableCollection() + } else { + showingDisableCollectionAlert = true + } + } + + /// On success the key is already false. On throw, turns it back on and sets `errorMessage`. + func disableCollection(using dataStore: any DebugLogPersisting) async { + let record = errorRecord + do { + try await DebugLogBuffer.disableCollection(persistenceStore: dataStore) + } catch { + collectLogs = true + setErrorMessage(error.userFacingMessage, record: record) + } + } + + private func setErrorMessage(_ message: String, record: ErrorRecord) { + record.text = message + presentedErrorMessage = message } private func exportLogs() { @@ -59,7 +123,7 @@ struct DiagnosticsSection: View { ) { exportedFile = ExportedLogFile(url: url) } else { - errorMessage = L10n.Settings.Diagnostics.Error.exportFailed + setErrorMessage(L10n.Settings.Diagnostics.Error.exportFailed, record: errorRecord) } isExporting = false } @@ -72,7 +136,7 @@ struct DiagnosticsSection: View { do { try await dataStore.clearDebugLogEntries() } catch { - errorMessage = error.userFacingMessage + setErrorMessage(error.userFacingMessage, record: errorRecord) } } } diff --git a/MC1/Views/Settings/Sections/DirectMessagesSettingsSection.swift b/MC1/Views/Settings/Sections/DirectMessagesSettingsSection.swift index 88b389c9cf..ca396f0da9 100644 --- a/MC1/Views/Settings/Sections/DirectMessagesSettingsSection.swift +++ b/MC1/Views/Settings/Sections/DirectMessagesSettingsSection.swift @@ -1,11 +1,14 @@ import MC1Services import SwiftUI -/// Settings section for direct message acknowledgment count struct DirectMessagesSettingsSection: View { @Environment(\.appState) private var appState @Environment(\.appTheme) private var theme @Environment(\.dismiss) private var dismiss + @AppStorage(AppStorageKey.dmDirectAttempts.rawValue) + private var storedDirectAttempts = AppStorageKey.defaultDMDirectAttempts + @AppStorage(AppStorageKey.dmFloodAttempts.rawValue) + private var storedFloodAttempts = AppStorageKey.defaultDMFloodAttempts @State private var errorMessage: String? @State private var retryAlert = RetryAlertState() @State private var isSaving = false @@ -14,7 +17,40 @@ struct DirectMessagesSettingsSection: View { appState.connectedDevice } + private var fallsBackToFlood: Bool { + storedFloodAttempts > 0 + } + var body: some View { + Section { + Toggle(L10n.Settings.DirectMessages.fallback, isOn: fallbackBinding) + + Picker(L10n.Settings.DirectMessages.directAttempts, selection: directAttemptsBinding) { + ForEach(Array(DMSendBudget.directRange), id: \.self) { count in + Text(String(count)).tag(count) + } + } + .pickerStyle(.menu) + + if fallsBackToFlood { + Picker(L10n.Settings.DirectMessages.floodAttempts, selection: floodAttemptsBinding) { + ForEach(Array(DMSendBudget.enabledFloodRange), id: \.self) { count in + Text(String(count)).tag(count) + } + } + .pickerStyle(.menu) + } + } header: { + Text(L10n.Settings.DirectMessages.header) + } footer: { + Text( + fallsBackToFlood + ? L10n.Settings.DirectMessages.attemptsFooterOn + : L10n.Settings.DirectMessages.attemptsFooterOff + ) + } + .themedRowBackground(theme) + Section { Picker(L10n.Settings.DirectMessages.acknowledgments, selection: acksBinding) { Text("1").tag(1) @@ -22,8 +58,6 @@ struct DirectMessagesSettingsSection: View { } .pickerStyle(.menu) .radioDisabled(for: appState.connectionState, or: isSaving) - } header: { - Text(L10n.Settings.DirectMessages.header) } footer: { Text(L10n.Settings.DirectMessages.footer) } @@ -34,6 +68,32 @@ struct DirectMessagesSettingsSection: View { // MARK: - Binding + private var fallbackBinding: Binding { + Binding( + get: { fallsBackToFlood }, + set: { isOn in + storedFloodAttempts = DMSendBudget.floodAttempts( + enablingFallback: isOn, + stored: storedFloodAttempts + ) + } + ) + } + + private var directAttemptsBinding: Binding { + Binding( + get: { DMSendBudget.clampedDirectAttempts(storedDirectAttempts) }, + set: { storedDirectAttempts = DMSendBudget.clampedDirectAttempts($0) } + ) + } + + private var floodAttemptsBinding: Binding { + Binding( + get: { DMSendBudget.menuFloodAttempts(stored: storedFloodAttempts) }, + set: { storedFloodAttempts = DMSendBudget.clampedMenuFloodAttempts($0) } + ) + } + private var acksBinding: Binding { Binding( get: { Int(device?.multiAcks ?? 0) + 1 }, diff --git a/MC1/Views/Settings/Sections/NewTextRuleSheet.swift b/MC1/Views/Settings/Sections/NewTextRuleSheet.swift new file mode 100644 index 0000000000..2335e8b9ab --- /dev/null +++ b/MC1/Views/Settings/Sections/NewTextRuleSheet.swift @@ -0,0 +1,109 @@ +import MC1Services +import SwiftUI + +struct NewTextRuleSheet: View { + @Environment(\.appState) private var appState + @Environment(\.appTheme) private var theme + @Environment(\.dismiss) private var dismiss + @State private var phrase = "" + @State private var lookIn = TextRulesPreference.Rule.LookIn.message + @State private var match = TextRulesPreference.Rule.Match.contains + @State private var errorMessage: String? + + private var trimmedPhrase: String { + phrase.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private var ruleFooter: String { + switch (lookIn, match) { + case (.message, .contains): + L10n.Settings.TextRules.New.containsMessageFooter + case (.message, .wholeField): + L10n.Settings.TextRules.New.wholeMessageFooter + case (.sender, .contains): + L10n.Settings.TextRules.New.containsSenderFooter + case (.sender, .wholeField): + L10n.Settings.TextRules.New.wholeNameFooter + case (.messageOrSender, .contains): + L10n.Settings.TextRules.New.containsMessageOrSenderFooter + case (.messageOrSender, .wholeField): + L10n.Settings.TextRules.New.wholeMessageOrSenderFooter + } + } + + var body: some View { + NavigationStack { + Form { + Section { + TextField(L10n.Settings.TextRules.New.phrase, text: $phrase, axis: .vertical) + Picker(L10n.Settings.TextRules.New.lookIn, selection: $lookIn) { + ForEach(TextRulesPreference.Rule.LookIn.allCases, id: \.self) { field in + Text(field.title).tag(field) + } + } + .pickerStyle(.menu) + Picker(L10n.Settings.TextRules.New.match, selection: $match) { + ForEach(TextRulesPreference.Rule.Match.allCases, id: \.self) { mode in + Text(mode.title(for: lookIn)).tag(mode) + } + } + .pickerStyle(.menu) + } footer: { + Text(ruleFooter) + } + .themedRowBackground(theme) + } + .themedCanvas(theme) + .navigationTitle(L10n.Settings.TextRules.New.title) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button(L10n.Localizable.Common.cancel) { dismiss() } + } + ToolbarItem(placement: .confirmationAction) { + Button(L10n.Contacts.Contacts.Add.add, action: add) + .disabled(trimmedPhrase.isEmpty) + } + } + .errorAlert($errorMessage) + } + } + + private func add() { + let rule = TextRulesPreference.Rule(phrase: trimmedPhrase, lookIn: lookIn, match: match) + guard rule.isValid else { return } + do { + try appState.connectionManager.updateTextRules { $0.append(rule) } + dismiss() + } catch { + errorMessage = L10n.Settings.TextRules.saveFailed + } + } +} + +extension TextRulesPreference.Rule.LookIn { + var title: String { + switch self { + case .message: L10n.Settings.TextRules.Field.message + case .sender: L10n.Settings.TextRules.Field.sender + case .messageOrSender: L10n.Settings.TextRules.Field.messageOrSender + } + } +} + +extension TextRulesPreference.Rule.Match { + func title(for field: TextRulesPreference.Rule.LookIn) -> String { + switch (self, field) { + case (.contains, _): L10n.Settings.TextRules.Match.contains + case (.wholeField, .message): L10n.Settings.TextRules.Match.wholeMessage + case (.wholeField, .sender): L10n.Settings.TextRules.Match.wholeName + case (.wholeField, .messageOrSender): L10n.Settings.TextRules.Match.wholeField + } + } +} + +extension TextRulesPreference.Rule { + var summary: String { + L10n.Settings.TextRules.ruleSummary(match.title(for: lookIn), lookIn.title) + } +} diff --git a/MC1/Views/Settings/Sections/NotificationSettingsSection.swift b/MC1/Views/Settings/Sections/NotificationSettingsSection.swift index 06906e9149..ec516ec38a 100644 --- a/MC1/Views/Settings/Sections/NotificationSettingsSection.swift +++ b/MC1/Views/Settings/Sections/NotificationSettingsSection.swift @@ -62,7 +62,7 @@ struct NotificationSettingsSection: View { } if preferences.newContactDiscoveredEnabled { Toggle(isOn: $preferences.discoveryContactEnabled) { - TintedLabel(L10n.Settings.Notifications.discoveryContact, systemImage: "person") + TintedLabel(L10n.Settings.Notifications.discoveryCompanionsAndSensors, systemImage: "person") } .listRowInsets(EdgeInsets(top: 0, leading: 52, bottom: 0, trailing: 20)) Toggle(isOn: $preferences.discoveryRepeaterEnabled) { diff --git a/MC1/Views/Settings/Sections/PathFallbackSettingsSection.swift b/MC1/Views/Settings/Sections/PathFallbackSettingsSection.swift new file mode 100644 index 0000000000..90f58e748f --- /dev/null +++ b/MC1/Views/Settings/Sections/PathFallbackSettingsSection.swift @@ -0,0 +1,23 @@ +import MC1Services +import SwiftUI + +struct PathFallbackSettingsSection: View { + @Environment(\.appTheme) private var theme + @AppStorage(AppStorageKey.remoteFloodFallback.rawValue) + private var remoteFloodFallback = AppStorageKey.defaultRemoteFloodFallback + + var body: some View { + Section { + Toggle(L10n.Settings.PathFallback.fallback, isOn: $remoteFloodFallback) + } header: { + Text(L10n.Settings.PathFallback.header) + } footer: { + Text( + remoteFloodFallback + ? L10n.Settings.PathFallback.footerOn + : L10n.Settings.PathFallback.footerOff + ) + } + .themedRowBackground(theme) + } +} diff --git a/MC1/Views/Settings/Sections/RadioCleanupSection.swift b/MC1/Views/Settings/Sections/RadioCleanupSection.swift new file mode 100644 index 0000000000..3c6d0797df --- /dev/null +++ b/MC1/Views/Settings/Sections/RadioCleanupSection.swift @@ -0,0 +1,43 @@ +import MC1Services +import SwiftUI + +struct RadioCleanupSection: View { + @Environment(\.appState) private var appState + @Environment(\.appTheme) private var theme + + private typealias Strings = L10n.Settings.RadioCleanup + + private var operations: [ConnectionManager.RadioCleanup] { + appState.connectionManager.radioCleanup.values.sorted { + $0.target.radioName.localizedStandardCompare($1.target.radioName) == .orderedAscending + } + } + + var body: some View { + if !operations.isEmpty { + Section(Strings.title) { + ForEach(operations) { operation in + VStack(alignment: .leading) { + Text(operation.target.radioName) + .font(.headline) + switch operation.state { + case .running: + ProgressView(Strings.running) + case .failed: + Text(Strings.failed) + .foregroundStyle(.secondary) + Button(L10n.Localizable.Common.tryAgain) { + appState.connectionManager.retryRadioErase(operation.target) + } + .accessibilityLabel(Strings.retryAccessibility(operation.target.radioName)) + case .completed: + Text(Strings.completed) + .foregroundStyle(.secondary) + } + } + } + } + .themedRowBackground(theme) + } + } +} diff --git a/MC1/Views/Settings/Sections/RadioWiFiEditSheet.swift b/MC1/Views/Settings/Sections/RadioWiFiEditSheet.swift index 3a10a47bab..47719099e8 100644 --- a/MC1/Views/Settings/Sections/RadioWiFiEditSheet.swift +++ b/MC1/Views/Settings/Sections/RadioWiFiEditSheet.swift @@ -14,6 +14,11 @@ struct RadioWiFiEditSheet: View { .autocorrectionDisabled() .disabled(viewModel.isBusy) passwordField + if viewModel.needsEditorRead, !viewModel.isBusy { + Button(L10n.Localizable.Common.tryAgain) { + Task { await viewModel.loadEditor() } + } + } } footer: { Text(viewModel.editorFooter) } @@ -24,7 +29,7 @@ struct RadioWiFiEditSheet: View { .toolbar { ToolbarItem(placement: .cancellationAction) { Button(L10n.Localizable.Common.cancel) { - viewModel.editorOpen = false + Task { await viewModel.closeEditor() } } .disabled(viewModel.isWriting) } @@ -44,12 +49,12 @@ struct RadioWiFiEditSheet: View { viewModel.cancelWiFiWarning() } Button(viewModel.linkWarningConfirmTitle) { - Task { await viewModel.continuePastWiFiWarning() } + viewModel.confirmFromAlert(.wifiWarning) } } message: { Text(L10n.Settings.RadioWiFi.Alert.WifiTransport.message) } - .errorAlert($viewModel.errorMessage) + .errorAlert($viewModel.errorMessage, retryAction: { Task { await viewModel.loadEditor() } }) .interactiveDismissDisabled(viewModel.isWriting) } } diff --git a/MC1/Views/Settings/Sections/RadioWiFiSection.swift b/MC1/Views/Settings/Sections/RadioWiFiSection.swift index 6b23a0ea0c..dec5abc35c 100644 --- a/MC1/Views/Settings/Sections/RadioWiFiSection.swift +++ b/MC1/Views/Settings/Sections/RadioWiFiSection.swift @@ -25,12 +25,12 @@ struct RadioWiFiSection: View { } Button { - viewModel.editorOpen = true + viewModel.openEditor() } label: { HStack { Text(L10n.Settings.RadioWiFi.network) Spacer() - Text(viewModel.networkName ?? L10n.Settings.RadioWiFi.Network.notSet) + Text(viewModel.networkValue) .foregroundStyle(.secondary) Image(systemName: "chevron.right") .font(.caption) @@ -42,9 +42,7 @@ struct RadioWiFiSection: View { LabeledContent( L10n.Settings.RadioWiFi.status, - value: viewModel.statusConnected - ? L10n.Settings.RadioWiFi.Status.connected - : L10n.Settings.RadioWiFi.Status.notConnected + value: viewModel.statusValue ) if let ipAddress = viewModel.ipAddress { @@ -73,7 +71,7 @@ struct RadioWiFiSection: View { viewModel.cancelWiFiWarning() } Button(viewModel.linkWarningConfirmTitle) { - Task { await viewModel.continuePastWiFiWarning() } + viewModel.confirmFromAlert(.wifiWarning) } } message: { Text(L10n.Settings.RadioWiFi.Alert.WifiTransport.message) @@ -81,7 +79,7 @@ struct RadioWiFiSection: View { .alert(L10n.Settings.RadioWiFi.Alert.Clear.title, isPresented: $viewModel.showingClearConfirm) { Button(L10n.Localizable.Common.cancel, role: .cancel) {} Button(L10n.Settings.RadioWiFi.clear, role: .destructive) { - Task { await viewModel.confirmClear() } + viewModel.confirmFromAlert(.clear) } } message: { Text(viewModel.clearMessage) @@ -91,7 +89,7 @@ struct RadioWiFiSection: View { viewModel.cancelReboot() } Button(L10n.Settings.DeviceActions.Alert.Reboot.confirm) { - Task { await viewModel.confirmReboot() } + viewModel.confirmFromAlert(.reboot) } } message: { Text(viewModel.rebootMessage) diff --git a/MC1/Views/Settings/Sections/RadioWiFiViewModel+Editor.swift b/MC1/Views/Settings/Sections/RadioWiFiViewModel+Editor.swift new file mode 100644 index 0000000000..4331d6c1cd --- /dev/null +++ b/MC1/Views/Settings/Sections/RadioWiFiViewModel+Editor.swift @@ -0,0 +1,131 @@ +import Foundation +import MC1Services + +extension RadioWiFiViewModel { + func ensureEditor() { + guard editor == nil else { return } + editor = Editor(id: UUID(), ssid: networkName ?? "") + } + + func openEditor() { + guard canEditNetwork else { return } + ensureEditor() + setEditorPresented(true) + } + + func closeEditor() async { + let editorID = editor?.id + let owner = context + editor = nil + confirmation = nil + setEditorPresented(false) + if let editorID, let owner, matches(owner), let settings = settingsService { + await settings.closeRadioWiFiEditor(editorID: editorID) + } + await drainOwedRead() + } + + func loadEditor() async { + guard !isBusy else { return } + adoptCurrentContext() + guard let owner = context, matches(owner), let settings = settingsService else { return } + ensureEditor() + guard let editorID = editor?.id else { return } + let id = UUID() + operation = .editor(id, owner, editorID) + editor?.baseline = nil + do { + let baseline = try await settings.readRadioWiFiCredentials( + editorID: editorID, expectedContextID: owner.wifiContextID + ) + guard matches(owner), editor?.id == editorID, operation?.id == id else { + finish(id) + await drainOwedRead() + return + } + if let baseline { + editor?.baseline = baseline + if editor?.ssidEdited == false { editor?.ssid = baseline.ssid } + if editor?.passwordEdited == false { editor?.password = baseline.password } + observation.networkName = baseline.ssid.isEmpty ? nil : baseline.ssid + observation.networkRevision = baseline.revision + observation.networkNameIsCurrent = true + errorMessage = nil + } + } catch is CancellationError { + // A cancelled or superseded read cannot confer credential knowledge. + } catch { + if matches(owner), editor?.id == editorID { errorMessage = error.userFacingMessage } + } + finish(id) + await drainOwedRead() + } + + func requestSave() async { + guard canSave, let owner = context, let editor, let baseline = editor.baseline else { return } + let submission = Submission(owner: owner, baseline: baseline, ssid: editor.ssid, password: editor.password) + if currentTransportType == .wifi { + confirmation = .save(submission) + } else { + await performSave(submission) + } + } + + func performSave(_ submission: Submission) async { + guard canRunCommands, matches(submission.owner), editor?.id == submission.baseline.editorID, + let settings = settingsService else { return } + let id = UUID() + operation = .write(id, submission.owner) + do { + let receipt = try await settings.saveRadioWiFiCredentials( + ssid: submission.ssid, + password: submission.password, + baseline: submission.baseline, + editorID: submission.baseline.editorID, + ownerIsCurrent: { [weak self] in + guard let self else { return false } + return self.matches(submission.owner) + && self.editor?.id == submission.baseline.editorID + && self.operation?.id == id + } + ) + if matches(submission.owner), editor?.id == submission.baseline.editorID { + if receipt.contextID == submission.owner.wifiContextID, let revision = receipt.revision, + settings.radioWiFiState.stableRevision() == revision { + if receipt.ssidAccepted || !receipt.uncertain { + adoptMutationRevision(from: submission.baseline.revision, to: revision) + } else { + if observation.enabledRevision == submission.baseline.revision { observation.enabledRevision = revision } + observation.networkNameIsCurrent = false + } + if receipt.ssidAccepted { + observation.networkName = submission.ssid + observation.networkRevision = revision + observation.networkNameIsCurrent = true + } + } else { + if receipt.ssidAccepted, observation.networkRevision == submission.baseline.revision { + observation.networkName = submission.ssid + observation.networkRevision = nil + observation.networkNameIsCurrent = false + } + oweRead(submission.owner) + } + editor?.baseline = receipt.updatedBaseline + if let error = receipt.error { + if !(error is CancellationError) { errorMessage = error.userFacingMessage } + } else if receipt.revision != nil { + await closeEditor() + } + } + } catch is CancellationError { + if matches(submission.owner), editor?.id == submission.baseline.editorID { + editor?.baseline = nil + } + } catch { + if matches(submission.owner) { errorMessage = error.userFacingMessage } + } + finish(id) + await drainOwedRead() + } +} diff --git a/MC1/Views/Settings/Sections/RadioWiFiViewModel+Observation.swift b/MC1/Views/Settings/Sections/RadioWiFiViewModel+Observation.swift new file mode 100644 index 0000000000..d6d0009896 --- /dev/null +++ b/MC1/Views/Settings/Sections/RadioWiFiViewModel+Observation.swift @@ -0,0 +1,147 @@ +import Foundation +import MC1Services + +extension RadioWiFiViewModel { + func noteSessionReadiness() async { + adoptCurrentContext() + guard connectionState == .ready, let context, matchesContext(context) else { + clearAssociation() + owedRead = nil + if settingsService == nil { + editor = nil + setEditorPresented(false) + confirmation = nil + } + return + } + oweRead(context) + await drainOwedRead() + } + + func refresh() async { + await noteSessionReadiness() + } + + func load() async { + guard !isBusy else { return } + await noteSessionReadiness() + } + + func adoptCurrentContext() { + guard let radioID = connectedDevice?.radioID, let settingsService else { return } + let binding = settingsService.radioWiFiBinding + let current = Context( + radioID: radioID, serviceID: ObjectIdentifier(settingsService), wifiContextID: binding.contextID + ) + guard current != context else { return } + context = current + enabledContext = nil + observation = ObservedWiFiState() + setSupport(.unknown) + owedRead = nil + confirmation = nil + editor = nil + setEditorPresented(false) + errorMessage = nil + } + + func drainOwedRead() async { + guard !editorOpen, !isBusy, owedRead != nil, connectionState == .ready else { return } + if let refreshTask { + await refreshTask.value + return + } + let id = UUID() + refreshTaskID = id + let task = Task { + while !self.editorOpen, !self.isBusy, let debt = self.owedRead, self.matches(debt.owner) { + let owner = debt.owner + self.owedRead = nil + let operationID = UUID() + self.operation = .snapshot(operationID, owner) + await self.performSnapshot(owner: owner) + self.finish(operationID) + } + if self.refreshTaskID == id { + self.refreshTaskID = nil + self.refreshTask = nil + } + } + refreshTask = task + await task.value + } + + func performSnapshot(owner: Context) async { + guard matches(owner), let settings = settingsService else { return } + guard connectedDevice?.supportsRadioCLI == true else { + setSupport(.unknown) + enabledContext = nil + return + } + do { + let capability = try await settings.probeRadioWiFiSettings(expectedContextID: owner.wifiContextID) + guard matches(owner) else { return } + switch capability { + case .unavailable: + setSupport(.unavailable) + enabledContext = nil + observation = ObservedWiFiState() + errorMessage = nil + case .busy: + clearAssociation() + case let .supported(probe): + guard settings.radioWiFiState.stableRevision() == probe.revision else { + oweRead(owner) + return + } + setSupport(.supported) + enabledContext = owner + observation.enabled = probe.enabled + observation.enabledRevision = probe.revision + observation.networkNameIsCurrent = false + clearAssociation() + let result = await settings.readRadioWiFiObservation(probe: probe) + guard matches(owner) else { return } + guard let result, settings.radioWiFiState.stableRevision() == result.revision else { + if let revision = settings.radioWiFiState.stableRevision(), revision != probe.revision { oweRead(owner) } + return + } + apply(result) + if let error = result.error { + if !(error is CancellationError) { errorMessage = error.userFacingMessage } + } else { + errorMessage = nil + } + } + } catch is CancellationError { + // The owner task survives cancellation of a view waiting for this snapshot. + } catch { + guard matches(owner) else { return } + clearAssociation() + errorMessage = error.userFacingMessage + } + } + + func apply(_ result: RadioWiFiReadResult) { + guard context?.wifiContextID == result.contextID, context?.radioID == result.radioID else { return } + observation.enabled = result.enabled + observation.enabledRevision = result.revision + if result.networkNameWasRead { + observation.networkName = result.networkName + observation.networkRevision = result.revision + observation.networkNameIsCurrent = true + } + if let associated = result.associated { observation.associated = associated } + if result.ipAddressWasRead { observation.ipAddress = result.ipAddress } + } + + func clearAssociation() { + observation.associated = nil + observation.ipAddress = nil + } + + func adoptMutationRevision(from baseline: UInt64, to revision: UInt64) { + if observation.enabledRevision == baseline { observation.enabledRevision = revision } + if observation.networkRevision == baseline { observation.networkRevision = revision } + } +} diff --git a/MC1/Views/Settings/Sections/RadioWiFiViewModel+Operations.swift b/MC1/Views/Settings/Sections/RadioWiFiViewModel+Operations.swift new file mode 100644 index 0000000000..2f5596ab1a --- /dev/null +++ b/MC1/Views/Settings/Sections/RadioWiFiViewModel+Operations.swift @@ -0,0 +1,153 @@ +import Foundation +import MC1Services + +extension RadioWiFiViewModel { + @discardableResult + func confirmFromAlert(_ action: AlertAction) -> Task { + let captured: Confirmation? + switch (action, confirmation) { + case (.wifiWarning, .save), (.wifiWarning, .disable), (.clear, .clear), (.reboot, .reboot): + captured = confirmation + confirmation = nil + default: + captured = nil + } + return Task { + switch captured { + case let .save(submission): await performSave(submission) + case let .disable(owner, revision): await writeEnabled(false, owner: owner, revision: revision) + case let .clear(owner, revision): await performClear(owner: owner, revision: revision) + case let .reboot(owner, revision): await performReboot(owner: owner, revision: revision) + case nil: break + } + } + } + + func setWiFiEnabled(_ enabled: Bool) async { + guard canRunCommands, let owner = context, + let revision = binding(for: owner)?.state.stableRevision() else { return } + if !enabled, currentTransportType == .wifi { + confirmation = .disable(owner, revision) + } else { + await writeEnabled(enabled, owner: owner, revision: revision) + } + } + + func cancelWiFiWarning() { + switch confirmation { case .save, .disable: confirmation = nil; default: break } + } + + func requestClear() { + guard canClear, let owner = context, + let revision = binding(for: owner)?.state.stableRevision() else { return } + confirmation = .clear(owner, revision) + } + + private func performClear(owner: Context, revision: UInt64) async { + guard canClear, matches(owner), let settings = settingsService else { return } + let id = UUID() + operation = .write(id, owner) + do { + let result = try await settings.clearRadioWiFi( + expectedContextID: owner.wifiContextID, expectedRevision: revision + ) + if matches(owner) { + await closeEditor() + clearAssociation() + observation.networkNameIsCurrent = false + if let result, settings.radioWiFiState.stableRevision() == result.revision { + apply(result) + errorMessage = result.error?.userFacingMessage + } else { + oweRead(owner) + } + } + } catch is CancellationError { + if matches(owner) { oweRead(owner) } + } catch { + if matches(owner) { + observation.networkNameIsCurrent = false + clearAssociation() + oweRead(owner) + errorMessage = error.userFacingMessage + } + } + finish(id) + await drainOwedRead() + } + + func writeEnabled(_ enabled: Bool, owner: Context, revision: UInt64) async { + guard canRunCommands, matches(owner), let settings = settingsService else { return } + let id = UUID() + operation = .write(id, owner) + do { + let receipt = try await settings.changeRadioWiFiEnabled( + enabled, expectedContextID: owner.wifiContextID, expectedRevision: revision + ) + if matches(owner) { + if receipt.contextID == owner.wifiContextID, let settled = receipt.revision, + binding(for: owner)?.state.stableRevision() == settled { + switch receipt.outcome { + case .accepted: + adoptMutationRevision(from: revision, to: settled) + observation.enabled = enabled + observation.enabledRevision = settled + case .rejected: + adoptMutationRevision(from: revision, to: settled) + case .uncertain: + observation.enabledRevision = nil + oweRead(owner) + } + } else { + oweRead(owner) + } + if let error = receipt.error, !(error is CancellationError) { errorMessage = error.userFacingMessage } + } + } catch is CancellationError { + if matches(owner) { oweRead(owner) } + } catch { + if matches(owner) { + errorMessage = error.userFacingMessage + observation.enabledRevision = nil + observation.networkNameIsCurrent = false + clearAssociation() + oweRead(owner) + } + } + finish(id) + await drainOwedRead() + } + + func requestReboot() { + guard canRunCommands, rebootPending, let context, + let revision = binding(for: context)?.state.stableRevision() else { return } + confirmation = .reboot(context, revision) + } + + func cancelReboot() { + if case .reboot = confirmation { confirmation = nil } + } + + private func performReboot(owner: Context, revision: UInt64) async { + guard canRunCommands, matches(owner), let settings = settingsService else { return } + let id = UUID() + operation = .write(id, owner) + do { + try await settings.reboot(expectedContextID: owner.wifiContextID, expectedRevision: revision) + } catch is CancellationError { + if matches(owner) { oweRead(owner) } + } catch { + if matches(owner) { + switch error { + case BLEError.notConnected, BLEError.operationTimeout, + MeshTransportError.notConnected, + WiFiTransportError.notConnected, WiFiTransportError.sendTimeout: + break + default: errorMessage = error.userFacingMessage + } + } + } + finish(id) + await drainOwedRead() + } +} diff --git a/MC1/Views/Settings/Sections/RadioWiFiViewModel.swift b/MC1/Views/Settings/Sections/RadioWiFiViewModel.swift index a7e3597db5..387224ae3d 100644 --- a/MC1/Views/Settings/Sections/RadioWiFiViewModel.swift +++ b/MC1/Views/Settings/Sections/RadioWiFiViewModel.swift @@ -2,712 +2,314 @@ import Foundation import MC1Services import Observation -/// Radio CLI WiFi settings for a paired 1.18.0 radio. @Observable @MainActor final class RadioWiFiViewModel { - private static let connectedStatus = "connected" - private static let enabledValue = "1" - private static let disabledValue = "0" - private static let minSSIDBytes = 1 - private static let maxSSIDBytes = 32 - private static let maxPasswordBytes = 63 + enum RecoverySurface: Equatable { case connection, wifiPage, editor } - /// Which surface presents `errorMessage`. One error has one presenter. - enum RecoverySurface: Equatable { - case connection - case wifiPage - case editor + struct Context: Equatable, Sendable { + let radioID: UUID + let serviceID: ObjectIdentifier + let wifiContextID: UUID } - private var settingsServiceProvider: @MainActor () -> SettingsService? = { nil } - private var connectionStateProvider: @MainActor () -> DeviceConnectionState = { .disconnected } - private var connectedDeviceProvider: @MainActor () -> DeviceDTO? = { nil } - private var currentTransportTypeProvider: @MainActor () -> TransportType? = { nil } - private var rebootAction: @MainActor () async throws -> Void = {} - - /// The settings service whose rows are still due. A read starts only while the - /// editor is closed and this view model is idle, and only that service may replace the rows. - private var owedSettingsService: SettingsService? - - /// Radio currently displayed. A different id clears the previous radio before the next probe. - private var adoptedRadioID: UUID? - /// Service currently displayed. A replacement must probe again before its fields are writable. - private var adoptedServiceID: ObjectIdentifier? - /// Service that parsed `wifi.enabled`. Writes use this, not a default or a previous service. - private var confirmedRadioID: UUID? - private var confirmedServiceID: ObjectIdentifier? - private var enabledConfirmed = false - private var networkConfirmed = false - private var credentialsConfirmed = false - private var ignoreEditorClose = false + struct ObservedWiFiState { + var enabled = false + var enabledRevision: UInt64? + var networkName: String? + var networkRevision: UInt64? + var networkNameIsCurrent = false + var associated: Bool? + var ipAddress: String? + } - private(set) var wifiSettingsSupport: ConnectionLinkRows.WiFiSettingsSupport = .unknown - private(set) var isLoading = false - private(set) var isWriting = false - var errorMessage: String? - private(set) var statusConnected = false - private(set) var ipAddress: String? - private(set) var networkName: String? - private(set) var wifiEnabled = false - private(set) var rebootPending = false - var editorOpen = false { - didSet { - guard ignoreEditorClose == false else { return } - guard oldValue, editorOpen == false else { return } - Task { await startOwedRead() } - } + struct ReadDebt: Equatable { + let owner: Context + let revision: UInt64 } - var ssidField = "" - var passwordField = "" - var showingWiFiWarning = false - var showingClearConfirm = false - var showingRebootConfirm = false + struct Editor { + let id: UUID + var baseline: RadioWiFiCredentialBaseline? + var ssid = "" + var password = "" + var ssidEdited = false + var passwordEdited = false + } - private var loadedSSID = "" - private var loadedPassword = "" - private var pendingWiFiAction: WiFiWarningAction? + enum Operation { + case snapshot(UUID, Context) + case editor(UUID, Context, UUID) + case write(UUID, Context) - /// The SSID, password, and whether the password differs from the loaded one. - /// Captured when Save is tapped. Later edits do not change the commands. - private struct WiFiCredentialSubmission: Equatable { - var ssid: String - var password: String - var passwordChanged: Bool + var id: UUID { + switch self { + case let .snapshot(id, _), let .editor(id, _, _), let .write(id, _): id + } + } } - private struct CommandOwner: Equatable { - var radioID: UUID? - var serviceID: ObjectIdentifier + struct Submission: Sendable { + let owner: Context + let baseline: RadioWiFiCredentialBaseline + let ssid: String + let password: String } - private enum WiFiWarningAction { - case save(WiFiCredentialSubmission) - case disable - } + enum AlertAction: Sendable { case wifiWarning, clear, reboot } - private enum EnabledProbe { - case enabled(Bool) - case unavailable - case invalid + enum Confirmation { + case save(Submission) + case disable(Context, UInt64) + case clear(Context, UInt64) + case reboot(Context, UInt64) } - private var settingsService: SettingsService? { + private var settingsServiceProvider: @MainActor () -> SettingsService? = { nil } + private var connectionStateProvider: @MainActor () -> DeviceConnectionState = { .disconnected } + private var connectedDeviceProvider: @MainActor () -> DeviceDTO? = { nil } + private var currentTransportTypeProvider: @MainActor () -> TransportType? = { nil } + + var context: Context? + var enabledContext: Context? + var observation = ObservedWiFiState() + var editor: Editor? + var operation: Operation? + var confirmation: Confirmation? + var owedRead: ReadDebt? + var refreshTask: Task? + var refreshTaskID: UUID? + + private(set) var wifiSettingsSupport: ConnectionLinkRows.WiFiSettingsSupport = .unknown + private(set) var editorOpen = false + var errorMessage: String? + + var settingsService: SettingsService? { settingsServiceProvider() } - private var transportIsWiFi: Bool { - currentTransportTypeProvider() == .wifi + var connectionState: DeviceConnectionState { + connectionStateProvider() } - var showsSection: Bool { - wifiSettingsSupport == .supported + var connectedDevice: DeviceDTO? { + connectedDeviceProvider() } - var isBusy: Bool { - isLoading || isWriting + var currentTransportType: TransportType? { + currentTransportTypeProvider() } - var canRunCommands: Bool { - guard connectionStateProvider() == .ready, isBusy == false else { return false } - guard enabledConfirmed, let confirmedServiceID, let confirmedRadioID else { return false } - guard let settings = settingsService, ObjectIdentifier(settings) == confirmedServiceID else { return false } - return connectedDeviceProvider()?.radioID == confirmedRadioID + var showsSection: Bool { + wifiSettingsSupport == .supported } - var canEditNetwork: Bool { - canRunCommands && credentialsConfirmed + var isBusy: Bool { + operation != nil } - var canSave: Bool { - guard canEditNetwork else { return false } - guard ssidField != loadedSSID || passwordField != loadedPassword else { return false } - let nameBytes = Self.utf8ByteCount(ssidField) - guard nameBytes >= Self.minSSIDBytes, nameBytes <= Self.maxSSIDBytes else { return false } - return Self.utf8ByteCount(passwordField) <= Self.maxPasswordBytes + var isWriting: Bool { + if case .write = operation { true } else { false } } - var canClear: Bool { - networkConfirmed && networkName != nil && canRunCommands + var isLoading: Bool { + isBusy && !isWriting } - var editorFooter: String { - let nameBytes = Self.utf8ByteCount(ssidField) - if nameBytes < Self.minSSIDBytes { - return L10n.Settings.RadioWiFi.Editor.emptyName - } - if nameBytes > Self.maxSSIDBytes { - return L10n.Settings.RadioWiFi.Editor.nameLength - } - if Self.utf8ByteCount(passwordField) > Self.maxPasswordBytes { - return L10n.Settings.RadioWiFi.Editor.passwordLength - } - return L10n.Settings.RadioWiFi.Editor.footer + var wifiEnabled: Bool { + observation.enabled } - var clearMessage: String { - if transportIsWiFi { - return L10n.Settings.RadioWiFi.Alert.Clear.wifiMessage - } - return L10n.Settings.RadioWiFi.Alert.Clear.message + var networkName: String? { + observation.networkName } - var rebootMessage: String { - guard wifiEnabled else { - return L10n.Settings.RadioWiFi.Alert.Reboot.disabled - } - if let networkName { - return L10n.Settings.RadioWiFi.Alert.Reboot.join(networkName) - } - return L10n.Settings.RadioWiFi.Alert.Reboot.restart + var statusConnected: Bool { + observation.associated == true } - var linkWarningTitle: String { - switch pendingWiFiAction { - case .save: - L10n.Settings.RadioWiFi.Alert.Save.title - case .disable, nil: - L10n.Settings.RadioWiFi.Alert.TurnOff.title - } + var networkValue: String { + networkName ?? (observation.networkRevision == nil + ? L10n.Settings.DeviceInfo.unknown : L10n.Settings.RadioWiFi.Network.notSet) } - var linkWarningConfirmTitle: String { - switch pendingWiFiAction { - case .save: - L10n.Localizable.Common.save - case .disable, nil: - L10n.Settings.RadioWiFi.Alert.TurnOff.confirm + var statusValue: String { + switch observation.associated { + case nil: L10n.Settings.DeviceInfo.unknown + case true: L10n.Settings.RadioWiFi.Status.connected + case false: L10n.Settings.RadioWiFi.Status.notConnected } } - func recoverySurface(wifiPageVisible: Bool) -> RecoverySurface? { - Self.recoverySurface( - errorMessage: errorMessage, - editorOpen: editorOpen, - wifiPageVisible: wifiPageVisible - ) - } - - static func recoverySurface( - errorMessage: String?, - editorOpen: Bool, - wifiPageVisible: Bool - ) -> RecoverySurface? { - guard errorMessage != nil else { return nil } - if editorOpen { return .editor } - if wifiPageVisible { return .wifiPage } - return .connection + var ipAddress: String? { + observation.ipAddress } - func configure( - settingsService: @escaping @MainActor () -> SettingsService?, - connectionState: @escaping @MainActor () -> DeviceConnectionState, - connectedDevice: @escaping @MainActor () -> DeviceDTO?, - currentTransportType: @escaping @MainActor () -> TransportType?, - reboot: @escaping @MainActor () async throws -> Void - ) { - settingsServiceProvider = settingsService - connectionStateProvider = connectionState - connectedDeviceProvider = connectedDevice - currentTransportTypeProvider = currentTransportType - rebootAction = reboot + var rebootPending: Bool { + guard let context, context == enabledContext, let binding = binding(for: context) else { return false } + return binding.state.rebootPending } - /// Clears the live link rows while the phone is down, or owes one snapshot for the current service. - func noteSessionReadiness() async { - adoptCurrentRadio() - guard connectionStateProvider() == .ready, let settings = settingsService else { - statusConnected = false - ipAddress = nil - owedSettingsService = nil - return + var ssidField: String { + get { editor?.ssid ?? "" } + set { + ensureEditor() + editor?.ssid = newValue + editor?.ssidEdited = true } - adoptService(settings) - owedSettingsService = settings - await startOwedRead() - } - - /// Reads again when the editor is closed and no read or write is running. A busy editor keeps the debt. - func refresh() async { - await noteSessionReadiness() } - func load() async { - guard !isBusy else { return } - adoptCurrentRadio() - let device = connectedDeviceProvider() - guard device?.supportsRadioCLI == true else { - markRadioCLIUnavailable() - return - } - guard let settings = settingsService else { - wifiSettingsSupport = .unknown - return + var passwordField: String { + get { editor?.password ?? "" } + set { + ensureEditor() + editor?.password = newValue + editor?.passwordEdited = true } - adoptService(settings) - await performSnapshot(from: settings) - await continueOwedRead() - } - - func loadEditor() async { - guard !isBusy else { return } - ssidField = loadedSSID - passwordField = loadedPassword - guard let settings = settingsService else { return } - let radioID = connectedDeviceProvider()?.radioID - isLoading = true - do { - let password = try await settings.getRadioCLIValue(RadioCLIKey.wifiPassword) - if matches(settings, radioID: radioID), Task.isCancelled == false { - loadedPassword = Self.storedPassword(password) - passwordField = loadedPassword - await refreshRebootPending(from: settings, radioID: radioID) - } - } catch is CancellationError { - // Cancellation leaves the password fields and does not set an error. - } catch { - if matches(settings, radioID: radioID) { - errorMessage = error.userFacingMessage - } - } - isLoading = false - await continueOwedRead() } - func setWiFiEnabled(_ enabled: Bool) async { - guard canRunCommands else { return } - if !enabled, transportIsWiFi { - presentLinkWarning(.disable) - return - } - await writeEnabled(enabled) - } - - func requestSave() async { - guard canSave else { return } - let submission = WiFiCredentialSubmission( - ssid: ssidField, - password: passwordField, - passwordChanged: passwordField != loadedPassword - ) - if transportIsWiFi { - presentLinkWarning(.save(submission)) - return - } - await performSave(submission) + var canRunCommands: Bool { + guard !isBusy, let context, enabledContext == context, observation.enabledRevision != nil else { return false } + return matches(context) } - func requestClear() { - guard canClear else { return } - showingClearConfirm = true + var canEditNetwork: Bool { + canRunCommands && showsSection } - func continuePastWiFiWarning() async { - let action = pendingWiFiAction - pendingWiFiAction = nil - showingWiFiWarning = false - switch action { - case let .save(submission): - await performSave(submission) - case .disable: - await writeEnabled(false) - case nil: - break - } + var needsEditorRead: Bool { + guard let editor else { return false } + guard let baseline = editor.baseline, let context, let binding = binding(for: context) else { return true } + if let owedRead, owedRead.owner == context, owedRead.revision > baseline.revision { return true } + return binding.contextID != baseline.contextID || binding.state.stableRevision() != baseline.revision } - func cancelWiFiWarning() { - pendingWiFiAction = nil - showingWiFiWarning = false + var canClear: Bool { + guard canRunCommands, let context, let binding = binding(for: context), + let revision = binding.state.stableRevision() else { return false } + return networkName != nil && observation.networkNameIsCurrent && observation.networkRevision == revision } - private func presentLinkWarning(_ action: WiFiWarningAction) { - pendingWiFiAction = action - showingWiFiWarning = true + var canSave: Bool { + guard canEditNetwork, !needsEditorRead, let context, let binding = binding(for: context), + let editor, let baseline = editor.baseline, baseline.editorID == editor.id, + binding.contextID == baseline.contextID, binding.state.stableRevision() == baseline.revision else { return false } + let changed = !RadioWiFiCredentialBaseline.hasSameBytes(editor.ssid, baseline.ssid) + || !RadioWiFiCredentialBaseline.hasSameBytes(editor.password, baseline.password) + return changed && RadioWiFiCredentialBaseline.validCredentials(ssid: editor.ssid, password: editor.password) } - func confirmClear() async { - guard canClear else { return } - showingClearConfirm = false - guard let settings = settingsService else { - errorMessage = SettingsServiceError.notConnected.userFacingMessage - return - } - let radioID = connectedDeviceProvider()?.radioID - isWriting = true - do { - try await settings.setRadioCLIValue(RadioCLIKey.wifiClear, to: nil) - if matches(settings, radioID: radioID) { - loadedSSID = "" - loadedPassword = "" - ssidField = "" - passwordField = "" - networkName = nil - networkConfirmed = true - credentialsConfirmed = true - await refreshRebootPending(from: settings, radioID: radioID) - } - } catch { - if matches(settings, radioID: radioID) { - errorMessage = error.userFacingMessage - } + var editorFooter: String { + let bytes = ssidField.utf8.count + if bytes < RadioWiFiCredentialBaseline.minSSIDBytes { return L10n.Settings.RadioWiFi.Editor.emptyName } + if bytes > RadioWiFiCredentialBaseline.maxSSIDBytes { return L10n.Settings.RadioWiFi.Editor.nameLength } + if passwordField.utf8.count > RadioWiFiCredentialBaseline.maxPasswordBytes { + return L10n.Settings.RadioWiFi.Editor.passwordLength } - isWriting = false - await continueOwedRead() - } - - func requestReboot() { - guard canRunCommands, rebootPending else { return } - showingRebootConfirm = true - } - - func cancelReboot() { - showingRebootConfirm = false - } - - func confirmReboot() async { - showingRebootConfirm = false - guard canRunCommands else { return } - let radioID = connectedDeviceProvider()?.radioID - let serviceID = settingsService.map(ObjectIdentifier.init) - do { - try await rebootAction() - } catch { - guard connectedDeviceProvider()?.radioID == radioID else { return } - guard settingsService.map(ObjectIdentifier.init) == serviceID else { return } - switch error { - case BLEError.notConnected, BLEError.operationTimeout: - // The radio reboots without a reply and drops the link. - break - case WiFiTransportError.notConnected, WiFiTransportError.sendTimeout: - break - default: - errorMessage = error.userFacingMessage - } + if !RadioWiFiCredentialBaseline.isRepresentable(ssidField) + || !RadioWiFiCredentialBaseline.isRepresentable(passwordField) { + return L10n.Settings.RadioWiFi.Editor.unsupportedCharacter } + return L10n.Settings.RadioWiFi.Editor.footer } - private func performSave(_ submission: WiFiCredentialSubmission) async { - guard canRunCommands else { return } - guard let settings = settingsService else { - errorMessage = SettingsServiceError.notConnected.userFacingMessage - return - } - let radioID = connectedDeviceProvider()?.radioID - isWriting = true - let ssidChanged = submission.ssid != loadedSSID - do { - if ssidChanged || submission.passwordChanged { - try await settings.setRadioCLIValue(RadioCLIKey.wifiSSID, to: submission.ssid) - if matches(settings, radioID: radioID) { - loadedSSID = submission.ssid - networkName = Self.displayedNetworkName(loadedSSID) - networkConfirmed = true - credentialsConfirmed = true - } - } - if submission.passwordChanged, matches(settings, radioID: radioID) { - try await settings.setRadioCLIValue(RadioCLIKey.wifiPassword, to: submission.password) - if matches(settings, radioID: radioID) { - loadedPassword = submission.password - } - } - if matches(settings, radioID: radioID) { - await refreshRebootPending(from: settings, radioID: radioID) - closeEditor() - } - } catch { - if matches(settings, radioID: radioID) { - errorMessage = error.userFacingMessage - await refreshRebootPending(from: settings, radioID: radioID) - } - } - isWriting = false - await continueOwedRead() + var clearMessage: String { + currentTransportType == .wifi + ? L10n.Settings.RadioWiFi.Alert.Clear.wifiMessage : L10n.Settings.RadioWiFi.Alert.Clear.message } - private func writeEnabled(_ enabled: Bool) async { - guard canRunCommands else { return } - guard let settings = settingsService else { - errorMessage = SettingsServiceError.notConnected.userFacingMessage - return - } - let radioID = connectedDeviceProvider()?.radioID - isWriting = true - do { - try await settings.setRadioCLIValue( - RadioCLIKey.wifiEnabled, - to: enabled ? Self.enabledValue : Self.disabledValue - ) - if matches(settings, radioID: radioID) { - wifiEnabled = enabled - await refreshRebootPending(from: settings, radioID: radioID) - } - } catch { - if matches(settings, radioID: radioID) { - errorMessage = error.userFacingMessage - } + var rebootMessage: String { + guard let context, enabledContext == context, let binding = binding(for: context), + let revision = binding.state.stableRevision(), observation.enabledRevision == revision else { + return L10n.Settings.RadioWiFi.Alert.Reboot.restart } - isWriting = false - await continueOwedRead() - } - - private func performSnapshot(from settings: SettingsService) async { - let owner = CommandOwner( - radioID: connectedDeviceProvider()?.radioID, - serviceID: ObjectIdentifier(settings) - ) - isLoading = true - defer { isLoading = false } - do { - let enabled = try await settings.getRadioCLIValue(RadioCLIKey.wifiEnabled) - guard shouldApplySnapshot(owner) else { return } - switch Self.classifyEnabled(enabled) { - case .unavailable: - applyUnavailable() - return - case .invalid: - applyReadFailure(owner: owner, error: SettingsServiceError.invalidResponse) - return - case let .enabled(isOn): - applySupported(owner: owner, isOn: isOn) - } - let ssid = try await settings.getRadioCLIValue(RadioCLIKey.wifiSSID) - guard shouldApplySnapshot(owner) else { return } - let status = try await settings.getRadioCLIValue(RadioCLIKey.wifiStatus) - guard shouldApplySnapshot(owner) else { return } - let ip = try await settings.getRadioCLIValue(RadioCLIKey.wifiIP) - guard shouldApplySnapshot(owner) else { return } - let rebootPending = await settings.radioWiFiRebootPending - guard shouldApplySnapshot(owner) else { return } - applyDetails(ssid: ssid, status: status, ip: ip, rebootPending: rebootPending) - } catch is CancellationError { - // Cancellation leaves the previous rows and does not set an error. - } catch { - guard shouldApplySnapshot(owner) else { return } - applyReadFailure(owner: owner, error: error) + guard wifiEnabled else { return L10n.Settings.RadioWiFi.Alert.Reboot.disabled } + guard observation.networkNameIsCurrent, observation.networkRevision == revision else { + return L10n.Settings.RadioWiFi.Alert.Reboot.restart } + return networkName.map(L10n.Settings.RadioWiFi.Alert.Reboot.join) ?? L10n.Settings.RadioWiFi.Alert.Reboot.restart } - private func shouldApplySnapshot(_ owner: CommandOwner) -> Bool { - guard Task.isCancelled == false else { return false } - guard matches(serviceID: owner.serviceID, radioID: owner.radioID) else { return false } - if let owed = owedSettingsService, ObjectIdentifier(owed) != owner.serviceID { - return false + var showingWiFiWarning: Bool { + get { + switch confirmation { case .save, .disable: true; default: false } } - return true + set { if !newValue { cancelWiFiWarning() } } } - /// Starts the owed read when the editor is closed, the phone is ready, and no read or write is running. - /// A cancelled caller starts that read on a new task so it does not drop the service a replacement caller just owed. - private func continueOwedRead() async { - if Task.isCancelled { - Task { await self.startOwedRead(hopIfCancelled: false) } - return - } - await startOwedRead(hopIfCancelled: true) + var showingClearConfirm: Bool { + get { if case .clear = confirmation { true } else { false } } + set { if !newValue, case .clear = confirmation { confirmation = nil } } } - private func startOwedRead() async { - await startOwedRead(hopIfCancelled: true) + var showingRebootConfirm: Bool { + get { if case .reboot = confirmation { true } else { false } } + set { if !newValue { cancelReboot() } } } - private func startOwedRead(hopIfCancelled: Bool) async { - if Task.isCancelled { - if hopIfCancelled { - Task { await self.startOwedRead(hopIfCancelled: false) } - } - return - } - guard connectionStateProvider() == .ready else { return } - guard editorOpen == false, isBusy == false else { return } - guard let owed = owedSettingsService else { return } - guard let settings = settingsService, settings === owed else { - owedSettingsService = nil - return - } - let device = connectedDeviceProvider() - if let radioID = device?.radioID, radioID != adoptedRadioID { - owedSettingsService = nil - return - } - guard device?.supportsRadioCLI == true else { - owedSettingsService = nil - markRadioCLIUnavailable() - return - } - owedSettingsService = nil - await performSnapshot(from: owed) - await continueOwedRead() - } - - private func adoptCurrentRadio() { - guard let radioID = connectedDeviceProvider()?.radioID, radioID != adoptedRadioID else { return } - resetForNewRadio(radioID) - } - - private func adoptService(_ settings: SettingsService) { - let serviceID = ObjectIdentifier(settings) - guard serviceID != adoptedServiceID else { return } - invalidateForService(serviceID) - } - - private func resetForNewRadio(_ radioID: UUID) { - adoptedRadioID = radioID - adoptedServiceID = nil - owedSettingsService = nil - wifiSettingsSupport = .unknown - clearConfirmedFields() - clearDisplayedNetwork() - errorMessage = nil - closeEditor() - } - - private func invalidateForService(_ serviceID: ObjectIdentifier) { - adoptedServiceID = serviceID - wifiSettingsSupport = .unknown - clearConfirmedFields() - clearDisplayedNetwork() - errorMessage = nil - closeEditor() - } - - private func markRadioCLIUnavailable() { - wifiSettingsSupport = .unknown - enabledConfirmed = false - networkConfirmed = false - credentialsConfirmed = false - confirmedRadioID = nil - confirmedServiceID = nil - } - - private func clearConfirmedFields() { - enabledConfirmed = false - networkConfirmed = false - credentialsConfirmed = false - confirmedRadioID = nil - confirmedServiceID = nil - rebootPending = false - statusConnected = false - ipAddress = nil - pendingWiFiAction = nil - showingWiFiWarning = false - showingClearConfirm = false - showingRebootConfirm = false - } - - private func clearDisplayedNetwork() { - networkName = nil - wifiEnabled = false - loadedSSID = "" - loadedPassword = "" - ssidField = "" - passwordField = "" - } - - private func closeEditor() { - ignoreEditorClose = true - editorOpen = false - ignoreEditorClose = false - } - - private func applySupported(owner: CommandOwner, isOn: Bool) { - if let radioID = owner.radioID { - adoptedRadioID = radioID + var linkWarningTitle: String { + if case .save = confirmation { L10n.Settings.RadioWiFi.Alert.Save.title } else { + L10n.Settings.RadioWiFi.Alert.TurnOff.title } - adoptedServiceID = owner.serviceID - confirmedRadioID = owner.radioID - confirmedServiceID = owner.serviceID - enabledConfirmed = true - wifiSettingsSupport = .supported - wifiEnabled = isOn - } - - private func applyUnavailable() { - wifiSettingsSupport = .unavailable - enabledConfirmed = false - networkConfirmed = false - credentialsConfirmed = false - confirmedRadioID = nil - confirmedServiceID = nil - statusConnected = false - ipAddress = nil - rebootPending = false - clearDisplayedNetwork() - errorMessage = nil } - private func applyDetails(ssid: String?, status: String?, ip: String?, rebootPending: Bool) { - networkConfirmed = true - credentialsConfirmed = true - loadedSSID = Self.storedSSID(ssid) - networkName = Self.displayedNetworkName(loadedSSID) - let statusText = status?.trimmingCharacters(in: .whitespacesAndNewlines) - statusConnected = statusText == Self.connectedStatus - ipAddress = Self.displayedIP(ip) - self.rebootPending = rebootPending - errorMessage = nil + var linkWarningConfirmTitle: String { + if case .save = confirmation { L10n.Localizable.Common.save } else { + L10n.Settings.RadioWiFi.Alert.TurnOff.confirm + } } - /// Support from this service stays. Association and the IP do not, so a switch cannot use them. - private func applyReadFailure(owner: CommandOwner, error: Error) { - errorMessage = error.userFacingMessage - statusConnected = false - ipAddress = nil - let stillSupported = wifiSettingsSupport == .supported - && enabledConfirmed - && confirmedServiceID == owner.serviceID - && confirmedRadioID == owner.radioID - if stillSupported { return } + func recoverySurface(wifiPageVisible: Bool) -> RecoverySurface? { + Self.recoverySurface(errorMessage: errorMessage, editorOpen: editorOpen, wifiPageVisible: wifiPageVisible) } - private func matches(_ settings: SettingsService, radioID: UUID?) -> Bool { - matches(serviceID: ObjectIdentifier(settings), radioID: radioID) + static func recoverySurface(errorMessage: String?, editorOpen: Bool, wifiPageVisible: Bool) -> RecoverySurface? { + guard errorMessage != nil else { return nil } + return editorOpen ? .editor : (wifiPageVisible ? .wifiPage : .connection) } - private func matches(serviceID: ObjectIdentifier, radioID: UUID?) -> Bool { - guard let settings = settingsService, ObjectIdentifier(settings) == serviceID else { return false } - return connectedDeviceProvider()?.radioID == radioID + func configure( + settingsService: @escaping @MainActor () -> SettingsService?, + connectionState: @escaping @MainActor () -> DeviceConnectionState, + connectedDevice: @escaping @MainActor () -> DeviceDTO?, + currentTransportType: @escaping @MainActor () -> TransportType? + ) { + settingsServiceProvider = settingsService + connectionStateProvider = connectionState + connectedDeviceProvider = connectedDevice + currentTransportTypeProvider = currentTransportType } - private func refreshRebootPending(from settings: SettingsService, radioID: UUID?) async { - let pending = await settings.radioWiFiRebootPending - guard matches(settings, radioID: radioID) else { return } - rebootPending = pending + func matches(_ owner: Context) -> Bool { + connectionState == .ready && matchesContext(owner) } - private static func classifyEnabled(_ value: String?) -> EnabledProbe { - guard let value else { return .unavailable } - let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) - if trimmed == enabledValue { return .enabled(true) } - if trimmed == disabledValue { return .enabled(false) } - return .invalid + func matchesContext(_ owner: Context) -> Bool { + binding(for: owner) != nil } - private static func utf8ByteCount(_ value: String) -> Int { - Data(value.utf8).count + func binding(for owner: Context) -> RadioWiFiBinding? { + guard connectedDevice?.radioID == owner.radioID, let settingsService, + ObjectIdentifier(settingsService) == owner.serviceID else { return nil } + let binding = settingsService.radioWiFiBinding + guard binding.contextID == owner.wifiContextID, binding.state.radioID == owner.radioID else { return nil } + return binding } - /// The SSID reply, unchanged. `(not set)` and an empty value mean no network. - private static func storedSSID(_ value: String?) -> String { - guard let value, !value.isEmpty, value != RadioCLIReply.notSet else { return "" } - return value + func oweRead(_ owner: Context) { + guard let binding = binding(for: owner) else { return } + owedRead = ReadDebt(owner: owner, revision: binding.state.revision) } - /// The password reply, unchanged. The password has no sentinel. - private static func storedPassword(_ value: String?) -> String { - value ?? "" + func finish(_ id: UUID) { + if operation?.id == id { operation = nil } } - private static func displayedNetworkName(_ ssid: String) -> String? { - if ssid.isEmpty || ssid == RadioCLIReply.notSet { return nil } - return ssid + func setSupport(_ support: ConnectionLinkRows.WiFiSettingsSupport) { + wifiSettingsSupport = support } - /// `(not connected)` and an empty value mean no address. Other text is kept. - private static func displayedIP(_ value: String?) -> String? { - guard let value, !value.isEmpty, value != RadioCLIReply.notConnected else { return nil } - return value + func setEditorPresented(_ presented: Bool) { + editorOpen = presented } } diff --git a/MC1/Views/Settings/Sections/RecentlyBlockedRow.swift b/MC1/Views/Settings/Sections/RecentlyBlockedRow.swift new file mode 100644 index 0000000000..74e2418b5b --- /dev/null +++ b/MC1/Views/Settings/Sections/RecentlyBlockedRow.swift @@ -0,0 +1,85 @@ +import MC1Services +import SwiftUI + +struct RecentlyBlockedRow: View { + let entry: RecentlyBlockedMessageDTO + + var body: some View { + VStack(alignment: .leading, spacing: Metrics.lineSpacing) { + HStack(alignment: .firstTextBaseline, spacing: Metrics.titleSpacing) { + if let sender = entry.sender { + Text(Self.highlighted(sender, matches: entry.match.senderHighlights, base: .primary)) + .font(.headline) + .lineLimit(1) + } + Spacer(minLength: Metrics.titleSpacing) + ConversationTimestamp(date: entry.arrivedAt) + } + Text(Self.highlighted(entry.body, matches: entry.match.bodyHighlights, base: .secondary)) + .font(.subheadline) + Text(Self.caption( + conversationName: entry.conversationName, + phrase: entry.match.rule.phrase, + summary: entry.match.rule.summary + )) + .font(.footnote) + .foregroundStyle(.secondary) + } + .fixedSize(horizontal: false, vertical: true) + .accessibilityElement(children: .ignore) + .accessibilityLabel(Self.accessibilityLabel(for: entry)) + } + + static func caption(conversationName: String?, phrase: String, summary: String) -> String { + if let conversationName { + return L10n.Settings.TextRules.Archive.caption(conversationName, phrase, summary) + } + return L10n.Settings.TextRules.Archive.captionWithoutChat(phrase, summary) + } + + static func accessibilityLabel(for entry: RecentlyBlockedMessageDTO) -> String { + var parts: [String] = [] + if let sender = entry.sender { + parts.append(labeled(L10n.Settings.TextRules.Field.sender, sender)) + } + parts.append(labeled(L10n.Settings.TextRules.Field.message, entry.body)) + let rule = L10n.Settings.TextRules.ruleSummary(entry.match.rule.phrase, entry.match.rule.summary) + parts.append(labeled(L10n.Settings.TextRules.Archive.rule, rule)) + if let conversationName = entry.conversationName { + parts.append(labeled(L10n.Settings.TextRules.Archive.chat, conversationName)) + } + let time = entry.arrivedAt.formatted(.dateTime.month(.abbreviated).day().hour().minute()) + parts.append(labeled(L10n.Settings.TextRules.Archive.time, time)) + return parts.formatted(.list(type: .and)) + } + + static func highlighted( + _ text: String, + matches: [TextRulesPreference.RuleMatch.Highlight], + base: Color + ) -> AttributedString { + var attributed = AttributedString(text) + attributed.foregroundColor = base + for match in matches { + guard let range = match.range(in: text), + let start = AttributedString.Index(range.lowerBound, within: attributed), + let end = AttributedString.Index(range.upperBound, within: attributed) else { continue } + attributed[start.. String { + L10n.Settings.TextRules.Archive.labelPrefix(label) + value + } + + private enum Metrics { + static let lineSpacing: CGFloat = 4 + static let titleSpacing: CGFloat = 8 + static let matchHighlightOpacity = 0.4 + static var matchHighlight: Color { + Color.yellow.opacity(matchHighlightOpacity) + } + } +} diff --git a/MC1/Views/Settings/Sections/RecentlyBlockedView.swift b/MC1/Views/Settings/Sections/RecentlyBlockedView.swift new file mode 100644 index 0000000000..d75eda7884 --- /dev/null +++ b/MC1/Views/Settings/Sections/RecentlyBlockedView.swift @@ -0,0 +1,121 @@ +import MC1Services +import SwiftUI + +struct RecentlyBlockedView: View { + struct RadioGroup: Identifiable { + let radioID: UUID + let radioName: String? + let entries: [RecentlyBlockedMessageDTO] + + var id: UUID { + radioID + } + } + + @Environment(\.appState) private var appState + @Environment(\.appTheme) private var theme + @State private var entries: [RecentlyBlockedMessageDTO] = [] + @State private var errorMessage: String? + + var body: some View { + let groups = Self.radioGroups(in: entries) + List { + if groups.count > 1 { + ForEach(groups) { group in + radioSection(group, isLast: group.id == groups.last?.id) + } + } else { + messageSection(entries) + } + } + .themedCanvas(theme) + .navigationTitle(L10n.Settings.TextRules.Archive.title) + .navigationBarTitleDisplayMode(.inline) + .errorAlert($errorMessage) + .task { + let store = appState.connectionManager.persistenceStore + let changes = store.recentlyBlockedUpdates() + await refresh(from: store) + for await _ in changes { + await refresh(from: store) + } + } + } + + static func radioGroups(in entries: [RecentlyBlockedMessageDTO]) -> [RadioGroup] { + var order: [UUID] = [] + var grouped: [UUID: [RecentlyBlockedMessageDTO]] = [:] + var names: [UUID: String] = [:] + for entry in entries { + let radioID = entry.identity.radioID + if grouped[radioID] == nil { + order.append(radioID) + } + grouped[radioID, default: []].append(entry) + if names[radioID] == nil, let radioName = entry.radioName { + names[radioID] = radioName + } + } + return order.map { radioID in + RadioGroup(radioID: radioID, radioName: names[radioID], entries: grouped[radioID] ?? []) + } + } + + private func messageSection(_ rows: [RecentlyBlockedMessageDTO]) -> some View { + Section { + if rows.isEmpty { + Text(L10n.Settings.TextRules.Archive.empty) + .foregroundStyle(.secondary) + } + ForEach(rows) { entry in + RecentlyBlockedRow(entry: entry) + } + } footer: { + retentionFooter + } + .themedRowBackground(theme) + } + + @ViewBuilder + private func radioSection(_ group: RadioGroup, isLast: Bool) -> some View { + if isLast { + Section { + messageRows(group.entries) + } header: { + Text(radioHeader(group)) + } footer: { + retentionFooter + } + .themedRowBackground(theme) + } else { + Section { + messageRows(group.entries) + } header: { + Text(radioHeader(group)) + } + .themedRowBackground(theme) + } + } + + private func messageRows(_ rows: [RecentlyBlockedMessageDTO]) -> some View { + ForEach(rows) { entry in + RecentlyBlockedRow(entry: entry) + } + } + + private func radioHeader(_ group: RadioGroup) -> String { + group.radioName ?? L10n.Settings.TextRules.Archive.unknownRadio + } + + private var retentionFooter: Text { + Text(L10n.Settings.TextRules.Archive.footer(PersistenceStore.recentlyBlockedRetentionLimit)) + } + + private func refresh(from store: PersistenceStore) async { + do { + entries = try await store.recentlyBlockedMessages() + } catch { + errorMessage = L10n.Localizable.Common.Error.failedToLoad + } + } +} diff --git a/MC1/Views/Settings/Sections/TextRuleChatsView.swift b/MC1/Views/Settings/Sections/TextRuleChatsView.swift new file mode 100644 index 0000000000..7513871eb6 --- /dev/null +++ b/MC1/Views/Settings/Sections/TextRuleChatsView.swift @@ -0,0 +1,107 @@ +import MC1Services +import SwiftUI + +struct TextRuleChatsView: View { + let kind: TextRulesPreference.Kind + + @Environment(\.appState) private var appState + @Environment(\.appTheme) private var theme + @State private var inventory: [TextRulesPreference.Conversation] = [] + @State private var errorMessage: String? + + var body: some View { + List { + if let preference = appState.textRulesPreference { + selectionSection(preference.selection(for: kind)) + } else { + TextRulesLoadNotice() + .themedRowBackground(theme) + } + } + .themedCanvas(theme) + .navigationTitle(kind.title) + .navigationBarTitleDisplayMode(.inline) + .errorAlert($errorMessage) + .task { + do { + inventory = try await appState.connectionManager.persistenceStore.textRulesConversations(kind: kind) + } catch { + errorMessage = L10n.Localizable.Common.Error.failedToLoad + } + } + } + + private func selectionSection(_ selection: TextRulesPreference.Selection) -> some View { + Section { + Button { + updateSelection { _ in .all } + } label: { + selectionLabel(L10n.Settings.TextRules.Selection.all, radio: nil, isSelected: selection == .all) + } + .accessibilityAddTraits(selection == .all ? .isSelected : []) + ForEach(inventory) { conversation in + let isSelected = selection.includes(conversation.key) + Button { + toggle(conversation.key) + } label: { + selectionLabel(conversation.name, radio: conversation.radioName, isSelected: isSelected) + } + .accessibilityAddTraits(isSelected ? .isSelected : []) + } + } footer: { + Text(L10n.Settings.TextRules.Selection.footer) + } + .buttonStyle(.plain) + .disabled(!selection.isOn) + .themedRowBackground(theme) + } + + private func selectionLabel(_ title: String, radio: String?, isSelected: Bool) -> some View { + HStack { + VStack(alignment: .leading) { + Text(verbatim: title) + if let radio { + Text(verbatim: radio) + .font(.subheadline) + .foregroundStyle(.secondary) + } + } + Spacer() + if isSelected { + Image(systemName: "checkmark") + .foregroundStyle(.tint) + .accessibilityHidden(true) + } + } + .contentShape(.rect) + } + + private func toggle(_ key: TextRulesPreference.Key) { + updateSelection { selection in + var selected: Set + switch selection { + case .off: return .off + case .all: selected = Set(inventory.map(\.key)) + case let .fixed(keys): selected = keys + } + if selected.remove(key) == nil { + selected.insert(key) + } + return .fixed(selected) + } + } + + private func updateSelection( + _ update: (TextRulesPreference.Selection) -> TextRulesPreference.Selection + ) { + do { + try appState.connectionManager.updateTextRules { preference in + let selection = preference.selection(for: kind) + guard selection.isOn else { return } + preference.setSelection(update(selection), for: kind) + } + } catch { + errorMessage = L10n.Settings.TextRules.saveFailed + } + } +} diff --git a/MC1/Views/Settings/Sections/TextRulesLoadNotice.swift b/MC1/Views/Settings/Sections/TextRulesLoadNotice.swift new file mode 100644 index 0000000000..63909d3eb0 --- /dev/null +++ b/MC1/Views/Settings/Sections/TextRulesLoadNotice.swift @@ -0,0 +1,20 @@ +import SwiftUI + +struct TextRulesLoadNotice: View { + @Environment(\.appState) private var appState + + var body: some View { + if appState.isTextRulesLoading { + ProgressView(L10n.Settings.TextRules.loading) + } else if appState.textRulesPreference == nil { + VStack(alignment: .leading) { + Text(L10n.Settings.TextRules.loadFailed) + .foregroundStyle(.secondary) + Button(L10n.Localizable.Common.tryAgain) { + Task { await appState.connectionManager.retryTextRulesLoad() } + } + .accessibilityLabel(L10n.Settings.TextRules.retryAccessibility) + } + } + } +} diff --git a/MC1/Views/Settings/Sections/WiFiEditSheet.swift b/MC1/Views/Settings/Sections/WiFiEditSheet.swift index 7491926ae8..48c778c851 100644 --- a/MC1/Views/Settings/Sections/WiFiEditSheet.swift +++ b/MC1/Views/Settings/Sections/WiFiEditSheet.swift @@ -118,17 +118,20 @@ struct WiFiEditSheet: View { Task { do { - // Disconnect from current connection, then connect to new address - await appState.disconnect(reason: .wifiAddressChange) - try await appState.connectViaWiFi( + let result = try await appState.connectViaWiFi( host: WiFiAddressFields.normalizedHost(ipAddress), port: portNumber, forceFullSync: true ) + guard case let .operational(snapshot) = result, appState.connectionManager.isCurrent(snapshot) else { + isReconnecting = false + return + } dismiss() } catch { - errorMessage = error.userFacingMessage isReconnecting = false + guard let failure = appState.currentConnectionFailure(error) else { return } + errorMessage = failure.userFacingMessage } } } diff --git a/MC1/Views/Settings/SettingsDetail.swift b/MC1/Views/Settings/SettingsDetail.swift index 5b87bf1f52..1477f62efa 100644 --- a/MC1/Views/Settings/SettingsDetail.swift +++ b/MC1/Views/Settings/SettingsDetail.swift @@ -10,6 +10,7 @@ enum SettingsDetail: Hashable { case advanced case notifications case chats + case blocksAndFilters case appearance case maps case language @@ -23,7 +24,7 @@ enum SettingsDetail: Hashable { switch self { case .deviceInfo, .radio, .location, .connection, .advanced: true - case .notifications, .chats, .appearance, .maps, .language, .backup, .support, .feedback: + case .notifications, .chats, .blocksAndFilters, .appearance, .maps, .language, .backup, .support, .feedback: false } } diff --git a/MC1/Views/Settings/SettingsDetailView.swift b/MC1/Views/Settings/SettingsDetailView.swift index 591bbf025b..c4ad520f9c 100644 --- a/MC1/Views/Settings/SettingsDetailView.swift +++ b/MC1/Views/Settings/SettingsDetailView.swift @@ -8,6 +8,7 @@ struct SettingsDetailView: View { let requestNameEdit: SettingsEditorPresentation.NameRequest let requestRegionAdd: SettingsEditorPresentation.RegionRequest let backupPresentation: SettingsBackupPresentation? + let configImport: NodeConfigImportViewModel var body: some View { switch detail { @@ -20,11 +21,15 @@ struct SettingsDetailView: View { case .connection: ConnectionSettingsView(descendantPath: descendantPath) case .advanced: - AdvancedSettingsView(descendantPath: descendantPath, requestRegionAdd: requestRegionAdd) + AdvancedSettingsView( + descendantPath: descendantPath, requestRegionAdd: requestRegionAdd, configImport: configImport + ) case .notifications: NotificationSettingsView() case .chats: ChatSettingsView() + case .blocksAndFilters: + BlocksAndFiltersSettingsView() case .appearance: AppearanceView() case .maps: diff --git a/MC1/Views/Settings/SettingsListContent.swift b/MC1/Views/Settings/SettingsListContent.swift index e4e3f12442..0e1512782d 100644 --- a/MC1/Views/Settings/SettingsListContent.swift +++ b/MC1/Views/Settings/SettingsListContent.swift @@ -13,12 +13,22 @@ struct SettingsListContent: View { /// `true` when this list is the iPad split-view sidebar column, whose `.sidebar` style draws /// rows transparent so the column canvas shows through and the native selection highlight shows. let isSidebar: Bool + let requestIdentityRecovery: (IdentityImportRecovery) -> Void private let liveActivityTip = LiveActivityTip() private var settingSelection: Binding { Binding( get: { appState.navigation.selectedSetting }, - set: { appState.navigation.selectedSetting = $0 } + set: { proposed in + // The My Device rows leave while `identityRebuildUnpublished` is set. Ignoring + // that nil write keeps the open page. + if proposed == nil, + appState.navigation.selectedSetting?.requiresDevice == true, + appState.connectionManager.identityRebuildUnpublished { + return + } + appState.navigation.selectedSetting = proposed + } ) } @@ -58,6 +68,26 @@ struct SettingsListContent: View { NoDeviceSection(showingDeviceSelection: $showingDeviceSelection, isSidebar: isSidebar) } + if !appState.connectionManager.identityImportRecoveries.isEmpty { + Section { + ForEach(appState.connectionManager.identityImportRecoveries, id: \.receiptID) { recovery in + Button { + requestIdentityRecovery(recovery) + } label: { + VStack(alignment: .leading) { + TintedLabel(L10n.Settings.ConfigImport.retryIdentityImport, systemImage: "arrow.clockwise") + Text(recovery.sourceName) + Text(recovery.targetDescription) + .font(.footnote) + .foregroundStyle(.secondary) + } + } + .accessibilityIdentifier("settings.identityImportRecovery.\(recovery.receiptID)") + } + } + .themedRowBackground(theme, flatten: isSidebar) + } + Section { SettingsDetailRow(detail: .notifications) { TintedLabel(L10n.Settings.Notifications.header, systemImage: "bell.badge") @@ -67,6 +97,10 @@ struct SettingsListContent: View { TintedLabel(L10n.Settings.ChatSettings.title, systemImage: "bubble.left.and.bubble.right") } + SettingsDetailRow(detail: .blocksAndFilters) { + TintedLabel(L10n.Settings.BlocksAndFilters.title, systemImage: "line.3.horizontal.decrease") + } + AppearanceSection() TipView(liveActivityTip, arrowEdge: .bottom) diff --git a/MC1/Views/Settings/SettingsSubpage.swift b/MC1/Views/Settings/SettingsSubpage.swift index 0ad1b6e9e1..67955a9d75 100644 --- a/MC1/Views/Settings/SettingsSubpage.swift +++ b/MC1/Views/Settings/SettingsSubpage.swift @@ -6,6 +6,8 @@ enum SettingsSubpage: Hashable { case publicKey(Data) case configExport case configImport + case textRuleChats(TextRulesPreference.Kind) + case recentlyBlocked case blockedChannelSenders case blockedContacts case trustedContacts @@ -17,6 +19,8 @@ enum SettingsSubpage: Hashable { case support case bluetoothLink case wifiLink + case deviceInfoTelemetryHistory(publicKey: Data) + case deviceInfoLocationMap(publicKey: Data, fix: NodeLocationFix, name: String?) func isAdmitted(for detail: SettingsDetail?, device: DeviceDTO?) -> Bool { switch self { @@ -24,12 +28,16 @@ enum SettingsSubpage: Hashable { detail == .connection case .publicKey: detail == .deviceInfo + case let .deviceInfoTelemetryHistory(publicKey): + detail == .deviceInfo && device?.publicKey == publicKey + case let .deviceInfoLocationMap(publicKey, _, _): + detail == .deviceInfo && device?.publicKey == publicKey case .configExport, .configImport, .trustedContacts: detail == .advanced case .remoteCLIContacts: detail == .advanced && device?.supportsRadioCLI == true - case .blockedChannelSenders, .blockedContacts: - detail == .chats + case .textRuleChats, .recentlyBlocked, .blockedChannelSenders, .blockedContacts: + detail == .blocksAndFilters case .translateIntoLanguage: detail == .language case .presetLocation: @@ -56,8 +64,9 @@ enum SettingsSubpage: Hashable { private enum SettingsSubpageContext { case standard case radio(PresetLocationSession) - case advanced(RegionDiscoveryState, SettingsEditorPresentation.RegionRequest) + case advanced(RegionDiscoveryState, SettingsEditorPresentation.RegionRequest, NodeConfigImportViewModel) case connection(RadioWiFiViewModel) + case deviceInfo(DeviceInfoTelemetryViewModel) } extension View { @@ -71,14 +80,19 @@ extension View { func settingsSubpageDestinations( regions discovery: RegionDiscoveryState, - requestRegionAdd: @escaping SettingsEditorPresentation.RegionRequest + requestRegionAdd: @escaping SettingsEditorPresentation.RegionRequest, + configImport: NodeConfigImportViewModel ) -> some View { - modifier(SettingsSubpageRegistration(context: .advanced(discovery, requestRegionAdd))) + modifier(SettingsSubpageRegistration(context: .advanced(discovery, requestRegionAdd, configImport))) } func settingsSubpageDestinations(radioWiFi: RadioWiFiViewModel) -> some View { modifier(SettingsSubpageRegistration(context: .connection(radioWiFi))) } + + func settingsSubpageDestinations(deviceInfoTelemetry model: DeviceInfoTelemetryViewModel) -> some View { + modifier(SettingsSubpageRegistration(context: .deviceInfo(model))) + } } /// Stack destinations are siblings, so child pages receive their root's context explicitly. @@ -103,7 +117,14 @@ private struct SettingsSubpageDestination: View { case .configExport: NodeConfigExportView() case .configImport: - NodeConfigImportView() + if case let .advanced(_, _, configImport) = context { + NodeConfigImportView(viewModel: configImport) + .onAppear { configImport.beginImport() } + } + case let .textRuleChats(kind): + TextRuleChatsView(kind: kind) + case .recentlyBlocked: + RecentlyBlockedView() case .blockedChannelSenders: BlockedChannelSendersView() case .blockedContacts: @@ -124,7 +145,7 @@ private struct SettingsSubpageDestination: View { .environment(session) } case .manageRegions: - if case let .advanced(discovery, requestRegionAdd) = context { + if case let .advanced(discovery, requestRegionAdd, _) = context { ManageRegionsPage(discovery: discovery, requestRegionAdd: requestRegionAdd) } case .bluetoothLink: @@ -133,6 +154,12 @@ private struct SettingsSubpageDestination: View { if case let .connection(radioWiFi) = context { ConnectionWiFiPage(radioWiFi: radioWiFi) } + case .deviceInfoTelemetryHistory: + if case let .deviceInfo(model) = context { + TelemetryHistoryView(fetchSnapshots: model.fetchHistory, ocvArray: model.ocvValues) + } + case let .deviceInfoLocationMap(_, fix, name): + nodeLocationMap(fix: fix, name: name) } } } diff --git a/MC1/Views/Settings/SettingsView.swift b/MC1/Views/Settings/SettingsView.swift index 745868cfe5..40a6c2839c 100644 --- a/MC1/Views/Settings/SettingsView.swift +++ b/MC1/Views/Settings/SettingsView.swift @@ -13,6 +13,8 @@ struct SettingsView: View { @State private var nestedPath: [SettingsSubpage] = [] @State private var editorPresentation = SettingsEditorPresentation() @State private var backupPresentation: SettingsBackupPresentation? + @State private var configImport = NodeConfigImportViewModel() + @State private var showingIdentityRecovery = false private var demoModeManager = DemoModeManager.shared private var tabBarVisibility: Visibility { @@ -94,7 +96,10 @@ struct SettingsView: View { SettingsListContent( showingDeviceSelection: $showingDeviceSelection, demoModeManager: demoModeManager, - isSidebar: sizeClass == .regular + isSidebar: sizeClass == .regular, + requestIdentityRecovery: { recovery in + if configImport.beginRecovery(recovery) { showingIdentityRecovery = true } + } ) .sectionSplitColumnChrome() } detail: { @@ -106,7 +111,8 @@ struct SettingsView: View { descendantPath: nestedPath, requestNameEdit: requestNameEdit, requestRegionAdd: requestRegionAdd, - backupPresentation: currentBackupPresentation + backupPresentation: currentBackupPresentation, + configImport: configImport ) } else { ContentUnavailableView(L10n.Settings.selectSetting, systemImage: "gear") @@ -116,6 +122,19 @@ struct SettingsView: View { } .id(appState.navigation.selectedSetting) } + .sheet(isPresented: $showingIdentityRecovery) { + NavigationStack { + NodeConfigImportView(viewModel: configImport) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button(L10n.Localizable.Common.done) { showingIdentityRecovery = false } + .disabled(configImport.recoverySheetDismissalDisabled) + } + } + .interactiveDismissDisabled(configImport.recoverySheetDismissalDisabled) + } + } + .onAppear { configureConfigImport() } .navigationSplitViewStyle(.balanced) .sectionSplitChrome(tabBarVisibility: tabBarVisibility) .sectionSplitState( @@ -140,6 +159,13 @@ struct SettingsView: View { device: appState.connectedDevice ) } + .onChange(of: appState.connectedDevice?.publicKey) { _, _ in + nestedPath = SettingsSubpage.admitted( + nestedPath, + for: appState.navigation.selectedSetting, + device: appState.connectedDevice + ) + } .onChange(of: appState.navigation.settingsPresentationRevision, initial: true) { _, _ in prepareBackupPresentation() } @@ -159,6 +185,16 @@ struct SettingsView: View { )) } + private func configureConfigImport() { + let appState = appState + configImport.configure( + nodeConfigService: { appState.services?.nodeConfigService }, + settingsService: { appState.services?.settingsService }, + connectedDevice: { appState.connectedDevice }, + connectionManager: appState.connectionManager + ) + } + private func prepareBackupPresentation() { let appState = appState let navigation = appState.navigation diff --git a/MC1/Views/Support/Components/ContributionRow.swift b/MC1/Views/Support/Components/ContributionRow.swift index 27ea2e2c6e..d12d3c2fdb 100644 --- a/MC1/Views/Support/Components/ContributionRow.swift +++ b/MC1/Views/Support/Components/ContributionRow.swift @@ -18,16 +18,6 @@ struct ContributionRow: View { Spacer() priceButton } - .confirmationDialog( - L10n.Settings.Support.Contributions.highValueConfirm(displayName), - isPresented: $showingConfirmation, - titleVisibility: .visible - ) { - Button(L10n.Settings.Support.Contributions.confirmButton(displayPrice ?? displayName)) { - Task { await runPurchase() } - } - Button(L10n.Localizable.Common.cancel, role: .cancel) {} - } .accessibilityElement(children: .ignore) .accessibilityLabel(L10n.Settings.Support.Accessibility.ContributionRow.label(displayName, displayPrice ?? "")) .accessibilityHint(L10n.Settings.Support.Accessibility.ContributionRow.hint) @@ -49,6 +39,16 @@ struct ContributionRow: View { } .buttonStyle(.bordered) .disabled(displayPrice == nil || isPurchasing) + .confirmationDialog( + L10n.Settings.Support.Contributions.highValueConfirm(displayName), + isPresented: $showingConfirmation, + titleVisibility: .visible + ) { + Button(L10n.Settings.Support.Contributions.confirmButton(displayPrice ?? displayName)) { + Task { await runPurchase() } + } + Button(L10n.Localizable.Common.cancel, role: .cancel) {} + } } private func runPurchase() async { diff --git a/MC1/Views/Tools/CLI/CLICompletionEngine.swift b/MC1/Views/Tools/CLI/CLICompletionEngine.swift index 1565874922..d093d2d45b 100644 --- a/MC1/Views/Tools/CLI/CLICompletionEngine.swift +++ b/MC1/Views/Tools/CLI/CLICompletionEngine.swift @@ -57,6 +57,13 @@ final class CLICompletionEngine { "start" ] + private static let sensorCommands = [ + "ver", "board", "clock", "clkreboot", "get", "set", "sensor", "password", + "reboot", "poweroff", "shutdown", "power", "advert", "advert.zerohop", "gps" + ] + private static let sensorGetKeys = ["role", "name", "radio", "tx", "lat", "lon", "public.key"] + private static let sensorSetKeys = ["name", "radio", "tx", "lat", "lon"] + private static let sessionSubcommands = ["list", "local"] private static let sensorSubcommands = ["get", "list", "set"] @@ -218,6 +225,18 @@ final class CLICompletionEngine { // A trailing space starts the next argument (position = parts.count); otherwise we are still typing the current one. let argPosition = endsWithSpace ? parts.count : parts.count - 1 + if remoteTarget == .sensor, !isLocal { + let options: [String] = switch command { + case "get": Self.sensorGetKeys + case "set": Self.sensorSetKeys + case "sensor": Self.sensorSubcommands + case "clock": Self.clockSubcommands + case "gps": ["on", "off"] + default: [] + } + return argPosition == 1 ? options.filter { $0.hasPrefix(prefix) }.sorted() : [] + } + switch command { case "session", "login", "log", "powersaving", "clear", "clock", "start": // 1-arg commands: only complete when argPosition == 1 @@ -307,13 +326,15 @@ final class CLICompletionEngine { ) -> [String] { var commands = Self.builtInCommands - if includeSessionCommands { + if includeSessionCommands, remoteTarget != .sensor { commands.append(contentsOf: Self.sessionCommands) } if isLocal { commands.append(contentsOf: Self.localOnlyCommands) commands.append(contentsOf: Self.localRadioCommands) + } else if remoteTarget == .sensor { + commands.append(contentsOf: Self.sensorCommands) } else if remoteTarget == .radio { commands.append(contentsOf: Self.radioCommands) } else { diff --git a/MC1/Views/Tools/CLI/CLIRemoteTarget.swift b/MC1/Views/Tools/CLI/CLIRemoteTarget.swift index 01366fe4af..c4d6e28a25 100644 --- a/MC1/Views/Tools/CLI/CLIRemoteTarget.swift +++ b/MC1/Views/Tools/CLI/CLIRemoteTarget.swift @@ -4,6 +4,7 @@ import MC1Services enum CLIRemoteTarget: Hashable, Sendable { case repeater case room + case sensor /// A chat contact's radio. Callers set this directly. `init?(contactType:)` stays nil for chat. case radio @@ -11,6 +12,7 @@ enum CLIRemoteTarget: Hashable, Sendable { switch role { case .repeater: self = .repeater case .roomServer: self = .room + case .sensor: self = .sensor } } @@ -18,6 +20,7 @@ enum CLIRemoteTarget: Hashable, Sendable { switch contactType { case .repeater: self = .repeater case .room: self = .room + case .sensor: self = .sensor case .chat: return nil } } diff --git a/MC1/Views/Tools/CLI/CLIToolViewModel+LocalCommands.swift b/MC1/Views/Tools/CLI/CLIToolViewModel+LocalCommands.swift index 43dd3ac4e7..681e9bfef2 100644 --- a/MC1/Views/Tools/CLI/CLIToolViewModel+LocalCommands.swift +++ b/MC1/Views/Tools/CLI/CLIToolViewModel+LocalCommands.swift @@ -33,12 +33,19 @@ extension CLIToolViewModel { } /// Sends an unmapped local line via Radio CLI and prints the UTF-8 reply. - func runRadioCLI(_ raw: String) async { - guard let settingsService else { return notConnected() } + func runRadioCLI(_ raw: String, intent: RadioCLIIntent?) async { + guard let intent else { return notConnected() } + guard isCurrent(intent), let settingsService else { return } do { - let reply = try await settingsService.runCliCommand(raw) + let reply = try await settingsService.runCliCommand(raw, expectedContextID: intent.contextID) + guard isCurrent(intent) else { return } output(reply) - } catch { renderError(error) } + } catch is CancellationError { + return + } catch { + guard isCurrent(intent) else { return } + renderError(error) + } } /// Renders a parser error as a usage or error output line. diff --git a/MC1/Views/Tools/CLI/CLIToolViewModel.swift b/MC1/Views/Tools/CLI/CLIToolViewModel.swift index cb7b9c2f1e..b3368bf31f 100644 --- a/MC1/Views/Tools/CLI/CLIToolViewModel.swift +++ b/MC1/Views/Tools/CLI/CLIToolViewModel.swift @@ -10,6 +10,12 @@ final class CLIToolViewModel { private static let maxHistoryEntries = 100 static let logger = Logger(subsystem: "com.mc1", category: "CLIToolViewModel") + struct RadioCLIIntent { + let serviceID: ObjectIdentifier + let contextID: UUID + let radioID: UUID + } + // MARK: - State private(set) var outputLines: [CLIOutputLine] = [] @@ -312,7 +318,10 @@ final class CLIToolViewModel { return } - let recorded = radioCLILine(original: command, normalized: trimmed) + let isRadioCLI = activeSession?.isLocal == true + && connectedDevice?.supportsRadioCLI == true && RadioCLIPassthrough.shouldSend(trimmed) + let intent = isRadioCLI ? captureRadioCLIIntent() : nil + let recorded = isRadioCLI ? command : trimmed addToHistory(recorded) appendOutput("\(promptPrefix) \(recorded)", type: .command) @@ -327,7 +336,11 @@ final class CLIToolViewModel { var task: Task! task = Task { defer { clearWaitingIfCurrent(task) } - await handleCommand(cmd, args: args, raw: recorded) + if isRadioCLI { + await runRadioCLI(recorded, intent: intent) + } else { + await handleCommand(cmd, args: args, raw: recorded) + } } currentCommandTask = task @@ -361,14 +374,21 @@ final class CLIToolViewModel { isWaitingForResponse = false } - /// Radio CLI passthrough keeps the submitted line. App commands keep the trimmed line. - private func radioCLILine(original: String, normalized: String) -> String { - guard activeSession?.isLocal == true, - connectedDevice?.supportsRadioCLI == true, - RadioCLIPassthrough.shouldSend(normalized) else { - return normalized - } - return original + func captureRadioCLIIntent() -> RadioCLIIntent? { + guard let settingsService, let radioID = connectedDevice?.radioID else { return nil } + let binding = settingsService.radioWiFiBinding + guard binding.state.radioID == radioID else { return nil } + return RadioCLIIntent( + serviceID: ObjectIdentifier(settingsService), contextID: binding.contextID, radioID: radioID + ) + } + + func isCurrent(_ intent: RadioCLIIntent) -> Bool { + guard activeSession?.isLocal == true, connectedDevice?.radioID == intent.radioID, + let settingsService else { return false } + let binding = settingsService.radioWiFiBinding + return ObjectIdentifier(settingsService) == intent.serviceID + && binding.contextID == intent.contextID && binding.state.radioID == intent.radioID } private func addToHistory(_ command: String) { @@ -386,15 +406,6 @@ final class CLIToolViewModel { return } - // Local radio commands are interpreted app-side; the same words keep passing - // through to repeaters on remote sessions. - if activeSession?.isLocal == true, - connectedDevice?.supportsRadioCLI == true, - RadioCLIPassthrough.shouldSend(raw) { - await runRadioCLI(raw) - return - } - if activeSession?.isLocal == true { switch CLILocalCommandParser.parse(raw) { case let .command(command): diff --git a/MC1/Views/Tools/NodeDiscovery/NodeDiscoveryView.swift b/MC1/Views/Tools/NodeDiscovery/NodeDiscoveryView.swift index d7f27fc811..bd6be19e3d 100644 --- a/MC1/Views/Tools/NodeDiscovery/NodeDiscoveryView.swift +++ b/MC1/Views/Tools/NodeDiscovery/NodeDiscoveryView.swift @@ -136,7 +136,7 @@ extension NodeDiscoveryWorkspace { result: result, isAdded: viewModel.isAdded(publicKey: result.publicKey), isAdding: viewModel.addingPublicKey == result.publicKey, - onAdd: ContactType(rawValue: result.nodeType) != nil + onAdd: viewModel.canAdd(result) ? { viewModel.addNode(result) } : nil ) diff --git a/MC1/Views/Tools/NodeDiscovery/NodeDiscoveryViewModel.swift b/MC1/Views/Tools/NodeDiscovery/NodeDiscoveryViewModel.swift index 5e25b492a9..6ebbf39d20 100644 --- a/MC1/Views/Tools/NodeDiscovery/NodeDiscoveryViewModel.swift +++ b/MC1/Views/Tools/NodeDiscovery/NodeDiscoveryViewModel.swift @@ -16,6 +16,13 @@ enum NodeDiscoveryFilter: String, CaseIterable { } } + func matches(_ type: ContactType) -> Bool { + switch self { + case .repeaters: type == .repeater + case .sensors: type == .sensor + } + } + var localizedTitle: String { switch self { case .repeaters: L10n.Tools.Tools.NodeDiscovery.repeaters @@ -62,7 +69,7 @@ struct NodeDiscoveryResult: Identifiable { @MainActor final class NodeDiscoveryViewModel { private static let logger = Logger(subsystem: "com.mc1", category: "NodeDiscoveryViewModel") - private static let scanDuration: Duration = .seconds(15) + private static let scanSeconds: TimeInterval = 15 // MARK: - Published state @@ -184,11 +191,14 @@ final class NodeDiscoveryViewModel { } guard ticket.isCurrent(in: self.scanEpoch), !Task.isCancelled else { return } - let tag = try await self.sendDiscover(filter: activeFilter.filterValue) + let subscribed = self.session + let events = await subscribed?.events(filter: Self.discoverFilter) + guard ticket.isCurrent(in: self.scanEpoch), !Task.isCancelled else { return } + let tag = try await self.sendDiscover(filter: activeFilter.filterValue, tag: UInt32.random(in: 1...UInt32.max)) guard ticket.isCurrent(in: self.scanEpoch), !Task.isCancelled else { return } let tagData = withUnsafeBytes(of: tag.littleEndian) { Data($0) } self.armScanDeadline(ticket: ticket) - await self.listen(ticket: ticket, tag: tagData) + await self.listen(ticket: ticket, tag: tagData, filter: activeFilter, events: events, subscribed: subscribed) } catch is CancellationError { return } catch { @@ -239,6 +249,7 @@ final class NodeDiscoveryViewModel { for key in Array(addEpochs.keys) { addEpochs[key]?.bump() } + addTickets.removeAll() stopScan() results.removeAll() addedPublicKeys.removeAll() @@ -278,17 +289,17 @@ final class NodeDiscoveryViewModel { return scanDurationForTesting } #endif - return 15 + return Self.scanSeconds } - private func sendDiscover(filter: UInt8) async throws -> UInt32 { + private func sendDiscover(filter: UInt8, tag: UInt32) async throws -> UInt32 { #if DEBUG if let sendDiscoverForTesting { return try await sendDiscoverForTesting(filter) } #endif guard let session else { throw CancellationError() } - return try await session.sendNodeDiscoverRequest(filter: filter, prefixOnly: false) + return try await session.sendNodeDiscoverRequest(filter: filter, prefixOnly: false, tag: tag) } private func armScanDeadline(ticket: Epoch.Ticket) { @@ -299,34 +310,51 @@ final class NodeDiscoveryViewModel { if seconds > 0 { try? await Task.sleep(for: .seconds(seconds)) } - guard let self, ticket.isCurrent(in: self.scanEpoch) else { return } + guard let self, !Task.isCancelled, ticket.isCurrent(in: self.scanEpoch) else { return } self.finishScan() } } - private func listen(ticket: Epoch.Ticket, tag: Data) async { - let discoverFilter = EventFilter.eventType { event in - if case .discoverResponse = event { return true } - return false - } + private static let discoverFilter = EventFilter.eventType { event in + if case .discoverResponse = event { return true } + return false + } + + private func listen( + ticket: Epoch.Ticket, + tag: Data, + filter: NodeDiscoveryFilter, + events initialEvents: AsyncStream?, + subscribed initialSession: MeshCoreSession? + ) async { + var bufferedEvents = initialEvents + var bufferedSession = initialSession while ticket.isCurrent(in: scanEpoch), acceptResponses, !Task.isCancelled { - guard let session else { + guard let subscribed = bufferedSession ?? session else { await waitForSession() continue } + let events: AsyncStream = if let bufferedEvents { + bufferedEvents + } else { + await subscribed.events(filter: Self.discoverFilter) + } + bufferedEvents = nil + bufferedSession = nil let generation = listenGeneration - let subscribed = session #if DEBUG isListeningForTesting = true #endif - let events = await session.events(filter: discoverFilter) for await event in events { #if DEBUG listenLoopIterationsForTesting += 1 #endif guard generation == listenGeneration, ticket.isCurrent(in: scanEpoch), acceptResponses else { break } if case let .discoverResponse(response) = event, response.tag == tag { - appendOrUpdateResult(from: response) + guard (scanDeadline.map { Date() < $0 } ?? false), + let type = ContactType(rawValue: response.nodeType), + filter.matches(type) else { continue } + appendOrUpdateResult(from: response, filter: filter) } } #if DEBUG @@ -398,7 +426,7 @@ final class NodeDiscoveryViewModel { return "\(L10n.Tools.Tools.NodeDiscovery.unknownNode) (\(hexPrefix))" } - private func appendOrUpdateResult(from response: DiscoverResponse) { + private func appendOrUpdateResult(from response: DiscoverResponse, filter: NodeDiscoveryFilter) { let result = NodeDiscoveryResult( name: resolveName(for: response.publicKey), publicKey: response.publicKey, @@ -417,6 +445,15 @@ final class NodeDiscoveryViewModel { } private func finishScan() { + acceptResponses = false + wakeListener() + scanTask?.cancel() + scanTask = nil + timeoutTask?.cancel() + timeoutTask = nil + #if DEBUG + isListeningForTesting = false + #endif isScanning = false if results.contains(where: { $0.scanFilter == filter }) { scanSuccessHapticTrigger += 1 @@ -431,7 +468,16 @@ final class NodeDiscoveryViewModel { addedPublicKeys.contains(publicKey) } + func canAdd(_ result: NodeDiscoveryResult) -> Bool { + guard result.publicKey.count == ProtocolLimits.publicKeySize, + let type = ContactType(rawValue: result.nodeType) else { return false } + return result.scanFilter.matches(type) + } + func addNode(_ result: NodeDiscoveryResult) { + guard canAdd(result), !isAdded(publicKey: result.publicKey), + addTickets[result.publicKey] == nil, + let type = ContactType(rawValue: result.nodeType) else { return } guard (contactService != nil && radioID != nil) || hasAddTestHook else { return } var epoch = addEpochs[result.publicKey] ?? Epoch() @@ -440,14 +486,15 @@ final class NodeDiscoveryViewModel { let ticket = epoch.ticket() addTickets[result.publicKey] = ticket let capturedRadioID = radioID + let admittedContactService = contactService addingPublicKey = result.publicKey Task { [weak self] in - guard let self else { return } + guard let self, self.addTicketIsCurrent(result.publicKey, ticket: ticket) else { return } do { let contact = ContactFrame( publicKey: result.publicKey, - type: ContactType(rawValue: result.nodeType) ?? .repeater, + type: type, flags: 0, outPathLength: PacketBuilder.floodPathSentinel, outPath: Data(), @@ -457,12 +504,12 @@ final class NodeDiscoveryViewModel { longitude: 0, lastModified: 0 ) - try await self.performAdd(contact: contact, capturedRadioID: capturedRadioID) - guard self.addTicketIsCurrent(result.publicKey) else { return } + try await self.performAdd(contact: contact, capturedRadioID: capturedRadioID, admittedContactService: admittedContactService) + guard self.addTicketIsCurrent(result.publicKey, ticket: ticket) else { return } self.addedPublicKeys.insert(result.publicKey) self.addSuccessHapticTrigger += 1 } catch ContactServiceError.contactTableFull { - guard self.addTicketIsCurrent(result.publicKey) else { return } + guard self.addTicketIsCurrent(result.publicKey, ticket: ticket) else { return } if let maxContacts = self.maxContacts { self.errorMessage = L10n.Contacts.Contacts.Add.Error.nodeListFull(Int(maxContacts)) } else { @@ -470,12 +517,13 @@ final class NodeDiscoveryViewModel { } self.addErrorHapticTrigger += 1 } catch { - guard self.addTicketIsCurrent(result.publicKey) else { return } + guard self.addTicketIsCurrent(result.publicKey, ticket: ticket) else { return } self.errorMessage = error.userFacingMessage self.addErrorHapticTrigger += 1 } - guard self.addTicketIsCurrent(result.publicKey) else { return } - self.addingPublicKey = nil + guard self.addTicketIsCurrent(result.publicKey, ticket: ticket) else { return } + self.addTickets[result.publicKey] = nil + if self.addingPublicKey == result.publicKey { self.addingPublicKey = nil } } } @@ -487,21 +535,27 @@ final class NodeDiscoveryViewModel { #endif } - private func performAdd(contact: ContactFrame, capturedRadioID: UUID?) async throws { + private func performAdd( + contact: ContactFrame, + capturedRadioID: UUID?, + admittedContactService: ContactService? + ) async throws { #if DEBUG if let addContactForTesting { try await addContactForTesting(contact) return } #endif - guard let contactService, let capturedRadioID else { throw CancellationError() } + guard let contactService = admittedContactService, self.contactService === contactService, + let capturedRadioID else { throw CancellationError() } try await contactService.addOrUpdateContact(radioID: capturedRadioID, contact: contact) { - self.radioID + guard self.contactService === contactService else { return nil } + return self.radioID } } - private func addTicketIsCurrent(_ publicKey: Data) -> Bool { - guard let ticket = addTickets[publicKey], let epoch = addEpochs[publicKey] else { return false } + private func addTicketIsCurrent(_ publicKey: Data, ticket: Epoch.Ticket) -> Bool { + guard let epoch = addEpochs[publicKey] else { return false } return ticket.isCurrent(in: epoch) } } diff --git a/MC1/Views/Tools/TracePath/Map/PathActionsSectionView.swift b/MC1/Views/Tools/TracePath/Map/PathActionsSectionView.swift index ac3b74ee79..b6ff4f5348 100644 --- a/MC1/Views/Tools/TracePath/Map/PathActionsSectionView.swift +++ b/MC1/Views/Tools/TracePath/Map/PathActionsSectionView.swift @@ -79,6 +79,17 @@ struct PathActionsSectionView: View { Button(L10n.Contacts.Contacts.Trace.clearPath, systemImage: "trash", role: .destructive) { showingClearConfirmation = true } + .confirmationDialog( + L10n.Contacts.Contacts.Trace.clearPath, + isPresented: $showingClearConfirmation, + titleVisibility: .visible + ) { + Button(L10n.Contacts.Contacts.Trace.clearPath, role: .destructive) { + viewModel.clearPath() + } + } message: { + Text(L10n.Contacts.Contacts.Trace.clearPathMessage) + } } } footer: { if !viewModel.outboundPath.isEmpty { diff --git a/MC1/Views/Tools/TracePath/SavedPathsSheet.swift b/MC1/Views/Tools/TracePath/SavedPathsSheet.swift index f475fac2f1..bf2522905c 100644 --- a/MC1/Views/Tools/TracePath/SavedPathsSheet.swift +++ b/MC1/Views/Tools/TracePath/SavedPathsSheet.swift @@ -41,28 +41,6 @@ struct SavedPathsSheet: View { await viewModel.loadSavedPaths() } .errorAlert($viewModel.errorMessage) - .confirmationDialog( - L10n.Contacts.Contacts.SavedPaths.deleteTitle, - isPresented: .init( - get: { pathToDelete != nil }, - set: { if !$0 { pathToDelete = nil } } - ), - titleVisibility: .visible - ) { - Button(L10n.Contacts.Contacts.Common.delete, role: .destructive) { - if let path = pathToDelete { - let pathId = path.id - Task { - await viewModel.deletePath(path) - onDelete?(pathId) - } - } - } - } message: { - if let path = pathToDelete { - Text(L10n.Contacts.Contacts.SavedPaths.deleteMessage(path.name)) - } - } .alert(L10n.Contacts.Contacts.SavedPaths.renameTitle, isPresented: .init( get: { pathToRename != nil }, set: { if !$0 { pathToRename = nil } } @@ -117,6 +95,28 @@ struct SavedPathsSheet: View { pathToDelete = path } } + .confirmationDialog( + L10n.Contacts.Contacts.SavedPaths.deleteTitle, + isPresented: .init( + get: { pathToDelete?.id == path.id }, + set: { if !$0, pathToDelete?.id == path.id { pathToDelete = nil } } + ), + titleVisibility: .visible + ) { + Button(L10n.Contacts.Contacts.Common.delete, role: .destructive) { + if let path = pathToDelete { + let pathId = path.id + Task { + await viewModel.deletePath(path) + onDelete?(pathId) + } + } + } + } message: { + if let path = pathToDelete { + Text(L10n.Contacts.Contacts.SavedPaths.deleteMessage(path.name)) + } + } .transition(.opacity) if index < viewModel.savedPaths.count - 1 { Divider().padding(.leading, Self.rowHorizontalPadding) diff --git a/MC1/Views/Tools/TracePath/TracePathView.swift b/MC1/Views/Tools/TracePath/TracePathView.swift index f3951c7bf1..959f11319a 100644 --- a/MC1/Views/Tools/TracePath/TracePathView.swift +++ b/MC1/Views/Tools/TracePath/TracePathView.swift @@ -108,17 +108,6 @@ private struct TracePathWorkspace: View { .presentationDetents([.large]) .presentationDragIndicator(.visible) } - .confirmationDialog( - L10n.Contacts.Contacts.Trace.clearPath, - isPresented: $showingClearConfirmation, - titleVisibility: .visible - ) { - Button(L10n.Contacts.Contacts.Trace.clearPath, role: .destructive) { - viewModel.clearPath() - } - } message: { - Text(L10n.Contacts.Contacts.Trace.clearPathMessage) - } .alert(L10n.Contacts.Contacts.Trace.failed, isPresented: Binding( get: { viewModel.errorMessage != nil }, set: { if !$0 { viewModel.clearError() } } diff --git a/MC1/Views/Tools/TracePath/TracePathViewModel.swift b/MC1/Views/Tools/TracePath/TracePathViewModel.swift index 4173722075..1ed6963c3a 100644 --- a/MC1/Views/Tools/TracePath/TracePathViewModel.swift +++ b/MC1/Views/Tools/TracePath/TracePathViewModel.swift @@ -48,6 +48,7 @@ final class TracePathViewModel { /// Buffer between consecutive batch traces to avoid network flooding. private static let interTraceBufferMs = 500 + private static let millisecondsPerSecond: Double = 1000 // MARK: - Batch Trace State @@ -66,9 +67,6 @@ final class TracePathViewModel { /// Flag to signal batch loop should stop (since we await in the calling context) private var batchCancelled = false - /// Continuation for awaiting trace response in batch mode - private var traceContinuation: CheckedContinuation? - var isBatchInProgress: Bool { batchEnabled && currentTraceIndex > 0 && currentTraceIndex <= batchSize } @@ -152,25 +150,14 @@ final class TracePathViewModel { // MARK: - Trace Correlation - private var pendingTag: UInt32? - private var pendingDeviceID: UUID? // Track which device initiated trace - private var traceStartTime: Date? - private var timeoutTask: Task? + private var traceRequest: TraceRequestState = .idle private var executionTask: Task? /// Owns one run. Hiding the tool does not bump it. private var executionEpoch = Epoch() - private var waitingTicket: Epoch.Ticket? - private var responseDeadline: Date? - private var pendingIsBatch = false private var isWorkspaceVisible = false private var resultDismissedWhileVisible = false private var presentedSuccessID: UUID? - // MARK: - Path Hash Tracking (for save validation) - - private var pendingPathHash: [UInt8]? - // resultPathHash removed - now derived from result.tracedPathBytes - // MARK: - Event Subscription private var traceEventsTask: Task? @@ -226,7 +213,7 @@ final class TracePathViewModel { } errorAutoClearTask?.cancel() errorAutoClearTask = nil - if pendingTag == nil, executionTask == nil { + if traceRequest.submission == nil, executionTask == nil { stopListening() } } @@ -234,15 +221,15 @@ final class TracePathViewModel { /// Same-device ready. Attaches a waiting run to the service the provider /// returns now and does not bump the epoch. func reattachIfWaiting() { - guard pendingTag != nil else { return } + guard traceRequest.submission != nil else { return } startListening() } /// Foreground return. A deadline that passed while `Task.sleep` was /// suspended ends the run through the same path as an in-process timeout. func expireWaitingRunIfDeadlinePassed() { - guard let deadline = responseDeadline, Date() >= deadline, let tag = pendingTag else { return } - applyTimeout(tag: tag) + guard case let .waiting(submission, wait) = traceRequest, Date() >= wait.deadline else { return } + applyTimeout(tag: submission.tag) } func noteResultSheetDismissed() { @@ -259,8 +246,7 @@ final class TracePathViewModel { /// List mode asks once per stored success. A second call for the same /// `resultID` returns nil. Map mode does not call this. func consumeStoredResultForPresentation() -> TraceResult? { - guard isWorkspaceVisible, let result, result.success, let resultID else { return nil } - guard !resultDismissedWhileVisible, presentedSuccessID != resultID else { return nil } + guard isWorkspaceVisible, let result, result.success, let resultID, !resultDismissedWhileVisible, presentedSuccessID != resultID else { return nil } let batchStillSending = isBatchInProgress guard !isRunning || batchStillSending else { return nil } presentedSuccessID = resultID @@ -277,7 +263,6 @@ final class TracePathViewModel { completedResults.removeAll() clearBatchState() activeSavedPath = nil - responseDeadline = nil presentedSuccessID = nil resultDismissedWhileVisible = false clearError() @@ -377,12 +362,11 @@ final class TracePathViewModel { /// Can save path if result is successful and path hasn't changed since trace ran var canSavePath: Bool { if batchEnabled { - guard !completedResults.isEmpty else { return false } - guard let firstSuccess = successfulResults.first else { return false } - return fullPathBytes == firstSuccess.tracedPathBytes + guard !completedResults.isEmpty, let firstSuccess = successfulResults.first else { return false } + return fullPathBytes == firstSuccess.tracedPathBytes && hashSize == firstSuccess.hashSize } else { guard let result, result.success else { return false } - return fullPathBytes == result.tracedPathBytes + return fullPathBytes == result.tracedPathBytes && hashSize == result.hashSize } } @@ -393,8 +377,7 @@ final class TracePathViewModel { /// 2. Intermediate repeaters only if device lacks location /// 3. Nil if fewer than 2 hops with valid location var totalPathDistance: Double? { - guard let result, result.success else { return nil } - guard result.hops.count >= 2 else { return nil } + guard let result, result.success, result.hops.count >= 2 else { return nil } // Priority 1: Full path including device legs if let fullDistance = calculateDistance(for: result.hops) { @@ -441,9 +424,7 @@ final class TracePathViewModel { /// Whether the distance calculation used intermediate-only fallback (device has no location) var isDistanceUsingFallback: Bool { - guard let result, result.success, totalPathDistance != nil else { return false } - - guard let startNode = result.hops.first, let endNode = result.hops.last else { return false } + guard let result, result.success, totalPathDistance != nil, let startNode = result.hops.first, let endNode = result.hops.last else { return false } // If device nodes lack location, we used the intermediate-only fallback return !startNode.hasLocation || !endNode.hasLocation @@ -542,7 +523,6 @@ final class TracePathViewModel { let hop = PathHop(hashBytes: hashBytes, publicKey: node.publicKey, resolvedName: node.resolvableName) outboundPath.append(hop) activeSavedPath = nil - pendingPathHash = nil result = nil } @@ -566,7 +546,6 @@ final class TracePathViewModel { return hop } activeSavedPath = nil - pendingPathHash = nil result = nil } @@ -591,7 +570,6 @@ final class TracePathViewModel { // Clear saved path reference if we added anything if !result.added.isEmpty { activeSavedPath = nil - pendingPathHash = nil self.result = nil clearError() } @@ -605,7 +583,6 @@ final class TracePathViewModel { guard outboundPath.indices.contains(index) else { return } outboundPath.remove(at: index) activeSavedPath = nil - pendingPathHash = nil result = nil } @@ -614,7 +591,6 @@ final class TracePathViewModel { clearError() outboundPath.move(fromOffsets: source, toOffset: destination) activeSavedPath = nil - pendingPathHash = nil result = nil } @@ -670,7 +646,7 @@ final class TracePathViewModel { radioID: radioID, name: name, pathBytes: Data(firstSuccess.tracedPathBytes), - hashSize: hashSize, + hashSize: firstSuccess.hashSize, initialRun: initialRun ) @@ -717,7 +693,7 @@ final class TracePathViewModel { radioID: radioID, name: name, pathBytes: Data(result.tracedPathBytes), - hashSize: hashSize, + hashSize: result.hashSize, initialRun: initialRun ) activeSavedPath = savedPath @@ -758,7 +734,6 @@ final class TracePathViewModel { func loadSavedPath(_ savedPath: SavedTracePathDTO) { outboundPath.removeAll() result = nil - pendingPathHash = nil let fullPath = savedPath.pathBytes let size = savedPath.hashSize @@ -804,7 +779,6 @@ final class TracePathViewModel { activeSavedPath = nil outboundPath.removeAll() result = nil - pendingPathHash = nil traceHashMode = nil } @@ -868,31 +842,19 @@ final class TracePathViewModel { private func runTrace(ticket: Epoch.Ticket) async { guard isCurrent(ticket), canSendTrace, !outboundPath.isEmpty else { return } - timeoutTask?.cancel() - timeoutTask = nil - resultID = nil clearError() - if activeSavedPath == nil { - if let matchedPath = await findMatchingSavedPath() { - guard isCurrent(ticket) else { return } - activeSavedPath = matchedPath - logger.info("Matched path to saved path: \(matchedPath.name)") - } + if activeSavedPath == nil, let matchedPath = await findMatchingSavedPath() { + guard isCurrent(ticket) else { return } + activeSavedPath = matchedPath + logger.info("Matched path to saved path: \(matchedPath.name)") } guard isCurrent(ticket) else { return } isRunning = true result = nil - pendingPathHash = fullPathBytes - - switch await sendAndArm(ticket: ticket, isBatch: false) { - case .abandoned, .failedBeforeTag: - return - case .waiting: - armCurrentWait(ticket: ticket) - } + await sendAndArm(ticket: ticket, isBatch: false) } // MARK: - Batch Trace Execution @@ -915,12 +877,10 @@ final class TracePathViewModel { guard isCurrent(ticket), canSendTrace, !outboundPath.isEmpty else { return } - if activeSavedPath == nil { - if let matchedPath = await findMatchingSavedPath() { - guard isCurrent(ticket) else { return } - activeSavedPath = matchedPath - logger.info("Matched path to saved path: \(matchedPath.name)") - } + if activeSavedPath == nil, let matchedPath = await findMatchingSavedPath() { + guard isCurrent(ticket) else { return } + activeSavedPath = matchedPath + logger.info("Matched path to saved path: \(matchedPath.name)") } guard isCurrent(ticket) else { return } @@ -965,64 +925,56 @@ final class TracePathViewModel { /// Execute a single trace within a batch, storing result in completedResults private func executeSingleTrace(ticket: Epoch.Ticket) async { guard isCurrent(ticket) else { return } - pendingPathHash = fullPathBytes - - switch await sendAndArm(ticket: ticket, isBatch: true) { - case .abandoned, .failedBeforeTag: - return - case .waiting: - break - } + await sendAndArm(ticket: ticket, isBatch: true) - guard pendingTag != nil, isCurrent(ticket) else { return } + guard isCurrent(ticket) else { return } await withCheckedContinuation { (continuation: CheckedContinuation) in - traceContinuation = continuation - armCurrentWait(ticket: ticket) + guard case .waiting(let submission, var wait) = traceRequest, submission.input.ticket == ticket else { + continuation.resume() + return + } + wait.continuation = continuation + traceRequest = .waiting(submission, wait) } } - private enum SendArmResult { - case waiting - case failedBeforeTag - case abandoned - } - - /// Assigns `pendingTag` only after the pre-tag step. A throw after that - /// leaves the tag in place and arms the deadline if it is not armed yet. - private func sendAndArm(ticket: Epoch.Ticket, isBatch: Bool) async -> SendArmResult { + /// A post-tag send error still permits a response; a consumed request cannot be revived by send completion. + private func sendAndArm(ticket: Epoch.Ticket, isBatch: Bool) async { + let input = TraceRequestState.Input( + ticket: ticket, + isBatch: isBatch, + path: fullPathBytes, + flags: effectiveTraceMode + ) do { try await preflightBeforeTag() } catch { - guard isCurrent(ticket) else { return .abandoned } - failBeforeTag(ticket: ticket, isBatch: isBatch) - return .failedBeforeTag + guard isCurrent(ticket) else { return } + failBeforeTag(input: input) + return } + guard isCurrent(ticket) else { return } - let tag = UInt32.random(in: 0...UInt32.max) - pendingTag = tag - waitingTicket = ticket - pendingIsBatch = isBatch - pendingDeviceID = connectedDevice?.radioID - traceStartTime = Date() + let submission = TraceRequestState.Submission( + input: input, + tag: UInt32.random(in: 0...UInt32.max), + radioID: connectedDevice?.radioID, + startedAt: Date() + ) + traceRequest = .sending(submission) + let timeoutSeconds: Double do { - let sentInfo = try await performSendTrace(tag: tag, flags: effectiveTraceMode, path: Data(fullPathBytes)) - guard isCurrent(ticket) else { return .abandoned } - let timeoutSeconds = responseTimeoutSeconds(suggestedTimeoutMs: sentInfo.suggestedTimeoutMs) - logger.info("Sent trace with tag \(tag), path: \(self.fullPathString), timeout: \(timeoutSeconds)s") - pendingTimeoutSeconds = timeoutSeconds - return .waiting + let sentInfo = try await performSendTrace(tag: submission.tag, flags: input.flags, path: Data(input.path)) + timeoutSeconds = responseTimeoutSeconds(suggestedTimeoutMs: sentInfo.suggestedTimeoutMs) } catch { - guard isCurrent(ticket) else { return .abandoned } - if pendingTag == tag { - if responseDeadline == nil { - pendingTimeoutSeconds = unackedTimeoutSeconds - } - return .waiting - } - failBeforeTag(ticket: ticket, isBatch: isBatch) - return .failedBeforeTag + timeoutSeconds = unackedTimeoutSeconds } + guard isCurrent(ticket), case let .sending(current) = traceRequest, + current.tag == submission.tag, current.input.ticket == ticket else { return } + logger.info("Waiting for trace with tag \(submission.tag), timeout: \(timeoutSeconds)s") + let timeoutClock = clock + armTimeout(submission: submission, timeoutSeconds: timeoutSeconds, clock: timeoutClock) } private func preflightBeforeTag() async throws { @@ -1033,25 +985,20 @@ final class TracePathViewModel { #endif } - private func failBeforeTag(ticket: Epoch.Ticket, isBatch: Bool) { - guard isCurrent(ticket) else { return } + private func failBeforeTag(input: TraceRequestState.Input) { logger.error("Failed to send trace before a tag was assigned") - if isBatch { + if input.isBatch { let failedResult = TraceResult.sendFailed( L10n.Contacts.Contacts.Trace.Error.sendFailed, - attemptedPath: pendingPathHash ?? [], - hashSize: hashSize + attemptedPath: input.path, + hashSize: input.hashSize ) completedResults.append(failedResult) } else { setError(L10n.Contacts.Contacts.Trace.Error.sendFailed) isRunning = false } - recordFailedRun(ticket: ticket) - pendingPathHash = nil - pendingTag = nil - pendingDeviceID = nil - waitingTicket = nil + recordFailedRun(ticket: input.ticket) } private var canSendTrace: Bool { @@ -1098,74 +1045,54 @@ final class TracePathViewModel { return try await session.sendTrace(tag: tag, authCode: 0, flags: flags, path: path) } - private var pendingTimeoutSeconds: Double = 0 - - private func armCurrentWait(ticket: Epoch.Ticket) { - guard isCurrent(ticket), let tag = pendingTag, responseDeadline == nil else { return } - let timeoutClock = clock - armTimeout(tag: tag, timeoutSeconds: pendingTimeoutSeconds, clock: timeoutClock) - } - - private func armTimeout(tag: UInt32, timeoutSeconds: Double, clock: C) where C.Duration == Duration { - responseDeadline = Date().addingTimeInterval(timeoutSeconds) + private func armTimeout( + submission: TraceRequestState.Submission, + timeoutSeconds: Double, + clock: C + ) where C.Duration == Duration { + let responseDeadline = Date().addingTimeInterval(timeoutSeconds) let deadline = clock.now.advanced(by: .seconds(timeoutSeconds)) - timeoutTask?.cancel() - timeoutTask = Task { @MainActor in + let timeoutTask = Task { @MainActor in try? await clock.sleep(until: deadline, tolerance: nil) guard !Task.isCancelled else { return } - applyTimeout(tag: tag) + applyTimeout(tag: submission.tag) } + traceRequest = .waiting(submission, .init(deadline: responseDeadline, timeoutTask: timeoutTask)) } private func applyTimeout(tag: UInt32) { - let isBatch = pendingIsBatch - let ticket = waitingTicket - guard claimPendingResponse(tag: tag), let ticket else { return } + guard let submission = claimPendingResponse(tag: tag) else { return } + let input = submission.input - if isBatch { + if input.isBatch { logger.warning("Batch trace timeout for tag \(tag)") - let timeoutResult = TraceResult.timeout(attemptedPath: pendingPathHash ?? [], hashSize: hashSize) + let timeoutResult = TraceResult.timeout(attemptedPath: input.path, hashSize: input.hashSize) completedResults.append(timeoutResult) - recordFailedRun(ticket: ticket) - pendingPathHash = nil - resumeContinuationOnce() } else { logger.warning("Trace timeout for tag \(tag)") setError(L10n.Contacts.Contacts.Trace.Error.noResponse) - pendingPathHash = nil - recordFailedRun(ticket: ticket) isRunning = false - pendingDeviceID = nil } + recordFailedRun(ticket: input.ticket) } /// First owner of the tag wins. The response path and the deadline path both call this before writing. - private func claimPendingResponse(tag: UInt32) -> Bool { - guard pendingTag == tag, let waitingTicket, waitingTicket.isCurrent(in: executionEpoch) else { return false } - pendingTag = nil - self.waitingTicket = nil - responseDeadline = nil - timeoutTask?.cancel() - timeoutTask = nil - return true + private func claimPendingResponse(tag: UInt32) -> TraceRequestState.Submission? { + guard let submission = traceRequest.submission, submission.tag == tag, + submission.input.ticket.isCurrent(in: executionEpoch) else { return nil } + traceRequest.finish() + return submission } private func handleTraceStreamEnded(finished: AdvertisementService) { - guard pendingTag != nil, let waitingTicket, waitingTicket.isCurrent(in: executionEpoch) else { return } - guard let next = advertisementService, next !== finished else { return } + guard let submission = traceRequest.submission, submission.input.ticket.isCurrent(in: executionEpoch), + let next = advertisementService, next !== finished else { return } startListening() } - private func resumeContinuationOnce() { - guard let continuation = traceContinuation else { return } - traceContinuation = nil - continuation.resume() - } - /// Record a failed run for saved paths private func recordFailedRun(ticket: Epoch.Ticket) { - guard ticket.isCurrent(in: executionEpoch) else { return } - guard let savedPath = activeSavedPath else { return } + guard ticket.isCurrent(in: executionEpoch), let savedPath = activeSavedPath else { return } let failedRun = TracePathRunDTO( id: UUID(), @@ -1209,14 +1136,7 @@ final class TracePathViewModel { func cancelExecution() { executionEpoch.bump() batchCancelled = true - pendingTag = nil - waitingTicket = nil - responseDeadline = nil - pendingDeviceID = nil - pendingPathHash = nil - timeoutTask?.cancel() - timeoutTask = nil - resumeContinuationOnce() + traceRequest.finish() executionTask?.cancel() executionTask = nil isRunning = false @@ -1225,26 +1145,21 @@ final class TracePathViewModel { /// Handle trace response from event stream func handleTraceResponse(_ traceInfo: TraceInfo, radioID: UUID?) { - guard traceInfo.tag == pendingTag else { + guard let pending = traceRequest.submission, traceInfo.tag == pending.tag else { logger.debug("Ignoring trace response with non-matching tag \(traceInfo.tag)") return } - // Validate device ID if both are available; skip if either is nil - if let pending = pendingDeviceID, let received = radioID, pending != received { - logger.warning("Ignoring trace response from different device") + // Validate Radio ID if both are available; skip if either is nil. + if let pendingRadioID = pending.radioID, let received = radioID, pendingRadioID != received { + logger.warning("Ignoring trace response from different radio") return } - let ticket = waitingTicket - guard claimPendingResponse(tag: traceInfo.tag), let ticket else { return } + guard let submission = claimPendingResponse(tag: traceInfo.tag) else { return } // Calculate duration - let durationMs = if let startTime = traceStartTime { - Int(Date().timeIntervalSince(startTime) * 1000) - } else { - 0 - } + let durationMs = Int(Date().timeIntervalSince(submission.startedAt) * Self.millisecondsPerSecond) // Build hops from response using receiver attribution model: // Each node's SNR shows what it measured when receiving. @@ -1319,12 +1234,11 @@ final class TracePathViewModel { durationMs: durationMs, success: true, errorMessage: nil, - tracedPathBytes: pendingPathHash ?? [], - hashSize: hashSize + tracedPathBytes: submission.input.path, + hashSize: submission.input.hashSize ) - // In batch mode, store result and resume continuation - if batchEnabled, let result { + if submission.input.isBatch, let result { completedResults.append(result) } else { resultID = UUID() @@ -1333,13 +1247,6 @@ final class TracePathViewModel { isRunning = false } - resumeContinuationOnce() - - pendingPathHash = nil - pendingTag = nil - pendingDeviceID = nil - traceStartTime = nil - // Auto-append run if this is a saved path if let savedPath = activeSavedPath, dataStore != nil { let hopsSNR = hops @@ -1353,7 +1260,7 @@ final class TracePathViewModel { hopsSNR: hopsSNR ) - appendRunIfCurrent(ticket: ticket, pathID: savedPath.id, run: runDTO) + appendRunIfCurrent(ticket: submission.input.ticket, pathID: savedPath.id, run: runDTO) } logger.info("Trace completed: \(hops.count) hops, \(durationMs)ms") @@ -1377,7 +1284,7 @@ final class TracePathViewModel { } var timeoutTaskForTesting: Task? { - timeoutTask + traceRequest.timeoutTask } var errorAutoClearTaskForTesting: Task? { @@ -1385,29 +1292,23 @@ final class TracePathViewModel { } var pendingTagForTesting: UInt32? { - pendingTag + traceRequest.submission?.tag } var hasActiveTimeoutTaskForTesting: Bool { - guard let timeoutTask else { return false } + guard let timeoutTask = traceRequest.timeoutTask else { return false } return !timeoutTask.isCancelled } - /// Test helper to set pending tag without running a full trace - func setPendingTagForTesting(_ tag: UInt32) { - pendingTag = tag - waitingTicket = executionEpoch.ticket() - pendingIsBatch = batchEnabled - } - - /// Test helper to set pending device ID - func setPendingDeviceIDForTesting(_ radioID: UUID?) { - pendingDeviceID = radioID - } - - /// Test helper to set pending path hash - func setPendingPathHashForTesting(_ pathHash: [UInt8]?) { - pendingPathHash = pathHash + /// Installs a complete submitted request without sending to a radio. + func setPendingTraceForTesting(_ tag: UInt32, radioID: UUID? = nil, path: [UInt8]? = nil) { + traceRequest.finish() + traceRequest = .sending(.init( + input: .init(ticket: executionEpoch.ticket(), isBatch: batchEnabled, path: path ?? fullPathBytes, flags: effectiveTraceMode), + tag: tag, + radioID: radioID, + startedAt: Date() + )) } /// Test helper to set contacts for hash resolution diff --git a/MC1/Views/Tools/TracePath/TraceRequestState+Input.swift b/MC1/Views/Tools/TracePath/TraceRequestState+Input.swift new file mode 100644 index 0000000000..6050c0937f --- /dev/null +++ b/MC1/Views/Tools/TracePath/TraceRequestState+Input.swift @@ -0,0 +1,12 @@ +extension TraceRequestState { + struct Input { + let ticket: Epoch.Ticket + let isBatch: Bool + let path: [UInt8] + let flags: UInt8 + + var hashSize: Int { + 1 << Int(flags) + } + } +} diff --git a/MC1/Views/Tools/TracePath/TraceRequestState+Submission.swift b/MC1/Views/Tools/TracePath/TraceRequestState+Submission.swift new file mode 100644 index 0000000000..55db68fd32 --- /dev/null +++ b/MC1/Views/Tools/TracePath/TraceRequestState+Submission.swift @@ -0,0 +1,10 @@ +import Foundation + +extension TraceRequestState { + struct Submission { + let input: Input + let tag: UInt32 + let radioID: UUID? + let startedAt: Date + } +} diff --git a/MC1/Views/Tools/TracePath/TraceRequestState+Wait.swift b/MC1/Views/Tools/TracePath/TraceRequestState+Wait.swift new file mode 100644 index 0000000000..d70a2301c4 --- /dev/null +++ b/MC1/Views/Tools/TracePath/TraceRequestState+Wait.swift @@ -0,0 +1,9 @@ +import Foundation + +extension TraceRequestState { + struct Wait { + let deadline: Date + let timeoutTask: Task + var continuation: CheckedContinuation? + } +} diff --git a/MC1/Views/Tools/TracePath/TraceRequestState.swift b/MC1/Views/Tools/TracePath/TraceRequestState.swift new file mode 100644 index 0000000000..f8c4a0cbc5 --- /dev/null +++ b/MC1/Views/Tools/TracePath/TraceRequestState.swift @@ -0,0 +1,30 @@ +/// Owns one Trace request, independently of batch scheduling and result presentation. +enum TraceRequestState { + case idle + case sending(Submission) + case waiting(Submission, Wait) + + var submission: Submission? { + switch self { + case .idle: + nil + case let .sending(submission), let .waiting(submission, _): + submission + } + } + + var timeoutTask: Task? { + guard case let .waiting(_, wait) = self else { return nil } + return wait.timeoutTask + } + + /// Clears ownership before releasing the waiter so a late event cannot finish twice. + mutating func finish() { + let previous = self + self = .idle + if case let .waiting(_, wait) = previous { + wait.timeoutTask.cancel() + wait.continuation?.resume() + } + } +} diff --git a/MC1AccessibilityFixture/ChatAccessibilityFixtureApp.swift b/MC1AccessibilityFixture/ChatAccessibilityFixtureApp.swift new file mode 100644 index 0000000000..595225f9a7 --- /dev/null +++ b/MC1AccessibilityFixture/ChatAccessibilityFixtureApp.swift @@ -0,0 +1,136 @@ +import MC1Services +import SwiftUI +import UIKit + +@main +struct ChatAccessibilityFixtureApp: App { + var body: some Scene { + WindowGroup { + Transcript() + } + } + + private struct Transcript: View { + @State private var isAtBottom = true + @State private var unreadCount = 0 + @State private var voiceOverFocus = "" + + var body: some View { + let rows = Fixture.rows(longDay: ProcessInfo.processInfo.arguments.contains("-long-day")) + let factory = ChatCellContentFactory( + contactName: "Alice", + deviceName: "Me", + configuration: .directMessage, + theme: .default, + openURL: OpenURLAction { _ in .handled }, + resolver: BubbleResolver( + message: { item in rows.first { $0.item.id == item.id }?.message }, + image: { _ in nil } + ), + actions: BubbleActions( + onRetryMessage: { _ in }, + onLongPress: { _ in }, + onImageTap: { _ in }, + onRetryInlineImage: { _ in }, + onRequestPreviewFetch: { _ in }, + onManualPreviewFetch: { _ in }, + onMapPreviewTap: { _ in }, + snapshotResolver: { _ in nil }, + requestSnapshot: { _ in }, + retrySnapshot: { _ in }, + onTranslationAction: { _ in } + ) + ) + ChatTiledView( + items: rows.map(\.item), + cellContent: { factory.makeContent(for: $0) }, + isAtBottom: $isAtBottom, + unreadCount: $unreadCount, + initialScrollTargetID: rows.first?.item.id, + accessibilityHeadingIDs: rows.map(\.item).filter(\.grouping.showDayDivider).map(\.id) + ) + .onReceive(NotificationCenter.default.publisher(for: UIAccessibility.elementFocusedNotification)) { _ in + guard ProcessInfo.processInfo.arguments.contains("-verify-heading-focus"), + let element = UIAccessibility.focusedElement(using: .notificationVoiceOver) as? NSObject else { return } + voiceOverFocus = "\(element.accessibilityLabel ?? "")|header:\(element.accessibilityTraits.contains(.header))|frame:\(!element.accessibilityFrame.isEmpty)" + } + .overlay(alignment: .bottomLeading) { + if ProcessInfo.processInfo.arguments.contains("-verify-heading-focus") { + Text("Focus diagnostics") + .font(.caption2) + .accessibilityIdentifier("fixture.voiceOverFocus") + .accessibilityValue(voiceOverFocus) + .allowsHitTesting(false) + } + } + } + } + + private enum Fixture { + static let radioID = UUID(uuidString: "11111111-1111-1111-1111-111111111111")! + static let contactID = UUID(uuidString: "22222222-2222-2222-2222-222222222222")! + + struct Row { + let message: MessageDTO + let item: MessageItem + } + + static func rows(longDay: Bool) -> [Row] { + let messagesPerDay = longDay ? 24 : 12 + let messageCount = messagesPerDay * 3 + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(secondsFromGMT: 0)! + return (0.. String { + app.typeKey(forward ? .downArrow : .upArrow, modifierFlags: [.control, .option]) + return try waitForSpeech(voiceOver) { utterance in + let heading = app.staticTexts[date] + guard utterance.contains(date), utterance.localizedCaseInsensitiveContains("heading"), heading.exists else { return false } + let frame = heading.frame + let nativeFocus = app.staticTexts["fixture.voiceOverFocus"].value as? String + return nativeFocus == "\(date)|header:true|frame:true" + && frame.width > 0 && frame.height > 0 && app.frame.intersects(frame) + } + } + + private func waitForSpeech( + _ voiceOver: XCUIVoiceOverService, matching matches: @escaping (String) -> Bool, + file: StaticString = #filePath, line: UInt = #line + ) throws -> String { + var samples: [String] = [] + let settled = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in + guard let utterance = try? voiceOver.currentSpeech().utterance else { return false } + if samples.last != utterance { samples.append(utterance) } + return matches(utterance) + }, object: nil) + let result = XCTWaiter.wait(for: [settled], timeout: Self.rotorTransitionTimeout) + if result != .completed { attachSpeech(samples.joined(separator: "\n"), name: "Unsettled VoiceOver transition") } + return try XCTUnwrap(result == .completed ? samples.last : nil, "VoiceOver did not reach the expected element.", file: file, line: line) + } + + private func verifyJump() throws { + try withTranscript(verifyHeadingFocus: true) { app, voiceOver in + let jump = app.buttons["chat.scrollToBottom"] + XCTAssertTrue(jump.waitForExistence(timeout: 10)) + jump.tap() + let before = try voiceOver.currentSpeech().utterance + XCTAssertTrue(before.contains("Scroll to latest message")) + let started = ProcessInfo.processInfo.systemUptime + jump.doubleTap() + + var nativeFocus = "" + let accepted = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in + nativeFocus = app.staticTexts["fixture.voiceOverFocus"].value as? String ?? "" + return nativeFocus.hasSuffix("Fixture message 35|header:false|frame:true") + }, object: nil) + let acceptance = XCTWaiter.wait(for: [accepted], timeout: 10) + if acceptance != .completed { + attachSpeech(nativeFocus, name: "Latest-message jump native focus timeout") + } + XCTAssertEqual(acceptance, .completed) + + var after = "" + var speechSamples: [String] = [] + let focused = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in + let previous = after + do { + after = try voiceOver.currentSpeech().utterance + } catch { + after = "Speech unavailable: \(error)" + } + if after != previous { + speechSamples.append("\(ProcessInfo.processInfo.systemUptime - started)s: \(after)") + } + return after.contains("Fixture message 35") + }, object: nil) + let result = XCTWaiter.wait(for: [focused], timeout: 10) + if result != .completed { + attachSpeech("Button hittable before navigation: \(jump.isHittable)", name: "Latest-message jump speech timeout") + } + attachSpeech(speechSamples.joined(separator: "\n"), name: "Latest-message jump speech samples") + attachSpeech("Before: \(before)\nAfter: \(after)", name: "Latest-message jump accepted focus") + XCTAssertEqual(result, .completed) + let backward = try voiceOver.moveBackward().utterance + attachSpeech(backward, name: "Latest-message jump backward navigation") + XCTAssertTrue(backward.contains("Fixture message 34")) + let forward = try voiceOver.moveForward().utterance + attachSpeech(forward, name: "Latest-message jump forward navigation") + XCTAssertTrue(forward.contains("Fixture message 35")) + XCTAssertFalse(jump.isHittable) + } + } + + private func withTranscript( + voiceOverEnabled: Bool = true, + longDay: Bool = false, + verifyHeadingFocus: Bool = false, + verify: (XCUIApplication, XCUIVoiceOverService) throws -> Void + ) throws { + let app = XCUIApplication() + let voiceOver = XCUIDevice.shared.voiceOverService + let wasEnabled = voiceOver.isEnabled + defer { + app.terminate() + if voiceOver.isEnabled != wasEnabled { + do { + if wasEnabled { try voiceOver.enable() } else { try voiceOver.disable() } + } catch { + XCTFail("Could not restore VoiceOver: \(error)") + } + } + } + if voiceOver.isEnabled != voiceOverEnabled { + if voiceOverEnabled { try voiceOver.enable() } else { try voiceOver.disable() } + } + if longDay { app.launchArguments.append("-long-day") } + if verifyHeadingFocus { app.launchArguments.append("-verify-heading-focus") } + app.launch() + XCTAssertTrue(app.wait(for: .runningForeground, timeout: 10)) + XCTAssertEqual(voiceOver.isEnabled, voiceOverEnabled) + try verify(app, voiceOver) + } + + private func attachSpeech(_ text: String, name: String) { + let speech = XCTAttachment(string: text) + speech.name = name + speech.lifetime = .keepAlways + add(speech) + } +} diff --git a/MC1Services/Package.swift b/MC1Services/Package.swift index c2978fe847..1da5ecbbbe 100644 --- a/MC1Services/Package.swift +++ b/MC1Services/Package.swift @@ -3,6 +3,7 @@ import PackageDescription let package = Package( name: "MC1Services", + defaultLocalization: "en", platforms: [.iOS(.v18), .macOS(.v15)], products: [ .library(name: "MC1Services", targets: ["MC1Services"]) @@ -13,13 +14,19 @@ let package = Package( targets: [ .target( name: "MC1Services", - dependencies: ["MeshCore"] + dependencies: ["MeshCore"], + resources: [ + .process("MECP/Languages") + ] ), .testTarget( name: "MC1ServicesTests", dependencies: [ "MC1Services", .product(name: "MeshCoreTestSupport", package: "MeshCore") + ], + resources: [ + .process("MECP") ] ) ] diff --git a/MC1Services/Sources/MC1Services/Connection/BLEReconnectionCoordinator.swift b/MC1Services/Sources/MC1Services/Connection/BLEReconnectionCoordinator.swift index 6f9aadb2f2..df40544db4 100644 --- a/MC1Services/Sources/MC1Services/Connection/BLEReconnectionCoordinator.swift +++ b/MC1Services/Sources/MC1Services/Connection/BLEReconnectionCoordinator.swift @@ -1,360 +1,194 @@ import Foundation -import OSLog -/// Owns reconnect cycles and UI timeouts while its delegate rebuilds sessions. +/// Owns the retry and presentation timeout for one OS auto-reconnect cycle. @MainActor final class BLEReconnectionCoordinator { - private let logger = PersistentLogger(subsystem: "com.mc1", category: "BLEReconnectionCoordinator") - - weak var delegate: BLEReconnectionDelegate? - - /// The device ID for the reconnect cycle currently claimed by - /// `handleEnteringAutoReconnect`. Completions are accepted only when this matches - /// the completing device. A nil value (entry suppressed, or manually superseded) - /// rejects late completions to prevent them from racing a new flow. - var reconnectingDeviceID: UUID? { - activeCycle?.deviceID - } - - private struct ReconnectCycle { - let deviceID: UUID + struct Cycle: Sendable, Equatable { + let id: UUID let generation: Int - var uiTimedOut: Bool + let deviceID: UUID + let requestID: UUID } - private var activeCycle: ReconnectCycle? + private enum Timing { + static let uiTimeout: TimeInterval = 15 + static let maxUIWindow: TimeInterval = 60 + static let rebuildRetry: Duration = .seconds(2) + } - private var timeoutTask: Task? + private enum RebuildOutcome { + case rebuilt + case exhausted + case superseded + } - var uiTimeoutTaskForTest: Task? { - timeoutTask + private struct RebuildOperation { + let cycleID: UUID + let task: Task } - /// Generation of an in-flight `rebuildSession` (including first-fail retry), or - /// nil when none. Rejects a second completion only for the same generation so - /// a newer cycle (bumped by `handleEnteringAutoReconnect`) can still rebuild - /// while a stale retry sleeps, without allowing dual entry on one generation. - private var sessionRebuildInFlightGeneration: Int? + var onRebuild: (@MainActor (Cycle) async throws -> Void)? + var onExhausted: (@MainActor (Cycle) async -> Void)? + var onTimeout: (@MainActor (Cycle) async -> Void)? + var isAutoReconnecting: @MainActor () async -> Bool = { false } - /// Incremented each time a reconnection cycle starts, used to detect stale rebuilds and retries. + private(set) var currentCycle: Cycle? private(set) var reconnectGeneration = 0 - /// UI timeout duration before transitioning from "connecting" to "disconnected". - /// iOS auto-reconnect continues in the background even after this fires. - private let uiTimeoutDuration: TimeInterval - - /// When the current reconnect UI window started. Used to bound re-arms. - private var reconnectUIWindowStart: Date? - - /// Maximum time the UI can stay in `.connecting` state, even if BLE is still - /// auto-reconnecting. Prevents indefinite connecting UI when transport is stuck. - private let maxConnectingUIWindow: TimeInterval - - /// Delay before retrying a failed session rebuild during auto-reconnect. - private static let rebuildRetryDelay: Duration = .seconds(2) + var reconnectingDeviceID: UUID? { + currentCycle?.deviceID + } - /// Clock for the rebuild-retry backoff. Defaults to `ContinuousClock`; - /// inject a test clock to make the retry deterministic in tests. + private let uiTimeoutDuration: Duration + private let maxConnectingUIWindow: Duration private let clock: any Clock + private var elapsedInUIWindow: (@Sendable () -> Duration)? + private var timeoutTask: Task? + private var timeoutID: UUID? + private var rebuildOperation: RebuildOperation? init( - uiTimeoutDuration: TimeInterval = 15, - maxConnectingUIWindow: TimeInterval = 60, + uiTimeoutDuration: TimeInterval = Timing.uiTimeout, + maxConnectingUIWindow: TimeInterval = Timing.maxUIWindow, clock: (any Clock)? = nil ) { - self.uiTimeoutDuration = uiTimeoutDuration - self.maxConnectingUIWindow = maxConnectingUIWindow + self.uiTimeoutDuration = .seconds(uiTimeoutDuration) + self.maxConnectingUIWindow = .seconds(maxConnectingUIWindow) self.clock = clock ?? ContinuousClock() } - /// Handles the device entering iOS auto-reconnect phase. - /// Tears down session layer and starts a UI timeout. @discardableResult - func handleEnteringAutoReconnect(deviceID: UUID) async -> Int? { - guard let delegate else { return nil } - logger.info("[BLE] handleEnteringAutoReconnect: device=\(deviceID.uuidString.prefix(8)), connectionState=\(String(describing: delegate.connectionState))") - - guard delegate.connectionIntent.wantsConnection else { - logger.info("Ignoring auto-reconnect: user disconnected") - await delegate.disconnectTransport() - return nil - } - - // Publish .connecting before suspending so handleReconnectionComplete - // can accept a completion during teardown. - delegate.setConnectionState(.connecting) - reconnectGeneration += 1 - let generation = reconnectGeneration - activeCycle = ReconnectCycle(deviceID: deviceID, generation: generation, uiTimedOut: false) - reconnectUIWindowStart = Date() - - // Notify after claiming the cycle and before teardown so the Live Activity - // updates within CoreBluetooth's disconnect wake window. - await delegate.notifyAutoReconnectStarted() - guard reconnectGeneration == generation else { return generation } - - await delegate.teardownSessionForReconnect() - guard reconnectGeneration == generation else { return generation } - - logger.info("[BLE] Arming UI timeout: \(uiTimeoutDuration)s for device \(deviceID.uuidString.prefix(8))") - armTimeout(deviceID: deviceID, generation: generation) - return generation + func begin(deviceID: UUID, requestID: UUID) -> Cycle { + clear() + let cycle = Cycle(id: UUID(), generation: reconnectGeneration, deviceID: deviceID, requestID: requestID) + currentCycle = cycle + elapsedInUIWindow = clock.elapsedSinceNow() + return cycle } - /// Handles iOS auto-reconnect completion. Cancels the UI timeout - /// and delegates session rebuild to ConnectionManager. - func handleReconnectionComplete(deviceID: UUID) async { - guard let delegate else { return } - logger.info("[BLE] handleReconnectionComplete: device=\(deviceID.uuidString.prefix(8))") - - guard delegate.connectionIntent.wantsConnection else { - cancelTimeout() - logger.info("Ignoring reconnection: user disconnected") - clearActiveCycle(invalidateGeneration: true) - await delegate.disconnectTransport() - return - } - - // Reject completions for cycles we didn't claim — an orphaned completion - // would race the new flow. Don't cancel the active timeout — the current - // reconnect retains its fallback. - guard activeCycle?.deviceID == deviceID else { - let claim = reconnectingDeviceID?.uuidString.prefix(8) ?? "no claim" - logger.warning("[BLE] Ignoring auto-reconnect completion for \(deviceID.uuidString.prefix(8)): \(claim)") - return - } + func isCurrent(_ cycle: Cycle) -> Bool { + currentCycle == cycle + } - let completedAfterUITimeout = activeCycle?.uiTimedOut == true - if completedAfterUITimeout { - logger.info("[BLE] Accepting auto-reconnect completion after UI timeout for \(deviceID.uuidString.prefix(8))") - } + func isRebuilding(_ cycle: Cycle) -> Bool { + isCurrent(cycle) && rebuildOperation?.cycleID == cycle.id + } - // This completion is for our device — safe to cancel timeout + func armTimeout(_ cycle: Cycle) { + guard isCurrent(cycle), rebuildOperation?.cycleID != cycle.id else { return } cancelTimeout() - // Keep the cycle claimed across rebuild, the first-fail → retry sleep, and - // handleReconnectionFailure so concurrent checkBLEConnectionHealth cannot - // install a stack that the failure handler would tear down. - - // Accept both disconnected (normal) and connecting (auto-reconnect in progress). - // Production rebuildSession sets `.connected` early, so a second same-device - // completion often arrives while state is already `.connected`. If a rebuild - // (or its retry/failure path) is in flight, ignore without clearing the cycle - // claim — that claim is what keeps health single-flight during the gap. - let state = delegate.connectionState - guard state == .disconnected || state == .connecting else { - if sessionRebuildInFlightGeneration != nil { - logger.info( - "[BLE] Ignoring reconnection for \(deviceID.uuidString.prefix(8)): already \(String(describing: state)) while rebuild in flight" - ) + let id = UUID() + timeoutID = id + let clock = clock + let duration = uiTimeoutDuration + timeoutTask = Task { @concurrent [weak self] in + do { + try await clock.sleep(for: duration) + } catch { return } - logger.info("Ignoring reconnection: already \(String(describing: state))") - clearActiveCycle(invalidateGeneration: false) - return - } - - // Reject a second completion while a rebuild for *this* generation is live - // (dual didConnect). Compare against reconnectGeneration *before* bumping so - // the first completion's in-flight mark matches. A newer - // handleEnteringAutoReconnect bumps generation first, so a completion after - // that can rebuild while a stale retry still sleeps under an older mark. - if sessionRebuildInFlightGeneration == reconnectGeneration { - logger.warning( - "[BLE] Ignoring auto-reconnect completion for \(deviceID.uuidString.prefix(8)): session rebuild already in flight for generation \(reconnectGeneration)" - ) - return - } - - reconnectGeneration += 1 - let expectedGeneration = reconnectGeneration - - delegate.setConnectionState(.connecting) - sessionRebuildInFlightGeneration = expectedGeneration - defer { - if sessionRebuildInFlightGeneration == expectedGeneration { - sessionRebuildInFlightGeneration = nil - } - } - - do { - try await delegate.rebuildSession(deviceID: deviceID) - // Only clear if we still own the generation — a non-throwing supersession - // abort leaves a newer cycle's claim intact. - if expectedGeneration == reconnectGeneration { - clearActiveCycle(invalidateGeneration: false) - } - } catch { - logger.warning("[BLE] Auto-reconnect session rebuild failed: \(error.localizedDescription) - retrying in 2s") - await retryRebuild(deviceID: deviceID, expectedGeneration: expectedGeneration) + await self?.handleUITimeout(cycle, timeoutID: id) } } - /// Restarts the UI timeout without tearing down the session. - /// Used when user taps Connect while iOS auto-reconnect is already in progress. func restartTimeout(deviceID: UUID) { - if activeCycle?.deviceID != deviceID { - reconnectGeneration += 1 - activeCycle = ReconnectCycle(deviceID: deviceID, generation: reconnectGeneration, uiTimedOut: false) - } else { - activeCycle?.uiTimedOut = false - } - reconnectUIWindowStart = Date() - guard let generation = activeCycle?.generation else { return } - armTimeout(deviceID: deviceID, generation: generation) + guard let cycle = currentCycle, cycle.deviceID == deviceID else { return } + elapsedInUIWindow = clock.elapsedSinceNow() + armTimeout(cycle) } - private func armTimeout(deviceID: UUID, generation: Int) { - cancelTimeout() - timeoutTask = Task { [weak self, uiTimeoutDuration] in - try? await Task.sleep(for: .seconds(uiTimeoutDuration)) - guard !Task.isCancelled, let self else { return } - await handleUITimeout(deviceID: deviceID, generation: generation) - } - } - - /// Cancels the UI timeout timer. func cancelTimeout() { - if timeoutTask != nil { - logger.debug("[BLE] Cancelling UI timeout") - } + timeoutID = nil timeoutTask?.cancel() timeoutTask = nil } - /// Clears the reconnecting device ID, used when manual connect supersedes auto-reconnect. - func clearReconnectingDevice() { - clearActiveCycle(invalidateGeneration: true) + func clear() { + cancelTimeout() + rebuildOperation?.task.cancel() + rebuildOperation = nil + currentCycle = nil + elapsedInUIWindow = nil + reconnectGeneration += 1 } - private func clearActiveCycle(invalidateGeneration: Bool) { - guard activeCycle != nil else { return } - activeCycle = nil - reconnectUIWindowStart = nil - if invalidateGeneration { - reconnectGeneration += 1 - } - } + func complete(_ cycle: Cycle) async { + guard isCurrent(cycle), let onRebuild else { return } + guard rebuildOperation?.cycleID != cycle.id else { return } + cancelTimeout() - /// Retries a failed session rebuild after a short delay, aborting if the reconnect - /// generation has changed or the user disconnected during the wait. - private func retryRebuild(deviceID: UUID, expectedGeneration: Int) async { - guard let delegate else { - if expectedGeneration == reconnectGeneration { - clearActiveCycle(invalidateGeneration: false) - } - return + let task = Task { [weak self] in + guard let self, isCurrent(cycle) else { return RebuildOutcome.superseded } + return await rebuild(cycle, action: onRebuild) + } + rebuildOperation = RebuildOperation(cycleID: cycle.id, task: task) + let outcome = await task.value + guard rebuildOperation?.cycleID == cycle.id else { return } + rebuildOperation = nil + guard isCurrent(cycle) else { return } + + switch outcome { + case .rebuilt: + finish(cycle) + case .exhausted: + // Cleanup may join the rebuild worker, so its result is consumed before handing off. + await onExhausted?(cycle) + finish(cycle) + case .superseded: + finish(cycle) } + } - try? await clock.sleep(for: Self.rebuildRetryDelay) - - guard expectedGeneration == reconnectGeneration else { - logger.info("New reconnect cycle started during rebuild retry delay - aborting stale retry") - // A newer cycle owns the claim; do not clear theirs. - return - } - guard delegate.connectionIntent.wantsConnection else { - logger.info("User disconnected during rebuild retry delay") - // Hold claim through failure handling so concurrent health cannot rebuild - // under a torn-down stack, then release only if we still own the generation. - await delegate.handleReconnectionFailure() - if expectedGeneration == reconnectGeneration { - clearActiveCycle(invalidateGeneration: false) - } - return + private func rebuild( + _ cycle: Cycle, + action: @MainActor (Cycle) async throws -> Void + ) async -> RebuildOutcome { + do { + try Task.checkCancellation() + try await action(cycle) + return isCurrent(cycle) && !Task.isCancelled ? .rebuilt : .superseded + } catch { + guard isCurrent(cycle), !Task.isCancelled else { return .superseded } } do { - try await delegate.rebuildSession(deviceID: deviceID) - logger.info("[BLE] Auto-reconnect session rebuild succeeded on retry") - if expectedGeneration == reconnectGeneration { - clearActiveCycle(invalidateGeneration: false) - } + try await clock.sleep(for: Timing.rebuildRetry) + guard isCurrent(cycle), !Task.isCancelled else { return .superseded } + try await action(cycle) + return isCurrent(cycle) && !Task.isCancelled ? .rebuilt : .superseded } catch { - logger.error("[BLE] Auto-reconnect session rebuild failed on retry: \(error.localizedDescription)") - await delegate.handleReconnectionFailure() - if expectedGeneration == reconnectGeneration { - clearActiveCycle(invalidateGeneration: false) - } + return isCurrent(cycle) && !Task.isCancelled ? .exhausted : .superseded } } - private func handleUITimeout(deviceID: UUID, generation: Int) async { - guard let delegate, delegate.connectionState == .connecting else { return } - guard let activeCycle, - activeCycle.deviceID == deviceID, - activeCycle.generation == generation else { return } - let elapsed = Date().timeIntervalSince(reconnectUIWindowStart ?? Date()) - logger.info("[BLE] handleUITimeout: device=\(deviceID.uuidString.prefix(8)), elapsed=\(elapsed.formatted(.number.precision(.fractionLength(1))))s") - - // If BLE transport is still actively auto-reconnecting and we haven't - // exceeded the max connecting window, re-arm the timeout instead of - // forcing disconnected state. This handles the case where the timeout - // was armed before suspension and fires immediately on resume. - let transportAutoReconnecting = await delegate.isTransportAutoReconnecting() + private func handleUITimeout(_ cycle: Cycle, timeoutID id: UUID) async { + guard isCurrent(cycle), timeoutID == id, !Task.isCancelled else { return } + let autoReconnecting = await isAutoReconnecting() + guard isCurrent(cycle), timeoutID == id, !Task.isCancelled else { return } - // Re-validate after the await: handleReconnectionComplete can run to - // completion during the suspension, and this timeout must not force - // a freshly rebuilt session back to disconnected. - guard delegate.connectionState == .connecting, - let currentCycle = self.activeCycle, - currentCycle.deviceID == deviceID, - currentCycle.generation == generation else { return } - - if transportAutoReconnecting, elapsed < maxConnectingUIWindow { - logger.info("[BLE] UI timeout fired but BLE still auto-reconnecting, re-arming (elapsed: \(elapsed.formatted(.number.precision(.fractionLength(1))))s)") - armTimeout(deviceID: deviceID, generation: generation) + if autoReconnecting, let elapsedInUIWindow, elapsedInUIWindow() < maxConnectingUIWindow { + armTimeout(cycle) return } - if transportAutoReconnecting { - self.activeCycle?.uiTimedOut = true - } else { - clearActiveCycle(invalidateGeneration: true) + timeoutTask = nil + timeoutID = nil + await onTimeout?(cycle) + if !autoReconnecting { + finish(cycle) } - logger.warning( - "[BLE] Auto-reconnect UI timeout (\(uiTimeoutDuration)s) fired - transitioning UI to disconnected (iOS reconnect continues in background)" - ) - delegate.setConnectionState(.disconnected) - delegate.setConnectedDevice(nil) - await delegate.notifyConnectionLost() } -} - -/// Delegate protocol for BLEReconnectionCoordinator. -/// ConnectionManager implements this to provide session management. -@MainActor -protocol BLEReconnectionDelegate: AnyObject { - var connectionIntent: ConnectionIntent { get } - var connectionState: DeviceConnectionState { get } - /// Sets the connection state (used by coordinator for state transitions). - func setConnectionState(_ state: DeviceConnectionState) - - /// Sets the connected device (used by coordinator to clear on timeout). - func setConnectedDevice(_ device: DeviceDTO?) - - /// Tears down the current session and services for reconnection. - func teardownSessionForReconnect() async - - /// Rebuilds the session after iOS auto-reconnect completes. - func rebuildSession(deviceID: UUID) async throws - - /// Disconnects the BLE transport (used when user disconnected during reconnect). - func disconnectTransport() async - - /// Notifies the UI layer that the link dropped and iOS auto-reconnect has begun, - /// after the cycle is claimed and before session teardown. - func notifyAutoReconnectStarted() async - - /// Notifies the UI layer of connection loss. - func notifyConnectionLost() async - - /// Handles reconnection failure: app-stack teardown with preserve-vs-sever - /// branching on link health, intent, and rebuild budget. Does not always - /// disconnect the transport — a live link under budget is preserved for - /// in-place health-check rebuild. - func handleReconnectionFailure() async + private func finish(_ cycle: Cycle) { + guard isCurrent(cycle) else { return } + currentCycle = nil + elapsedInUIWindow = nil + } +} - /// Returns whether the BLE transport is currently in auto-reconnecting phase. - func isTransportAutoReconnecting() async -> Bool +private extension Clock where Duration == Swift.Duration { + func elapsedSinceNow() -> @Sendable () -> Duration { + let start = now + return { start.duration(to: now) } + } } diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionActivity.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionActivity.swift new file mode 100644 index 0000000000..d2a488573a --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionActivity.swift @@ -0,0 +1,17 @@ +import Foundation + +/// A request-scoped read model for connection controls, independent of a live Link. +public struct ConnectionActivity: Sendable, Equatable { + public enum Phase: Sendable, Equatable { + case connecting + case reconnecting + case waitingToReconnect + case connected + case syncing + case ready + } + + public let requestID: UUID + public let targetName: String? + public let phase: Phase +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionAttempt.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionAttempt.swift new file mode 100644 index 0000000000..0862c726d6 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionAttempt.swift @@ -0,0 +1,17 @@ +import MeshCore + +/// Captures one attempt within a request, including same-request recovery replacements. +@MainActor +final class ConnectionAttempt { + let target: ConnectionRequest.Target + var identity: ConnectionDeviceIdentity + let binding = SessionTransportBinding() + var resource: ConnectionResource? + var preparedServices: ServiceContainer? + var ackEvents: AsyncStream? + + init(target: ConnectionRequest.Target) { + self.target = target + identity = ConnectionDeviceIdentity(deviceID: target.deviceID) + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionDeviceIdentity.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionDeviceIdentity.swift new file mode 100644 index 0000000000..1492ff48a5 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionDeviceIdentity.swift @@ -0,0 +1,27 @@ +import Foundation + +/// Facts acquired about a radio independently of the address used to reach it. +struct ConnectionDeviceIdentity: Sendable, Equatable { + var deviceID: UUID? + var publicKey: Data? + var radioID: UUID? + + init(deviceID: UUID? = nil, publicKey: Data? = nil, radioID: UUID? = nil) { + self.deviceID = deviceID + self.publicKey = publicKey + self.radioID = radioID + } + + init(_ device: DeviceDTO) { + deviceID = device.id + publicKey = device.publicKey + radioID = device.radioID + } + + func matches(_ other: Self) -> Bool { + if let radioID, radioID == other.radioID { return true } + if let publicKey, !publicKey.isEmpty, publicKey == other.publicKey { return true } + if let deviceID, deviceID == other.deviceID { return true } + return false + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionLink.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionLink.swift new file mode 100644 index 0000000000..79a0504dbe --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionLink.swift @@ -0,0 +1,45 @@ +import Foundation + +@MainActor +final class ConnectionLink { + let generation = UUID() + let requestID: UUID + let target: ConnectionRequest.Target + let resource: ConnectionResource + let services: ServiceContainer + var device: DeviceDTO + let synthetic: Bool + var setupWorker: Task? + var completionWorker: Task? + var listenerRepairWorker: Task? + var completionID: UUID? + var usableSyncResult: FullSyncResult? + var timeEffectsClaimed = false + var didCompleteSync = false + + var snapshot: ConnectionSnapshot { + ConnectionSnapshot( + generation: generation, + requestID: requestID, + device: device, + services: services, + transportType: target.transportType + ) + } + + init( + requestID: UUID, + target: ConnectionRequest.Target, + resource: ConnectionResource, + services: ServiceContainer, + device: DeviceDTO, + synthetic: Bool = false + ) { + self.requestID = requestID + self.target = target + self.resource = resource + self.services = services + self.device = device + self.synthetic = synthetic + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionLossReceipt.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionLossReceipt.swift new file mode 100644 index 0000000000..e0fe6cd828 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionLossReceipt.swift @@ -0,0 +1,8 @@ +import Foundation + +/// A loss notification remains eligible only while its request still owns the manager. +public struct ConnectionLossReceipt: Sendable { + public let id = UUID() + public let requestID: UUID + public let retiredGeneration: UUID? +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+BLE.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+BLE.swift index 0857db697f..58370b6d85 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+BLE.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+BLE.swift @@ -2,32 +2,6 @@ import MeshCore extension ConnectionManager { - /// The connection methods recorded for a freshly connected BLE device. Centralized so the - /// BLE connect and device-switch paths persist an identical `.bluetooth` descriptor rather - /// than repeating the literal at each call site. - static func bleConnectionMethods(for deviceID: UUID) -> [ConnectionMethod] { - [.bluetooth(peripheralUUID: deviceID, displayName: nil)] - } - - /// Drops a live WiFi session first. The prep reason keeps the intent to connect. - public func connectViaBluetooth(peripheralID: UUID, forceFullSync: Bool = false) async throws { - try Task.checkCancellation() - invalidatePowerOffForConnectionChange() - try await waitForConnectionTeardown() - #if DEBUG - testBluetoothConnectAttempts.append(peripheralID) - if let testBluetoothConnectHandler { - try await testBluetoothConnectHandler(peripheralID) - return - } - #endif - - if connectionState != .disconnected { - await disconnect(reason: .bluetoothConnectPrep) - } - try await connect(to: peripheralID, forceFullSync: forceFullSync, forceReconnect: true) - } - // MARK: - BLE Diagnostics /// Returns a best-effort snapshot of the BLE state machine for debug exports. @@ -48,7 +22,6 @@ extension ConnectionManager { false } let activeReconnectDeviceShort = reconnectionCoordinator.reconnectingDeviceID?.uuidString.prefix(8) ?? "none" - let sessionRebuildDeviceShort = sessionRebuildDeviceID?.uuidString.prefix(8) ?? "none" return "BLE: state=\(bleState), " + "phase=\(blePhase), " + @@ -60,8 +33,7 @@ extension ConnectionManager { "servicesPresent=\(servicesPresent), " + "eventMonitoringActive=\(eventMonitoringActive), " + "autoFetchActive=\(autoFetchActive), " + - "activeReconnectDevice=\(activeReconnectDeviceShort), " + - "sessionRebuildDevice=\(sessionRebuildDeviceShort)" + "activeReconnectDevice=\(activeReconnectDeviceShort)" } // MARK: - BLE Device Checks @@ -91,9 +63,6 @@ extension ConnectionManager { // Don't check during auto-reconnect - that's our own connection guard !isAutoReconnecting else { return false } - // Don't check if we're already connected (switching devices) - guard connectionState == .disconnected else { return false } - // Don't report our own connection as "another app" (state restoration may have completed) if smIsConnected, smConnectedDeviceID == deviceID { return false @@ -113,73 +82,6 @@ extension ConnectionManager { return false } - /// Adopts a system-connected BLE link that survived app termination without state restoration. - /// - Returns: `true` if adoption started or a newer connection flow superseded the attempt. - func startAdoptingLastSystemConnectedPeripheralIfAvailable( - deviceID: UUID, - context: String, - requireLastConnected: Bool = true - ) async -> Bool { - if requireLastConnected { - guard deviceID == lastConnectedDeviceID else { return false } - } - guard currentTransportType == nil || currentTransportType == .bluetooth else { return false } - guard connectionState == .disconnected else { return false } - guard connectionIntent.wantsConnection else { return false } - - // Don't interfere with iOS auto-reconnect or an active BLE connection. - guard await !(stateMachine.isAutoReconnecting) else { return false } - if await stateMachine.isConnected, await stateMachine.connectedDeviceID == deviceID { - return false - } - - // Adoption is only valid from an idle BLE state machine. If restoration or another - // discovery chain is already in progress, let that flow own the reconnect. - let diagnostics = await stateMachine.linkDiagnostics - guard diagnostics.phase == .idle else { return false } - let blePhase = diagnostics.phase - - // Avoid doing teardown/UI transitions when there is no system-level link. - guard await stateMachine.isDeviceConnectedToSystem(deviceID) else { return false } - - let bleState = diagnostics.centralState - let blePeripheralState = diagnostics.peripheralState ?? "none" - logger.warning( - "[BLE] \(context): device appears system-connected while disconnected; attempting adoption - " + - "device=\(deviceID.uuidString.prefix(8)), " + - "bleState=\(bleState), " + - "blePhase=\(blePhase), " + - "blePeripheralState=\(blePeripheralState)" - ) - - // A newer flow owns the link after supersession; returning true prevents fallback. - guard let generation = await reconnectionCoordinator.handleEnteringAutoReconnect(deviceID: deviceID), - reconnectionCoordinator.reconnectGeneration == generation else { return true } - - let started = await stateMachine.startAdoptingSystemConnectedPeripheral(deviceID) - guard started else { - guard reconnectionCoordinator.reconnectGeneration == generation else { return true } - logger.warning("[BLE] \(context): startAdoptingSystemConnectedPeripheral returned false after system-connected preflight") - // Undo UI timeout + state changes so downstream health checks remain accurate. - reconnectionCoordinator.cancelTimeout() - reconnectionCoordinator.clearReconnectingDevice() - if connectionState == .connecting { - connectionState = .disconnected - } - return false - } - - persistDisconnectDiagnostic( - "source=\(context).adoptSystemConnectedPeripheral, " + - "device=\(deviceID.uuidString.prefix(8)), " + - "bleState=\(bleState), " + - "blePhase=\(blePhase), " + - "blePeripheralState=\(blePeripheralState), " + - "intent=\(connectionIntent)" - ) - return true - } - // MARK: - BLE Scanning /// Starts scanning for nearby BLE devices and returns an AsyncStream of `DiscoveredDevice`. @@ -192,8 +94,7 @@ extension ConnectionManager { let requestID = bleScanRequestID bleScanTask = Task { @MainActor [weak self] in - guard let self else { return } - guard !Task.isCancelled, requestID == bleScanRequestID else { return } + guard let self, !Task.isCancelled, requestID == bleScanRequestID else { return } await stateMachine.setDeviceDiscoveredHandler { @Sendable deviceID, name, rssi in _ = continuation.yield(DiscoveredDevice(id: deviceID, name: name, rssi: rssi)) @@ -205,8 +106,7 @@ extension ConnectionManager { continuation.onTermination = { [weak self] _ in Task { @MainActor in - guard let self else { return } - guard self.bleScanRequestID == requestID else { return } + guard let self, self.bleScanRequestID == requestID else { return } self.bleScanRequestID &+= 1 self.bleScanTask?.cancel() self.bleScanTask = nil @@ -229,6 +129,11 @@ extension ConnectionManager { // MARK: - Reconnection Watchdog + private enum WatchdogTiming { + static let initialDelay: Duration = .seconds(30) + static let maximumDelay: Duration = .seconds(120) + } + /// Starts a watchdog that periodically retries connection when the user wants to be /// connected but the device is stuck in disconnected state (e.g., after auto-reconnect failure). /// Uses exponential backoff: 30s → 60s → 120s (capped). @@ -241,6 +146,7 @@ extension ConnectionManager { reconnectionWatchdogGeneration += 1 let generation = reconnectionWatchdogGeneration + let requestID = desiredRequest?.id reconnectionWatchdogTask = Task { // Nil the property on every natural exit so "arm if nil" cannot see a // finished Task as live. Generation fence avoids nilling a replacement. @@ -251,14 +157,14 @@ extension ConnectionManager { } #if DEBUG - var delay: Duration = testWatchdogInitialDelay ?? .seconds(30) + var delay: Duration = testWatchdogInitialDelay ?? WatchdogTiming.initialDelay #else - var delay: Duration = .seconds(30) + var delay = WatchdogTiming.initialDelay #endif - let maxDelay: Duration = .seconds(120) + let maxDelay = WatchdogTiming.maximumDelay while !Task.isCancelled { - try? await Task.sleep(for: delay) + try? await reconnectionClock.sleep(for: delay) guard !Task.isCancelled else { return } guard connectionIntent.wantsConnection, @@ -280,9 +186,19 @@ extension ConnectionManager { continue } + guard !Task.isCancelled, reconnectionWatchdogGeneration == generation, + desiredRequest?.id == requestID else { return } logger.info("[BLE] Watchdog attempting reconnection (delay was \(delay))") - await checkBLEConnectionHealth() - + // Admission cancels this watchdog, so health needs an independent caller. + // Join that caller before scheduling another tick. + let health = Task { @MainActor in + guard self.reconnectionWatchdogGeneration == generation, + self.desiredRequest?.id == requestID else { return } + await self.checkBLEConnectionHealth() + } + await health.value + guard !Task.isCancelled, reconnectionWatchdogGeneration == generation, + desiredRequest?.id == requestID else { return } delay = min(delay * 2, maxDelay) } } @@ -295,508 +211,8 @@ extension ConnectionManager { reconnectionWatchdogTask = nil } - // MARK: - BLE Connection Health - - /// Attempts BLE reconnection if user expects to be connected but iOS auto-reconnect gave up. - /// Called when the app returns to foreground (`appDidBecomeActive`) and from the reconnection - /// watchdog loop. - /// - /// The guards below run as an ordered priority ladder, each ending in an early return so the - /// first matching situation wins. Order is load-bearing: cheap stand-down checks (wrong - /// transport, pairing, no intent, reconnect already in flight) come first so the expensive - /// state-machine queries below them only run when a reconnect is actually warranted; the live - /// transport check precedes the disconnected paths so an already-healthy link is reconciled - /// rather than torn down; stale-state cleanup runs before the adopt/other-app/reconnect - /// strategies so they start from a clean `connectionState`. Reordering can either tear down a - /// good connection or attempt a redundant reconnect. - public func checkBLEConnectionHealth() async { - // Only check BLE connections - guard currentTransportType == nil || currentTransportType == .bluetooth else { return } - - if shouldDeferOpportunisticReconnect { - logger.info("[BLE] Foreground health check standing down: pairing in progress") - return - } - - let deviceShort = lastConnectedDeviceID?.uuidString.prefix(8) ?? "none" - let diagnostics = await stateMachine.linkDiagnostics - let bleState = diagnostics.centralState - let blePhase = diagnostics.phase - logger.info(""" - [BLE] Foreground health check - \ - connectionIntent: \(connectionIntent), \ - lastDevice: \(deviceShort), \ - connectionState: \(String(describing: connectionState)), \ - bleState: \(bleState), \ - blePhase: \(blePhase) - """) - - // Check if user expects to be connected - guard connectionIntent.wantsConnection, - let deviceID = lastConnectedDeviceID else { return } - - if await shouldStandDownOpportunisticBluetoothReconnect(for: deviceID) { - return - } - - if activeReconnectDeviceID == deviceID { - logger.info("[BLE] Skipping foreground reconnect: reconnect/session rebuild already in progress for \(deviceID.uuidString.prefix(8))") - return - } - - // Check actual BLE state. A live BLE transport is only healthy if the - // MC1 session, services, and listeners are alive too. - let bleConnected = await stateMachine.isConnected - if bleConnected { - await reconcileConnectedBLEAppStack(deviceID: deviceID) - return - } - - // Don't interfere if iOS auto-reconnect is still in progress - if await stateMachine.isAutoReconnecting { - logger.info("[BLE] Skipping foreground reconnect: iOS auto-reconnect still in progress") - return - } - - // Don't attempt reconnection when Bluetooth is off - if await stateMachine.isBluetoothPoweredOff { - logger.info("[BLE] Skipping foreground reconnect: Bluetooth is powered off") - return - } - - // Detect stale connection state: app thinks connected but BLE is actually disconnected - // This happens when iOS terminates the BLE connection while app is suspended - if connectionState.isConnected { - logger.warning("[BLE] Detected stale connection state on foreground: connectionState=\(String(describing: connectionState)) but BLE disconnected, triggering cleanup") - await handleConnectionLoss(deviceID: deviceID, error: nil) - } - - // If iOS kept a system-level BLE link alive (common across app updates) but our state machine is idle, - // adopt the existing connection rather than treating it as "connected elsewhere". - if await startAdoptingLastSystemConnectedPeripheralIfAvailable( - deviceID: deviceID, - context: "checkBLEConnectionHealth" - ) { - return - } - - // Don't reconnect if device is connected to another app - if await isDeviceConnectedToOtherApp(deviceID) { - let blePeripheralState = await stateMachine.linkDiagnostics.peripheralState ?? "none" - persistDisconnectDiagnostic( - "source=checkBLEConnectionHealth.otherAppConnected, " + - "device=\(deviceID.uuidString.prefix(8)), " + - "bleState=\(bleState), " + - "blePhase=\(blePhase), " + - "blePeripheralState=\(blePeripheralState), " + - "intent=\(connectionIntent)" - ) - - // Ensure retries continue even when this method is called directly - // (outside appDidBecomeActive's watchdog re-arm path). - if reconnectionWatchdogTask == nil { - startReconnectionWatchdog() - } - logger.info("[BLE] Skipping foreground reconnect: device connected to another app") - return - } - - logger.info("[BLE] Attempting foreground reconnection to \(deviceID.uuidString.prefix(8))") - await attemptOpportunisticReconnect(deviceID: deviceID, reason: "foreground health check") - } - - /// True when the saved row's last method is WiFi, so a foreground check or a - /// Bluetooth power-on must not dial that peripheral. No saved row still dials. - func shouldStandDownOpportunisticBluetoothReconnect(for deviceID: UUID) async -> Bool { - guard let device = try? await persistenceStore.fetchDevice(id: deviceID) else { - return false - } - guard case .wifi = device.lastUsedConnectionMethod else { - return false - } - logger.info( - "[BLE] Opportunistic Bluetooth reconnect standing down: last-used method is WiFi for \(deviceID.uuidString.prefix(8))" - ) - return true - } - - private func reconcileConnectedBLEAppStack(deviceID: UUID) async { - if await stateMachine.isAutoReconnecting { - logger.info("[BLE] Skipping connected-transport recovery: iOS auto-reconnect still in progress") - return - } - - let bleConnectedDeviceID = await stateMachine.connectedDeviceID - if let bleConnectedDeviceID, bleConnectedDeviceID != deviceID { - logger.warning( - "[BLE] Connected transport belongs to \(bleConnectedDeviceID.uuidString.prefix(8)); expected \(deviceID.uuidString.prefix(8))" - ) - return - } - - guard let services, - session != nil, - let connectedDevice, - connectedDevice.id == deviceID else { - await rebuildConnectedBLEAppStack(deviceID: deviceID) - return - } - - guard connectionState.isOperational else { - logger.info( - "[BLE] Connected transport app stack present while state is \(String(describing: connectionState)); leaving active connection flow in place" - ) - return - } - - await reconcileConnectedBLEListeners( - services: services, - radioID: connectedDevice.radioID - ) - } - - private func rebuildConnectedBLEAppStack(deviceID: UUID) async { - guard connectionTeardownCount == 0, - connectionIntent.wantsConnection, - !powerOffBlocksReconnect, - currentTransportType != .wifi, - wifiTransport == nil, - connectingDeviceID == nil, - connectionState != .connecting else { return } - // Claim before any further await so concurrent health Tasks (watchdog + - // foreground after preserve) cannot both observe connected and enter rebuild. - // Same structural single-flight the coordinator retry gap requires. - guard activeReconnectDeviceID == nil else { - logger.info( - "[BLE] Skipping connected-transport rebuild: reconnect/session rebuild already in progress for \(activeReconnectDeviceID?.uuidString.prefix(8) ?? "nil")" - ) - return - } - sessionRebuildDeviceID = deviceID - defer { - if sessionRebuildDeviceID == deviceID { - sessionRebuildDeviceID = nil - } - } - - logger.warning( - "[BLE] Connected BLE transport has missing app stack; rebuilding session for \(deviceID.uuidString.prefix(8))" - ) - connectionState = .connecting - - do { - try await rebuildSessionForHealthCheck(deviceID: deviceID) - } catch { - logger.warning("[BLE] Connected-transport session rebuild failed: \(error.localizedDescription)") - await handleReconnectionFailure() - } - } - - private func rebuildSessionForHealthCheck(deviceID: UUID) async throws { - #if DEBUG - if let rebuildSessionForHealthCheckOverride { - try await rebuildSessionForHealthCheckOverride(deviceID) - return - } - #endif - - try await rebuildSession(deviceID: deviceID) - } - - private func reconcileConnectedBLEListeners( - services: ServiceContainer, - radioID: UUID - ) async { - let eventMonitoringActive = services.isEventMonitoringActive - let autoFetchActive = await services.messagePollingService.isAutoFetching - - guard !eventMonitoringActive || !autoFetchActive else { return } - - logger.warning( - "[BLE] Connected BLE app stack missing listeners; restarting event pipeline for \(radioID.uuidString.prefix(8))" - ) - - if !eventMonitoringActive { - await services.startEventMonitoring(radioID: radioID) - } else { - await services.messagePollingService.startAutoFetch(radioID: radioID) - } - } - - // MARK: - BLE Connection - - /// Connects with retry logic for reconnection scenarios - func connectWithRetry(deviceID: UUID, attemptID: UUID, maxAttempts: Int) async throws { - var lastError: Error = ConnectionError.connectionFailed("Unknown error") - - for attempt in 1...maxAttempts { - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw CancellationError() } - - do { - try await performConnection(deviceID: deviceID, attemptID: attemptID) - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw CancellationError() } - - recordConnectionSuccess() - if attempt > 1 { - logger.info("Reconnection succeeded on attempt \(attempt)") - } - return - - } catch { - lastError = error - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw error } - - // BLE precondition failures won't resolve between retries. - // Exit without retrying or tripping the circuit breaker so that - // onBluetoothPoweredOn can reconnect cleanly when BLE comes back. - // Auth failures also bypass retry — the bond is bad, the user has to - // intervene; four sequential auth failures just delays the recovery alert. - if let bleError = error as? BLEError { - switch bleError { - case .bluetoothPoweredOff, .bluetoothUnavailable, .bluetoothUnauthorized: - throw error - case .authenticationFailed: - // The peripheral connected before auth failed, leaving the - // BLE state machine in a non-idle phase. Tear down before - // bypassing retries so subsequent connects start fresh. - do { - beginConnectionTeardown() - defer { endConnectionTeardown() } - await cleanupResources() - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw error } - await transport.disconnect() - } - throw error - default: - break - } - } - - if isDeviceNotFoundError(error) { - await logDeviceNotFoundDiagnostics(deviceID: deviceID, context: "connectWithRetry attempt \(attempt)") - } - - // Diagnostic: Log BLE state on each failed attempt - let diagnostics = await stateMachine.linkDiagnostics - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw error } - let blePhase = diagnostics.phase - let blePeripheralState = diagnostics.peripheralState ?? "none" - let backoffDelay = attempt < maxAttempts ? 0.3 * pow(2.0, Double(attempt - 1)) : 0.0 - let backoffStr = backoffDelay.formatted(.number.precision(.fractionLength(2))) - logger.warning( - "[BLE] Reconnection attempt \(attempt)/\(maxAttempts) failed - error: \(error.localizedDescription), blePhase: \(blePhase), blePeripheralState: \(blePeripheralState), nextBackoff: \(backoffStr)s" - ) - - // Clean up resources but keep state as .connecting - do { - beginConnectionTeardown() - defer { endConnectionTeardown() } - await cleanupResources() - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw error } - await transport.disconnect() - } - - if attempt < maxAttempts { - // Backoff delay - state remains .connecting - let baseDelay = 0.3 * pow(2.0, Double(attempt - 1)) - let jitter = Double.random(in: 0...0.1) * baseDelay - try await Task.sleep(for: .seconds(baseDelay + jitter)) - } - } - } - - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw CancellationError() } - // All retries exhausted - trip circuit breaker, then throw - recordConnectionFailure() - - // Diagnostic: Log final failure state - let finalDiagnostics = await stateMachine.linkDiagnostics - let finalBlePhase = finalDiagnostics.phase - let finalBlePeripheralState = finalDiagnostics.peripheralState ?? "none" - logger.error( - "[BLE] All \(maxAttempts) reconnection attempts exhausted - lastError: \(lastError.localizedDescription), blePhase: \(finalBlePhase), blePeripheralState: \(finalBlePeripheralState)" - ) - - throw lastError - } - - /// Performs the actual connection to a device - func performConnection(deviceID: UUID, attemptID: UUID) async throws { - // Note: connectionState is already .connecting (set by caller) - - // Stop any existing session to prevent multiple receive loops racing for transport data - await session?.stop() - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw CancellationError() } - session = nil - - // Set device ID and connect - await transport.setDeviceID(deviceID) - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw CancellationError() } - try await transport.connect() - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw CancellationError() } - - logger.info("[BLE] State → .connected (transport connected for device: \(deviceID.uuidString.prefix(8)))") - connectionState = .connected - - // Create session - let newSession = MeshCoreSession(transport: transport) - session = newSession - - let (meshCoreSelfInfo, deviceCapabilities) = try await initializeSession(newSession) - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw CancellationError() } - - // Session traffic flowed over the encrypted UART link, so the bond is - // proven healthy as of now. Also marks the app session live for RSSI refresh. - await recordBondVerification(deviceID: deviceID) - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw CancellationError() } - - // Configure BLE write pacing based on device platform - await configureBLEPacing(for: deviceCapabilities) - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw CancellationError() } - - let (newServices, radioID) = try await buildServicesAndSaveDevice( - deviceID: deviceID, - session: newSession, - selfInfo: meshCoreSelfInfo, - capabilities: deviceCapabilities, - connectionMethods: Self.bleConnectionMethods(for: deviceID), - connectionAttemptID: attemptID - ) - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw CancellationError() } - - // Persist connection for auto-reconnect - persistConnection(deviceID: deviceID, radioID: radioID, deviceName: meshCoreSelfInfo.name) - - // Notify observers before sync starts so they can wire callbacks - // (e.g., AppState needs to set sync activity callbacks for the syncing pill) - await onConnectionReady?() - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw CancellationError() } - let shouldForceFullSync: Bool - if case let .wantsConnection(force) = connectionIntent { - shouldForceFullSync = force - if force { connectionIntent = .wantsConnection() } - } else { - shouldForceFullSync = false - } - let syncResult = await performInitialSync(radioID: radioID, services: newServices, forceFullSync: shouldForceFullSync) - - guard await promoteToReady( - syncResult: syncResult, - expectedServices: newServices, - transportType: .bluetooth, - additionalGuard: { self.ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) } - ) else { - await newSession.stop(disconnectTransport: false) - return - } - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw CancellationError() } - - stopReconnectionWatchdog() - logger.info("Connection complete - device ready") - } - - // MARK: - BLE Diagnostics Helpers - - func logDeviceNotFoundDiagnostics(deviceID: UUID, context: String) async { - let diagnostics = await stateMachine.linkDiagnostics - let bleState = diagnostics.centralState - let blePhase = diagnostics.phase - let lastDeviceShort = lastConnectedDeviceID?.uuidString.prefix(8) ?? "none" - let registeredDevices = pairing.registeredDeviceInfos() - let pairedSummary = registeredDevices.prefix(5).map { info in - "\(info.name)(\(info.id.uuidString.prefix(8)))" - } - let pairedSummaryText = pairedSummary.isEmpty ? "none" : pairedSummary.joined(separator: ", ") - - logger.warning( - // swiftlint:disable:next line_length - "[BLE] Device not found diagnostics (\(context)) - device: \(deviceID.uuidString.prefix(8)), lastDevice: \(lastDeviceShort), connectionIntent: \(connectionIntent), bleState: \(bleState), blePhase: \(blePhase), pairingSessionActive: \(pairing.isSessionActive), pairedCount: \(registeredDevices.count), paired: \(pairedSummaryText)" - ) - } - - func isDeviceNotFoundError(_ error: Error) -> Bool { - if case ConnectionError.deviceNotFound = error { return true } - if case BLEError.deviceNotFound = error { return true } - return false - } - - // MARK: - Connection Loss Handling - - /// Handles unexpected connection loss - func handleConnectionLoss(deviceID: UUID, error: Error?) async { - // Don't clobber a newer connection attempt - if connectionState == .connecting { - let activeID = connectingDeviceID ?? reconnectionCoordinator.reconnectingDeviceID - if let activeID, activeID != deviceID { - logger.info("[BLE] Ignoring connection loss for \(deviceID.uuidString.prefix(8)) — connecting to \(activeID.uuidString.prefix(8))") - return - } - } - - let stateBeforeLoss = connectionState - var errorInfo = "none" - if let error = error as NSError? { - errorInfo = "domain=\(error.domain), code=\(error.code), desc=\(error.localizedDescription)" - } - logger.warning("[BLE] Connection lost: \(deviceID.uuidString.prefix(8)), currentState: \(String(describing: connectionState)), error: \(errorInfo)") - - // Cancel any pending auto-reconnect timeout and clear device identity - reconnectionCoordinator.cancelTimeout() - reconnectionCoordinator.clearReconnectingDevice() - - cancelResyncLoop() - - // Capture and clear synchronously, mirroring teardownSessionForReconnect: - // a same-device rebuild can install a new container during the awaits - // below, and re-reading self.services would tear that new container down. - let oldServices = services - services = nil - session = nil - - logger.warning("[BLE] State → .disconnected (connection loss for device: \(deviceID.uuidString.prefix(8)))") - connectionState = .disconnected - if connectingDeviceID == deviceID { connectingDeviceID = nil } - connectedDevice = nil - allowedRepeatFreqRanges = [] - - if let oldServices { - // Mark room sessions disconnected before tearing down services - _ = await oldServices.remoteNodeService.handleBLEDisconnection() - await oldServices.tearDown() - // Reset sync state to prevent stuck "Syncing" pill - await oldServices.syncCoordinator.onDisconnected(notificationService: oldServices.notificationService) - } - - persistDisconnectDiagnostic( - "source=handleConnectionLoss, " + - "device=\(deviceID.uuidString.prefix(8)), " + - "stateBefore=\(String(describing: stateBeforeLoss)), " + - "error=\(errorInfo), " + - "intent=\(connectionIntent)" - ) - - // Keep transport reference for iOS auto-reconnect to use - - // Notify UI layer of connection loss - await onConnectionLost?() - - // An invalidated bond can't heal through auto-reconnect or the watchdog; - // surface the guided pairing-failure recovery instead of retrying silently. - if let error, case BLEError.authenticationFailed = error { - surfaceAuthenticationFailure(deviceID: deviceID) - } - - // iOS auto-reconnect handles normal disconnects via reconnectionCoordinator - // Bluetooth power-cycle handled via onBluetoothPoweredOn callback - // Watchdog provides fallback retry if both fail - if connectionIntent.wantsConnection { - startReconnectionWatchdog() - } - } - - /// Publishes user-actionable Bluetooth availability for the pickers and logs the change. - /// Disconnect logic is not duplicated here — BLEStateMachine already handles - /// `.poweredOff` via `cancelCurrentOperation` which fires `onDisconnection`. + /// Publishes Bluetooth availability for pickers and diagnostics. + /// `BLEStateMachine` owns power-loss cancellation and its disconnected lifecycle event. func handleBluetoothStateChange(_ state: CBManagerState) { let stateName = switch state { case .unknown: "unknown" diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+BLEHealth.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+BLEHealth.swift new file mode 100644 index 0000000000..9adfd05170 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+BLEHealth.swift @@ -0,0 +1,247 @@ +import Foundation + +extension ConnectionManager { + func handOffBluetoothIfNeeded(_ request: ConnectionRequest, deviceID: UUID) async throws -> Bool { + await stateMachine.activate() + try requireOwnership(request) + if try await handOffToOwningBluetoothLink(request, deviceID: deviceID) { return true } + if try await startAdoptingSystemLink(request, deviceID: deviceID) { return true } + // willRestoreState can claim the peripheral after the idle sample that let + // adoption start. Dialing then cancels that restored link on teardown. + if try await handOffToOwningBluetoothLink(request, deviceID: deviceID) { return true } + let heldElsewhere = await isDeviceConnectedToOtherApp(deviceID) + try requireOwnership(request) + if heldElsewhere, !isOwnedSystemConnectedLink(deviceID) || request.origin == .recovery { + persistDisconnectDiagnostic("source=ble.otherAppConnected, device=\(deviceID.uuidString.prefix(8))") + throw BLEError.deviceConnectedToOtherApp + } + return false + } + + func handOffToOwningBluetoothLink(_ request: ConnectionRequest, deviceID: UUID) async throws -> Bool { + let autoReconnecting = await stateMachine.isAutoReconnecting + let connectedID = await stateMachine.connectedDeviceID + let connected = await stateMachine.isConnected + try requireOwnership(request) + guard autoReconnecting || connected, connectedID == deviceID, !request.forceReconnect else { return false } + guard let origin = await transport.lifecycleOrigin, origin.deviceID == deviceID else { return false } + try requireOwnership(request) + if let accepted = request.physicalOrigin, accepted.generation > origin.generation { return true } + await enterBLERecovery(request, origin: origin) + if let cycle = reconnectionCoordinator.currentCycle, cycle.requestID == request.id { + try await reconcileBLERecoveryCompletion(request, cycle: cycle, origin: origin) + } + return true + } + + private func startAdoptingSystemLink(_ request: ConnectionRequest, deviceID: UUID) async throws -> Bool { + guard isOwnedSystemConnectedLink(deviceID) else { return false } + let diagnostics = await stateMachine.linkDiagnostics + try requireOwnership(request) + guard diagnostics.phase == .idle else { return false } + let systemConnected = await stateMachine.isDeviceConnectedToSystem(deviceID) + try requireOwnership(request) + guard systemConnected else { return false } + persistDisconnectDiagnostic("source=ble.adoptSystemConnectedPeripheral, device=\(deviceID.uuidString.prefix(8))") + request.handedOff = true + let cycle = reconnectionCoordinator.begin(deviceID: deviceID, requestID: request.id) + publishPending(request, phase: .connecting) + let started = await stateMachine.startAdoptingSystemConnectedPeripheral(deviceID) + try requireOwnership(request) + if !started { + request.handedOff = false + reconnectionCoordinator.clear() + return false + } + let origin = await transport.lifecycleOrigin + try requireOwnership(request) + guard reconnectionCoordinator.isCurrent(cycle) else { return true } + if let origin, origin.deviceID == deviceID { + request.physicalOrigin = origin + try await reconcileBLERecoveryCompletion(request, cycle: cycle, origin: origin) + } else { + reconnectionCoordinator.armTimeout(cycle) + } + return true + } + + private func reconcileBLERecoveryCompletion( + _ request: ConnectionRequest, + cycle: BLEReconnectionCoordinator.Cycle, + origin: BLELifecycleOrigin + ) async throws { + let connected = await stateMachine.isConnected + let currentOrigin = await transport.lifecycleOrigin + try requireOwnership(request) + guard reconnectionCoordinator.isCurrent(cycle), cycle.requestID == request.id, + cycle.deviceID == origin.deviceID, + request.physicalOrigin?.deviceID == origin.deviceID, + request.physicalOrigin?.generation == origin.generation, + currentOrigin?.deviceID == origin.deviceID, + currentOrigin?.generation == origin.generation else { return } + if connected { + Task { await self.reconnectionCoordinator.complete(cycle) } + } else { + reconnectionCoordinator.armTimeout(cycle) + } + } + + public func checkBLEConnectionHealth() async { + guard !shouldDeferBLEHealthReconciliation, connectionIntent.wantsConnection, + currentTransportType != .wifi, let deviceID = opportunisticBluetoothDeviceID else { return } + let observedRequest = desiredRequest?.id + if await shouldStandDownOpportunisticBluetoothReconnect(for: deviceID) { return } + guard canReconcileBLEHealth(deviceID: deviceID, requestID: observedRequest) else { return } + let connected = await stateMachine.isConnected + let connectedID = await stateMachine.connectedDeviceID + guard canReconcileBLEHealth(deviceID: deviceID, requestID: observedRequest) else { return } + if connected, connectedID == deviceID { + if let link = installedLink { + _ = await reconcileConnectedListeners(for: link) + return + } + let origin = await transport.lifecycleOrigin + guard canReconcileBLEHealth(deviceID: deviceID, requestID: observedRequest), let origin else { return } + let request: ConnectionRequest + if let current = desiredRequest, current.target == .bluetooth(deviceID) { + request = current + } else { + request = ConnectionRequest( + targets: [.bluetooth(deviceID)], origin: .recovery, forceFullSync: false, forceReconnect: false, + continuing: desiredRequest + ) + desiredRequest = request + } + await enterBLERecovery(request, origin: origin) + guard let cycle = reconnectionCoordinator.currentCycle, owns(request) else { return } + await reconnectionCoordinator.complete(cycle) + return + } + let autoReconnecting = await stateMachine.isAutoReconnecting + let poweredOff = await stateMachine.isBluetoothPoweredOff + guard canReconcileBLEHealth(deviceID: deviceID, requestID: observedRequest), !autoReconnecting, !poweredOff else { return } + if connectionState != .disconnected, let request = desiredRequest { + let barrier = beginOwnedRetirement(previousRequest: request, phase: .disconnected, closePhysical: true, retainMembership: true) + await barrier.value + guard owns(request), isCurrent(barrier.receipt), + canReconcileBLEHealth(deviceID: deviceID, requestID: observedRequest) else { return } + await onConnectionLost?(barrier.receipt) + guard owns(request), isCurrent(barrier.receipt), + canReconcileBLEHealth(deviceID: deviceID, requestID: observedRequest) else { return } + } + do { + _ = try await requestConnection(targets: [.bluetooth(deviceID)], origin: .recovery, forceFullSync: false, forceReconnect: false) + } catch let failure as ConnectionRequestFailure { + guard isCurrent(failure) else { return } + if case BLEError.authenticationFailed = failure.underlying { + surfaceAuthenticationFailure(deviceID: deviceID) + } else if connectionIntent.wantsConnection { + startReconnectionWatchdog() + } + } catch { logger.warning("BLE health recovery failed: \(error.localizedDescription)") } + } + + private var shouldDeferBLEHealthReconciliation: Bool { + if shouldDeferOpportunisticReconnect || connectionTeardownCount > 0 { return true } + guard installedLink == nil, let request = desiredRequest else { return false } + if request.attempt?.resource != nil { return true } + return request.worker != nil && request.committedGeneration == nil && connectionState != .disconnected + } + + private func canReconcileBLEHealth(deviceID: UUID, requestID: UUID?) -> Bool { + desiredRequest?.id == requestID && !shouldDeferBLEHealthReconciliation + && connectionIntent.wantsConnection && currentTransportType != .wifi + && reconnectionCoordinator.currentCycle == nil + && (desiredRequest == nil || desiredRequest?.target == .bluetooth(deviceID)) + } + + private var opportunisticBluetoothDeviceID: UUID? { + if let request = desiredRequest { + guard case let .bluetooth(id) = request.target else { return nil } + return id + } + return lastConnectedDeviceID + } + + func shouldStandDownOpportunisticBluetoothReconnect(for deviceID: UUID) async -> Bool { + if let request = desiredRequest { return request.target != .bluetooth(deviceID) } + guard let device = try? await persistenceStore.fetchDevice(id: deviceID) else { return false } + if case .wifi = device.lastUsedConnectionMethod { return true } + return false + } + + /// Bluetooth radio came back while the user still wants a connection. + /// Follows the admitted Bluetooth choice, or saved selection without a request. + func handleBluetoothPoweredOn() async { + #if DEBUG + defer { testBluetoothPoweredOnHandlerRuns += 1 } + #endif + guard connectionIntent.wantsConnection, + connectionState == .disconnected, + let deviceID = opportunisticBluetoothDeviceID else { return } + + if shouldDeferOpportunisticReconnect { + logger.info("[BLE] Bluetooth powered on: standing down (pairing in progress)") + return + } + + let observedRequestID = desiredRequest?.id + let blePhase = await stateMachine.linkDiagnostics.phase + let bleConnectedDeviceID = await stateMachine.connectedDeviceID + guard canReconcileBLEHealth(deviceID: deviceID, requestID: observedRequestID) else { return } + if blePhase != .idle || bleConnectedDeviceID == deviceID { + logger.info( + "[BLE] Bluetooth powered on: BLE already owns reconnect flow for \(deviceID.uuidString.prefix(8)) " + + "(phase: \(blePhase), bleConnectedDevice: \(bleConnectedDeviceID?.uuidString.prefix(8) ?? "none"))" + ) + return + } + + if await shouldStandDownOpportunisticBluetoothReconnect(for: deviceID) { + return + } + + guard canReconcileBLEHealth(deviceID: deviceID, requestID: observedRequestID) else { return } + logger.info("[BLE] Bluetooth powered on: attempting reconnection to \(deviceID.uuidString.prefix(8))") + await attemptOpportunisticReconnect(deviceID: deviceID, reason: "Bluetooth powered on") + } + + /// Admits Bluetooth recovery only for the current choice while lifecycle work permits it. + func attemptOpportunisticReconnect(deviceID: UUID, reason: String) async { + guard !shouldDeferBLEHealthReconciliation, connectionIntent.wantsConnection, + opportunisticBluetoothDeviceID == deviceID else { + logger.info("[BLE] Opportunistic reconnect skipped (\(reason)): target or lifecycle changed") + return + } + do { + _ = try await requestConnection(targets: [.bluetooth(deviceID)], origin: .recovery, forceFullSync: false, forceReconnect: false) + } catch let failure as ConnectionRequestFailure { + guard isCurrent(failure) else { return } + if case BLEError.authenticationFailed = failure.underlying { + surfaceAuthenticationFailure(deviceID: deviceID) + } else if connectionIntent.wantsConnection { + startReconnectionWatchdog() + } + logger.warning("Opportunistic reconnect (\(reason)) failed: \(failure.localizedDescription)") + } catch { + logger.warning("Opportunistic reconnect (\(reason)) failed: \(error.localizedDescription)") + } + } + + /// Routes authentication failures through one latch so each failure episode + /// presents recovery at most once for the affected Device ID. + func surfaceAuthenticationFailure(deviceID: UUID) { + guard surfacedAuthFailureDeviceID != deviceID else { + logger.info("[BLE] Pairing-failure recovery already surfaced for \(deviceID.uuidString.prefix(8)), suppressing repeat") + return + } + surfacedAuthFailureDeviceID = deviceID + onAuthenticationFailure?(deviceID) + } + + /// Clears the auth-failure surfacing latch so the next failure episode for the + /// same device re-presents the guided recovery. + public func clearSurfacedAuthenticationFailure() { + surfacedAuthFailureDeviceID = nil + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+BLEReconnectionDelegate.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+BLEReconnectionDelegate.swift deleted file mode 100644 index 4675e9dea2..0000000000 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+BLEReconnectionDelegate.swift +++ /dev/null @@ -1,388 +0,0 @@ -import Foundation -import MeshCore - -// MARK: - BLEReconnectionDelegate - -extension ConnectionManager: BLEReconnectionDelegate { - func setConnectionState(_ state: DeviceConnectionState) { - let previousState = connectionState - connectionState = state - if state == .disconnected, previousState != .disconnected { - let transportName = switch currentTransportType { - case .bluetooth: "bluetooth" - case .wifi: "wifi" - case nil: "none" - } - persistDisconnectDiagnostic( - "source=reconnectionCoordinator.setConnectionState, " + - "previousState=\(String(describing: previousState)), " + - "transport=\(transportName), " + - "intent=\(connectionIntent)" - ) - } - } - - func setConnectedDevice(_ device: DeviceDTO?) { - connectedDevice = device - } - - func teardownSessionForReconnect() async { - // Capture and clear synchronously so a concurrent rebuildSession can - // assume nil-and-rebuild without racing the terminal writes that used - // to land at the end of this method. Subsequent awaits operate on the - // captured local — they no longer touch self.services / self.session. - let oldServices = services - let oldSession = session - services = nil - session = nil - - // Stop the old session (keeping the transport for the pending reconnect) - // so its receive and auto-fetch loops end now instead of parking on the - // finished dispatcher stream until the object deallocates. - await oldSession?.stop(disconnectTransport: false) - // Symmetry with other stack teardowns: drop session-live so RSSI cannot - // refresh a bond stamp while the app stack is gone (phase may still be - // `.connected` briefly during auto-reconnect entry). - await stateMachine.setAppSessionLive(deviceID: nil) - - if let oldServices { - sessionsAwaitingReauth = await oldServices.remoteNodeService.handleBLEDisconnection() - await oldServices.tearDown() - } - cancelResyncLoop() - - // Reset sync state on the captured services to prevent stuck "Syncing" pill - if let oldServices { - await oldServices.syncCoordinator.onDisconnected(notificationService: oldServices.notificationService) - } - } - - /// Background execution note: iOS provides ~10s of background execution time. - /// Session rebuild (transport + session.start) should complete within this window. - /// Full sync is deferred until performInitialSync returns to foreground via onConnectionEstablished. - func rebuildSession(deviceID: UUID) async throws { - try Task.checkCancellation() - guard connectionTeardownCount == 0, - connectionIntent.wantsConnection, - !powerOffBlocksReconnect, - currentTransportType != .wifi else { throw CancellationError() } - let expectedGeneration = reconnectionCoordinator.reconnectGeneration - logger.info("[BLE] Rebuilding session for auto-reconnect: \(deviceID.uuidString.prefix(8))") - // Nested claim: health-check rebuild may already hold sessionRebuildDeviceID; - // only clear on exit when this call installed the claim. - let claimedHere = sessionRebuildDeviceID == nil - if claimedHere { - sessionRebuildDeviceID = deviceID - } else { - assert( - sessionRebuildDeviceID == deviceID, - "Nested rebuildSession claim must match outer sessionRebuildDeviceID" - ) - } - defer { - if claimedHere, sessionRebuildDeviceID == deviceID { - sessionRebuildDeviceID = nil - } - } - - // The auto-reconnect link is already live, so surface .connected up front, - // matching fresh connect: the syncing pill stays visible through rebuild and - // initial sync instead of a .connecting window the reconnect UI never bounds. - connectionState = .connected - - // Session teardown in this rebuild never disconnects the transport: the - // link belongs to the reconnect cycle (or, when superseded, to a newer - // one), and an explicit disconnect here cancels the OS pending connect - // that is recovering it. User-initiated disconnects sever the transport - // through disconnect(reason:) independently. - - // Stop any existing session to prevent multiple receive loops racing for transport data - await session?.stop(disconnectTransport: false) - session = nil - // App stack is down until handshake succeeds; prevent RSSI from refreshing - // the bond shield over a dead stack. - await stateMachine.setAppSessionLive(deviceID: nil) - - // The stopped session's receive-loop cancellation terminated the vended - // stream's shared storage, so the transport must re-vend before the new - // session reads receivedData. Ordered after the stop above so the stop - // cannot finish the fresh stream. - await transport.refreshDataStream() - - let newSession = MeshCoreSession(transport: transport) - session = newSession - - do { - try await withTimeout(.seconds(10), operationName: "session.start") { - try await newSession.start(reconnectingAttempt: 1, disconnectTransportOnFailure: false) - } - } catch { - logger.warning("[BLE] rebuildSession: session.start() failed: \(error.localizedDescription)") - throw error - } - - // Session traffic flowed over the encrypted UART link, so the bond is - // proven healthy as of now. Also marks the app session live for RSSI refresh. - await recordBondVerification(deviceID: deviceID) - - // Check after await — user may have disconnected or a new reconnect cycle may have started - guard connectionIntent.wantsConnection else { - logger.info("User disconnected during session setup") - await abandonRebuildAfterHandshake( - session: newSession, - setDisconnected: true - ) - return - } - guard reconnectionCoordinator.reconnectGeneration == expectedGeneration else { - logger.info("[BLE] rebuildSession superseded by new reconnect cycle during session setup") - await abandonRebuildAfterHandshake(session: newSession) - return - } - - guard let selfInfo = await newSession.currentSelfInfo else { - logger.warning("[BLE] rebuildSession: selfInfo is nil after start()") - throw ConnectionError.initializationFailed("No self info") - } - let capabilities: DeviceCapabilities - do { - capabilities = try await withTimeout(.seconds(10), operationName: "queryDevice") { - try await newSession.queryDevice() - } - } catch { - logger.warning("[BLE] rebuildSession: queryDevice() failed: \(error.localizedDescription)") - throw error - } - - // Configure BLE write pacing based on device platform - await configureBLEPacing(for: capabilities) - - // Check after await - guard connectionIntent.wantsConnection else { - logger.info("User disconnected during device query") - await abandonRebuildAfterHandshake( - session: newSession, - setDisconnected: true - ) - return - } - guard reconnectionCoordinator.reconnectGeneration == expectedGeneration else { - logger.info("[BLE] rebuildSession superseded by new reconnect cycle during device query") - await abandonRebuildAfterHandshake(session: newSession) - return - } - - let (newServices, radioID) = try await buildServicesAndSaveDevice( - deviceID: deviceID, - session: newSession, - selfInfo: selfInfo, - capabilities: capabilities - ) - - // Check after await — user may have disconnected or new reconnect cycle started - guard connectionIntent.wantsConnection else { - logger.info("User disconnected during service wiring") - await abandonRebuildAfterHandshake( - session: newSession, - services: newServices, - setDisconnected: true - ) - return - } - guard reconnectionCoordinator.reconnectGeneration == expectedGeneration else { - logger.info("[BLE] rebuildSession superseded by new reconnect cycle during service wiring") - await abandonRebuildAfterHandshake(session: newSession, services: newServices) - return - } - - // Notify observers before sync starts so they can wire callbacks - await onConnectionReady?() - // onConnectionReady can suspend; a reentrant main-actor disconnect or - // reconnect-UI timeout may clear connectedDevice or replace services during - // that await. Recheck so an aborted reconnect bails here instead of syncing - // a torn-down session. - guard connectionIntent.wantsConnection, - reconnectionCoordinator.reconnectGeneration == expectedGeneration, - services === newServices, - connectedDevice != nil - else { - logger.info("[BLE] rebuildSession aborted after onConnectionReady: reconnect state changed") - await abandonRebuildAfterHandshake(session: newSession, services: newServices) - return - } - let syncResult = await performInitialSync(radioID: radioID, services: newServices, context: "[BLE] iOS auto-reconnect") - let syncSucceeded = syncResult?.isConnectionUsable == true - - // Caller-specific guard: generation check for superseded reconnects - guard connectionIntent.wantsConnection, - reconnectionCoordinator.reconnectGeneration == expectedGeneration, - services === newServices - else { - await abandonRebuildAfterHandshake(session: newSession, services: newServices) - return - } - - if syncSucceeded { - // Re-authenticate room sessions (sends BLE commands — skip on failure path). - let sessionIDs = sessionsAwaitingReauth - await newServices.remoteNodeService.handleBLEReconnection(sessionIDs: sessionIDs) - - guard connectionIntent.wantsConnection, - reconnectionCoordinator.reconnectGeneration == expectedGeneration, - services === newServices - else { - // IDs preserved for next reconnect cycle — new IDs may have - // arrived during handleBLEReconnection if BLE dropped mid-reauth. - await abandonRebuildAfterHandshake(session: newSession, services: newServices) - return - } - - // Only clear consumed IDs after confirming this cycle is still authoritative. - // Any IDs appended during the await (via teardownSessionForReconnect) survive. - sessionsAwaitingReauth.subtract(sessionIDs) - } - - guard await promoteToReady( - syncResult: syncResult, - expectedServices: newServices, - transportType: .bluetooth, - additionalGuard: { [reconnectionCoordinator] in - reconnectionCoordinator.reconnectGeneration == expectedGeneration - } - ) else { - await abandonRebuildAfterHandshake(session: newSession, services: newServices) - return - } - - recordConnectionSuccess() - stopReconnectionWatchdog() - logger.info("[BLE] iOS auto-reconnect: session ready, device: \(deviceID.uuidString.prefix(8))") - } - - /// Stops a mid-rebuild session that already completed the handshake (session-live - /// may be set), nils the stored session/services when they match, and clears - /// session-live so RSSI cannot refresh over a dead stack while phase stays - /// `.connected`. - private func abandonRebuildAfterHandshake( - session rebuildSession: MeshCoreSession, - services rebuildServices: ServiceContainer? = nil, - setDisconnected: Bool = false - ) async { - await rebuildSession.stop(disconnectTransport: false) - if let rebuildServices { - await rebuildServices.tearDown() - if services === rebuildServices { - services = nil - } - } - if session === rebuildSession { - session = nil - } - await stateMachine.setAppSessionLive(deviceID: nil) - if setDisconnected { - connectionState = .disconnected - connectedDevice = nil - allowedRepeatFreqRanges = [] - } - } - - func disconnectTransport() async { - await transport.disconnect() - } - - func notifyAutoReconnectStarted() async { - await onAutoReconnectStarted?() - } - - func notifyConnectionLost() async { - await onConnectionLost?() - // Reaching UI connection-loss while intent still wants a connection means - // the automatic reconnect paths have been abandoned; the watchdog is the - // remaining recovery. It stands down by itself while iOS auto-reconnect - // is in progress, so arming it alongside a live pending connect is safe. - if connectionIntent.wantsConnection, - connectionState == .disconnected, - currentTransportType == nil || currentTransportType == .bluetooth { - startReconnectionWatchdog() - } - } - - func isTransportAutoReconnecting() async -> Bool { - await stateMachine.isAutoReconnecting - } - - func handleReconnectionFailure() async { - logger.error("[BLE] Auto-reconnect session rebuild failed") - - // Budget only advances when intent still wants a connection. The user-disconnect - // path (coordinator retry under .userDisconnected) reaches here with - // wantsConnection == false; burning the counter on that path would exhaust - // preserve budget after a few disconnect-during-retry events so a later real - // failure severs early. - if connectionIntent.wantsConnection { - consecutiveRebuildFailures += 1 - } - - // Capture and clear synchronously *before* any await so a concurrent rebuild - // that installs session/services during SM queries cannot be torn down by - // re-reading self. Coordinator claim is held through this entire method - // (cleared only after return) so health-check should not start a rebuild - // under us either. - let oldSession = session - let oldServices = services - session = nil - services = nil - connectionState = .disconnected - connectedDevice = nil - allowedRepeatFreqRanges = [] - - // A rebuild failure is an app-layer failure. Severing the link cancels the OS - // pending connect and the live GATT subscription, the only wake sources that - // survive process suspension, and discards a link the health-check ladder can - // rebuild in place. - let isConnected = await stateMachine.isConnected - let isAutoReconnecting = await stateMachine.isAutoReconnecting - let holdsLink = isConnected || isAutoReconnecting - let preserveLink = connectionIntent.wantsConnection - && holdsLink - && consecutiveRebuildFailures <= Self.maxRebuildFailuresPreservingLink - - // Session-live bond refresh must stop while the app stack is dead. - // Clear on both branches — preserve keeps phase `.connected`, so phase cleanup - // never clears the signal there. - await stateMachine.setAppSessionLive(deviceID: nil) - - await oldSession?.stop(disconnectTransport: false) - await oldServices?.tearDown() - - if preserveLink { - // n of N still preserving; sever is on the (N+1)th wanting entry. - logger.warning( - "[BLE] Rebuild failure \(consecutiveRebuildFailures) of \(Self.maxRebuildFailuresPreservingLink) still preserving link (sever on next)" - ) - // Preserve-only: arm if none is running. Natural exit paths inside the - // watchdog Task nil reconnectionWatchdogTask (a finished Task is not - // isCancelled — non-nil alone is not "live"). Do not call - // startReconnectionWatchdog when a live task is running (that always - // cancel+restarts at 30s). - if reconnectionWatchdogTask == nil { - startReconnectionWatchdog() - } - await onConnectionLost?() - } else { - if connectionIntent.wantsConnection, holdsLink { - logger.error( - "[BLE] Rebuild preserve budget exhausted after \(consecutiveRebuildFailures) failures; severing link" - ) - persistDisconnectDiagnostic( - "source=handleReconnectionFailure.preserveBudgetExhausted, " + - "failures=\(consecutiveRebuildFailures), " + - "intent=\(connectionIntent)" - ) - } - await transport.disconnect() - // Exhaustion / no-link / user-disconnect: full path (cancel+restart 30s). - await notifyConnectionLost() - } - } -} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+BLERecovery.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+BLERecovery.swift new file mode 100644 index 0000000000..9477f4ca74 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+BLERecovery.swift @@ -0,0 +1,111 @@ +import Foundation + +extension ConnectionManager { + func wireReconnectPolicy() { + reconnectionCoordinator.onRebuild = { [weak self] cycle in + guard let self else { throw CancellationError() } + try await self.rebuildBLEStack(cycle) + } + reconnectionCoordinator.onExhausted = { [weak self] cycle in + await self?.finishBLERecoveryFailure(cycle) + } + reconnectionCoordinator.onTimeout = { [weak self] cycle in + guard let self, self.reconnectionCoordinator.isCurrent(cycle), + let request = self.desiredRequest, request.id == cycle.requestID, + self.installedLink == nil else { return } + self.publishPending(request, phase: .disconnected) + guard let receipt = self.currentLossReceipt, self.isCurrent(receipt) else { return } + await self.onConnectionLost?(receipt) + } + reconnectionCoordinator.isAutoReconnecting = { [stateMachine] in await stateMachine.isAutoReconnecting } + } + + func handleBLELifecycleEvent(_ event: BLELifecycleEvent) async { + #if DEBUG + defer { testBLELifecycleEventHandled?(event) } + #endif + let origin = event.origin + guard let request = desiredRequest, request.target == .bluetooth(origin.deviceID), + connectionIntent.wantsConnection, + origin.eventTime >= request.admittedAt || request.physicalOrigin?.generation == origin.generation else { return } + if let accepted = request.physicalOrigin, origin.generation < accepted.generation { return } + switch event { + case .remoteLinkLost: + notePowerOffRemoteLoss(deviceID: origin.deviceID, eventTime: origin.eventTime) + case let .autoReconnecting(_, errorInfo): + persistDisconnectDiagnostic("source=ble.autoReconnecting, device=\(origin.deviceID.uuidString.prefix(8)), error=\(errorInfo)") + if shouldDeferOpportunisticReconnect, request.origin != .pairing { + await retireLostBLE(request, origin: origin, error: nil) + return + } + guard !powerOffSuppressesReconnect(for: origin.deviceID) else { return } + await enterBLERecovery(request, origin: origin) + case .reconnected: + guard let cycle = reconnectionCoordinator.currentCycle, cycle.requestID == request.id, + request.physicalOrigin?.generation == origin.generation else { return } + await reconnectionCoordinator.complete(cycle) + case let .disconnected(_, error): + await retireLostBLE(request, origin: origin, error: error) + } + } + + func enterBLERecovery(_ request: ConnectionRequest, origin: BLELifecycleOrigin) async { + guard owns(request) else { return } + if let cycle = reconnectionCoordinator.currentCycle, + cycle.requestID == request.id, request.physicalOrigin?.generation == origin.generation { return } + request.physicalOrigin = origin + request.handedOff = true + request.binding?.revoke() + let cycle = reconnectionCoordinator.begin(deviceID: origin.deviceID, requestID: request.id) + let barrier = beginOwnedRetirement(previousRequest: request, phase: .connecting, closePhysical: false, retainMembership: true) + await onAutoReconnectStarted?(barrier.receipt) + await barrier.value + guard owns(request), reconnectionCoordinator.isCurrent(cycle), installedLink == nil else { return } + reconnectionCoordinator.armTimeout(cycle) + } + + func rebuildBLEStack(_ cycle: BLEReconnectionCoordinator.Cycle) async throws { + guard let request = desiredRequest, request.id == cycle.requestID, + reconnectionCoordinator.isCurrent(cycle), connectionIntent.wantsConnection, + !powerOffBlocksReconnect else { throw CancellationError() } + await retirementTask?.value + try requireOwnership(request) + guard reconnectionCoordinator.isCurrent(cycle) else { throw CancellationError() } + _ = try await establishAttempt(request, preservePhysicalBLE: true) + try requireOwnership(request) + } + + func finishBLERecoveryFailure(_ cycle: BLEReconnectionCoordinator.Cycle) async { + guard let request = desiredRequest, request.id == cycle.requestID, + reconnectionCoordinator.isCurrent(cycle) else { return } + if connectionIntent.wantsConnection { consecutiveRebuildFailures += 1 } + let connected = await stateMachine.isConnected + let reconnecting = await stateMachine.isAutoReconnecting + guard owns(request), reconnectionCoordinator.isCurrent(cycle) else { return } + let preserve = connectionIntent.wantsConnection && (connected || reconnecting) + && consecutiveRebuildFailures <= Self.maxRebuildFailuresPreservingLink + if !preserve, connected || reconnecting, + consecutiveRebuildFailures > Self.maxRebuildFailuresPreservingLink { + persistDisconnectDiagnostic("source=ble.preserveBudgetExhausted, device=\(cycle.deviceID.uuidString.prefix(8))") + } + let barrier = beginOwnedRetirement(previousRequest: request, phase: .disconnected, closePhysical: !preserve, retainMembership: true) + await barrier.value + guard isCurrent(barrier.receipt) else { return } + await onConnectionLost?(barrier.receipt) + guard isCurrent(barrier.receipt), connectionIntent.wantsConnection else { return } + if !preserve || reconnectionWatchdogTask == nil { startReconnectionWatchdog() } + } + + private func retireLostBLE(_ request: ConnectionRequest, origin: BLELifecycleOrigin, error: BLEError?) async { + guard owns(request) else { return } + if let accepted = request.physicalOrigin, accepted.generation > origin.generation { return } + reconnectionCoordinator.clear() + let barrier = beginOwnedRetirement(previousRequest: request, phase: .disconnected, closePhysical: false, retainMembership: true) + await barrier.value + guard isCurrent(barrier.receipt) else { return } + await onConnectionLost?(barrier.receipt) + guard owns(request) else { return } + if case .authenticationFailed = error { surfaceAuthenticationFailure(deviceID: origin.deviceID) } + if connectionIntent.wantsConnection { startReconnectionWatchdog() } + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Connect.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Connect.swift new file mode 100644 index 0000000000..6bc2314842 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Connect.swift @@ -0,0 +1,139 @@ +import Foundation +import MeshCore + +public extension ConnectionManager { + @discardableResult + func connect(to deviceID: UUID, forceFullSync: Bool = false, forceReconnect: Bool = false) async throws -> ConnectionResult { + try Task.checkCancellation() + return try await requestConnection( + targets: [.bluetooth(deviceID)], origin: .explicit, forceFullSync: forceFullSync, forceReconnect: forceReconnect + ) + } + + @discardableResult + func connectViaBluetooth(peripheralID: UUID, forceFullSync: Bool = false) async throws -> ConnectionResult { + try await connect(to: peripheralID, forceFullSync: forceFullSync, forceReconnect: true) + } + + @discardableResult + func connectViaWiFi(host: String, port: UInt16, forceFullSync: Bool = false) async throws -> ConnectionResult { + let normalized = host.trimmingCharacters(in: .whitespacesAndNewlines) + guard !normalized.isEmpty else { throw WiFiTransportError.invalidHost } + return try await requestConnection( + targets: [.wifi(host: normalized, port: port)], origin: .explicit, + forceFullSync: forceFullSync, forceReconnect: true + ) + } + + @discardableResult + func simulatorConnect() async throws -> ConnectionResult { + try await requestConnection(targets: [.simulator], origin: .simulator, forceFullSync: false, forceReconnect: false) + } + + internal func reconnectLastUsedTransport(device: DeviceDTO?, lastDeviceID: UUID) async { + let bluetooth = device?.bluetoothPeripheralID.map { ConnectionRequest.Target.bluetooth($0) } + let wifi: ConnectionRequest.Target? = if case let .wifi(host, port, _) = device?.wifiConnectionMethod { .wifi(host: host, port: port) } else { nil } + let targets: [ConnectionRequest.Target] = if case .wifi = device?.lastUsedConnectionMethod { + [wifi, bluetooth].compactMap(\.self) + } else { + [bluetooth ?? .bluetooth(lastDeviceID), wifi].compactMap(\.self) + } + do { + _ = try await requestConnection(targets: targets, origin: .launch, forceFullSync: false, forceReconnect: false) + } catch let failure as ConnectionRequestFailure { + guard isCurrent(failure) else { return } + if case BLEError.authenticationFailed = failure.underlying { + surfaceAuthenticationFailure(deviceID: bluetooth?.deviceID ?? lastDeviceID) + } + if targets.contains(where: { $0.transportType == .bluetooth }) { startReconnectionWatchdog() } + } catch { + logger.warning("Launch reconnect failed: \(error.localizedDescription)") + } + } + + @discardableResult + func disconnect(reason: DisconnectReason = .userInitiated) async -> ConnectionLossReceipt { + let operation = beginDisconnect(reason: reason) + let metadata = metadataCommitTask + await operation.barrier.value + await metadata?.value + if isCurrent(operation.receipt) { await onConnectionLost?(operation.receipt) } + return operation.receipt + } + + internal func beginDisconnect(reason: DisconnectReason) -> (barrier: ConnectionRetirement, receipt: ConnectionLossReceipt) { + let previous = desiredRequest + switch reason { + case .userInitiated, .statusMenuDisconnectTap, .forgetDevice, .deviceRemovedFromSettings, .factoryReset, .switchingDevice, .powerOff: + connectionIntent = .userDisconnected + surfacedAuthFailureDeviceID = nil + lastCleanChannelSync = nil + lastAttemptedChannelSync = nil + case .resyncFailed, .wifiAddressChange, .wifiReconnectPrep, .bluetoothConnectPrep, .pairingFailed: + break + } + let target = connectionIntent.wantsConnection ? previous?.target ?? .disconnected : .disconnected + let terminal = ConnectionRequest( + targets: [target], origin: .explicit, forceFullSync: false, forceReconnect: false, + continuing: connectionIntent.wantsConnection ? previous : nil + ) + desiredRequest = terminal + logLifecycle("disconnectAdmitted", context: lifecycleContext(request: terminal, attempt: nil, link: nil), reason: reason.rawValue) + previous?.worker?.cancel() + previous?.binding?.revoke() + if reason != .powerOff { invalidatePowerOffForConnectionChange() } + cancelExpectedWiFiReboots() + reconnectionCoordinator.clear() + cancelWiFiReconnection() + stopReconnectionWatchdog() + persistIntent() + let barrier = beginOwnedRetirement( + previousRequest: previous, phase: .disconnected, closePhysical: true, retainMembership: false, closeUnboundPhysical: true + ) + _ = enqueueMetadata { store in try await store.clearActiveConnection() } + return (barrier, barrier.receipt) + } + + internal func establishSimulator(_ request: ConnectionRequest) async throws -> ConnectionResult { + let attempt = ConnectionAttempt(target: .simulator) + installAttempt(attempt, on: request, ownedByAdmissionWorker: true) + do { + await simulatorMode.connect() + try requireAttemptOwnership(request, attempt) + let physical = SimulatorMockTransport() + let binding = attempt.binding + let session = makeBoundSession( + transport: SessionBoundTransport(transport: physical, binding: binding), + scope: request.radioCLICorrelationScope + ) + let resource = ConnectionResource(binding: binding, transport: physical, session: session, wifi: nil, ble: nil) + attempt.resource = resource + await installFloodScopeRecovery(on: resource, requestID: request.id) + let container = ServiceContainer( + session: session, dataStore: persistenceStore, radioID: MockDataProvider.simulatorDeviceID, + appStateProvider: appStateProvider, connectionStateEvents: connectionStateEvents, + initialConnectionState: .connected, radioWiFiState: radioWiFiState(for: MockDataProvider.simulatorDeviceID), + notificationService: notificationServiceForTesting(), + textRulesPreference: { [weak self] in await self?.textRulesPreference } + ) + attempt.preparedServices = container + try await simulatorMode.seedDataStore(persistenceStore) + try requireAttemptOwnership(request, attempt) + await container.chatSendQueueService.hydrate() + try requireAttemptOwnership(request, attempt) + let link = ConnectionLink( + requestID: request.id, target: .simulator, resource: resource, services: container, + device: MockDataProvider.simulatorDevice, synthetic: true + ) + try await commitConnection(request, attempt: attempt, link: link, repeatRanges: []) + await onConnectionReady?(link.snapshot) + guard owns(request), installedLink === link else { return .superseded } + _ = await completeSync(link, syncResult: FullSyncResult(contacts: .clean, channels: .clean, messages: .clean)) + guard owns(request), installedLink === link else { return .superseded } + return .operational(link.snapshot) + } catch { + await retireCandidate(request, attempt: attempt, closePhysical: true) + throw error + } + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+DeviceUpdates.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+DeviceUpdates.swift new file mode 100644 index 0000000000..3dbb218338 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+DeviceUpdates.swift @@ -0,0 +1,203 @@ +import Foundation +import MeshCore + +public extension ConnectionManager { + func updateDevice(from selfInfo: MeshCore.SelfInfo, appliedRadioPresetID: String?) { + applyDeviceUpdate { device in + var updated = device.updating(from: selfInfo) + if let appliedRadioPresetID { + updated.appliedRadioPresetID = appliedRadioPresetID + } else if !device.clientRepeat { + let matches = RadioPresets.matchingPresets( + frequencyKHz: updated.frequency, bandwidthKHz: updated.bandwidth, + spreadingFactor: updated.spreadingFactor, codingRate: updated.codingRate + ) + if let current = updated.appliedRadioPresetID, !matches.contains(where: { $0.id == current }) { + updated.appliedRadioPresetID = nil + } + } + return updated + } + } + + func applyDeviceObservation(_ info: MeshCore.SelfInfo, from producer: ServiceContainer) async { + guard services === producer, let device = connectedDevice else { return } + let radio = NodeConfigService.buildRadioSettings(from: info) + var mapped = device.updating(from: info) + mapped.frequency = radio.frequency + mapped.bandwidth = radio.bandwidth + mapped.spreadingFactor = radio.spreadingFactor + mapped.codingRate = radio.codingRate + mapped.txPower = radio.txPower + mapped.appliedRadioPresetID = catalogID(for: .init( + frequencyKHz: radio.frequency, bandwidthHz: radio.bandwidth, + spreadingFactor: radio.spreadingFactor, codingRate: radio.codingRate, catalogStamp: .reconcile + ), on: device) + let snapshot = mapped + let source = installedLink + let work = enqueueMetadata { store in + try await store.updateConnectionDevice(id: device.id) { current in + guard current.id == device.id, current.publicKey == device.publicKey, + current.radioID == device.radioID else { return nil } + return current.applyingRefresh(snapshot) + } + } + do { + guard try await work.value else { return } + } catch { + logger.error("Failed to persist device observation: \(error.localizedDescription)") + return + } + guard let source, owns(source), services === producer, let current = connectedDevice, + current.id == device.id, current.publicKey == device.publicKey, + current.radioID == device.radioID else { return } + setPublishedDevice(current.applyingRefresh(snapshot)) + } + + func applyNodeName(_ name: String) async { + await applySettingsUpdate { $0.copy { $0.nodeName = name } } + } + + func applyCoordinates(latitude: Double, longitude: Double) async { + await applySettingsUpdate { $0.copy { $0.latitude = latitude; $0.longitude = longitude } } + } + + func applyRadio(_ change: SettingsEvent.RadioChange) async { + guard let device = connectedDevice else { return } + let presetID = catalogID(for: change, on: device) + await applySettingsUpdate { $0.copy { + $0.frequency = change.frequencyKHz + $0.bandwidth = change.bandwidthHz + $0.spreadingFactor = change.spreadingFactor + $0.codingRate = change.codingRate + $0.appliedRadioPresetID = presetID + } } + } + + func applyTxPower(_ power: Int8) async { + await applySettingsUpdate { $0.copy { $0.txPower = power } } + } + + func applyOtherParams(_ intent: OtherParamsIntent) async { + await applySettingsUpdate { $0.copy { + if let value = intent.manualAddContacts { $0.manualAddContacts = value } + if let value = intent.telemetryModeBase { $0.telemetryModeBase = value } + if let value = intent.telemetryModeLocation { $0.telemetryModeLoc = value } + if let value = intent.telemetryModeEnvironment { $0.telemetryModeEnv = value } + if let value = intent.advertisementLocationPolicy { $0.advertLocationPolicy = value } + if let value = intent.multiAcks { $0.multiAcks = value } + } } + } + + private func catalogID(for change: SettingsEvent.RadioChange, on device: DeviceDTO) -> String? { + switch change.catalogStamp { + case let .set(id): return id + case .reconcile: + if device.clientRepeat { return device.appliedRadioPresetID } + let matches = RadioPresets.matchingPresets( + frequencyKHz: change.frequencyKHz, bandwidthKHz: change.bandwidthHz, + spreadingFactor: change.spreadingFactor, codingRate: change.codingRate + ) + guard let current = device.appliedRadioPresetID, matches.contains(where: { $0.id == current }) else { return nil } + return current + } + } + + func updateDevice(with device: DeviceDTO) { + if let current = installedLink?.device { + guard device.id == current.id, device.radioID == current.radioID, + device.publicKey == current.publicKey else { return } + } + setPublishedDevice(device) + } + + func updateAutoAddConfig(_ config: MeshCore.AutoAddConfig) { + applyDeviceUpdate { device in device.copy { + $0.autoAddConfig = config.bitmask + $0.autoAddMaxHops = config.maxHops + } } + } + + func updateClientRepeat(_ enabled: Bool) { + applyDeviceUpdate { $0.copy { $0.clientRepeat = enabled } } + } + + func updatePathHashMode(_ mode: UInt8) { + applyDeviceUpdate { $0.copy { $0.pathHashMode = mode } } + } + + func updateDefaultFloodScopeName(_ name: String?) { + applyDeviceUpdate { $0.copy { $0.defaultFloodScopeName = name } } + } + + func addKnownRegion(_ region: String) { + guard let device = connectedDevice, !device.knownRegions.contains(region), let services else { return } + let source = installedLink + let updated = device.copy { $0.knownRegions.append(region) } + setPublishedDevice(updated) + let work = enqueueMetadata { store in try await store.addDeviceKnownRegion(radioID: updated.radioID, region: region) } + Task { + _ = await work.result + guard let source, self.owns(source) else { return } + await services.rxLogService.updateKnownRegions(updated.knownRegions) + } + } + + func removeKnownRegion(_ region: String) { + guard let device = connectedDevice, let services else { return } + let source = installedLink + let wasDefault = device.defaultFloodScopeName == region + let updated = device.copy { + $0.knownRegions.removeAll { $0 == region } + if wasDefault { $0.defaultFloodScopeName = nil } + } + setPublishedDevice(updated) + let work = enqueueMetadata { store in try await store.removeDeviceKnownRegion(radioID: updated.radioID, region: region) } + Task { + _ = await work.result + guard let source, self.owns(source) else { return } + if wasDefault { + do { _ = try await services.settingsService.setDefaultFloodScopeVerified(name: nil) } catch { + self.logger.error("Failed to clear default flood scope after region removal: \(error)") + } + } + guard self.owns(source) else { return } + await services.rxLogService.updateKnownRegions(updated.knownRegions) + } + } + + func savePreRepeatSettings() { + applyDeviceUpdate { $0.savingPreRepeatSettings() } + } + + func clearPreRepeatSettings() { + applyDeviceUpdate { $0.clearingPreRepeatSettings() } + } +} + +private extension ConnectionManager { + func applySettingsUpdate(_ update: @escaping @Sendable (DeviceDTO) -> DeviceDTO) async { + guard let device = connectedDevice else { return } + setPublishedDevice(update(device)) + let work = enqueueMetadata { store in + try await store.updateConnectionDevice(id: device.id) { current in + guard current.id == device.id, current.publicKey == device.publicKey, + current.radioID == device.radioID else { return nil } + return update(current) + } + } + _ = await work.result + } + + func applyDeviceUpdate(_ update: @escaping @Sendable (DeviceDTO) -> DeviceDTO) { + guard let device = connectedDevice else { return } + setPublishedDevice(update(device)) + _ = enqueueMetadata { store in + try await store.updateConnectionDevice(id: device.id) { current in + guard current.id == device.id, current.publicKey == device.publicKey, + current.radioID == device.radioID else { return nil } + return update(current) + } + } + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Diagnostics.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Diagnostics.swift new file mode 100644 index 0000000000..bc8be8b14d --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Diagnostics.swift @@ -0,0 +1,43 @@ +import Foundation + +extension ConnectionManager { + func lifecycleContext( + request: ConnectionRequest?, attempt: ConnectionAttempt?, link: ConnectionLink?, resource: ConnectionResource? = nil + ) -> String { + let resource = resource ?? link?.resource ?? attempt?.resource + let attempt = attempt.flatMap { candidate in + resource == nil || candidate.binding === resource?.binding ? candidate : nil + } + let binding = resource?.binding ?? attempt?.binding + let requestID = request?.id ?? link?.requestID + let origin = link != nil && attempt != nil ? request?.physicalOrigin : nil + let cycle = reconnectionCoordinator.currentCycle.flatMap { $0.requestID == requestID ? $0 : nil } + let deviceID = link?.device.id ?? attempt?.identity.deviceID ?? origin?.deviceID ?? request?.target.deviceID + let target = link?.target ?? attempt?.target ?? request?.target + let transport = target == .disconnected ? nil : target?.transportType + return "request=\(requestID?.uuidString ?? "none"), " + + "attempt=\(attempt.map { String(describing: ObjectIdentifier($0)) } ?? "none"), " + + "link=\(link?.generation.uuidString ?? "none"), " + + "binding=\(binding.map { String(describing: ObjectIdentifier($0)) } ?? "none"), " + + "bindingActive=\(binding.map { String($0.isActive) } ?? "none"), " + + "session=\(resource.map { String(describing: ObjectIdentifier($0.session)) } ?? "none"), " + + "transport=\(transport.map { String(describing: $0) } ?? "none"), " + + "device=\(deviceID.map { String($0.uuidString.prefix(8)) } ?? "none"), " + + "physicalGeneration=\(origin.map { String($0.generation) } ?? "none"), " + + "physicalEventTime=\(origin.map { String($0.eventTime) } ?? "none"), " + + "reconnectCycle=\(cycle?.id.uuidString ?? "none"), " + + "reconnectGeneration=\(cycle.map { String($0.generation) } ?? "none")" + } + + func logLifecycle(_ event: String, context: String, reason: String? = nil) { + let binding = installedLink?.resource.binding ?? desiredRequest?.binding + logger.info( + "[ConnectionLifecycle] event=\(event), \(context), " + + "currentRequest=\(desiredRequest?.id.uuidString ?? "none"), " + + "currentLink=\(installedLink?.generation.uuidString ?? "none"), " + + "currentBinding=\(binding.map { String(describing: ObjectIdentifier($0)) } ?? "none"), " + + "state=\(String(describing: connectionState))" + + (reason.map { ", reason=\($0)" } ?? "") + ) + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Identity.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Identity.swift new file mode 100644 index 0000000000..c931978d11 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Identity.swift @@ -0,0 +1,129 @@ +import Foundation +import MeshCore +import os + +extension ConnectionManager { + func importIdentity(_ key: Data, expectedServices: ServiceContainer, deviceID: UUID) async throws -> UUID? { + try Task.checkCancellation() + guard key.count == ProtocolLimits.privateKeySize else { throw ConnectionError.notConnected } + guard let source = installedLink, source.services === expectedServices, source.device.id == deviceID, + let request = desiredRequest, owns(source) else { throw CancellationError() } + #if DEBUG + await testIdentityBeforeAdmission?() + #endif + let cancelled = OSAllocatedUnfairLock(initialState: false) + let acknowledged = OSAllocatedUnfairLock(initialState: false) + let job = enqueueMetadata { store in + try await self.performIdentityImport( + key, source: source, request: request, store: store, + cancelled: { cancelled.withLock { $0 } }, acknowledged: acknowledged + ) + } + do { + let result = try await withTaskCancellationHandler { + try await job.value + } onCancel: { + cancelled.withLock { $0 = true } + } + let completion: @Sendable () async throws -> Void = { [weak self] in + guard let self else { throw CancellationError() } + _ = try await self.completeImportedIdentity( + request, attempt: result.attempt, resource: result.resource, prepared: result.prepared + ) + } + let deferred = await source.services.nodeConfigService.adoptImportRuntime( + session: result.resource.session, settingsService: result.prepared.services.settingsService, + channelService: result.prepared.services.channelService, + syncCoordinator: result.prepared.services.syncCoordinator, + contactRadio: result.prepared.services.contactService, onImportFinished: completion + ) + if deferred { + try requireAttemptOwnership(request, result.attempt) + try result.resource.binding.checkActive() + } else { + try await completion() + try Task.checkCancellation() + } + return result.prepared.device.radioID + } catch { + if acknowledged.withLock({ $0 }) { throw ConfigIdentityImportFailure(underlying: error) } + throw error + } + } + + private func performIdentityImport( + _ key: Data, source: ConnectionLink, request: ConnectionRequest, store: PersistenceStore, + cancelled: @escaping @Sendable () -> Bool, acknowledged: OSAllocatedUnfairLock + ) async throws -> (attempt: ConnectionAttempt, resource: ConnectionResource, prepared: PreparedConnection) { + guard owns(source), !cancelled(), let method = source.target.method else { throw CancellationError() } + let repeatRanges = allowedRepeatFreqRanges + let attempt = ConnectionAttempt(target: source.target) + attempt.identity = ConnectionDeviceIdentity(source.device) + installAttempt(attempt, on: request, ownedByAdmissionWorker: true) + let settings = source.services.settingsService + let receipt = IdentityImportReceipt(device: source.device, method: method) + transition(source, to: .connected) + stopWiFiHeartbeat() + cancelResyncLoop() + cancelChannelRetry() + settings.radioWiFiBinding.state.closeAdmission() + do { + await source.services.nodeConfigService.retirePublicAdmission() + try await source.resource.session.prepareForIdentityImport() + await source.resource.cancelUnsubmittedWrites() + await settings.retireRadioWiFiOperations() + source.listenerRepairWorker?.cancel() + await source.services.prepareForIdentityImport() + _ = await source.listenerRepairWorker?.value + try requireAttemptOwnership(request, attempt) + guard !cancelled() else { throw CancellationError() } + guard try await validateIdentitySource(receipt, selfInfo: nil, store: store) != nil else { + throw IdentityReceiptFailure.staleSource + } + try requireAttemptOwnership(request, attempt) + guard !cancelled() else { throw CancellationError() } + pendingIdentityReconciliations[source.device.id] = receipt + let info = try await source.resource.session.importPrivateKeyForReconnection( + key, binding: source.resource.binding, onAcknowledged: { acknowledged.withLock { $0 = true } } + ) + pendingIdentityReconciliations[source.device.id]?.publicKey = info.publicKey + attempt.identity.publicKey = info.publicKey + #if DEBUG + await testIdentityBeforeCommit?() + #endif + let device = try await reconcileImportedIdentity( + receipt: receipt, selfInfo: info, request: request, attempt: attempt, store: store, cancelled: cancelled + ) + attempt.identity = ConnectionDeviceIdentity(device) + return try await rebuildImportedIdentity( + request, attempt: attempt, previousResource: source.resource, device: device, + info: info, retainedSource: source, repeatRanges: repeatRanges, cancelled: cancelled + ) + } catch { + let failure = settleIdentityImportFailure(error, receipt: receipt, preservingEarlierReceipt: false) + if request.removedIdentities.contains(where: { $0.matches(receipt.originalIdentity) }) { consumeIdentityReceipt(receipt) } + if installedLink === source { detachPublication(phase: .disconnected) } + await source.resource.retire(closePhysical: true) + await source.services.tearDown() + await retireCandidate(request, attempt: attempt, closePhysical: true) + if owns(request), request.attempt == nil { _ = beginDisconnect(reason: .userInitiated) } + if let unresolved = pendingIdentityReconciliations[source.device.id], unresolved.publicKey == nil { + throw IdentityImportRecoveryRequired(recovery: unresolved.recovery(currentRequestID: connectionRequestID)) + } + throw failure + } + } + + func settleIdentityImportFailure( + _ error: any Error, receipt: IdentityImportReceipt, preservingEarlierReceipt: Bool + ) -> any Error { + guard let failure = error as? IdentityImportReconnectionError else { return identityFailureForPresentation(error) } + if !preservingEarlierReceipt, pendingIdentityReconciliations[receipt.originalDeviceID]?.receiptID == receipt.receiptID { + pendingIdentityReconciliations[receipt.originalDeviceID] = nil + } + switch failure { + case .uncertainResponseHistory: return ConnectionError.notConnected + case let .rejected(underlying): return underlying + } + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+IdentityReconciliation.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+IdentityReconciliation.swift new file mode 100644 index 0000000000..d7547ef758 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+IdentityReconciliation.swift @@ -0,0 +1,119 @@ +import Foundation +import MeshCore + +extension ConnectionManager { + enum IdentityReceiptFailure: Error { + case staleSource + case ambiguousIdentity + } + + func reconcileImportedIdentity( + receipt: IdentityImportReceipt, selfInfo: SelfInfo, request: ConnectionRequest, + attempt: ConnectionAttempt, store: PersistenceStore, cancelled: @Sendable () -> Bool + ) async throws -> DeviceDTO { + try requireIdentityReceipt(receipt, request: request, attempt: attempt) + guard !cancelled() else { throw CancellationError() } + guard let imported = try await validateIdentitySource(receipt, selfInfo: selfInfo, store: store) else { + consumeIdentityReceipt(receipt) + throw IdentityReceiptFailure.staleSource + } + #if DEBUG + await testIdentityAfterCommit?() + #endif + await transferRadioWiFiEvidence(from: receipt.originalRadioID, to: imported.radioID) + consumeIdentityReceipt(receipt) + if receipt.originalPublicKey != selfInfo.publicKey { + await dropStaleVContact(dataStore: store, radioID: receipt.originalRadioID, oldSelfPublicKey: receipt.originalPublicKey) + } + return imported + } + + func reconcilePendingIdentity( + request: ConnectionRequest, attempt: ConnectionAttempt, deviceID: UUID, selfInfo: SelfInfo + ) async throws -> Bool { + let receipt: IdentityImportReceipt + if let exact = pendingIdentityReconciliations[deviceID], exact.publicKey != nil || exact.target == attempt.target { + receipt = exact + } else if let source = pendingIdentityReconciliations.values.first(where: { $0.target == attempt.target }) { + receipt = source + } else { + let matches = pendingIdentityReconciliations.values.filter { $0.publicKey == selfInfo.publicKey } + guard !matches.isEmpty else { return false } + guard matches.count == 1, let match = matches.first else { throw IdentityReceiptFailure.ambiguousIdentity } + receipt = match + } + let work = enqueueMetadata { store in + try self.requireIdentityReceipt(receipt, request: request, attempt: attempt) + if receipt.publicKey == selfInfo.publicKey { + _ = try await self.reconcileImportedIdentity( + receipt: receipt, selfInfo: selfInfo, request: request, attempt: attempt, store: store, cancelled: { false } + ) + return true + } + guard try await self.validateIdentitySource(receipt, selfInfo: nil, store: store) != nil else { + self.consumeIdentityReceipt(receipt) + throw IdentityReceiptFailure.staleSource + } + try self.requireIdentityReceipt(receipt, request: request, attempt: attempt) + if receipt.publicKey == nil, receipt.originalPublicKey == selfInfo.publicKey { + self.consumeIdentityReceipt(receipt) + return false + } + if receipt.publicKey == nil { + throw IdentityImportRecoveryRequired(recovery: receipt.recovery(currentRequestID: self.connectionRequestID)) + } + throw IdentityReceiptFailure.ambiguousIdentity + } + return try await work.value + } + + func validateIdentitySource( + _ receipt: IdentityImportReceipt, selfInfo: SelfInfo?, store: PersistenceStore + ) async throws -> DeviceDTO? { + #if DEBUG + await testIdentityBeforeSourceValidation?() + #endif + return try await store.importConnectionIdentity( + deviceID: receipt.originalDeviceID, expectedRadioID: receipt.originalRadioID, + expectedPublicKey: receipt.originalPublicKey, selfInfo: selfInfo + ) + } + + func requireIdentityReceipt( + _ receipt: IdentityImportReceipt, request: ConnectionRequest, attempt: ConnectionAttempt + ) throws { + try requireAttemptOwnership(request, attempt) + guard pendingIdentityReconciliations[receipt.originalDeviceID]?.receiptID == receipt.receiptID else { + throw CancellationError() + } + if request.removedIdentities.contains(where: { $0.matches(receipt.originalIdentity) }) { throw CancellationError() } + } + + func consumeIdentityReceipt(_ receipt: IdentityImportReceipt) { + if pendingIdentityReconciliations[receipt.originalDeviceID]?.receiptID == receipt.receiptID { + pendingIdentityReconciliations[receipt.originalDeviceID] = nil + } + } + + func isTerminalIdentityError(_ error: any Error) -> Bool { + error is IdentityImportRecoveryRequired || error is IdentityReceiptFailure + } + + func identityFailureForPresentation(_ error: any Error) -> any Error { + guard let failure = error as? IdentityReceiptFailure else { return error } + switch failure { + case .staleSource: return ConnectionError.deviceNotFound + case .ambiguousIdentity: return ConnectionError.notConnected + } + } + + private func dropStaleVContact(dataStore: PersistenceStore, radioID: UUID, oldSelfPublicKey: Data) async { + guard let oldVKey = VContactIdentity.publicKey(forSelfPublicKey: oldSelfPublicKey) else { return } + do { + guard let contact = try await dataStore.fetchContact(radioID: radioID, publicKey: oldVKey) else { return } + try await dataStore.deleteContact(id: contact.id) + } catch { + logger.warning("Failed to drop stale V-contact after identity rotation: \(error.localizedDescription)") + } + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+IdentityRecovery.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+IdentityRecovery.swift new file mode 100644 index 0000000000..88fc3c4a25 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+IdentityRecovery.swift @@ -0,0 +1,119 @@ +import Foundation +import MeshCore +import os + +public extension ConnectionManager { + var identityImportRecoveries: [IdentityImportRecovery] { + pendingIdentityReconciliations.values.filter { $0.publicKey == nil } + .map { $0.recovery(currentRequestID: connectionRequestID) } + .sorted { $0.receiptID.uuidString < $1.receiptID.uuidString } + } + + func prepareIdentityImportRecovery(receiptID: UUID) -> IdentityImportRecovery? { + identityImportRecoveries.first { $0.receiptID == receiptID } + } + + func retryIdentityImport( + confirmation: IdentityImportRecovery, privateKey: Data + ) async throws -> ConnectionResult { + try Task.checkCancellation() + guard privateKey.count == ProtocolLimits.privateKeySize, + prepareIdentityImportRecovery(receiptID: confirmation.receiptID) == confirmation, + let receipt = pendingIdentityReconciliations[confirmation.originalDeviceID], + receipt.receiptID == confirmation.receiptID else { throw CancellationError() } + let preflight = enqueueMetadata { store in + try Task.checkCancellation() + guard self.prepareIdentityImportRecovery(receiptID: confirmation.receiptID) == confirmation else { + throw CancellationError() + } + let source = try await self.validateIdentitySource(receipt, selfInfo: nil, store: store) + try Task.checkCancellation() + guard self.prepareIdentityImportRecovery(receiptID: confirmation.receiptID) == confirmation else { + throw CancellationError() + } + guard source != nil else { + self.consumeIdentityReceipt(receipt) + throw ConnectionError.deviceNotFound + } + } + try await withTaskCancellationHandler { + try await preflight.value + } onCancel: { + preflight.cancel() + } + try Task.checkCancellation() + guard prepareIdentityImportRecovery(receiptID: confirmation.receiptID) == confirmation else { + throw CancellationError() + } + return try await requestConnection( + targets: [receipt.target], origin: .explicit, forceFullSync: false, forceReconnect: true, + operation: { request in + try await self.runIdentityRecovery(request, receipt: receipt, privateKey: privateKey) + } + ) + } + + private func runIdentityRecovery( + _ request: ConnectionRequest, receipt: IdentityImportReceipt, privateKey: Data + ) async throws -> ConnectionResult { + let attempt = ConnectionAttempt(target: receipt.target) + attempt.identity = receipt.originalIdentity + installAttempt(attempt, on: request, ownedByAdmissionWorker: true) + do { + let resource = try await openConnectionResource(request, attempt: attempt, preservePhysicalBLE: false) + _ = try await initializeSession(resource.session, attempt: attempt) + try requireIdentityReceipt(receipt, request: request, attempt: attempt) + let cancelled = OSAllocatedUnfairLock(initialState: false) + let job = enqueueMetadata { store in + guard !cancelled.withLock({ $0 }) else { throw CancellationError() } + try self.requireIdentityReceipt(receipt, request: request, attempt: attempt) + guard try await self.validateIdentitySource(receipt, selfInfo: nil, store: store) != nil else { + self.consumeIdentityReceipt(receipt) + throw IdentityReceiptFailure.staleSource + } + try self.requireIdentityReceipt(receipt, request: request, attempt: attempt) + try await resource.session.prepareForIdentityImport() + try self.requireIdentityReceipt(receipt, request: request, attempt: attempt) + let info = try await resource.session.importPrivateKeyForReconnection( + privateKey, binding: resource.binding, onAcknowledged: {} + ) + if self.pendingIdentityReconciliations[receipt.originalDeviceID]?.receiptID == receipt.receiptID { + self.pendingIdentityReconciliations[receipt.originalDeviceID]?.publicKey = info.publicKey + } + attempt.identity.publicKey = info.publicKey + #if DEBUG + await self.testIdentityBeforeCommit?() + #endif + let device = try await self.reconcileImportedIdentity( + receipt: receipt, selfInfo: info, request: request, attempt: attempt, store: store, + cancelled: { cancelled.withLock { $0 } } + ) + attempt.identity = ConnectionDeviceIdentity(device) + return try await self.rebuildImportedIdentity( + request, attempt: attempt, previousResource: resource, device: device, info: info, + retainedSource: nil, repeatRanges: nil, cancelled: { cancelled.withLock { $0 } } + ) + } + let prepared = try await withTaskCancellationHandler { + try await job.value + } onCancel: { + cancelled.withLock { $0 = true } + } + let link = try await completeImportedIdentity( + request, attempt: prepared.attempt, resource: prepared.resource, prepared: prepared.prepared + ) + guard owns(request), owns(link) else { return .superseded } + return .operational(link.snapshot) + } catch { + let failure = settleIdentityImportFailure(error, receipt: receipt, preservingEarlierReceipt: true) + if request.removedIdentities.contains(where: { $0.matches(receipt.originalIdentity) }) { consumeIdentityReceipt(receipt) } + await retireCandidate(request, attempt: attempt, closePhysical: true) + if owns(request), request.attempt == nil { _ = beginDisconnect(reason: .userInitiated) } + if let pending = pendingIdentityReconciliations[receipt.originalDeviceID], pending.publicKey == nil, + !(error is IdentityImportReconnectionError) { + throw IdentityImportRecoveryRequired(recovery: pending.recovery(currentRequestID: connectionRequestID)) + } + throw failure + } + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+IdentityRuntime.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+IdentityRuntime.swift new file mode 100644 index 0000000000..c2cb74f14c --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+IdentityRuntime.swift @@ -0,0 +1,101 @@ +import MeshCore + +extension ConnectionManager { + func rebuildImportedIdentity( + _ request: ConnectionRequest, attempt: ConnectionAttempt, previousResource: ConnectionResource, + device: DeviceDTO, info: SelfInfo, + retainedSource: ConnectionLink?, repeatRanges: [MeshCore.FrequencyRange]?, + cancelled: @Sendable () -> Bool + ) async throws -> (attempt: ConnectionAttempt, resource: ConnectionResource, prepared: PreparedConnection) { + try requireAttemptOwnership(request, attempt) + guard !cancelled() else { throw CancellationError() } + if let retainedSource, installedLink === retainedSource { + // Set the flag before detachPublication. The device nils in that call, and the + // settings observers read the flag when they see the nil device. + identityRebuildUnpublished = true + detachPublication(phase: .connected) + } + await previousResource.retire(closePhysical: false) + await retainedSource?.services.tearDown() + try requireAttemptOwnership(request, attempt) + guard !cancelled() else { throw CancellationError() } + let replacement = ConnectionAttempt(target: attempt.target) + replacement.identity = ConnectionDeviceIdentity(device) + installAttempt(replacement, on: request, ownedByAdmissionWorker: true) + func requireRuntimeOwnership() throws { + try requireAttemptOwnership(request, replacement) + guard !cancelled() else { throw CancellationError() } + } + do { + let resource = try await openConnectionResource( + request, attempt: replacement, preservePhysicalBLE: attempt.target.transportType == .bluetooth + ) + let (freshInfo, capabilities) = try await initializeSession(resource.session, attempt: replacement) + guard freshInfo.publicKey == info.publicKey else { throw ConnectionError.notConnected } + try requireRuntimeOwnership() + if let bluetoothID = replacement.target.deviceID { + await recordBondVerification(deviceID: bluetoothID, binding: resource.binding) + try requireRuntimeOwnership() + await configureBLEPacing(for: capabilities, binding: resource.binding) + } + try requireRuntimeOwnership() + let container = try await buildServiceContainer( + request, attempt: replacement, resource: resource, device: device + ) + try requireRuntimeOwnership() + let ranges: [MeshCore.FrequencyRange] = if let repeatRanges { repeatRanges } else { + await capabilities.clientRepeat ? ((try? resource.session.getRepeatFreq()) ?? []) : [] + } + try requireRuntimeOwnership() + return (replacement, resource, PreparedConnection(services: container, device: device, repeatRanges: ranges)) + } catch { + await retireCandidate(request, attempt: replacement, closePhysical: true) + throw error + } + } + + func completeImportedIdentity( + _ request: ConnectionRequest, attempt: ConnectionAttempt, + resource: ConnectionResource, prepared: PreparedConnection + ) async throws -> ConnectionLink { + do { + guard owns(request), request.attempt === attempt, resource.binding.isActive else { throw CancellationError() } + let finalization = enqueueMetadata { store in + await resource.session.waitForQuiescence() + try self.requireAttemptOwnership(request, attempt) + try resource.binding.checkActive() + #if DEBUG + try await self.testConnectionSelectionHandler?(request.id) + #endif + try self.requireAttemptOwnership(request, attempt) + try resource.binding.checkActive() + let selected = try await store.selectConnectionDevice(id: prepared.device.id, method: attempt.target.method) + try self.requireAttemptOwnership(request, attempt) + try resource.binding.checkActive() + let link = ConnectionLink( + requestID: request.id, target: attempt.target, resource: resource, services: prepared.services, device: selected + ) + try self.publish(link, repeatRanges: prepared.repeatRanges) + self.persistConnection(deviceID: selected.id, radioID: selected.radioID, deviceName: selected.nodeName) + request.committedGeneration = link.generation + attempt.resource = nil + attempt.preparedServices = nil + return link + } + let link = try await finalization.value + guard ownsRuntime(link), resource.binding.isActive else { throw CancellationError() } + await beginConnectionSetup(request, link: link).value + #if DEBUG + await testPostSetupResultHandler?(link.generation) + #endif + guard ownsRuntime(link), resource.binding.isActive else { throw CancellationError() } + return link + } catch { + let retirement = owns(request) && request.attempt === attempt + ? beginDisconnect(reason: .userInitiated).barrier : nil + await retireCandidate(request, attempt: attempt, closePhysical: true) + await retirement?.value + throw error + } + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Lifecycle.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Lifecycle.swift index 638926fd31..b548feb505 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Lifecycle.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Lifecycle.swift @@ -3,11 +3,7 @@ import MeshCore public extension ConnectionManager { internal var activeConnectionAttemptDeviceID: UUID? { - connectingDeviceID ?? sessionRebuildDeviceID ?? reconnectionCoordinator.reconnectingDeviceID - } - - internal var activeReconnectDeviceID: UUID? { - sessionRebuildDeviceID ?? reconnectionCoordinator.reconnectingDeviceID + desiredRequest?.attempt?.identity.deviceID ?? desiredRequest?.target.deviceID ?? reconnectionCoordinator.reconnectingDeviceID } // MARK: - App Lifecycle @@ -63,8 +59,7 @@ public extension ConnectionManager { "blePhase: \(blePhase)" ) - guard currentTransportType == nil || currentTransportType == .bluetooth else { return } - guard connectionIntent.wantsConnection, connectionState == .disconnected else { return } + guard currentTransportType == nil || currentTransportType == .bluetooth, connectionIntent.wantsConnection, connectionState == .disconnected else { return } if shouldDeferOpportunisticReconnect { logger.info("[BLE] ConnectionManager: not re-arming watchdog on foreground (pairing in progress)") @@ -108,10 +103,13 @@ public extension ConnectionManager { /// Activates the connection manager on app launch. /// Call this once during app initialization. func activate() async { + loadTextRules() + // Ensure lifecycle handlers are installed before anything below can // construct the CBCentralManager; creating the central can fire // restoration callbacks synchronously, and a missed handler would // strand the restored link without a session rebuild. + let activationRequestID = desiredRequest?.id await wireTransportHandlers() let lastDeviceShort = lastConnectedDeviceID?.uuidString.prefix(8) ?? "none" @@ -175,7 +173,25 @@ public extension ConnectionManager { logger.error("sortDate reset migration failed: \(error)") } + guard desiredRequest?.id == activationRequestID else { return } + + if desiredRequest != nil { + guard connectionIntent.wantsConnection else { return } + do { + try await pairing.activate() + Task { await resumePendingRadioErases(pairingReady: true) } + } catch { + logger.error("Failed to activate pairing session: \(error.localizedDescription)") + await resumePendingRadioErases(pairingReady: false) + } + guard desiredRequest?.id == activationRequestID else { return } + await checkWiFiConnectionHealth() + await checkBLEConnectionHealth() + return + } + #if targetEnvironment(simulator) + Task { await resumePendingRadioErases(pairingReady: true) } // Skip auto-reconnect if user explicitly disconnected if connectionIntent.isUserDisconnected { logger.info("Simulator: skipping auto-reconnect - user previously disconnected") @@ -200,9 +216,10 @@ public extension ConnectionManager { // ASK events and iOS 26 state restoration. On macOS this is a no-op. do { try await pairing.activate() + Task { await resumePendingRadioErases(pairingReady: true) } } catch { logger.error("Failed to activate pairing session: \(error.localizedDescription)") - // Don't return - WiFi doesn't need the pairing session + await resumePendingRadioErases(pairingReady: false) } // Skip auto-reconnect if user explicitly disconnected @@ -211,670 +228,18 @@ public extension ConnectionManager { return } + guard desiredRequest?.id == activationRequestID else { return } + // Auto-reconnect to last device if available if let lastDeviceID = lastConnectedDeviceID { logger.info("Attempting auto-reconnect to last device: \(lastDeviceID)") connectionIntent = .wantsConnection() let device = try? await persistenceStore.fetchDevice(id: lastDeviceID) + guard desiredRequest?.id == activationRequestID else { return } await reconnectLastUsedTransport(device: device, lastDeviceID: lastDeviceID) } else { logger.info("No last connected device - skipping auto-reconnect") } #endif } - - /// Dials the last-used transport, then the other one when that dial throws. - /// A WiFi-only row stops after a WiFi failure. Restoration, an already-connected radio, adoption, and another app's link do not fall through. - func reconnectLastUsedTransport(device: DeviceDTO?, lastDeviceID: UUID) async { - if case let .wifi(host, port, _) = device?.lastUsedConnectionMethod { - logger.info("Auto-reconnecting via WiFi to \(host):\(port)") - do { - try await connectViaWiFi(host: host, port: port) - return - } catch { - logger.warning("WiFi auto-reconnect failed: \(error.localizedDescription)") - guard device?.bluetoothPeripheralID != nil else { return } - } - } - await reconnectViaBluetooth(device: device, lastDeviceID: lastDeviceID) - } - - private func reconnectViaBluetooth(device: DeviceDTO?, lastDeviceID: UUID) async { - let dialID = device?.bluetoothPeripheralID ?? lastDeviceID - - // Activate BLE before restoration checks. This follows ASK activation and the - // explicit-disconnect guard, and precedes the auto-reconnect and system-link checks. - await stateMachine.activate() - - if await stateMachine.isAutoReconnecting { - let diagnostics = await stateMachine.linkDiagnostics - let blePhase = diagnostics.phase - let blePeripheralState = diagnostics.peripheralState ?? "none" - logger.info( - "State restoration in progress - blePhase: \(blePhase), blePeripheralState: \(blePeripheralState), waiting for auto-reconnect" - ) - return - } - - if await stateMachine.isConnected, await stateMachine.connectedDeviceID == dialID { - logger.info("State restoration complete - device already connected, waiting for session setup") - return - } - - if await startAdoptingLastSystemConnectedPeripheralIfAvailable( - deviceID: dialID, - context: "activate", - requireLastConnected: dialID == lastDeviceID - ) { - return - } - - if await isDeviceConnectedToOtherApp(dialID) { - logger.info("Auto-reconnect skipped: device connected to another app") - let diagnostics = await stateMachine.linkDiagnostics - let bleState = diagnostics.centralState - let blePhase = diagnostics.phase - let blePeripheralState = diagnostics.peripheralState ?? "none" - persistDisconnectDiagnostic( - "source=activate.autoReconnectSkippedOtherApp, " + - "device=\(dialID.uuidString.prefix(8)), " + - "bleState=\(bleState), " + - "blePhase=\(blePhase), " + - "blePeripheralState=\(blePeripheralState), " + - "intent=\(connectionIntent)" - ) - startReconnectionWatchdog() - return - } - - do { - try await connect(to: dialID) - } catch { - logger.warning("Auto-reconnect failed: \(error.localizedDescription)") - let diagnostics = await stateMachine.linkDiagnostics - let bleState = diagnostics.centralState - let blePhase = diagnostics.phase - let blePeripheralState = diagnostics.peripheralState ?? "none" - persistDisconnectDiagnostic( - "source=activate.autoReconnectFailed, " + - "device=\(dialID.uuidString.prefix(8)), " + - "bleState=\(bleState), " + - "blePhase=\(blePhase), " + - "blePeripheralState=\(blePeripheralState), " + - "error=\(error.localizedDescription), " + - "intent=\(connectionIntent)" - ) - if case BLEError.authenticationFailed = error { - surfaceAuthenticationFailure(deviceID: dialID) - } - if case let .wifi(host, port, _) = device?.wifiConnectionMethod { - do { - try await connectViaWiFi(host: host, port: port) - return - } catch { - logger.warning("WiFi fallback after BLE auto-reconnect failed: \(error.localizedDescription)") - } - } - startReconnectionWatchdog() - } - } - - // MARK: - Connection - - /// Connects to a previously paired device. - /// - /// This method handles all connection scenarios: - /// - If disconnected: connects to the device - /// - If already connected to this device: no-op - /// - If connected to a different device: switches to the new device - /// - /// - Parameters: - /// - deviceID: The UUID of the device to connect to - /// - forceFullSync: Whether to force a full sync instead of incremental - /// - forceReconnect: When `true`, marks the connect as user-initiated: it bypasses the - /// circuit breaker, and on a platform without a system pairing registry (macOS) it also - /// bounds the retry budget to `unverifiedConnectAttempts`, so a tap on an out-of-range - /// radio fails fast instead of hanging the full budget. Background reconnects pass - /// `false` to keep the full budget for unattended recovery. - /// - Throws: Connection errors - func connect(to deviceID: UUID, forceFullSync: Bool = false, forceReconnect: Bool = false) async throws { - // Honor cancellation before any state mutation. Without this checkpoint - // a cancelled `pairNewDevice` task whose preceding awaits all swallowed - // cancellation would still drive a real BLE connect to completion. - try Task.checkCancellation() - - if connectionTeardownCount > 0 { - invalidatePowerOffForConnectionChange() - } - try await waitForConnectionTeardown() - - // Circuit breaker: prevent rapid reconnection loops after repeated failures - guard shouldAllowConnection(force: forceReconnect) else { - logger.info("[BLE] Circuit breaker open, rejecting connection to \(deviceID.uuidString.prefix(8))") - throw BLEError.connectionFailed("Connection blocked by circuit breaker (cooling down)") - } - - if connectedDevice?.id != deviceID || connectionState == .disconnected { - invalidatePowerOffForConnectionChange() - } - - if activeReconnectDeviceID == deviceID { - if forceReconnect, connectionState == .disconnected, sessionRebuildDeviceID != deviceID { - await abandonStuckReconnect(deviceID: deviceID) - } else { - connectionIntent = .wantsConnection(forceFullSync: forceFullSync) - persistIntent() - if sessionRebuildDeviceID != deviceID { - reconnectionCoordinator.restartTimeout(deviceID: deviceID) - } - logger.info("[BLE] Reconnect already in progress for \(deviceID.uuidString.prefix(8)), deferring duplicate connect request") - return - } - } - - // Prevent concurrent connection attempts - if connectionState == .connecting { - let currentDeviceID = activeConnectionAttemptDeviceID - - if currentDeviceID == deviceID { - if connectingDeviceID == nil { - // Auto-reconnect same device — refresh UI timeout - connectionIntent = .wantsConnection(forceFullSync: forceFullSync) - persistIntent() - reconnectionCoordinator.restartTimeout(deviceID: deviceID) - } - logger.info("Connection already in progress for \(deviceID.uuidString.prefix(8)), ignoring") - return - } - - // Different device — cancel current and fall through - logger.info("Cancelling connection to \(currentDeviceID?.uuidString.prefix(8) ?? "unknown") to connect to \(deviceID.uuidString.prefix(8))") - connectingDeviceID = nil - reconnectionCoordinator.cancelTimeout() - reconnectionCoordinator.clearReconnectingDevice() - cancelResyncLoop() - stopReconnectionWatchdog() - do { - beginConnectionTeardown() - defer { endConnectionTeardown() } - await cleanupResources() - await transport.disconnect() - connectionState = .disconnected - } - } - - // Handle already-connected cases - if connectionState != .disconnected { - if connectedDevice?.id == deviceID { - logger.info("Already connected to device: \(deviceID)") - return - } - // Connected to different device - switch to new one - logger.info("Switching from current device to: \(deviceID)") - try await switchDevice(to: deviceID) - return - } - - // Claim the attempt before the pre-connect awaits below. Two connect - // calls interleaving at those suspension points would otherwise both - // pass the guards above and build duplicate sessions over one - // transport. The newest claim wins; a superseded call observes the - // mismatch after each await and bails. - if connectingDeviceID == deviceID { - logger.info("Connection already claimed for \(deviceID.uuidString.prefix(8)), ignoring") - return - } - let attemptID = UUID() - connectingAttemptID = attemptID - connectingDeviceID = deviceID - - // Handle state restoration auto-reconnect - let transportAutoReconnecting = await stateMachine.isAutoReconnecting - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw CancellationError() } - if transportAutoReconnecting { - let restoringDeviceID = await stateMachine.connectedDeviceID - let diagnostics = await stateMachine.linkDiagnostics - let blePhase = diagnostics.phase - let blePeripheralState = diagnostics.peripheralState ?? "none" - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw CancellationError() } - - if restoringDeviceID != deviceID { - logger.info("Cancelling state restoration auto-reconnect to \(restoringDeviceID?.uuidString ?? "unknown") to connect to \(deviceID)") - await transport.disconnect() - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw CancellationError() } - } else if forceReconnect, connectionState == .disconnected { - // Reached when the coordinator's reconnect cycle was already cleared while - // the state machine itself is still mid auto-reconnect for this device. - await abandonStuckReconnect( - deviceID: deviceID, - detail: " - blePhase: \(blePhase), blePeripheralState: \(blePeripheralState)" - ) - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw CancellationError() } - } else { - // Same device - let auto-reconnect complete instead of racing with it. - // The reconnection handler will create the session when auto-reconnect succeeds. - // Release the claim: the reconnect cycle owns identity tracking from here. - connectingDeviceID = nil - // Preserve user intent so the watchdog can retry if auto-reconnect fails. - connectionIntent = .wantsConnection(forceFullSync: forceFullSync) - persistIntent() - // Show connecting UI so the user sees their tap did something - if connectionState != .connecting { - connectionState = .connecting - } - // Re-arm timeout in case the previous one already fired - reconnectionCoordinator.restartTimeout(deviceID: deviceID) - logger.warning( - "[BLE] Deferring to iOS auto-reconnect for device \(deviceID.uuidString.prefix(8)) - connectionState: \(String(describing: connectionState)), blePhase: \(blePhase), blePeripheralState: \(blePeripheralState)" - ) - return - } - } - - if try await adoptOrRejectSystemConnectedLink(deviceID: deviceID, attemptID: attemptID, forceFullSync: forceFullSync) { - return - } - - // Clear intentional disconnect flag before changing state, - // so the didSet invariant check sees consistent state - connectionIntent = .wantsConnection(forceFullSync: forceFullSync) - persistIntent() - - // Set connecting state for immediate UI feedback - // (connectingDeviceID was already claimed above) - connectionState = .connecting - - logger.info("Connecting to device: \(deviceID)") - - // Cancel any pending auto-reconnect timeout and clear device identity - reconnectionCoordinator.cancelTimeout() - reconnectionCoordinator.clearReconnectingDevice() - - do { - // Validate device is still registered with the pairing registry. macOS reports - // no active session, so this guard is skipped and CoreBluetooth resolves the device. - if pairing.isSessionActive { - let isConnectable = pairing.isDeviceConnectable(deviceID) - - if !isConnectable { - await logDeviceNotFoundDiagnostics(deviceID: deviceID, context: "connect(to:) paired accessories mismatch") - throw ConnectionError.deviceNotFound - } - } - - // Attempt connection with retry. Without a system pairing registry (macOS), - // CoreBluetooth cannot pre-reject an absent saved peripheral, so a user-initiated - // tap on an out-of-range radio would hang the full retry budget. Bound user taps - // there; background reconnects (forceReconnect == false) keep the full budget so - // unattended recovery still gets every attempt. - let maxAttempts = (forceReconnect && !pairing.hasSystemPairingRegistry) - ? Self.unverifiedConnectAttempts - : Self.defaultConnectAttempts - try await connectWithRetry(deviceID: deviceID, attemptID: attemptID, maxAttempts: maxAttempts) - } catch { - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { - logger.info("Connection to \(deviceID.uuidString.prefix(8)) superseded") - throw error - } - if error is CancellationError { - logger.info("Connection cancelled") - } else { - logger.warning("Connection failed: \(error.localizedDescription)") - } - connectingDeviceID = nil - connectionState = .disconnected - throw error - } - if ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) { - connectingDeviceID = nil - } - } - - /// Adopts leftover GATT this app owns, or throws if another app holds the link. - /// Settings forget clears last-connected; ASK membership or an in-flight pair still marks it ours. - private func adoptOrRejectSystemConnectedLink( - deviceID: UUID, - attemptID: UUID, - forceFullSync: Bool - ) async throws -> Bool { - let ownedLink = isOwnedSystemConnectedLink(deviceID) - if ownedLink { - connectionIntent = .wantsConnection(forceFullSync: forceFullSync) - persistIntent() - - if await startAdoptingLastSystemConnectedPeripheralIfAvailable( - deviceID: deviceID, - context: "connect(to:)", - requireLastConnected: false - ) { - if isPairingInProgress { - do { - try await waitForPairingAdoptionToSettle() - } catch { - if ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) { connectingDeviceID = nil } - throw error - } - } - if ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) { connectingDeviceID = nil } - return true - } - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw CancellationError() } - } - - if await isDeviceConnectedToOtherApp(deviceID), !ownedLink { - if ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) { connectingDeviceID = nil } - throw BLEError.deviceConnectedToOtherApp - } - guard ownsConnectionAttempt(deviceID: deviceID, attemptID: attemptID) else { throw CancellationError() } - return false - } - - /// Break-glass teardown for a user-initiated (`forceReconnect`) connect that found - /// a stuck reconnect: the UI already abandoned the cycle (pill shows "Disconnected") - /// but the OS pending connect never resolved, e.g. the bond was invalidated. - /// Deferring again would restart the same doomed wait forever, so cancel the cycle - /// and tear down the pending connect; the caller falls through to a fresh attempt - /// that surfaces the real CoreBluetooth error instead. - private func abandonStuckReconnect(deviceID: UUID, detail: String = "") async { - logger.warning("[BLE] Break-glass: abandoning stuck reconnect for \(deviceID.uuidString.prefix(8)) to allow a fresh connect attempt\(detail)") - reconnectionCoordinator.cancelTimeout() - reconnectionCoordinator.clearReconnectingDevice() - await transport.disconnect() - } - - /// Disconnects from the current device. - /// - Parameter reason: The reason for disconnecting (for debugging) - func disconnect(reason: DisconnectReason = .userInitiated) async { - if reason != .powerOff { - invalidatePowerOffForConnectionChange() - } - beginConnectionTeardown() - defer { endConnectionTeardown() } - let initialState = String(describing: connectionState) - let transportName = switch currentTransportType { - case .bluetooth: "bluetooth" - case .wifi: "wifi" - case nil: "none" - } - let activeDevice = connectedDevice?.id.uuidString.prefix(8) ?? "none" - - logger.info( - "Disconnecting from device (" + - "reason: \(reason.rawValue), " + - "transport: \(transportName), " + - "device: \(activeDevice), " + - "initialState: \(initialState), " + - "intent: \(connectionIntent)" + - ")" - ) - - // Cancel any pending auto-reconnect timeout and clear device identity - reconnectionCoordinator.cancelTimeout() - reconnectionCoordinator.clearReconnectingDevice() - connectingDeviceID = nil - - // Cancel any WiFi reconnection in progress - cancelWiFiReconnection() - - // Stop WiFi heartbeat - stopWiFiHeartbeat() - - // Stop reconnection watchdog - stopReconnectionWatchdog() - - cancelResyncLoop() - cancelChannelRetry() - - // Only clear user intent and clean-channel state for explicit disconnects. - // Transient reasons preserve both so the next reconnect can skip redundant channel sync. - switch reason { - case .userInitiated, .statusMenuDisconnectTap, .forgetDevice, .deviceRemovedFromSettings, .factoryReset, .switchingDevice, .powerOff: - connectionIntent = .userDisconnected - persistIntent() - surfacedAuthFailureDeviceID = nil - lastCleanChannelSync = nil - lastAttemptedChannelSync = nil - case .resyncFailed, .wifiAddressChange, .wifiReconnectPrep, .bluetoothConnectPrep, .pairingFailed: - // Preserve .wantsConnection so health check can retry - break - } - - // Drop the live stack before the awaits. Callbacks during teardown must see the connection already gone. - let oldServices = services - let oldSession = session - let capturedTransportType = currentTransportType - let capturedWiFi = wifiTransport - services = nil - session = nil - logger.info("[BLE] disconnect: state → .disconnected") - connectionState = .disconnected - connectingDeviceID = nil - connectedDevice = nil - allowedRepeatFreqRanges = [] - - #if DEBUG - await testConnectionTeardownHandler?() - #endif - - if let oldServices { - // Mark room sessions disconnected before tearing down services - _ = await oldServices.remoteNodeService.handleBLEDisconnection() - sessionsAwaitingReauth = [] - await oldServices.tearDown() - // Reset sync state and clear notification suppression (safety net) - await oldServices.syncCoordinator.onDisconnected(notificationService: oldServices.notificationService) - } - - // The manager closes the captured transport after the old receive loop stops. - await oldSession?.stop(disconnectTransport: false) - - // Close the captured transport before releasing replacement connections. - if let capturedWiFi { - await capturedWiFi.disconnect() - if wifiTransport === capturedWiFi { - wifiTransport = nil - } - } else if session == nil, currentTransportType == capturedTransportType { - await transport.disconnect() - } - - if session == nil, currentTransportType == capturedTransportType { - currentTransportType = nil - } - - persistDisconnectDiagnostic( - "source=disconnect(reason), " + - "reason=\(reason.rawValue), " + - "transport=\(transportName), " + - "device=\(activeDevice), " + - "initialState=\(initialState), " + - "finalState=\(String(describing: connectionState)), " + - "intent=\(connectionIntent)" - ) - - logger.info( - "Disconnected (" + - "reason: \(reason.rawValue), " + - "transport: \(transportName), " + - "device: \(activeDevice), " + - "initialState: \(initialState), " + - "finalState: \(String(describing: connectionState)), " + - "intent: \(connectionIntent)" + - ")" - ) - } - - // MARK: - Simulator - - /// Connects to the simulator device with mock data. - /// Used for simulator builds and demo mode on device. - func simulatorConnect() async throws { - invalidatePowerOffForConnectionChange() - try await waitForConnectionTeardown() - logger.info("Starting simulator connection") - - connectionIntent = .wantsConnection() - persistIntent() - connectingDeviceID = MockDataProvider.simulatorDeviceID - connectionState = .connecting - - do { - // Connect simulator mode - await simulatorMode.connect() - - // Create services with a placeholder session - // Note: We need a MeshCoreSession but won't actually use it for communication - // The mock data is seeded directly into the persistence store - let mockTransport = SimulatorMockTransport() - let session = MeshCoreSession(transport: mockTransport) - self.session = session - - // Create services - let newServices = ServiceContainer( - session: session, - dataStore: persistenceStore, - radioID: MockDataProvider.simulatorDeviceID, - appStateProvider: appStateProvider, - connectionStateEvents: connectionStateEvents, - initialConnectionState: connectionState - ) - await wireCleanChannelSyncCallback(on: newServices) - await newServices.chatSendQueueService.hydrate() - services = newServices - - // Seed mock data - try await simulatorMode.seedDataStore(newServices.dataStore) - - // Set connected device - connectedDevice = MockDataProvider.simulatorDevice - - // Persist for auto-reconnect - persistConnection( - deviceID: MockDataProvider.simulatorDeviceID, - radioID: MockDataProvider.simulatorDeviceID, - deviceName: "MeshCore One Sim" - ) - - // Notify observers - await onConnectionReady?() - - connectingDeviceID = nil - connectionState = .ready - // The seeded fixture is the simulator's whole recipient set. - await onDeviceSynced?(true) - logger.info("Simulator connection complete") - } catch { - connectingDeviceID = nil - await cleanupConnection() - throw error - } - } - - // MARK: - Device Switching - - /// Switches to a different device. - /// - /// - Parameter deviceID: UUID of the new device to connect to - func switchDevice(to deviceID: UUID) async throws { - try Task.checkCancellation() - invalidatePowerOffForConnectionChange() - try await waitForConnectionTeardown() - logger.info("Switching to device: \(deviceID)") - lastCleanChannelSync = nil - lastAttemptedChannelSync = nil - - // Update intent - connectionIntent = .wantsConnection() - persistIntent() - - do { - // Validate device is registered with the pairing registry. Skipped on macOS, - // which has no active session; CoreBluetooth resolves the device on connect. - if pairing.isSessionActive { - let isConnectable = pairing.isDeviceConnectable(deviceID) - if !isConnectable { - await logDeviceNotFoundDiagnostics(deviceID: deviceID, context: "switchDevice paired accessories mismatch") - throw ConnectionError.deviceNotFound - } - } - - // Cancel any resync loop from the old device before teardown - cancelResyncLoop() - - // Reset sync state before destroying services to prevent stuck "Syncing" pill - if let services { - await services.syncCoordinator.onDisconnected(notificationService: services.notificationService) - } - - // Stop current services - await services?.tearDown() - // tearDown above cancelled the old container's connection-state - // subscription; nilling drops the dead reference before the - // connect ceremony installs its replacement. - services = nil - await session?.stop() - await stateMachine.setAppSessionLive(deviceID: nil) - - // Switch transport - logger.info("[BLE] switchDevice: state → .connecting for device: \(deviceID.uuidString.prefix(8))") - connectionState = .connecting - try await transport.switchDevice(to: deviceID) - logger.info("[BLE] switchDevice: state → .connected for device: \(deviceID.uuidString.prefix(8))") - connectionState = .connected - - // Re-create session with existing transport - let newSession = MeshCoreSession(transport: transport) - session = newSession - - let (meshCoreSelfInfo, deviceCapabilities) = try await initializeSession(newSession) - - // Session traffic flowed over the encrypted UART link, so the bond is - // proven healthy as of now. Also marks the app session live for RSSI refresh. - await recordBondVerification(deviceID: deviceID) - - // Configure BLE write pacing based on device platform - await configureBLEPacing(for: deviceCapabilities) - - let (newServices, radioID) = try await buildServicesAndSaveDevice( - deviceID: deviceID, - session: newSession, - selfInfo: meshCoreSelfInfo, - capabilities: deviceCapabilities, - connectionMethods: Self.bleConnectionMethods(for: deviceID) - ) - - // Persist connection for auto-reconnect - persistConnection(deviceID: deviceID, radioID: radioID, deviceName: meshCoreSelfInfo.name) - - // Notify observers before sync starts so they can wire callbacks - await onConnectionReady?() - let syncResult = await performInitialSync(radioID: radioID, services: newServices, context: "Device switch", forceFullSync: true) - - guard await promoteToReady(syncResult: syncResult, expectedServices: newServices, transportType: .bluetooth) else { return } - - // Refill the rebuild-preserve budget so a spent counter on radio A cannot - // force radio B's first rebuild failure to sever. - resetPreserveBudgetAfterDeviceSwitch() - stopReconnectionWatchdog() - logger.info("Device switch complete - device ready") - } catch { - // Without this, a partial switch would leave services, session, and - // connectedDevice pointing at the old device with state stuck on - // .connecting or .connected. pairNewDevice routes through here when - // an old radio is still connected, so the failure alert's recovery - // actions need clean state. - do { - beginConnectionTeardown() - defer { endConnectionTeardown() } - await cleanupConnection() - await transport.disconnect() - } - // cleanupConnection tore down the session without firing onConnectionLost, - // so observers (and the radio's Live Activity) would otherwise be stranded - // on the old device's "connected" state. Route through the same callback the - // transport-loss and reconnect-failure paths use. - await onConnectionLost?() - throw error - } - } } diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+NotificationTesting.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+NotificationTesting.swift new file mode 100644 index 0000000000..6663b259f7 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+NotificationTesting.swift @@ -0,0 +1,10 @@ +extension ConnectionManager { + func notificationServiceForTesting() -> NotificationService? { + #if DEBUG + if let testNotificationSystemOperations { + return NotificationService(notificationDefaults: .standard, systemOperations: testNotificationSystemOperations) + } + #endif + return nil + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Pairing.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Pairing.swift index 00255f6186..0140b9f74e 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Pairing.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Pairing.swift @@ -4,109 +4,89 @@ import MeshCore // MARK: - Pairing public extension ConnectionManager { - /// Discovers a new device through the platform pairing service (AccessorySetupKit on - /// iOS, an in-app CoreBluetooth scan picker on macOS), then connects through the shared - /// `connect(to:)` ceremony. The connect path coordinates with in-flight auto-reconnects, - /// switch-device handling, and the circuit breaker, which `connectAfterPairing`'s direct - /// `performConnection` call used to bypass. - /// - /// **Cancellation behavior** (per `await`): - /// - `pairing.discoverDevice()` — `withTaskCancellationHandler` resumes the - /// continuation with `CancellationError`. On iOS the system picker may stay visible - /// (no public ASK API to dismiss programmatically without invalidating the - /// session); if the user completes pairing in the orphaned picker, - /// `accessoryAdded` removes the bond immediately. The device is not registered - /// when this point is reached, so no cleanup needed here. - /// - `waitForOtherAppReconnection` — checks `Task.isCancelled` at the top of - /// each iteration and short-circuits to `false`. A system-connected result - /// proceeds to `connect(to:)` rather than throwing other-app. Cancellation - /// is surfaced at `connect(to:)`'s entry-point `Task.checkCancellation()`. - /// - `connect(to:)` — runs `Task.checkCancellation()` before any state mutation - /// so a cancelled task cannot drive a real BLE connect through to success. - /// Leftover GATT this app owns is adopted; while pairing, that path waits - /// until `isOperational` or throws. Propagates `CancellationError` normally; - /// we catch it explicitly and re-throw without re-wrapping so the UI alert - /// path stays quiet. - /// - /// Hard quit: process death; defer doesn't fire; the in-memory flag resets to - /// `false` on next launch. No persistent state corruption. - /// - /// - Throws: - /// - `DevicePairingError.alreadyInProgress` on re-entry. - /// - `PairingError.deviceConnectedToOtherApp` when another app holds the radio. - /// - `PairingError.connectionFailed` for any other connection failure (auth, - /// timeout, transport error). The wrapped `underlying` is checked by - /// `PairingError.isAuthenticationFailure` so the auth alert path keeps working. - /// - `CancellationError` if the surrounding task is cancelled mid-flight. - func pairNewDevice() async throws { - logger.info("Starting device pairing") - guard !isPairingInProgress else { - throw DevicePairingError.alreadyInProgress - } + /// The request `pairNewDevice()` has already admitted. Nil during the picker, + /// so cancelling discovery does not drop a radio that is already connected. + var admittedPairingRequestID: UUID? { + guard isPairingInProgress, let request = desiredRequest, request.origin == .pairing else { return nil } + return request.id + } + + /// Pairs through the platform picker, then joins the admitted connection request. + @discardableResult + func pairNewDevice() async throws -> ConnectionResult { + guard !isPairingInProgress else { throw DevicePairingError.alreadyInProgress } + let operationID = UUID() + let observedRequestID = desiredRequest?.id + pairingOperationID = operationID isPairingInProgress = true - defer { isPairingInProgress = false } - - connectionIntent = .wantsConnection() - persistIntent() - + defer { + if pairingOperationID == operationID { isPairingInProgress = false; pairingOperationID = nil } + } await stopBLEScanning() - - // ASK's picker is empty until the session is active. try await pairing.activate() - + try Task.checkCancellation() + guard desiredRequest?.id == observedRequestID else { return .superseded } let deviceID = try await pairing.discoverDevice() - - // ASK has just associated this radio. A leftover system GATT link is ours - // (or the accessory we just set up); `connect(to:)` adopts or connects. - if await waitForOtherAppReconnection(deviceID) { - logger.info( - "[OtherAppCheck] System-connected after pairing \(deviceID.uuidString.prefix(8)); connecting" - ) - } - + guard desiredRequest?.id == observedRequestID, pairingOperationID == operationID else { return .superseded } + var handoffRequestID: UUID? do { - try await connect(to: deviceID, forceFullSync: true, forceReconnect: true) - } catch BLEError.deviceConnectedToOtherApp { - // No `cleanupPartialPairing` here — the bond is good; the user retries - // after dismissing the other app via the otherAppWarningDeviceID alert. - // Removing the bond would force a fresh pair instead. - throw PairingError.deviceConnectedToOtherApp(deviceID: deviceID) + _ = await waitForOtherAppReconnection(deviceID) + try Task.checkCancellation() + guard desiredRequest?.id == observedRequestID else { return .superseded } + let result = try await requestConnection( + targets: [.bluetooth(deviceID)], origin: .pairing, forceFullSync: true, forceReconnect: true + ) + switch result { + case .operational: return result + case let .handoff(requestID): + handoffRequestID = requestID + try await waitForPairingAdoptionToSettle(expectedRequestID: requestID) + guard let snapshot = currentConnection, snapshot.requestID == requestID else { return .superseded } + return .operational(snapshot) + case .cancelled: + if let request = desiredRequest, request.target == .bluetooth(deviceID), installedLink == nil { + await cleanupPartialPairing(deviceID: deviceID, requestID: request.id) + } + return .cancelled + case .superseded: return .superseded + } + } catch let failure as ConnectionRequestFailure { + guard isCurrent(failure) else { return .superseded } + let pairingError: PairingError = if case BLEError.deviceConnectedToOtherApp = failure.underlying { + .deviceConnectedToOtherApp(deviceID: deviceID) + } else { + .connectionFailed(deviceID: deviceID, underlying: failure.underlying) + } + throw ConnectionRequestFailure(requestID: failure.requestID, underlying: pairingError) } catch is CancellationError { - await cleanupPartialPairing(deviceID: deviceID) - throw CancellationError() + let ownerID = handoffRequestID ?? observedRequestID + await cleanupPartialPairing(deviceID: deviceID, requestID: ownerID) + return .cancelled } catch { - // Edge case: a domain error bubbled up while the surrounding task was - // also cancelled. Without this guard the user sees "Couldn't connect" - // instead of silent cancellation. Re-throw as CancellationError so the - // alert path doesn't fire. - if Task.isCancelled { - await cleanupPartialPairing(deviceID: deviceID) - throw CancellationError() - } - logger.error("Connection after pairing failed: \(error.localizedDescription)") - throw PairingError.connectionFailed(deviceID: deviceID, underlying: error) + guard let requestID = handoffRequestID, desiredRequest?.id == requestID else { throw error } + throw ConnectionRequestFailure( + requestID: requestID, underlying: PairingError.connectionFailed(deviceID: deviceID, underlying: error) + ) } } - /// Removes a partially-paired device from the system registry when pairing is cancelled - /// mid-flight before a usable connection exists. On iOS the system has the device; we don't. - /// Without this cleanup, iOS retains a paired bond with no app-level state, surfacing as a - /// phantom device in Settings → Bluetooth that won't show up in the picker again. No-op on macOS. - private func cleanupPartialPairing(deviceID: UUID) async { - logger.info("Removing partially-paired device \(deviceID.uuidString.prefix(8)) from pairing registry") - try? await pairing.removeDevice(deviceID) - reconnectionCoordinator.cancelTimeout() - reconnectionCoordinator.clearReconnectingDevice() - await transport.disconnect() - // Defensive backstop — connectWithRetry and switchDevice both reset state - // on throw, so this is normally a no-op. Kept so a future cancellation - // path that lands here without doing so still leaves a clean UI. - connectionState = .disconnected + private func cleanupPartialPairing(deviceID: UUID, requestID: UUID?) async { + let cleanup = Task { @MainActor in + guard self.desiredRequest?.id == requestID, self.connectedDevice?.id != deviceID else { return } + let admitted = self.desiredRequest?.target == .bluetooth(deviceID) + guard !admitted || self.installedLink == nil else { return } + let device = try? await self.persistenceStore.fetchDevice(id: deviceID) + let context = ConnectionRemovalContext(deviceID: deviceID, device: device, requestID: requestID, generation: nil) + _ = try? await self.removeDevice( + context, policy: .bluetoothAssociation(pairingFailed: false), reason: .pairingFailed, systemPolicy: .required + ) + } + await cleanup.value } - /// Pairing leftover-GATT wait. `.syncing` already has a session - /// (`promoteToReady` with a non-usable result); `.connected` is still rebuilding. - func waitForPairingAdoptionToSettle() async throws { + /// Pairing waits for the admitted request's operational stack; physical + /// `.connected` alone does not authorize completion. + func waitForPairingAdoptionToSettle(expectedRequestID: UUID) async throws { #if DEBUG if let strategy = pairingAdoptionSettleStrategyOverride { try await strategy() @@ -124,6 +104,7 @@ public extension ConnectionManager { while true { try Task.checkCancellation() + guard desiredRequest?.id == expectedRequestID else { throw CancellationError() } if connectionState.isOperational { guard services != nil else { throw BLEError.connectionFailed(Self.pairingAdoptionMissingSessionDetail) @@ -174,52 +155,14 @@ public extension ConnectionManager { } } - /// Removes a device that failed to connect after pairing, for the guided - /// "remove and retry" recovery. Demotes the row to a ghost rather than deleting - /// it, preserving the publicKey ↔ radioID bridge: an established radio that lost - /// its bond re-pairs onto the same radioID and its contacts, messages, and - /// channels reattach. A fresh pairing has no row to demote, so this is a no-op there. - /// - Parameter deviceID: The device ID from `PairingError.connectionFailed` - func removeFailedPairing(deviceID: UUID) async { - logger.info("Removing failed pairing for device: \(deviceID)") - - await transport.disconnect() - - do { - try await pairing.removeDevice(deviceID) - } catch { - logger.warning("Failed to remove from pairing registry: \(error.localizedDescription)") - } - - if await retainedWiFiRowAfterBluetoothRemoval(peripheralID: deviceID) != nil { - return - } - - let dataStore = persistenceStore - try? await dataStore.demoteDeviceToGhost(id: deviceID) - - // Always clear this device's bond verification; store keys are holder-matched. - await clearPersistedConnection(for: deviceID) - } - - /// Clears bond verification, then strips Bluetooth when the row also has WiFi. - /// Nil means the caller should ghost or delete and clear the last-connection slot. - private func retainedWiFiRowAfterBluetoothRemoval(peripheralID: UUID) async -> DeviceDTO? { - await clearBondVerification(for: peripheralID) - do { - guard let kept = try await persistenceStore.removeBluetoothMethod(peripheralID: peripheralID) else { - return nil - } - if connectedDevice?.id == kept.id { - connectedDevice = kept - } - return kept - } catch { - logger.warning( - "Failed to remove Bluetooth method for \(peripheralID.uuidString.prefix(8)): \(error.localizedDescription)" - ) - return nil - } + /// Removes the failed Bluetooth association while retaining its radio partition. + @discardableResult + func removeFailedPairing(deviceID: UUID) async throws -> ConnectionRemovalResult { + let context = try await captureRemoval(id: deviceID) + return try await removeDevice( + context, policy: .bluetoothAssociation(pairingFailed: false), + reason: .forgetDevice, systemPolicy: .required + ) } // MARK: - Other-App Detection @@ -267,64 +210,25 @@ public extension ConnectionManager { // MARK: - Forget Device - /// Forgets the device, removing it from paired accessories and local storage. - /// - Parameter deleteData: If `true`, also deletes all associated data (contacts, messages, channels, trace paths). - /// - Throws: `ConnectionError.notConnected` if no device is connected - func forgetDevice(deleteData: Bool) async throws { - guard let deviceID = connectedDevice?.id else { - throw ConnectionError.notConnected - } - - guard pairing.isDeviceConnectable(deviceID) else { - throw ConnectionError.deviceNotFound - } - - logger.info("Forgetting device: \(deviceID), deleteData: \(deleteData)") - - try await pairing.removeDevice(deviceID) - await disconnect(reason: .forgetDevice) - - let dataStore = persistenceStore - do { - if deleteData { - try await dataStore.deleteDeviceAndData(id: deviceID) - } else { - try await dataStore.demoteDeviceToGhost(id: deviceID) - } - } catch { - logger.warning("Failed to demote device in SwiftData: \(error.localizedDescription)") + @discardableResult + func forgetDevice(_ context: ConnectionRemovalContext, deleteData: Bool) async throws -> ConnectionRemovalResult { + if !deleteData { + return try await removeDevice( + context, policy: .wholeDevice(deleteData: false), reason: .forgetDevice, systemPolicy: .required + ) } - - await clearPersistedConnection(for: deviceID) - logger.info("Device forgotten") - } - - /// Forgets a device by ID, removing it from paired accessories and local storage. - /// Deletes both the device record and all associated data (factory reset path). - /// Best-effort cleanup — does not throw. - func forgetDevice(id: UUID) async { - logger.info("Forgetting device by ID: \(id)") - - await disconnect(reason: .factoryReset) - - do { - try await pairing.removeDevice(id) - } catch { - logger.warning("Failed to remove device from pairing registry: \(error.localizedDescription)") + guard ownsRemovalSource(context) else { return .superseded } + let device = if let connectedDevice, context.identity.matches(ConnectionDeviceIdentity(connectedDevice)) { + connectedDevice + } else { + try await resolveRemovalDevice(context.identity, store: persistenceStore) } - - let dataStore = persistenceStore + guard let device, ownsRemovalSource(context) else { return .superseded } do { - try await dataStore.deleteDeviceAndData(id: id) - } catch { - logger.warning("Failed to delete device data from SwiftData: \(error.localizedDescription)") + return try await startRadioErase(device, context: context) + } catch DevicePairingError.cancelled { + return .cancelled } - - // Always clear this device's bond verification; store keys are holder-matched - // so a non-last-connected forget still drops its in-memory/persistent shield. - await clearPersistedConnection(for: id) - - logger.info("Device forgotten by ID: \(id)") } // MARK: - Node Management @@ -464,332 +368,6 @@ public extension ConnectionManager { logger.info("Stale pairings cleared") } - // MARK: - Device Updates - - /// Updates the connected device with new settings from SelfInfo. - /// Called by SettingsService after device settings are successfully changed. - /// Also persists to SwiftData so changes appear in Connect Device sheet. - func updateDevice(from selfInfo: MeshCore.SelfInfo, appliedRadioPresetID: String?) { - guard let device = connectedDevice else { return } - var updated = device.updating(from: selfInfo) - if let appliedRadioPresetID { - updated.appliedRadioPresetID = appliedRadioPresetID - } else if !device.clientRepeat { - // Drop a stale catalog id only when live RF no longer matches it. Repeat Mode - // keeps the id so restore can still paint the community name. - let matches = RadioPresets.matchingPresets( - frequencyKHz: updated.frequency, - bandwidthKHz: updated.bandwidth, - spreadingFactor: updated.spreadingFactor, - codingRate: updated.codingRate - ) - if let current = updated.appliedRadioPresetID, - !matches.contains(where: { $0.id == current }) { - updated.appliedRadioPresetID = nil - } - } - connectedDevice = updated - let radioID = updated.radioID - Task { - let store = services?.dataStore - try? await store?.updateDeviceNodeName(radioID: radioID, name: updated.nodeName) - try? await store?.updateDeviceCoordinates( - radioID: radioID, - latitude: updated.latitude, - longitude: updated.longitude - ) - try? await store?.updateDeviceRadio( - radioID: radioID, - frequency: updated.frequency, - bandwidth: updated.bandwidth, - spreadingFactor: updated.spreadingFactor, - codingRate: updated.codingRate, - appliedRadioPresetID: updated.appliedRadioPresetID - ) - try? await store?.updateDeviceTxPower(radioID: radioID, txPower: updated.txPower) - try? await store?.updateDeviceOtherParams( - radioID: radioID, - intent: OtherParamsIntent( - manualAddContacts: updated.manualAddContacts, - telemetryModeBase: updated.telemetryModeBase, - telemetryModeLocation: updated.telemetryModeLoc, - telemetryModeEnvironment: updated.telemetryModeEnv, - advertisementLocationPolicy: updated.advertLocationPolicy, - multiAcks: updated.multiAcks - ) - ) - } - } - - /// Persists one refresh onto the existing row, then publishes it on the live device. - /// A missing row is left missing. A replaced producer does not update a successor. - func applyDeviceObservation(_ info: MeshCore.SelfInfo, from producer: ServiceContainer) async { - guard services === producer, let device = connectedDevice else { return } - let radio = NodeConfigService.buildRadioSettings(from: info) - var mapped = device.updating(from: info) - mapped.frequency = radio.frequency - mapped.bandwidth = radio.bandwidth - mapped.spreadingFactor = radio.spreadingFactor - mapped.codingRate = radio.codingRate - mapped.txPower = radio.txPower - mapped.appliedRadioPresetID = catalogID( - for: SettingsEvent.RadioChange( - frequencyKHz: radio.frequency, - bandwidthHz: radio.bandwidth, - spreadingFactor: radio.spreadingFactor, - codingRate: radio.codingRate, - catalogStamp: .reconcile - ), - on: device - ) - let snapshotID = device.id - let radioID = device.radioID - let store = producer.dataStore - do { - try await store.updateDeviceObservation(radioID: radioID, mapped: mapped) - } catch { - logger.error("Failed to persist device observation: \(error.localizedDescription)") - return - } - // The row write used the captured radio. Live state updates only if that device is still current. - guard services === producer, let current = connectedDevice, current.id == snapshotID else { return } - connectedDevice = current.applyingRefresh(mapped) - } - - func applyNodeName(_ name: String) async { - guard let device = connectedDevice else { return } - connectedDevice = device.copy { $0.nodeName = name } - try? await services?.dataStore.updateDeviceNodeName(radioID: device.radioID, name: name) - } - - func applyCoordinates(latitude: Double, longitude: Double) async { - guard let device = connectedDevice else { return } - connectedDevice = device.copy { - $0.latitude = latitude - $0.longitude = longitude - } - try? await services?.dataStore.updateDeviceCoordinates( - radioID: device.radioID, - latitude: latitude, - longitude: longitude - ) - } - - func applyRadio(_ change: SettingsEvent.RadioChange) async { - guard let device = connectedDevice else { return } - let presetID = catalogID(for: change, on: device) - connectedDevice = device.copy { - $0.frequency = change.frequencyKHz - $0.bandwidth = change.bandwidthHz - $0.spreadingFactor = change.spreadingFactor - $0.codingRate = change.codingRate - $0.appliedRadioPresetID = presetID - } - try? await services?.dataStore.updateDeviceRadio( - radioID: device.radioID, - frequency: change.frequencyKHz, - bandwidth: change.bandwidthHz, - spreadingFactor: change.spreadingFactor, - codingRate: change.codingRate, - appliedRadioPresetID: presetID - ) - } - - func applyTxPower(_ power: Int8) async { - guard let device = connectedDevice else { return } - connectedDevice = device.copy { $0.txPower = power } - try? await services?.dataStore.updateDeviceTxPower(radioID: device.radioID, txPower: power) - } - - func applyOtherParams(_ intent: OtherParamsIntent) async { - guard let device = connectedDevice else { return } - connectedDevice = device.copy { - if let manualAddContacts = intent.manualAddContacts { - $0.manualAddContacts = manualAddContacts - } - if let telemetryModeBase = intent.telemetryModeBase { - $0.telemetryModeBase = telemetryModeBase - } - if let telemetryModeLocation = intent.telemetryModeLocation { - $0.telemetryModeLoc = telemetryModeLocation - } - if let telemetryModeEnvironment = intent.telemetryModeEnvironment { - $0.telemetryModeEnv = telemetryModeEnvironment - } - if let advertisementLocationPolicy = intent.advertisementLocationPolicy { - $0.advertLocationPolicy = advertisementLocationPolicy - } - if let multiAcks = intent.multiAcks { - $0.multiAcks = multiAcks - } - } - try? await services?.dataStore.updateDeviceOtherParams(radioID: device.radioID, intent: intent) - } - - private func catalogID(for change: SettingsEvent.RadioChange, on device: DeviceDTO) -> String? { - switch change.catalogStamp { - case let .set(id): - return id - case .reconcile: - if device.clientRepeat { return device.appliedRadioPresetID } - let matches = RadioPresets.matchingPresets( - frequencyKHz: change.frequencyKHz, - bandwidthKHz: change.bandwidthHz, - spreadingFactor: change.spreadingFactor, - codingRate: change.codingRate - ) - if let current = device.appliedRadioPresetID, matches.contains(where: { $0.id == current }) { - return current - } - return nil - } - } - - /// Updates the connected device with a new DeviceDTO. - /// Called by DeviceService after local device settings are successfully changed. - func updateDevice(with deviceDTO: DeviceDTO) { - connectedDevice = deviceDTO - } - - /// Updates the connected device's auto-add config. - /// Called by SettingsService after auto-add config is successfully changed. - func updateAutoAddConfig(_ config: MeshCore.AutoAddConfig) { - guard let device = connectedDevice else { return } - let updated = device.copy { - $0.autoAddConfig = config.bitmask - $0.autoAddMaxHops = config.maxHops - } - connectedDevice = updated - - Task { - do { - try await services?.dataStore.updateDeviceAutoAdd( - radioID: updated.radioID, - config: config.bitmask, - maxHops: config.maxHops - ) - } catch { - logger.error("Failed to persist auto-add config: \(error)") - } - } - } - - /// Updates the connected device's client repeat state. - /// Called by SettingsService after client repeat is successfully changed. - func updateClientRepeat(_ enabled: Bool) { - guard let device = connectedDevice else { return } - let updated = device.copy { $0.clientRepeat = enabled } - connectedDevice = updated - - Task { - do { - try await services?.dataStore.updateDeviceClientRepeat(radioID: updated.radioID, enabled: enabled) - } catch { - logger.error("Failed to persist client repeat state: \(error)") - } - } - } - - /// Updates the connected device's path hash mode. - /// Called by SettingsService after path hash mode is successfully changed. - func updatePathHashMode(_ mode: UInt8) { - guard let device = connectedDevice else { return } - let updated = device.copy { $0.pathHashMode = mode } - connectedDevice = updated - - Task { - do { - try await services?.dataStore.updateDevicePathHashMode(radioID: updated.radioID, mode: mode) - } catch { - logger.error("Failed to persist path hash mode: \(error)") - } - } - } - - /// Updates the connected device's cached default flood scope name. - /// Called by SettingsService after a `getDefaultFloodScope` read or a successful write. - func updateDefaultFloodScopeName(_ name: String?) { - guard let device = connectedDevice else { return } - let updated = device.copy { $0.defaultFloodScopeName = name } - connectedDevice = updated - - Task { - do { - try await services?.dataStore.updateDeviceDefaultFloodScopeName(radioID: updated.radioID, name: name) - } catch { - logger.error("Failed to persist default flood scope: \(error)") - } - } - } - - /// Appends a region to the connected device's known-regions list and persists. - /// No-ops if the region is already present. - func addKnownRegion(_ region: String) { - guard let device = connectedDevice, - !device.knownRegions.contains(region) else { return } - let updated = device.copy { $0.knownRegions.append(region) } - connectedDevice = updated - Task { - do { try await services?.dataStore.addDeviceKnownRegion(radioID: updated.radioID, region: region) } catch { logger.error("Failed to add known region: \(error)") } - await services?.rxLogService.updateKnownRegions(updated.knownRegions) - } - } - - /// Removes a region from the connected device's known-regions list and persists. - /// If the removed region is the device's current default flood scope, also clears - /// the scope on the radio so firmware state doesn't dangle on a deleted name. - func removeKnownRegion(_ region: String) { - guard let device = connectedDevice else { return } - let wasDefaultFloodScope = device.defaultFloodScopeName == region - let updated = device.copy { - $0.knownRegions.removeAll { $0 == region } - if wasDefaultFloodScope { - $0.defaultFloodScopeName = nil - } - } - connectedDevice = updated - Task { - do { - try await services?.dataStore.removeDeviceKnownRegion(radioID: updated.radioID, region: region) - } catch { - logger.error("Failed to remove known region: \(error)") - } - - if wasDefaultFloodScope, let settingsService = services?.settingsService { - do { - _ = try await settingsService.setDefaultFloodScopeVerified(name: nil) - } catch { - logger.error("Failed to clear default flood scope after region removal: \(error)") - } - } - - await services?.rxLogService.updateKnownRegions(updated.knownRegions) - } - } - - /// Saves the connected device's current radio settings as pre-repeat settings. - /// Called before enabling repeat mode so settings can be restored later. - func savePreRepeatSettings() { - guard let device = connectedDevice else { return } - let updated = device.savingPreRepeatSettings() - connectedDevice = updated - - Task { - do { try await services?.dataStore.saveDevice(updated) } catch { logger.error("Failed to persist pre-repeat settings: \(error)") } - } - } - - /// Clears the connected device's pre-repeat settings after restoration. - func clearPreRepeatSettings() { - guard let device = connectedDevice else { return } - let updated = device.clearingPreRepeatSettings() - connectedDevice = updated - - Task { - do { try await services?.dataStore.saveDevice(updated) } catch { logger.error("Failed to persist cleared pre-repeat settings: \(error)") } - } - } - // MARK: - Accessory Management /// Checks if a device is registered with the system pairing registry. @@ -809,38 +387,13 @@ public extension ConnectionManager { return devices } - /// Forgets the system pairing registry entry (no-op if unregistered), then demotes the row to a ghost. - /// Declining iOS Remove Accessory throws `DevicePairingError.cancelled` and leaves the row listed. - /// - Parameter id: The device UUID to forget + /// Removes the confirmed subject while preserving its radio partition as a Ghost. func deleteDevice(id: UUID) async throws { - logger.info("deleteDevice called for device: \(id)") - - // Snapshot before removeDevice: ASK can drop BLE, then handleConnectionLoss - // nils connectedDevice while wantsConnection stays. - let shouldTearDownSession = - connectedDevice?.id == id || activeConnectionAttemptDeviceID == id - if shouldTearDownSession { - isPairingFlowActive = true - } - defer { - if shouldTearDownSession { - isPairingFlowActive = false - } - } - - try await pairing.removeDevice(id) - if shouldTearDownSession { - await disconnect(reason: .forgetDevice) - } - - let dataStore = persistenceStore - try await dataStore.demoteDeviceToGhost(id: id) - - // Always clear this device's bond verification; store keys are holder-matched - // so a non-last-connected delete still drops its shield. - await clearPersistedConnection(for: id) - - logger.info("deleteDevice completed for device: \(id)") + let context = try await captureRemoval(id: id) + let result = try await removeDevice( + context, policy: .wholeDevice(deleteData: false), reason: .forgetDevice, systemPolicy: .required + ) + if case .cancelled = result { throw DevicePairingError.cancelled } } /// Returns devices registered with the system pairing registry (AccessorySetupKit on iOS). @@ -868,78 +421,40 @@ public extension ConnectionManager { // MARK: - DevicePairingDelegate extension ConnectionManager: DevicePairingDelegate { - public func devicePairing( - _ service: any DevicePairingService, - didRemoveDeviceWithID bluetoothID: UUID - ) { - logger.info("Device removed from pairing registry: \(bluetoothID)") - - // DevicePairingDelegate is non-async, so bond clear cannot be awaited at the - // callback signature. Ordered first in the Task so it runs before reconnect- - // adjacent work; residual race with concurrent classify is accepted here. - Task { - let disconnectBluetoothSession = connectedDevice?.id == bluetoothID && wifiTransport == nil - - // iOS can fire accessoryRemoved while session.accessories still lists the - // id. Ghosting then turns a still-authorized radio into a Set Up leftover - // that blocks Scan. Keep the Device row so Connect still works. - if pairing.isDeviceConnectable(bluetoothID) { - await clearPersistedConnection(for: bluetoothID) - if disconnectBluetoothSession { - await disconnect(reason: .deviceRemovedFromSettings) - } - logger.info( - "ASK still lists \(bluetoothID.uuidString.prefix(8)) after removal; keeping Device row" - ) - return - } + public func devicePairing(_ service: any DevicePairingService, didRemoveDeviceWithID bluetoothID: UUID) { + guard !isRemovingPairing(bluetoothID) else { return } + handleRegistryRemoval(bluetoothID, pairingFailed: false) + } - let keptWiFi = await retainedWiFiRowAfterBluetoothRemoval(peripheralID: bluetoothID) != nil - if disconnectBluetoothSession { - await disconnect(reason: .deviceRemovedFromSettings) - } - if keptWiFi { - return - } + public func devicePairing(_ service: any DevicePairingService, didFailPairingForDeviceWithID bluetoothID: UUID) { + guard !isRemovingPairing(bluetoothID) else { return } + handleRegistryRemoval(bluetoothID, pairingFailed: true) + } - await clearPersistedConnection(for: bluetoothID) - let dataStore = persistenceStore - do { - try await dataStore.demoteDeviceToGhost(id: bluetoothID) - } catch { - logger.warning("Failed to demote device in SwiftData: \(error.localizedDescription)") - } + private func isRemovingPairing(_ bluetoothID: UUID) -> Bool { + removalDeviceID == bluetoothID || radioCleanup.values.contains { + $0.target.pairingID == bluetoothID && radioEraseTasks[$0.target.radioID] != nil } } - public func devicePairing( - _ service: any DevicePairingService, - didFailPairingForDeviceWithID bluetoothID: UUID - ) { - // Clean up device record so the device can appear in picker again. - // No data cascade — failed pairings have no associated data. - logger.info("Pairing failed for device: \(bluetoothID)") - - // DevicePairingDelegate is non-async; bond clear is ordered first in the Task. - Task { - let disconnectBluetoothSession = connectedDevice?.id == bluetoothID && wifiTransport == nil - let keptWiFi = await retainedWiFiRowAfterBluetoothRemoval(peripheralID: bluetoothID) != nil - if disconnectBluetoothSession { - await disconnect(reason: .pairingFailed) - } - if keptWiFi { - return - } - - await clearPersistedConnection(for: bluetoothID) - - // Delete device record only — no data exists for a failed pairing - let dataStore = persistenceStore - do { - try await dataStore.deleteDevice(id: bluetoothID) - logger.info("Deleted device record after failed pairing") - } catch { - logger.info("No device record to delete: \(error.localizedDescription)") + private func handleRegistryRemoval(_ id: UUID, pairingFailed: Bool) { + let identity: ConnectionDeviceIdentity = if let device = connectedDevice, device.id == id { + ConnectionDeviceIdentity(device) + } else if let attempt = desiredRequest?.attempt, attempt.identity.deviceID == id { + attempt.identity + } else { + ConnectionDeviceIdentity(deviceID: id) + } + let context = ConnectionRemovalContext( + deviceID: id, identity: identity, requestID: desiredRequest?.id, generation: installedLink?.generation + ) + let work = startRemoval( + context, policy: .bluetoothAssociation(pairingFailed: pairingFailed), + reason: pairingFailed ? .pairingFailed : .deviceRemovedFromSettings, sourceIsCurrent: true + ) + Task { @MainActor in + if case let .failure(error) = await work.result { + self.logger.warning("Association removal failed: \(error.localizedDescription)") } } } diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+PowerOff.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+PowerOff.swift index 48c4e36776..03ef634a4b 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+PowerOff.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+PowerOff.swift @@ -142,7 +142,7 @@ extension ConnectionManager { powerOffCancelGeneration &+= 1 guard resumeReconnect, !operation.invalidated else { return } guard connectionIntent.wantsConnection else { return } - if currentTransportType == .wifi, connectionState == .connecting { + if desiredRequest?.target.transportType == .wifi, connectionState == .connecting { if !isHandlingWiFiDisconnection { startWiFiReconnection() } diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Preparation.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Preparation.swift new file mode 100644 index 0000000000..e48bf94cc7 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Preparation.swift @@ -0,0 +1,294 @@ +import Foundation +import MeshCore + +extension ConnectionManager { + struct PreparedConnection: Sendable { + let services: ServiceContainer + let device: DeviceDTO + let repeatRanges: [MeshCore.FrequencyRange] + } + + func enqueueMetadata( + _ operation: @escaping @MainActor @Sendable (PersistenceStore) async throws -> T + ) -> Task { + let predecessor = metadataCommitTask + let store = persistenceStore + let work = Task { + await predecessor?.value + return try await operation(store) + } + metadataCommitTask = Task { _ = await work.result } + return work + } + + func prepareConnection( + _ request: ConnectionRequest, + attempt: ConnectionAttempt, + resource: ConnectionResource, + selfInfo: SelfInfo, + capabilities: DeviceCapabilities + ) async throws -> PreparedConnection { + attempt.identity.publicKey = selfInfo.publicKey + try requireAttemptOwnership(request, attempt) + var deviceID: UUID = if let bluetoothID = attempt.target.deviceID { + bluetoothID + } else { + await wifiDeviceID(publicKey: selfInfo.publicKey) + } + try requireAttemptOwnership(request, attempt) + let byID = try await persistenceStore.fetchDevice(id: deviceID) + try requireAttemptOwnership(request, attempt) + let existing: DeviceDTO? = if let byID { byID } else { try await persistenceStore.fetchDevice(publicKey: selfInfo.publicKey) } + attempt.identity.deviceID = existing?.id ?? deviceID + attempt.identity.radioID = existing?.radioID + try requireAttemptOwnership(request, attempt) + let reconciled = try await reconcilePendingIdentity( + request: request, attempt: attempt, deviceID: deviceID, selfInfo: selfInfo + ) + try requireAttemptOwnership(request, attempt) + if reconciled, attempt.target.transportType == .wifi { + deviceID = await wifiDeviceID(publicKey: selfInfo.publicKey) + try requireAttemptOwnership(request, attempt) + } + let canonicalExisting = try await persistenceStore.fetchDevice(id: deviceID) + attempt.identity.deviceID = canonicalExisting?.id ?? deviceID + attempt.identity.radioID = canonicalExisting?.radioID ?? existing?.radioID + try requireAttemptOwnership(request, attempt) + let config = await (try? resource.session.getAutoAddConfig()) ?? AutoAddConfig(bitmask: 0) + try requireAttemptOwnership(request, attempt) + let observation = DeviceDTO(from: createDevice( + deviceID: deviceID, radioID: canonicalExisting?.radioID ?? existing?.radioID ?? UUID(), selfInfo: selfInfo, + capabilities: capabilities, autoAddConfig: config, existingDevice: canonicalExisting ?? existing + )) + let bluetoothPeripheralID = attempt.target.deviceID + let registration = enqueueMetadata { store in + let device = try await store.registerConnectionDevice(observation, bluetoothPeripheralID: bluetoothPeripheralID) + try await store.backfillTextRulesIdentities(radioID: device.radioID) + return device + } + let device = try await registration.value + attempt.identity = ConnectionDeviceIdentity(device) + try requireAttemptOwnership(request, attempt) + if membershipBatch?.radioID != device.radioID { membershipBatch = nil } + let ranges = await capabilities.clientRepeat ? ((try? resource.session.getRepeatFreq()) ?? []) : [] + try requireAttemptOwnership(request, attempt) + let container = try await buildServiceContainer( + request, attempt: attempt, resource: resource, device: device + ) + return PreparedConnection(services: container, device: device, repeatRanges: ranges) + } + + func buildServiceContainer( + _ request: ConnectionRequest, + attempt: ConnectionAttempt, + resource: ConnectionResource, + device: DeviceDTO + ) async throws -> ServiceContainer { + let wifiState = radioWiFiState(for: device.radioID) + wifiState.openAdmission() + let container = ServiceContainer( + session: resource.session, dataStore: persistenceStore, radioID: device.radioID, + appStateProvider: appStateProvider, connectionStateEvents: connectionStateEvents, + initialConnectionState: .connected, radioWiFiState: wifiState, + notificationService: notificationServiceForTesting(), ackEvents: attempt.ackEvents, + textRulesPreference: { [weak self] in await self?.textRulesPreference } + ) + attempt.preparedServices = container + await wireCleanChannelSyncCallback(on: container) + try requireAttemptOwnership(request, attempt) + await container.nodeConfigService.setIdentityImportHandler { [weak self, weak container] key in + guard let self, let container else { throw CancellationError() } + return try await self.importIdentity(key, expectedServices: container, deviceID: device.id) + } + try requireAttemptOwnership(request, attempt) + try await container.warmUp() + try requireAttemptOwnership(request, attempt) + return container + } + + func commitConnection( + _ request: ConnectionRequest, + attempt: ConnectionAttempt, + link: ConnectionLink, + repeatRanges: [MeshCore.FrequencyRange] + ) async throws { + try requireAttemptOwnership(request, attempt) + let id = link.device.id + let method = link.target.method + let selection = enqueueMetadata { store in + #if DEBUG + try await self.testConnectionSelectionHandler?(request.id) + #endif + return try await store.selectConnectionDevice(id: id, method: method) + } + link.device = try await selection.value + try requireAttemptOwnership(request, attempt) + persistConnection(deviceID: id, radioID: link.device.radioID, deviceName: link.device.nodeName) + try publish(link, repeatRanges: repeatRanges) + request.committedGeneration = link.generation + attempt.resource = nil + attempt.preparedServices = nil + } + + // MARK: - Session Helpers + + private static let sessionInitializationTimeout: Duration = .seconds(10) + + private static let floodScopeBaselineMinimumFirmwareVersion: UInt8 = 8 + + /// Starts a session and queries device capabilities. + func initializeSession( + _ session: MeshCoreSession, + attempt: ConnectionAttempt? = nil + ) async throws -> (SelfInfo, DeviceCapabilities) { + if let attempt { + attempt.ackEvents = await session.events(filter: .anyAcknowledgement) + } + do { + try await withTimeout(Self.sessionInitializationTimeout, operationName: "session.start") { + try await session.start(disconnectTransportOnFailure: false) + } + } catch { + logger.warning("[BLE] session.start() timed out or failed: \(error.localizedDescription)") + throw error + } + + guard let selfInfo = await session.currentSelfInfo else { + logger.warning("[BLE] selfInfo is nil after session.start()") + throw ConnectionError.initializationFailed("Failed to get device self info") + } + if let attempt { + attempt.identity.publicKey = selfInfo.publicKey + guard let request = desiredRequest else { throw CancellationError() } + try requireAttemptOwnership(request, attempt) + } + let capabilities: DeviceCapabilities + do { + capabilities = try await withTimeout(Self.sessionInitializationTimeout, operationName: "queryDevice") { + try await session.queryDevice() + } + } catch { + logger.warning("[BLE] queryDevice() timed out or failed: \(error.localizedDescription)") + throw error + } + if let attempt { + guard let request = desiredRequest else { throw CancellationError() } + try requireAttemptOwnership(request, attempt) + } + // Clear an override left by a previous connection before publishing the session. + if capabilities.firmwareVersion >= Self.floodScopeBaselineMinimumFirmwareVersion { + do { + try await withTimeout(Self.sessionInitializationTimeout, operationName: "floodScopeBaseline") { + try await session.setFloodScope(scopeKey: FloodScope.disabled.scopeKey()) + } + } catch { + logger.warning("[BLE] flood scope baseline timed out or failed: \(error.localizedDescription)") + throw error + } + if let attempt { + guard let request = desiredRequest else { throw CancellationError() } + try requireAttemptOwnership(request, attempt) + } + } + return (selfInfo, capabilities) + } + + // MARK: - Service Wiring Helpers + + /// Records clean channel sync completion for the next connection's sync policy. + func wireCleanChannelSyncCallback(on services: ServiceContainer) async { + await services.syncCoordinator.setCleanChannelSyncCallback { [weak self, weak services] radioID in + await MainActor.run { + guard let self, let services, self.services === services, + self.connectedDevice?.radioID == radioID else { return } + self.lastCleanChannelSync = (radioID: radioID, completedAt: Date()) + } + } + await services.syncCoordinator.setChannelSyncAttemptedCallback { [weak self, weak services] radioID in + await MainActor.run { + guard let self, let services, self.services === services, + self.connectedDevice?.radioID == radioID else { return } + self.lastAttemptedChannelSync = (radioID: radioID, attemptedAt: Date()) + } + } + } + + /// Uses the same resolved Radio ID as `ServiceContainer` so persisted Device and + /// `PendingSend` rows share a partition, including on first pair. + func createDevice( + deviceID: UUID, + radioID: UUID, + selfInfo: MeshCore.SelfInfo, + capabilities: MeshCore.DeviceCapabilities, + autoAddConfig: MeshCore.AutoAddConfig, + existingDevice: DeviceDTO? = nil, + connectionMethods: [ConnectionMethod] = [] + ) -> Device { + // Merge new connection methods with existing ones, replacing by transport type + var mergedMethods = ConnectionMethod.canonicalized(existingDevice?.connectionMethods ?? []) + for method in connectionMethods { + if method.isWiFi { + mergedMethods.removeAll { $0.isWiFi } + } else if method.isBluetooth { + mergedMethods.removeAll { $0.isBluetooth } + } + mergedMethods.append(method) + } + + let device = Device( + id: deviceID, + radioID: radioID, + publicKey: selfInfo.publicKey, + nodeName: selfInfo.name, + firmwareVersion: capabilities.firmwareVersion, + firmwareVersionString: capabilities.version, + manufacturerName: capabilities.model, + buildDate: capabilities.firmwareBuild, + maxContacts: UInt16(capabilities.maxContacts), + maxChannels: UInt8(min(capabilities.maxChannels, 255)), + frequency: UInt32(selfInfo.radioFrequency * 1000), // Convert MHz to kHz + bandwidth: UInt32(selfInfo.radioBandwidth * 1000), // Convert kHz to Hz + spreadingFactor: selfInfo.radioSpreadingFactor, + codingRate: selfInfo.radioCodingRate, + txPower: selfInfo.txPower, + maxTxPower: selfInfo.maxTxPower, + latitude: selfInfo.latitude, + longitude: selfInfo.longitude, + blePin: capabilities.blePin, + clientRepeat: capabilities.clientRepeat, + pathHashMode: capabilities.pathHashMode, + defaultFloodScopeName: existingDevice?.defaultFloodScopeName, + preRepeatFrequency: existingDevice?.preRepeatFrequency, + preRepeatBandwidth: existingDevice?.preRepeatBandwidth, + preRepeatSpreadingFactor: existingDevice?.preRepeatSpreadingFactor, + preRepeatCodingRate: existingDevice?.preRepeatCodingRate, + manualAddContacts: selfInfo.manualAddContacts, + autoAddConfig: autoAddConfig.bitmask, + autoAddMaxHops: autoAddConfig.maxHops, + multiAcks: selfInfo.multiAcks, + telemetryModeBase: selfInfo.telemetryModeBase, + telemetryModeLoc: selfInfo.telemetryModeLocation, + telemetryModeEnv: selfInfo.telemetryModeEnvironment, + advertLocationPolicy: selfInfo.advertisementLocationPolicy, + lastConnected: Date(), + lastContactSync: existingDevice?.lastContactSync ?? 0, + isActive: true, + ocvPreset: existingDevice?.ocvPreset + ?? OCVPreset.preset(forManufacturer: capabilities.model)?.rawValue, + appliedRadioPresetID: existingDevice?.appliedRadioPresetID, + customOCVArrayString: existingDevice?.customOCVArrayString, + connectionMethods: mergedMethods, + knownRegions: existingDevice?.knownRegions ?? [] + ) + + // If repeat mode was disabled externally, clear orphaned pre-repeat settings + if !capabilities.clientRepeat, existingDevice?.preRepeatFrequency != nil { + device.preRepeatFrequency = nil + device.preRepeatBandwidth = nil + device.preRepeatSpreadingFactor = nil + device.preRepeatCodingRate = nil + } + + return device + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Presentation.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Presentation.swift new file mode 100644 index 0000000000..59498ab32c --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Presentation.swift @@ -0,0 +1,36 @@ +import Foundation + +public extension ConnectionManager { + var connectionActivity: ConnectionActivity? { + guard connectionIntent.wantsConnection, let request = desiredRequest, + request.target != .disconnected else { return nil } + let recovering = request.handedOff || request.committedGeneration != nil || request.origin == .recovery + let phase: ConnectionActivity.Phase = switch connectionState { + case .disconnected: .waitingToReconnect + case .connecting: recovering ? .reconnecting : .connecting + case .connected: .connected + case .syncing: .syncing + case .ready: .ready + } + return ConnectionActivity(requestID: request.id, targetName: connectionTargetName(request), phase: phase) + } + + @discardableResult + func disconnect(requestID: UUID, reason: DisconnectReason = .userInitiated) async -> ConnectionLossReceipt? { + guard let request = desiredRequest, request.id == requestID, connectionIntent.wantsConnection, + request.target != .disconnected else { return nil } + return await disconnect(reason: reason) + } + + private func connectionTargetName(_ request: ConnectionRequest) -> String? { + if let link = installedLink, link.requestID == request.id { return link.device.nodeName } + switch request.target { + case let .bluetooth(deviceID): + if lastConnectedDeviceID == deviceID, let name = lastConnectedDeviceName { return name } + return pairedAccessoryInfos.first { $0.id == deviceID }?.name + case let .wifi(host, _): return host + case .simulator: return MockDataProvider.simulatorDevice.nodeName + case .disconnected: return nil + } + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+RadioErase.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+RadioErase.swift new file mode 100644 index 0000000000..fbdd9f7c4b --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+RadioErase.swift @@ -0,0 +1,221 @@ +import Foundation + +public extension ConnectionManager { + struct RadioCleanup: Identifiable, Sendable { + public enum State: Sendable { + case running + case failed + case completed + } + + public let target: PendingRadioEraseDTO + public var state: State + public var id: UUID { + target.radioID + } + } + + func factoryResetAndEraseRadio(_ context: ConnectionRemovalContext) async throws -> ConnectionRemovalResult { + guard ownsRemovalSource(context), let device = connectedDevice, let settings = services?.settingsService, + context.identity.matches(ConnectionDeviceIdentity(device)) else { return .superseded } + return try await startRadioErase(device, context: context, resetWith: settings) + } + + func retryRadioErase(_ target: PendingRadioEraseDTO) { + guard radioEraseTasks[target.radioID] == nil else { return } + beginRadioEraseTask(radioID: target.radioID) { [self] in + guard try await persistenceStore.isRadioErasePending(target.radioID) else { return .superseded } + let context = ConnectionRemovalContext( + deviceID: target.deviceID, identity: .init(deviceID: target.deviceID, radioID: target.radioID), + requestID: desiredRequest?.id, generation: installedLink?.generation + ) + return try await finishRadioErase(target, context: context) + } + } +} + +extension ConnectionManager { + @discardableResult + func startRadioErase( + _ device: DeviceDTO, context: ConnectionRemovalContext? = nil, resetWith settings: SettingsService? = nil + ) async throws -> ConnectionRemovalResult { + let context = context ?? ConnectionRemovalContext( + deviceID: device.id, device: device, requestID: desiredRequest?.id, generation: installedLink?.generation + ) + guard ownsRemovalSource(context) else { return .superseded } + if let running = radioEraseTasks[device.radioID] { + return try await running.value + } + let task = beginRadioEraseTask(radioID: device.radioID) { [self] in + guard ownsRemovalSource(context) else { return .superseded } + let alreadyPending = try await persistenceStore.isRadioErasePending(device.radioID) + guard ownsRemovalSource(context) else { return .superseded } + let poller = connectedDevice?.radioID == device.radioID ? services?.messagePollingService : nil + do { + try await poller?.suspendForRadioErase() + } catch { + guard ownsRemovalSource(context) else { return .superseded } + throw error + } + + let record: Task = enqueueMetadata { store in + guard self.ownsRemovalSource(context), + self.connectedDevice?.radioID != device.radioID || self.services?.messagePollingService === poller else { return nil } + return try await store.beginRadioErase(device, isFactoryReset: settings != nil) + } + let target: PendingRadioEraseDTO? + do { + target = try await record.value + } catch { + if services?.messagePollingService === poller { await poller?.resumeAfterRadioErase() } + guard ownsRemovalSource(context) else { return .superseded } + throw error + } + guard let target else { + if services?.messagePollingService === poller { await poller?.resumeAfterRadioErase() } + return .superseded + } + radioCleanup[target.radioID] = .init(target: target, state: .running) + if let settings, !alreadyPending { + let canSubmitReset = ownsRemovalSource(context) && services?.settingsService === settings + if canSubmitReset { + // The radio usually reboots before it can acknowledge the command. + do { + try await settings.factoryReset() + try await Task.sleep(for: Self.factoryResetRebootGracePeriod) + } catch { + logger.info("Factory reset response interrupted: \(error.localizedDescription)") + } + } + // An admitted recovery owns the next Link record while the old reset settles. + let recoveryOwnsRequest = installedLink == nil && reconnectionCoordinator.currentCycle.map { + $0.requestID == context.requestID + } == true + if !canSubmitReset || !ownsRemovalSource(context) || recoveryOwnsRequest { + do { + try await persistenceStore.cancelRadioErase(radioID: target.radioID) + radioCleanup[target.radioID] = nil + if services?.messagePollingService === poller { await poller?.resumeAfterRadioErase() } + } catch { + radioCleanup[target.radioID]?.state = .failed + logger.warning("Failed to roll back superseded reset cleanup: \(error.localizedDescription)") + } + return .superseded + } + } + return try await finishRadioErase(target, context: context) + } + return try await task.value + } + + func resumePendingRadioErases(pairingReady: Bool) async { + do { + for target in try await persistenceStore.fetchPendingRadioErases() { + if pairingReady { + retryRadioErase(target) + _ = await radioEraseTasks[target.radioID]?.result + } else { + radioCleanup[target.radioID] = .init(target: target, state: .failed) + } + } + } catch { + logger.error("Failed to read pending radio cleanup: \(error.localizedDescription)") + } + } + + @discardableResult + private func beginRadioEraseTask( + radioID: UUID, + operation: @escaping @MainActor () async throws -> ConnectionRemovalResult + ) -> Task { + let task = Task { [self] in + defer { radioEraseTasks[radioID] = nil } + return try await operation() + } + radioEraseTasks[radioID] = task + return task + } + + private func finishRadioErase( + _ target: PendingRadioEraseDTO, context: ConnectionRemovalContext + ) async throws -> ConnectionRemovalResult { + radioCleanup[target.radioID] = .init(target: target, state: .running) + let operationID = UUID() + if ownsRemovalSource(context), removalMatchesCurrent(context, policy: .wholeDevice(deleteData: true)) { + removalOperationID = operationID + removalDeviceID = target.pairingID + } + defer { + if removalOperationID == operationID { removalOperationID = nil; removalDeviceID = nil } + } + + do { + #if canImport(UIKit) && !targetEnvironment(simulator) + if pairing.hasSystemPairingRegistry, !pairing.isSessionActive { + try await pairing.activate() + guard pairing.isSessionActive else { throw AccessorySetupKitError.sessionNotActive } + } + #endif + do { + try await pairing.removeDevice(target.pairingID) + } catch DevicePairingError.cancelled where target.isFactoryReset == false { + try await persistenceStore.cancelRadioErase(radioID: target.radioID) + radioCleanup[target.radioID] = nil + if connectedDevice?.radioID == target.radioID { + await services?.messagePollingService.resumeAfterRadioErase() + } + throw DevicePairingError.cancelled + } + } catch { + if radioCleanup[target.radioID] != nil { radioCleanup[target.radioID]?.state = .failed } + guard ownsRemovalSource(context) else { return .superseded } + throw error + } + + let sourceIsCurrent = ownsRemovalSource(context) + if sourceIsCurrent, let request = desiredRequest, !request.removedIdentities.contains(context.identity) { + request.removedIdentities.append(context.identity) + } + let terminal = if sourceIsCurrent, + removalMatchesCurrent(context, policy: .wholeDevice(deleteData: true)) || + desiredRequest?.target.deviceID == target.pairingID { + beginDisconnect(reason: target.isFactoryReset == true ? .factoryReset : .forgetDevice) + } else { + nil as (barrier: ConnectionRetirement, receipt: ConnectionLossReceipt)? + } + let writerDrain = retirementTask + let notifyingRequestID = terminal?.receipt.requestID ?? context.requestID + let cleanup = enqueueMetadata { store -> Bool in + await writerDrain?.value + let sourceStillCurrent = terminal.map { self.isCurrent($0.receipt) } ?? self.ownsRemovalSource(context) + let sourceWasSuperseded = !sourceIsCurrent || !sourceStillCurrent + if sourceWasSuperseded, self.pairing.hasSystemPairingRegistry, self.pairing.isDeviceConnectable(target.pairingID) { + try await store.cancelRadioErase(radioID: target.radioID) + return false + } + await self.clearPersistedConnection(for: target.deviceID, notifyingRequestID: notifyingRequestID) + try await store.completeRadioErase(radioID: target.radioID) + return true + } + do { + guard try await cleanup.value else { + radioCleanup[target.radioID] = nil + return .superseded + } + radioCleanup[target.radioID]?.state = .completed + guard let terminal, isCurrent(terminal.receipt) else { return .superseded } + await onConnectionLost?(terminal.receipt) + return .removed(terminal.receipt) + } catch { + radioCleanup[target.radioID]?.state = .failed + if let terminal { + guard isCurrent(terminal.receipt) else { return .superseded } + } else { + guard ownsRemovalSource(context) else { return .superseded } + } + throw error + } + } + + private static let factoryResetRebootGracePeriod: Duration = .seconds(1) +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+RadioWiFiState.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+RadioWiFiState.swift new file mode 100644 index 0000000000..217739d715 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+RadioWiFiState.swift @@ -0,0 +1,38 @@ +import Foundation + +extension ConnectionManager { + public func radioWiFiState(for radioID: UUID) -> RadioWiFiState { + if let existing = radioWiFiStates[radioID] { return existing } + let state = RadioWiFiState(radioID: radioID) + radioWiFiStates[radioID] = state + return state + } + + func transferRadioWiFiEvidence(from previousID: UUID, to canonicalID: UUID) async { + let previous = radioWiFiState(for: previousID) + let canonical = radioWiFiState(for: canonicalID) + previous.closeAdmission() + canonical.closeAdmission() + await previous.waitForMutationSettlement() + if canonical !== previous { await canonical.waitForMutationSettlement() } + canonical.adoptCanonicalEvidence(rebootPending: previous.rebootPending) + if canonical !== previous, radioWiFiStates[previousID] === previous { radioWiFiStates[previousID] = nil } + } + + func cancelExpectedWiFiReboots() { + for state in radioWiFiStates.values { + state.cancelExpectedReboot() + } + } + + func revalidateExpectedWiFiReboot(_ link: ConnectionLink) async { + let settings = link.services.settingsService + let state = settings.radioWiFiState + guard owns(link), connectionState == .ready, + let candidate = state.expectedRebootID else { return } + await settings.confirmExpectedRadioWiFiReboot(id: candidate, expectedRadioID: link.device.radioID) { [weak self] in + guard let self else { return false } + return self.owns(link) && self.connectionState == .ready + } + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Removal.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Removal.swift new file mode 100644 index 0000000000..946cb1f804 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Removal.swift @@ -0,0 +1,166 @@ +import Foundation + +extension ConnectionManager { + enum RemovalPolicy { + case wholeDevice(deleteData: Bool) + case bluetoothAssociation(pairingFailed: Bool) + } + + enum SystemRemovalPolicy { + case required + case bestEffort + } + + public func captureCurrentRemoval() -> ConnectionRemovalContext? { + guard let device = connectedDevice else { return nil } + return ConnectionRemovalContext( + deviceID: device.id, device: device, requestID: desiredRequest?.id, generation: installedLink?.generation + ) + } + + func captureRemoval(id: UUID) async throws -> ConnectionRemovalContext { + let requestID = desiredRequest?.id + let generation = installedLink?.generation + let device = try await persistenceStore.fetchDevice(id: id) + return ConnectionRemovalContext(deviceID: id, device: device, requestID: requestID, generation: generation) + } + + @discardableResult + func removeDevice( + _ context: ConnectionRemovalContext, + policy: RemovalPolicy, + reason: DisconnectReason, + systemPolicy: SystemRemovalPolicy + ) async throws -> ConnectionRemovalResult { + guard ownsRemovalSource(context) else { return .superseded } + let operationID = UUID() + removalOperationID = operationID + removalDeviceID = context.deviceID + defer { + if removalOperationID == operationID { removalOperationID = nil; removalDeviceID = nil } + } + do { + switch systemPolicy { + case .required: + try await pairing.removeDevice(context.deviceID) + case .bestEffort: + try? await pairing.removeDevice(context.deviceID) + } + } catch DevicePairingError.cancelled { + return .cancelled + } catch { + guard ownsRemoval(context, operationID: operationID) else { return .superseded } + throw error + } + return try await startRemoval( + context, policy: policy, reason: reason, + sourceIsCurrent: ownsRemoval(context, operationID: operationID) + ).value + } + + private func ownsRemoval(_ context: ConnectionRemovalContext, operationID: UUID) -> Bool { + removalOperationID == operationID && ownsRemovalSource(context) + } + + func ownsRemovalSource(_ context: ConnectionRemovalContext) -> Bool { + desiredRequest?.id == context.requestID + && (context.generation == nil || desiredRequest?.committedGeneration == context.generation) + } + + func startRemoval( + _ context: ConnectionRemovalContext, + policy: RemovalPolicy, + reason: DisconnectReason, + sourceIsCurrent: Bool + ) -> Task { + let sourceLink = installedLink + let affectsConnection = removalMatchesCurrent(context, policy: policy) + if sourceIsCurrent, case .wholeDevice = policy, let request = desiredRequest, + !request.removedIdentities.contains(context.identity) { + request.removedIdentities.append(context.identity) + } + let terminal = sourceIsCurrent && affectsConnection ? beginDisconnect(reason: reason) : nil + // Captured here, including when confirmation arrives after the Link is already detached. + // deleteData waits for this task; a nil task is already drained. Later retirement is not consulted. + let admittedWriterDrain: Task? = if case .wholeDevice(deleteData: true) = policy { retirementTask } else { nil } + let notifyOwnerID = terminal?.receipt.requestID ?? context.requestID + let metadata: Task = enqueueMetadata { store in + await admittedWriterDrain?.value + // A newer pairing of the same handle owns its new association and row. + if !sourceIsCurrent, self.pairing.isDeviceConnectable(context.deviceID) { return nil } + if !sourceIsCurrent, self.removalMatchesCurrent(context, policy: .wholeDevice(deleteData: false)) { + let kept = try await store.removeBluetoothMethod(peripheralID: context.deviceID) + await self.clearBondVerification(for: context.deviceID) + return kept + } + switch policy { + case let .wholeDevice(deleteData): + if let current = try await self.resolveRemovalDevice(context.identity, store: store) { + if deleteData { try await store.deleteDeviceAndData(id: current.id) } else { + try await store.demoteDeviceToGhost(id: current.id) + } + await self.clearPersistedConnection(for: current.id, notifyingRequestID: notifyOwnerID) + } + await self.clearPersistedConnection(for: context.deviceID, notifyingRequestID: notifyOwnerID) + case let .bluetoothAssociation(pairingFailed): + if self.pairing.hasSystemPairingRegistry, self.pairing.isDeviceConnectable(context.deviceID) { + await self.clearPersistedConnection(for: context.deviceID, notifyingRequestID: notifyOwnerID) + return nil + } + if let kept = try await store.removeBluetoothMethod(peripheralID: context.deviceID) { + await self.clearBondVerification(for: context.deviceID) + return kept + } + if let current = try await self.resolveRemovalDevice(context.identity, store: store) { + if pairingFailed { try await store.deleteDevice(id: current.id) } else { + try await store.demoteDeviceToGhost(id: current.id) + } + } + await self.clearPersistedConnection(for: context.deviceID, notifyingRequestID: notifyOwnerID) + } + return nil + } + return Task { @MainActor in + await terminal?.barrier.value + let kept: DeviceDTO? + do { + kept = try await metadata.value + } catch { + if let terminal { + guard self.isCurrent(terminal.receipt) else { return .superseded } + } else { + guard self.ownsRemovalSource(context) else { return .superseded } + } + throw error + } + if let kept, let sourceLink, self.installedLink === sourceLink, self.owns(sourceLink), + sourceLink.device.id == kept.id { + self.setPublishedDevice(kept) + } + guard let terminal, self.isCurrent(terminal.receipt) else { return .superseded } + await self.onConnectionLost?(terminal.receipt) + return .removed(terminal.receipt) + } + } + + func removalMatchesCurrent(_ context: ConnectionRemovalContext, policy: RemovalPolicy) -> Bool { + switch policy { + case .wholeDevice: + if let device = connectedDevice, context.identity.matches(ConnectionDeviceIdentity(device)) { return true } + if let attempt = desiredRequest?.attempt, context.identity.matches(attempt.identity) { return true } + return desiredRequest?.target.deviceID == context.deviceID + case .bluetoothAssociation: + return desiredRequest?.target == .bluetooth(context.deviceID) + || (currentTransportType == .bluetooth && connectedDevice?.id == context.deviceID) + } + } + + func resolveRemovalDevice( + _ identity: ConnectionDeviceIdentity, store: PersistenceStore + ) async throws -> DeviceDTO? { + if let id = identity.deviceID, let device = try await store.fetchDevice(id: id) { return device } + if let radioID = identity.radioID, let device = try await store.fetchDevice(radioID: radioID) { return device } + if let key = identity.publicKey { return try await store.fetchDevice(publicKey: key) } + return nil + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Requests.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Requests.swift new file mode 100644 index 0000000000..3f11f764a1 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Requests.swift @@ -0,0 +1,349 @@ +import Foundation +import MeshCore + +private enum AdmissionWorkerInstallation { + @TaskLocal static var isActive = false +} + +extension ConnectionManager { + public var connectionRequestID: UUID? { + desiredRequest?.id + } + + public func isCurrent(_ failure: ConnectionRequestFailure) -> Bool { + desiredRequest?.id == failure.requestID + } + + func owns(_ request: ConnectionRequest) -> Bool { + desiredRequest === request + } + + func requireOwnership(_ request: ConnectionRequest) throws { + do { + try Task.checkCancellation() + } catch { + logLifecycle("admissionRejected", context: lifecycleContext(request: request, attempt: request.attempt, link: nil), reason: "cancelledCaller") + throw error + } + guard owns(request) else { + logLifecycle("admissionRejected", context: lifecycleContext(request: request, attempt: request.attempt, link: nil), reason: "supersededRequest") + throw CancellationError() + } + } + + func requireAttemptOwnership(_ request: ConnectionRequest, _ attempt: ConnectionAttempt) throws { + // Admission follows this task, the current request, and this attempt. + try requireOwnership(request) + guard request.attempt === attempt else { + logLifecycle("admissionRejected", context: lifecycleContext(request: request, attempt: attempt, link: nil), reason: "supersededAttempt") + throw CancellationError() + } + if request.removedIdentities.contains(where: { $0.matches(attempt.identity) }) { + logLifecycle("admissionRejected", context: lifecycleContext(request: request, attempt: attempt, link: nil), reason: "removedIdentity") + _ = beginDisconnect(reason: .forgetDevice) + throw CancellationError() + } + } + + func requestConnection( + targets: [ConnectionRequest.Target], + origin: ConnectionRequest.Origin, + forceFullSync: Bool, + forceReconnect: Bool, + operation: (@MainActor @Sendable (ConnectionRequest) async throws -> ConnectionResult)? = nil + ) async throws -> ConnectionResult { + try Task.checkCancellation() + if let link = installedLink, targets.first == link.target, !forceReconnect, !forceFullSync, + connectionState.isOperational { + return .operational(link.snapshot) + } + // Forced recovery replaces the session even while its BLE rebuild still owns the cycle. + let forceRecovery = origin == .recovery && forceReconnect + if !forceRecovery, + let request = desiredRequest, request.target == targets.first, + let cycle = reconnectionCoordinator.currentCycle, cycle.requestID == request.id, + !forceReconnect || connectionState != .disconnected || reconnectionCoordinator.isRebuilding(cycle) { + if connectionState == .connecting, !reconnectionCoordinator.isRebuilding(cycle) { + reconnectionCoordinator.restartTimeout(deviceID: cycle.deviceID) + } + return .handoff(requestID: request.id) + } + if origin == .explicit || origin == .pairing, + case let .bluetooth(deviceID) = targets.first, + pairing.isSessionActive, !pairing.isDeviceConnectable(deviceID) { + throw ConnectionError.deviceNotFound + } + let previous = desiredRequest + let request = ConnectionRequest( + targets: targets, origin: origin, forceFullSync: forceFullSync, forceReconnect: forceReconnect, + continuing: origin == .recovery || origin == .launch ? previous : nil + ) + if origin == .explicit || origin == .pairing { cancelExpectedWiFiReboots() } + desiredRequest = request + logLifecycle("admitted", context: lifecycleContext(request: request, attempt: nil, link: nil)) + invalidatePowerOffForConnectionChange() + previous?.binding?.revoke() + previous?.worker?.cancel() + reconnectionCoordinator.cancelTimeout() + reconnectionCoordinator.clear() + stopReconnectionWatchdog() + cancelWiFiReconnection() + connectionIntent = .wantsConnection(forceFullSync: forceFullSync) + persistIntent() + let keepMembership = origin == .recovery || targets.first?.transportType == .wifi || installedLink.map { link in + targets.contains(link.target) || targets.contains { target in + target.deviceID == link.device.id || target.method == link.device.wifiConnectionMethod + } + } ?? false + if !keepMembership { membershipBatch = nil } + let barrier = beginOwnedRetirement( + previousRequest: previous, phase: .connecting, closePhysical: true, retainMembership: keepMembership + ) + let worker = Task { @MainActor in + try await AdmissionWorkerInstallation.$isActive.withValue(true) { + // Ownership first so a superseded worker cannot publish into its successor. + // A current cancellation joins this admission's retirement, then uses the ordinary outcome. + guard self.owns(request) else { return ConnectionResult.superseded } + if Task.isCancelled { + await barrier.value + return await self.settleCurrentCancellation(request) + } + await barrier.value + guard self.owns(request) else { return ConnectionResult.superseded } + if Task.isCancelled { + return await self.settleCurrentCancellation(request) + } + await self.metadataCommitTask?.value + guard self.owns(request) else { return ConnectionResult.superseded } + if Task.isCancelled { + return await self.settleCurrentCancellation(request) + } + if let operation { return try await operation(request) } + return try await self.runConnectionRequest(request) + } + } + request.worker = worker + return try await withTaskCancellationHandler { + let result = try await worker.value + if Task.isCancelled { return .cancelled } + return result + } onCancel: { + Task { @MainActor [weak self] in + guard let self, self.owns(request), request.committedGeneration == nil else { return } + request.worker?.cancel() + #if DEBUG + self.testAdmissionCancellationFinished = false + await self.testAdmissionCancellationHandler?() + #endif + guard self.owns(request), request.committedGeneration == nil else { return } + request.admissionBinding?.revoke() + #if DEBUG + self.testAdmissionCancellationFinished = true + #endif + } + } + } + + func installAttempt(_ attempt: ConnectionAttempt, on request: ConnectionRequest, ownedByAdmissionWorker: Bool) { + request.attempt = attempt + if ownedByAdmissionWorker { + request.admissionBinding = attempt.binding + } + } + + private func runConnectionRequest(_ request: ConnectionRequest) async throws -> ConnectionResult { + var lastError: any Error = ConnectionError.deviceNotFound + var lastBluetoothError: (any Error)? + for index in request.targets.indices { + request.targetIndex = index + do { + try requireOwnership(request) + if request.target == .simulator { return try await establishSimulator(request) } + if case let .bluetooth(deviceID) = request.target, + try await handOffBluetoothIfNeeded(request, deviceID: deviceID) { + return .handoff(requestID: request.id) + } + let count = request.target.transportType == .bluetooth + ? ((request.forceReconnect && !pairing.hasSystemPairingRegistry) ? Self.unverifiedConnectAttempts : Self.defaultConnectAttempts) + : 1 + for attempt in 1...count { + do { + return try await establishAttempt(request, preservePhysicalBLE: false) + } catch { + lastError = error + if let failure = error as? ConnectionRequestFailure { throw failure } + guard owns(request) else { return .superseded } + if request.handedOff { return .handoff(requestID: request.id) } + try requireOwnership(request) + if isTerminalConnectError(error) || attempt == count { throw error } + let delay = Self.connectRetryBaseDelay * pow(2, Double(attempt - 1)) + try await Task.sleep(for: .seconds(delay)) + } + } + } catch { + lastError = error + if let failure = error as? ConnectionRequestFailure { throw failure } + guard owns(request) else { return .superseded } + if request.handedOff { return .handoff(requestID: request.id) } + if error is CancellationError || Task.isCancelled { + return await settleCurrentCancellation(request) + } + if case .bluetooth = request.target { lastBluetoothError = error } + } + } + guard owns(request) else { return .superseded } + if let lastBluetoothError { + switch lastBluetoothError { + case BLEError.bluetoothPoweredOff, BLEError.bluetoothUnavailable, BLEError.bluetoothUnauthorized: break + default: recordConnectionFailure() + } + } + if request.origin == .launch, + let bluetoothIndex = request.targets.firstIndex(where: { $0.transportType == .bluetooth }) { + request.targetIndex = bluetoothIndex + } + publishPending(request, phase: .disconnected) + if let receipt = currentLossReceipt, isCurrent(receipt) { await onConnectionLost?(receipt) } + throw ConnectionRequestFailure(requestID: request.id, underlying: lastError) + } + + static let connectRetryBaseDelay: TimeInterval = 0.3 + + private func settleCurrentCancellation(_ request: ConnectionRequest) async -> ConnectionResult { + guard owns(request) else { return .superseded } + publishPending(request, phase: .disconnected) + if let receipt = currentLossReceipt, isCurrent(receipt) { await onConnectionLost?(receipt) } + return .cancelled + } + + private func connectRejectionBelongsToRestoredLink(_ error: any Error, attempt: ConnectionAttempt) async -> Bool { + guard attempt.target.transportType == .bluetooth, + let deviceID = attempt.target.deviceID, + let ble = error as? BLEError, case .connectionFailed = ble else { return false } + let phase = await stateMachine.linkDiagnostics.phase + switch phase { + case .restoringState, .autoReconnecting, .connected: + break + default: + return false + } + return await stateMachine.connectedDeviceID == deviceID + } + + private func isTerminalConnectError(_ error: any Error) -> Bool { + guard let error = error as? BLEError else { return error is CancellationError } + return switch error { + case .authenticationFailed, .bluetoothPoweredOff, .bluetoothUnavailable, .bluetoothUnauthorized, + .deviceConnectedToOtherApp, .deviceNotFound: true + default: false + } + } + + func establishAttempt(_ request: ConnectionRequest, preservePhysicalBLE: Bool) async throws -> ConnectionResult { + try requireOwnership(request) + let predecessor = retirementTask + await predecessor?.value + try requireOwnership(request) + await metadataCommitTask?.value + try requireOwnership(request) + let attempt = ConnectionAttempt(target: request.target) + installAttempt(attempt, on: request, ownedByAdmissionWorker: AdmissionWorkerInstallation.isActive) + logLifecycle("attemptStarted", context: lifecycleContext(request: request, attempt: attempt, link: nil)) + let binding = attempt.binding + do { + let resource = try await openConnectionResource(request, attempt: attempt, preservePhysicalBLE: preservePhysicalBLE) + let newSession = resource.session + let (selfInfo, capabilities) = try await initializeSession(newSession, attempt: attempt) + attempt.identity.publicKey = selfInfo.publicKey + try requireAttemptOwnership(request, attempt) + if attempt.target.transportType == .bluetooth { + guard let deviceID = attempt.target.deviceID else { throw CancellationError() } + await recordBondVerification(deviceID: deviceID, binding: binding) + try requireAttemptOwnership(request, attempt) + await configureBLEPacing(for: capabilities, binding: binding) + } else { + detectAndStorePlatform(model: capabilities.model, transportType: .wifi) + } + try requireAttemptOwnership(request, attempt) + let prepared = try await prepareConnection(request, attempt: attempt, resource: resource, selfInfo: selfInfo, capabilities: capabilities) + try requireAttemptOwnership(request, attempt) + let link = ConnectionLink( + requestID: request.id, target: attempt.target, resource: resource, services: prepared.services, device: prepared.device + ) + try await commitConnection(request, attempt: attempt, link: link, repeatRanges: prepared.repeatRanges) + try requireAttemptOwnership(request, attempt) + guard owns(request), installedLink === link else { return resultForRetiredLink(request) } + let setup = beginConnectionSetup(request, link: link) + await setup.value + #if DEBUG + await testPostSetupResultHandler?(link.generation) + #endif + guard owns(request), installedLink === link else { return resultForRetiredLink(request) } + recordConnectionSuccess() + stopReconnectionWatchdog() + return .operational(link.snapshot) + } catch { + // Preserve the peripheral only after the handoff adopts it. A false + // return still retires the attempt and closes the link. + if owns(request), !preservePhysicalBLE, !request.forceReconnect, + await connectRejectionBelongsToRestoredLink(error, attempt: attempt), + let deviceID = attempt.target.deviceID, + await (try? handOffToOwningBluetoothLink(request, deviceID: deviceID)) == true { + request.handedOff = true + } + // Retirement revokes every binding, so classify an already-lost owned attempt before cleanup. + let establishmentError: any Error = if error is CancellationError, !binding.isActive, owns(request), request.attempt === attempt, + !Task.isCancelled, request.worker?.isCancelled != true, !request.handedOff { + ConnectionError.notConnected + } else { + error + } + let handedOff = owns(request) && request.handedOff && attempt.target.transportType == .bluetooth + await retireCandidate(request, attempt: attempt, closePhysical: !preservePhysicalBLE && !handedOff) + if isTerminalIdentityError(error) { + let failureRequestID = owns(request) ? beginDisconnect(reason: .userInitiated).receipt.requestID : request.id + throw ConnectionRequestFailure(requestID: failureRequestID, underlying: identityFailureForPresentation(error)) + } + throw establishmentError + } + } + + func beginConnectionSetup(_ request: ConnectionRequest, link: ConnectionLink) -> Task { + let setup = Task { @MainActor in + guard self.ownsRuntime(link), !Task.isCancelled else { return } + await link.services.chatSendQueueService.hydrate() + guard self.ownsRuntime(link), !Task.isCancelled else { return } + await self.onConnectionReady?(link.snapshot) + guard self.ownsRuntime(link), self.owns(request), !Task.isCancelled else { return } + let forceFullSync = request.forceFullSync + request.forceFullSync = false + self.connectionIntent = .wantsConnection() + let syncResult = await self.performInitialSync( + radioID: link.device.radioID, services: link.services, transportType: link.target.transportType, + forceFullSync: forceFullSync + ) + _ = await self.completeSync(link, syncResult: syncResult) + } + link.setupWorker = setup + return setup + } + + private func resultForRetiredLink(_ request: ConnectionRequest) -> ConnectionResult { + guard owns(request) else { return .superseded } + if let link = installedLink, link.requestID == request.id { return .operational(link.snapshot) } + return .handoff(requestID: request.id) + } + + func wireSocketLoss(_ resource: ConnectionResource) async { + guard let socket = resource.wifi else { return } + let binding = resource.binding + await socket.setDisconnectionHandler { [weak self, weak resource, weak socket] error, eventTime in + binding.revoke() + Task { @MainActor in + guard let self, let resource, let socket, + self.installedLink?.resource === resource else { return } + await self.handleWiFiDisconnection(error: error, remoteLossAt: eventTime, source: socket) + } + } + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+ResourcePreparation.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+ResourcePreparation.swift new file mode 100644 index 0000000000..8678309d45 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+ResourcePreparation.swift @@ -0,0 +1,87 @@ +import Foundation +import MeshCore + +extension ConnectionManager { + func openConnectionResource( + _ request: ConnectionRequest, attempt: ConnectionAttempt, preservePhysicalBLE: Bool + ) async throws -> ConnectionResource { + let binding = attempt.binding + let physical: any MeshTransport + let wifi: (any WiFiMeshTransport)? + let view: SessionBoundTransport + switch attempt.target { + case let .bluetooth(deviceID): + if pairing.isSessionActive, !pairing.isDeviceConnectable(deviceID) { throw ConnectionError.deviceNotFound } + guard shouldAllowConnection(force: request.forceReconnect) else { + throw BLEError.connectionFailed("Connection blocked by circuit breaker (cooling down)") + } + view = await transport.makeSessionTransport(deviceID: deviceID, binding: binding) + try requireAttemptOwnership(request, attempt) + if preservePhysicalBLE { await transport.refreshDataStream(sessionBinding: binding) } + try requireAttemptOwnership(request, attempt) + physical = transport + wifi = nil + case let .wifi(host, port): + let socket = makeWiFiTransport() + await socket.setConnectionInfo(host: host, port: port) + try requireAttemptOwnership(request, attempt) + physical = socket + wifi = socket + view = SessionBoundTransport(transport: socket, binding: binding) + case .simulator, .disconnected: + preconditionFailure("Simulator has its own synthetic preparation") + } + let newSession = makeBoundSession(transport: view, scope: request.radioCLICorrelationScope) + let resource = ConnectionResource( + binding: binding, transport: physical, session: newSession, wifi: wifi, + ble: attempt.target.transportType == .bluetooth ? transport : nil + ) + attempt.resource = resource + await installFloodScopeRecovery(on: resource, requestID: request.id) + await wireSocketLoss(resource) + try requireAttemptOwnership(request, attempt) + publishPending(request, phase: .connecting) + try await view.connect() + try requireAttemptOwnership(request, attempt) + if attempt.target.transportType == .bluetooth { + let origin = await transport.lifecycleOrigin + try requireAttemptOwnership(request, attempt) + request.physicalOrigin = origin + } + try requireAttemptOwnership(request, attempt) + publishPending(request, phase: .connected) + return resource + } + + /// Schedules recovery without awaiting it because retirement waits for the command slot. + func installFloodScopeRecovery(on resource: ConnectionResource, requestID: UUID) async { + await resource.session.setFloodScopeRecoveryHandler { [weak self, weak resource] in + Task { @MainActor [weak self, weak resource] in + guard let self, let resource else { return } + await self.recoverFloodScope(resource: resource, requestID: requestID) + } + } + } + + func recoverFloodScope(resource: ConnectionResource, requestID: UUID) async { + while let link = installedLink, + link.resource === resource, + link.requestID == requestID, + desiredRequest?.id == requestID, + connectionIntent.wantsConnection { + if powerOffBlocksReconnect { + // Power Off owns reconnect until it settles. Revalidate the link if it fails. + guard let worker = powerOffOperation?.worker, case .failure = await worker.result else { return } + continue + } + do { + _ = try await requestConnection( + targets: [link.target], origin: .recovery, forceFullSync: false, forceReconnect: true + ) + } catch { + logger.warning("Flood scope recovery failed: \(error.localizedDescription)") + } + return + } + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+SyncCompletion.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+SyncCompletion.swift new file mode 100644 index 0000000000..a51f74236e --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+SyncCompletion.swift @@ -0,0 +1,113 @@ +import Foundation + +extension ConnectionManager { + func owns(_ link: ConnectionLink) -> Bool { + installedLink === link && desiredRequest?.id == link.requestID && connectionIntent.wantsConnection + } + + func ownsRuntime(_ link: ConnectionLink) -> Bool { + owns(link) && link.services.isAcceptingRuntimeWork + } + + func reconcileConnectedListeners(for link: ConnectionLink) async -> Bool { + guard ownsRuntime(link), !Task.isCancelled else { return false } + if let worker = link.listenerRepairWorker { return await worker.value } + let worker = Task { @MainActor in + defer { link.listenerRepairWorker = nil } + guard self.ownsRuntime(link), !Task.isCancelled else { return false } + if !link.services.isEventMonitoringActive { + await link.services.startEventMonitoring(radioID: link.device.radioID, enableAutoFetch: false) + } + guard self.ownsRuntime(link), !Task.isCancelled else { return false } + let fetching = await link.services.messagePollingService.isAutoFetching + guard self.ownsRuntime(link), !Task.isCancelled else { return false } + if !fetching { + #if DEBUG + await self.testMessageListenerRepairHandler?(link.generation) + #endif + guard self.ownsRuntime(link), !Task.isCancelled else { return false } + await link.services.messagePollingService.startAutoFetch(radioID: link.device.radioID) + } + return self.ownsRuntime(link) && !Task.isCancelled + } + link.listenerRepairWorker = worker + return await worker.value + } + + @discardableResult + func completeSync(_ link: ConnectionLink, syncResult: FullSyncResult?) async -> Bool { + let succeeded = syncResult?.isConnectionUsable == true + guard ownsRuntime(link) else { return false } + if succeeded { + guard await reconcileConnectedListeners(for: link), ownsRuntime(link) else { return false } + link.usableSyncResult = syncResult + transition(link, to: .ready) + surfacedAuthFailureDeviceID = nil + if link.target.transportType == .wifi, wifiHeartbeatTask == nil { startWiFiHeartbeat() } + } else { + transition(link, to: .syncing) + } + if let worker = link.completionWorker { return await worker.value } + if link.didCompleteSync { return ownsRuntime(link) } + if !succeeded, link.target.transportType == .bluetooth { return true } + let operationID = UUID() + link.completionID = operationID + let worker = Task { @MainActor in + defer { + if link.completionID == operationID { link.completionWorker = nil; link.completionID = nil } + } + guard self.ownsRuntime(link), !Task.isCancelled else { return false } + if !link.synthetic, !link.timeEffectsClaimed { + link.timeEffectsClaimed = true + await self.syncDeviceTimeIfNeeded(for: link) + guard self.ownsRuntime(link), !Task.isCancelled else { return false } + await RadioTimezone.syncIfNeeded( + supportsRadioCLI: link.device.supportsRadioCLI, secondsFromGMT: TimeZone.current.secondsFromGMT(), + settings: link.services.settingsService, stillCurrent: { self.ownsRuntime(link) && !Task.isCancelled } + ) + } + guard self.ownsRuntime(link), !Task.isCancelled else { return false } + guard let usableSyncResult = link.usableSyncResult else { return true } + if !link.synthetic, let batch = self.membershipBatch, batch.radioID == link.device.radioID { + await link.services.remoteNodeService.handleLinkReconnection(radioID: batch.radioID, sessionIDs: batch.sessionIDs) + guard self.ownsRuntime(link), !Task.isCancelled else { return false } + if self.membershipBatch?.id == batch.id { self.membershipBatch?.sessionIDs.subtract(batch.sessionIDs) } + } + guard self.ownsRuntime(link), !Task.isCancelled else { return false } + await self.revalidateExpectedWiFiReboot(link) + guard self.ownsRuntime(link), !Task.isCancelled else { return false } + link.didCompleteSync = true + await self.onDeviceSynced?(link.snapshot, usableSyncResult.hasCleanRecipientData) + return self.ownsRuntime(link) + } + link.completionWorker = worker + return await worker.value + } + + /// A backward clock step triggers remote replay protection until the previous time is reached. + /// Limit each step to the tolerance while still recovering clocks far in the future. + private static let deviceClockDriftTolerance: TimeInterval = 5 + + /// Syncs the device clock when it drifts beyond `deviceClockDriftTolerance`. + func syncDeviceTimeIfNeeded(for link: ConnectionLink) async { + guard ownsRuntime(link) else { return } + let session = link.resource.session + do { + let deviceTime = try await withTimeout(.seconds(5), operationName: "getTime") { + try await session.getTime() + } + guard ownsRuntime(link), !Task.isCancelled else { return } + let timeDifference = abs(deviceTime.timeIntervalSinceNow) + if timeDifference > Self.deviceClockDriftTolerance { + try await withTimeout(.seconds(5), operationName: "setTime") { + try await session.setTime(Date()) + } + logger.info("Synced device time (was off by \(Int(timeDifference))s)") + } else { + logger.info("Device time in sync (drift: \(Int(timeDifference))s)") + } + } catch { + logger.warning("Failed to sync device time: \(error.localizedDescription)") + } + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Teardown.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Teardown.swift index 1ce7cd8854..defe6f8729 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Teardown.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Teardown.swift @@ -1,8 +1,117 @@ import Foundation extension ConnectionManager { - func ownsConnectionAttempt(deviceID: UUID, attemptID: UUID) -> Bool { - connectingDeviceID == deviceID && connectingAttemptID == attemptID + @discardableResult + func beginOwnedRetirement( + previousRequest: ConnectionRequest?, + phase: DeviceConnectionState, + closePhysical: Bool, + retainMembership: Bool, + closeUnboundPhysical: Bool = false + ) -> ConnectionRetirement { + let predecessor = retirementTask + let oldLink = installedLink + let receipt = ConnectionLossReceipt(requestID: desiredRequest?.id ?? UUID(), retiredGeneration: oldLink?.generation) + currentLossReceipt = receipt + let candidate = previousRequest?.attempt?.resource + let candidateServices = previousRequest?.attempt?.preparedServices + let oldContext = oldLink.map { link in + let request = previousRequest?.id == link.requestID ? previousRequest : nil + return lifecycleContext(request: request, attempt: request?.attempt, link: link) + } + let candidateContext = candidate.map { + lifecycleContext(request: previousRequest, attempt: previousRequest?.attempt, link: nil, resource: $0) + } + let retirementReason = closePhysical ? "closePhysical" : "preservePhysical" + if let oldContext { logLifecycle("dispose", context: oldContext, reason: retirementReason) } + if let candidateContext, candidate !== oldLink?.resource { + logLifecycle("candidateDispose", context: candidateContext, reason: retirementReason) + } + let closeUnboundBLE = closePhysical && oldLink == nil && candidate == nil + && (closeUnboundPhysical || previousRequest?.handedOff == true) + && connectionTeardownCount == 0 + oldLink?.resource.revoke() + candidate?.revoke() + previousRequest?.binding?.revoke() + oldLink?.setupWorker?.cancel() + oldLink?.completionWorker?.cancel() + oldLink?.listenerRepairWorker?.cancel() + stopWiFiHeartbeat() + cancelResyncLoop() + cancelChannelRetry() + let workers = retiringWorkers + retiringWorkers.removeAll() + if !retainMembership { + membershipBatch = nil + } else if let oldLink { + let retained = membershipBatch?.radioID == oldLink.device.radioID ? membershipBatch?.sessionIDs ?? [] : [] + membershipBatch = MembershipBatch(id: UUID(), radioID: oldLink.device.radioID, sessionIDs: retained) + } + detachPublication(phase: phase) + beginConnectionTeardown() + let worker = Task { @MainActor in + defer { self.endConnectionTeardown() } + await predecessor?.value + #if DEBUG + await self.testConnectionTeardownHandler?() + #endif + if let oldLink { + let ids = await oldLink.services.remoteNodeService.handleLinkDisconnection(radioID: oldLink.device.radioID) + if retainMembership, self.membershipBatch?.radioID == oldLink.device.radioID { + self.membershipBatch?.sessionIDs.formUnion(ids) + } + oldLink.services.settingsService.radioWiFiState.noteLinkEnded(contextID: oldLink.services.settingsService.radioWiFiContextID) + async let settingsRetired: Void = oldLink.services.settingsService.retireRadioWiFiOperations() + await oldLink.resource.retire(closePhysical: closePhysical) + await settingsRetired + await oldLink.setupWorker?.value + _ = await oldLink.completionWorker?.value + _ = await oldLink.listenerRepairWorker?.value + await oldLink.services.tearDown() + await oldLink.services.syncCoordinator.onDisconnected(notificationService: oldLink.services.notificationService) + } + if let candidateServices, candidateServices !== oldLink?.services { + async let settingsRetired: Void = candidateServices.settingsService.retireRadioWiFiOperations() + if let candidate, candidate !== oldLink?.resource { + await candidate.retire(closePhysical: closePhysical) + } + await settingsRetired + await candidateServices.tearDown() + } else if let candidate, candidate !== oldLink?.resource { + await candidate.retire(closePhysical: closePhysical) + } + for worker in workers { + await worker.value + } + if closeUnboundBLE { await self.transport.disconnect() } + if let binding = oldLink?.resource.binding ?? candidate?.binding { + await self.stateMachine.setAppSessionLive(deviceID: nil, sessionBinding: binding) + } + if let oldContext { self.logLifecycle("retired", context: oldContext, reason: retirementReason) } + if let candidateContext, candidate !== oldLink?.resource { + self.logLifecycle("candidateRetired", context: candidateContext, reason: retirementReason) + } + } + retirementTask = worker + return ConnectionRetirement(worker: worker, receipt: receipt) + } + + func retireCandidate(_ request: ConnectionRequest, attempt: ConnectionAttempt, closePhysical: Bool) async { + let resource = attempt.resource + let prepared = attempt.preparedServices + let context = lifecycleContext(request: request, attempt: attempt, link: nil, resource: resource) + let retirementReason = closePhysical ? "closePhysical" : "preservePhysical" + logLifecycle("candidateDispose", context: context, reason: retirementReason) + attempt.binding.revoke() + #if DEBUG + await testCandidateRetirementHandler?(attempt.binding) + #endif + async let settingsRetired: Void? = prepared?.settingsService.retireRadioWiFiOperations() + await resource?.retire(closePhysical: closePhysical) + await settingsRetired + await prepared?.tearDown() + logLifecycle("candidateRetired", context: context, reason: retirementReason) + if request.attempt === attempt { request.attempt = nil } } func beginConnectionTeardown() { @@ -11,28 +120,5 @@ extension ConnectionManager { func endConnectionTeardown() { connectionTeardownCount -= 1 - guard connectionTeardownCount == 0 else { return } - let waiters = connectionTeardownWaiters - connectionTeardownWaiters.removeAll() - for waiter in waiters { - waiter.resume() - } - } - - /// A replacement connect waits here until teardown has stopped the old session and closed its transport. - func waitForConnectionTeardown() async throws { - #if DEBUG - if connectionTeardownCount > 0 { - testConnectionTeardownWaiterCount += 1 - } - let didWait = connectionTeardownCount > 0 - defer { - if didWait { testConnectionTeardownWaiterCount -= 1 } - } - #endif - while connectionTeardownCount > 0 { - await withCheckedContinuation { connectionTeardownWaiters.append($0) } - } - try Task.checkCancellation() } } diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+TextRules.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+TextRules.swift new file mode 100644 index 0000000000..2d7cdf3e49 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+TextRules.swift @@ -0,0 +1,46 @@ +import Foundation + +extension ConnectionManager { + static var defaultTextRulesURL: URL { + FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] + .appending(path: "TextRules.json") + } + + func loadTextRules() { + defer { isTextRulesLoading = false } + do { + let data = try Data(contentsOf: textRulesURL) + let preference = try JSONDecoder().decode(TextRulesPreference.self, from: data) + guard preference.isValid else { throw CocoaError(.fileReadCorruptFile) } + textRulesPreference = preference + } catch let error as CocoaError where error.code == .fileReadNoSuchFile { + textRulesPreference = TextRulesPreference() + } catch { + textRulesPreference = nil + logger.error("Could not load Text Rules: \(error.localizedDescription)") + } + } + + public func retryTextRulesLoad() async { + guard !isTextRulesLoading, textRulesPreference == nil else { return } + isTextRulesLoading = true + await Task.yield() + loadTextRules() + } + + public func updateTextRules(_ update: (inout TextRulesPreference) -> Void) throws { + guard !isTextRulesLoading, var preference = textRulesPreference else { + throw CocoaError(.fileReadCorruptFile) + } + update(&preference) + guard preference.isValid else { throw CocoaError(.fileWriteInapplicableStringEncoding) } + guard preference != textRulesPreference else { return } + let data = try JSONEncoder().encode(preference) + try FileManager.default.createDirectory( + at: textRulesURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try data.write(to: textRulesURL, options: .atomic) + textRulesPreference = preference + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+WiFi.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+WiFi.swift index 28c76928aa..aae7d293bf 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+WiFi.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+WiFi.swift @@ -2,479 +2,179 @@ import Foundation import MeshCore extension ConnectionManager { - // MARK: - WiFi Heartbeat - - /// Starts periodic heartbeat to detect dead WiFi connections. - /// ESP32's TCP stack doesn't respond to TCP keepalives, so we use application-level probes. func startWiFiHeartbeat() { + guard let link = installedLink, link.target.transportType == .wifi else { return } stopWiFiHeartbeat() - - wifiHeartbeatTask = Task { [weak self] in + let slot = UUID() + heartbeatSlotID = slot + wifiHeartbeatTask = Task { @MainActor [weak self] in + guard let self else { return } + defer { + if self.heartbeatSlotID == slot { self.wifiHeartbeatTask = nil; self.heartbeatSlotID = nil } + } while !Task.isCancelled { - guard let self else { return } + do { try await self.sleepForWiFiHeartbeat() } catch { return } + guard self.installedLink === link, self.heartbeatSlotID == slot else { return } + if self.shouldPauseWiFiHeartbeatProbe { continue } do { - try await self.sleepForWiFiHeartbeat() + _ = try await link.resource.session.getTime() } catch { - break - } - - guard self.currentTransportType == .wifi, - self.connectionState.isOperational, - let session = self.session else { break } - - if self.shouldPauseWiFiHeartbeatProbe { - self.logger.info("WiFi heartbeat skipped while a probe would be inconclusive") - continue - } - - // Probe connection with lightweight command - do { - _ = try await session.getTime() - } catch { - if Task.isCancelled || self.session !== session { - break - } - if self.shouldPauseWiFiHeartbeatProbe { - self.logger.info("WiFi heartbeat failure treated as inconclusive") - continue + guard !Task.isCancelled, self.installedLink === link, !self.shouldPauseWiFiHeartbeatProbe else { continue } + Task { @MainActor [weak self] in + guard let self, self.installedLink === link else { return } + await self.handleWiFiDisconnection(error: error, remoteLossAt: nil, isHeartbeat: true, source: link.resource.wifi) } - self.logger.warning("WiFi heartbeat failed: \(error.localizedDescription)") - await self.handleWiFiDisconnection(error: error, remoteLossAt: nil, isHeartbeat: true) - break + return } } } } var shouldPauseWiFiHeartbeatProbe: Bool { - powerOffBlocksReconnect - || connectionState == .syncing - || resyncTask != nil - || channelRetryTask != nil + powerOffBlocksReconnect || connectionState == .syncing || resyncTask != nil || channelRetryTask != nil } private func sleepForWiFiHeartbeat() async throws { #if DEBUG - if let testWiFiHeartbeatClock { - try await testWiFiHeartbeatClock.sleep(for: Self.wifiHeartbeatInterval) - return - } + if let clock = testWiFiHeartbeatClock { try await clock.sleep(for: Self.wifiHeartbeatInterval); return } #endif try await Task.sleep(for: Self.wifiHeartbeatInterval) } - /// Stops the WiFi heartbeat loop func stopWiFiHeartbeat() { + if let wifiHeartbeatTask { retiringWorkers.append(wifiHeartbeatTask) } + heartbeatSlotID = nil wifiHeartbeatTask?.cancel() wifiHeartbeatTask = nil } - // MARK: - WiFi Disconnection Handling - - /// Socket loss records `remoteLossAt`. A heartbeat passes nil and `isHeartbeat` - /// because the socket is still up and cannot prove the radio powered off. func handleWiFiDisconnection( - error: Error?, - remoteLossAt: CFAbsoluteTime?, - isHeartbeat: Bool = false, - source: WiFiTransport? = nil + error: Error?, remoteLossAt: CFAbsoluteTime?, isHeartbeat: Bool = false, source: (any WiFiMeshTransport)? = nil ) async { - if let source, wifiTransport !== source { return } - if let remoteLossAt { - notePowerOffRemoteLoss(deviceID: connectedDevice?.id, eventTime: remoteLossAt) - } - if isHeartbeat, powerOffBlocksReconnect { - logger.info("[WiFi] Heartbeat ignored during power-off") - return - } - - // User-initiated disconnect - don't reconnect + guard let link = installedLink, link.target.transportType == .wifi, + let request = desiredRequest, request.id == link.requestID else { return } + if let source, source !== link.resource.wifi { return } + if let remoteLossAt { notePowerOffRemoteLoss(deviceID: link.device.id, eventTime: remoteLossAt) } guard connectionIntent.wantsConnection else { return } - - // Only handle WiFi disconnections - guard currentTransportType == .wifi else { return } - - // Prevent re-entrant calls: multiple disconnection callbacks can fire - // simultaneously from the transport handler and heartbeat. The flag - // covers the window between entry and startWiFiReconnection() where - // await suspension points could allow interleaving on @MainActor. - guard !isHandlingWiFiDisconnection, wifiReconnectTask == nil else { - logger.info("WiFi disconnection already being handled, ignoring duplicate") - return - } - isHandlingWiFiDisconnection = true - defer { isHandlingWiFiDisconnection = false } - beginConnectionTeardown() - defer { endConnectionTeardown() } - - logger.warning("WiFi connection lost: \(error?.localizedDescription ?? "unknown")") - - // Stop heartbeat before teardown - stopWiFiHeartbeat() - - cancelResyncLoop() - cancelChannelRetry() - - // Enter .connecting and clear the old stack before the await. - // A power-off that settles mid-teardown must see recovery already pending. - let oldServices = services - services = nil - session = nil - logger.info("[WiFi] State → .connecting (WiFi disconnection, starting reconnection)") - connectionState = .connecting - - #if DEBUG - await testConnectionTeardownHandler?() - #endif - - if let oldServices { - // Mark room sessions disconnected before tearing down services - _ = await oldServices.remoteNodeService.handleBLEDisconnection() - // Reset sync state before destroying services to prevent stuck "Syncing" pill - await oldServices.syncCoordinator.onDisconnected(notificationService: oldServices.notificationService) - await oldServices.tearDown() - } - - // Start reconnection attempts + if isHeartbeat, powerOffBlocksReconnect { return } + let barrier = beginOwnedRetirement(previousRequest: request, phase: .connecting, closePhysical: true, retainMembership: true) + wifiDisconnectionReceipt = barrier.receipt + defer { + if wifiDisconnectionReceipt?.id == barrier.receipt.id { wifiDisconnectionReceipt = nil } + } + await onAutoReconnectStarted?(barrier.receipt) + await barrier.value + guard owns(request), isCurrent(barrier.receipt) else { return } startWiFiReconnection() } - // MARK: - WiFi Reconnection - - /// Starts the WiFi reconnection retry loop func startWiFiReconnection() { - guard !powerOffBlocksReconnect else { - logger.info("[WiFi] Reconnect suppressed during power-off") - return - } - // If a reconnect task is already running, don't start another - if wifiReconnectTask != nil { - logger.info("WiFi reconnection already in progress, skipping") - return - } - - // Rate limiting: prevent rapid reconnection attempts - let reconnectCooldown: TimeInterval + guard !powerOffBlocksReconnect, wifiReconnectTask == nil, + let request = desiredRequest, case .wifi = request.target else { return } + let cooldown: TimeInterval #if DEBUG - reconnectCooldown = testWiFiReconnectCooldown ?? Self.wifiReconnectCooldown + cooldown = testWiFiReconnectCooldown ?? Self.wifiReconnectCooldown #else - reconnectCooldown = Self.wifiReconnectCooldown + cooldown = Self.wifiReconnectCooldown #endif - if let lastStart = lastWiFiReconnectStartTime, - Date().timeIntervalSince(lastStart) < reconnectCooldown { - logger.warning("Suppressing WiFi reconnection: too soon after last attempt") - Task { await abandonWiFiConnection() } + if let last = lastWiFiReconnectStartTime, Date().timeIntervalSince(last) < cooldown { + Task { @MainActor in await self.finishWiFiRecovery(request) } return } lastWiFiReconnectStartTime = Date() - + let slot = UUID() + wifiRecoverySlotID = slot wifiReconnectAttempt = 0 - wifiReconnectTask?.cancel() - - wifiReconnectTask = Task { - // Only self-nil when not cancelled: startWiFiReconnection cancels the - // old task before assigning a new one, and an unconditional defer in - // the cancelled old task would destroy the replacement's handle (the - // same pattern resyncTask and channelRetryTask document). + let predecessor = retirementTask + wifiReconnectTask = Task { @MainActor in defer { - if !Task.isCancelled { - wifiReconnectTask = nil - wifiReconnectAttempt = 0 + if self.wifiRecoverySlotID == slot { + self.wifiReconnectTask = nil + self.wifiRecoverySlotID = nil + self.wifiReconnectAttempt = 0 } } - - let startTime = ContinuousClock.now - - while !Task.isCancelled, connectionIntent.wantsConnection, !powerOffBlocksReconnect { - // Check if we've exceeded 30 second window - let elapsed = ContinuousClock.now - startTime - let maxReconnectDuration: Duration - #if DEBUG - maxReconnectDuration = testWiFiMaxReconnectDuration ?? Self.wifiMaxReconnectDuration - #else - maxReconnectDuration = Self.wifiMaxReconnectDuration - #endif - if elapsed > maxReconnectDuration { - logger.info("WiFi reconnection timeout after 30s") - await abandonWiFiConnection() - return - } - - wifiReconnectAttempt += 1 - logger.info("WiFi reconnect attempt \(self.wifiReconnectAttempt)") - + #if DEBUG + await self.testWiFiRecoveryEntryHandler?() + #endif + guard self.owns(request), self.wifiRecoverySlotID == slot, !Task.isCancelled else { return } + await predecessor?.value + guard self.owns(request), self.wifiRecoverySlotID == slot, !Task.isCancelled else { return } + let started = ContinuousClock.now + let limit: Duration + #if DEBUG + limit = self.testWiFiMaxReconnectDuration ?? Self.wifiMaxReconnectDuration + #else + limit = Self.wifiMaxReconnectDuration + #endif + while !Task.isCancelled, self.owns(request), self.wifiRecoverySlotID == slot, + self.connectionIntent.wantsConnection, !self.powerOffBlocksReconnect { + if ContinuousClock.now - started > limit { break } + self.wifiReconnectAttempt += 1 + let retirement = self.retirementTask + await retirement?.value + guard self.owns(request), self.wifiRecoverySlotID == slot, !Task.isCancelled, + self.connectionIntent.wantsConnection, !self.powerOffBlocksReconnect else { return } do { - try await reconnectWiFi() - logger.info("WiFi reconnection succeeded") - return + let result = try await self.establishAttempt(request, preservePhysicalBLE: false) + if case .operational = result { return } + guard self.owns(request) else { return } } catch { - logger.warning("WiFi reconnect failed: \(error.localizedDescription)") + guard self.owns(request), !Task.isCancelled else { return } + self.logger.warning("WiFi reconnect failed: \(error.localizedDescription)") } - - // Exponential backoff: 0.5s, 1s, 2s, 4s (capped) - let delay = min(0.5 * pow(2.0, Double(wifiReconnectAttempt - 1)), 4.0) - try? await Task.sleep(for: .seconds(delay)) + let delay = min(Self.wifiReconnectBaseDelay * pow(2, Double(self.wifiReconnectAttempt - 1)), Self.wifiReconnectMaxDelay) + do { try await Task.sleep(for: .seconds(delay)) } catch { return } } + guard self.owns(request), !Task.isCancelled else { return } + Task { @MainActor in await self.finishWiFiRecovery(request) } } } - /// Attempts to reconnect to the WiFi device using stored connection info - private func reconnectWiFi() async throws { - try await waitForConnectionTeardown() - guard let wifiTransport, - let (host, port) = await wifiTransport.connectionInfo else { - throw ConnectionError.connectionFailed("No WiFi connection info") - } - try Task.checkCancellation() - - // Stop any existing session to prevent receive loops racing for transport data - await session?.stop() - try Task.checkCancellation() - session = nil - - // Disconnect old transport cleanly - await wifiTransport.disconnect() - try Task.checkCancellation() - - // Create fresh transport with same connection info - let newTransport = WiFiTransport() - await newTransport.setConnectionInfo(host: host, port: port) - try Task.checkCancellation() - self.wifiTransport = newTransport - - // Connect - try await newTransport.connect() - try Task.checkCancellation() - connectionState = .connected - - // Re-establish session - let newSession = MeshCoreSession(transport: newTransport) - session = newSession - try await newSession.start() - try Task.checkCancellation() - - guard let selfInfo = await newSession.currentSelfInfo else { - throw ConnectionError.initializationFailed("No self info") - } + static let wifiReconnectBaseDelay: TimeInterval = 0.5 + static let wifiReconnectMaxDelay: TimeInterval = 4 - let deviceID = await wifiDeviceID(publicKey: selfInfo.publicKey) - try Task.checkCancellation() - try await completeWiFiReconnection( - session: newSession, - transport: newTransport, - deviceID: deviceID - ) + private func finishWiFiRecovery(_ request: ConnectionRequest) async { + guard owns(request), installedLink == nil else { return } + let barrier = beginOwnedRetirement(previousRequest: request, phase: .disconnected, closePhysical: true, retainMembership: true) + await barrier.value + guard isCurrent(barrier.receipt) else { return } + await onConnectionLost?(barrier.receipt) } - /// Completes WiFi reconnection by re-establishing services - private func completeWiFiReconnection( - session: MeshCoreSession, - transport: WiFiTransport, - deviceID: UUID - ) async throws { - let capabilities = try await session.queryDevice() - detectAndStorePlatform(model: capabilities.model, transportType: .wifi) - guard let selfInfo = await session.currentSelfInfo else { - throw ConnectionError.initializationFailed("No self info") - } - - let (newServices, radioID) = try await buildServicesAndSaveDevice( - deviceID: deviceID, - session: session, - selfInfo: selfInfo, - capabilities: capabilities - ) - persistConnection(deviceID: deviceID, radioID: radioID, deviceName: selfInfo.name) - - // Wire disconnection handler on new transport - await transport.setDisconnectionHandler { [weak self, weak transport] error, eventTime in - guard let transport else { return } - Task { @MainActor in - await self?.handleWiFiDisconnection(error: error, remoteLossAt: eventTime, source: transport) - } - } - - await onConnectionReady?() - // onConnectionReady can suspend; a reentrant main-actor WiFi disconnect may - // clear connectedDevice or replace services during that await. Recheck so an - // aborted reconnect bails here instead of syncing a torn-down session. - guard connectionIntent.wantsConnection, - services === newServices, - connectedDevice != nil - else { - logger.info("[WiFi] reconnect aborted after onConnectionReady: connection state changed") - await session.stop() - await newServices.tearDown() - services = nil - connectedDevice = nil - allowedRepeatFreqRanges = [] - return - } - let syncResult = await performInitialSync(radioID: radioID, services: newServices, transportType: .wifi, context: "WiFi reconnect") - - guard await promoteToReady(syncResult: syncResult, expectedServices: newServices, transportType: .wifi) else { return } - - stopReconnectionWatchdog() - if connectionState == .ready { - startWiFiHeartbeat() - } - } - - // MARK: - WiFi Connection Health - - /// Checks if the WiFi connection is still alive (call on app foreground) public func checkWiFiConnectionHealth() async { - // If a reconnect task is already running, let it finish - if wifiReconnectTask != nil { - logger.info("WiFi reconnection already in progress on foreground") + if wifiReconnectTask != nil || shouldDeferOpportunisticReconnect { return } + if let link = installedLink, let socket = link.resource.wifi { + let connected = await socket.isConnected + guard installedLink === link else { return } + if !connected { await handleWiFiDisconnection(error: nil, remoteLossAt: nil, source: socket) } return } - - // Case 1: We think we're connected but the transport died while backgrounded - if currentTransportType == .wifi, - connectionState.isOperational, - let wifiTransport { - let isConnected = await wifiTransport.isConnected - if !isConnected { - logger.info("WiFi connection died while backgrounded") - await handleWiFiDisconnection(error: nil, remoteLossAt: nil) - return - } - } - - // Case 2: Connection was lost and cleanup already ran while backgrounded, - // but user still wants to be connected — attempt fresh reconnection - if connectionState == .disconnected, - connectionIntent.wantsConnection, - let lastDeviceID = lastConnectedDeviceID { - let dataStore = persistenceStore - if let device = try? await dataStore.fetchDevice(id: lastDeviceID), - case let .wifi(host, port, _) = device.lastUsedConnectionMethod { - logger.info("WiFi foreground reconnect to \(host):\(port)") - do { - try await connectViaWiFi(host: host, port: port) - } catch { - logger.warning("WiFi foreground reconnect failed: \(error.localizedDescription)") - } - } - } - } - - // MARK: - WiFi Connection - - /// Connects to a device via WiFi/TCP. - /// - /// - Parameters: - /// - host: The hostname or IP address of the device - /// - port: The TCP port to connect to - /// - forceFullSync: When true, performs a complete sync ignoring cached timestamps - /// - Throws: Connection or session errors - public func connectViaWiFi(host: String, port: UInt16, forceFullSync: Bool = false) async throws { - let host = host.trimmingCharacters(in: .whitespacesAndNewlines) - guard !host.isEmpty else { - throw WiFiTransportError.invalidHost - } - - try Task.checkCancellation() - invalidatePowerOffForConnectionChange() - try await waitForConnectionTeardown() - - logger.info("Connecting via WiFi to \(host):\(port)") - - #if DEBUG - testWiFiConnectAttempts.append((host, port)) - if let testWiFiConnectHandler { - try await testWiFiConnectHandler(host, port) - return - } - #endif - - // Disconnect existing connection if any - if connectionState != .disconnected { - await disconnect(reason: .wifiReconnectPrep) - } - - connectionIntent = .wantsConnection() - persistIntent() - connectionState = .connecting - + guard connectionState == .disconnected, connectionIntent.wantsConnection, connectionTeardownCount == 0 else { return } + let observed = desiredRequest?.id + let host: String + let port: UInt16 + if let request = desiredRequest { + guard case let .wifi(requestHost, requestPort) = request.target else { return } + host = requestHost + port = requestPort + } else { + guard let deviceID = lastConnectedDeviceID, + let device = try? await persistenceStore.fetchDevice(id: deviceID), + case let .wifi(savedHost, savedPort, _) = device.lastUsedConnectionMethod else { return } + host = savedHost + port = savedPort + } + guard desiredRequest?.id == observed, !shouldDeferOpportunisticReconnect, + connectionTeardownCount == 0, connectionState == .disconnected, connectionIntent.wantsConnection else { return } do { - // Create and configure WiFi transport - let newWiFiTransport = WiFiTransport() - await newWiFiTransport.setConnectionInfo(host: host, port: port) - wifiTransport = newWiFiTransport - - // Connect the transport - try await newWiFiTransport.connect() - - connectionState = .connected - - // Create session (same as BLE) - let newSession = MeshCoreSession(transport: newWiFiTransport) - session = newSession - - let (meshCoreSelfInfo, deviceCapabilities) = try await initializeSession(newSession) - detectAndStorePlatform(model: deviceCapabilities.model, transportType: .wifi) - - let deviceID = await wifiDeviceID(publicKey: meshCoreSelfInfo.publicKey) - - let wifiMethod = ConnectionMethod.wifi(host: host, port: port, displayName: nil) - let (newServices, radioID) = try await buildServicesAndSaveDevice( - deviceID: deviceID, - session: newSession, - selfInfo: meshCoreSelfInfo, - capabilities: deviceCapabilities, - connectionMethods: [wifiMethod] - ) - - // Persist connection for potential future use - persistConnection(deviceID: deviceID, radioID: radioID, deviceName: meshCoreSelfInfo.name) - - await onConnectionReady?() - let syncResult = await performInitialSync(radioID: radioID, services: newServices, transportType: .wifi, forceFullSync: forceFullSync) - - // Wire disconnection handler before promotion — needed even if promotion fails - await newWiFiTransport.setDisconnectionHandler { [weak self, weak newWiFiTransport] error, eventTime in - guard let newWiFiTransport else { return } - Task { @MainActor in - await self?.handleWiFiDisconnection(error: error, remoteLossAt: eventTime, source: newWiFiTransport) - } - } - - guard await promoteToReady(syncResult: syncResult, expectedServices: newServices, transportType: .wifi) else { return } - - stopReconnectionWatchdog() - if connectionState == .ready { - startWiFiHeartbeat() - } - logger.info("WiFi connection complete - device ready") - - } catch { - await abandonWiFiConnection() - throw error - } + _ = try await requestConnection(targets: [.wifi(host: host, port: port)], origin: .recovery, forceFullSync: false, forceReconnect: false) + } catch { logger.warning("WiFi foreground reconnect failed: \(error.localizedDescription)") } } - /// Drops the WiFi socket and the transport marker, then tears the session down. - /// `disconnect()` closes `wifiTransport` when it is set, so a give-up has to clear it. - private func abandonWiFiConnection() async { - beginConnectionTeardown() - defer { endConnectionTeardown() } - if let wifiTransport { - await wifiTransport.disconnect() - self.wifiTransport = nil - } - currentTransportType = nil - await cleanupConnection() - } - - /// Saved id for a WiFi connect: the row's Bluetooth peripheral UUID, else its id. - /// Derives from the public key when no row exists or the fetch fails. func wifiDeviceID(publicKey: Data) async -> UUID { let rows = await (try? persistenceStore.fetchDevices(publicKey: publicKey)) ?? [] - if let row = rows.first(where: { $0.bluetoothPeripheralID != nil }) ?? rows.first { - return row.bluetoothPeripheralID ?? row.id - } + if let row = rows.first(where: { $0.bluetoothPeripheralID != nil }) ?? rows.first { return row.bluetoothPeripheralID ?? row.id } return DeviceIdentity.deriveUUID(from: publicKey) } } diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager.swift index b72e355b93..874e1c90a5 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager.swift @@ -1,46 +1,9 @@ -@preconcurrency import CoreBluetooth import Foundation import MeshCore -import OSLog import SwiftData -/// Manages the connection lifecycle for mesh devices. -/// -/// `ConnectionManager` owns the transport, session, and services. It handles: -/// - Device pairing via the `DevicePairingService` seam (AccessorySetupKit on iOS, in-app scan picker on macOS) -/// - Connection and disconnection -/// - Auto-reconnect on connection loss -/// - Last-device persistence for app restoration -/// -/// ## Connection-state model -/// -/// Three distinct enums describe "where are we", at three layers, and they do -/// not collapse into one another: -/// -/// - `BLEPhase` (on `BLEStateMachine`): the CoreBluetooth link lifecycle -/// (`idle`, `connecting`, `discoveringServices`, `discoveryComplete`, -/// `connected`, `autoReconnecting`, ...). Driven by CBCentralManager -/// callbacks; every transition routes through `BLEStateMachine.transition(to:)`. -/// Concerns only the BLE transport, and does not apply to a radio connected over WiFi. -/// - `MeshCore.ConnectionState`: the transport-link state the session publishes -/// (`disconnected`, `connecting`, `connected`, `reconnecting`, `failed`). -/// `@_exported import MeshCore` makes its bare name visible app-wide; this one -/// is the lower layer. -/// - `DeviceConnectionState`: the app-facing rung (`disconnected`, `connecting`, -/// `connected`, `syncing`, `ready`). Adds the post-link `syncing`/`ready` -/// distinction the transport layer has no concept of. This is the value -/// `connectionState` holds and the one UI gates on. -/// -/// `ConnectionManager` drives `connectionState` directly from the connect, sync, -/// disconnect, and reconnect paths; nothing else writes it. The transport layer -/// reports link events through the lifecycle callbacks wired in `init` -/// (`setDisconnectionHandler`, `setReconnectionHandler`, the auto-reconnect and -/// powered-on handlers), which this class translates into `connectionState` -/// transitions. `ConnectionIntent` is the orthogonal "does the user want to be -/// connected" axis that gates auto-reconnect, and is the only piece persisted -/// across launches. In DEBUG, `assertStateInvariants()` enforces that `.syncing` -/// and `.ready` always carry a live `services`, `session`, and `connectedDevice`, -/// and that `.userDisconnected` intent only coexists with `.disconnected`. +/// Owns connection requests, installed stacks, retirement and radio metadata. +/// UI state, BLE phase and session state describe separate lifecycles. @Observable @MainActor public final class ConnectionManager { @@ -58,29 +21,32 @@ public final class ConnectionManager { let connectionStateEvents = EventBroadcaster() /// Current connection state - public internal(set) var connectionState: DeviceConnectionState = .disconnected { + public private(set) var connectionState: DeviceConnectionState = .disconnected { didSet { + logLifecycle("state", context: lifecycleContext(request: desiredRequest, attempt: desiredRequest?.attempt, link: installedLink)) connectionStateEvents.yield(connectionState) #if DEBUG assertStateInvariants() #endif - if connectionState == .ready, oldValue != .ready { - onConnectionBecameUsable?() - } + if connectionState == .ready, oldValue != .ready, let snapshot = currentConnection { onConnectionBecameUsable?(snapshot) } } } /// Connected device info (nil when disconnected) - public internal(set) var connectedDevice: DeviceDTO? + public private(set) var connectedDevice: DeviceDTO? + + /// The open request unpublished its link to rebuild an imported identity. + /// Cleared when the replacement link publishes or the request disconnects. + public internal(set) var identityRebuildUnpublished = false /// Allowed repeat frequency ranges from connected device (empty when disconnected or unsupported) public var allowedRepeatFreqRanges: [MeshCore.FrequencyRange] = [] /// Services container (nil when disconnected) - public internal(set) var services: ServiceContainer? + public private(set) var services: ServiceContainer? /// Current transport type (bluetooth or wifi) - public internal(set) var currentTransportType: TransportType? + public private(set) var currentTransportType: TransportType? /// Current user-actionable Bluetooth availability, updated as `CBCentralManager` reports state /// changes. The macOS scan picker reads this to swap its scanning state for a remedy when @@ -103,21 +69,6 @@ public final class ConnectionManager { /// The user's connection intent. Replaces shouldBeConnected, userExplicitlyDisconnected, and pendingForceFullSync. var connectionIntent: ConnectionIntent = .none - /// The device being actively connected via connect(to:). - /// Nil during auto-reconnect (tracked by reconnectionCoordinator.reconnectingDeviceID instead). - var connectingDeviceID: UUID? { - didSet { - if connectingDeviceID == nil { connectingAttemptID = nil } - } - } - - /// Distinguishes successive manual attempts to the same radio. - var connectingAttemptID: UUID? - - /// The device whose MeshCore session is currently being rebuilt after a BLE auto-reconnect. - /// Used to suppress duplicate reconnect attempts while session startup is still in flight. - var sessionRebuildDeviceID: UUID? - /// Device whose pairing-failure recovery has already been surfaced this failure /// episode. While the bond stays invalid every watchdog retry fails the same way, /// so without this latch the recovery alert would re-interrupt after each retry. @@ -138,91 +89,7 @@ public final class ConnectionManager { /// Opportunistic reconnect call sites consult this; or new conditions in here /// when the next contention class shows up, so every site picks them up. public var shouldDeferOpportunisticReconnect: Bool { - isPairingInProgress || isPairingFlowActive - } - - /// Bluetooth radio came back while the user still wants a connection. - /// Stands down when the saved row's last method is WiFi. - func handleBluetoothPoweredOn() async { - #if DEBUG - defer { testBluetoothPoweredOnHandlerRuns += 1 } - #endif - guard connectionIntent.wantsConnection, - connectionState == .disconnected, - let deviceID = lastConnectedDeviceID else { return } - - if shouldDeferOpportunisticReconnect { - logger.info("[BLE] Bluetooth powered on: standing down (pairing in progress)") - return - } - - let blePhase = await stateMachine.linkDiagnostics.phase - let bleConnectedDeviceID = await stateMachine.connectedDeviceID - if blePhase != .idle || bleConnectedDeviceID == deviceID { - logger.info( - "[BLE] Bluetooth powered on: BLE already owns reconnect flow for \(deviceID.uuidString.prefix(8)) " + - "(phase: \(blePhase), bleConnectedDevice: \(bleConnectedDeviceID?.uuidString.prefix(8) ?? "none"))" - ) - return - } - - if activeReconnectDeviceID == deviceID { - logger.info("[BLE] Bluetooth powered on: reconnect/session rebuild already in progress for \(deviceID.uuidString.prefix(8))") - return - } - - if await shouldStandDownOpportunisticBluetoothReconnect(for: deviceID) { - return - } - - logger.info("[BLE] Bluetooth powered on: attempting reconnection to \(deviceID.uuidString.prefix(8))") - await attemptOpportunisticReconnect(deviceID: deviceID, reason: "Bluetooth powered on") - } - - /// Single chokepoint for opportunistic reconnect attempts. Consults the defer - /// predicate and dispatches to `connect(to:)`. New opportunistic-reconnect - /// sites must route through this helper rather than duplicating the gate logic. - /// The auto-reconnect-handler closure (`setAutoReconnectingHandler`) operates - /// on `.autoReconnecting` phases rather than initiating a `.connecting`, so it - /// applies the same gate predicate at its own call site instead. - /// - Parameters: - /// - deviceID: device to reconnect to. The caller is responsible for - /// vetting that the user wants this device connected before invoking. - /// - reason: short string for log correlation across call sites. - func attemptOpportunisticReconnect(deviceID: UUID, reason: String) async { - guard !shouldDeferOpportunisticReconnect else { - logger.info("[BLE] Opportunistic reconnect skipped (\(reason)): pairing in progress") - return - } - do { - try await connect(to: deviceID) - } catch { - logger.warning("[BLE] Opportunistic reconnect (\(reason)) failed: \(error.localizedDescription)") - // An invalidated bond can't be resolved by retrying in the background; - // route it to the same guided pairing-failure recovery a fresh connect - // attempt would show, rather than leaving the user on a silent watchdog loop. - if case BLEError.authenticationFailed = error { - surfaceAuthenticationFailure(deviceID: deviceID) - } - } - } - - /// Fires `onAuthenticationFailure` at most once per failure episode, tracked by - /// `surfacedAuthFailureDeviceID`. All auth-failure surfacing routes through here - /// so the latch covers every producer path. - func surfaceAuthenticationFailure(deviceID: UUID) { - guard surfacedAuthFailureDeviceID != deviceID else { - logger.info("[BLE] Pairing-failure recovery already surfaced for \(deviceID.uuidString.prefix(8)), suppressing repeat") - return - } - surfacedAuthFailureDeviceID = deviceID - onAuthenticationFailure?(deviceID) - } - - /// Clears the auth-failure surfacing latch so the next failure episode for the - /// same device re-presents the guided recovery. - public func clearSurfacedAuthenticationFailure() { - surfacedAuthFailureDeviceID = nil + isPairingInProgress || isPairingFlowActive || removalOperationID != nil } // MARK: - Callbacks @@ -230,15 +97,15 @@ public final class ConnectionManager { /// Called when connection is ready and services are available. /// Use this to wire up UI observation of services. /// Installed by `AppState` during initialization. - public var onConnectionReady: (() async -> Void)? + public var onConnectionReady: ((ConnectionSnapshot) async -> Void)? /// Called synchronously on entry into `.ready` so UI readiness precedes post-sync awaits. - public var onConnectionBecameUsable: (@MainActor () -> Void)? + public var onConnectionBecameUsable: (@MainActor (ConnectionSnapshot) -> Void)? /// Called when connection is lost (disconnection, BLE power off, etc). /// Use this to update UI state when services become unavailable. /// Installed by `AppState` during initialization. - public var onConnectionLost: (() async -> Void)? + public var onConnectionLost: ((ConnectionLossReceipt) async -> Void)? /// Called when a live link drops and iOS auto-reconnect begins; /// `connectionState` stays `.connecting` and `onConnectionLost` fires only if @@ -247,7 +114,7 @@ public final class ConnectionManager { /// wake window, so the Live Activity reflects the loss ahead of the heavy /// teardown work and before the app suspends. /// Installed by `AppState` during initialization. - public var onAutoReconnectStarted: (() async -> Void)? + public var onAutoReconnectStarted: ((ConnectionLossReceipt) async -> Void)? /// Called when a background reconnect attempt fails because the peer /// invalidated its bond. Use this to present guided pairing-failure recovery, @@ -259,7 +126,7 @@ public final class ConnectionManager { /// Called after a usable sync promotes the connection to `.ready`. /// The flag is clean contacts and clean channels from that result, so a partial channel pass is `.ready` with false. /// Installed by `AppState` during initialization. - public var onDeviceSynced: ((_ hasCleanRecipientData: Bool) async -> Void)? + public var onDeviceSynced: ((ConnectionSnapshot, _ hasCleanRecipientData: Bool) async -> Void)? /// Called when `clearPersistedConnection(for:)` clears the last-connected slot. /// Installed by `AppState` during initialization. @@ -299,18 +166,69 @@ public final class ConnectionManager { let modelContainer: ModelContainer private let defaults: UserDefaults private let lastConnectionStore: LastConnectionStore + + let textRulesURL: URL + public internal(set) var textRulesPreference: TextRulesPreference? + public internal(set) var isTextRulesLoading = true let transport: any iOSMeshTransport - var wifiTransport: WiFiTransport? - var session: MeshCoreSession? { + private(set) var wifiTransport: (any WiFiMeshTransport)? + private(set) var session: MeshCoreSession? { didSet { invalidatePowerOffIfReplaced(newSession: session) } } + var radioWiFiStates: [UUID: RadioWiFiState] = [:] + var pendingIdentityReconciliations: [UUID: IdentityImportReceipt] = [:] + #if DEBUG + var sessionClockForTesting: (any Clock)? + var testIdentityBeforeAdmission: (@MainActor @Sendable () async -> Void)? + var testIdentityBeforeSourceValidation: (@MainActor @Sendable () async -> Void)? + var testIdentityBeforeCommit: (@MainActor @Sendable () async -> Void)? + var testIdentityAfterCommit: (@MainActor @Sendable () async -> Void)? + #endif + var desiredRequest: ConnectionRequest? + var installedLink: ConnectionLink? + var currentLossReceipt: ConnectionLossReceipt? + var retirementTask: Task? + var retiringWorkers: [Task] = [] + var metadataCommitTask: Task? + var pairingOperationID: UUID? + var removalDeviceID: UUID? + var removalOperationID: UUID? + var resyncSlotID: UUID? + var channelRetrySlotID: UUID? + var heartbeatSlotID: UUID? + var wifiRecoverySlotID: UUID? + let makeWiFiTransport: @Sendable () -> any WiFiMeshTransport + + public var currentConnection: ConnectionSnapshot? { + installedLink?.snapshot + } + + public func isCurrent(generation: UUID, requestID: UUID) -> Bool { + installedLink?.generation == generation && desiredRequest?.id == requestID + } + + public func isCurrent(_ snapshot: ConnectionSnapshot) -> Bool { + installedLink?.generation == snapshot.generation && desiredRequest?.id == snapshot.requestID + } + + public func isCurrent(_ receipt: ConnectionLossReceipt) -> Bool { + desiredRequest?.id == receipt.requestID && installedLink == nil && currentLossReceipt?.id == receipt.id + } + + public func isCurrent(_ result: ConnectionResult) -> Bool { + switch result { + case let .operational(snapshot): isCurrent(snapshot) + case let .handoff(requestID): desiredRequest?.id == requestID + case .superseded, .cancelled: false + } + } + /// The in-flight power-off, if this manager still owns it. var powerOffOperation: PowerOffOperation? var powerOffCancelGeneration = 0 var powerOffCleanupToken: UUID? var connectionTeardownCount = 0 - var connectionTeardownWaiters: [CheckedContinuation] = [] /// Device discovery + system pairing-registry seam. Resolves to AccessorySetupKit on /// iOS, or an in-app CoreBluetooth scan picker on macOS "Designed for iPad". let pairing: any DevicePairingService @@ -326,7 +244,8 @@ public final class ConnectionManager { let stateMachine: any BLEStateMachineProtocol /// Coordinates iOS auto-reconnect lifecycle (timeouts, teardown, rebuild). - let reconnectionCoordinator = BLEReconnectionCoordinator() + let reconnectionCoordinator: BLEReconnectionCoordinator + let reconnectionClock: any Clock // MARK: - WiFi Reconnection @@ -370,13 +289,16 @@ public final class ConnectionManager { /// Task managing the resync retry loop var resyncTask: Task? + public internal(set) var radioCleanup: [UUID: RadioCleanup] = [:] + @ObservationIgnored var radioEraseTasks: [UUID: Task] = [:] + /// Task managing delayed channel-only retry after a partial channel phase. var channelRetryTask: Task? /// Callback when resync fails after all attempts (triggers "Sync Failed" pill) /// Note: @Sendable @MainActor ensures safe cross-isolation callback /// Installed by `ConnectionUIState.wireCallbacks`. - public var onResyncFailed: (@Sendable @MainActor () -> Void)? + public var onResyncFailed: (@Sendable @MainActor (ConnectionSnapshot) -> Void)? // MARK: - Circuit Breaker @@ -406,17 +328,12 @@ public final class ConnectionManager { static let pairingAdoptionMissingSessionDetail = "adoption rebuilt no session" static let pairingAdoptionTimedOutDetail = "adoption timed out" - /// Consecutive entries into `handleReconnectionFailure` while intent still wants a - /// connection that are allowed to preserve a live link (not radio handshakes — on the - /// auto-reconnect path the coordinator's first failed rebuild retries once before - /// reaching this funnel, so one unit can already cover two handshakes). Uses `<=` - /// comparison: N preserve attempts then sever on the (N+1)th wanting entry. - /// Exhaustion severs the link and leaves recovery to the ContinuousClock watchdog - /// (which only completes when the process is awake), so recovery waits until the - /// user foregrounds or another wake arrives — do not tighten lightly. + /// Allows this many consecutive recovery failures to preserve the live BLE link. + /// One failure can include two handshakes; exhaustion severs the link and waits + /// for the reconnect watchdog to run while the process is awake. static let maxRebuildFailuresPreservingLink = 3 - /// Count of consecutive intent-wanting rebuild failures into `handleReconnectionFailure`. + /// Count of consecutive intent-wanting rebuild failures into `finishBLERecoveryFailure`. /// Reset on every operational session via `recordConnectionSuccess`. var consecutiveRebuildFailures = 0 @@ -467,12 +384,6 @@ public final class ConnectionManager { logger.info("[BLE] Circuit breaker: → closed (connection succeeded)") } - /// Refills the rebuild-preserve budget after a successful device switch. - /// Sole production call site: `switchDevice` after `promoteToReady`. - func resetPreserveBudgetAfterDeviceSwitch() { - recordConnectionSuccess() - } - /// Epoch bumped by every `clearPersistedConnection` so a queued bond-refresh /// persist hop that already passed `shouldPersistBondRefresh` cannot write /// after a forget clears the shield. @@ -489,7 +400,13 @@ public final class ConnectionManager { /// Session IDs that need re-authentication after BLE reconnect. /// Populated by `handleBLEDisconnection()`, consumed by `rebuildSession()`. /// Empty after app restart, so rooms show "Tap to reconnect" instead of auto-connecting. - var sessionsAwaitingReauth: Set = [] + struct MembershipBatch { + let id: UUID + let radioID: UUID + var sessionIDs: Set + } + + var membershipBatch: MembershipBatch? // MARK: - Simulator Support @@ -521,18 +438,6 @@ public final class ConnectionManager { /// tests can complete without waiting on production backoff. var testWatchdogInitialDelay: Duration? - /// When set, `connectViaWiFi` records the attempt and returns this result - /// instead of opening a TCP socket. - var testWiFiConnectHandler: (@MainActor (String, UInt16) async throws -> Void)? - - var testWiFiConnectAttempts: [(host: String, port: UInt16)] = [] - - /// When set, `connectViaBluetooth` records the attempt and returns this result - /// instead of opening a Bluetooth connection. - var testBluetoothConnectHandler: (@MainActor (UUID) async throws -> Void)? - - var testBluetoothConnectAttempts: [UUID] = [] - /// When set, WiFi reconnect gives up after this duration instead of 30s. var testWiFiMaxReconnectDuration: Duration? @@ -543,13 +448,19 @@ public final class ConnectionManager { var testWiFiHeartbeatClock: (any Clock)? var testConnectionTeardownHandler: (@MainActor () async -> Void)? - var testConnectionTeardownWaiterCount = 0 + var testNotificationSystemOperations: NotificationService.SystemOperations? + var testConnectionSelectionHandler: (@MainActor (UUID) async throws -> Void)? + var testCandidateRetirementHandler: (@MainActor (SessionTransportBinding) async -> Void)? + var testAdmissionCancellationHandler: (@MainActor () async -> Void)? + var testAdmissionCancellationFinished = false + var testWiFiRecoveryEntryHandler: (@MainActor () async -> Void)? + var testMessageListenerRepairHandler: (@MainActor (UUID) async -> Void)? + var testPostSetupResultHandler: (@MainActor (UUID) async -> Void)? + var testBLELifecycleEventHandled: (@MainActor (BLELifecycleEvent) -> Void)? /// How many times the Bluetooth powered-on handler has run. var testBluetoothPoweredOnHandlerRuns = 0 - var testAutoReconnectEntryCompletions = 0 - /// Runs after `shouldPersistBondRefresh` returns true and before the epoch /// check in `persistBondRefreshIfStillValid` — tests force clear in that window. var bondRefreshPersistAfterShouldPersistHook: (@MainActor () async -> Void)? @@ -574,9 +485,6 @@ public final class ConnectionManager { var testPairingAdoptionSettleTimeout: Duration? - typealias HealthCheckSessionRebuildOverride = @MainActor (UUID) async throws -> Void - - var rebuildSessionForHealthCheckOverride: HealthCheckSessionRebuildOverride? #endif /// The last connected device ID (for auto-reconnect) @@ -611,10 +519,12 @@ public final class ConnectionManager { /// gates that link behind MITM-bonded encryption, so any successful exchange /// proves the bond. Never called on the WiFi path, which bypasses the bond. /// Also marks the app session live for RSSI bond-shield refresh (awaited). - func recordBondVerification(deviceID: UUID) async { - lastConnectionStore.persistBondVerification(deviceID: deviceID) - await stateMachine.recordBondVerification(deviceID: deviceID, at: Date()) - await stateMachine.setAppSessionLive(deviceID: deviceID) + func recordBondVerification(deviceID: UUID, binding: SessionTransportBinding) async { + do { + try binding.performIfActive { lastConnectionStore.persistBondVerification(deviceID: deviceID) } + } catch { return } + await stateMachine.recordBondVerification(deviceID: deviceID, at: Date(), sessionBinding: binding) + await stateMachine.setAppSessionLive(deviceID: deviceID, sessionBinding: binding) } /// Clears this device's bond verification without touching the last-connection slot. @@ -630,10 +540,14 @@ public final class ConnectionManager { /// Clears bond verification and, when `deviceID` holds it, the last-connection slot. func clearPersistedConnection(for deviceID: UUID) async { + await clearPersistedConnection(for: deviceID, notifyingRequestID: desiredRequest?.id) + } + + func clearPersistedConnection(for deviceID: UUID, notifyingRequestID: UUID?) async { let wasLastConnected = lastConnectionStore.deviceID == deviceID await clearBondVerification(for: deviceID) lastConnectionStore.clearLastConnection(for: deviceID) - if wasLastConnected { + if wasLastConnected, desiredRequest?.id == notifyingRequestID { onLastConnectedDeviceCleared?() } } @@ -680,14 +594,20 @@ public final class ConnectionManager { lastConnectedDeviceID == MockDataProvider.simulatorDeviceID } - /// Whether a WiFi disconnection is currently being handled (prevents interleaving - /// across await suspension points before wifiReconnectTask is set). - var isHandlingWiFiDisconnection = false + var wifiDisconnectionReceipt: ConnectionLossReceipt? + + var isHandlingWiFiDisconnection: Bool { + guard desiredRequest?.target.transportType == .wifi, + let wifiDisconnectionReceipt else { return false } + return isCurrent(wifiDisconnectionReceipt) + } // MARK: - Cancellation Helpers /// Cancels any in-progress WiFi reconnection attempts func cancelWiFiReconnection() { + if let wifiReconnectTask { retiringWorkers.append(wifiReconnectTask) } + wifiRecoverySlotID = nil wifiReconnectTask?.cancel() wifiReconnectTask = nil wifiReconnectAttempt = 0 @@ -706,12 +626,20 @@ public final class ConnectionManager { defaults: UserDefaults = .standard, stateMachine: (any BLEStateMachineProtocol)? = nil, transport: (any iOSMeshTransport)? = nil, - pairing: (any DevicePairingService)? = nil + pairing: (any DevicePairingService)? = nil, + reconnectionClock: (any Clock)? = nil, + makeWiFiTransport: @escaping @Sendable () -> any WiFiMeshTransport = { WiFiTransport() }, + textRulesURL: URL? = nil ) { self.modelContainer = modelContainer + self.makeWiFiTransport = makeWiFiTransport + let clock = reconnectionClock ?? ContinuousClock() + self.reconnectionClock = clock + reconnectionCoordinator = BLEReconnectionCoordinator(clock: clock) persistenceStore = PersistenceStore(modelContainer: modelContainer) self.defaults = defaults lastConnectionStore = LastConnectionStore(defaults: defaults) + self.textRulesURL = textRulesURL ?? Self.defaultTextRulesURL connectionIntent = .restored(from: defaults) // Use provided state machine or create default @@ -730,7 +658,7 @@ public final class ConnectionManager { self.pairing = pairing ?? DevicePairingFactory.make() self.pairing.delegate = self - reconnectionCoordinator.delegate = self + wireReconnectPolicy() // Best-effort early wiring. activate() awaits the same idempotent // method before constructing the CBCentralManager, which is the @@ -750,117 +678,14 @@ public final class ConnectionManager { let stateMachine = stateMachine let transport = transport - // Handle disconnection events - await transport.setDisconnectionHandler { [weak self] deviceID, error in - Task { @MainActor in - guard let self else { return } - await self.handleConnectionLoss(deviceID: deviceID, error: error) - } - } - - await stateMachine.setRemoteLinkLostHandler { [weak self] deviceID, eventTime in - Task { @MainActor in - self?.notePowerOffRemoteLoss(deviceID: deviceID, eventTime: eventTime) - } + await transport.setLifecycleHandler { [weak self] event in + Task { @MainActor in await self?.handleBLELifecycleEvent(event) } } - - // A bond verified in a previous launch must still shield an exhausted - // encryption-timeout budget, so seed the persisted verification before - // any teardown classification can run. Keyed off the bond slot, not the - // connection slot: a WiFi connection overwrites the latter without - // touching the bond. if let deviceID = lastConnectionStore.bondVerifiedDeviceID, let verified = lastConnectionStore.bondVerificationDate(for: deviceID) { await stateMachine.recordBondVerification(deviceID: deviceID, at: verified) } - // Handle entering auto-reconnecting phase - await stateMachine.setAutoReconnectingHandler { [weak self] (deviceID: UUID, errorInfo: String) in - Task { @MainActor in - guard let self else { return } - #if DEBUG - defer { self.testAutoReconnectEntryCompletions += 1 } - #endif - guard !self.powerOffSuppressesReconnect(for: deviceID) else { - self.logger.info("[BLE] Auto-reconnect suppressed during power-off for \(deviceID.uuidString.prefix(8))") - return - } - - if self.shouldDeferOpportunisticReconnect { - self.logger.info( - "[BLE] Auto-reconnect entry suppressed for \(deviceID.uuidString.prefix(8)) (pairing in progress) — tearing down stale session" - ) - // Skip the reconnect-cycle claim and UI timeout (pairing's - // connect(to:) ceremony owns the next state transitions), - // but tear down the prior session so a pairing early-exit - // path doesn't strand the UI on stale `.ready` state. - await self.handleConnectionLoss(deviceID: deviceID, error: nil) - return - } - - if let manualConnectDeviceID = self.connectingDeviceID { - guard manualConnectDeviceID == deviceID else { - self.logger.info( - "[BLE] Auto-reconnect entry for \(deviceID.uuidString.prefix(8)) standing down: manual connect in flight for \(manualConnectDeviceID.uuidString.prefix(8))" - ) - return - } - // The dropped link belongs to the in-flight manual connect. Release - // its claim so the retry loop bails out instead of disconnecting the - // transport — that would cancel the OS pending connect recovering - // this link and leave a reconnect-cycle claim no completion can ever - // clear, silently disabling the watchdog, the foreground health - // check, and power-on recovery. The cycle claimed below owns - // teardown, the UI timeout, and the session rebuild from here. - self.logger.info("[BLE] Auto-reconnect entry adopting in-flight manual connect for \(deviceID.uuidString.prefix(8))") - self.connectingDeviceID = nil - } - - // Snapshot pre-claim state before entering — handleEnteringAutoReconnect - // mutates connectionState to .connecting before its first await. - let initialState = String(describing: self.connectionState) - let transportName = switch self.currentTransportType { - case .bluetooth: "bluetooth" - case .wifi: "wifi" - case nil: "none" - } - - // Claim before the state-machine queries below. Without this, - // a state-restoration adoption where iOS callbacks land within - // microseconds of each other can fire onReconnection while these - // awaits are still queued, and the strict completion guard would - // drop the completion since reconnectingDeviceID is still nil. - await self.reconnectionCoordinator.handleEnteringAutoReconnect(deviceID: deviceID) - - let diagnostics = await self.stateMachine.linkDiagnostics - let bleState = diagnostics.centralState - let blePhase = diagnostics.phase - let blePeripheralState = diagnostics.peripheralState ?? "none" - - self.persistDisconnectDiagnostic( - "source=bleStateMachine.autoReconnectingHandler, " + - "device=\(deviceID.uuidString.prefix(8)), " + - "transport=\(transportName), " + - "initialState=\(initialState), " + - "bleState=\(bleState), " + - "blePhase=\(blePhase), " + - "blePeripheralState=\(blePeripheralState), " + - "error=\(errorInfo), " + - "intent=\(self.connectionIntent)" - ) - } - } - - // Handle iOS auto-reconnect completion - // Using transport.setReconnectionHandler ensures the transport captures - // the data stream internally before calling our handler - await transport.setReconnectionHandler { [weak self] deviceID in - Task { @MainActor in - guard let self else { return } - await self.reconnectionCoordinator.handleReconnectionComplete(deviceID: deviceID) - } - } - // RSSI bond refresh runs on the state-machine actor; persist on MainActor // via epoch-gated re-validation so a clear between shouldPersist and the // UserDefaults write cannot resurrect a forgotten cross-launch shield. @@ -887,476 +712,14 @@ public final class ConnectionManager { } } - // MARK: - Session Helpers - - /// Starts a session and queries device capabilities. - func initializeSession( - _ session: MeshCoreSession - ) async throws -> (SelfInfo, DeviceCapabilities) { - do { - try await withTimeout(.seconds(10), operationName: "session.start") { - try await session.start() - } - } catch { - logger.warning("[BLE] session.start() timed out or failed: \(error.localizedDescription)") - throw error - } - - guard let selfInfo = await session.currentSelfInfo else { - logger.warning("[BLE] selfInfo is nil after session.start()") - throw ConnectionError.initializationFailed("Failed to get device self info") - } - do { - let capabilities = try await withTimeout(.seconds(10), operationName: "queryDevice") { - try await session.queryDevice() - } - return (selfInfo, capabilities) - } catch { - logger.warning("[BLE] queryDevice() timed out or failed: \(error.localizedDescription)") - throw error - } - } - - // MARK: - Service Wiring Helpers - - /// Wires the clean-channel-sync callback on a new ServiceContainer so that - /// `lastCleanChannelSync` is updated when a channel phase completes without errors. - /// Called from every path that creates a new ServiceContainer. - func wireCleanChannelSyncCallback(on services: ServiceContainer) async { - await services.syncCoordinator.setCleanChannelSyncCallback { [weak self] radioID in - await MainActor.run { - self?.lastCleanChannelSync = (radioID: radioID, completedAt: Date()) - } - } - await services.syncCoordinator.setChannelSyncAttemptedCallback { [weak self] radioID in - await MainActor.run { - self?.lastAttemptedChannelSync = (radioID: radioID, attemptedAt: Date()) - } - } - } - - // MARK: - Connection Ceremony - - /// Builds a fresh ServiceContainer, fetches device configuration from the radio - /// and database, builds and persists the device record, and updates self. - /// - /// Each connection path (BLE, WiFi, reconnect, device switch) calls this after - /// its transport and session are established. Post-ceremony work (sync, promote, - /// cleanup) remains in each caller since it genuinely varies. - /// - /// - Returns: The wired `ServiceContainer` for the caller's sync phase. - func buildServicesAndSaveDevice( - deviceID: UUID, - session: MeshCoreSession, - selfInfo: SelfInfo, - capabilities: DeviceCapabilities, - connectionMethods: [ConnectionMethod] = [], - connectionAttemptID: UUID? = nil - ) async throws -> (services: ServiceContainer, radioID: UUID) { - // Kick off `getAutoAddConfig` up-front so the BLE roundtrip overlaps - // with the local DB fetches and container wiring below. - async let autoAddConfigResult = session.getAutoAddConfig() - - // Resolve the radio before constructing the container so the - // chat send queue can scope its `PendingSend` hydration to the - // right radio from frame zero. Falls back to publicKey lookup - // (backup import) and finally to a fresh UUID for first-time - // pairings. - let existingDevice = try? await persistenceStore.fetchDevice(id: deviceID) - let deviceByPublicKey: DeviceDTO? = if existingDevice == nil { - try? await persistenceStore.fetchDevice(publicKey: selfInfo.publicKey) - } else { - nil - } - let effectiveExisting = existingDevice ?? deviceByPublicKey - let resolvedRadioID = effectiveExisting?.radioID ?? UUID() - - let newServices = ServiceContainer( - session: session, - dataStore: persistenceStore, - radioID: resolvedRadioID, - appStateProvider: appStateProvider, - connectionStateEvents: connectionStateEvents, - initialConnectionState: connectionState - ) - await wireCleanChannelSyncCallback(on: newServices) - await newServices.nodeConfigService.setOnPostIdentityImport { [weak self, weak newServices] in - guard let self, let services = newServices else { return nil } - return try await reconcileIdentity(expectedServices: services, deviceID: deviceID) - } - - let autoAddConfig = await (try? autoAddConfigResult) ?? MeshCore.AutoAddConfig(bitmask: 0) - - let repeatFreqRanges: [MeshCore.FrequencyRange] = await capabilities.clientRepeat - ? (try? session.getRepeatFreq()) ?? [] - : [] - - let device = createDevice( - deviceID: deviceID, - radioID: resolvedRadioID, - selfInfo: selfInfo, - capabilities: capabilities, - autoAddConfig: autoAddConfig, - existingDevice: effectiveExisting, - connectionMethods: connectionMethods - ) - - let deviceDTO = DeviceDTO(from: device) - // Persist before warmUp so purgeOrphanPendingSends sees the in-progress - // radio's Device row and does not classify its PendingSends as orphans. - try await newServices.dataStore.saveDevice(deviceDTO) - - // Clean up orphaned Device row from backup import - if let oldDevice = deviceByPublicKey, oldDevice.id != deviceID { - try? await newServices.dataStore.deleteDevice(id: oldDevice.id) - } - - // Run startup-time DB hygiene before hydrating the send queue. - // warmUp's inner operations (purgeOrphanPendingSends and - // purgeLegacyAttemptCountRows) are best-effort; failure is non-fatal. - do { - try await newServices.warmUp() - } catch { - logger.warning("ServiceContainer.warmUp failed: \(error.localizedDescription)") - } - - // Hydrate the chat send queue before exposing the container so - // view-model `configure` calls see a hydrated service from the - // first read. - await newServices.chatSendQueueService.hydrate() - - if let connectionAttemptID, - !ownsConnectionAttempt(deviceID: deviceID, attemptID: connectionAttemptID) { - await newServices.tearDown() - throw CancellationError() - } - - // Restore `self.session` together with `self.services`: an interleaved - // `handleConnectionLoss` nils both atomically, and `promoteToReady`'s - // state invariants require both. - self.session = session - services = newServices - - connectedDevice = deviceDTO - allowedRepeatFreqRanges = repeatFreqRanges - - return (newServices, deviceDTO.radioID) - } - - // MARK: - Ready Promotion - - /// Promotes connection to `.ready` if the connection is still alive and owned by the expected services. - /// Skips post-sync work (time sync, timezone, onDeviceSynced) when sync failed to avoid BLE pressure. - /// Returns `true` if `.ready` was set, `false` if promotion was suppressed. - /// - /// - Parameter additionalGuard: Caller-specific invariant checked at every guard point, - /// including after async operations like `syncDeviceTimeIfNeeded()`. This cannot be an - /// inline check at the call site because the invariant must hold both before and after - /// the internal awaits — a competing reconnect cycle could start during time sync, - /// and promoting a stale session to `.ready` would shadow the new one. - /// Currently only `rebuildSession` uses this (reconnect-generation check). - @discardableResult - func promoteToReady( - syncResult: FullSyncResult?, - expectedServices: ServiceContainer, - transportType: TransportType, - additionalGuard: (() -> Bool)? = nil - ) async -> Bool { - let syncSucceeded = syncResult?.isConnectionUsable == true - func canPromote(_ phase: String) -> Bool { - guard connectionIntent.wantsConnection else { - logger.warning("Promotion suppressed\(phase): user disconnected") - return false - } - guard services === expectedServices else { - logger.warning("Promotion suppressed\(phase): services replaced or nil") - return false - } - guard additionalGuard?() ?? true else { - logger.warning("Promotion suppressed\(phase): caller guard failed (e.g. reconnect generation)") - return false - } - return true - } - guard canPromote("") else { return false } - - currentTransportType = transportType - connectionState = syncSucceeded ? .ready : .syncing - surfacedAuthFailureDeviceID = nil - - // Skip time sync on BLE failure to avoid pressure on a saturated link. - // WiFi/TCP has no such constraint, so always correct the clock there. - if syncSucceeded || transportType == .wifi { - await syncDeviceTimeIfNeeded() - guard canPromote(" after time sync") else { return false } - - await RadioTimezone.syncIfNeeded( - supportsRadioCLI: connectedDevice?.supportsRadioCLI == true, - secondsFromGMT: TimeZone.current.secondsFromGMT(), - settings: expectedServices.settingsService, - stillCurrent: { [weak self] in - guard let self else { return false } - return self.services === expectedServices - } - ) - guard canPromote(" after timezone sync") else { return false } - } - - if syncSucceeded { - await onDeviceSynced?(syncResult?.hasCleanRecipientData == true) - guard canPromote(" after device sync callback") else { return false } - } - return true - } - - /// Re-evaluates the connected device's identity after `NodeConfigService.importIdentity` - /// has restored a privateKey on the radio. If the radio is now reporting a different - /// `publicKey` than the local Device row, attempts to reconcile against any ghost - /// carrying that publicKey (left by a prior "remove from MC1"). - /// - /// Mirrors the `promoteToReady` lifecycle pattern: takes the `ServiceContainer` - /// the caller expects to still own, plus the `deviceID` it expects to still be - /// connected to. Bails out (returns `nil`) if either invariant fails before or - /// after the `currentSelfInfo` await — a competing reconnect cycle could otherwise - /// reconcile state onto the wrong connection. - /// - /// - Parameters: - /// - expectedServices: The `ServiceContainer` captured at the start of the - /// config-import operation. If `self.services` no longer points to it, the - /// reconcile is silently skipped. - /// - deviceID: The connected row's `Device.id`. - /// - Returns: The new `radioID` if reconciliation reassigned the device, - /// otherwise `nil` (no publicKey change, no matching ghost, or a guard tripped). - @discardableResult - public func reconcileIdentity( - expectedServices: ServiceContainer, - deviceID: UUID - ) async throws -> UUID? { - guard services === expectedServices else { - logger.info("reconcileIdentity skipped: services replaced before currentSelfInfo") - return nil - } - guard let preDevice = connectedDevice, preDevice.id == deviceID else { - logger.info("reconcileIdentity skipped: connectedDevice changed before currentSelfInfo") - return nil - } - let previousSelfPublicKey = preDevice.publicKey - let previousRadioID = preDevice.radioID - - let selfInfo: MeshCore.SelfInfo - do { - guard let info = await expectedServices.session.currentSelfInfo else { - logger.warning("reconcileIdentity failed: session.currentSelfInfo is nil") - return nil - } - selfInfo = info - } - - guard services === expectedServices else { - logger.info("reconcileIdentity skipped: services replaced after currentSelfInfo") - return nil - } - guard connectedDevice?.id == deviceID else { - logger.info("reconcileIdentity skipped: connectedDevice changed after currentSelfInfo") - return nil - } - - // No publicKey-equality short-circuit: after a partial-import + app restart, - // `buildServicesAndSaveDevice` finds the Device by BLE UUID and overwrites - // `Device.publicKey` with the restored key via `Device.apply(dto:)`. On the - // user's retry, `selfInfo.publicKey == connectedDevice.publicKey` even though - // `radioID` is still stale. Always ask `reconcileGhostIdentity` — its - // predicate handles the no-ghost case by returning nil, so the cost of an - // unconditional query is one cheap DB lookup per import. - - let newRadioID: UUID? - do { - newRadioID = try await expectedServices.dataStore.reconcileGhostIdentity( - currentDeviceID: deviceID, - newPublicKey: selfInfo.publicKey - ) - } catch { - logger.warning("reconcileIdentity: reconcileGhostIdentity failed: \(error.localizedDescription)") - return nil - } - - // Drop the local ZephCore V-contact derived from the previous self key when - // identity rotates; the new V-key arrives on the next contact sync. It was synced - // under the pre-reconcile partition, and ghost reconciliation re-keys only the - // Device row, never contacts, so it always lives under previousRadioID. - if previousSelfPublicKey != selfInfo.publicKey { - await dropStaleVContact( - dataStore: expectedServices.dataStore, - radioID: previousRadioID, - oldSelfPublicKey: previousSelfPublicKey - ) - } - - guard let newRadioID else { - logger.info("reconcileIdentity: publicKey changed but no ghost matched") - return nil - } - - // Final guard: the DB save just ran on a background actor; the connection - // could still have churned. Only mutate live state if the captured container - // is still authoritative. - guard services === expectedServices, connectedDevice?.id == deviceID else { - logger.info("reconcileIdentity: state churned after DB save; skipping in-memory refresh") - return newRadioID - } - if let refreshed = try? await expectedServices.dataStore.fetchDevice(id: deviceID), - services === expectedServices, - connectedDevice?.id == deviceID { - connectedDevice = refreshed - persistConnection( - deviceID: refreshed.id, - radioID: refreshed.radioID, - deviceName: refreshed.nodeName - ) - } - - logger.info("Reconciled identity to ghost radioID after key import: \(newRadioID)") - return newRadioID - } - - /// Removes a local contact row for the V-contact derived from a retired self public key. - private func dropStaleVContact( - dataStore: PersistenceStore, - radioID: UUID, - oldSelfPublicKey: Data - ) async { - guard let oldVKey = VContactIdentity.publicKey(forSelfPublicKey: oldSelfPublicKey) else { return } - do { - guard let contact = try await dataStore.fetchContact(radioID: radioID, publicKey: oldVKey) else { - return - } - try await dataStore.deleteContact(id: contact.id) - logger.info("Dropped stale ZephCore V-contact after identity rotation") - } catch { - logger.warning("Failed to drop stale V-contact after identity rotation: \(error.localizedDescription)") - } - } - - /// Setting the radio clock backward makes its request timestamps fall below - /// the `last_timestamp` remote repeaters recorded for it, and their replay - /// protection then silently drops every packet until the clock re-passes the - /// stored value. A tight tolerance keeps each backward step, and therefore - /// each deaf window, no longer than the tolerance itself, while still - /// recovering radios whose clocks are stuck far in the future. - private static let deviceClockDriftTolerance: TimeInterval = 5 - - /// Syncs the device clock when it drifts beyond `deviceClockDriftTolerance`. - func syncDeviceTimeIfNeeded() async { - guard let session else { return } - do { - let deviceTime = try await withTimeout(.seconds(5), operationName: "getTime") { - try await session.getTime() - } - let timeDifference = abs(deviceTime.timeIntervalSinceNow) - if timeDifference > Self.deviceClockDriftTolerance { - try await withTimeout(.seconds(5), operationName: "setTime") { - try await session.setTime(Date()) - } - logger.info("Synced device time (was off by \(Int(timeDifference))s)") - } else { - logger.info("Device time in sync (drift: \(Int(timeDifference))s)") - } - } catch { - logger.warning("Failed to sync device time: \(error.localizedDescription)") - } - } - - /// Creates a Device from MeshCore types - /// - /// `radioID` is the resolved partition UUID for this device. Callers in - /// the connect path must pass the same UUID they used to construct - /// `ServiceContainer(radioID:)` so the chat send queue's `PendingSend` - /// scope and the persisted `Device.radioID` cannot diverge on first pair. - /// A bare `?? UUID()` fallback here would mint a second UUID that the - /// container would never see. - func createDevice( - deviceID: UUID, - radioID: UUID, - selfInfo: MeshCore.SelfInfo, - capabilities: MeshCore.DeviceCapabilities, - autoAddConfig: MeshCore.AutoAddConfig, - existingDevice: DeviceDTO? = nil, - connectionMethods: [ConnectionMethod] = [] - ) -> Device { - // Merge new connection methods with existing ones, replacing by transport type - var mergedMethods = ConnectionMethod.canonicalized(existingDevice?.connectionMethods ?? []) - for method in connectionMethods { - if method.isWiFi { - mergedMethods.removeAll { $0.isWiFi } - } else if method.isBluetooth { - mergedMethods.removeAll { $0.isBluetooth } - } - mergedMethods.append(method) - } - - let device = Device( - id: deviceID, - radioID: radioID, - publicKey: selfInfo.publicKey, - nodeName: selfInfo.name, - firmwareVersion: capabilities.firmwareVersion, - firmwareVersionString: capabilities.version, - manufacturerName: capabilities.model, - buildDate: capabilities.firmwareBuild, - maxContacts: UInt16(capabilities.maxContacts), - maxChannels: UInt8(min(capabilities.maxChannels, 255)), - frequency: UInt32(selfInfo.radioFrequency * 1000), // Convert MHz to kHz - bandwidth: UInt32(selfInfo.radioBandwidth * 1000), // Convert kHz to Hz - spreadingFactor: selfInfo.radioSpreadingFactor, - codingRate: selfInfo.radioCodingRate, - txPower: selfInfo.txPower, - maxTxPower: selfInfo.maxTxPower, - latitude: selfInfo.latitude, - longitude: selfInfo.longitude, - blePin: capabilities.blePin, - clientRepeat: capabilities.clientRepeat, - pathHashMode: capabilities.pathHashMode, - defaultFloodScopeName: existingDevice?.defaultFloodScopeName, - preRepeatFrequency: existingDevice?.preRepeatFrequency, - preRepeatBandwidth: existingDevice?.preRepeatBandwidth, - preRepeatSpreadingFactor: existingDevice?.preRepeatSpreadingFactor, - preRepeatCodingRate: existingDevice?.preRepeatCodingRate, - manualAddContacts: selfInfo.manualAddContacts, - autoAddConfig: autoAddConfig.bitmask, - autoAddMaxHops: autoAddConfig.maxHops, - multiAcks: selfInfo.multiAcks, - telemetryModeBase: selfInfo.telemetryModeBase, - telemetryModeLoc: selfInfo.telemetryModeLocation, - telemetryModeEnv: selfInfo.telemetryModeEnvironment, - advertLocationPolicy: selfInfo.advertisementLocationPolicy, - lastConnected: Date(), - lastContactSync: existingDevice?.lastContactSync ?? 0, - isActive: true, - ocvPreset: existingDevice?.ocvPreset - ?? OCVPreset.preset(forManufacturer: capabilities.model)?.rawValue, - appliedRadioPresetID: existingDevice?.appliedRadioPresetID, - customOCVArrayString: existingDevice?.customOCVArrayString, - connectionMethods: mergedMethods, - knownRegions: existingDevice?.knownRegions ?? [] - ) - - // If repeat mode was disabled externally, clear orphaned pre-repeat settings - if !capabilities.clientRepeat, existingDevice?.preRepeatFrequency != nil { - device.preRepeatFrequency = nil - device.preRepeatBandwidth = nil - device.preRepeatSpreadingFactor = nil - device.preRepeatCodingRate = nil - } - - return device - } - /// Configures BLE write pacing based on detected device platform. /// - Parameter capabilities: The device capabilities from queryDevice() - func configureBLEPacing(for capabilities: MeshCore.DeviceCapabilities) async { - detectAndStorePlatform(model: capabilities.model, transportType: .bluetooth) + func configureBLEPacing(for capabilities: MeshCore.DeviceCapabilities, binding: SessionTransportBinding) async { + do { + try binding.performIfActive { detectAndStorePlatform(model: capabilities.model, transportType: .bluetooth) } + } catch { return } let pacing = detectedPlatform.recommendedWritePacing - await stateMachine.setWritePacingDelay(pacing) + await stateMachine.setWritePacingDelay(pacing, sessionBinding: binding) if pacing > 0 { logger.info("[BLE] Platform detected: \(capabilities.model) -> \(detectedPlatform), write pacing: \(pacing)s") } @@ -1384,37 +747,79 @@ public final class ConnectionManager { } } - // MARK: - Cleanup + // MARK: - Persisted Intent and Diagnostics - /// Cleans up session and services without changing connection state (used during retries) - func cleanupResources() async { - // Default stop() closes the shared transport, so teardown stays held until that close finishes. - beginConnectionTeardown() - defer { endConnectionTeardown() } - let oldSession = session - let oldServices = services - session = nil - services = nil - await oldSession?.stop() - await oldServices?.tearDown() + func persistDisconnectDiagnostic(_ summary: String) { + lastConnectionStore.persistDisconnectDiagnostic(summary) } - /// Full cleanup including state reset (used on explicit disconnect) - func cleanupConnection() async { - logger.info("[BLE] cleanupConnection: state → .disconnected") - connectionState = .disconnected - connectingDeviceID = nil + func persistIntent() { + connectionIntent.persist(to: defaults) + } + + // MARK: - Owned Publication + + func publish(_ link: ConnectionLink, repeatRanges: [MeshCore.FrequencyRange]) throws { + guard desiredRequest?.id == link.requestID, link.resource.binding.isActive else { + logLifecycle("publicationRejected", context: lifecycleContext(request: nil, attempt: nil, link: link), reason: "requestOrBinding") + throw CancellationError() + } + currentLossReceipt = nil + installedLink = link + session = link.resource.session + services = link.services + connectedDevice = link.device + currentTransportType = link.target.transportType + wifiTransport = link.resource.wifi + allowedRepeatFreqRanges = repeatRanges + connectionState = .syncing + identityRebuildUnpublished = false + logLifecycle("published", context: lifecycleContext(request: desiredRequest, attempt: desiredRequest?.attempt, link: link)) + } + + func publishPending(_ request: ConnectionRequest, phase: DeviceConnectionState) { + guard desiredRequest === request, installedLink == nil else { + logLifecycle("publicationRejected", context: lifecycleContext(request: request, attempt: request.attempt, link: nil), reason: "requestOrInstalledLink") + return + } + if phase == .disconnected { identityRebuildUnpublished = false } + currentTransportType = phase == .disconnected ? nil : request.target.transportType + connectionState = phase + } + + @discardableResult + func detachPublication(phase: DeviceConnectionState) -> ConnectionLink? { + if phase == .disconnected { identityRebuildUnpublished = false } + let old = installedLink + installedLink = nil + session = nil + services = nil connectedDevice = nil + wifiTransport = nil + currentTransportType = nil allowedRepeatFreqRanges = [] - await cleanupResources() + connectionState = phase + return old } - func persistDisconnectDiagnostic(_ summary: String) { - lastConnectionStore.persistDisconnectDiagnostic(summary) + func transition(_ link: ConnectionLink, to state: DeviceConnectionState) { + guard installedLink === link, desiredRequest?.id == link.requestID else { + logLifecycle("transitionRejected", context: lifecycleContext(request: nil, attempt: nil, link: link), reason: "requestOrLink") + return + } + connectionState = state } - func persistIntent() { - connectionIntent.persist(to: defaults) + func setPublishedDevice(_ device: DeviceDTO) { + guard let link = installedLink else { + #if DEBUG + connectedDevice = device + #endif + return + } + guard device.id == link.device.id else { return } + link.device = device + connectedDevice = device } // MARK: - State Invariants @@ -1438,6 +843,18 @@ public final class ConnectionManager { } #endif + func makeBoundSession(transport: any MeshTransport, scope: RadioCLICorrelationScope) -> MeshCoreSession { + let clock: (any Clock)? + #if DEBUG + clock = sessionClockForTesting + #else + clock = nil + #endif + return MeshCoreSession( + transport: transport, configuration: .default, clock: clock, radioCLICorrelationScope: scope + ) + } + // MARK: - Test Helpers #if DEBUG @@ -1454,6 +871,7 @@ public final class ConnectionManager { session: MeshCoreSession?? = nil, connectedDevice: DeviceDTO?? = nil, currentTransportType: TransportType?? = nil, + wifiTransport: (any WiFiMeshTransport)?? = nil, connectionIntent: ConnectionIntent? = nil, connectingDeviceID: UUID?? = nil, sessionRebuildDeviceID: UUID?? = nil, @@ -1461,7 +879,8 @@ public final class ConnectionManager { isPairingFlowActive: Bool? = nil, detectedPlatform: DevicePlatform? = nil, lastCleanChannelSync: (radioID: UUID, completedAt: Date)?? = nil, - lastAttemptedChannelSync: (radioID: UUID, attemptedAt: Date)?? = nil + lastAttemptedChannelSync: (radioID: UUID, attemptedAt: Date)?? = nil, + identityRebuildUnpublished: Bool? = nil ) { suppressInvariantChecks = true defer { suppressInvariantChecks = false } @@ -1481,14 +900,22 @@ public final class ConnectionManager { if let transport = currentTransportType { self.currentTransportType = transport } + if let socket = wifiTransport { self.wifiTransport = socket } if let intent = connectionIntent { self.connectionIntent = intent } if let deviceID = connectingDeviceID { - self.connectingDeviceID = deviceID + if let deviceID { + desiredRequest = ConnectionRequest( + targets: [.bluetooth(deviceID)], origin: .explicit, forceFullSync: false, forceReconnect: false, + continuing: nil + ) + } else if installedLink == nil { + desiredRequest = nil + } } - if let deviceID = sessionRebuildDeviceID { - self.sessionRebuildDeviceID = deviceID + if let deviceID = sessionRebuildDeviceID, let deviceID, let request = desiredRequest { + _ = reconnectionCoordinator.begin(deviceID: deviceID, requestID: request.id) } if let pairing = isPairingInProgress { self.isPairingInProgress = pairing @@ -1499,12 +926,32 @@ public final class ConnectionManager { if let platform = detectedPlatform { self.detectedPlatform = platform } + if services != nil || session != nil || connectedDevice != nil || wifiTransport != nil, + let liveSession = self.session, let liveServices = self.services, let device = self.connectedDevice { + let target: ConnectionRequest.Target = self.currentTransportType == .wifi ? .wifi(host: "test", port: 5000) : .bluetooth(device.id) + let request = desiredRequest ?? ConnectionRequest( + targets: [target], origin: .explicit, forceFullSync: false, forceReconnect: false, continuing: nil + ) + desiredRequest = request + let physical: any MeshTransport = if let socket = self.wifiTransport { socket } else { self.transport } + let resource = ConnectionResource( + binding: SessionTransportBinding(), transport: physical, session: liveSession, wifi: self.wifiTransport, + ble: self.wifiTransport == nil ? self.transport : nil + ) + installedLink = ConnectionLink(requestID: request.id, target: target, resource: resource, services: liveServices, device: device) + request.committedGeneration = installedLink?.generation + } else if services != nil || session != nil || connectedDevice != nil { + installedLink = nil + } if let cleanSync = lastCleanChannelSync { self.lastCleanChannelSync = cleanSync } if let attemptedSync = lastAttemptedChannelSync { self.lastAttemptedChannelSync = attemptedSync } + if let identityRebuildUnpublished { + self.identityRebuildUnpublished = identityRebuildUnpublished + } } #endif } diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionRemovalContext.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionRemovalContext.swift new file mode 100644 index 0000000000..bcc160dd67 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionRemovalContext.swift @@ -0,0 +1,23 @@ +import Foundation + +/// Captures a removal subject and the request that may retire its connection. +public struct ConnectionRemovalContext: Sendable { + let identity: ConnectionDeviceIdentity + let deviceID: UUID + let requestID: UUID? + let generation: UUID? + + init(deviceID: UUID, device: DeviceDTO?, requestID: UUID?, generation: UUID?) { + self.deviceID = deviceID + identity = device.map(ConnectionDeviceIdentity.init) ?? ConnectionDeviceIdentity(deviceID: deviceID) + self.requestID = requestID + self.generation = generation + } + + init(deviceID: UUID, identity: ConnectionDeviceIdentity, requestID: UUID?, generation: UUID?) { + self.deviceID = deviceID + self.identity = identity + self.requestID = requestID + self.generation = generation + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionRemovalResult.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionRemovalResult.swift new file mode 100644 index 0000000000..47542648d8 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionRemovalResult.swift @@ -0,0 +1,6 @@ +/// Removing a failed pairing advances its caller only after confirmed, owned removal. +public enum ConnectionRemovalResult: Sendable { + case removed(ConnectionLossReceipt) + case cancelled + case superseded +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionRequest.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionRequest.swift new file mode 100644 index 0000000000..1f0a8b863d --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionRequest.swift @@ -0,0 +1,79 @@ +import Foundation +import MeshCore + +@MainActor +final class ConnectionRequest { + enum Target: Equatable { + case bluetooth(UUID) + case wifi(host: String, port: UInt16) + case simulator + case disconnected + + var deviceID: UUID? { + if case let .bluetooth(id) = self { return id } + if case .simulator = self { return MockDataProvider.simulatorDeviceID } + return nil + } + + var transportType: TransportType { + if case .wifi = self { return .wifi } + return .bluetooth + } + + var method: ConnectionMethod? { + switch self { + case let .bluetooth(id): .bluetooth(peripheralUUID: id, displayName: nil) + case let .wifi(host, port): .wifi(host: host, port: port, displayName: nil) + case .simulator, .disconnected: nil + } + } + } + + enum Origin { + case explicit + case pairing + case launch + case recovery + case simulator + } + + let id = UUID() + let radioCLICorrelationScope = RadioCLICorrelationScope() + let admittedAt = CFAbsoluteTimeGetCurrent() + let targets: [Target] + let origin: Origin + var forceFullSync: Bool + let forceReconnect: Bool + var targetIndex = 0 + var attempt: ConnectionAttempt? + var binding: SessionTransportBinding? { + attempt?.binding + } + + /// Binding the admission worker installed. Caller cancellation revokes this binding. + var admissionBinding: SessionTransportBinding? + + var worker: Task? + var committedGeneration: UUID? + var physicalOrigin: BLELifecycleOrigin? + var handedOff = false + var removedIdentities: [ConnectionDeviceIdentity] + + var target: Target { + targets[targetIndex] + } + + init( + targets: [Target], origin: Origin, forceFullSync: Bool, forceReconnect: Bool, + continuing previous: ConnectionRequest? + ) { + precondition(!targets.isEmpty) + self.targets = targets + self.origin = origin + self.forceFullSync = forceFullSync + self.forceReconnect = forceReconnect + // Recovery may replace its request while continuing the same user choice. + // Removed identities remain excluded until a fresh choice is admitted. + removedIdentities = previous?.removedIdentities ?? [] + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionRequestFailure.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionRequestFailure.swift new file mode 100644 index 0000000000..1cf8fec45c --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionRequestFailure.swift @@ -0,0 +1,10 @@ +import Foundation + +/// A domain failure can affect the caller only while this request still owns the manager. +public struct ConnectionRequestFailure: LocalizedError { + public let requestID: UUID + public let underlying: any Error + public var errorDescription: String? { + underlying.localizedDescription + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionResource.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionResource.swift new file mode 100644 index 0000000000..bc0d19c1a8 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionResource.swift @@ -0,0 +1,66 @@ +import MeshCore + +/// Captures the physical owner and session so retirement never looks up a successor. +@MainActor +final class ConnectionResource { + let binding: SessionTransportBinding + let transport: any MeshTransport + let session: MeshCoreSession + let wifi: (any WiFiMeshTransport)? + private let ble: (any iOSMeshTransport)? + private var retirement: Task? + private var physicalClose: Task? + + init( + binding: SessionTransportBinding, + transport: any MeshTransport, + session: MeshCoreSession, + wifi: (any WiFiMeshTransport)?, + ble: (any iOSMeshTransport)? + ) { + self.binding = binding + self.transport = transport + self.session = session + self.wifi = wifi + self.ble = ble + } + + func revoke() { + binding.revoke() + } + + func cancelUnsubmittedWrites() async { + await ble?.cancelUnsubmittedWrites(sessionBinding: binding) + } + + func retire(closePhysical: Bool) async { + revoke() + await cancelUnsubmittedWrites() + if closePhysical { await ble?.cancelPendingEstablishment(sessionBinding: binding) } + let drain: Task + if let retirement { + drain = retirement + } else { + drain = Task { [session, binding, wifi] in + async let stopped: Void = session.stop(disconnectTransport: false, drainExchanges: true) + if let wifi { await wifi.disconnect() } + await stopped + await binding.waitForQuiescence() + await session.waitForQuiescence() + } + retirement = drain + } + await drain.value + guard closePhysical, wifi == nil else { return } + let close: Task + if let physicalClose { + close = physicalClose + } else { + close = Task { [transport, binding] in + await transport.disconnect(sessionBinding: binding) + } + physicalClose = close + } + await close.value + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionResult.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionResult.swift new file mode 100644 index 0000000000..833ee08ec2 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionResult.swift @@ -0,0 +1,10 @@ +import Foundation + +/// Completion of the caller's wait, distinct from the physical link state. +@MainActor +public enum ConnectionResult { + case operational(ConnectionSnapshot) + case handoff(requestID: UUID) + case superseded + case cancelled +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionRetirement.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionRetirement.swift new file mode 100644 index 0000000000..f04aae64a5 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionRetirement.swift @@ -0,0 +1,9 @@ +@MainActor +struct ConnectionRetirement { + let worker: Task + let receipt: ConnectionLossReceipt + + var value: Void { + get async { await worker.value } + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionSnapshot.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionSnapshot.swift new file mode 100644 index 0000000000..dc32149dc7 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionSnapshot.swift @@ -0,0 +1,11 @@ +import Foundation + +/// The installed stack captured by a connection callback or caller. +@MainActor +public struct ConnectionSnapshot { + public let generation: UUID + public let requestID: UUID + public let device: DeviceDTO + public let services: ServiceContainer + public let transportType: TransportType +} diff --git a/MC1Services/Sources/MC1Services/Connection/IdentityImportReceipt.swift b/MC1Services/Sources/MC1Services/Connection/IdentityImportReceipt.swift new file mode 100644 index 0000000000..14ea10bda9 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/IdentityImportReceipt.swift @@ -0,0 +1,37 @@ +import Foundation + +struct IdentityImportReceipt: Equatable, Sendable { + let receiptID = UUID() + let originalDeviceID: UUID + let originalRadioID: UUID + let originalPublicKey: Data + let sourceName: String + let capturedConnectionMethod: ConnectionMethod + var publicKey: Data? + + init(device: DeviceDTO, method: ConnectionMethod) { + originalDeviceID = device.id + originalRadioID = device.radioID + originalPublicKey = device.publicKey + sourceName = device.nodeName + capturedConnectionMethod = method + } + + func recovery(currentRequestID: UUID?) -> IdentityImportRecovery { + IdentityImportRecovery( + receiptID: receiptID, originalDeviceID: originalDeviceID, originalRadioID: originalRadioID, + sourceName: sourceName, capturedConnectionMethod: capturedConnectionMethod, currentRequestID: currentRequestID + ) + } + + var target: ConnectionRequest.Target { + switch capturedConnectionMethod { + case let .bluetooth(id, _): .bluetooth(id) + case let .wifi(host, port, _): .wifi(host: host, port: port) + } + } + + var originalIdentity: ConnectionDeviceIdentity { + ConnectionDeviceIdentity(deviceID: originalDeviceID, publicKey: originalPublicKey, radioID: originalRadioID) + } +} diff --git a/MC1Services/Sources/MC1Services/Connection/IdentityImportRecovery.swift b/MC1Services/Sources/MC1Services/Connection/IdentityImportRecovery.swift new file mode 100644 index 0000000000..898b0bdf26 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/IdentityImportRecovery.swift @@ -0,0 +1,12 @@ +import Foundation + +/// A captured identity-reapplication choice, without private-key material. +public struct IdentityImportRecovery: Equatable, Sendable { + public let receiptID: UUID + public let originalDeviceID: UUID + public let originalRadioID: UUID + public let sourceName: String + public let capturedConnectionMethod: ConnectionMethod + /// Equality includes the request so a newer connection invalidates a prepared confirmation. + public let currentRequestID: UUID? +} diff --git a/MC1Services/Sources/MC1Services/Connection/IdentityImportRecoveryRequired.swift b/MC1Services/Sources/MC1Services/Connection/IdentityImportRecoveryRequired.swift new file mode 100644 index 0000000000..e35d9d6ff6 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/IdentityImportRecoveryRequired.swift @@ -0,0 +1,4 @@ +/// The radio's identity could have changed without a confirmed wire result. +public struct IdentityImportRecoveryRequired: Error, Sendable { + public let recovery: IdentityImportRecovery +} diff --git a/MC1Services/Sources/MC1Services/Connection/WiFiMeshTransport.swift b/MC1Services/Sources/MC1Services/Connection/WiFiMeshTransport.swift new file mode 100644 index 0000000000..20ef8c7dea --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/WiFiMeshTransport.swift @@ -0,0 +1,11 @@ +import Foundation +import MeshCore + +/// Socket construction is injectable while session setup stays in the connection runner. +public protocol WiFiMeshTransport: MeshTransport, AnyObject { + var connectionInfo: (host: String, port: UInt16)? { get async } + func setConnectionInfo(host: String, port: UInt16) async + func setDisconnectionHandler(_ handler: @escaping @Sendable (Error?, CFAbsoluteTime) -> Void) async +} + +extension WiFiTransport: WiFiMeshTransport {} diff --git a/MC1Services/Sources/MC1Services/Errors/RemoteNodeError.swift b/MC1Services/Sources/MC1Services/Errors/RemoteNodeError.swift index ace4cc16fd..beb40afbe4 100644 --- a/MC1Services/Sources/MC1Services/Errors/RemoteNodeError.swift +++ b/MC1Services/Sources/MC1Services/Errors/RemoteNodeError.swift @@ -3,6 +3,10 @@ import MeshCore public enum RemoteNodeError: Error, LocalizedError, Sendable { case notConnected + case invalidPasswordLength + case invalidSensorSetting + case sensorSettingRejected + case sensorOutcomeUnknown case loginFailed(String) case sendFailed(String) case invalidResponse @@ -19,6 +23,14 @@ public enum RemoteNodeError: Error, LocalizedError, Sendable { public var errorDescription: String? { switch self { + case .invalidPasswordLength: + "Password exceeds the remote password byte limit" + case .invalidSensorSetting: + "The setting must contain a key and value without whitespace and fit in one command" + case .sensorSettingRejected: + "The sensor rejected this setting" + case .sensorOutcomeUnknown: + "The change could not be verified. Reload before saving again" case .notConnected: "Not connected to mesh device" case let .loginFailed(reason): diff --git a/MC1Services/Sources/MC1Services/Extensions/LPPSensorType+LocaleUnits.swift b/MC1Services/Sources/MC1Services/Extensions/LPPSensorType+LocaleUnits.swift index 002a071f1e..4f5d93b0a4 100644 --- a/MC1Services/Sources/MC1Services/Extensions/LPPSensorType+LocaleUnits.swift +++ b/MC1Services/Sources/MC1Services/Extensions/LPPSensorType+LocaleUnits.swift @@ -5,25 +5,42 @@ public extension LPPSensorType { /// Converts an SI telemetry value to the user's locale-preferred unit. /// Non-locale-sensitive types return the input unchanged. func convertedValue(_ siValue: Double) -> Double { - guard let target = preferredUnit, let si = siDimension else { return siValue } + convertedValue(siValue, locale: .current) + } + + func convertedValue(_ siValue: Double, locale: Locale) -> Double { + guard let target = preferredUnit(for: locale), let si = siDimension else { return siValue } return Measurement(value: siValue, unit: si).converted(to: target).value } /// The locale-appropriate unit symbol (e.g. "°F" on US, "°C" on metric). /// Falls back to the SI `unit` property for non-locale-sensitive types. var localizedUnitSymbol: String { - guard let target = preferredUnit else { return unit } + localizedUnitSymbol(for: .current) + } + + func localizedUnitSymbol(for locale: Locale) -> String { + guard let target = preferredUnit(for: locale) else { return unit } return target.symbol } /// Whether this type's value will be converted for the current locale. var isConverted: Bool { - preferredUnit != nil + isConverted(for: .current) + } + + func isConverted(for locale: Locale) -> Bool { + guard let target = preferredUnit(for: locale), let si = siDimension else { return false } + return target != si } /// The fraction length appropriate for the converted value. var convertedFractionLength: Int { - guard isConverted else { + convertedFractionLength(for: .current) + } + + func convertedFractionLength(for locale: Locale) -> Int { + guard isConverted(for: locale) else { switch self { case .temperature, .barometer, .altitude: return 1 case .distance: return 3 @@ -32,8 +49,8 @@ public extension LPPSensorType { } switch self { case .temperature: return 1 - case .barometer: return 2 // 29.92 inHg - case .altitude: return 0 // whole feet + case .barometer: return barometerFractionLength(for: locale) + case .altitude: return 0 case .distance: return 1 default: return 1 } @@ -41,19 +58,24 @@ public extension LPPSensorType { // MARK: - Private - /// The locale-preferred Dimension for this sensor type, or nil if metric (no conversion needed). - private var preferredUnit: Dimension? { - guard siDimension != nil, - Locale.current.measurementSystem != .metric else { return nil } + /// The Foundation locale-preferred unit, or nil for non-locale-sensitive types. + private func preferredUnit(for locale: Locale) -> Dimension? { switch self { - case .temperature: return UnitTemperature.fahrenheit - case .barometer: return UnitPressure.inchesOfMercury - case .altitude: return UnitLength.feet - case .distance: return UnitLength.feet - default: return nil + case .temperature: UnitTemperature(forLocale: locale) + case .barometer: UnitPressure(forLocale: locale, usage: .barometric) + case .altitude, .distance: UnitLength(forLocale: locale) + default: nil } } + /// Millibars match the hectopascal number and still compare unequal, so the digit count follows the unit. + private func barometerFractionLength(for locale: Locale) -> Int { + guard let target = preferredUnit(for: locale) else { return 1 } + if target == UnitPressure.inchesOfMercury { return 2 } + if target == UnitPressure.millimetersOfMercury { return 0 } + return 1 + } + /// Maps locale-sensitive sensor types to their Foundation SI Dimension. private var siDimension: Dimension? { switch self { diff --git a/MC1Services/Sources/MC1Services/MECP/Languages/LICENSE-LANGUAGES b/MC1Services/Sources/MC1Services/MECP/Languages/LICENSE-LANGUAGES new file mode 100644 index 0000000000..da6ab6cc8f --- /dev/null +++ b/MC1Services/Sources/MC1Services/MECP/Languages/LICENSE-LANGUAGES @@ -0,0 +1,396 @@ +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. + diff --git a/MC1Services/Sources/MC1Services/MECP/Languages/de.json b/MC1Services/Sources/MC1Services/MECP/Languages/de.json new file mode 100644 index 0000000000..4b59e0a27d --- /dev/null +++ b/MC1Services/Sources/MC1Services/MECP/Languages/de.json @@ -0,0 +1,313 @@ +{ + "language": "de", + "language_name": "Deutsch", + "language_name_en": "German", + "language_name_latin": "Deutsch", + "flag_emoji": "🇩🇪", + "text_direction": "ltr", + "severities": { + "0": { + "local": "MAYDAY", + "label": "MAYDAY / Lebensbedrohlich" + }, + "1": { + "local": "DRINGEND", + "label": "DRINGEND / Zeitkritisch" + }, + "2": { + "local": "SICHERHEIT", + "label": "SICHERHEIT / Wichtig" + }, + "3": { + "local": "ROUTINE", + "label": "ROUTINE / Normal" + } + }, + "categories": { + "M": { + "name": "Medizin", + "icon": "medical" + }, + "T": { + "name": "Gelände / Infrastruktur", + "icon": "terrain" + }, + "W": { + "name": "Wetter / Umwelt", + "icon": "weather" + }, + "S": { + "name": "Versorgung", + "icon": "supplies" + }, + "P": { + "name": "Position / Bewegung", + "icon": "position" + }, + "C": { + "name": "Koordination", + "icon": "coordination" + }, + "R": { + "name": "Antwort", + "icon": "response" + }, + "D": { + "name": "Übung / Test", + "icon": "drill" + }, + "L": { + "name": "Alltag / Freizeit", + "icon": "leisure" + }, + "X": { + "name": "Bedrohung / Sicherheit", + "icon": "threat" + }, + "H": { + "name": "Vorhanden / Ressourcen anbieten", + "icon": "resources" + }, + "B": { + "name": "Leuchtfeuer", + "icon": "beacon" + } + }, + "codes": { + "M01": "Verletzung", + "M02": "Bewusstlose Person", + "M03": "Atemnot", + "M04": "Herznotfall", + "M05": "Unterkühlung", + "M06": "Starke Blutung", + "M07": "Fraktur / nicht gehfähig", + "M08": "Verbrennungen", + "M09": "Mehrere Verletzte", + "M10": "Verstorben", + "M11": "Tierbiss / -stich", + "M12": "Allergische Reaktion / Anaphylaxie", + "M13": "Vergiftung / Schadstoffkontakt", + "M14": "Personen lebend gefunden", + "M15": "Gebiet durchsucht, keine Opfer", + "T01": "Straße blockiert", + "T02": "Brücke zerstört", + "T03": "Gebäude eingestürzt", + "T04": "Überschwemmung", + "T05": "Erdrutsch", + "T06": "Stromausfall", + "T07": "Feuer", + "T08": "Lawine", + "T09": "Weg unpassierbar", + "T10": "Unterkunft verfügbar", + "T11": "Ertrinken / Wasserrettung nötig", + "T12": "Wasserverunreinigung", + "T13": "Erdbeben", + "T14": "Gasleck", + "T15": "Chemieunfall / Gefahrgut", + "T16": "Verkehrsunfall", + "T17": "Fahrzeugbrand", + "W01": "Sturm im Anmarsch", + "W02": "Sicht null", + "W03": "Extreme Kälte", + "W04": "Extreme Hitze", + "W05": "Luftqualität gefährlich", + "W06": "Tsunami- / Sturmflutwarnung", + "S01": "Brauche Wasser", + "S02": "Brauche Nahrung", + "S03": "Brauche Medikamente", + "S04": "Brauche Batterie / Strom", + "S05": "Brauche Treibstoff", + "S06": "Brauche Werkzeug / Ausrüstung", + "P01": "Gestrandet / festsitzend", + "P02": "Evakuierung Richtung", + "P03": "Vor Ort verschanzt", + "P04": "Unterwegs nach", + "P05": "An GPS-Koordinaten", + "P06": "Verirrt", + "P07": "Gruppe getrennt", + "C01": "Rettung schicken", + "C02": "Brauche Transport", + "C03": "Nachricht weiterleiten", + "C04": "Empfang bestätigen", + "C05": "Wie viele Personen", + "C06": "Was ist der Status", + "C07": "Könnt ihr erreichen", + "C08": "Treffpunkt bei", + "R01": "Bestätigt", + "R02": "Hilfe kommt", + "R03": "Ankunft in [Minuten]", + "R04": "Kann nicht helfen", + "R05": "Umleitung nach", + "R06": "Bitte warten", + "R07": "Lage gelöst / Entwarnung", + "D01": "Dies ist eine Übung", + "D02": "Dies ist ein Test", + "D03": "Ende der Übung", + "D04": "Vorherige ignorieren — irrtümlich gesendet", + "L01": "Bier / Getränke", + "L02": "Kaffee", + "L03": "Essen fertig", + "L04": "Gipfel erreicht", + "L05": "Im Lager", + "L06": "Verspätet", + "L07": "Gutes Signal hier", + "L08": "Fotogelegenheit", + "L09": "Wildtier gesichtet", + "L10": "Schöne Aussicht", + "L11": "Wegverhältnisse gut", + "L12": "Wegverhältnisse schlecht", + "L13": "Brauche Pause", + "L14": "Auf dem Heimweg", + "L15": "Guten Morgen / Meldung", + "L16": "Gute Nacht", + "L17": "Danke", + "L18": "Macht Spaß", + "L19": "Fest / Veranstaltung hier", + "L20": "Knotentest / Ping", + "X01": "Gefährliche Person / Bedrohung in Nähe", + "X02": "Gebiet unsicher — meiden", + "X03": "Schüsse / Explosionen gehört", + "X04": "Unruhen / Menschenmenge gefährlich", + "X05": "Diebstahl / Plünderung gemeldet", + "X06": "Behörden / Rettungsdienste vor Ort", + "X07": "Kontrollpunkt / Straßensperre (Behörde)", + "H01": "Wasser verfügbar", + "H02": "Nahrung verfügbar", + "H03": "Medizinisches Material vorhanden", + "H04": "Strom / Ladestation vorhanden", + "H05": "Treibstoff vorhanden", + "H06": "Werkzeug / Ausrüstung vorhanden", + "H07": "Unterkunft / Platz für [N] Pers.", + "H08": "Transport / Fahrzeug vorhanden", + "B01": "Automatisches Notsignal aktiv — Absender möglicherweise nicht ansprechbar", + "B02": "Leuchtfeuer bestätigt — Senderate reduzieren", + "B03": "Leuchtfeuer abbrechen — mir geht es gut" + }, + "ui": { + "send": "Senden", + "cancel": "Abbrechen", + "attach_gps": "GPS anhängen", + "attach_timestamp": "Zeitstempel (UTC)", + "add_count": "Anzahl hinzufügen", + "preview": "Vorschau", + "copy": "Kopieren", + "paste_decode": "Einfügen & dekodieren", + "severity_select": "Schweregrad wählen", + "category_select": "Kategorie wählen", + "code_select": "Codes wählen", + "freetext_placeholder": "Optionaler Text...", + "parse_failed": "MECP-Nachricht — konnte nicht vollständig geparst werden", + "unknown_code": "Unbekannter Code", + "message_too_long": "Nachricht überschreitet 200 Bytes", + "not_connected": "Kein Gerät verbunden", + "connecting": "Verbinde...", + "connected_to": "Verbunden mit", + "scan_devices": "Geräte suchen", + "compose": "Verfassen", + "decode": "Dekodieren", + "reference_card": "Referenzkarte", + "history": "Verlauf", + "clear_history": "Verlauf löschen", + "export_history": "Verlauf exportieren", + "drill_banner": "ÜBUNG", + "untranslated_warning": "Dieser Text ist nicht übersetzt", + "bytes_remaining": "Bytes verbleibend", + "confirm_mayday": "MAYDAY bestätigen — halten zum Senden", + "message_copied": "Nachricht kopiert", + "gps_acquiring": "GPS wird ermittelt...", + "add_reference_tag": "Vorfallkennung hinzufügen", + "back": "Zurück", + "next": "Weiter", + "add_more_codes": "Weitere Codes hinzufügen", + "freetext_preview": "Freitext & Vorschau", + "bytes_available": "Bytes verfügbar für weitere Codes + Freitext", + "gps_unavailable": "GPS nicht verfügbar", + "gps_not_supported": "GPS nicht unterstützt", + "freetext_conventions": "Freitext-Konventionen", + "no_messages": "Noch keine Nachrichten", + "severity_levels": "Schweregrade", + "person_count": "Personenanzahl", + "settings": "Einstellungen", + "inbox": "Posteingang", + "device": "Gerät", + "language_label": "Sprache", + "compose_defaults": "Verfassen-Standards", + "auto_gps": "GPS automatisch anhängen (Stufe 0-1)", + "auto_timestamp": "Zeitstempel automatisch anhängen", + "all_filter": "Alle", + "sent": "Gesendet", + "reset": "Zurücksetzen", + "freetext": "Freitext", + "severity_header": "Schweregrad", + "category_header": "Kategorie", + "codes_header": "Codes", + "preview_send": "Vorschau & Senden", + "no_radio_queued": "Kein Funkgerät verbunden — Nachricht wird gespeichert", + "mecp_message": "MECP-Nachricht", + "inbox_tab": "Eingang", + "reference_tab": "Referenz", + "activate_beacon": "Leuchtfeuer aktivieren", + "beacon_active": "Notsignal aktiv", + "beacon_cancel": "Leuchtfeuer abbrechen", + "beacon_confirm": "Notsignal aktivieren? Ihre Position wird automatisch gesendet.", + "beacon_countdown": "Nächste Übertragung in", + "beacon_ack_received": "Leuchtfeuer bestätigt von", + "beacon_drill": "ÜBUNGS-LEUCHTFEUER", + "ack_waiting": "Warte auf Bestätigung...", + "ack_no_response": "Keine Antwort erhalten", + "ack_resend": "Erneut mit Weiterleitungsanfrage senden?", + "beacon_positions": "Positionsverlauf", + "beacon_from": "Leuchtfeuer von", + "beacon_last_seen": "Zuletzt gesehen", + "beacon_duration": "Aktiv seit", + "site_nav_what": "Was ist MECP", + "site_nav_demo": "Demo", + "site_nav_app": "App-Simulation", + "site_nav_github": "GitHub", + "site_nav_discussion": "Diskussion", + "site_hero_headline": "Notfallkommunikation in jeder Sprache, über jedes Mesh-Netzwerk", + "site_hero_sub": "MECP ist ein offenes Protokoll, das Notfallnachrichten in winzige Pakete kodiert, die jedes LoRa-Mesh-Funkgerät übertragen kann — sofort verständlich in 20 Sprachen.", + "site_cta_demo": "Demo ausprobieren", + "site_cta_github": "Auf GitHub ansehen", + "site_what_title": "Was ist MECP?", + "site_what_p1": "Wenn Katastrophen zuschlagen und Mobilfunkmasten ausfallen, sind Freiwillige und Ersthelfer auf Mesh-Funkgeräte angewiesen. Doch Mesh-Funkgeräte übertragen sehr wenig Daten — oft weniger als 200 Bytes — und wenn Teams verschiedene Sprachen sprechen, geht wichtige Bedeutung verloren.", + "site_what_p2": "MECP (Mesh Emergency Communication Protocol) löst dies, indem es Notfallsituationen in kompakte, strukturierte Nachrichten kodiert. Jede Nachricht beginnt mit einer Dringlichkeitsstufe, gefolgt von standardisierten Codes aus 12 Kategorien — Medizin, Gelände, Wetter, Vorräte, Koordination und mehr.", + "site_what_p3": "Da jeder Code eine Übersetzung in 20 Sprachen hat, ist der MAYDAY eines tschechischen Freiwilligen sofort lesbar für ein japanisches Rettungsteam. Kein Dolmetscher nötig, keine Bandbreite verschwendet.", + "site_what_example_label": "Beispielnachricht", + "site_what_example_sev": "Dringlichkeit 0 — MAYDAY", + "site_what_example_codes": "Verletzung + Bewusstlos + Straße blockiert", + "site_what_example_pax": "3 Personen", + "site_what_example_gps": "GPS-Koordinaten", + "site_what_example_time": "Zeitstempel (UTC)", + "site_what_example_lang": "Sprachhinweis", + "site_what_feat_codes": "108 Codes in 12 Kategorien", + "site_what_feat_langs": "20 Sprachen unterstützt", + "site_what_feat_bytes": "Passt in 200 Bytes", + "site_demo_title": "Live-Demo", + "site_demo_sub": "Erstellen Sie eine echte MECP-Nachricht und sehen Sie sie sofort in einer anderen Sprache dekodiert.", + "site_demo_compose_label": "Erstellen", + "site_demo_decode_label": "Dekodiert", + "site_demo_swap_langs": "Sprachen tauschen", + "site_demo_raw_label": "Roher MECP-String", + "site_sim_title": "App-Simulation", + "site_sim_sub": "Sehen Sie, wie MECP über ein Mesh-Netzwerk funktioniert — erstellen Sie auf einem Gerät, empfangen Sie auf einem anderen in einer anderen Sprache.", + "site_sim_sender": "Absender", + "site_sim_receiver": "Empfänger", + "site_sim_send_btn": "Über Mesh senden", + "site_sim_sending": "Wird gesendet...", + "site_sim_just_now": "gerade eben", + "site_sim_change_lang": "Sprache ändern", + "site_community_title": "Community", + "site_community_github_desc": "Quellcode, Dokumentation und Beispiele. Markieren Sie das Repo mit einem Stern für Updates.", + "site_community_protocol_title": "Offenes Protokoll", + "site_community_protocol_desc": "Die MECP-Protokollspezifikation ist unter CC0 veröffentlicht — gemeinfrei. Verwenden Sie sie frei in jedem Projekt.", + "site_community_contribute_title": "Mitmachen", + "site_community_contribute_desc": "Fügen Sie Übersetzungen hinzu, erstellen Sie Integrationen oder verbessern Sie das Protokoll. Lesen Sie CONTRIBUTING.md.", + "site_discussion_title": "Diskussion", + "site_footer_desc": "Open Source, offenes Protokoll, gebaut für Widerstandsfähigkeit.", + "site_footer_links": "Links", + "site_footer_licenses": "Lizenzen", + "site_footer_web_tool": "Web-Tool" + }, + "deprecations": {} +} diff --git a/MC1Services/Sources/MC1Services/MECP/Languages/en.json b/MC1Services/Sources/MC1Services/MECP/Languages/en.json new file mode 100644 index 0000000000..2b8f69a038 --- /dev/null +++ b/MC1Services/Sources/MC1Services/MECP/Languages/en.json @@ -0,0 +1,313 @@ +{ + "language": "en", + "language_name": "English", + "language_name_en": "English", + "language_name_latin": "English", + "flag_emoji": "🇬🇧", + "text_direction": "ltr", + "severities": { + "0": { + "local": "MAYDAY", + "label": "MAYDAY / Life-threatening" + }, + "1": { + "local": "URGENT", + "label": "URGENT / Time-critical" + }, + "2": { + "local": "SAFETY", + "label": "SAFETY / Important" + }, + "3": { + "local": "ROUTINE", + "label": "ROUTINE / Normal" + } + }, + "categories": { + "M": { + "name": "Medical", + "icon": "medical" + }, + "T": { + "name": "Terrain / Infrastructure", + "icon": "terrain" + }, + "W": { + "name": "Weather / Environment", + "icon": "weather" + }, + "S": { + "name": "Supplies", + "icon": "supplies" + }, + "P": { + "name": "Position / Movement", + "icon": "position" + }, + "C": { + "name": "Coordination", + "icon": "coordination" + }, + "R": { + "name": "Response", + "icon": "response" + }, + "D": { + "name": "Drill / Test", + "icon": "drill" + }, + "L": { + "name": "Life / Leisure", + "icon": "leisure" + }, + "X": { + "name": "Threat / Security", + "icon": "threat" + }, + "H": { + "name": "Have / Offer Resources", + "icon": "resources" + }, + "B": { + "name": "Beacon", + "icon": "beacon" + } + }, + "codes": { + "M01": "Injury", + "M02": "Unconscious person", + "M03": "Breathing difficulty", + "M04": "Cardiac event", + "M05": "Hypothermia", + "M06": "Severe bleeding", + "M07": "Fracture / immobile", + "M08": "Burns", + "M09": "Multiple casualties", + "M10": "Deceased", + "M11": "Animal bite / sting", + "M12": "Allergic reaction / anaphylaxis", + "M13": "Poisoning / toxic exposure", + "M14": "Persons located alive", + "M15": "Area searched, no victims found", + "T01": "Road blocked", + "T02": "Bridge out", + "T03": "Building collapsed", + "T04": "Flooding", + "T05": "Landslide", + "T06": "Power out", + "T07": "Fire", + "T08": "Avalanche", + "T09": "Path impassable", + "T10": "Shelter available", + "T11": "Drowning / water rescue needed", + "T12": "Water contamination", + "T13": "Earthquake", + "T14": "Gas leak", + "T15": "Chemical spill / HAZMAT", + "T16": "Vehicle accident", + "T17": "Vehicle fire", + "W01": "Storm approaching", + "W02": "Visibility zero", + "W03": "Extreme cold", + "W04": "Extreme heat", + "W05": "Air quality danger", + "W06": "Tsunami / tidal surge warning", + "S01": "Need water", + "S02": "Need food", + "S03": "Need medication", + "S04": "Need battery / power", + "S05": "Need fuel", + "S06": "Need tools / equipment", + "P01": "Stranded / stuck", + "P02": "Evacuating toward", + "P03": "Sheltering in place", + "P04": "En route to", + "P05": "At GPS coordinates", + "P06": "Lost", + "P07": "Group separated", + "C01": "Send rescue", + "C02": "Need transport", + "C03": "Relay this message", + "C04": "Confirm received", + "C05": "How many people", + "C06": "What is status", + "C07": "Can you reach", + "C08": "Rendezvous at", + "R01": "Acknowledged", + "R02": "Help coming", + "R03": "ETA [minutes]", + "R04": "Cannot assist", + "R05": "Redirecting to", + "R06": "Stand by", + "R07": "Situation resolved / all clear", + "D01": "This is a drill", + "D02": "This is a test", + "D03": "End of drill", + "D04": "Ignore previous — sent in error", + "L01": "Beer / drinks", + "L02": "Coffee", + "L03": "Food ready", + "L04": "Summit reached", + "L05": "At camp", + "L06": "Running late", + "L07": "Good signal here", + "L08": "Photo opportunity", + "L09": "Wildlife spotted", + "L10": "Beautiful view", + "L11": "Trail conditions good", + "L12": "Trail conditions bad", + "L13": "Need a break", + "L14": "Heading home", + "L15": "Good morning / check-in", + "L16": "Good night", + "L17": "Thank you", + "L18": "Having fun", + "L19": "Festival / event here", + "L20": "Node test / ping", + "X01": "Dangerous person / threat nearby", + "X02": "Area unsafe — avoid", + "X03": "Gunfire / explosions heard", + "X04": "Civil unrest / crowd danger", + "X05": "Theft / looting reported", + "X06": "Authorities / emergency services present", + "X07": "Checkpoint / road closure (authority)", + "H01": "Have water available", + "H02": "Have food available", + "H03": "Have medical supplies", + "H04": "Have power / charging", + "H05": "Have fuel", + "H06": "Have tools / equipment", + "H07": "Have shelter / space for [N]pax", + "H08": "Have transport / vehicle", + "B01": "Automated distress beacon active — sender may be unresponsive", + "B02": "Beacon acknowledged — reduce transmission rate", + "B03": "Cancel beacon — I am OK" + }, + "ui": { + "send": "Send", + "cancel": "Cancel", + "attach_gps": "Attach GPS", + "attach_timestamp": "Timestamp (UTC)", + "add_count": "Add count", + "preview": "Preview", + "copy": "Copy", + "paste_decode": "Paste & decode", + "severity_select": "Select severity", + "category_select": "Select category", + "code_select": "Select codes", + "freetext_placeholder": "Optional text...", + "parse_failed": "MECP message — could not fully parse", + "unknown_code": "Unknown code", + "message_too_long": "Message exceeds 200 bytes", + "not_connected": "No device connected", + "connecting": "Connecting...", + "connected_to": "Connected to", + "scan_devices": "Scan for devices", + "compose": "Compose", + "decode": "Decode", + "reference_card": "Reference Card", + "history": "History", + "clear_history": "Clear history", + "export_history": "Export history", + "drill_banner": "DRILL", + "untranslated_warning": "This text is not translated", + "bytes_remaining": "bytes remaining", + "confirm_mayday": "Confirm MAYDAY — hold to send", + "message_copied": "Message copied", + "gps_acquiring": "Acquiring GPS...", + "add_reference_tag": "Add incident tag", + "back": "Back", + "next": "Next", + "add_more_codes": "Add more codes", + "freetext_preview": "Freetext & Preview", + "bytes_available": "bytes available for more codes + freetext", + "gps_unavailable": "GPS unavailable", + "gps_not_supported": "GPS not supported", + "freetext_conventions": "Freetext Conventions", + "no_messages": "No messages yet", + "severity_levels": "Severity Levels", + "person_count": "Person count", + "settings": "Settings", + "inbox": "Inbox", + "device": "Device", + "language_label": "Language", + "compose_defaults": "Compose Defaults", + "auto_gps": "Auto-attach GPS (sev 0-1)", + "auto_timestamp": "Auto-attach timestamp", + "all_filter": "All", + "sent": "Sent", + "reset": "Reset", + "freetext": "Freetext", + "severity_header": "Severity", + "category_header": "Category", + "codes_header": "Codes", + "preview_send": "Preview & Send", + "no_radio_queued": "No radio connected — message will be queued", + "mecp_message": "MECP Message", + "inbox_tab": "Inbox", + "reference_tab": "Reference", + "activate_beacon": "Activate Beacon", + "beacon_active": "Distress beacon active", + "beacon_cancel": "Cancel Beacon", + "beacon_confirm": "Activate distress beacon? This will broadcast your position automatically.", + "beacon_countdown": "Next transmission in", + "beacon_ack_received": "Beacon acknowledged by", + "beacon_drill": "DRILL BEACON", + "ack_waiting": "Waiting for acknowledgement...", + "ack_no_response": "No response received", + "ack_resend": "Resend with relay request?", + "beacon_positions": "Position History", + "beacon_from": "Beacon from", + "beacon_last_seen": "Last seen", + "beacon_duration": "Active for", + "site_nav_what": "What is MECP", + "site_nav_demo": "Demo", + "site_nav_app": "App Simulation", + "site_nav_github": "GitHub", + "site_nav_discussion": "Discussion", + "site_hero_headline": "Emergency communication across any language, over any mesh", + "site_hero_sub": "MECP is an open protocol that encodes emergency messages into tiny packets any LoRa mesh radio can carry — understood instantly in 20 languages.", + "site_cta_demo": "Try the demo", + "site_cta_github": "View on GitHub", + "site_what_title": "What is MECP?", + "site_what_p1": "When disaster strikes and cell towers go dark, volunteers and first responders rely on mesh radios to coordinate. But mesh radios carry very little data — often less than 200 bytes — and when teams speak different languages, critical meaning gets lost.", + "site_what_p2": "MECP (Mesh Emergency Communication Protocol) solves this by encoding emergency situations into compact, structured messages. Each message starts with a severity level, followed by standardised codes from 12 categories — medical, terrain, weather, supplies, coordination, and more.", + "site_what_p3": "Because every code maps to a translation in 20 languages, a Czech volunteer's MAYDAY is instantly readable by a Japanese search team. No interpreter needed, no bandwidth wasted.", + "site_what_example_label": "Example message", + "site_what_example_sev": "Severity 0 — MAYDAY", + "site_what_example_codes": "Injury + Unconscious + Road blocked", + "site_what_example_pax": "3 people", + "site_what_example_gps": "GPS coordinates", + "site_what_example_time": "Timestamp (UTC)", + "site_what_example_lang": "Language hint", + "site_what_feat_codes": "108 codes across 12 categories", + "site_what_feat_langs": "20 languages supported", + "site_what_feat_bytes": "Fits in 200 bytes", + "site_demo_title": "Live Demo", + "site_demo_sub": "Compose a real MECP message and see it decoded instantly in another language.", + "site_demo_compose_label": "Compose", + "site_demo_decode_label": "Decoded", + "site_demo_swap_langs": "Swap languages", + "site_demo_raw_label": "Raw MECP string", + "site_sim_title": "App Simulation", + "site_sim_sub": "See how MECP works across a mesh network — compose on one device, receive on another in a different language.", + "site_sim_sender": "Sender", + "site_sim_receiver": "Receiver", + "site_sim_send_btn": "Send via mesh", + "site_sim_sending": "Sending...", + "site_sim_just_now": "just now", + "site_sim_change_lang": "Change language", + "site_community_title": "Community", + "site_community_github_desc": "Source code, documentation, and examples. Star the repo to follow updates.", + "site_community_protocol_title": "Open Protocol", + "site_community_protocol_desc": "The MECP protocol specification is released under CC0 — public domain. Use it freely in any project.", + "site_community_contribute_title": "Get Involved", + "site_community_contribute_desc": "Add translations, build integrations, or improve the protocol. Read CONTRIBUTING.md to get started.", + "site_discussion_title": "Discussion", + "site_footer_desc": "Open source, open protocol, built for resilience.", + "site_footer_links": "Links", + "site_footer_licenses": "Licenses", + "site_footer_web_tool": "Web Tool" + }, + "deprecations": {} +} diff --git a/MC1Services/Sources/MC1Services/MECP/Languages/es.json b/MC1Services/Sources/MC1Services/MECP/Languages/es.json new file mode 100644 index 0000000000..e498360039 --- /dev/null +++ b/MC1Services/Sources/MC1Services/MECP/Languages/es.json @@ -0,0 +1,313 @@ +{ + "language": "es", + "language_name": "Español", + "language_name_en": "Spanish", + "language_name_latin": "Español", + "flag_emoji": "🇪🇸", + "text_direction": "ltr", + "severities": { + "0": { + "local": "MAYDAY", + "label": "MAYDAY / Peligro de muerte" + }, + "1": { + "local": "URGENTE", + "label": "URGENTE / Tiempo crítico" + }, + "2": { + "local": "SEGURIDAD", + "label": "SEGURIDAD / Importante" + }, + "3": { + "local": "RUTINA", + "label": "RUTINA / Normal" + } + }, + "categories": { + "M": { + "name": "Médico", + "icon": "medical" + }, + "T": { + "name": "Terreno / Infraestructura", + "icon": "terrain" + }, + "W": { + "name": "Clima / Medio ambiente", + "icon": "weather" + }, + "S": { + "name": "Suministros", + "icon": "supplies" + }, + "P": { + "name": "Posición / Movimiento", + "icon": "position" + }, + "C": { + "name": "Coordinación", + "icon": "coordination" + }, + "R": { + "name": "Respuesta", + "icon": "response" + }, + "D": { + "name": "Simulacro / Prueba", + "icon": "drill" + }, + "L": { + "name": "Vida / Ocio", + "icon": "leisure" + }, + "X": { + "name": "Amenaza / Seguridad", + "icon": "threat" + }, + "H": { + "name": "Disponible / Oferta de recursos", + "icon": "resources" + }, + "B": { + "name": "Baliza", + "icon": "beacon" + } + }, + "codes": { + "M01": "Lesión", + "M02": "Persona inconsciente", + "M03": "Dificultad respiratoria", + "M04": "Evento cardíaco", + "M05": "Hipotermia", + "M06": "Hemorragia grave", + "M07": "Fractura / inmovilizado", + "M08": "Quemaduras", + "M09": "Múltiples víctimas", + "M10": "Fallecido", + "M11": "Mordedura / picadura de animal", + "M12": "Reacción alérgica / anafilaxia", + "M13": "Envenenamiento / exposición tóxica", + "M14": "Personas localizadas con vida", + "M15": "Zona rastreada, sin víctimas", + "T01": "Carretera bloqueada", + "T02": "Puente caído", + "T03": "Edificio derrumbado", + "T04": "Inundación", + "T05": "Deslizamiento de tierra", + "T06": "Sin electricidad", + "T07": "Incendio", + "T08": "Avalancha", + "T09": "Camino intransitable", + "T10": "Refugio disponible", + "T11": "Ahogamiento / rescate acuático necesario", + "T12": "Agua contaminada", + "T13": "Terremoto", + "T14": "Fuga de gas", + "T15": "Derrame químico / HAZMAT", + "T16": "Accidente de vehículo", + "T17": "Vehículo en llamas", + "W01": "Tormenta acercándose", + "W02": "Visibilidad nula", + "W03": "Frío extremo", + "W04": "Calor extremo", + "W05": "Calidad del aire peligrosa", + "W06": "Alerta de tsunami / marejada", + "S01": "Necesitan agua", + "S02": "Necesitan comida", + "S03": "Necesitan medicamentos", + "S04": "Necesitan batería / energía", + "S05": "Necesitan combustible", + "S06": "Necesitan herramientas / equipo", + "P01": "Varados / atrapados", + "P02": "Evacuando hacia", + "P03": "Refugiados en el lugar", + "P04": "En camino a", + "P05": "En coordenadas GPS", + "P06": "Perdidos", + "P07": "Grupo separado", + "C01": "Envíen rescate", + "C02": "Necesitan transporte", + "C03": "Retransmitan este mensaje", + "C04": "Confirmen recepción", + "C05": "¿Cuántas personas?", + "C06": "¿Cuál es el estado?", + "C07": "¿Pueden contactar?", + "C08": "Punto de encuentro en", + "R01": "Recibido", + "R02": "Ayuda en camino", + "R03": "Llegada est. [minutos]", + "R04": "No podemos asistir", + "R05": "Redirigiendo a", + "R06": "Esperen", + "R07": "Situación resuelta / todo despejado", + "D01": "Esto es un simulacro", + "D02": "Esto es una prueba", + "D03": "Fin del simulacro", + "D04": "Ignoren lo anterior — enviado por error", + "L01": "Cerveza / bebidas", + "L02": "Café", + "L03": "Comida lista", + "L04": "Cumbre alcanzada", + "L05": "En el campamento", + "L06": "Llegando tarde", + "L07": "Buena señal aquí", + "L08": "Oportunidad de foto", + "L09": "Fauna avistada", + "L10": "Vista hermosa", + "L11": "Sendero en buen estado", + "L12": "Sendero en mal estado", + "L13": "Necesito un descanso", + "L14": "Rumbo a casa", + "L15": "Buenos días / registro", + "L16": "Buenas noches", + "L17": "Gracias", + "L18": "Divirtiéndose", + "L19": "Festival / evento aquí", + "L20": "Prueba de nodo / ping", + "X01": "Persona peligrosa / amenaza cercana", + "X02": "Zona insegura — evitar", + "X03": "Disparos / explosiones escuchados", + "X04": "Disturbios civiles / peligro de multitud", + "X05": "Robo / saqueo reportado", + "X06": "Autoridades / servicios de emergencia presentes", + "X07": "Puesto de control / corte de carretera (autoridad)", + "H01": "Agua disponible", + "H02": "Comida disponible", + "H03": "Suministros médicos disponibles", + "H04": "Energía / carga disponible", + "H05": "Combustible disponible", + "H06": "Herramientas / equipo disponible", + "H07": "Refugio / espacio para [N]pax", + "H08": "Transporte / vehículo disponible", + "B01": "Baliza de socorro automática activa — el remitente puede no responder", + "B02": "Baliza confirmada — reducir frecuencia de transmisión", + "B03": "Cancelar baliza — estoy bien" + }, + "ui": { + "send": "Enviar", + "cancel": "Cancelar", + "attach_gps": "Adjuntar GPS", + "attach_timestamp": "Marca de tiempo (UTC)", + "add_count": "Añadir cantidad", + "preview": "Vista previa", + "copy": "Copiar", + "paste_decode": "Pegar y decodificar", + "severity_select": "Seleccionar gravedad", + "category_select": "Seleccionar categoría", + "code_select": "Seleccionar códigos", + "freetext_placeholder": "Texto opcional...", + "parse_failed": "Mensaje MECP — no se pudo analizar completamente", + "unknown_code": "Código desconocido", + "message_too_long": "El mensaje supera los 200 bytes", + "not_connected": "Sin dispositivo conectado", + "connecting": "Conectando...", + "connected_to": "Conectado a", + "scan_devices": "Buscar dispositivos", + "compose": "Redactar", + "decode": "Decodificar", + "reference_card": "Tarjeta de referencia", + "history": "Historial", + "clear_history": "Borrar historial", + "export_history": "Exportar historial", + "drill_banner": "SIMULACRO", + "untranslated_warning": "Este texto no está traducido", + "bytes_remaining": "bytes restantes", + "confirm_mayday": "Confirmar MAYDAY — mantenga para enviar", + "message_copied": "Mensaje copiado", + "gps_acquiring": "Obteniendo GPS...", + "add_reference_tag": "Añadir etiqueta de incidente", + "back": "Atrás", + "next": "Siguiente", + "add_more_codes": "Añadir más códigos", + "freetext_preview": "Texto libre y Vista previa", + "bytes_available": "bytes disponibles para más códigos + texto", + "gps_unavailable": "GPS no disponible", + "gps_not_supported": "GPS no compatible", + "freetext_conventions": "Convenciones de texto libre", + "no_messages": "Sin mensajes aún", + "severity_levels": "Niveles de severidad", + "person_count": "Número de personas", + "settings": "Configuración", + "inbox": "Bandeja de entrada", + "device": "Dispositivo", + "language_label": "Idioma", + "compose_defaults": "Valores predeterminados", + "auto_gps": "Adjuntar GPS auto (sev 0-1)", + "auto_timestamp": "Adjuntar marca de tiempo auto", + "all_filter": "Todos", + "sent": "Enviados", + "reset": "Reiniciar", + "freetext": "Texto libre", + "severity_header": "Severidad", + "category_header": "Categoría", + "codes_header": "Códigos", + "preview_send": "Vista previa y Enviar", + "no_radio_queued": "Sin radio conectada — el mensaje se pondrá en cola", + "mecp_message": "Mensaje MECP", + "inbox_tab": "Bandeja", + "reference_tab": "Referencia", + "activate_beacon": "Activar baliza", + "beacon_active": "Baliza de socorro activa", + "beacon_cancel": "Cancelar baliza", + "beacon_confirm": "¿Activar baliza de socorro? Su posición se transmitirá automáticamente.", + "beacon_countdown": "Próxima transmisión en", + "beacon_ack_received": "Baliza confirmada por", + "beacon_drill": "BALIZA DE SIMULACRO", + "ack_waiting": "Esperando confirmación...", + "ack_no_response": "Sin respuesta", + "ack_resend": "¿Reenviar con solicitud de retransmisión?", + "beacon_positions": "Historial de posiciones", + "beacon_from": "Baliza de", + "beacon_last_seen": "Visto por última vez", + "beacon_duration": "Activa desde", + "site_nav_what": "Qué es MECP", + "site_nav_demo": "Demo", + "site_nav_app": "Simulación de app", + "site_nav_github": "GitHub", + "site_nav_discussion": "Discusión", + "site_hero_headline": "Comunicación de emergencia en cualquier idioma, a través de cualquier red mesh", + "site_hero_sub": "MECP es un protocolo abierto que codifica mensajes de emergencia en paquetes diminutos que cualquier radio mesh LoRa puede transportar — comprendidos al instante en 20 idiomas.", + "site_cta_demo": "Probar la demo", + "site_cta_github": "Ver en GitHub", + "site_what_title": "¿Qué es MECP?", + "site_what_p1": "Cuando ocurre un desastre y las torres de telefonía se apagan, voluntarios y socorristas dependen de radios mesh para coordinarse. Pero las radios mesh transportan muy pocos datos — a menudo menos de 200 bytes — y cuando los equipos hablan diferentes idiomas, el significado crítico se pierde.", + "site_what_p2": "MECP (Mesh Emergency Communication Protocol) resuelve esto codificando situaciones de emergencia en mensajes compactos y estructurados. Cada mensaje comienza con un nivel de gravedad, seguido de códigos estandarizados de 12 categorías — médica, terreno, clima, suministros, coordinación y más.", + "site_what_p3": "Como cada código tiene traducción en 20 idiomas, el MAYDAY de un voluntario checo es instantáneamente legible para un equipo de rescate japonés. Sin intérprete, sin desperdiciar ancho de banda.", + "site_what_example_label": "Mensaje de ejemplo", + "site_what_example_sev": "Gravedad 0 — MAYDAY", + "site_what_example_codes": "Lesión + Inconsciente + Carretera bloqueada", + "site_what_example_pax": "3 personas", + "site_what_example_gps": "Coordenadas GPS", + "site_what_example_time": "Marca de tiempo (UTC)", + "site_what_example_lang": "Indicación de idioma", + "site_what_feat_codes": "108 códigos en 12 categorías", + "site_what_feat_langs": "20 idiomas soportados", + "site_what_feat_bytes": "Cabe en 200 bytes", + "site_demo_title": "Demo en vivo", + "site_demo_sub": "Componga un mensaje MECP real y véalo decodificado al instante en otro idioma.", + "site_demo_compose_label": "Componer", + "site_demo_decode_label": "Decodificado", + "site_demo_swap_langs": "Intercambiar idiomas", + "site_demo_raw_label": "Cadena MECP cruda", + "site_sim_title": "Simulación de aplicación", + "site_sim_sub": "Vea cómo funciona MECP a través de una red mesh — componga en un dispositivo, reciba en otro en un idioma diferente.", + "site_sim_sender": "Emisor", + "site_sim_receiver": "Receptor", + "site_sim_send_btn": "Enviar por mesh", + "site_sim_sending": "Enviando...", + "site_sim_just_now": "ahora mismo", + "site_sim_change_lang": "Cambiar idioma", + "site_community_title": "Comunidad", + "site_community_github_desc": "Código fuente, documentación y ejemplos. Dale estrella al repositorio para seguir actualizaciones.", + "site_community_protocol_title": "Protocolo abierto", + "site_community_protocol_desc": "La especificación del protocolo MECP se publica bajo CC0 — dominio público. Úsela libremente en cualquier proyecto.", + "site_community_contribute_title": "Participa", + "site_community_contribute_desc": "Añade traducciones, crea integraciones o mejora el protocolo. Lee CONTRIBUTING.md para empezar.", + "site_discussion_title": "Discusión", + "site_footer_desc": "Código abierto, protocolo abierto, diseñado para la resiliencia.", + "site_footer_links": "Enlaces", + "site_footer_licenses": "Licencias", + "site_footer_web_tool": "Herramienta web" + }, + "deprecations": {} +} diff --git a/MC1Services/Sources/MC1Services/MECP/Languages/fr.json b/MC1Services/Sources/MC1Services/MECP/Languages/fr.json new file mode 100644 index 0000000000..45982848ef --- /dev/null +++ b/MC1Services/Sources/MC1Services/MECP/Languages/fr.json @@ -0,0 +1,313 @@ +{ + "language": "fr", + "language_name": "Français", + "language_name_en": "French", + "language_name_latin": "Français", + "flag_emoji": "🇫🇷", + "text_direction": "ltr", + "severities": { + "0": { + "local": "MAYDAY", + "label": "MAYDAY / Danger de mort" + }, + "1": { + "local": "URGENT", + "label": "URGENT / Critique" + }, + "2": { + "local": "SÉCURITÉ", + "label": "SÉCURITÉ / Important" + }, + "3": { + "local": "ROUTINE", + "label": "ROUTINE / Normal" + } + }, + "categories": { + "M": { + "name": "Médical", + "icon": "medical" + }, + "T": { + "name": "Terrain / Infrastructure", + "icon": "terrain" + }, + "W": { + "name": "Météo / Environnement", + "icon": "weather" + }, + "S": { + "name": "Approvisionnement", + "icon": "supplies" + }, + "P": { + "name": "Position / Déplacement", + "icon": "position" + }, + "C": { + "name": "Coordination", + "icon": "coordination" + }, + "R": { + "name": "Réponse", + "icon": "response" + }, + "D": { + "name": "Exercice / Test", + "icon": "drill" + }, + "L": { + "name": "Quotidien / Loisirs", + "icon": "leisure" + }, + "X": { + "name": "Menace / Sécurité", + "icon": "threat" + }, + "H": { + "name": "Disponible / Offrir des ressources", + "icon": "resources" + }, + "B": { + "name": "Balise", + "icon": "beacon" + } + }, + "codes": { + "M01": "Blessure", + "M02": "Personne inconsciente", + "M03": "Difficulté respiratoire", + "M04": "Urgence cardiaque", + "M05": "Hypothermie", + "M06": "Hémorragie grave", + "M07": "Fracture / immobilisé", + "M08": "Brûlures", + "M09": "Victimes multiples", + "M10": "Décédé", + "M11": "Morsure / piqûre d’animal", + "M12": "Réaction allergique / anaphylaxie", + "M13": "Empoisonnement / exposition toxique", + "M14": "Personnes trouvées vivantes", + "M15": "Zone fouillée, aucune victime", + "T01": "Route bloquée", + "T02": "Pont détruit", + "T03": "Bâtiment effondré", + "T04": "Inondation", + "T05": "Glissement de terrain", + "T06": "Coupure de courant", + "T07": "Incendie", + "T08": "Avalanche", + "T09": "Chemin impraticable", + "T10": "Abri disponible", + "T11": "Noyade / sauvetage aquatique nécessaire", + "T12": "Contamination de l’eau", + "T13": "Séisme", + "T14": "Fuite de gaz", + "T15": "Déversement chimique / matières dangereuses", + "T16": "Accident de véhicule", + "T17": "Véhicule en feu", + "W01": "Tempête en approche", + "W02": "Visibilité nulle", + "W03": "Froid extrême", + "W04": "Chaleur extrême", + "W05": "Qualité de l’air dangereuse", + "W06": "Alerte tsunami / raz-de-marée", + "S01": "Besoin d’eau", + "S02": "Besoin de nourriture", + "S03": "Besoin de médicaments", + "S04": "Besoin de batterie / courant", + "S05": "Besoin de carburant", + "S06": "Besoin d’outils / équipement", + "P01": "Bloqué / coincé", + "P02": "Évacuation vers", + "P03": "Confiné sur place", + "P04": "En route vers", + "P05": "Aux coordonnées GPS", + "P06": "Perdu", + "P07": "Groupe séparé", + "C01": "Envoyer les secours", + "C02": "Besoin de transport", + "C03": "Relayer ce message", + "C04": "Confirmer la réception", + "C05": "Combien de personnes", + "C06": "Quel est le statut", + "C07": "Pouvez-vous atteindre", + "C08": "Rendez-vous à", + "R01": "Reçu", + "R02": "Secours en route", + "R03": "Arrivée dans [minutes]", + "R04": "Ne peut pas aider", + "R05": "Redirection vers", + "R06": "Veuillez patienter", + "R07": "Situation résolue / fin d’alerte", + "D01": "Ceci est un exercice", + "D02": "Ceci est un test", + "D03": "Fin de l’exercice", + "D04": "Ignorer le précédent — envoyé par erreur", + "L01": "Bière / boissons", + "L02": "Café", + "L03": "Repas prêt", + "L04": "Sommet atteint", + "L05": "Au camp", + "L06": "En retard", + "L07": "Bon signal ici", + "L08": "Occasion photo", + "L09": "Faune observée", + "L10": "Belle vue", + "L11": "Sentier en bon état", + "L12": "Sentier en mauvais état", + "L13": "Besoin d’une pause", + "L14": "Retour à la maison", + "L15": "Bonjour / pointage", + "L16": "Bonne nuit", + "L17": "Merci", + "L18": "On s’amuse bien", + "L19": "Festival / événement ici", + "L20": "Test de nœud / ping", + "X01": "Personne dangereuse / menace à proximité", + "X02": "Zone dangereuse — à éviter", + "X03": "Coups de feu / explosions entendus", + "X04": "Troubles civils / foule dangereuse", + "X05": "Vol / pillage signalé", + "X06": "Autorités / services d’urgence sur place", + "X07": "Point de contrôle / barrage routier (autorités)", + "H01": "Eau disponible", + "H02": "Nourriture disponible", + "H03": "Matériel médical disponible", + "H04": "Courant / recharge disponible", + "H05": "Carburant disponible", + "H06": "Outils / équipement disponibles", + "H07": "Abri / place pour [N] pers.", + "H08": "Transport / véhicule disponible", + "B01": "Balise de détresse automatique active — l'expéditeur peut ne pas répondre", + "B02": "Balise confirmée — réduire la fréquence d'émission", + "B03": "Annuler la balise — je vais bien" + }, + "ui": { + "send": "Envoyer", + "cancel": "Annuler", + "attach_gps": "Joindre GPS", + "attach_timestamp": "Horodatage (UTC)", + "add_count": "Ajouter un nombre", + "preview": "Aperçu", + "copy": "Copier", + "paste_decode": "Coller & décoder", + "severity_select": "Sélectionner la gravité", + "category_select": "Sélectionner la catégorie", + "code_select": "Sélectionner les codes", + "freetext_placeholder": "Texte optionnel...", + "parse_failed": "Message MECP — analyse incomplète", + "unknown_code": "Code inconnu", + "message_too_long": "Le message dépasse 200 octets", + "not_connected": "Aucun appareil connecté", + "connecting": "Connexion...", + "connected_to": "Connecté à", + "scan_devices": "Rechercher des appareils", + "compose": "Rédiger", + "decode": "Décoder", + "reference_card": "Carte de référence", + "history": "Historique", + "clear_history": "Effacer l’historique", + "export_history": "Exporter l’historique", + "drill_banner": "EXERCICE", + "untranslated_warning": "Ce texte n’est pas traduit", + "bytes_remaining": "octets restants", + "confirm_mayday": "Confirmer MAYDAY — maintenir pour envoyer", + "message_copied": "Message copié", + "gps_acquiring": "Acquisition GPS...", + "add_reference_tag": "Ajouter un tag d’incident", + "back": "Retour", + "next": "Suivant", + "add_more_codes": "Ajouter plus de codes", + "freetext_preview": "Texte libre & Aperçu", + "bytes_available": "octets disponibles pour plus de codes + texte", + "gps_unavailable": "GPS indisponible", + "gps_not_supported": "GPS non pris en charge", + "freetext_conventions": "Conventions de texte libre", + "no_messages": "Aucun message", + "severity_levels": "Niveaux de gravité", + "person_count": "Nombre de personnes", + "settings": "Paramètres", + "inbox": "Boîte de réception", + "device": "Appareil", + "language_label": "Langue", + "compose_defaults": "Paramètres de rédaction", + "auto_gps": "Joindre GPS auto (sév 0-1)", + "auto_timestamp": "Joindre horodatage auto", + "all_filter": "Tout", + "sent": "Envoyés", + "reset": "Réinitialiser", + "freetext": "Texte libre", + "severity_header": "Gravité", + "category_header": "Catégorie", + "codes_header": "Codes", + "preview_send": "Aperçu & Envoi", + "no_radio_queued": "Aucune radio connectée — le message sera mis en file", + "mecp_message": "Message MECP", + "inbox_tab": "Messages", + "reference_tab": "Référence", + "activate_beacon": "Activer la balise", + "beacon_active": "Balise de détresse active", + "beacon_cancel": "Annuler la balise", + "beacon_confirm": "Activer la balise de détresse ? Votre position sera émise automatiquement.", + "beacon_countdown": "Prochaine transmission dans", + "beacon_ack_received": "Balise confirmée par", + "beacon_drill": "BALISE D'EXERCICE", + "ack_waiting": "En attente de confirmation...", + "ack_no_response": "Aucune réponse reçue", + "ack_resend": "Renvoyer avec demande de relais ?", + "beacon_positions": "Historique des positions", + "beacon_from": "Balise de", + "beacon_last_seen": "Vu pour la dernière fois", + "beacon_duration": "Active depuis", + "site_nav_what": "Qu'est-ce que MECP", + "site_nav_demo": "Démo", + "site_nav_app": "Simulation d'app", + "site_nav_github": "GitHub", + "site_nav_discussion": "Discussion", + "site_hero_headline": "Communication d'urgence dans toutes les langues, sur tout réseau mesh", + "site_hero_sub": "MECP est un protocole ouvert qui encode les messages d'urgence en paquets minuscules transportables par toute radio mesh LoRa — compris instantanément en 20 langues.", + "site_cta_demo": "Essayer la démo", + "site_cta_github": "Voir sur GitHub", + "site_what_title": "Qu'est-ce que MECP ?", + "site_what_p1": "Quand une catastrophe frappe et que les antennes-relais s'éteignent, les bénévoles et secouristes comptent sur les radios mesh. Mais ces radios transportent très peu de données — souvent moins de 200 octets — et quand les équipes parlent des langues différentes, le sens critique se perd.", + "site_what_p2": "MECP (Mesh Emergency Communication Protocol) résout ce problème en encodant les situations d'urgence en messages compacts et structurés. Chaque message commence par un niveau de gravité, suivi de codes standardisés issus de 12 catégories — médical, terrain, météo, fournitures, coordination, et plus.", + "site_what_p3": "Comme chaque code a une traduction en 20 langues, le MAYDAY d'un bénévole tchèque est instantanément lisible par une équipe de secours japonaise. Pas d'interprète nécessaire, pas de bande passante gaspillée.", + "site_what_example_label": "Exemple de message", + "site_what_example_sev": "Gravité 0 — MAYDAY", + "site_what_example_codes": "Blessure + Inconscient + Route bloquée", + "site_what_example_pax": "3 personnes", + "site_what_example_gps": "Coordonnées GPS", + "site_what_example_time": "Horodatage (UTC)", + "site_what_example_lang": "Indication de langue", + "site_what_feat_codes": "108 codes dans 12 catégories", + "site_what_feat_langs": "20 langues prises en charge", + "site_what_feat_bytes": "Tient dans 200 octets", + "site_demo_title": "Démo en direct", + "site_demo_sub": "Composez un vrai message MECP et voyez-le décodé instantanément dans une autre langue.", + "site_demo_compose_label": "Composer", + "site_demo_decode_label": "Décodé", + "site_demo_swap_langs": "Échanger les langues", + "site_demo_raw_label": "Chaîne MECP brute", + "site_sim_title": "Simulation d'application", + "site_sim_sub": "Voyez comment MECP fonctionne sur un réseau mesh — composez sur un appareil, recevez sur un autre dans une langue différente.", + "site_sim_sender": "Émetteur", + "site_sim_receiver": "Récepteur", + "site_sim_send_btn": "Envoyer via mesh", + "site_sim_sending": "Envoi en cours...", + "site_sim_just_now": "à l'instant", + "site_sim_change_lang": "Changer de langue", + "site_community_title": "Communauté", + "site_community_github_desc": "Code source, documentation et exemples. Ajoutez une étoile au dépôt pour suivre les mises à jour.", + "site_community_protocol_title": "Protocole ouvert", + "site_community_protocol_desc": "La spécification du protocole MECP est publiée sous CC0 — domaine public. Utilisez-la librement dans tout projet.", + "site_community_contribute_title": "Participer", + "site_community_contribute_desc": "Ajoutez des traductions, créez des intégrations ou améliorez le protocole. Lisez CONTRIBUTING.md pour commencer.", + "site_discussion_title": "Discussion", + "site_footer_desc": "Open source, protocole ouvert, conçu pour la résilience.", + "site_footer_links": "Liens", + "site_footer_licenses": "Licences", + "site_footer_web_tool": "Outil web" + }, + "deprecations": {} +} diff --git a/MC1Services/Sources/MC1Services/MECP/Languages/it.json b/MC1Services/Sources/MC1Services/MECP/Languages/it.json new file mode 100644 index 0000000000..afb9eb049a --- /dev/null +++ b/MC1Services/Sources/MC1Services/MECP/Languages/it.json @@ -0,0 +1,313 @@ +{ + "language": "it", + "language_name": "Italiano", + "language_name_en": "Italian", + "language_name_latin": "Italiano", + "flag_emoji": "🇮🇹", + "text_direction": "ltr", + "severities": { + "0": { + "local": "MAYDAY", + "label": "MAYDAY / Pericolo di vita" + }, + "1": { + "local": "URGENTE", + "label": "URGENTE / Tempo critico" + }, + "2": { + "local": "SICUREZZA", + "label": "SICUREZZA / Importante" + }, + "3": { + "local": "ROUTINE", + "label": "ROUTINE / Normale" + } + }, + "categories": { + "M": { + "name": "Medico", + "icon": "medical" + }, + "T": { + "name": "Terreno / Infrastruttura", + "icon": "terrain" + }, + "W": { + "name": "Meteo / Ambiente", + "icon": "weather" + }, + "S": { + "name": "Forniture", + "icon": "supplies" + }, + "P": { + "name": "Posizione / Movimento", + "icon": "position" + }, + "C": { + "name": "Coordinamento", + "icon": "coordination" + }, + "R": { + "name": "Risposta", + "icon": "response" + }, + "D": { + "name": "Esercitazione / Test", + "icon": "drill" + }, + "L": { + "name": "Vita / Svago", + "icon": "leisure" + }, + "X": { + "name": "Minaccia / Sicurezza", + "icon": "threat" + }, + "H": { + "name": "Disponibile / Offerta risorse", + "icon": "resources" + }, + "B": { + "name": "Faro", + "icon": "beacon" + } + }, + "codes": { + "M01": "Ferita", + "M02": "Persona priva di sensi", + "M03": "Difficoltà respiratoria", + "M04": "Evento cardiaco", + "M05": "Ipotermia", + "M06": "Emorragia grave", + "M07": "Frattura / immobilizzato", + "M08": "Ustioni", + "M09": "Vittime multiple", + "M10": "Deceduto", + "M11": "Morso / puntura di animale", + "M12": "Reazione allergica / anafilassi", + "M13": "Avvelenamento / esposizione tossica", + "M14": "Persone trovate in vita", + "M15": "Area perlustrata, nessuna vittima", + "T01": "Strada bloccata", + "T02": "Ponte crollato", + "T03": "Edificio crollato", + "T04": "Alluvione", + "T05": "Frana", + "T06": "Mancanza di corrente", + "T07": "Incendio", + "T08": "Valanga", + "T09": "Sentiero impraticabile", + "T10": "Rifugio disponibile", + "T11": "Annegamento / soccorso acquatico necessario", + "T12": "Acqua contaminata", + "T13": "Terremoto", + "T14": "Fuga di gas", + "T15": "Sversamento chimico / HAZMAT", + "T16": "Incidente stradale", + "T17": "Veicolo in fiamme", + "W01": "Tempesta in avvicinamento", + "W02": "Visibilità nulla", + "W03": "Freddo estremo", + "W04": "Caldo estremo", + "W05": "Qualità dell'aria pericolosa", + "W06": "Allerta tsunami / mareggiata", + "S01": "Serve acqua", + "S02": "Serve cibo", + "S03": "Servono medicinali", + "S04": "Serve batteria / energia", + "S05": "Serve carburante", + "S06": "Servono attrezzi / attrezzatura", + "P01": "Bloccati / intrappolati", + "P02": "In evacuazione verso", + "P03": "Rifugiati sul posto", + "P04": "In viaggio verso", + "P05": "Alle coordinate GPS", + "P06": "Persi", + "P07": "Gruppo separato", + "C01": "Inviate soccorso", + "C02": "Serve trasporto", + "C03": "Inoltrare questo messaggio", + "C04": "Confermare ricezione", + "C05": "Quante persone?", + "C06": "Qual è lo stato?", + "C07": "Potete raggiungere?", + "C08": "Punto d'incontro a", + "R01": "Ricevuto", + "R02": "Aiuto in arrivo", + "R03": "Arrivo stimato [minuti]", + "R04": "Impossibile assistere", + "R05": "Reindirizzamento a", + "R06": "Attendere", + "R07": "Situazione risolta / tutto libero", + "D01": "Questa è un'esercitazione", + "D02": "Questo è un test", + "D03": "Fine dell'esercitazione", + "D04": "Ignorare il precedente — inviato per errore", + "L01": "Birra / bevande", + "L02": "Caffè", + "L03": "Cibo pronto", + "L04": "Vetta raggiunta", + "L05": "Al campo", + "L06": "In ritardo", + "L07": "Buon segnale qui", + "L08": "Occasione fotografica", + "L09": "Fauna avvistata", + "L10": "Bella vista", + "L11": "Sentiero in buone condizioni", + "L12": "Sentiero in cattive condizioni", + "L13": "Serve una pausa", + "L14": "In rientro", + "L15": "Buongiorno / check-in", + "L16": "Buonanotte", + "L17": "Grazie", + "L18": "Ci stiamo divertendo", + "L19": "Festival / evento qui", + "L20": "Test nodo / ping", + "X01": "Persona pericolosa / minaccia vicina", + "X02": "Zona non sicura — evitare", + "X03": "Spari / esplosioni uditi", + "X04": "Disordini civili / pericolo folla", + "X05": "Furto / saccheggio segnalato", + "X06": "Autorità / servizi di emergenza presenti", + "X07": "Posto di blocco / chiusura stradale (autorità)", + "H01": "Acqua disponibile", + "H02": "Cibo disponibile", + "H03": "Forniture mediche disponibili", + "H04": "Energia / ricarica disponibile", + "H05": "Carburante disponibile", + "H06": "Attrezzi / attrezzatura disponibile", + "H07": "Rifugio / spazio per [N]pax", + "H08": "Trasporto / veicolo disponibile", + "B01": "Faro di soccorso automatico attivo — il mittente potrebbe non rispondere", + "B02": "Faro confermato — ridurre la frequenza di trasmissione", + "B03": "Annulla faro — sto bene" + }, + "ui": { + "send": "Invia", + "cancel": "Annulla", + "attach_gps": "Allega GPS", + "attach_timestamp": "Timestamp (UTC)", + "add_count": "Aggiungi conteggio", + "preview": "Anteprima", + "copy": "Copia", + "paste_decode": "Incolla e decodifica", + "severity_select": "Seleziona gravità", + "category_select": "Seleziona categoria", + "code_select": "Seleziona codici", + "freetext_placeholder": "Testo opzionale...", + "parse_failed": "Messaggio MECP — analisi incompleta", + "unknown_code": "Codice sconosciuto", + "message_too_long": "Il messaggio supera i 200 byte", + "not_connected": "Nessun dispositivo connesso", + "connecting": "Connessione...", + "connected_to": "Connesso a", + "scan_devices": "Cerca dispositivi", + "compose": "Componi", + "decode": "Decodifica", + "reference_card": "Scheda di riferimento", + "history": "Cronologia", + "clear_history": "Cancella cronologia", + "export_history": "Esporta cronologia", + "drill_banner": "ESERCITAZIONE", + "untranslated_warning": "Questo testo non è tradotto", + "bytes_remaining": "byte rimanenti", + "confirm_mayday": "Conferma MAYDAY — tieni premuto per inviare", + "message_copied": "Messaggio copiato", + "gps_acquiring": "Acquisizione GPS...", + "add_reference_tag": "Aggiungi tag incidente", + "back": "Indietro", + "next": "Avanti", + "add_more_codes": "Aggiungi altri codici", + "freetext_preview": "Testo libero & Anteprima", + "bytes_available": "byte disponibili per più codici + testo", + "gps_unavailable": "GPS non disponibile", + "gps_not_supported": "GPS non supportato", + "freetext_conventions": "Convenzioni testo libero", + "no_messages": "Nessun messaggio", + "severity_levels": "Livelli di gravità", + "person_count": "Numero di persone", + "settings": "Impostazioni", + "inbox": "Posta in arrivo", + "device": "Dispositivo", + "language_label": "Lingua", + "compose_defaults": "Impostazioni predefinite", + "auto_gps": "Allega GPS auto (sev 0-1)", + "auto_timestamp": "Allega timestamp auto", + "all_filter": "Tutti", + "sent": "Inviati", + "reset": "Reimposta", + "freetext": "Testo libero", + "severity_header": "Gravità", + "category_header": "Categoria", + "codes_header": "Codici", + "preview_send": "Anteprima e Invio", + "no_radio_queued": "Nessuna radio connessa — il messaggio sarà in coda", + "mecp_message": "Messaggio MECP", + "inbox_tab": "Posta", + "reference_tab": "Riferimento", + "activate_beacon": "Attiva faro", + "beacon_active": "Faro di soccorso attivo", + "beacon_cancel": "Annulla faro", + "beacon_confirm": "Attivare il faro di soccorso? La tua posizione verrà trasmessa automaticamente.", + "beacon_countdown": "Prossima trasmissione tra", + "beacon_ack_received": "Faro confermato da", + "beacon_drill": "FARO DI ESERCITAZIONE", + "ack_waiting": "In attesa di conferma...", + "ack_no_response": "Nessuna risposta ricevuta", + "ack_resend": "Reinviare con richiesta di inoltro?", + "beacon_positions": "Cronologia posizioni", + "beacon_from": "Faro da", + "beacon_last_seen": "Ultimo avvistamento", + "beacon_duration": "Attivo da", + "site_nav_what": "Cos'è MECP", + "site_nav_demo": "Demo", + "site_nav_app": "Simulazione app", + "site_nav_github": "GitHub", + "site_nav_discussion": "Discussione", + "site_hero_headline": "Comunicazione d'emergenza in qualsiasi lingua, su qualsiasi rete mesh", + "site_hero_sub": "MECP è un protocollo aperto che codifica messaggi di emergenza in pacchetti minuscoli trasportabili da qualsiasi radio mesh LoRa — compresi istantaneamente in 20 lingue.", + "site_cta_demo": "Prova la demo", + "site_cta_github": "Vedi su GitHub", + "site_what_title": "Cos'è MECP?", + "site_what_p1": "Quando un disastro colpisce e le torri cellulari si spengono, volontari e soccorritori si affidano alle radio mesh. Ma le radio mesh trasportano pochissimi dati — spesso meno di 200 byte — e quando i team parlano lingue diverse, il significato critico si perde.", + "site_what_p2": "MECP (Mesh Emergency Communication Protocol) risolve questo codificando situazioni d'emergenza in messaggi compatti e strutturati. Ogni messaggio inizia con un livello di gravità, seguito da codici standardizzati di 12 categorie — medico, terreno, meteo, forniture, coordinamento e altro.", + "site_what_p3": "Poiché ogni codice ha una traduzione in 20 lingue, il MAYDAY di un volontario ceco è immediatamente leggibile da un team di soccorso giapponese. Nessun interprete necessario, nessuna larghezza di banda sprecata.", + "site_what_example_label": "Esempio di messaggio", + "site_what_example_sev": "Gravità 0 — MAYDAY", + "site_what_example_codes": "Lesione + Incosciente + Strada bloccata", + "site_what_example_pax": "3 persone", + "site_what_example_gps": "Coordinate GPS", + "site_what_example_time": "Timestamp (UTC)", + "site_what_example_lang": "Indicazione lingua", + "site_what_feat_codes": "108 codici in 12 categorie", + "site_what_feat_langs": "20 lingue supportate", + "site_what_feat_bytes": "Sta in 200 byte", + "site_demo_title": "Demo dal vivo", + "site_demo_sub": "Componi un vero messaggio MECP e vedilo decodificato istantaneamente in un'altra lingua.", + "site_demo_compose_label": "Componi", + "site_demo_decode_label": "Decodificato", + "site_demo_swap_langs": "Scambia lingue", + "site_demo_raw_label": "Stringa MECP grezza", + "site_sim_title": "Simulazione applicazione", + "site_sim_sub": "Guarda come funziona MECP su una rete mesh — componi su un dispositivo, ricevi su un altro in una lingua diversa.", + "site_sim_sender": "Mittente", + "site_sim_receiver": "Destinatario", + "site_sim_send_btn": "Invia via mesh", + "site_sim_sending": "Invio in corso...", + "site_sim_just_now": "adesso", + "site_sim_change_lang": "Cambia lingua", + "site_community_title": "Comunità", + "site_community_github_desc": "Codice sorgente, documentazione ed esempi. Metti una stella al repo per seguire gli aggiornamenti.", + "site_community_protocol_title": "Protocollo aperto", + "site_community_protocol_desc": "La specifica del protocollo MECP è rilasciata sotto CC0 — dominio pubblico. Usala liberamente in qualsiasi progetto.", + "site_community_contribute_title": "Partecipa", + "site_community_contribute_desc": "Aggiungi traduzioni, crea integrazioni o migliora il protocollo. Leggi CONTRIBUTING.md per iniziare.", + "site_discussion_title": "Discussione", + "site_footer_desc": "Open source, protocollo aperto, costruito per la resilienza.", + "site_footer_links": "Link", + "site_footer_licenses": "Licenze", + "site_footer_web_tool": "Strumento web" + }, + "deprecations": {} +} diff --git a/MC1Services/Sources/MC1Services/MECP/Languages/nl.json b/MC1Services/Sources/MC1Services/MECP/Languages/nl.json new file mode 100644 index 0000000000..b24aca51c2 --- /dev/null +++ b/MC1Services/Sources/MC1Services/MECP/Languages/nl.json @@ -0,0 +1,313 @@ +{ + "language": "nl", + "language_name": "Nederlands", + "language_name_en": "Dutch", + "language_name_latin": "Nederlands", + "flag_emoji": "🇳🇱", + "text_direction": "ltr", + "severities": { + "0": { + "local": "MAYDAY", + "label": "MAYDAY / Levensbedreigend" + }, + "1": { + "local": "DRINGEND", + "label": "DRINGEND / Tijdkritiek" + }, + "2": { + "local": "VEILIGHEID", + "label": "VEILIGHEID / Belangrijk" + }, + "3": { + "local": "ROUTINE", + "label": "ROUTINE / Normaal" + } + }, + "categories": { + "M": { + "name": "Medisch", + "icon": "medical" + }, + "T": { + "name": "Terrein / Infrastructuur", + "icon": "terrain" + }, + "W": { + "name": "Weer / Milieu", + "icon": "weather" + }, + "S": { + "name": "Benodigdheden", + "icon": "supplies" + }, + "P": { + "name": "Positie / Verplaatsing", + "icon": "position" + }, + "C": { + "name": "Coördinatie", + "icon": "coordination" + }, + "R": { + "name": "Reactie", + "icon": "response" + }, + "D": { + "name": "Oefening / Test", + "icon": "drill" + }, + "L": { + "name": "Dagelijks / Vrije tijd", + "icon": "leisure" + }, + "X": { + "name": "Dreiging / Veiligheid", + "icon": "threat" + }, + "H": { + "name": "Beschikbaar / Middelen aanbieden", + "icon": "resources" + }, + "B": { + "name": "Noodbaken", + "icon": "beacon" + } + }, + "codes": { + "M01": "Verwonding", + "M02": "Bewusteloos persoon", + "M03": "Ademhalingsproblemen", + "M04": "Hartincident", + "M05": "Onderkoeling", + "M06": "Ernstige bloeding", + "M07": "Breuk / niet mobiel", + "M08": "Brandwonden", + "M09": "Meerdere slachtoffers", + "M10": "Overleden", + "M11": "Dierenbeet / -steek", + "M12": "Allergische reactie / anafylaxie", + "M13": "Vergiftiging / giftige blootstelling", + "M14": "Personen levend gevonden", + "M15": "Gebied doorzocht, geen slachtoffers", + "T01": "Weg geblokkeerd", + "T02": "Brug vernield", + "T03": "Gebouw ingestort", + "T04": "Overstroming", + "T05": "Aardverschuiving", + "T06": "Stroomuitval", + "T07": "Brand", + "T08": "Lawine", + "T09": "Pad onbegaanbaar", + "T10": "Schuilplaats beschikbaar", + "T11": "Verdrinking / waterredding nodig", + "T12": "Watervervuiling", + "T13": "Aardbeving", + "T14": "Gaslek", + "T15": "Chemisch incident / gevaarlijke stoffen", + "T16": "Verkeersongeval", + "T17": "Voertuigbrand", + "W01": "Storm nadert", + "W02": "Zicht nul", + "W03": "Extreme koude", + "W04": "Extreme hitte", + "W05": "Luchtkwaliteit gevaarlijk", + "W06": "Tsunami- / stormvloedwaarschuwing", + "S01": "Water nodig", + "S02": "Voedsel nodig", + "S03": "Medicijnen nodig", + "S04": "Batterij / stroom nodig", + "S05": "Brandstof nodig", + "S06": "Gereedschap / uitrusting nodig", + "P01": "Gestrand / vastzittend", + "P02": "Evacuatie richting", + "P03": "Schuilen ter plaatse", + "P04": "Onderweg naar", + "P05": "Op GPS-coördinaten", + "P06": "Verdwaald", + "P07": "Groep gescheiden", + "C01": "Stuur redding", + "C02": "Transport nodig", + "C03": "Bericht doorsturen", + "C04": "Ontvangst bevestigen", + "C05": "Hoeveel personen", + "C06": "Wat is de status", + "C07": "Kun je bereiken", + "C08": "Verzamelpunt bij", + "R01": "Bevestigd", + "R02": "Hulp onderweg", + "R03": "Aankomst over [minuten]", + "R04": "Kan niet helpen", + "R05": "Doorverwijzing naar", + "R06": "Even wachten", + "R07": "Situatie opgelost / veilig", + "D01": "Dit is een oefening", + "D02": "Dit is een test", + "D03": "Einde oefening", + "D04": "Vorige negeren — per ongeluk verzonden", + "L01": "Bier / drankjes", + "L02": "Koffie", + "L03": "Eten klaar", + "L04": "Top bereikt", + "L05": "Op de camping", + "L06": "Ben te laat", + "L07": "Goed signaal hier", + "L08": "Fotomoment", + "L09": "Wild dier gespot", + "L10": "Prachtig uitzicht", + "L11": "Padcondities goed", + "L12": "Padcondities slecht", + "L13": "Pauze nodig", + "L14": "Op weg naar huis", + "L15": "Goedemorgen / check-in", + "L16": "Goedenacht", + "L17": "Bedankt", + "L18": "Veel plezier", + "L19": "Festival / evenement hier", + "L20": "Knooppunttest / ping", + "X01": "Gevaarlijk persoon / dreiging nabij", + "X02": "Gebied onveilig — vermijden", + "X03": "Schoten / explosies gehoord", + "X04": "Onrust / menigte gevaarlijk", + "X05": "Diefstal / plundering gemeld", + "X06": "Autoriteiten / hulpdiensten aanwezig", + "X07": "Controlepost / wegafsluiting (overheid)", + "H01": "Water beschikbaar", + "H02": "Voedsel beschikbaar", + "H03": "Medische voorraad beschikbaar", + "H04": "Stroom / oplaadpunt beschikbaar", + "H05": "Brandstof beschikbaar", + "H06": "Gereedschap / uitrusting beschikbaar", + "H07": "Schuilplaats / ruimte voor [N] pers.", + "H08": "Transport / voertuig beschikbaar", + "B01": "Automatisch noodbaken actief — afzender reageert mogelijk niet", + "B02": "Baken bevestigd — zendfrequentie verlagen", + "B03": "Baken annuleren — het gaat goed met mij" + }, + "ui": { + "send": "Verzenden", + "cancel": "Annuleren", + "attach_gps": "GPS toevoegen", + "attach_timestamp": "Tijdstempel (UTC)", + "add_count": "Aantal toevoegen", + "preview": "Voorbeeld", + "copy": "Kopiëren", + "paste_decode": "Plakken & decoderen", + "severity_select": "Ernst selecteren", + "category_select": "Categorie selecteren", + "code_select": "Codes selecteren", + "freetext_placeholder": "Optionele tekst...", + "parse_failed": "MECP-bericht — kon niet volledig worden geparsed", + "unknown_code": "Onbekende code", + "message_too_long": "Bericht overschrijdt 200 bytes", + "not_connected": "Geen apparaat verbonden", + "connecting": "Verbinden...", + "connected_to": "Verbonden met", + "scan_devices": "Apparaten zoeken", + "compose": "Opstellen", + "decode": "Decoderen", + "reference_card": "Referentiekaart", + "history": "Geschiedenis", + "clear_history": "Geschiedenis wissen", + "export_history": "Geschiedenis exporteren", + "drill_banner": "OEFENING", + "untranslated_warning": "Deze tekst is niet vertaald", + "bytes_remaining": "bytes resterend", + "confirm_mayday": "MAYDAY bevestigen — houd ingedrukt om te verzenden", + "message_copied": "Bericht gekopieerd", + "gps_acquiring": "GPS wordt bepaald...", + "add_reference_tag": "Incidenttag toevoegen", + "back": "Terug", + "next": "Volgende", + "add_more_codes": "Meer codes toevoegen", + "freetext_preview": "Vrije tekst & Voorbeeld", + "bytes_available": "bytes beschikbaar voor meer codes + tekst", + "gps_unavailable": "GPS niet beschikbaar", + "gps_not_supported": "GPS niet ondersteund", + "freetext_conventions": "Vrije tekst conventies", + "no_messages": "Nog geen berichten", + "severity_levels": "Ernstniveaus", + "person_count": "Aantal personen", + "settings": "Instellingen", + "inbox": "Postvak", + "device": "Apparaat", + "language_label": "Taal", + "compose_defaults": "Standaardinstellingen", + "auto_gps": "GPS automatisch toevoegen (ernst 0-1)", + "auto_timestamp": "Tijdstempel automatisch toevoegen", + "all_filter": "Alle", + "sent": "Verzonden", + "reset": "Reset", + "freetext": "Vrije tekst", + "severity_header": "Ernst", + "category_header": "Categorie", + "codes_header": "Codes", + "preview_send": "Voorbeeld & Verzenden", + "no_radio_queued": "Geen radio verbonden — bericht wordt in wachtrij geplaatst", + "mecp_message": "MECP-bericht", + "inbox_tab": "Postvak", + "reference_tab": "Referentie", + "activate_beacon": "Noodbaken activeren", + "beacon_active": "Noodbaken actief", + "beacon_cancel": "Baken annuleren", + "beacon_confirm": "Noodbaken activeren? Uw positie wordt automatisch uitgezonden.", + "beacon_countdown": "Volgende uitzending over", + "beacon_ack_received": "Baken bevestigd door", + "beacon_drill": "OEFENING BAKEN", + "ack_waiting": "Wachten op bevestiging...", + "ack_no_response": "Geen reactie ontvangen", + "ack_resend": "Opnieuw verzenden met doorstuurverzoek?", + "beacon_positions": "Positiegeschiedenis", + "beacon_from": "Baken van", + "beacon_last_seen": "Laatst gezien", + "beacon_duration": "Actief sinds", + "site_nav_what": "Wat is MECP", + "site_nav_demo": "Demo", + "site_nav_app": "App-simulatie", + "site_nav_github": "GitHub", + "site_nav_discussion": "Discussie", + "site_hero_headline": "Noodcommunicatie in elke taal, over elk mesh-netwerk", + "site_hero_sub": "MECP is een open protocol dat noodberichten codeert in kleine pakketjes die elke LoRa mesh-radio kan verzenden — direct begrijpelijk in 20 talen.", + "site_cta_demo": "Probeer de demo", + "site_cta_github": "Bekijk op GitHub", + "site_what_title": "Wat is MECP?", + "site_what_p1": "Wanneer rampen toeslaan en zendmasten uitvallen, vertrouwen vrijwilligers en hulpverleners op mesh-radio's om te coördineren. Maar mesh-radio's verzenden zeer weinig data — vaak minder dan 200 bytes — en wanneer teams verschillende talen spreken, gaat cruciale betekenis verloren.", + "site_what_p2": "MECP (Mesh Emergency Communication Protocol) lost dit op door noodsituaties te coderen in compacte, gestructureerde berichten. Elk bericht begint met een ernst-niveau, gevolgd door gestandaardiseerde codes uit 12 categorieën — medisch, terrein, weer, voorraden, coördinatie en meer.", + "site_what_p3": "Omdat elke code een vertaling heeft in 20 talen, is de MAYDAY van een Tsjechische vrijwilliger direct leesbaar voor een Japans reddingsteam. Geen tolk nodig, geen bandbreedte verspild.", + "site_what_example_label": "Voorbeeldbericht", + "site_what_example_sev": "Ernst 0 — MAYDAY", + "site_what_example_codes": "Verwonding + Bewusteloos + Weg geblokkeerd", + "site_what_example_pax": "3 personen", + "site_what_example_gps": "GPS-coördinaten", + "site_what_example_time": "Tijdstempel (UTC)", + "site_what_example_lang": "Taalhint", + "site_what_feat_codes": "108 codes in 12 categorieën", + "site_what_feat_langs": "20 talen ondersteund", + "site_what_feat_bytes": "Past in 200 bytes", + "site_demo_title": "Live demo", + "site_demo_sub": "Stel een echt MECP-bericht samen en zie het direct gedecodeerd in een andere taal.", + "site_demo_compose_label": "Samenstellen", + "site_demo_decode_label": "Gedecodeerd", + "site_demo_swap_langs": "Talen wisselen", + "site_demo_raw_label": "Ruwe MECP-string", + "site_sim_title": "App-simulatie", + "site_sim_sub": "Bekijk hoe MECP werkt over een mesh-netwerk — stel samen op één apparaat, ontvang op een ander in een andere taal.", + "site_sim_sender": "Verzender", + "site_sim_receiver": "Ontvanger", + "site_sim_send_btn": "Verzend via mesh", + "site_sim_sending": "Verzenden...", + "site_sim_just_now": "zojuist", + "site_sim_change_lang": "Taal wijzigen", + "site_community_title": "Community", + "site_community_github_desc": "Broncode, documentatie en voorbeelden. Geef het repo een ster om updates te volgen.", + "site_community_protocol_title": "Open protocol", + "site_community_protocol_desc": "De MECP-protocolspecificatie is gepubliceerd onder CC0 — publiek domein. Gebruik het vrij in elk project.", + "site_community_contribute_title": "Doe mee", + "site_community_contribute_desc": "Voeg vertalingen toe, maak integraties of verbeter het protocol. Lees CONTRIBUTING.md om te beginnen.", + "site_discussion_title": "Discussie", + "site_footer_desc": "Open source, open protocol, gebouwd voor veerkracht.", + "site_footer_links": "Links", + "site_footer_licenses": "Licenties", + "site_footer_web_tool": "Webtool" + }, + "deprecations": {} +} diff --git a/MC1Services/Sources/MC1Services/MECP/Languages/pl.json b/MC1Services/Sources/MC1Services/MECP/Languages/pl.json new file mode 100644 index 0000000000..bb3269b23d --- /dev/null +++ b/MC1Services/Sources/MC1Services/MECP/Languages/pl.json @@ -0,0 +1,313 @@ +{ + "language": "pl", + "language_name": "Polski", + "language_name_en": "Polish", + "language_name_latin": "Polski", + "flag_emoji": "🇵🇱", + "text_direction": "ltr", + "severities": { + "0": { + "local": "MAYDAY", + "label": "MAYDAY / Zagrożenie życia" + }, + "1": { + "local": "PILNE", + "label": "PILNE / Czas krytyczny" + }, + "2": { + "local": "BEZPIECZEŃSTWO", + "label": "BEZPIECZEŃSTWO / Ważne" + }, + "3": { + "local": "RUTYNA", + "label": "RUTYNA / Normalne" + } + }, + "categories": { + "M": { + "name": "Medyczne", + "icon": "medical" + }, + "T": { + "name": "Teren / Infrastruktura", + "icon": "terrain" + }, + "W": { + "name": "Pogoda / Środowisko", + "icon": "weather" + }, + "S": { + "name": "Zaopatrzenie", + "icon": "supplies" + }, + "P": { + "name": "Pozycja / Ruch", + "icon": "position" + }, + "C": { + "name": "Koordynacja", + "icon": "coordination" + }, + "R": { + "name": "Odpowiedź", + "icon": "response" + }, + "D": { + "name": "Ćwiczenia / Test", + "icon": "drill" + }, + "L": { + "name": "Życie / Wypoczynek", + "icon": "leisure" + }, + "X": { + "name": "Zagrożenie / Bezpieczeństwo", + "icon": "threat" + }, + "H": { + "name": "Dostępne / Oferta zasobów", + "icon": "resources" + }, + "B": { + "name": "Sygnał", + "icon": "beacon" + } + }, + "codes": { + "M01": "Uraz", + "M02": "Osoba nieprzytomna", + "M03": "Trudności z oddychaniem", + "M04": "Zdarzenie kardiologiczne", + "M05": "Hipotermia", + "M06": "Silne krwawienie", + "M07": "Złamanie / unieruchomiony", + "M08": "Oparzenia", + "M09": "Wiele ofiar", + "M10": "Zgon", + "M11": "Ugryzienie / użądlenie przez zwierzę", + "M12": "Reakcja alergiczna / anafilaksja", + "M13": "Zatrucie / narażenie na toksyny", + "M14": "Osoby odnalezione żywe", + "M15": "Teren przeszukany, brak ofiar", + "T01": "Droga zablokowana", + "T02": "Most zniszczony", + "T03": "Budynek zawalony", + "T04": "Powódź", + "T05": "Osunięcie ziemi", + "T06": "Brak prądu", + "T07": "Pożar", + "T08": "Lawina", + "T09": "Szlak nieprzejezdny", + "T10": "Schronienie dostępne", + "T11": "Tonięcie / potrzebny ratunek wodny", + "T12": "Skażenie wody", + "T13": "Trzęsienie ziemi", + "T14": "Wyciek gazu", + "T15": "Wyciek chemiczny / HAZMAT", + "T16": "Wypadek drogowy", + "T17": "Pożar pojazdu", + "W01": "Zbliża się burza", + "W02": "Zerowa widoczność", + "W03": "Ekstremalny mróz", + "W04": "Ekstremalne upały", + "W05": "Niebezpieczna jakość powietrza", + "W06": "Ostrzeżenie przed tsunami / falą sztormową", + "S01": "Potrzebna woda", + "S02": "Potrzebna żywność", + "S03": "Potrzebne leki", + "S04": "Potrzebna bateria / zasilanie", + "S05": "Potrzebne paliwo", + "S06": "Potrzebne narzędzia / sprzęt", + "P01": "Uwięzieni / zablokowani", + "P02": "Ewakuacja w kierunku", + "P03": "Schronienie na miejscu", + "P04": "W drodze do", + "P05": "Na współrzędnych GPS", + "P06": "Zagubieni", + "P07": "Grupa rozdzielona", + "C01": "Wyślijcie ratunek", + "C02": "Potrzebny transport", + "C03": "Przekażcie tę wiadomość", + "C04": "Potwierdźcie odbiór", + "C05": "Ile osób?", + "C06": "Jaki jest stan?", + "C07": "Czy możecie dotrzeć?", + "C08": "Zbiórka w", + "R01": "Potwierdzono", + "R02": "Pomoc w drodze", + "R03": "Czas przybycia [minuty]", + "R04": "Nie możemy pomóc", + "R05": "Przekierowanie do", + "R06": "Czekajcie", + "R07": "Sytuacja opanowana / koniec zagrożenia", + "D01": "To ćwiczenia", + "D02": "To jest test", + "D03": "Koniec ćwiczeń", + "D04": "Zignorujcie poprzednie — wysłano przez pomyłkę", + "L01": "Piwo / napoje", + "L02": "Kawa", + "L03": "Jedzenie gotowe", + "L04": "Szczyt zdobyty", + "L05": "Na obozie", + "L06": "Spóźniam się", + "L07": "Dobry sygnał tutaj", + "L08": "Okazja na zdjęcie", + "L09": "Zauważono dziką zwierzynę", + "L10": "Piękny widok", + "L11": "Szlak w dobrym stanie", + "L12": "Szlak w złym stanie", + "L13": "Potrzebuję przerwy", + "L14": "Wracam do domu", + "L15": "Dzień dobry / meldunek", + "L16": "Dobranoc", + "L17": "Dziękuję", + "L18": "Dobrze się bawimy", + "L19": "Festiwal / wydarzenie tutaj", + "L20": "Test węzła / ping", + "X01": "Niebezpieczna osoba / zagrożenie w pobliżu", + "X02": "Strefa niebezpieczna — unikać", + "X03": "Słyszano strzały / eksplozje", + "X04": "Zamieszki / zagrożenie tłumem", + "X05": "Zgłoszono kradzież / grabież", + "X06": "Władze / służby ratunkowe na miejscu", + "X07": "Punkt kontrolny / blokada drogi (władze)", + "H01": "Dostępna woda", + "H02": "Dostępna żywność", + "H03": "Dostępne środki medyczne", + "H04": "Dostępne zasilanie / ładowanie", + "H05": "Dostępne paliwo", + "H06": "Dostępne narzędzia / sprzęt", + "H07": "Dostępne schronienie / miejsce dla [N]os.", + "H08": "Dostępny transport / pojazd", + "B01": "Automatyczny sygnał alarmowy aktywny — nadawca może nie odpowiadać", + "B02": "Sygnał potwierdzony — zmniejszyć częstotliwość nadawania", + "B03": "Anuluj sygnał — wszystko w porządku" + }, + "ui": { + "send": "Wyślij", + "cancel": "Anuluj", + "attach_gps": "Dołącz GPS", + "attach_timestamp": "Znacznik czasu (UTC)", + "add_count": "Dodaj liczbę", + "preview": "Podgląd", + "copy": "Kopiuj", + "paste_decode": "Wklej i dekoduj", + "severity_select": "Wybierz priorytet", + "category_select": "Wybierz kategorię", + "code_select": "Wybierz kody", + "freetext_placeholder": "Tekst opcjonalny...", + "parse_failed": "Wiadomość MECP — nie udało się w pełni odczytać", + "unknown_code": "Nieznany kod", + "message_too_long": "Wiadomość przekracza 200 bajtów", + "not_connected": "Brak połączonego urządzenia", + "connecting": "Łączenie...", + "connected_to": "Połączono z", + "scan_devices": "Szukaj urządzeń", + "compose": "Utwórz", + "decode": "Dekoduj", + "reference_card": "Karta referencyjna", + "history": "Historia", + "clear_history": "Wyczyść historię", + "export_history": "Eksportuj historię", + "drill_banner": "ĆWICZENIA", + "untranslated_warning": "Ten tekst nie jest przetłumaczony", + "bytes_remaining": "bajtów pozostało", + "confirm_mayday": "Potwierdź MAYDAY — przytrzymaj aby wysłać", + "message_copied": "Wiadomość skopiowana", + "gps_acquiring": "Uzyskiwanie GPS...", + "add_reference_tag": "Dodaj tag incydentu", + "back": "Wstecz", + "next": "Dalej", + "add_more_codes": "Dodaj więcej kodów", + "freetext_preview": "Tekst i podgląd", + "bytes_available": "bajtów dostępnych na więcej kodów + tekst", + "gps_unavailable": "GPS niedostępny", + "gps_not_supported": "GPS nieobsługiwany", + "freetext_conventions": "Konwencje tekstu", + "no_messages": "Brak wiadomości", + "severity_levels": "Poziomy ważności", + "person_count": "Liczba osób", + "settings": "Ustawienia", + "inbox": "Skrzynka", + "device": "Urządzenie", + "language_label": "Język", + "compose_defaults": "Domyślne ustawienia", + "auto_gps": "Automatycznie dołącz GPS (poz. 0-1)", + "auto_timestamp": "Automatycznie dołącz znacznik czasu", + "all_filter": "Wszystkie", + "sent": "Wysłane", + "reset": "Resetuj", + "freetext": "Dowolny tekst", + "severity_header": "Priorytet", + "category_header": "Kategoria", + "codes_header": "Kody", + "preview_send": "Podgląd i Wyślij", + "no_radio_queued": "Brak połączenia z radiem — wiadomość zostanie zakolejkowana", + "mecp_message": "Wiadomość MECP", + "inbox_tab": "Odbiór", + "reference_tab": "Kody", + "activate_beacon": "Aktywuj sygnał", + "beacon_active": "Sygnał alarmowy aktywny", + "beacon_cancel": "Anuluj sygnał", + "beacon_confirm": "Aktywować sygnał alarmowy? Twoja pozycja będzie nadawana automatycznie.", + "beacon_countdown": "Następna transmisja za", + "beacon_ack_received": "Sygnał potwierdzony przez", + "beacon_drill": "SYGNAŁ ĆWICZEBNY", + "ack_waiting": "Oczekiwanie na potwierdzenie...", + "ack_no_response": "Brak odpowiedzi", + "ack_resend": "Wysłać ponownie z prośbą o przekazanie?", + "beacon_positions": "Historia pozycji", + "beacon_from": "Sygnał od", + "beacon_last_seen": "Ostatnio widziany", + "beacon_duration": "Aktywny od", + "site_nav_what": "Czym jest MECP", + "site_nav_demo": "Demo", + "site_nav_app": "Symulacja aplikacji", + "site_nav_github": "GitHub", + "site_nav_discussion": "Dyskusja", + "site_hero_headline": "Komunikacja kryzysowa w każdym języku, przez każdą sieć mesh", + "site_hero_sub": "MECP to otwarty protokół, który koduje wiadomości alarmowe w małych pakietach, które przeniesie każde radio mesh LoRa — zrozumiałe natychmiast w 20 językach.", + "site_cta_demo": "Wypróbuj demo", + "site_cta_github": "Zobacz na GitHub", + "site_what_title": "Czym jest MECP?", + "site_what_p1": "Gdy nadchodzi katastrofa i wieże komórkowe gasną, wolontariusze i ratownicy polegają na radiach mesh. Ale radia mesh przenoszą bardzo mało danych — często poniżej 200 bajtów — a gdy zespoły mówią różnymi językami, kluczowe znaczenie ginie.", + "site_what_p2": "MECP (Mesh Emergency Communication Protocol) rozwiązuje to, kodując sytuacje kryzysowe w kompaktowe, ustrukturyzowane wiadomości. Każda wiadomość zaczyna się od poziomu ważności, po którym następują standardowe kody z 12 kategorii — medyczna, teren, pogoda, zaopatrzenie, koordynacja i więcej.", + "site_what_p3": "Ponieważ każdy kod ma tłumaczenie na 20 języków, MAYDAY czeskiego wolontariusza jest natychmiast czytelny dla japońskiego zespołu ratunkowego. Bez tłumacza, bez marnowania pasma.", + "site_what_example_label": "Przykładowa wiadomość", + "site_what_example_sev": "Ważność 0 — MAYDAY", + "site_what_example_codes": "Obrażenia + Nieprzytomny + Droga zablokowana", + "site_what_example_pax": "3 osoby", + "site_what_example_gps": "Współrzędne GPS", + "site_what_example_time": "Znacznik czasu (UTC)", + "site_what_example_lang": "Wskazówka językowa", + "site_what_feat_codes": "108 kodów w 12 kategoriach", + "site_what_feat_langs": "Obsługa 20 języków", + "site_what_feat_bytes": "Mieści się w 200 bajtach", + "site_demo_title": "Demo na żywo", + "site_demo_sub": "Utwórz prawdziwą wiadomość MECP i zobacz ją natychmiast zdekodowaną w innym języku.", + "site_demo_compose_label": "Tworzenie", + "site_demo_decode_label": "Zdekodowane", + "site_demo_swap_langs": "Zamień języki", + "site_demo_raw_label": "Surowy ciąg MECP", + "site_sim_title": "Symulacja aplikacji", + "site_sim_sub": "Zobacz, jak MECP działa w sieci mesh — utwórz na jednym urządzeniu, odbierz na drugim w innym języku.", + "site_sim_sender": "Nadawca", + "site_sim_receiver": "Odbiorca", + "site_sim_send_btn": "Wyślij przez mesh", + "site_sim_sending": "Wysyłanie...", + "site_sim_just_now": "właśnie teraz", + "site_sim_change_lang": "Zmień język", + "site_community_title": "Społeczność", + "site_community_github_desc": "Kod źródłowy, dokumentacja i przykłady. Daj gwiazdkę repozytorium, aby śledzić aktualizacje.", + "site_community_protocol_title": "Otwarty protokół", + "site_community_protocol_desc": "Specyfikacja protokołu MECP jest opublikowana pod CC0 — domena publiczna. Używaj swobodnie w każdym projekcie.", + "site_community_contribute_title": "Dołącz", + "site_community_contribute_desc": "Dodawaj tłumaczenia, twórz integracje lub ulepszaj protokół. Przeczytaj CONTRIBUTING.md, aby zacząć.", + "site_discussion_title": "Dyskusja", + "site_footer_desc": "Open source, otwarty protokół, zbudowany z myślą o odporności.", + "site_footer_links": "Linki", + "site_footer_licenses": "Licencje", + "site_footer_web_tool": "Narzędzie webowe" + }, + "deprecations": {} +} diff --git a/MC1Services/Sources/MC1Services/MECP/Languages/pt.json b/MC1Services/Sources/MC1Services/MECP/Languages/pt.json new file mode 100644 index 0000000000..d7b87d369e --- /dev/null +++ b/MC1Services/Sources/MC1Services/MECP/Languages/pt.json @@ -0,0 +1,313 @@ +{ + "language": "pt", + "language_name": "Português", + "language_name_en": "Portuguese", + "language_name_latin": "Português", + "flag_emoji": "🇵🇹", + "text_direction": "ltr", + "severities": { + "0": { + "local": "MAYDAY", + "label": "MAYDAY / Risco de vida" + }, + "1": { + "local": "URGENTE", + "label": "URGENTE / Crítico no tempo" + }, + "2": { + "local": "SEGURANÇA", + "label": "SEGURANÇA / Importante" + }, + "3": { + "local": "ROTINA", + "label": "ROTINA / Normal" + } + }, + "categories": { + "M": { + "name": "Médico", + "icon": "medical" + }, + "T": { + "name": "Terreno / Infraestrutura", + "icon": "terrain" + }, + "W": { + "name": "Meteorologia / Ambiente", + "icon": "weather" + }, + "S": { + "name": "Suprimentos", + "icon": "supplies" + }, + "P": { + "name": "Posição / Movimento", + "icon": "position" + }, + "C": { + "name": "Coordenação", + "icon": "coordination" + }, + "R": { + "name": "Resposta", + "icon": "response" + }, + "D": { + "name": "Simulacro / Teste", + "icon": "drill" + }, + "L": { + "name": "Vida / Lazer", + "icon": "leisure" + }, + "X": { + "name": "Ameaça / Segurança", + "icon": "threat" + }, + "H": { + "name": "Disponível / Oferta de Recursos", + "icon": "resources" + }, + "B": { + "name": "Baliza", + "icon": "beacon" + } + }, + "codes": { + "M01": "Ferimento", + "M02": "Pessoa inconsciente", + "M03": "Dificuldade respiratória", + "M04": "Evento cardíaco", + "M05": "Hipotermia", + "M06": "Hemorragia grave", + "M07": "Fratura / imóvel", + "M08": "Queimaduras", + "M09": "Múltiplas vítimas", + "M10": "Falecido", + "M11": "Mordida / picada de animal", + "M12": "Reação alérgica / anafilaxia", + "M13": "Envenenamento / exposição tóxica", + "M14": "Pessoas localizadas com vida", + "M15": "Área pesquisada, sem vítimas", + "T01": "Estrada bloqueada", + "T02": "Ponte destruída", + "T03": "Edifício desabado", + "T04": "Inundação", + "T05": "Deslizamento de terra", + "T06": "Sem eletricidade", + "T07": "Incêndio", + "T08": "Avalanche", + "T09": "Caminho intransitável", + "T10": "Abrigo disponível", + "T11": "Afogamento / resgate aquático necessário", + "T12": "Contaminação da água", + "T13": "Terramoto", + "T14": "Fuga de gás", + "T15": "Derrame químico / HAZMAT", + "T16": "Acidente de viação", + "T17": "Veículo em chamas", + "W01": "Tempestade a aproximar-se", + "W02": "Visibilidade nula", + "W03": "Frio extremo", + "W04": "Calor extremo", + "W05": "Qualidade do ar perigosa", + "W06": "Alerta de tsunami / maré de tempestade", + "S01": "Precisa de água", + "S02": "Precisa de comida", + "S03": "Precisa de medicação", + "S04": "Precisa de bateria / energia", + "S05": "Precisa de combustível", + "S06": "Precisa de ferramentas / equipamento", + "P01": "Retido / preso", + "P02": "A evacuar em direção a", + "P03": "Abrigado no local", + "P04": "A caminho de", + "P05": "Nas coordenadas GPS", + "P06": "Perdido", + "P07": "Grupo separado", + "C01": "Enviar resgate", + "C02": "Precisa de transporte", + "C03": "Retransmitir esta mensagem", + "C04": "Confirmar receção", + "C05": "Quantas pessoas", + "C06": "Qual é o estado", + "C07": "Consegue contactar", + "C08": "Encontro em", + "R01": "Recebido", + "R02": "Ajuda a caminho", + "R03": "Chegada em [minutos]", + "R04": "Não é possível ajudar", + "R05": "Redirecionando para", + "R06": "Aguarde", + "R07": "Situação resolvida / tudo limpo", + "D01": "Isto é um simulacro", + "D02": "Isto é um teste", + "D03": "Fim do simulacro", + "D04": "Ignorar anterior — enviado por erro", + "L01": "Cerveja / bebidas", + "L02": "Café", + "L03": "Comida pronta", + "L04": "Cume alcançado", + "L05": "No acampamento", + "L06": "Atrasado", + "L07": "Bom sinal aqui", + "L08": "Oportunidade de foto", + "L09": "Vida selvagem avistada", + "L10": "Vista bonita", + "L11": "Condições do trilho boas", + "L12": "Condições do trilho más", + "L13": "Preciso de uma pausa", + "L14": "A caminho de casa", + "L15": "Bom dia / check-in", + "L16": "Boa noite", + "L17": "Obrigado", + "L18": "A divertir-me", + "L19": "Festival / evento aqui", + "L20": "Teste de nó / ping", + "X01": "Pessoa perigosa / ameaça próxima", + "X02": "Área insegura — evitar", + "X03": "Tiros / explosões ouvidos", + "X04": "Agitação civil / perigo de multidão", + "X05": "Roubo / pilhagem reportados", + "X06": "Autoridades / serviços de emergência presentes", + "X07": "Posto de controlo / estrada cortada (autoridade)", + "H01": "Água disponível", + "H02": "Comida disponível", + "H03": "Material médico disponível", + "H04": "Energia / carregamento disponível", + "H05": "Combustível disponível", + "H06": "Ferramentas / equipamento disponível", + "H07": "Abrigo / espaço para [N]pax", + "H08": "Transporte / veículo disponível", + "B01": "Baliza de socorro automática ativa — remetente pode não responder", + "B02": "Baliza confirmada — reduzir frequência de transmissão", + "B03": "Cancelar baliza — estou bem" + }, + "ui": { + "send": "Enviar", + "cancel": "Cancelar", + "attach_gps": "Anexar GPS", + "attach_timestamp": "Carimbo de hora (UTC)", + "add_count": "Adicionar contagem", + "preview": "Pré-visualizar", + "copy": "Copiar", + "paste_decode": "Colar e descodificar", + "severity_select": "Selecionar severidade", + "category_select": "Selecionar categoria", + "code_select": "Selecionar códigos", + "freetext_placeholder": "Texto opcional...", + "parse_failed": "Mensagem MECP — não foi possível analisar", + "unknown_code": "Código desconhecido", + "message_too_long": "Mensagem excede 200 bytes", + "not_connected": "Nenhum dispositivo ligado", + "connecting": "A ligar...", + "connected_to": "Ligado a", + "scan_devices": "Procurar dispositivos", + "compose": "Compor", + "decode": "Descodificar", + "reference_card": "Cartão de Referência", + "history": "Histórico", + "clear_history": "Limpar histórico", + "export_history": "Exportar histórico", + "drill_banner": "SIMULACRO", + "untranslated_warning": "Este texto não está traduzido", + "bytes_remaining": "bytes restantes", + "confirm_mayday": "Confirmar MAYDAY — mantenha premido para enviar", + "message_copied": "Mensagem copiada", + "gps_acquiring": "A obter GPS...", + "add_reference_tag": "Adicionar etiqueta de incidente", + "back": "Voltar", + "next": "Seguinte", + "add_more_codes": "Adicionar mais códigos", + "freetext_preview": "Texto livre e Pré-visualização", + "bytes_available": "bytes disponíveis para mais códigos + texto", + "gps_unavailable": "GPS indisponível", + "gps_not_supported": "GPS não suportado", + "freetext_conventions": "Convenções de texto livre", + "no_messages": "Nenhuma mensagem ainda", + "severity_levels": "Níveis de gravidade", + "person_count": "Número de pessoas", + "settings": "Definições", + "inbox": "Caixa de entrada", + "device": "Dispositivo", + "language_label": "Idioma", + "compose_defaults": "Padrões de composição", + "auto_gps": "Anexar GPS auto (sev 0-1)", + "auto_timestamp": "Anexar hora auto", + "all_filter": "Todos", + "sent": "Enviados", + "reset": "Reiniciar", + "freetext": "Texto livre", + "severity_header": "Severidade", + "category_header": "Categoria", + "codes_header": "Códigos", + "preview_send": "Pré-visualizar e Enviar", + "no_radio_queued": "Sem rádio ligado — a mensagem será colocada em fila", + "mecp_message": "Mensagem MECP", + "inbox_tab": "Entrada", + "reference_tab": "Referência", + "activate_beacon": "Ativar baliza", + "beacon_active": "Baliza de socorro ativa", + "beacon_cancel": "Cancelar baliza", + "beacon_confirm": "Ativar baliza de socorro? A sua posição será transmitida automaticamente.", + "beacon_countdown": "Próxima transmissão em", + "beacon_ack_received": "Baliza confirmada por", + "beacon_drill": "BALIZA DE EXERCÍCIO", + "ack_waiting": "Aguardando confirmação...", + "ack_no_response": "Sem resposta recebida", + "ack_resend": "Reenviar com pedido de retransmissão?", + "beacon_positions": "Histórico de posições", + "beacon_from": "Baliza de", + "beacon_last_seen": "Visto pela última vez", + "beacon_duration": "Ativa há", + "site_nav_what": "O que é MECP", + "site_nav_demo": "Demo", + "site_nav_app": "Simulação de app", + "site_nav_github": "GitHub", + "site_nav_discussion": "Discussão", + "site_hero_headline": "Comunicação de emergência em qualquer idioma, através de qualquer rede mesh", + "site_hero_sub": "MECP é um protocolo aberto que codifica mensagens de emergência em pacotes minúsculos que qualquer rádio mesh LoRa pode transportar — compreendidos instantaneamente em 20 idiomas.", + "site_cta_demo": "Experimentar a demo", + "site_cta_github": "Ver no GitHub", + "site_what_title": "O que é MECP?", + "site_what_p1": "Quando um desastre acontece e as torres de telecomunicação ficam sem energia, voluntários e socorristas dependem de rádios mesh para coordenar. Mas rádios mesh transportam muito poucos dados — frequentemente menos de 200 bytes — e quando as equipas falam idiomas diferentes, o significado crítico perde-se.", + "site_what_p2": "O MECP (Mesh Emergency Communication Protocol) resolve isto codificando situações de emergência em mensagens compactas e estruturadas. Cada mensagem começa com um nível de gravidade, seguido de códigos padronizados de 12 categorias — médica, terreno, meteorologia, mantimentos, coordenação e mais.", + "site_what_p3": "Como cada código tem tradução em 20 idiomas, o MAYDAY de um voluntário checo é instantaneamente legível para uma equipa de resgate japonesa. Sem intérprete, sem desperdício de largura de banda.", + "site_what_example_label": "Exemplo de mensagem", + "site_what_example_sev": "Gravidade 0 — MAYDAY", + "site_what_example_codes": "Lesão + Inconsciente + Estrada bloqueada", + "site_what_example_pax": "3 pessoas", + "site_what_example_gps": "Coordenadas GPS", + "site_what_example_time": "Carimbo temporal (UTC)", + "site_what_example_lang": "Indicação de idioma", + "site_what_feat_codes": "108 códigos em 12 categorias", + "site_what_feat_langs": "20 idiomas suportados", + "site_what_feat_bytes": "Cabe em 200 bytes", + "site_demo_title": "Demo ao vivo", + "site_demo_sub": "Componha uma mensagem MECP real e veja-a descodificada instantaneamente noutro idioma.", + "site_demo_compose_label": "Compor", + "site_demo_decode_label": "Descodificado", + "site_demo_swap_langs": "Trocar idiomas", + "site_demo_raw_label": "String MECP em bruto", + "site_sim_title": "Simulação de aplicação", + "site_sim_sub": "Veja como o MECP funciona numa rede mesh — componha num dispositivo, receba noutro num idioma diferente.", + "site_sim_sender": "Remetente", + "site_sim_receiver": "Destinatário", + "site_sim_send_btn": "Enviar via mesh", + "site_sim_sending": "A enviar...", + "site_sim_just_now": "agora mesmo", + "site_sim_change_lang": "Mudar idioma", + "site_community_title": "Comunidade", + "site_community_github_desc": "Código-fonte, documentação e exemplos. Dê uma estrela ao repositório para acompanhar atualizações.", + "site_community_protocol_title": "Protocolo aberto", + "site_community_protocol_desc": "A especificação do protocolo MECP é publicada sob CC0 — domínio público. Use-a livremente em qualquer projeto.", + "site_community_contribute_title": "Participe", + "site_community_contribute_desc": "Adicione traduções, crie integrações ou melhore o protocolo. Leia CONTRIBUTING.md para começar.", + "site_discussion_title": "Discussão", + "site_footer_desc": "Código aberto, protocolo aberto, construído para resiliência.", + "site_footer_links": "Ligações", + "site_footer_licenses": "Licenças", + "site_footer_web_tool": "Ferramenta web" + }, + "deprecations": {} +} diff --git a/MC1Services/Sources/MC1Services/MECP/Languages/ru.json b/MC1Services/Sources/MC1Services/MECP/Languages/ru.json new file mode 100644 index 0000000000..9258419590 --- /dev/null +++ b/MC1Services/Sources/MC1Services/MECP/Languages/ru.json @@ -0,0 +1,313 @@ +{ + "language": "ru", + "language_name": "Русский", + "language_name_en": "Russian", + "language_name_latin": "Russkiy", + "flag_emoji": "🇷🇺", + "text_direction": "ltr", + "severities": { + "0": { + "local": "БЕДСТВИЕ", + "label": "MAYDAY / Угроза жизни" + }, + "1": { + "local": "СРОЧНО", + "label": "URGENT / Срочно" + }, + "2": { + "local": "БЕЗОПАСНОСТЬ", + "label": "SAFETY / Важно" + }, + "3": { + "local": "ОБЫЧНОЕ", + "label": "ROUTINE / Обычное" + } + }, + "categories": { + "M": { + "name": "Медицина", + "icon": "medical" + }, + "T": { + "name": "Местность / Инфраструктура", + "icon": "terrain" + }, + "W": { + "name": "Погода / Окружающая среда", + "icon": "weather" + }, + "S": { + "name": "Снабжение", + "icon": "supplies" + }, + "P": { + "name": "Местоположение / Движение", + "icon": "position" + }, + "C": { + "name": "Координация", + "icon": "coordination" + }, + "R": { + "name": "Ответ", + "icon": "response" + }, + "D": { + "name": "Учения / Тест", + "icon": "drill" + }, + "L": { + "name": "Быт / Досуг", + "icon": "leisure" + }, + "X": { + "name": "Угроза / Безопасность", + "icon": "threat" + }, + "H": { + "name": "Есть ресурсы / Предлагаю", + "icon": "resources" + }, + "B": { + "name": "Маяк", + "icon": "beacon" + } + }, + "codes": { + "M01": "Травма", + "M02": "Человек без сознания", + "M03": "Затруднённое дыхание", + "M04": "Сердечный приступ", + "M05": "Переохлаждение", + "M06": "Сильное кровотечение", + "M07": "Перелом / обездвижен", + "M08": "Ожоги", + "M09": "Массовые жертвы", + "M10": "Погибший", + "M11": "Укус / ужаление животного", + "M12": "Аллергическая реакция / анафилаксия", + "M13": "Отравление / токсическое воздействие", + "M14": "Обнаружены живые люди", + "M15": "Зона обследована, пострадавших не найдено", + "T01": "Дорога заблокирована", + "T02": "Мост разрушен", + "T03": "Здание обрушилось", + "T04": "Наводнение", + "T05": "Оползень", + "T06": "Нет электричества", + "T07": "Пожар", + "T08": "Лавина", + "T09": "Путь непроходим", + "T10": "Укрытие доступно", + "T11": "Утопающий / нужна водная спасательная операция", + "T12": "Загрязнение воды", + "T13": "Землетрясение", + "T14": "Утечка газа", + "T15": "Химический разлив / опасные вещества", + "T16": "ДТП", + "T17": "Автомобиль горит", + "W01": "Приближается шторм", + "W02": "Нулевая видимость", + "W03": "Экстремальный холод", + "W04": "Экстремальная жара", + "W05": "Опасное качество воздуха", + "W06": "Предупреждение о цунами / штормовом нагоне", + "S01": "Нужна вода", + "S02": "Нужна еда", + "S03": "Нужны лекарства", + "S04": "Нужна батарея / питание", + "S05": "Нужно топливо", + "S06": "Нужны инструменты / оборудование", + "P01": "Застряли / не можем двигаться", + "P02": "Эвакуируемся в направлении", + "P03": "Укрываемся на месте", + "P04": "В пути к", + "P05": "На координатах GPS", + "P06": "Заблудились", + "P07": "Группа разделилась", + "C01": "Отправьте спасателей", + "C02": "Нужен транспорт", + "C03": "Передайте это сообщение", + "C04": "Подтвердите получение", + "C05": "Сколько людей", + "C06": "Какой статус", + "C07": "Можете ли связаться", + "C08": "Встреча в", + "R01": "Принято", + "R02": "Помощь идёт", + "R03": "Время прибытия [минут]", + "R04": "Не можем помочь", + "R05": "Перенаправляем к", + "R06": "Ожидайте", + "R07": "Ситуация разрешена / всё чисто", + "D01": "Это учения", + "D02": "Это тест", + "D03": "Конец учений", + "D04": "Игнорируйте предыдущее — отправлено по ошибке", + "L01": "Пиво / напитки", + "L02": "Кофе", + "L03": "Еда готова", + "L04": "Вершина достигнута", + "L05": "В лагере", + "L06": "Опаздываю", + "L07": "Здесь хороший сигнал", + "L08": "Хорошее место для фото", + "L09": "Замечено дикое животное", + "L10": "Прекрасный вид", + "L11": "Тропа в хорошем состоянии", + "L12": "Тропа в плохом состоянии", + "L13": "Нужен отдых", + "L14": "Еду домой", + "L15": "Доброе утро / отметка", + "L16": "Спокойной ночи", + "L17": "Спасибо", + "L18": "Весело проводим время", + "L19": "Здесь фестиваль / мероприятие", + "L20": "Тест узла / пинг", + "X01": "Опасный человек / угроза рядом", + "X02": "Зона опасна — избегайте", + "X03": "Слышны выстрелы / взрывы", + "X04": "Гражданские беспорядки / опасность толпы", + "X05": "Сообщено о краже / мародёрстве", + "X06": "Власти / экстренные службы на месте", + "X07": "Блокпост / перекрытие дороги (власти)", + "H01": "Есть вода", + "H02": "Есть еда", + "H03": "Есть медикаменты", + "H04": "Есть электричество / зарядка", + "H05": "Есть топливо", + "H06": "Есть инструменты / оборудование", + "H07": "Есть укрытие / место для [N] чел.", + "H08": "Есть транспорт / автомобиль", + "B01": "Автоматический аварийный маяк активен — отправитель может не отвечать", + "B02": "Маяк подтверждён — снизить частоту передачи", + "B03": "Отменить маяк — я в порядке" + }, + "ui": { + "send": "Отправить", + "cancel": "Отмена", + "attach_gps": "Добавить GPS", + "attach_timestamp": "Метка времени (UTC)", + "add_count": "Добавить количество", + "preview": "Просмотр", + "copy": "Копировать", + "paste_decode": "Вставить и декодировать", + "severity_select": "Выберите уровень серьёзности", + "category_select": "Выберите категорию", + "code_select": "Выберите коды", + "freetext_placeholder": "Необязательный текст...", + "parse_failed": "MECP сообщение — не удалось полностью разобрать", + "unknown_code": "Неизвестный код", + "message_too_long": "Сообщение превышает 200 байт", + "not_connected": "Устройство не подключено", + "connecting": "Подключение...", + "connected_to": "Подключено к", + "scan_devices": "Поиск устройств", + "compose": "Создать", + "decode": "Декодировать", + "reference_card": "Справочная карточка", + "history": "История", + "clear_history": "Очистить историю", + "export_history": "Экспортировать историю", + "drill_banner": "УЧЕНИЯ", + "untranslated_warning": "Этот текст не переведён", + "bytes_remaining": "байт осталось", + "confirm_mayday": "Подтвердить MAYDAY — удерживайте для отправки", + "message_copied": "Сообщение скопировано", + "gps_acquiring": "Получение GPS...", + "add_reference_tag": "Добавить метку инцидента", + "back": "Назад", + "next": "Далее", + "add_more_codes": "Добавить ещё коды", + "freetext_preview": "Свободный текст и просмотр", + "bytes_available": "байт доступно для дополнительных кодов + текст", + "gps_unavailable": "GPS недоступен", + "gps_not_supported": "GPS не поддерживается", + "freetext_conventions": "Правила свободного текста", + "no_messages": "Сообщений пока нет", + "severity_levels": "Уровни серьёзности", + "person_count": "Количество человек", + "settings": "Настройки", + "inbox": "Входящие", + "device": "Устройство", + "language_label": "Язык", + "compose_defaults": "Настройки по умолчанию", + "auto_gps": "Автоприкрепление GPS (ур. 0-1)", + "auto_timestamp": "Автоприкрепление времени", + "all_filter": "Все", + "sent": "Отправленные", + "reset": "Сброс", + "freetext": "Свободный текст", + "severity_header": "Серьёзность", + "category_header": "Категория", + "codes_header": "Коды", + "preview_send": "Предпросмотр и отправка", + "no_radio_queued": "Радио не подключено — сообщение будет поставлено в очередь", + "mecp_message": "MECP сообщение", + "inbox_tab": "Входящие", + "reference_tab": "Справка", + "activate_beacon": "Активировать маяк", + "beacon_active": "Аварийный маяк активен", + "beacon_cancel": "Отменить маяк", + "beacon_confirm": "Активировать аварийный маяк? Ваше местоположение будет передаваться автоматически.", + "beacon_countdown": "Следующая передача через", + "beacon_ack_received": "Маяк подтверждён от", + "beacon_drill": "УЧЕБНЫЙ МАЯК", + "ack_waiting": "Ожидание подтверждения...", + "ack_no_response": "Ответ не получен", + "ack_resend": "Отправить повторно с запросом на ретрансляцию?", + "beacon_positions": "История позиций", + "beacon_from": "Маяк от", + "beacon_last_seen": "Последний раз замечен", + "beacon_duration": "Активен", + "site_nav_what": "Что такое MECP", + "site_nav_demo": "Демо", + "site_nav_app": "Симуляция приложения", + "site_nav_github": "GitHub", + "site_nav_discussion": "Обсуждение", + "site_hero_headline": "Экстренная связь на любом языке, через любую mesh-сеть", + "site_hero_sub": "MECP — открытый протокол, кодирующий экстренные сообщения в крошечные пакеты, которые передаст любое LoRa mesh-радио — мгновенно понятные на 20 языках.", + "site_cta_demo": "Попробовать демо", + "site_cta_github": "Смотреть на GitHub", + "site_what_title": "Что такое MECP?", + "site_what_p1": "Когда случается катастрофа и сотовые вышки гаснут, волонтёры и спасатели полагаются на mesh-радио для координации. Но mesh-радио передаёт очень мало данных — часто менее 200 байт — и когда команды говорят на разных языках, критически важный смысл теряется.", + "site_what_p2": "MECP (Mesh Emergency Communication Protocol) решает это, кодируя чрезвычайные ситуации в компактные, структурированные сообщения. Каждое сообщение начинается с уровня серьёзности, за которым следуют стандартизированные коды из 12 категорий — медицинские, местность, погода, снабжение, координация и другие.", + "site_what_p3": "Поскольку каждый код имеет перевод на 20 языков, MAYDAY чешского волонтёра мгновенно читается японской спасательной командой. Без переводчика, без траты полосы пропускания.", + "site_what_example_label": "Пример сообщения", + "site_what_example_sev": "Серьёзность 0 — MAYDAY", + "site_what_example_codes": "Травма + Без сознания + Дорога заблокирована", + "site_what_example_pax": "3 человека", + "site_what_example_gps": "GPS координаты", + "site_what_example_time": "Временная метка (UTC)", + "site_what_example_lang": "Подсказка языка", + "site_what_feat_codes": "108 кодов в 12 категориях", + "site_what_feat_langs": "Поддержка 20 языков", + "site_what_feat_bytes": "Умещается в 200 байт", + "site_demo_title": "Живое демо", + "site_demo_sub": "Составьте настоящее MECP-сообщение и увидьте его мгновенно декодированным на другом языке.", + "site_demo_compose_label": "Составление", + "site_demo_decode_label": "Декодировано", + "site_demo_swap_langs": "Поменять языки", + "site_demo_raw_label": "Исходная строка MECP", + "site_sim_title": "Симуляция приложения", + "site_sim_sub": "Посмотрите, как MECP работает через mesh-сеть — составьте на одном устройстве, примите на другом на другом языке.", + "site_sim_sender": "Отправитель", + "site_sim_receiver": "Получатель", + "site_sim_send_btn": "Отправить через mesh", + "site_sim_sending": "Отправка...", + "site_sim_just_now": "только что", + "site_sim_change_lang": "Сменить язык", + "site_community_title": "Сообщество", + "site_community_github_desc": "Исходный код, документация и примеры. Поставьте звезду репозиторию для отслеживания обновлений.", + "site_community_protocol_title": "Открытый протокол", + "site_community_protocol_desc": "Спецификация протокола MECP опубликована под CC0 — общественное достояние. Используйте свободно в любом проекте.", + "site_community_contribute_title": "Присоединяйтесь", + "site_community_contribute_desc": "Добавляйте переводы, создавайте интеграции или улучшайте протокол. Прочитайте CONTRIBUTING.md для начала.", + "site_discussion_title": "Обсуждение", + "site_footer_desc": "Открытый код, открытый протокол, создан для устойчивости.", + "site_footer_links": "Ссылки", + "site_footer_licenses": "Лицензии", + "site_footer_web_tool": "Веб-инструмент" + }, + "deprecations": {} +} diff --git a/MC1Services/Sources/MC1Services/MECP/Languages/uk.json b/MC1Services/Sources/MC1Services/MECP/Languages/uk.json new file mode 100644 index 0000000000..fb0966f4eb --- /dev/null +++ b/MC1Services/Sources/MC1Services/MECP/Languages/uk.json @@ -0,0 +1,313 @@ +{ + "language": "uk", + "language_name": "Українська", + "language_name_en": "Ukrainian", + "language_name_latin": "Ukrainska", + "flag_emoji": "🇺🇦", + "text_direction": "ltr", + "severities": { + "0": { + "local": "ЛИХО", + "label": "MAYDAY / Загроза життю" + }, + "1": { + "local": "ТЕРМІНОВО", + "label": "URGENT / Терміново" + }, + "2": { + "local": "БЕЗПЕКА", + "label": "SAFETY / Важливо" + }, + "3": { + "local": "ЗВИЧАЙНЕ", + "label": "ROUTINE / Звичайне" + } + }, + "categories": { + "M": { + "name": "Медичне", + "icon": "medical" + }, + "T": { + "name": "Місцевість / Інфраструктура", + "icon": "terrain" + }, + "W": { + "name": "Погода / Довкілля", + "icon": "weather" + }, + "S": { + "name": "Постачання", + "icon": "supplies" + }, + "P": { + "name": "Місцезнаходження / Рух", + "icon": "position" + }, + "C": { + "name": "Координація", + "icon": "coordination" + }, + "R": { + "name": "Відповідь", + "icon": "response" + }, + "D": { + "name": "Навчання / Тест", + "icon": "drill" + }, + "L": { + "name": "Побут / Дозвілля", + "icon": "leisure" + }, + "X": { + "name": "Загроза / Безпека", + "icon": "threat" + }, + "H": { + "name": "Є ресурси / Пропоную", + "icon": "resources" + }, + "B": { + "name": "Маяк", + "icon": "beacon" + } + }, + "codes": { + "M01": "Травма", + "M02": "Непритомна людина", + "M03": "Утруднене дихання", + "M04": "Серцевий напад", + "M05": "Переохолодження", + "M06": "Сильна кровотеча", + "M07": "Перелом / нерухомий", + "M08": "Опіки", + "M09": "Масові жертви", + "M10": "Загиблий", + "M11": "Укус / ужалення тварини", + "M12": "Алергічна реакція / анафілаксія", + "M13": "Отруєння / токсичний вплив", + "M14": "Знайдено живих людей", + "M15": "Зону обшукано, жертв не знайдено", + "T01": "Дорогу заблоковано", + "T02": "Міст зруйновано", + "T03": "Будівля обвалилась", + "T04": "Повінь", + "T05": "Зсув ґрунту", + "T06": "Немає електрики", + "T07": "Пожежа", + "T08": "Лавина", + "T09": "Шлях непрохідний", + "T10": "Укриття доступне", + "T11": "Потопаючий / потрібна водна порятунок", + "T12": "Забруднення води", + "T13": "Землетрус", + "T14": "Витік газу", + "T15": "Хімічний розлив / небезпечні речовини", + "T16": "ДТП", + "T17": "Автомобіль горить", + "W01": "Наближається шторм", + "W02": "Нульова видимість", + "W03": "Екстремальний холод", + "W04": "Екстремальна спека", + "W05": "Небезпечна якість повітря", + "W06": "Попередження про цунамі / штормовий нагін", + "S01": "Потрібна вода", + "S02": "Потрібна їжа", + "S03": "Потрібні ліки", + "S04": "Потрібна батарея / живлення", + "S05": "Потрібне паливо", + "S06": "Потрібні інструменти / обладнання", + "P01": "Застрягли / не можемо рухатись", + "P02": "Евакуюємось у напрямку", + "P03": "Ховаємось на місці", + "P04": "У дорозі до", + "P05": "На координатах GPS", + "P06": "Загубились", + "P07": "Група розділилась", + "C01": "Надішліть рятувальників", + "C02": "Потрібен транспорт", + "C03": "Передайте це повідомлення далі", + "C04": "Підтвердіть отримання", + "C05": "Скільки людей", + "C06": "Який статус", + "C07": "Чи можете зв'язатись", + "C08": "Зустріч о", + "R01": "Прийнято", + "R02": "Допомога йде", + "R03": "Час прибуття [хвилин]", + "R04": "Не можемо допомогти", + "R05": "Переспрямовуємо до", + "R06": "Очікуйте", + "R07": "Ситуацію вирішено / все чисто", + "D01": "Це навчання", + "D02": "Це тест", + "D03": "Кінець навчання", + "D04": "Ігноруйте попереднє — надіслано помилково", + "L01": "Пиво / напої", + "L02": "Кава", + "L03": "Їжа готова", + "L04": "Вершина досягнута", + "L05": "У таборі", + "L06": "Запізнююсь", + "L07": "Тут гарний сигнал", + "L08": "Гарне місце для фото", + "L09": "Помічено дику тварину", + "L10": "Чудовий краєвид", + "L11": "Стежка в хорошому стані", + "L12": "Стежка в поганому стані", + "L13": "Потрібна перерва", + "L14": "Їду додому", + "L15": "Доброго ранку / реєстрація", + "L16": "На добраніч", + "L17": "Дякую", + "L18": "Весело проводимо час", + "L19": "Тут фестиваль / подія", + "L20": "Тест вузла / пінг", + "X01": "Небезпечна людина / загроза поблизу", + "X02": "Зона небезпечна — уникайте", + "X03": "Чутно постріли / вибухи", + "X04": "Громадські заворушення / небезпека натовпу", + "X05": "Повідомлено про крадіжку / мародерство", + "X06": "Влада / екстрені служби на місці", + "X07": "Блокпост / перекриття дороги (влада)", + "H01": "Є вода", + "H02": "Є їжа", + "H03": "Є медичні засоби", + "H04": "Є електрика / зарядка", + "H05": "Є паливо", + "H06": "Є інструменти / обладнання", + "H07": "Є укриття / місце для [N] осіб", + "H08": "Є транспорт / автомобіль", + "B01": "Автоматичний аварійний маяк активний — відправник може не відповідати", + "B02": "Маяк підтверджено — зменшити частоту передачі", + "B03": "Скасувати маяк — я в порядку" + }, + "ui": { + "send": "Надіслати", + "cancel": "Скасувати", + "attach_gps": "Додати GPS", + "attach_timestamp": "Мітка часу (UTC)", + "add_count": "Додати кількість", + "preview": "Перегляд", + "copy": "Копіювати", + "paste_decode": "Вставити та декодувати", + "severity_select": "Оберіть рівень серйозності", + "category_select": "Оберіть категорію", + "code_select": "Оберіть коди", + "freetext_placeholder": "Необов'язковий текст...", + "parse_failed": "MECP повідомлення — не вдалося повністю розібрати", + "unknown_code": "Невідомий код", + "message_too_long": "Повідомлення перевищує 200 байт", + "not_connected": "Пристрій не підключено", + "connecting": "Підключення...", + "connected_to": "Підключено до", + "scan_devices": "Пошук пристроїв", + "compose": "Створити", + "decode": "Декодувати", + "reference_card": "Довідкова картка", + "history": "Історія", + "clear_history": "Очистити історію", + "export_history": "Експортувати історію", + "drill_banner": "НАВЧАННЯ", + "untranslated_warning": "Цей текст не перекладено", + "bytes_remaining": "байт залишилось", + "confirm_mayday": "Підтвердити MAYDAY — утримуйте для відправки", + "message_copied": "Повідомлення скопійовано", + "gps_acquiring": "Отримання GPS...", + "add_reference_tag": "Додати мітку інциденту", + "back": "Назад", + "next": "Далі", + "add_more_codes": "Додати більше кодів", + "freetext_preview": "Вільний текст та перегляд", + "bytes_available": "байт доступно для додаткових кодів + текст", + "gps_unavailable": "GPS недоступний", + "gps_not_supported": "GPS не підтримується", + "freetext_conventions": "Правила вільного тексту", + "no_messages": "Повідомлень ще немає", + "severity_levels": "Рівні серйозності", + "person_count": "Кількість осіб", + "settings": "Налаштування", + "inbox": "Вхідні", + "device": "Пристрій", + "language_label": "Мова", + "compose_defaults": "Стандартні налаштування", + "auto_gps": "Автоприкріплення GPS (рів. 0-1)", + "auto_timestamp": "Автоприкріплення часу", + "all_filter": "Усі", + "sent": "Надіслані", + "reset": "Скинути", + "freetext": "Вільний текст", + "severity_header": "Серйозність", + "category_header": "Категорія", + "codes_header": "Коди", + "preview_send": "Перегляд і надіслати", + "no_radio_queued": "Радіо не підключено — повідомлення буде в черзі", + "mecp_message": "MECP повідомлення", + "inbox_tab": "Вхідні", + "reference_tab": "Довідка", + "activate_beacon": "Активувати маяк", + "beacon_active": "Аварійний маяк активний", + "beacon_cancel": "Скасувати маяк", + "beacon_confirm": "Активувати аварійний маяк? Ваше місцезнаходження буде передаватися автоматично.", + "beacon_countdown": "Наступна передача через", + "beacon_ack_received": "Маяк підтверджено від", + "beacon_drill": "НАВЧАЛЬНИЙ МАЯК", + "ack_waiting": "Очікування підтвердження...", + "ack_no_response": "Відповіді не отримано", + "ack_resend": "Надіслати повторно з запитом на ретрансляцію?", + "beacon_positions": "Історія позицій", + "beacon_from": "Маяк від", + "beacon_last_seen": "Останній раз бачено", + "beacon_duration": "Активний", + "site_nav_what": "Що таке MECP", + "site_nav_demo": "Демо", + "site_nav_app": "Симуляція додатку", + "site_nav_github": "GitHub", + "site_nav_discussion": "Обговорення", + "site_hero_headline": "Екстрена комунікація будь-якою мовою, через будь-яку mesh мережу", + "site_hero_sub": "MECP — відкритий протокол, що кодує екстрені повідомлення у крихітні пакети, які може передати будь-яке LoRa mesh радіо — миттєво зрозумілі 20 мовами.", + "site_cta_demo": "Спробувати демо", + "site_cta_github": "Переглянути на GitHub", + "site_what_title": "Що таке MECP?", + "site_what_p1": "Коли лихо вражає і стільникові вежі вимикаються, волонтери та рятувальники покладаються на mesh радіо для координації. Але mesh радіо передає дуже мало даних — часто менше 200 байтів — і коли команди розмовляють різними мовами, критичний зміст втрачається.", + "site_what_p2": "MECP (Mesh Emergency Communication Protocol) вирішує це, кодуючи надзвичайні ситуації у компактні, структуровані повідомлення. Кожне повідомлення починається з рівня серйозності, за яким йдуть стандартизовані коди з 12 категорій — медичні, терен, погода, запаси, координація тощо.", + "site_what_p3": "Оскільки кожен код має переклад 20 мовами, MAYDAY чеського волонтера миттєво зрозумілий для японської рятувальної команди. Без перекладача, без марної витрати смуги пропускання.", + "site_what_example_label": "Приклад повідомлення", + "site_what_example_sev": "Серйозність 0 — MAYDAY", + "site_what_example_codes": "Травма + Непритомний + Дорога заблокована", + "site_what_example_pax": "3 особи", + "site_what_example_gps": "GPS координати", + "site_what_example_time": "Мітка часу (UTC)", + "site_what_example_lang": "Підказка мови", + "site_what_feat_codes": "108 кодів у 12 категоріях", + "site_what_feat_langs": "Підтримка 20 мов", + "site_what_feat_bytes": "Вміщується в 200 байтів", + "site_demo_title": "Демо наживо", + "site_demo_sub": "Складіть справжнє MECP повідомлення та побачте його декодованим іншою мовою миттєво.", + "site_demo_compose_label": "Створення", + "site_demo_decode_label": "Декодовано", + "site_demo_swap_langs": "Поміняти мови", + "site_demo_raw_label": "Необроблений рядок MECP", + "site_sim_title": "Симуляція додатку", + "site_sim_sub": "Подивіться, як MECP працює через mesh мережу — створіть на одному пристрої, отримайте на іншому іншою мовою.", + "site_sim_sender": "Відправник", + "site_sim_receiver": "Отримувач", + "site_sim_send_btn": "Надіслати через mesh", + "site_sim_sending": "Надсилання...", + "site_sim_just_now": "щойно", + "site_sim_change_lang": "Змінити мову", + "site_community_title": "Спільнота", + "site_community_github_desc": "Вихідний код, документація та приклади. Поставте зірку репозиторію для відстеження оновлень.", + "site_community_protocol_title": "Відкритий протокол", + "site_community_protocol_desc": "Специфікація протоколу MECP опублікована під CC0 — суспільне надбання. Використовуйте вільно в будь-якому проєкті.", + "site_community_contribute_title": "Долучайтеся", + "site_community_contribute_desc": "Додавайте переклади, створюйте інтеграції або покращуйте протокол. Прочитайте CONTRIBUTING.md для початку.", + "site_discussion_title": "Обговорення", + "site_footer_desc": "Відкритий код, відкритий протокол, створений для стійкості.", + "site_footer_links": "Посилання", + "site_footer_licenses": "Ліцензії", + "site_footer_web_tool": "Веб-інструмент" + }, + "deprecations": {} +} diff --git a/MC1Services/Sources/MC1Services/MECP/Languages/zh-cn.json b/MC1Services/Sources/MC1Services/MECP/Languages/zh-cn.json new file mode 100644 index 0000000000..173e7358ab --- /dev/null +++ b/MC1Services/Sources/MC1Services/MECP/Languages/zh-cn.json @@ -0,0 +1,313 @@ +{ + "language": "zh-cn", + "language_name": "简体中文", + "language_name_en": "Simplified Chinese", + "language_name_latin": "Jiantizi Zhongwen", + "flag_emoji": "🇨🇳", + "text_direction": "ltr", + "severities": { + "0": { + "local": "求救", + "label": "MAYDAY / 危及生命" + }, + "1": { + "local": "紧急", + "label": "URGENT / 时间紧迫" + }, + "2": { + "local": "安全", + "label": "SAFETY / 重要" + }, + "3": { + "local": "常规", + "label": "ROUTINE / 正常" + } + }, + "categories": { + "M": { + "name": "医疗", + "icon": "medical" + }, + "T": { + "name": "地形 / 基础设施", + "icon": "terrain" + }, + "W": { + "name": "天气 / 环境", + "icon": "weather" + }, + "S": { + "name": "物资", + "icon": "supplies" + }, + "P": { + "name": "位置 / 移动", + "icon": "position" + }, + "C": { + "name": "协调", + "icon": "coordination" + }, + "R": { + "name": "响应", + "icon": "response" + }, + "D": { + "name": "演习 / 测试", + "icon": "drill" + }, + "L": { + "name": "生活 / 休闲", + "icon": "leisure" + }, + "X": { + "name": "威胁 / 治安", + "icon": "threat" + }, + "H": { + "name": "可提供资源", + "icon": "resources" + }, + "B": { + "name": "信标", + "icon": "beacon" + } + }, + "codes": { + "M01": "受伤", + "M02": "失去意识者", + "M03": "呼吸困难", + "M04": "心脏事件", + "M05": "失温", + "M06": "严重出血", + "M07": "骨折 / 无法移动", + "M08": "烧伤", + "M09": "大量伤亡", + "M10": "死亡", + "M11": "动物咬伤 / 蛰伤", + "M12": "过敏反应 / 过敏性休克", + "M13": "中毒 / 毒性暴露", + "M14": "发现幸存者", + "M15": "搜索完毕,未发现伤亡者", + "T01": "道路封锁", + "T02": "桥梁损毁", + "T03": "建筑倒塌", + "T04": "洪水", + "T05": "山体滑坡", + "T06": "停电", + "T07": "火灾", + "T08": "雪崩", + "T09": "道路不可通行", + "T10": "有避难所", + "T11": "溺水 / 需水域救援", + "T12": "水源污染", + "T13": "地震", + "T14": "燃气泄漏", + "T15": "化学品泄漏 / 危险物质", + "T16": "车祸", + "T17": "车辆起火", + "W01": "暴风雨逼近", + "W02": "能见度为零", + "W03": "极度严寒", + "W04": "极度酷热", + "W05": "空气质量危险", + "W06": "海啸 / 风暴潮警报", + "S01": "需要饮水", + "S02": "需要食物", + "S03": "需要药物", + "S04": "需要电池 / 电源", + "S05": "需要燃料", + "S06": "需要工具 / 装备", + "P01": "被困 / 动弹不得", + "P02": "撤离中,方向:", + "P03": "就地避难中", + "P04": "前往途中", + "P05": "位于GPS坐标", + "P06": "迷路", + "P07": "队伍失散", + "C01": "请派救援", + "C02": "需要运输工具", + "C03": "请转发此消息", + "C04": "确认收到", + "C05": "有多少人", + "C06": "目前状况如何", + "C07": "能否联系到", + "C08": "会合地点:", + "R01": "收到", + "R02": "救援已出发", + "R03": "预计到达 [分钟]", + "R04": "无法协助", + "R05": "转介至:", + "R06": "待命", + "R07": "状况解除 / 安全确认", + "D01": "这是演习", + "D02": "这是测试", + "D03": "演习结束", + "D04": "请忽略前一条消息 — 误发", + "L01": "啤酒 / 饮料", + "L02": "咖啡", + "L03": "餐点备好", + "L04": "到达山顶", + "L05": "在营地", + "L06": "会迟到", + "L07": "这里信号好", + "L08": "拍照好地方", + "L09": "发现野生动物", + "L10": "美景", + "L11": "步道状况良好", + "L12": "步道状况不佳", + "L13": "需要休息", + "L14": "准备回家", + "L15": "早安 / 签到", + "L16": "晚安", + "L17": "谢谢", + "L18": "玩得开心", + "L19": "这里有节庆 / 活动", + "L20": "节点测试 / ping", + "X01": "附近有危险人物 / 威胁", + "X02": "区域不安全 — 回避", + "X03": "听到枪声 / 爆炸声", + "X04": "社会动乱 / 人群危险", + "X05": "通报盗窃 / 抢劫", + "X06": "当局 / 紧急服务在场", + "X07": "检查站 / 道路封锁(当局)", + "H01": "有饮水可提供", + "H02": "有食物可提供", + "H03": "有医疗物资", + "H04": "有电源 / 充电设备", + "H05": "有燃料", + "H06": "有工具 / 装备", + "H07": "有避难所 / 可容纳[N]人", + "H08": "有运输工具 / 车辆", + "B01": "自动遇险信标启动中 — 发送者可能无法回应", + "B02": "信标已确认 — 降低发送频率", + "B03": "取消信标 — 我没事" + }, + "ui": { + "send": "发送", + "cancel": "取消", + "attach_gps": "附加GPS", + "attach_timestamp": "时间戳 (UTC)", + "add_count": "添加人数", + "preview": "预览", + "copy": "复制", + "paste_decode": "粘贴并解码", + "severity_select": "选择严重程度", + "category_select": "选择类别", + "code_select": "选择代码", + "freetext_placeholder": "选填文字...", + "parse_failed": "MECP消息 — 无法完全解析", + "unknown_code": "未知代码", + "message_too_long": "消息超过200字节", + "not_connected": "未连接设备", + "connecting": "连接中...", + "connected_to": "已连接至", + "scan_devices": "扫描设备", + "compose": "撰写", + "decode": "解码", + "reference_card": "参考卡", + "history": "历史记录", + "clear_history": "清除记录", + "export_history": "导出记录", + "drill_banner": "演习", + "untranslated_warning": "此文字未翻译", + "bytes_remaining": "字节剩余", + "confirm_mayday": "确认求救 — 长按发送", + "message_copied": "消息已复制", + "gps_acquiring": "正在获取GPS...", + "add_reference_tag": "添加事件标签", + "back": "返回", + "next": "下一步", + "add_more_codes": "添加更多代码", + "freetext_preview": "自由文字与预览", + "bytes_available": "字节可用于更多代码+文字", + "gps_unavailable": "GPS不可用", + "gps_not_supported": "GPS不支持", + "freetext_conventions": "自由文字规范", + "no_messages": "暂无消息", + "severity_levels": "严重程度等级", + "person_count": "人数", + "settings": "设置", + "inbox": "收件箱", + "device": "设备", + "language_label": "语言", + "compose_defaults": "编写默认值", + "auto_gps": "自动附加 GPS(严重度 0-1)", + "auto_timestamp": "自动附加时间戳", + "all_filter": "全部", + "sent": "已发送", + "reset": "重置", + "freetext": "自由文本", + "severity_header": "严重度", + "category_header": "类别", + "codes_header": "代码", + "preview_send": "预览与发送", + "no_radio_queued": "未连接无线电 — 消息将排入队列", + "mecp_message": "MECP 消息", + "inbox_tab": "收件", + "reference_tab": "参考", + "activate_beacon": "启动信标", + "beacon_active": "遇险信标启动中", + "beacon_cancel": "取消信标", + "beacon_confirm": "启动遇险信标?您的位置将自动广播。", + "beacon_countdown": "下次发送倒计时", + "beacon_ack_received": "信标已被确认,来自", + "beacon_drill": "演习信标", + "ack_waiting": "等待确认回复...", + "ack_no_response": "未收到回复", + "ack_resend": "附带转发请求重新发送?", + "beacon_positions": "位置历史", + "beacon_from": "信标来自", + "beacon_last_seen": "最后出现", + "beacon_duration": "已启动", + "site_nav_what": "什么是 MECP", + "site_nav_demo": "演示", + "site_nav_app": "应用模拟", + "site_nav_github": "GitHub", + "site_nav_discussion": "讨论", + "site_hero_headline": "跨越语言障碍,通过任何 mesh 网络进行紧急通信", + "site_hero_sub": "MECP 是一个开放协议,将紧急消息编码成任何 LoRa mesh 无线电都能传输的小数据包 — 可即时以 20 种语言理解。", + "site_cta_demo": "试用演示", + "site_cta_github": "在 GitHub 查看", + "site_what_title": "什么是 MECP?", + "site_what_p1": "当灾难来袭、基站断电时,志愿者和急救人员依赖 mesh 无线电进行协调。但 mesh 无线电能传输的数据非常少 — 通常不到 200 字节 — 当团队说不同语言时,关键信息就会丢失。", + "site_what_p2": "MECP(Mesh Emergency Communication Protocol)通过将紧急情况编码为紧凑、结构化的消息来解决这个问题。每条消息以严重程度开头,后接 12 个类别的标准化代码 — 医疗、地形、天气、物资、协调等。", + "site_what_p3": "因为每个代码都有 20 种语言的翻译,捷克志愿者的 MAYDAY 可以被日本搜救队立即读懂。不需要翻译,不浪费带宽。", + "site_what_example_label": "消息示例", + "site_what_example_sev": "严重程度 0 — MAYDAY", + "site_what_example_codes": "受伤 + 失去意识 + 道路封锁", + "site_what_example_pax": "3 人", + "site_what_example_gps": "GPS 坐标", + "site_what_example_time": "时间戳(UTC)", + "site_what_example_lang": "语言提示", + "site_what_feat_codes": "12 个类别共 108 个代码", + "site_what_feat_langs": "支持 20 种语言", + "site_what_feat_bytes": "仅占 200 字节", + "site_demo_title": "实时演示", + "site_demo_sub": "编写真正的 MECP 消息,实时看到它以另一种语言解码。", + "site_demo_compose_label": "编写", + "site_demo_decode_label": "已解码", + "site_demo_swap_langs": "交换语言", + "site_demo_raw_label": "原始 MECP 字符串", + "site_sim_title": "应用模拟", + "site_sim_sub": "了解 MECP 如何在 mesh 网络上工作 — 在一台设备上编写,在另一台以不同语言接收。", + "site_sim_sender": "发送者", + "site_sim_receiver": "接收者", + "site_sim_send_btn": "通过 mesh 发送", + "site_sim_sending": "发送中...", + "site_sim_just_now": "刚刚", + "site_sim_change_lang": "更改语言", + "site_community_title": "社区", + "site_community_github_desc": "源代码、文档和示例。为仓库加星以跟踪更新。", + "site_community_protocol_title": "开放协议", + "site_community_protocol_desc": "MECP 协议规范以 CC0 发布 — 公共领域。可自由用于任何项目。", + "site_community_contribute_title": "参与贡献", + "site_community_contribute_desc": "添加翻译、构建集成或改进协议。阅读 CONTRIBUTING.md 开始。", + "site_discussion_title": "讨论", + "site_footer_desc": "开源、开放协议,为韧性而建。", + "site_footer_links": "链接", + "site_footer_licenses": "许可证", + "site_footer_web_tool": "网页工具" + }, + "deprecations": {} +} diff --git a/MC1Services/Sources/MC1Services/MECP/MECPCatalog+Quantity.swift b/MC1Services/Sources/MC1Services/MECP/MECPCatalog+Quantity.swift new file mode 100644 index 0000000000..a67fd7d4c3 --- /dev/null +++ b/MC1Services/Sources/MC1Services/MECP/MECPCatalog+Quantity.swift @@ -0,0 +1,106 @@ +import Foundation + +extension MECPCatalog { + static let quantityKey = "chats.message.mecpPersonCount" + static let quantityTable = "Chats" + + /// The quantity line follows the pack locale, so a Korean app still uses the English forms. + static func quantityLine(count: Int, preferredLocalization: String, bundle: Bundle) -> String { + let localization = lprojName(for: preferredLocalization) + let category = pluralCategory(count: count, localization: localization) + if let line = formattedQuantity(count: count, category: category, localization: localization, bundle: bundle) { + return line + } + if localization != englishStem, + let english = formattedQuantity(count: count, category: pluralCategory(count: count, localization: englishStem), localization: englishStem, bundle: bundle) { + return english + } + return String(count) + } + + private static let pluralSpec = "NSStringPluralRuleType" + private static let pluralValueType = "lld" + private static let otherCategory = "other" + private static let oneCategory = "one" + private static let fewCategory = "few" + private static let manyCategory = "many" + + private static func formattedQuantity(count: Int, category: String, localization: String, bundle: Bundle) -> String? { + let template = stringsdictVariant(category: category, localization: localization, bundle: bundle) + ?? stringsdictVariant(category: otherCategory, localization: localization, bundle: bundle) + ?? stringsValue(localization: localization, bundle: bundle) + guard let template else { return nil } + return String(format: template, locale: Locale(identifier: localization), Int64(count)) + } + + private static func stringsdictVariant(category: String, localization: String, bundle: Bundle) -> String? { + guard let url = localizationFile(name: quantityTable, extension: "stringsdict", localization: localization, bundle: bundle), + let data = try? Data(contentsOf: url), + let root = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any], + let entry = root[quantityKey] as? [String: Any] else { + return nil + } + for value in entry.values { + guard let variants = value as? [String: Any], + variants["NSStringFormatSpecTypeKey"] as? String == pluralSpec, + variants["NSStringFormatValueTypeKey"] as? String == pluralValueType, + let line = variants[category] as? String else { + continue + } + return line + } + return nil + } + + private static func stringsValue(localization: String, bundle: Bundle) -> String? { + guard let url = localizationFile(name: quantityTable, extension: "strings", localization: localization, bundle: bundle), + let data = try? Data(contentsOf: url), + let table = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: String] else { + return nil + } + return table[quantityKey] + } + + private static func localizationFile(name: String, extension ext: String, localization: String, bundle: Bundle) -> URL? { + if let url = bundle.url(forResource: name, withExtension: ext, subdirectory: nil, localization: localization) { + return url + } + guard let lproj = bundle.url(forResource: localization, withExtension: "lproj"), + let nested = Bundle(url: lproj) else { + return nil + } + return nested.url(forResource: name, withExtension: ext) + } + + private static func pluralCategory(count: Int, localization: String) -> String { + let language = localization.split(separator: "-").first.map(String.init) ?? localization + switch language { + case "pl": + return polishCategory(count) + case "ru", "uk": + return eastSlavicCategory(count) + case "fr": + return count == 0 || count == 1 ? oneCategory : otherCategory + case "zh", "ko": + return otherCategory + default: + return count == 1 ? oneCategory : otherCategory + } + } + + private static func polishCategory(_ count: Int) -> String { + if count == 1 { return oneCategory } + let mod10 = count % 10 + let mod100 = count % 100 + if (2...4).contains(mod10), !(12...14).contains(mod100) { return fewCategory } + return manyCategory + } + + private static func eastSlavicCategory(_ count: Int) -> String { + let mod10 = abs(count) % 10 + let mod100 = abs(count) % 100 + if mod10 == 1, mod100 != 11 { return oneCategory } + if (2...4).contains(mod10), !(12...14).contains(mod100) { return fewCategory } + return manyCategory + } +} diff --git a/MC1Services/Sources/MC1Services/MECP/MECPCatalog.swift b/MC1Services/Sources/MC1Services/MECP/MECPCatalog.swift new file mode 100644 index 0000000000..6ae086720e --- /dev/null +++ b/MC1Services/Sources/MC1Services/MECP/MECPCatalog.swift @@ -0,0 +1,204 @@ +import Foundation + +/// Phrase reading for a decoded MECP string. The JSON packs are the phrase source. +public enum MECPCatalog { + /// Nil when `text` does not decode. Otherwise each part is one line. + public static func reading( + _ text: String, + bundle: Bundle = .main, + preferredLocalizations: [String]? = nil + ) -> String? { + renderedLines( + text, + bundle: bundle, + preferredLocalizations: preferredLocalizations, + resourceBundle: .module + )?.joined(separator: "\n") + } + + public static func displayText( + _ text: String, + bundle: Bundle = .main, + preferredLocalizations: [String]? = nil + ) -> String { + displayText(text, bundle: bundle, preferredLocalizations: preferredLocalizations, resourceBundle: .module) + } + + static func displayText( + _ text: String, + bundle: Bundle, + preferredLocalizations: [String]?, + resourceBundle: Bundle + ) -> String { + renderedLines( + text, + bundle: bundle, + preferredLocalizations: preferredLocalizations, + resourceBundle: resourceBundle + )?.joined(separator: " ") ?? text + } + + static func firstPreferredLocalization(_ preferredLocalizations: [String]) -> String { + preferredLocalizations.first ?? fallbackLocalization + } + + static func renderedLines( + _ text: String, + bundle: Bundle, + preferredLocalizations: [String]?, + resourceBundle: Bundle + ) -> [String]? { + guard let message = MECPDecode.decode(text) else { return nil } + let preferred = firstPreferredLocalization(preferredLocalizations ?? bundle.preferredLocalizations) + let packs = languagePacks(in: resourceBundle) + let stem = packStem(for: preferred) + guard let english = packs[englishStem] else { return nil } + let pack = packs[stem] ?? english + return lines(for: message, pack: pack, english: english, preferredLocalization: preferred, bundle: bundle) + } + + struct LanguagePack: Equatable, Sendable { + var severityLocal: [String: String] + var codes: [String: String] + var unknownCode: String? + + init(severityLocal: [String: String], codes: [String: String], unknownCode: String?) { + self.severityLocal = severityLocal + self.codes = codes + self.unknownCode = unknownCode + } + + init?(data: Data) { + guard let file = try? JSONDecoder().decode(File.self, from: data) else { return nil } + severityLocal = file.severities.mapValues(\.local) + codes = file.codes + unknownCode = file.ui[unknownCodeKey] + } + + private struct File: Decodable { + var severities: [String: Label] + var codes: [String: String] + var ui: [String: String] + + struct Label: Decodable { + var local: String + } + } + } + + static func languagePack(stem: String, resourceBundle: Bundle = .module) -> LanguagePack? { + languagePacks(in: resourceBundle)[stem] + } + + static func phrase( + for code: String, + message: MECPMessage, + pack: LanguagePack, + english: LanguagePack + ) -> String { + if let template = pack.codes[code] ?? english.codes[code] { + return fillingSlots(in: template, code: code, message: message) + } + let unknown = pack.unknownCode ?? absentUnknownCode + return "\(code): \(unknown)" + } + + static let packStems = ["en", "de", "es", "fr", "it", "nl", "pl", "pt", "ru", "uk", "zh-cn"] + static let englishStem = "en" + static let simplifiedChineseStem = "zh-cn" + static let simplifiedChineseLocalization = "zh-Hans" + static let absentUnknownCode = "Unknown code" + + private static let fallbackLocalization = "en" + private static let etaCode = "R03" + private static let shelterCode = "H07" + private static let unknownCodeKey = "unknown_code" + private static let knownLocalizationStems: Set = ["de", "en", "es", "fr", "it", "nl", "pl", "pt", "ru", "uk"] + private static let cachedPacks: [String: LanguagePack] = loadPacks(in: .module) + + private static func languagePacks(in bundle: Bundle) -> [String: LanguagePack] { + if bundle.bundleURL == Bundle.module.bundleURL { + return cachedPacks + } + return loadPacks(in: bundle) + } + + private static func loadPacks(in bundle: Bundle) -> [String: LanguagePack] { + var packs: [String: LanguagePack] = [:] + for stem in packStems { + guard let url = bundle.url(forResource: stem, withExtension: "json"), + let data = try? Data(contentsOf: url), + let pack = LanguagePack(data: data) else { + continue + } + packs[stem] = pack + } + return packs + } + + private static func packStem(for preferredLocalization: String) -> String { + let normalized = preferredLocalization.replacingOccurrences(of: "_", with: "-") + if normalized == simplifiedChineseLocalization || normalized.hasPrefix("\(simplifiedChineseLocalization)-") { + return simplifiedChineseStem + } + let stem = normalized.split(separator: "-").first.map(String.init) ?? normalized + return knownLocalizationStems.contains(stem) ? stem : englishStem + } + + static func lprojName(for preferredLocalization: String) -> String { + packStem(for: preferredLocalization) == simplifiedChineseStem ? simplifiedChineseLocalization : packStem(for: preferredLocalization) + } + + private static func lines( + for message: MECPMessage, + pack: LanguagePack, + english: LanguagePack, + preferredLocalization: String, + bundle: Bundle + ) -> [String]? { + var parts: [String] = [] + let severityKey = String(message.severity.rawValue) + if let label = pack.severityLocal[severityKey] ?? english.severityLocal[severityKey], !label.isEmpty { + parts.append(label) + } + for code in message.codes { + parts.append(phrase(for: code, message: message, pack: pack, english: english)) + } + if let count = message.personCount { + parts.append(quantityLine(count: count, preferredLocalization: preferredLocalization, bundle: bundle)) + } + if let hhmm = message.timestampHHMM { + parts.append(clockLine(hhmm)) + } + if let tail = message.displayTail { + parts.append(tail) + } + return parts.isEmpty ? nil : parts + } + + private static func fillingSlots(in template: String, code: String, message: MECPMessage) -> String { + if code == etaCode, let eta = message.eta, let replaced = replacingBracket(in: template, with: { "\(eta) \($0)" }) { + return replaced + } + if code == shelterCode, let count = message.personCount, let replaced = replacingBracket(in: template, with: { _ in String(count) }) { + return replaced + } + return template + } + + private static func replacingBracket(in template: String, with replacement: (String) -> String) -> String? { + guard let open = template.firstIndex(of: "["), + let close = template[template.index(after: open)...].firstIndex(of: "]") else { + return nil + } + let inner = String(template[template.index(after: open).. String { + "\(hhmm.prefix(2)):\(hhmm.suffix(2)) UTC" + } +} diff --git a/MC1Services/Sources/MC1Services/MECP/MECPDecode.swift b/MC1Services/Sources/MC1Services/MECP/MECPDecode.swift new file mode 100644 index 0000000000..b7dca377e7 --- /dev/null +++ b/MC1Services/Sources/MC1Services/MECP/MECPDecode.swift @@ -0,0 +1,158 @@ +/// The MECP wire grammar. A string that does not match returns nil. +public enum MECPDecode { + public static func decode(_ input: String) -> MECPMessage? { + guard input.hasPrefix(prefix) else { return nil } + let severityIndex = input.index(input.startIndex, offsetBy: prefix.count, limitedBy: input.endIndex) + guard let severityIndex, severityIndex < input.endIndex else { return nil } + guard isASCIIDigit(input[severityIndex]), + let severityDigit = input[severityIndex].wholeNumberValue, + let severity = MECPMessage.Severity(rawValue: severityDigit) else { + return nil + } + + let bodyOffset = prefix.count + bodyLead + let body = if let bodyIndex = input.index(input.startIndex, offsetBy: bodyOffset, limitedBy: input.endIndex), bodyIndex < input.endIndex { + String(input[bodyIndex...]) + } else { + "" + } + + var codes: [String] = [] + var tailTokens: [String] = [] + var readingTail = false + for token in body.split(separator: " ", omittingEmptySubsequences: true) { + let text = String(token) + if !readingTail, isCodeToken(text) { + codes.append(text) + } else { + readingTail = true + tailTokens.append(text) + } + } + + let freetext = tailTokens.isEmpty ? nil : tailTokens.joined(separator: " ") + return MECPMessage(severity: severity, codes: codes, freetext: freetext) + } + + struct Extraction: Equatable { + var personCount: Int? + var timestampHHMM: String? + var eta: Int? + var displayTail: String? + } + + static func extracted(from freetext: String?, codes: [String]) -> Extraction { + guard let freetext else { return Extraction() } + var removal: [Range] = [] + var extraction = Extraction() + + if let match = firstPax(in: freetext) { + extraction.personCount = match.count + removal.append(match.range) + } + + if let match = firstTimestamp(in: freetext), isAcceptedClock(match.digits) { + extraction.timestampHHMM = match.digits + removal.append(match.range) + } + + if codes.contains(etaCode), let match = leadingEta(in: freetext) { + extraction.eta = match.minutes + removal.append(match.range) + } + + extraction.displayTail = removing(removal, from: freetext) + return extraction + } + + private static let prefix = "MECP/" + private static let bodyLead = 2 + private static let etaCode = "R03" + private static let maxHour = 23 + private static let maxMinute = 59 + private static let codeLength = 3 + private static let clockDigits = 4 + private static let paxSuffix = "pax" + + private static func isASCIIDigit(_ character: Character) -> Bool { + character.isASCII && character.isNumber + } + + private static func isCodeToken(_ token: String) -> Bool { + guard token.count == codeLength else { return false } + var characters = token.makeIterator() + guard let letter = characters.next(), letter.isASCII, letter.isUppercase, letter.isLetter, + let tens = characters.next(), isASCIIDigit(tens), + let ones = characters.next(), isASCIIDigit(ones) else { + return false + } + return true + } + + private static func firstPax(in text: String) -> (count: Int, range: Range)? { + var index = text.startIndex + while index < text.endIndex { + guard isASCIIDigit(text[index]) else { + index = text.index(after: index) + continue + } + let start = index + while index < text.endIndex, isASCIIDigit(text[index]) { + index = text.index(after: index) + } + guard text[index...].hasPrefix(paxSuffix) else { continue } + guard let count = Int(text[start.. (digits: String, range: Range)? { + var search = text.startIndex + while search < text.endIndex, let at = text[search...].firstIndex(of: "@") { + var cursor = text.index(after: at) + var count = 0 + while cursor < text.endIndex, count < clockDigits, isASCIIDigit(text[cursor]) { + cursor = text.index(after: cursor) + count += 1 + } + let atBoundary = cursor == text.endIndex || text[cursor] == " " + if count == clockDigits, atBoundary { + let digitsStart = text.index(after: at) + return (String(text[digitsStart.. (minutes: Int, range: Range)? { + var index = text.startIndex + guard index < text.endIndex, isASCIIDigit(text[index]) else { return nil } + let start = index + while index < text.endIndex, isASCIIDigit(text[index]) { + index = text.index(after: index) + } + guard index == text.endIndex || text[index] == " ", let minutes = Int(text[start.. Bool { + guard digits.count == 4, + let hour = Int(digits.prefix(2)), + let minute = Int(digits.suffix(2)) else { + return false + } + return hour <= maxHour && minute <= maxMinute + } + + private static func removing(_ ranges: [Range], from text: String) -> String? { + var result = text + for range in ranges.sorted(by: { $0.lowerBound > $1.lowerBound }) { + result.removeSubrange(range) + } + let collapsed = result.split(separator: " ", omittingEmptySubsequences: true).joined(separator: " ") + return collapsed.isEmpty ? nil : collapsed + } +} diff --git a/MC1Services/Sources/MC1Services/MECP/MECPMessage.swift b/MC1Services/Sources/MC1Services/MECP/MECPMessage.swift new file mode 100644 index 0000000000..fcf8f2a01f --- /dev/null +++ b/MC1Services/Sources/MC1Services/MECP/MECPMessage.swift @@ -0,0 +1,40 @@ +import Foundation + +/// Sender-shaped MECP value. Person count, an accepted clock, and an R03 eta are derived from the tail. +public struct MECPMessage: Sendable, Equatable { + public enum Severity: Int, Sendable, Equatable { + case mayday = 0 + case urgent = 1 + case safety = 2 + case routine = 3 + } + + /// UTF-8 budget a later sender matches. Decode does not reject a longer string. + public static let maxUTF8Bytes = 200 + + public let severity: Severity + public let codes: [String] + public let freetext: String? + + public init(severity: Severity, codes: [String], freetext: String?) { + self.severity = severity + self.codes = codes + self.freetext = freetext + } + + public var personCount: Int? { + MECPDecode.extracted(from: freetext, codes: codes).personCount + } + + public var timestampHHMM: String? { + MECPDecode.extracted(from: freetext, codes: codes).timestampHHMM + } + + public var eta: Int? { + MECPDecode.extracted(from: freetext, codes: codes).eta + } + + public var displayTail: String? { + MECPDecode.extracted(from: freetext, codes: codes).displayTail + } +} diff --git a/MC1Services/Sources/MC1Services/Models/Channel.swift b/MC1Services/Sources/MC1Services/Models/Channel.swift index cddc739a0f..fc8c691268 100644 --- a/MC1Services/Sources/MC1Services/Models/Channel.swift +++ b/MC1Services/Sources/MC1Services/Models/Channel.swift @@ -18,6 +18,13 @@ public final class Channel { @Attribute(originalName: "deviceID") public var radioID: UUID + var textRulesID: UUID? + var textRulesOverrideRawValue: String = TextRulesPreference.Override.inherit.rawValue + + var textRulesOverride: TextRulesPreference.Override { + TextRulesPreference.Override(rawValue: textRulesOverrideRawValue) ?? .inherit + } + /// Channel slot index public var index: UInt8 @@ -93,6 +100,7 @@ public final class Channel { ) { self.id = id self.radioID = radioID + textRulesID = UUID() self.index = index self.name = name self.secret = secret @@ -235,19 +243,21 @@ public extension Channel { /// A sendable snapshot of Channel for cross-actor transfers public struct ChannelDTO: Sendable, Equatable, Identifiable, Hashable, Codable { - public let id: UUID + public private(set) var id: UUID public var radioID: UUID - public let index: UInt8 + public internal(set) var textRulesID: UUID? + public internal(set) var textRulesOverride: TextRulesPreference.Override = .inherit + public private(set) var index: UInt8 public let name: String public let secret: Data public let isEnabled: Bool public let lastMessageDate: Date? public let unreadCount: Int public let unreadMentionCount: Int - public let notificationLevel: NotificationLevel - public let isPinned: Bool - public let floodScopeModeRawValue: String - public let regionScope: String? + public private(set) var notificationLevel: NotificationLevel + public private(set) var isPinned: Bool + public private(set) var floodScopeModeRawValue: String + public private(set) var regionScope: String? /// Convenience property for checking if muted public var isMuted: Bool { @@ -316,6 +326,8 @@ public struct ChannelDTO: Sendable, Equatable, Identifiable, Hashable, Codable { public init(from channel: Channel) { id = channel.id radioID = channel.radioID + textRulesID = channel.textRulesID + textRulesOverride = channel.textRulesOverride index = channel.index name = channel.name secret = channel.secret @@ -368,85 +380,49 @@ public struct ChannelDTO: Sendable, Equatable, Identifiable, Hashable, Codable { /// Returns a copy with only `notificationLevel` changed. public func with(notificationLevel: NotificationLevel) -> ChannelDTO { - ChannelDTO( - id: id, radioID: radioID, index: index, name: name, - secret: secret, isEnabled: isEnabled, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - notificationLevel: notificationLevel, isPinned: isPinned, - floodScope: floodScope - ) + var copy = self + copy.notificationLevel = notificationLevel + return copy } /// Returns a copy with only `isPinned` changed. public func with(isPinned: Bool) -> ChannelDTO { - ChannelDTO( - id: id, radioID: radioID, index: index, name: name, - secret: secret, isEnabled: isEnabled, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - notificationLevel: notificationLevel, isPinned: isPinned, - floodScope: floodScope - ) + var copy = self + copy.isPinned = isPinned + return copy } /// Returns a copy with only the flood-scope preference changed. public func with(floodScope: ChannelFloodScope) -> ChannelDTO { - ChannelDTO( - id: id, radioID: radioID, index: index, name: name, - secret: secret, isEnabled: isEnabled, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - notificationLevel: notificationLevel, isPinned: isPinned, - floodScope: floodScope - ) + var copy = self + let storage = ChannelFloodScopeStorage.decompose(floodScope) + copy.floodScopeModeRawValue = storage.mode.rawValue + copy.regionScope = storage.regionName + return copy } - /// Returns a copy placed at a different slot `index`, forwarding every other raw - /// storage field verbatim. Used by backup import to relocate a channel whose secret - /// has no local match onto a free slot without routing through the normalizing - /// ``ChannelFloodScope`` accessor (preserving pre-migration flood-scope rows). + /// Relocates the channel to a different slot while preserving raw flood-scope values for migration. func with(index newIndex: UInt8) -> ChannelDTO { - ChannelDTO( - id: id, radioID: radioID, index: newIndex, name: name, - secret: secret, isEnabled: isEnabled, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - notificationLevel: notificationLevel, isPinned: isPinned, - floodScopeModeRawValue: floodScopeModeRawValue, - regionScope: regionScope - ) + var copy = self + copy.index = newIndex + return copy } - /// Returns a copy with a fresh surrogate `id`, forwarding every other raw storage - /// field verbatim. Used by backup import so a relocated/non-matching channel can never - /// upsert a live local channel that happens to share the backup's `@Attribute(.unique)` - /// id. Channel has no inbound foreign key, so re-issuing the id breaks no linkage; it - /// uses the raw initializer to preserve pre-migration flood-scope rows (see ``init(dto:)``). + /// Replaces the row ID so backup import cannot overwrite a different channel with the same ID. func with(id newID: UUID) -> ChannelDTO { - ChannelDTO( - id: newID, radioID: radioID, index: index, name: name, - secret: secret, isEnabled: isEnabled, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - notificationLevel: notificationLevel, isPinned: isPinned, - floodScopeModeRawValue: floodScopeModeRawValue, - regionScope: regionScope - ) + var copy = self + copy.id = newID + return copy } - /// Returns a copy with only the raw `regionScope` column changed. This is the - /// low-level bypass used for tests that must simulate malformed on-disk state; - /// production code should go through ``with(floodScope:)``. + /// Changes the raw region name without normalizing the stored flood scope. func with(regionScope: String?) -> ChannelDTO { - ChannelDTO( - id: id, radioID: radioID, index: index, name: name, - secret: secret, isEnabled: isEnabled, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - notificationLevel: notificationLevel, isPinned: isPinned, - floodScopeModeRawValue: floodScopeModeRawValue, - regionScope: regionScope - ) + var copy = self + copy.regionScope = regionScope + return copy } - /// Low-level init that sets both raw storage fields directly. Kept `internal` - /// to prevent callers from constructing invalid combinations; used by - /// ``with(regionScope:)`` and migration tests. + /// Accepts raw flood-scope values, including combinations that require migration. init( id: UUID, radioID: UUID, diff --git a/MC1Services/Sources/MC1Services/Models/Contact.swift b/MC1Services/Sources/MC1Services/Models/Contact.swift index 373dea2af8..34a155fe36 100644 --- a/MC1Services/Sources/MC1Services/Models/Contact.swift +++ b/MC1Services/Sources/MC1Services/Models/Contact.swift @@ -20,6 +20,13 @@ public final class Contact { @Attribute(originalName: "deviceID") public var radioID: UUID + var textRulesID: UUID? + var textRulesOverrideRawValue: String = TextRulesPreference.Override.inherit.rawValue + + var textRulesOverride: TextRulesPreference.Override { + TextRulesPreference.Override(rawValue: textRulesOverrideRawValue) ?? .inherit + } + /// The 32-byte public key of the contact public var publicKey: Data @@ -117,6 +124,7 @@ public final class Contact { ) { self.id = id self.radioID = radioID + textRulesID = UUID() self.publicKey = publicKey self.name = name self.typeRawValue = typeRawValue @@ -301,6 +309,8 @@ public extension Contact { public struct ContactDTO: Sendable, Equatable, Identifiable, Hashable, Codable, RepeaterResolvable { public let id: UUID public var radioID: UUID + public internal(set) var textRulesID: UUID? + public internal(set) var textRulesOverride: TextRulesPreference.Override = .inherit public let publicKey: Data public let name: String public let typeRawValue: UInt8 @@ -315,15 +325,15 @@ public struct ContactDTO: Sendable, Equatable, Identifiable, Hashable, Codable, public let lastHeardTimestamp: UInt32? public let nickname: String? public let isBlocked: Bool - public let isMuted: Bool - public let isFavorite: Bool - public let isPinned: Bool + public private(set) var isMuted: Bool + public private(set) var isFavorite: Bool + public private(set) var isPinned: Bool public let lastMessageDate: Date? public let unreadCount: Int public let unreadMentionCount: Int public let ocvPreset: String? public let customOCVArrayString: String? - public let avatarImageData: Data? + public private(set) var avatarImageData: Data? /// A missing `isPinned` key decodes as `isFavorite`. An explicit false stays unpinned. private enum CodingKeys: String, CodingKey { @@ -396,6 +406,8 @@ public struct ContactDTO: Sendable, Equatable, Identifiable, Hashable, Codable, public init(from contact: Contact) { id = contact.id radioID = contact.radioID + textRulesID = contact.textRulesID + textRulesOverride = contact.textRulesOverride publicKey = contact.publicKey name = contact.name typeRawValue = contact.typeRawValue @@ -549,66 +561,30 @@ public struct ContactDTO: Sendable, Equatable, Identifiable, Hashable, Codable, /// Returns a copy with only `isMuted` changed. public func with(isMuted: Bool) -> ContactDTO { - ContactDTO( - id: id, radioID: radioID, publicKey: publicKey, name: name, - typeRawValue: typeRawValue, flags: flags, outPathLength: outPathLength, - outPath: outPath, lastAdvertTimestamp: lastAdvertTimestamp, - latitude: latitude, longitude: longitude, lastModified: lastModified, - lastHeardTimestamp: lastHeardTimestamp, - nickname: nickname, isBlocked: isBlocked, isMuted: isMuted, - isFavorite: isFavorite, isPinned: isPinned, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - ocvPreset: ocvPreset, customOCVArrayString: customOCVArrayString, - avatarImageData: avatarImageData - ) + var copy = self + copy.isMuted = isMuted + return copy } /// Returns a copy with only `isFavorite` changed. public func with(isFavorite: Bool) -> ContactDTO { - ContactDTO( - id: id, radioID: radioID, publicKey: publicKey, name: name, - typeRawValue: typeRawValue, flags: flags, outPathLength: outPathLength, - outPath: outPath, lastAdvertTimestamp: lastAdvertTimestamp, - latitude: latitude, longitude: longitude, lastModified: lastModified, - lastHeardTimestamp: lastHeardTimestamp, - nickname: nickname, isBlocked: isBlocked, isMuted: isMuted, - isFavorite: isFavorite, isPinned: isPinned, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - ocvPreset: ocvPreset, customOCVArrayString: customOCVArrayString, - avatarImageData: avatarImageData - ) + var copy = self + copy.isFavorite = isFavorite + return copy } /// Returns a copy with only `isPinned` changed. public func with(isPinned: Bool) -> ContactDTO { - ContactDTO( - id: id, radioID: radioID, publicKey: publicKey, name: name, - typeRawValue: typeRawValue, flags: flags, outPathLength: outPathLength, - outPath: outPath, lastAdvertTimestamp: lastAdvertTimestamp, - latitude: latitude, longitude: longitude, lastModified: lastModified, - lastHeardTimestamp: lastHeardTimestamp, - nickname: nickname, isBlocked: isBlocked, isMuted: isMuted, - isFavorite: isFavorite, isPinned: isPinned, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - ocvPreset: ocvPreset, customOCVArrayString: customOCVArrayString, - avatarImageData: avatarImageData - ) + var copy = self + copy.isPinned = isPinned + return copy } /// Returns a copy with only `avatarImageData` changed. public func with(avatarImageData: Data?) -> ContactDTO { - ContactDTO( - id: id, radioID: radioID, publicKey: publicKey, name: name, - typeRawValue: typeRawValue, flags: flags, outPathLength: outPathLength, - outPath: outPath, lastAdvertTimestamp: lastAdvertTimestamp, - latitude: latitude, longitude: longitude, lastModified: lastModified, - lastHeardTimestamp: lastHeardTimestamp, - nickname: nickname, isBlocked: isBlocked, isMuted: isMuted, - isFavorite: isFavorite, isPinned: isPinned, lastMessageDate: lastMessageDate, - unreadCount: unreadCount, unreadMentionCount: unreadMentionCount, - ocvPreset: ocvPreset, customOCVArrayString: customOCVArrayString, - avatarImageData: avatarImageData - ) + var copy = self + copy.avatarImageData = avatarImageData + return copy } /// The active OCV array for this contact (preset or custom) diff --git a/MC1Services/Sources/MC1Services/Models/Device.swift b/MC1Services/Sources/MC1Services/Models/Device.swift index 370cdab239..0d059a297f 100644 --- a/MC1Services/Sources/MC1Services/Models/Device.swift +++ b/MC1Services/Sources/MC1Services/Models/Device.swift @@ -269,12 +269,8 @@ public final class Device { ) } - /// Applies all mutable fields from a DTO to this model instance. - /// Unlike `Channel.apply` and `Contact.apply`, the identity fields - /// `publicKey` and `radioID` are deliberately rewritten: rows are matched - /// by the stable `id`, runtime key rotation must persist the new key, and - /// ghost reconciliation after a partial backup import depends on the - /// overwrite (see `ConnectionManager.reconcileIdentity`). + /// Rewrites identity fields on the row matched by Device ID so key rotation and + /// Ghost reconciliation persist the canonical public key and Radio ID. func apply(_ dto: DeviceDTO) { radioID = dto.radioID publicKey = dto.publicKey diff --git a/MC1Services/Sources/MC1Services/Models/DirectMessageEnvelope.swift b/MC1Services/Sources/MC1Services/Models/DirectMessageEnvelope.swift index 9f71b9ff15..585aee0488 100644 --- a/MC1Services/Sources/MC1Services/Models/DirectMessageEnvelope.swift +++ b/MC1Services/Sources/MC1Services/Models/DirectMessageEnvelope.swift @@ -1,23 +1,17 @@ import Foundation -/// Direct-message envelope for `SendQueue`. -/// Captures the target contact at enqueue time so the drain can fetch -/// a fresh contact DTO per iteration — preserves the per-iteration -/// fetch semantics that defend against stale contact state. -/// -/// `isResend` is true only when the envelope represents an explicit -/// user-initiated resend of an already-sent DM. The DM queue drain -/// branches on this flag between `sendPendingDirectMessage` (no -/// `sendCount` bump) and `resendDirectMessage` (bumps `sendCount`, -/// broadcasts `MessageStatusEvent.resent`). +/// A queued DM whose Contact is fetched again when the send is admitted. public struct DirectMessageEnvelope: Sendable { public let messageID: UUID public let contactID: UUID + /// Explicit user resends increment `sendCount`; queue retries do not. public let isResend: Bool + public let isSingleAttempt: Bool - public init(messageID: UUID, contactID: UUID, isResend: Bool = false) { + public init(messageID: UUID, contactID: UUID, isResend: Bool = false, isSingleAttempt: Bool = false) { self.messageID = messageID self.contactID = contactID self.isResend = isResend + self.isSingleAttempt = isSingleAttempt } } diff --git a/MC1Services/Sources/MC1Services/Models/Message.swift b/MC1Services/Sources/MC1Services/Models/Message.swift index 27caa780e5..e0695af521 100644 --- a/MC1Services/Sources/MC1Services/Models/Message.swift +++ b/MC1Services/Sources/MC1Services/Models/Message.swift @@ -26,10 +26,14 @@ public final class Message { [\.radioID, \.channelIndex, \.createdAt], [\.radioID, \.channelIndex, \.sortDate], [\.radioID, \.channelIndex, \.timestamp], + [\.radioID, \.channelIndex, \.senderTimestamp], [\.contactID, \.createdAt], [\.contactID, \.sortDate], [\.contactID, \.containsSelfMention, \.mentionSeen], [\.radioID, \.channelIndex, \.containsSelfMention, \.mentionSeen], + [\.radioID, \.senderKeyPrefix, \.senderTimestamp], + [\.radioID, \.senderKeyPrefix, \.timestamp], + [\.reactionTargetMessageID], [\.deduplicationKey] ) @@ -150,6 +154,10 @@ public final class Message { /// Format: "👍:3,❤️:2,😂:1" (emoji:count pairs, ordered by count desc) public var reactionSummary: String? + /// Target and local sender retained for outgoing reaction recovery. + public var reactionTargetMessageID: UUID? + public var reactionSenderName: String? + /// Route type from RxLog correlation (-1 = unknown/uncorrelated) public var routeTypeRawValue: Int = -1 @@ -203,6 +211,8 @@ public final class Message { timestampCorrected: Bool = false, senderTimestamp: UInt32? = nil, reactionSummary: String? = nil, + reactionTargetMessageID: UUID? = nil, + reactionSenderName: String? = nil, routeTypeRawValue: Int = -1, regionScope: String? = nil, regionScopeMatches: [String] = [] @@ -243,6 +253,8 @@ public final class Message { self.timestampCorrected = timestampCorrected self.senderTimestamp = senderTimestamp self.reactionSummary = reactionSummary + self.reactionTargetMessageID = reactionTargetMessageID + self.reactionSenderName = reactionSenderName self.routeTypeRawValue = routeTypeRawValue self.regionScope = regionScope self.regionScopeMatches = regionScopeMatches @@ -290,6 +302,8 @@ public final class Message { timestampCorrected: dto.timestampCorrected, senderTimestamp: dto.senderTimestamp, reactionSummary: dto.reactionSummary, + reactionTargetMessageID: dto.reactionTargetMessageID, + reactionSenderName: dto.reactionSenderName, routeTypeRawValue: dto.routeType.map { Int($0.rawValue) } ?? -1, regionScope: dto.regionScope, regionScopeMatches: dto.regionScopeMatches @@ -377,6 +391,8 @@ public struct MessageDTO: Sendable, Equatable, Hashable, Identifiable, Codable { public var timestampCorrected: Bool public var senderTimestamp: UInt32? public var reactionSummary: String? + public var reactionTargetMessageID: UUID? + public var reactionSenderName: String? public var routeType: RouteType? public var regionScope: String? /// Sorted multi-match set. Empty when the backup key is missing. @@ -393,7 +409,8 @@ public struct MessageDTO: Sendable, Equatable, Hashable, Identifiable, Codable { roundTripTime, heardRepeats, sendCount, retryAttempt, maxRetryAttempts, deduplicationKey, linkPreviewURL, linkPreviewTitle, linkPreviewImageData, linkPreviewIconData, linkPreviewFetched, containsSelfMention, mentionSeen, - failureSeen, timestampCorrected, senderTimestamp, reactionSummary, routeType, + failureSeen, timestampCorrected, senderTimestamp, reactionSummary, + reactionTargetMessageID, reactionSenderName, routeType, regionScope, regionScopeMatches } @@ -436,6 +453,8 @@ public struct MessageDTO: Sendable, Equatable, Hashable, Identifiable, Codable { timestampCorrected = try container.decode(Bool.self, forKey: .timestampCorrected) senderTimestamp = try container.decodeIfPresent(UInt32.self, forKey: .senderTimestamp) reactionSummary = try container.decodeIfPresent(String.self, forKey: .reactionSummary) + reactionTargetMessageID = try container.decodeIfPresent(UUID.self, forKey: .reactionTargetMessageID) + reactionSenderName = try container.decodeIfPresent(String.self, forKey: .reactionSenderName) routeType = try container.decodeIfPresent(RouteType.self, forKey: .routeType) regionScope = try container.decodeIfPresent(String.self, forKey: .regionScope) // Missing key → []; do not invent matches from regionScope. @@ -488,6 +507,8 @@ public struct MessageDTO: Sendable, Equatable, Hashable, Identifiable, Codable { timestampCorrected = message.timestampCorrected senderTimestamp = message.senderTimestamp reactionSummary = message.reactionSummary + reactionTargetMessageID = message.reactionTargetMessageID + reactionSenderName = message.reactionSenderName routeType = UInt8(exactly: message.routeTypeRawValue) .flatMap(RouteType.init(rawValue:)) regionScope = message.regionScope @@ -532,6 +553,8 @@ public struct MessageDTO: Sendable, Equatable, Hashable, Identifiable, Codable { timestampCorrected: Bool = false, senderTimestamp: UInt32? = nil, reactionSummary: String? = nil, + reactionTargetMessageID: UUID? = nil, + reactionSenderName: String? = nil, routeType: RouteType? = nil, regionScope: String? = nil, regionScopeMatches: [String] = [] @@ -572,6 +595,8 @@ public struct MessageDTO: Sendable, Equatable, Hashable, Identifiable, Codable { self.timestampCorrected = timestampCorrected self.senderTimestamp = senderTimestamp self.reactionSummary = reactionSummary + self.reactionTargetMessageID = reactionTargetMessageID + self.reactionSenderName = reactionSenderName self.routeType = routeType self.regionScope = regionScope self.regionScopeMatches = regionScopeMatches @@ -624,9 +649,9 @@ public struct MessageDTO: Sendable, Equatable, Hashable, Identifiable, Codable { Date(timeIntervalSince1970: TimeInterval(senderTimestamp ?? timestamp)) } - /// Hop count decoded from pathLength (lower 6 bits) - public var hopCount: Int { - decodePathLen(pathLength)?.hopCount ?? Int(pathLength & 63) + /// Hop count from a path-length byte `decodePathLen` accepts. A rejected byte, including 0xFF, has none. + public var hopCount: Int? { + decodePathLen(pathLength)?.hopCount } /// Whether this message was flood-routed (broadcast). @@ -723,8 +748,7 @@ public struct MessageDTO: Sendable, Equatable, Hashable, Identifiable, Codable { } private static func isSameSender(_ a: MessageDTO, _ b: MessageDTO) -> Bool { - guard a.direction == b.direction else { return false } - guard a.isChannelMessage == b.isChannelMessage else { return false } + guard a.direction == b.direction, a.isChannelMessage == b.isChannelMessage else { return false } // For channel messages, compare sender node name (nil = unknown, treat as different). // senderNodeName isn't unique — two users with the same name may be falsely clustered. diff --git a/MC1Services/Sources/MC1Services/Models/NodeStatusSnapshot.swift b/MC1Services/Sources/MC1Services/Models/NodeStatusSnapshot.swift index 028db01ce9..9a435a883d 100644 --- a/MC1Services/Sources/MC1Services/Models/NodeStatusSnapshot.swift +++ b/MC1Services/Sources/MC1Services/Models/NodeStatusSnapshot.swift @@ -5,9 +5,7 @@ import SwiftData /// Capture-rate policy for node status snapshots. enum NodeSnapshotPolicy { - /// Minimum interval between persisted snapshots for the same node. - /// A status, telemetry, or neighbor capture arriving within this window of - /// the latest snapshot enriches that row rather than inserting a new one. + /// Window for coalescing captures for the same public key and owner. static let minimumInterval: TimeInterval = 15 * 60 } @@ -133,7 +131,7 @@ public struct TelemetrySnapshotEntry: Codable, Sendable, Equatable { } } -/// Point-in-time snapshot of a remote node's status, captured when the user views it. +/// Point-in-time snapshot of node status or the connected radio's own telemetry. @Model final class NodeStatusSnapshot { #Index([\.nodePublicKey, \.timestamp]) @@ -144,9 +142,12 @@ final class NodeStatusSnapshot { /// When this snapshot was captured var timestamp: Date - /// The node's full public key (32 bytes) -- links to RemoteNodeSession + /// Full public key at capture. Keeping it separates readings taken before and after key rotation. var nodePublicKey: Data + /// Radio ID for self telemetry so deletion covers every captured key. Nil denotes remote history. + var selfRadioID: UUID? + // MARK: - Radio metrics // Intentionally excluded: txQueueLength, airtime, fullEvents @@ -198,6 +199,7 @@ final class NodeStatusSnapshot { id: UUID = UUID(), timestamp: Date = .now, nodePublicKey: Data, + selfRadioID: UUID? = nil, batteryMillivolts: UInt16? = nil, lastSNR: Double? = nil, lastRSSI: Int16? = nil, @@ -224,6 +226,7 @@ final class NodeStatusSnapshot { self.id = id self.timestamp = timestamp self.nodePublicKey = nodePublicKey + self.selfRadioID = selfRadioID self.batteryMillivolts = batteryMillivolts self.lastSNR = lastSNR self.lastRSSI = lastRSSI @@ -276,6 +279,7 @@ final class NodeStatusSnapshot { id: dto.id, timestamp: dto.timestamp, nodePublicKey: dto.nodePublicKey, + selfRadioID: dto.selfRadioID, batteryMillivolts: dto.batteryMillivolts, lastSNR: dto.lastSNR, lastRSSI: dto.lastRSSI, @@ -308,6 +312,7 @@ public struct NodeStatusSnapshotDTO: Sendable, Equatable, Identifiable, Codable public let id: UUID public let timestamp: Date public let nodePublicKey: Data + public let selfRadioID: UUID? public let batteryMillivolts: UInt16? public let lastSNR: Double? public let lastRSSI: Int16? @@ -338,6 +343,7 @@ public struct NodeStatusSnapshotDTO: Sendable, Equatable, Identifiable, Codable id = model.id timestamp = model.timestamp nodePublicKey = model.nodePublicKey + selfRadioID = model.selfRadioID batteryMillivolts = model.batteryMillivolts lastSNR = model.lastSNR lastRSSI = model.lastRSSI @@ -366,6 +372,7 @@ public struct NodeStatusSnapshotDTO: Sendable, Equatable, Identifiable, Codable id: UUID = UUID(), timestamp: Date = .now, nodePublicKey: Data, + selfRadioID: UUID? = nil, batteryMillivolts: UInt16? = nil, lastSNR: Double? = nil, lastRSSI: Int16? = nil, @@ -392,6 +399,7 @@ public struct NodeStatusSnapshotDTO: Sendable, Equatable, Identifiable, Codable self.id = id self.timestamp = timestamp self.nodePublicKey = nodePublicKey + self.selfRadioID = selfRadioID self.batteryMillivolts = batteryMillivolts self.lastSNR = lastSNR self.lastRSSI = lastRSSI diff --git a/MC1Services/Sources/MC1Services/Models/PendingRadioErase.swift b/MC1Services/Sources/MC1Services/Models/PendingRadioErase.swift new file mode 100644 index 0000000000..eac8dbe05a --- /dev/null +++ b/MC1Services/Sources/MC1Services/Models/PendingRadioErase.swift @@ -0,0 +1,50 @@ +import Foundation +import SwiftData + +@Model +final class PendingRadioErase { + @Attribute(.unique) var radioID: UUID + var deviceID: UUID + var pairingID: UUID + var radioName: String + /// A legacy target has unknown purpose and must remain retryable. + var isFactoryReset: Bool? + + init(_ target: PendingRadioEraseDTO) { + radioID = target.radioID + deviceID = target.deviceID + pairingID = target.pairingID + radioName = target.radioName + isFactoryReset = target.isFactoryReset + } +} + +public struct PendingRadioEraseDTO: Sendable, Identifiable { + public let radioID: UUID + public let deviceID: UUID + public let pairingID: UUID + public let radioName: String + let isFactoryReset: Bool? + + public var id: UUID { + radioID + } + + init(radioID: UUID, deviceID: UUID, pairingID: UUID, radioName: String, isFactoryReset: Bool?) { + self.radioID = radioID + self.deviceID = deviceID + self.pairingID = pairingID + self.radioName = radioName + self.isFactoryReset = isFactoryReset + } + + init(_ target: PendingRadioErase) { + self.init( + radioID: target.radioID, + deviceID: target.deviceID, + pairingID: target.pairingID, + radioName: target.radioName, + isFactoryReset: target.isFactoryReset + ) + } +} diff --git a/MC1Services/Sources/MC1Services/Models/PendingSend.swift b/MC1Services/Sources/MC1Services/Models/PendingSend.swift index 26836068d0..c250ab6795 100644 --- a/MC1Services/Sources/MC1Services/Models/PendingSend.swift +++ b/MC1Services/Sources/MC1Services/Models/PendingSend.swift @@ -1,41 +1,10 @@ import Foundation import SwiftData -/// Persistent record of an envelope queued for send. Survives process death -/// so `SendQueue` resumes draining after the app restarts. -/// -/// Rows are scoped to a single radio via `radioID` so reconnecting to a -/// different radio does not attempt to send envelopes whose messages live -/// in a different radio's data partition. -/// -/// `sequence` is a per-radio monotonic counter assigned by -/// `PersistenceStore.insertPendingSendAssigningSequence(_:)` at enqueue -/// time. `fetchPendingSends` orders by `sequence` ascending so drain order -/// across process death matches the original enqueue order. -/// -/// Storage type choices align with `Message` (UInt32 timestamp, -/// UInt8? channelIndex) so future readers don't pay an `Int` conversion -/// hop on every read/write. -/// -/// PendingSend uses a discriminated single-table design (`kindRawValue` -/// selects DM vs. channel) rather than two parallel @Model classes. No -/// other @Model in MC1 follows this pattern, but the alternative — two -/// tables with two sets of CRUD — adds far more surface than the ≤6 -/// optional fields per variant justify. Documenting the choice here so -/// future maintainers don't re-evaluate it from scratch. +/// Durable send work partitioned by Radio ID and ordered by a per-radio sequence. +/// ACK metadata retains delivery tracking after command issuance ends. @Model public final class PendingSend { - // Compound indexes targeting the two hot fetch paths: - // - `(radioID, sequence)` powers `fetchPendingSends(radioID:)`'s - // ordered scan during hydrate-on-configure. - // - `messageID` alone powers `deletePendingSendsForMessage(...)`, - // which runs on every successful send and every non-cancellation - // error — i.e., the highest-frequency read path on this table. - // Radio is intentionally not part of this index because the - // drain-time delete must succeed regardless of which radio is - // currently in scope. - // The uniqueness on `id` already produces an implicit index for the - // `deletePendingSend(id:)` path, so no third compound is needed. #Index([\.radioID, \.sequence], [\.messageID]) @Attribute(.unique) @@ -44,12 +13,12 @@ public final class PendingSend { public var radioID: UUID public var messageID: UUID - /// Discriminator: 0 = DM, 1 = channel. See `PendingSendKind`. public var kindRawValue: Int public var contactID: UUID? public var channelIndex: UInt8? public var isResend: Bool + public var isSingleAttempt: Bool = false public var messageText: String public var messageTimestamp: UInt32 @@ -58,31 +27,21 @@ public final class PendingSend { public var sequence: Int public var enqueuedAt: Date - /// Number of drain attempts the send queue has progressed past the - /// `hasPendingSend` gate for this row. Bumped at the top of each drain - /// attempt, before any wire-affecting work. Three distinguishable states: - /// - /// - `nil` — pre-migration row, lightweight-migrated from a schema - /// version without this column. Drain history is ambiguous, - /// so `purgeLegacyAttemptCountRows` in - /// `PersistenceStore.warmUp()` deletes these on connect. - /// - `0` — row that has been persisted but has not yet progressed - /// past the top-of-drain bump (either fresh enqueue in - /// flight, or process death between persist and bump). - /// The recipient cannot have seen this packet, so the - /// next drain stamps a fresh wire timestamp - /// (`preserveTimestamp = false`). - /// - positive — at least one drain attempt has run. A wire send may - /// already have happened, so auto-retries must preserve the - /// original wire timestamp via `postBumpCount > 1`. - /// - /// PendingSendDTO is `Sendable, Hashable, Identifiable` only — intentionally - /// not Codable, intentionally excluded from AppBackupEnvelope — so there - /// is no on-disk wire format to defend against. The only "legacy" data is - /// live SwiftData rows persisted by a build that predates this field, - /// which lightweight migration maps to `nil` and warmUp purges on connect. + /// Persisted before issuing a command so recovery knows whether to reuse the wire timestamp. + /// `nil` marks legacy rows with ambiguous send history; warm-up purges them. + /// `0` permits a fresh timestamp because no attempt has started. A positive count + /// means transmission may have started, so replay preserves the timestamp. public var attemptCount: Int? + /// Next `CMD_SEND_TXT_MSG` attempt byte for this row's current wire timestamp. + /// Bytes already handed to the radio stay below this value. `0` is a new timestamp. + public var nextWireAttempt: UInt8 = 0 + + /// Non-nil ACK metadata changes this row from queued work to delivery tracking without retransmission. + public var ackCodes: [Data]? + public var ackSentAt: Date? + public var ackDeadline: Date? + public init( id: UUID, radioID: UUID, @@ -96,7 +55,12 @@ public final class PendingSend { localNodeName: String?, sequence: Int, enqueuedAt: Date, - attemptCount: Int? = nil + attemptCount: Int? = nil, + nextWireAttempt: UInt8 = 0, + ackCodes: [Data]? = nil, + ackSentAt: Date? = nil, + ackDeadline: Date? = nil, + isSingleAttempt: Bool = false ) { self.id = id self.radioID = radioID @@ -105,12 +69,17 @@ public final class PendingSend { self.contactID = contactID self.channelIndex = channelIndex self.isResend = isResend + self.isSingleAttempt = isSingleAttempt self.messageText = messageText self.messageTimestamp = messageTimestamp self.localNodeName = localNodeName self.sequence = sequence self.enqueuedAt = enqueuedAt self.attemptCount = attemptCount + self.nextWireAttempt = nextWireAttempt + self.ackCodes = ackCodes + self.ackSentAt = ackSentAt + self.ackDeadline = ackDeadline } var kind: PendingSendKind { @@ -118,25 +87,13 @@ public final class PendingSend { } } -/// Discriminator for which `SendQueue` a row drains into. -/// -/// Raw values are pinned explicitly per CLAUDE.md "Backup and restore" — -/// even though `PendingSendDTO` is excluded from `AppBackupEnvelope`, the -/// discriminator IS persisted via `kindRawValue` and a future case rename -/// must not silently change the on-disk format. +/// Raw values persist in `kindRawValue` and must survive case renames. enum PendingSendKind: Int { case dm = 0 case channel = 1 } -/// Sendable DTO mirror of `PendingSend`. Raw `@Model` instances never leave -/// `PersistenceStore`. -/// -/// Intentionally non-Codable: pending sends are transient queue state and -/// are excluded from `AppBackupEnvelope` by design. Restoring a pending -/// send from backup would replay a message that may have already been -/// delivered on the radio, so the DTO does not flow through backup- -/// envelope encoding paths. +/// Excluded from `AppBackupEnvelope` because restoring pending work could replay a delivered send. public struct PendingSendDTO: Sendable, Hashable, Identifiable { public let id: UUID public let radioID: UUID @@ -145,16 +102,19 @@ public struct PendingSendDTO: Sendable, Hashable, Identifiable { public let contactID: UUID? public let channelIndex: UInt8? public let isResend: Bool + public let isSingleAttempt: Bool public let messageText: String public let messageTimestamp: UInt32 public let localNodeName: String? public let sequence: Int public let enqueuedAt: Date - /// See `PendingSend.attemptCount` for the three-state semantics. The DTO - /// memberwise init defaults this to `0` (current-build sentinel) so - /// new envelopes enter disk distinguishable from pre-migration rows that - /// lightweight-migrate to `nil`. + /// Zero distinguishes new sends from legacy rows migrated to nil. public let attemptCount: Int? + /// Bytes below this value were already handed to the radio for this timestamp. + public let nextWireAttempt: UInt8 + public let ackCodes: [Data]? + public let ackSentAt: Date? + public let ackDeadline: Date? init( id: UUID, @@ -169,7 +129,12 @@ public struct PendingSendDTO: Sendable, Hashable, Identifiable { localNodeName: String?, sequence: Int, enqueuedAt: Date, - attemptCount: Int? = 0 + attemptCount: Int? = 0, + nextWireAttempt: UInt8 = 0, + ackCodes: [Data]? = nil, + ackSentAt: Date? = nil, + ackDeadline: Date? = nil, + isSingleAttempt: Bool = false ) { self.id = id self.radioID = radioID @@ -178,12 +143,17 @@ public struct PendingSendDTO: Sendable, Hashable, Identifiable { self.contactID = contactID self.channelIndex = channelIndex self.isResend = isResend + self.isSingleAttempt = isSingleAttempt self.messageText = messageText self.messageTimestamp = messageTimestamp self.localNodeName = localNodeName self.sequence = sequence self.enqueuedAt = enqueuedAt self.attemptCount = attemptCount + self.nextWireAttempt = nextWireAttempt + self.ackCodes = ackCodes + self.ackSentAt = ackSentAt + self.ackDeadline = ackDeadline } } @@ -202,7 +172,12 @@ public extension PendingSend { localNodeName: dto.localNodeName, sequence: dto.sequence, enqueuedAt: dto.enqueuedAt, - attemptCount: dto.attemptCount + attemptCount: dto.attemptCount, + nextWireAttempt: dto.nextWireAttempt, + ackCodes: dto.ackCodes, + ackSentAt: dto.ackSentAt, + ackDeadline: dto.ackDeadline, + isSingleAttempt: dto.isSingleAttempt ) } @@ -220,7 +195,12 @@ public extension PendingSend { localNodeName: localNodeName, sequence: sequence, enqueuedAt: enqueuedAt, - attemptCount: attemptCount + attemptCount: attemptCount, + nextWireAttempt: nextWireAttempt, + ackCodes: ackCodes, + ackSentAt: ackSentAt, + ackDeadline: ackDeadline, + isSingleAttempt: isSingleAttempt ) } } diff --git a/MC1Services/Sources/MC1Services/Models/PendingSendEnvelope.swift b/MC1Services/Sources/MC1Services/Models/PendingSendEnvelope.swift index c9035ceec1..004fe26401 100644 --- a/MC1Services/Sources/MC1Services/Models/PendingSendEnvelope.swift +++ b/MC1Services/Sources/MC1Services/Models/PendingSendEnvelope.swift @@ -1,13 +1,12 @@ import Foundation -/// Convert a `PendingSendDTO` back into the runtime envelope shape the -/// `SendQueue` actor consumes. Returns nil if the DTO's discriminator does -/// not match the requested envelope type — guards against mis-routing a -/// channel row into the DM queue or vice versa. public extension PendingSendDTO { + /// ACK-owned rows retain delivery tracking without replaying the DM. func directMessageEnvelope() -> DirectMessageEnvelope? { - guard kind == .dm, let contactID else { return nil } - return DirectMessageEnvelope(messageID: messageID, contactID: contactID, isResend: isResend) + guard kind == .dm, ackDeadline == nil, let contactID else { return nil } + return DirectMessageEnvelope( + messageID: messageID, contactID: contactID, isResend: isResend, isSingleAttempt: isSingleAttempt + ) } func channelMessageEnvelope() -> ChannelMessageEnvelope? { @@ -23,31 +22,18 @@ public extension PendingSendDTO { } } -/// Construct a `PendingSendDTO` from a runtime envelope. Used by the -/// chat send queue service immediately before calling -/// `PersistenceStore.insertPendingSendAssigningSequence(_:)`. -/// -/// `sequence` is initialized to 0 here; the production persist path -/// assigns the real value inside `PersistenceStore` so two concurrent -/// enqueues can't race to produce the same sequence. Tests that need -/// to pin sequence values should call the full positional -/// `PendingSendDTO.init(...)` directly. +/// `PersistenceStore` assigns the sequence atomically so concurrent enqueues remain ordered. public extension PendingSendDTO { init( id: UUID = UUID(), envelope: DirectMessageEnvelope, radioID: UUID, - enqueuedAt: Date = Date() + enqueuedAt: Date = Date(), + ackCodes: [Data]? = nil, + ackSentAt: Date? = nil, + ackDeadline: Date? = nil ) { - // DM rows persist `isResend` so a process restart between enqueue - // and drain routes the row to the same send method it would have - // hit pre-restart (sendPendingDirectMessage vs. resendDirectMessage). - // `messageTimestamp` stays sentinel: the DM drain keys preserve- - // timestamp behaviour off `PendingSend.attemptCount` via the - // top-of-drain bump (`postBumpCount > 1` returns true on the 2nd+ - // drain attempt), so the wire timestamp does not round-trip - // through the DTO. Channel rows persist both explicitly because - // reaction indexing hashes off the post-send wire timestamp. + // The DM message row owns its text and wire timestamp; the envelope retains only send policy. self.init( id: id, radioID: radioID, @@ -60,7 +46,11 @@ public extension PendingSendDTO { messageTimestamp: 0, localNodeName: nil, sequence: 0, - enqueuedAt: enqueuedAt + enqueuedAt: enqueuedAt, + ackCodes: ackCodes, + ackSentAt: ackSentAt, + ackDeadline: ackDeadline, + isSingleAttempt: envelope.isSingleAttempt ) } @@ -70,14 +60,7 @@ public extension PendingSendDTO { radioID: UUID, enqueuedAt: Date = Date() ) { - // ChannelMessageEnvelope DTO factory captures `envelope.messageTimestamp` - // verbatim. For isResend=true rows the stored timestamp is overwritten - // before use — `resendChannelMessage(preserveTimestamp: postBumpCount > 1)` - // stamps a fresh wire timestamp when this is the first drain attempt - // (`postBumpCount == 1`), and reaction indexing keys off the - // post-resend value, not the persisted one. Kept non-zero on resend - // rows for symmetry with original-send rows; readers must not depend - // on the value for retry-path semantics. + // A first resend replaces this timestamp; reaction indexing uses the post-send value. self.init( id: id, radioID: radioID, diff --git a/MC1Services/Sources/MC1Services/Models/ProtocolLimits.swift b/MC1Services/Sources/MC1Services/Models/ProtocolLimits.swift index addd01ce59..f5abe5ab9a 100644 --- a/MC1Services/Sources/MC1Services/Models/ProtocolLimits.swift +++ b/MC1Services/Sources/MC1Services/Models/ProtocolLimits.swift @@ -18,6 +18,7 @@ public enum ProtocolLimits { public static let maxNameLength = 32 public static let channelSecretSize = 16 public static let maxMessageLength = 160 + public static let maxRemotePasswordBytes = 15 /// Maximum usable bytes for names (firmware char[32] minus null terminator) public static let maxUsableNameBytes = 31 diff --git a/MC1Services/Sources/MC1Services/Models/ProtocolTypes.swift b/MC1Services/Sources/MC1Services/Models/ProtocolTypes.swift index e75cff07c6..532a628510 100644 --- a/MC1Services/Sources/MC1Services/Models/ProtocolTypes.swift +++ b/MC1Services/Sources/MC1Services/Models/ProtocolTypes.swift @@ -25,6 +25,7 @@ public extension ContactType { case .chat: "Contact" case .repeater: "Repeater" case .room: "Room" + case .sensor: "Sensor" } } } @@ -45,12 +46,14 @@ public enum TextType: UInt8, Sendable, Codable { public enum RemoteNodeRole: UInt8, Sendable, Codable { case repeater = 0x02 case roomServer = 0x03 + case sensor = 0x04 /// Initialize from ContactType public init?(contactType: ContactType) { switch contactType { case .repeater: self = .repeater case .room: self = .roomServer + case .sensor: self = .sensor case .chat: return nil } } diff --git a/MC1Services/Sources/MC1Services/Models/QueuedDirectMessageWireAttempt.swift b/MC1Services/Sources/MC1Services/Models/QueuedDirectMessageWireAttempt.swift new file mode 100644 index 0000000000..95c35684a0 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Models/QueuedDirectMessageWireAttempt.swift @@ -0,0 +1,26 @@ +import Foundation + +/// A queued direct message whose attempt bytes were already handed to the radio. +/// The service hashes acknowledgement codes from these fields. The store does not. +public struct QueuedDirectMessageWireAttempt: Sendable, Equatable { + public let pendingSendID: UUID + public let messageID: UUID + public let timestamp: UInt32 + public let text: String + /// Attempt bytes `0.. Bool { + lhs.radioID == rhs.radioID && lhs.link === rhs.link && lhs.partition === rhs.partition + } + + public var isCurrent: Bool { + link.isCurrent && partition.isCurrent + } +} diff --git a/MC1Services/Sources/MC1Services/Models/RecentlyBlockedMessage.swift b/MC1Services/Sources/MC1Services/Models/RecentlyBlockedMessage.swift new file mode 100644 index 0000000000..e9b75f5864 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Models/RecentlyBlockedMessage.swift @@ -0,0 +1,52 @@ +import Foundation +import SwiftData + +@Model +final class RecentlyBlockedMessage { + #Index([\.radioID, \.senderTimestamp]) + + @Attribute(.unique) + var id: UUID + var radioID: UUID + var conversationID: UUID? + var senderPrefix: Data? + var senderTimestamp: UInt32 + var textTypeRawValue: UInt8? + var wireText: Data + + var arrivedAt: Date + var body: String + var sender: String? + var conversationName: String? + var radioName: String? + var matchData: Data + var contactID: UUID? + + init(_ entry: RecentlyBlockedMessageDTO) throws { + id = entry.id + radioID = entry.identity.radioID + conversationID = entry.identity.conversationID + senderPrefix = entry.identity.senderPrefix + senderTimestamp = entry.identity.senderTimestamp + textTypeRawValue = entry.identity.textType + wireText = entry.identity.wireText + arrivedAt = entry.arrivedAt + body = entry.body + sender = entry.sender + conversationName = entry.conversationName + radioName = entry.radioName + matchData = try JSONEncoder().encode(entry.match) + contactID = entry.contactID + } + + var identity: RecentlyBlockedMessageDTO.Identity { + RecentlyBlockedMessageDTO.Identity( + radioID: radioID, + conversationID: conversationID, + senderPrefix: senderPrefix, + senderTimestamp: senderTimestamp, + textType: textTypeRawValue, + wireText: wireText + ) + } +} diff --git a/MC1Services/Sources/MC1Services/Models/RecentlyBlockedMessageDTO.swift b/MC1Services/Sources/MC1Services/Models/RecentlyBlockedMessageDTO.swift new file mode 100644 index 0000000000..600a5a996d --- /dev/null +++ b/MC1Services/Sources/MC1Services/Models/RecentlyBlockedMessageDTO.swift @@ -0,0 +1,72 @@ +import Foundation + +public struct RecentlyBlockedMessageDTO: Identifiable, Sendable, Equatable { + public struct Identity: Sendable, Equatable { + public let radioID: UUID + public let conversationID: UUID? + public let senderPrefix: Data? + public let senderTimestamp: UInt32 + public let textType: UInt8? + public let wireText: Data + + public init( + radioID: UUID, + conversationID: UUID?, + senderPrefix: Data?, + senderTimestamp: UInt32, + textType: UInt8?, + wireText: Data + ) { + self.radioID = radioID + self.conversationID = conversationID + self.senderPrefix = senderPrefix + self.senderTimestamp = senderTimestamp + self.textType = textType + self.wireText = wireText + } + } + + public let id: UUID + public let identity: Identity + public let arrivedAt: Date + public let body: String + public let sender: String? + public let conversationName: String? + public let radioName: String? + public let match: TextRulesPreference.RuleMatch + public let contactID: UUID? + + public init( + id: UUID = UUID(), + identity: Identity, + arrivedAt: Date, + body: String, + sender: String?, + conversationName: String?, + radioName: String?, + match: TextRulesPreference.RuleMatch, + contactID: UUID? = nil + ) { + self.id = id + self.identity = identity + self.arrivedAt = arrivedAt + self.body = body + self.sender = sender + self.conversationName = conversationName + self.radioName = radioName + self.match = match + self.contactID = contactID + } + + init(from entry: RecentlyBlockedMessage) throws { + id = entry.id + identity = entry.identity + arrivedAt = entry.arrivedAt + body = entry.body + sender = entry.sender + conversationName = entry.conversationName + radioName = entry.radioName + match = try JSONDecoder().decode(TextRulesPreference.RuleMatch.self, from: entry.matchData) + contactID = entry.contactID + } +} diff --git a/MC1Services/Sources/MC1Services/Models/RemoteNodeSession.swift b/MC1Services/Sources/MC1Services/Models/RemoteNodeSession.swift index 507f8ff8cf..c39b77235e 100644 --- a/MC1Services/Sources/MC1Services/Models/RemoteNodeSession.swift +++ b/MC1Services/Sources/MC1Services/Models/RemoteNodeSession.swift @@ -3,7 +3,7 @@ import Foundation import SwiftData /// Represents an authenticated session with a remote node. -/// Used for both room servers and repeater admin connections. +/// Used for room membership and remote node management. @Model public final class RemoteNodeSession { #Index([\.radioID]) @@ -16,6 +16,13 @@ public final class RemoteNodeSession { @Attribute(originalName: "deviceID") public var radioID: UUID + var textRulesID: UUID? + var textRulesOverrideRawValue: String = TextRulesPreference.Override.inherit.rawValue + + var textRulesOverride: TextRulesPreference.Override { + TextRulesPreference.Override(rawValue: textRulesOverrideRawValue) ?? .inherit + } + /// 32-byte remote node's public key public var publicKey: Data @@ -120,6 +127,7 @@ public final class RemoteNodeSession { ) { self.id = id self.radioID = radioID + textRulesID = UUID() self.publicKey = publicKey self.name = name roleRawValue = role.rawValue @@ -215,6 +223,10 @@ public extension RemoteNodeSession { role == .repeater } + var isSensor: Bool { + role == .sensor + } + /// 6-byte public key prefix for addressing var publicKeyPrefix: Data { publicKey.prefix(6) @@ -242,6 +254,8 @@ public extension RemoteNodeSession { public struct RemoteNodeSessionDTO: Sendable, Equatable, Identifiable, Hashable, Codable { public let id: UUID public var radioID: UUID + public internal(set) var textRulesID: UUID? + public internal(set) var textRulesOverride: TextRulesPreference.Override = .inherit public let publicKey: Data public let name: String public let role: RemoteNodeRole @@ -254,8 +268,8 @@ public struct RemoteNodeSessionDTO: Sendable, Equatable, Identifiable, Hashable, public let lastUptimeSeconds: UInt32? public let lastNoiseFloor: Int16? public let unreadCount: Int - public let notificationLevel: NotificationLevel - public let isPinned: Bool + public private(set) var notificationLevel: NotificationLevel + public private(set) var isPinned: Bool /// Convenience property for checking if muted public var isMuted: Bool { @@ -331,6 +345,8 @@ public struct RemoteNodeSessionDTO: Sendable, Equatable, Identifiable, Hashable, public init(from model: RemoteNodeSession) { id = model.id radioID = model.radioID + textRulesID = model.textRulesID + textRulesOverride = model.textRulesOverride publicKey = model.publicKey name = model.name role = model.role @@ -407,34 +423,16 @@ public struct RemoteNodeSessionDTO: Sendable, Equatable, Identifiable, Hashable, /// Returns a copy with only `notificationLevel` changed. public func with(notificationLevel: NotificationLevel) -> RemoteNodeSessionDTO { - RemoteNodeSessionDTO( - id: id, radioID: radioID, publicKey: publicKey, name: name, - role: role, latitude: latitude, longitude: longitude, - isConnected: isConnected, permissionLevel: permissionLevel, - lastConnectedDate: lastConnectedDate, - lastBatteryMillivolts: lastBatteryMillivolts, - lastUptimeSeconds: lastUptimeSeconds, lastNoiseFloor: lastNoiseFloor, - unreadCount: unreadCount, notificationLevel: notificationLevel, - isPinned: isPinned, lastRxAirtimeSeconds: lastRxAirtimeSeconds, - neighborCount: neighborCount, lastSyncTimestamp: lastSyncTimestamp, - lastMessageDate: lastMessageDate - ) + var copy = self + copy.notificationLevel = notificationLevel + return copy } /// Returns a copy with only `isPinned` changed. public func with(isPinned: Bool) -> RemoteNodeSessionDTO { - RemoteNodeSessionDTO( - id: id, radioID: radioID, publicKey: publicKey, name: name, - role: role, latitude: latitude, longitude: longitude, - isConnected: isConnected, permissionLevel: permissionLevel, - lastConnectedDate: lastConnectedDate, - lastBatteryMillivolts: lastBatteryMillivolts, - lastUptimeSeconds: lastUptimeSeconds, lastNoiseFloor: lastNoiseFloor, - unreadCount: unreadCount, notificationLevel: notificationLevel, - isPinned: isPinned, lastRxAirtimeSeconds: lastRxAirtimeSeconds, - neighborCount: neighborCount, lastSyncTimestamp: lastSyncTimestamp, - lastMessageDate: lastMessageDate - ) + var copy = self + copy.isPinned = isPinned + return copy } public var publicKeyPrefix: Data { @@ -453,6 +451,10 @@ public struct RemoteNodeSessionDTO: Sendable, Equatable, Identifiable, Hashable, role == .repeater } + public var isSensor: Bool { + role == .sensor + } + public var canPost: Bool { isRoom && permissionLevel.canPost } diff --git a/MC1Services/Sources/MC1Services/Models/Rendering/MessageTranslationChrome.swift b/MC1Services/Sources/MC1Services/Models/Rendering/MessageTranslationChrome.swift index fda5ac96d7..9ef1587ecf 100644 --- a/MC1Services/Sources/MC1Services/Models/Rendering/MessageTranslationChrome.swift +++ b/MC1Services/Sources/MC1Services/Models/Rendering/MessageTranslationChrome.swift @@ -17,13 +17,15 @@ public struct MessageTranslationChrome: Sendable, Hashable { self.sourceLanguageCode = sourceLanguageCode } - /// In-flight wins; showing wins only if its target still matches preferred. - /// Otherwise an offer exists only when detection differs from preferred. + /// Nil when `text` decodes as an MECP reading. In-flight wins, and showing wins only when its target still matches preferred. + /// An offer exists only when detection differs from preferred. public static func resolved( detected: DetectedLanguage?, phase: Phase?, - preferredLanguageCode: String + preferredLanguageCode: String, + text: String ) -> MessageTranslationChrome? { + guard MECPCatalog.reading(text) == nil else { return nil } guard case let .identified(languageCode: sourceLanguageCode) = detected else { return nil } if let phase { switch phase { diff --git a/MC1Services/Sources/MC1Services/Models/SensorSetting.swift b/MC1Services/Sources/MC1Services/Models/SensorSetting.swift new file mode 100644 index 0000000000..94b7748a06 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Models/SensorSetting.swift @@ -0,0 +1,41 @@ +import Foundation + +/// A firmware-enumerated setting; values remain verbatim, including empty values. +public struct SensorSetting: Sendable, Equatable, Identifiable { + public let key: String + public let value: String + public var id: String { + key + } + + public static let correlationPrefixBytes = 3 + public static let maxCommandBytes = ProtocolLimits.maxMessageLength - correlationPrefixBytes + private static let setPrefix = "sensor set " + + public init(key: String, value: String) { + self.key = key + self.value = value + } + + public func command(setting value: String) throws -> String { + guard Self.isToken(key), Self.isToken(value) else { + throw RemoteNodeError.invalidSensorSetting + } + let command = Self.setPrefix + key + " " + value + try Self.validateCommand(command) + return command + } + + public static func validateCommand(_ command: String) throws { + guard !command.isEmpty, command.utf8.count <= maxCommandBytes, + !command.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }) else { + throw RemoteNodeError.invalidSensorSetting + } + } + + private static func isToken(_ value: String) -> Bool { + !value.isEmpty && !value.unicodeScalars.contains { + CharacterSet.whitespacesAndNewlines.contains($0) || CharacterSet.controlCharacters.contains($0) + } + } +} diff --git a/MC1Services/Sources/MC1Services/Models/TextRulesPreference.swift b/MC1Services/Sources/MC1Services/Models/TextRulesPreference.swift new file mode 100644 index 0000000000..92790d5879 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Models/TextRulesPreference.swift @@ -0,0 +1,238 @@ +import Foundation + +// swiftformat:disable redundantRawValues +// swiftlint:disable redundant_string_enum_value + +/// The installation-wide snapshot used by both receive and Settings. +public struct TextRulesPreference: Sendable, Codable, Equatable { + public enum Kind: String, CaseIterable, Sendable, Codable { + case publicChannel = "publicChannel" + case hashtagChannel = "hashtagChannel" + case privateChannel = "privateChannel" + case directMessage = "directMessage" + case room = "room" + } + + public struct Key: Hashable, Sendable, Codable { + public let radioID: UUID + public let conversationID: UUID + + public init(radioID: UUID, conversationID: UUID) { + self.radioID = radioID + self.conversationID = conversationID + } + } + + public struct Conversation: Identifiable, Sendable, Equatable { + public var id: Key { + key + } + + public let key: Key + public let kind: Kind + public let name: String + public let radioName: String + public let override: Override + + public init(key: Key, kind: Kind, name: String, radioName: String, override: Override) { + self.key = key + self.kind = kind + self.name = name + self.radioName = radioName + self.override = override + } + } + + public enum Selection: Sendable, Codable, Equatable { + case off + case all + case fixed(Set) + + private enum CodingKeys: String, CodingKey { + case off = "off" + case all = "all" + case fixed = "fixed" + } + + public var isOn: Bool { + self != .off + } + + public func includes(_ key: Key) -> Bool { + switch self { + case .off: false + case .all: true + case let .fixed(keys): keys.contains(key) + } + } + } + + public enum Override: String, CaseIterable, Sendable, Codable { + case inherit = "inherit" + case on = "on" + case off = "off" + } + + public struct Effective: Sendable, Equatable { + public enum Source: Sendable, Equatable { + case type + case fixedExclusion + case explicit + } + + public let isOn: Bool + public let source: Source + } + + public struct Rule: Identifiable, Sendable, Codable, Equatable { + public enum LookIn: String, CaseIterable, Sendable, Codable { + case message = "message" + case sender = "sender" + case messageOrSender = "messageOrSender" + } + + public enum Match: String, CaseIterable, Sendable, Codable { + case contains = "contains" + case wholeField = "wholeField" + } + + public let id: UUID + public let phrase: String + public let lookIn: LookIn + public let match: Match + + public var isValid: Bool { + !phrase.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + public init(id: UUID = UUID(), phrase: String, lookIn: LookIn, match: Match) { + self.id = id + self.phrase = phrase + self.lookIn = lookIn + self.match = match + } + } + + public struct RuleMatch: Sendable, Codable, Equatable { + public struct Highlight: Sendable, Codable, Equatable { + let location: Int + let length: Int + + init(_ range: NSRange) { + location = range.location + length = range.length + } + + public func range(in text: String) -> Range? { + Range(NSRange(location: location, length: length), in: text) + } + } + + public let rule: Rule + public let bodyHighlights: [Highlight] + public let senderHighlights: [Highlight] + } + + private static let comparisonLocale = Locale(identifier: "en_US_POSIX") + + public private(set) var rules: [Rule] = [] + private var selections: [Kind: Selection] = [ + .publicChannel: .all, + .hashtagChannel: .all, + .privateChannel: .off, + .directMessage: .off, + .room: .off + ] + + public init() {} + + public mutating func append(_ rule: Rule) { + rules.append(rule) + } + + public mutating func removeRule(id: UUID) { + rules.removeAll { $0.id == id } + } + + public mutating func setSelection(_ selection: Selection, for kind: Kind) { + selections[kind] = selection + } + + public func selection(for kind: Kind) -> Selection { + selections[kind] ?? .off + } + + public func effective(for kind: Kind, key: Key?, override: Override) -> Effective { + switch override { + case .on: + Effective(isOn: true, source: .explicit) + case .off: + Effective(isOn: false, source: .explicit) + case .inherit: + switch selection(for: kind) { + case .off: + Effective(isOn: false, source: .type) + case .all: + Effective(isOn: true, source: .type) + case let .fixed(keys): + if let key, keys.contains(key) { + Effective(isOn: true, source: .type) + } else { + Effective(isOn: false, source: .fixedExclusion) + } + } + } + } + + public func firstMatch(body: String?, sender: String?) -> RuleMatch? { + for rule in rules { + let bodyHighlights = rule.lookIn == .sender ? [] : Self.highlights(in: body, for: rule) + let senderHighlights = rule.lookIn == .message ? [] : Self.highlights(in: sender, for: rule) + if !bodyHighlights.isEmpty || !senderHighlights.isEmpty { + return RuleMatch(rule: rule, bodyHighlights: bodyHighlights, senderHighlights: senderHighlights) + } + } + return nil + } + + var isValid: Bool { + selections.count == Kind.allCases.count && + rules.allSatisfy(\.isValid) && + Set(rules.map(\.id)).count == rules.count + } + + private static func highlights(in field: String?, for rule: Rule) -> [RuleMatch.Highlight] { + guard let field, !field.isEmpty, !rule.phrase.isEmpty else { return [] } + let text = field as NSString + let entireField = NSRange(location: 0, length: text.length) + let options: String.CompareOptions = [.literal, .caseInsensitive] + if rule.match == .wholeField { + let equal = text.compare(rule.phrase, options: options, range: entireField, locale: comparisonLocale) + return equal == .orderedSame ? [RuleMatch.Highlight(entireField)] : [] + } + + var highlights: [RuleMatch.Highlight] = [] + var start = 0 + while start < text.length { + let searchRange = NSRange(location: start, length: text.length - start) + let match = text.range(of: rule.phrase, options: options, range: searchRange, locale: comparisonLocale) + guard match.location != NSNotFound else { break } + let highlight = RuleMatch.Highlight(text.rangeOfComposedCharacterSequences(for: match)) + if highlights.last != highlight { + highlights.append(highlight) + } + start = NSMaxRange(match) + } + return highlights + } +} + +// swiftlint:enable redundant_string_enum_value +// swiftformat:enable redundantRawValues + +public extension TextRulesPreference { + static func channelKind(isPublic: Bool, name: String) -> Kind { + if isPublic { return .publicChannel } + return name.hasPrefix("#") ? .hashtagChannel : .privateChannel + } +} diff --git a/MC1Services/Sources/MC1Services/Protocols/MessagePollingServiceProtocol.swift b/MC1Services/Sources/MC1Services/Protocols/MessagePollingServiceProtocol.swift index 9e67ee4e51..bbe2c70750 100644 --- a/MC1Services/Sources/MC1Services/Protocols/MessagePollingServiceProtocol.swift +++ b/MC1Services/Sources/MC1Services/Protocols/MessagePollingServiceProtocol.swift @@ -43,13 +43,13 @@ protocol MessagePollingServiceProtocol: Actor { // MARK: - Ingestion Handlers /// Install the handler invoked for each incoming direct message. - func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext) async -> Void) + func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void) /// Install the handler invoked for each incoming channel message. - func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext) async -> Void) + func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void) /// Install the handler invoked for each incoming signed room message. - func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) + func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ReceiveScope) async -> Void) /// Install the handler invoked for each incoming CLI response. func setCLIMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/ContactPersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/ContactPersisting.swift index c3ae8aa57e..220b02cdf4 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/ContactPersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/ContactPersisting.swift @@ -2,6 +2,23 @@ import Foundation /// Store operations for contact rows, contact mention tracking, and blocked senders. public protocol ContactPersisting: Actor { + func currentDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope) async throws -> ContactDTO? + + func materializeContactForDirectMessage( + from frame: ContactFrame, + receivedAt: Date, + scope: ReceiveScope + ) async throws -> ContactDTO? + + func touchDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope, at date: Date) async throws + + func updateContactAfterDirectMessage( + _ message: MessageDTO, + contact: ContactDTO, + scope: ReceiveScope, + isViewingContact: Bool + ) async throws -> ContactDTO? + // MARK: - Contact Operations /// Fetch all confirmed contacts for a device @@ -103,14 +120,8 @@ public protocol ContactPersisting: Actor { skippingPublicKeys: @Sendable () -> Set ) async throws -> [UUID] - /// Deletes the contact only when no messages reference it. Insert-only - /// rollback of a mid-sync radio delete: prefer an orphan contact over a - /// cascade that wipes a concurrent DM. Implementations that share a - /// ModelActor with message storage must keep probe and delete in one - /// isolation region with no suspension between them. - /// - /// PendingSend and Reaction cascade with their Message rows on - /// `deleteContact`, so a Message probe is sufficient. + /// Deletes a Contact only when no message or review entry references it. + /// Check references and delete without suspension so a concurrent DM cannot be cascaded. func deleteContactIfUnreferenced(id: UUID) async throws /// Links direct messages stored before their contact row existed. Channel @@ -244,3 +255,28 @@ public extension ContactPersisting where Self: MessagePersisting { [:] } } + +public extension ContactPersisting { + func currentDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope) async throws -> ContactDTO? { + nil + } + + func materializeContactForDirectMessage( + from frame: ContactFrame, + receivedAt: Date, + scope: ReceiveScope + ) async throws -> ContactDTO? { + nil + } + + func touchDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope, at date: Date) async throws {} + + func updateContactAfterDirectMessage( + _ message: MessageDTO, + contact: ContactDTO, + scope: ReceiveScope, + isViewingContact: Bool + ) async throws -> ContactDTO? { + nil + } +} diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/DevicePersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/DevicePersisting.swift index b9a94c7bc3..0a07efac53 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/DevicePersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/DevicePersisting.swift @@ -1,5 +1,4 @@ import Foundation -import MeshCore /// Store operations for device rows. public protocol DevicePersisting: Actor { @@ -16,23 +15,6 @@ public protocol DevicePersisting: Actor { /// Save or update a device func saveDevice(_ dto: DeviceDTO) async throws - func updateDeviceNodeName(radioID: UUID, name: String) async throws - func updateDeviceCoordinates(radioID: UUID, latitude: Double, longitude: Double) async throws - func updateDeviceRadio( - radioID: UUID, - frequency: UInt32, - bandwidth: UInt32, - spreadingFactor: UInt8, - codingRate: UInt8, - appliedRadioPresetID: String? - ) async throws - func updateDeviceTxPower(radioID: UUID, txPower: Int8) async throws - func updateDeviceOtherParams(radioID: UUID, intent: OtherParamsIntent) async throws - /// Copies one refresh onto the existing row, preserving Device ID, Radio ID, and local metadata. - /// A missing row throws and is not inserted. - func updateDeviceObservation(radioID: UUID, mapped: DeviceDTO) async throws - func updateDeviceClientRepeat(radioID: UUID, enabled: Bool) async throws - func updateDevicePathHashMode(radioID: UUID, mode: UInt8) async throws - func updateDeviceAutoAdd(radioID: UUID, config: UInt8, maxHops: UInt8) async throws - func updateDeviceDefaultFloodScopeName(radioID: UUID, name: String?) async throws + /// Patches only OCV fields on an existing row in one actor turn. + func updateDeviceOCVSettings(id: UUID, preset: String, customArray: String?) async throws -> DeviceDTO? } diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/HeardRepeatPersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/HeardRepeatPersisting.swift index c69bf93362..3f9f508668 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/HeardRepeatPersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/HeardRepeatPersisting.swift @@ -15,9 +15,6 @@ public protocol HeardRepeatPersisting: Actor { /// Fetch all repeats for a message func fetchMessageRepeats(messageID: UUID) async throws -> [MessageRepeatDTO] - /// Delete all repeats for a message - func deleteMessageRepeats(messageID: UUID) async throws - /// Check if a repeat exists for the given RX log entry func messageRepeatExists(rxLogEntryID: UUID) async throws -> Bool @@ -36,10 +33,11 @@ public protocol HeardRepeatPersisting: Actor { rxLogEntryID: UUID? ) async throws -> IncomingPathAdmission - /// Records a sent-channel echo even when the hop list matches another echo. - /// The same RX entry is recorded once. Returns nil when that entry already exists. + /// Records every sent echo, including identical paths, while its timestamp matches. + /// Returns nil for a duplicate RX entry or an echo from a prior send. func admitSentEcho( messageID: UUID, + expectedTimestamp: UInt32, receivedAt: Date, pathNodes: Data, pathLength: UInt8, diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift index d2dba541cc..896bef9a4a 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift @@ -2,6 +2,26 @@ import Foundation /// Store operations for message rows and their pending-send queue entries. public protocol MessagePersisting: Actor { + // MARK: - Incoming Messages + + func captureReceiveScope(radioID: UUID, link: ReceiveScope.Lifetime) async throws -> ReceiveScope? + + func admitDirectMessage( + _ message: MessageDTO, + wireTextType: UInt8, + contact: ContactDTO?, + scope: ReceiveScope, + preference: TextRulesPreference? + ) async throws -> DirectMessageAdmission + + func shouldSuppressChannelMessage( + _ message: MessageDTO, + frame: ChannelMessage, + channel: ChannelDTO, + scope: ReceiveScope, + preference: TextRulesPreference? + ) async throws -> Bool + // MARK: - Message Operations /// Check if a message with this deduplication key already exists for the given radio. @@ -19,6 +39,15 @@ public protocol MessagePersisting: Actor { /// Save a new message func saveMessage(_ dto: MessageDTO) async throws + /// Atomically admits one outgoing reaction and its durable send work. + func admitOutgoingReaction(_ message: MessageDTO) async throws -> MessageDTO? + + /// Materializes the target badge only after this outgoing reaction is accepted. + func completeOutgoingReaction(messageID: UUID) async throws -> ReactionAdmission? + + /// Saves only while the captured receive scope and any resolved channel identity are current. + func saveReceivedChannelMessage(_ dto: MessageDTO, scope: ReceiveScope, conversationID: UUID?) async throws -> Bool + /// Fetch a message by ID func fetchMessage(id: UUID) async throws -> MessageDTO? @@ -132,8 +161,16 @@ public protocol MessagePersisting: Actor { /// Update message timestamp (for resending) func updateMessageTimestamp(id: UUID, timestamp: UInt32) async throws - /// Update heard repeats count - func updateMessageHeardRepeats(id: UUID, heardRepeats: Int) async throws + /// Stores a direct-message timestamp immediately before its command. + /// A `.delivered` row becomes `.pending`, and the previous timestamp is returned for rollback. + func commitOutgoingDirectMessageTimestamp(id: UUID, timestamp: UInt32) async throws -> UInt32? + + /// Puts a delivered direct message back after a rejected command. + /// Writes only while the row is still `.pending`. A row already `.delivered` is left unchanged. + func restoreUnacceptedDeliveredDirectMessage(id: UUID, timestamp: UInt32) async throws -> Bool + + /// Updates a new channel send's timestamp and clears prior echo evidence in one turn. + func prepareChannelMessageResend(id: UUID, timestamp: UInt32) async throws /// Mark a message as read func markMessageAsRead(id: UUID) async throws @@ -157,6 +194,12 @@ public protocol MessagePersisting: Actor { /// Returns the assigned sequence number. func insertPendingSendAssigningSequence(_ dto: PendingSendDTO) async throws -> Int + /// Atomically hands an accepted DM to durable ACK tracking, only while its original queue row remains current. + func savePendingAcknowledgement(_ dto: PendingSendDTO, replacingPendingSendID: UUID?, markSent: Bool) async throws -> Bool + + /// Resolves only this durable ACK owner; a replacement retry row must remain untouched. + func resolvePendingAcknowledgement(id: UUID, expectedDeadline: Date?, status: MessageStatus, ackCode: UInt32?, roundTripTime: UInt32?) async throws -> Bool + /// Fetch all pending sends for a given radio, ordered by sequence ascending. func fetchPendingSends(radioID: UUID) async throws -> [PendingSendDTO] @@ -171,12 +214,28 @@ public protocol MessagePersisting: Actor { /// `messageID` is globally unique. func hasPendingSend(messageID: UUID) async throws -> Bool - /// Increments the `attemptCount` for the `PendingSend` row matching - /// `messageID`. Returns the new count, or `nil` if no row matched. - /// Throws on SwiftData read/write failure; callers must treat a thrown - /// error as transient (park + retry) and `nil` as terminal (deleted row). + /// Atomically restores eligible unsent DMs and increments the queued row's attempt count. + /// Returns its ID and new count, or nil if none remains; callers park and retry persistence errors. @discardableResult - func incrementPendingSendAttemptCount(messageID: UUID) async throws -> Int? + func preparePendingSendAttempt(messageID: UUID) async throws -> (pendingSendID: UUID, attemptCount: Int)? + + /// Next attempt byte while this row is still queued work. Nil when the id is gone or already an ACK owner. + func pendingSendWireAttempt(id: UUID) async throws -> UInt8? + + /// Records the next attempt byte only while this id is still queued work. + func setPendingSendWireAttempt(id: UUID, to next: UInt8) async throws -> Bool + + /// Queued direct messages that already handed attempt bytes to the radio. + /// The service hashes acknowledgement codes from these fields. + func queuedDirectMessageWireAttempts() async throws -> [QueuedDirectMessageWireAttempt] + + /// Marks this queued direct message delivered and deletes its row. + /// Skips a channel message, a row that already has a deadline, and a message already delivered. + func deliverQueuedDirectMessage( + pendingSendID: UUID, + ackCode: UInt32, + roundTripTime: UInt32? + ) async throws -> MessageDTO? } // MARK: - Default Parameter Values @@ -187,10 +246,71 @@ extension MessagePersisting { try await updateMessageAck(id: id, ackCode: ackCode, status: status, roundTripTime: nil) } + func restoreUnacceptedDeliveredDirectMessage(id: UUID, timestamp: UInt32) async throws -> Bool { + false + } + /// Default no-op for lightweight stubs. Concrete stores override; the method /// must be `async throws` on the store so overload resolution does not pick /// this empty default over the real implementation. func newestUnreadIncomingMessage(contactID: UUID) async throws -> MessageDTO? { nil } + + func pendingSendWireAttempt(id: UUID) async throws -> UInt8? { + nil + } + + func queuedDirectMessageWireAttempts() async throws -> [QueuedDirectMessageWireAttempt] { + [] + } + + func deliverQueuedDirectMessage( + pendingSendID: UUID, + ackCode: UInt32, + roundTripTime: UInt32? + ) async throws -> MessageDTO? { + nil + } +} + +public extension MessagePersisting { + func admitOutgoingReaction(_ message: MessageDTO) async throws -> MessageDTO? { + nil + } + + func completeOutgoingReaction(messageID: UUID) async throws -> ReactionAdmission? { + nil + } + + func saveReceivedChannelMessage(_ dto: MessageDTO, scope: ReceiveScope, conversationID: UUID?) async throws -> Bool { + guard scope.isCurrent, scope.radioID == dto.radioID else { return false } + try await saveMessage(dto) + return true + } + + func captureReceiveScope(radioID: UUID, link: ReceiveScope.Lifetime) async throws -> ReceiveScope? { + guard link.isCurrent else { return nil } + return ReceiveScope(radioID: radioID, link: link, partition: .init()) + } + + func admitDirectMessage( + _ message: MessageDTO, + wireTextType: UInt8, + contact: ContactDTO?, + scope: ReceiveScope, + preference: TextRulesPreference? + ) async throws -> DirectMessageAdmission { + .discarded + } + + func shouldSuppressChannelMessage( + _ message: MessageDTO, + frame: ChannelMessage, + channel: ChannelDTO, + scope: ReceiveScope, + preference: TextRulesPreference? + ) async throws -> Bool { + false + } } diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/NodeSnapshotPersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/NodeSnapshotPersisting.swift index 6581245887..8e793a2828 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/NodeSnapshotPersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/NodeSnapshotPersisting.swift @@ -53,6 +53,21 @@ public protocol NodeSnapshotPersisting: Actor { /// Delete snapshots older than the given date func deleteOldNodeStatusSnapshots(olderThan date: Date) async throws + + /// Checks Device identity before saving so a delayed write cannot recreate deleted history. + func recordSelfTelemetrySnapshot( + deviceID: UUID, + radioID: UUID, + nodePublicKey: Data, + telemetry: [TelemetrySnapshotEntry]?, + location: NodeLocationFix? + ) async throws -> UUID? + + /// Self telemetry captured for one radio under one public key, oldest first. + func fetchSelfTelemetrySnapshots( + radioID: UUID, + nodePublicKey: Data + ) async throws -> [NodeStatusSnapshotDTO] } public extension NodeSnapshotPersisting { diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/ReactionPersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/ReactionPersisting.swift index 43857736ca..7de05aa8a4 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/ReactionPersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/ReactionPersisting.swift @@ -2,6 +2,11 @@ import Foundation /// Store operations for message reactions and their summary cache. public protocol ReactionPersisting: Actor { + func admitDirectMessageReaction( + _ reaction: ReactionDTO, + contact: ContactDTO, + scope: ReceiveScope + ) async throws -> ReactionAdmission? /// Fetch reactions for a message, ordered by most recent first func fetchReactions(for messageID: UUID, limit: Int) async throws -> [ReactionDTO] @@ -30,3 +35,13 @@ extension ReactionPersisting { try await fetchReactions(for: messageID, limit: ReactionParser.summaryRowLimit) } } + +public extension ReactionPersisting { + func admitDirectMessageReaction( + _ reaction: ReactionDTO, + contact: ContactDTO, + scope: ReceiveScope + ) async throws -> ReactionAdmission? { + nil + } +} diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/RoomPersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/RoomPersisting.swift index 977cbf00a1..96d491cb0f 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/RoomPersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/RoomPersisting.swift @@ -49,6 +49,8 @@ public protocol RoomPersisting: Actor { // MARK: - Room Message Operations + func hasRecentlyBlockedMessages(radioID: UUID, conversationID: UUID) async throws -> Bool + /// Save a new room message func saveRoomMessage(_ dto: RoomMessageDTO) async throws @@ -86,6 +88,12 @@ public protocol RoomPersisting: Actor { // MARK: - Default Parameter Values +public extension RoomPersisting { + func hasRecentlyBlockedMessages(radioID: UUID, conversationID: UUID) async throws -> Bool { + false + } +} + extension RoomPersisting { /// Update room activity with nil sync timestamp (sort date only) func updateRoomActivity(_ sessionID: UUID) async throws { diff --git a/MC1Services/Sources/MC1Services/ServiceContainer.swift b/MC1Services/Sources/MC1Services/ServiceContainer.swift index bc92654b99..fd55a18070 100644 --- a/MC1Services/Sources/MC1Services/ServiceContainer.swift +++ b/MC1Services/Sources/MC1Services/ServiceContainer.swift @@ -2,68 +2,8 @@ import Foundation import MeshCore import SwiftData -/// Dependency injection container for MC1Services. -/// -/// `ServiceContainer` creates and manages all services needed by the MeshCore One app, -/// handling the dependency graph between services. It provides a single point of -/// initialization for the service layer. -/// -/// ## Lifetime -/// -/// The container is per-connection, not a singleton: `ConnectionManager` builds a -/// fresh `ServiceContainer` (and a fresh session) on every connection in -/// `buildServicesAndSaveDevice`, and tears it down via `tearDown()` on disconnect -/// before nilling its reference. The `PersistenceStore` is injected and -/// process-lifetime on `ConnectionManager`; it is not minted here. Anything -/// else that must survive reconnects (for example detected platform or -/// last-clean-sync state) lives on `ConnectionManager`, not here. `init` also -/// reassigns the `DebugLogBuffer.shared` global to this container's buffer, -/// so a stale container's services must not keep running past teardown. -/// -/// ## Usage -/// -/// ```swift -/// // Create container with session and model container -/// let container = ServiceContainer( -/// session: meshCoreSession, -/// dataStore: persistenceStore, -/// radioID: radioUUID -/// ) -/// -/// // Start event monitoring when device is connected -/// await container.startEventMonitoring(radioID: radioUUID) -/// ``` -/// -/// ## Dependency injection -/// -/// `init` constructs services in dependency order, so a fully wired container -/// exists as soon as `init` returns. Stable one-to-one dependencies are -/// constructor-injected. One-to-many notifications flow through typed event -/// streams (`SyncDataEvent`, `AdvertisementEvent`, `MessageStatusEvent`, -/// `HeardRepeatEvent`, `RemoteNodeEvent`, `RoomServerEvent`, -/// `ContactServiceEvent`, and the RX log entry stream), every one of which is -/// finished in `tearDown()` so consumer loops cannot outlive the container. -/// -/// Setter injection survives only where ordering or a reference cycle forces it: -/// - `MessagePollingService` ingestion handlers: installed by -/// `SyncCoordinator.wireMessageHandlers` before event monitoring starts, -/// cleared in `tearDown()`. -/// - `SyncCoordinator.setSyncActivityCallbacks`: installed by -/// `ConnectionUIState.wireCallbacks` before `onConnectionEstablished` so the -/// count-paired started/ended events keep the sync pill accurate. -/// - `SyncCoordinator.setCleanChannelSyncCallback` / -/// `setChannelSyncAttemptedCallback`: installed by -/// `ConnectionManager.wireCleanChannelSyncCallback` at container build. -/// - `NotificationService` action closures and `getBadgeCount`: installed by -/// `AppState` and `NavigationCoordinator` when notification handling is -/// configured. The action closures are cleared in `tearDown()` because they -/// capture `NotificationActionHandler`, which strong-holds the service back. -/// - `ChannelService.setSlotOccupantChangedHandler` and -/// `DeviceService.setDeviceUpdateCallback`: installed by -/// `AppState.wireServicesIfConnected` per connection. -/// - `NodeConfigService.setOnPostIdentityImport`: installed by -/// `ConnectionManager.buildServicesAndSaveDevice`; a cycle-forced upward -/// call into `ConnectionManager`. +/// Owns the service graph for one connection; retirement joins `tearDown()` before replacement. +/// `ConnectionManager` injects its process-lifetime `PersistenceStore` so reconnects share one store. @Observable @MainActor public final class ServiceContainer { @@ -74,6 +14,7 @@ public final class ServiceContainer { /// The persistence store for SwiftData operations public let dataStore: PersistenceStore + let receiveLifetime = ReceiveScope.Lifetime() /// Persists inline-image aspect ratios for chat link previews. Built early /// because downstream caches and the prefetcher depend on it. @@ -154,18 +95,12 @@ public final class ServiceContainer { // MARK: - Chat Send Queue - /// Service-layer outbound chat queue. Replaces the per-view-model - /// `dmSendQueue` / `channelSendQueue` instances. Hydrates from - /// `PendingSend` on construction; drain gated on `ConnectionManager` - /// transport state via `BLETransportOpenedSignal`. - /// - /// Constructed eagerly in `ServiceContainer.init` because `radioID` - /// is known at container-build time (`buildServicesAndSaveDevice` - /// resolves the device record before instantiating the container). - /// Eager construction closes the visibility window where the - /// container exists but the service is `nil`. + /// Hydrates this Radio ID's `PendingSend` rows during connection setup. + /// Connection-state events wake parked sends when the connection becomes ready. public let chatSendQueueService: ChatSendQueueService + let plainTextSendGate: PlainTextSendGate + // MARK: - Notification Actions /// Executes the multi-service transactions behind notification actions @@ -194,6 +129,18 @@ public final class ServiceContainer { } private var eventMonitoringState: EventMonitoringState = .stopped + private var eventMonitoringStartTask: Task? + private var eventMonitoringStopTask: Task? + private var tearDownTask: Task? + private var isTornDown = false + + public var isAcceptingRuntimeWork: Bool { + !isTornDown + } + + #if DEBUG + var testEventMonitoringStartHandler: (@MainActor () async -> Void)? + #endif /// Whether service event listeners are active or currently starting. var isEventMonitoringActive: Bool { @@ -202,30 +149,20 @@ public final class ServiceContainer { // MARK: - Initialization - /// Creates a new service container. - /// - /// - Parameters: - /// - session: The MeshCoreSession for device communication - /// - dataStore: Process-lifetime persistence store. Injected by - /// `ConnectionManager`; the container does not mint its own. - /// - radioID: The connected device's radio ID. Used to scope the - /// chat send queue's pending-send rows so two radios cannot share - /// drain state across reconnects. - /// - appStateProvider: Optional provider for app foreground/background state - /// - connectionStateEvents: Optional broadcaster of connection-state - /// changes. When provided, the chat send queue observes it to wake - /// parked drains on each disconnected-to-connected edge. - /// - initialConnectionState: The connection state at container build - /// time. Connect paths reach `.connected` before constructing the - /// container, so the queue's edge detection treats an - /// already-connected initial value as a fired edge. + /// Constructs the connection's services around the shared store and resolved Radio ID. + /// An initially ready connection or a later ready event wakes parked sends. init( session: MeshCoreSession, dataStore: PersistenceStore, radioID: UUID, appStateProvider: AppStateProvider? = nil, connectionStateEvents: EventBroadcaster? = nil, - initialConnectionState: DeviceConnectionState = .disconnected + initialConnectionState: DeviceConnectionState = .disconnected, + radioWiFiState: RadioWiFiState? = nil, + notificationService suppliedNotificationService: NotificationService? = nil, + ackEvents: AsyncStream? = nil, + messageConfig: MessageServiceConfig = .default, + textRulesPreference: @escaping @Sendable () async -> TextRulesPreference? = { nil } ) { self.session = session self.appStateProvider = appStateProvider @@ -234,7 +171,7 @@ public final class ServiceContainer { // Independent services (no dependencies) keychainService = KeychainService() - notificationService = NotificationService() + notificationService = suppliedNotificationService ?? NotificationService() syncCoordinator = SyncCoordinator() // Core services, constructed so every dependency exists before its consumer @@ -249,7 +186,10 @@ public final class ServiceContainer { session: session, dataStore: dataStore, keychainService: keychainService, - contactRadioOwner: contactRadioOwner + contactRadioOwner: contactRadioOwner, + textRulesPreference: textRulesPreference, + receiveLifetime: receiveLifetime, + radioID: radioID ) let cleanupCoordinator = ContactCleanupCoordinator( dataStore: dataStore, @@ -265,25 +205,38 @@ public final class ServiceContainer { cleanupCoordinator: cleanupCoordinator ) contactRadioOwner.bind(contactService) + let plainTextSendGate = PlainTextSendGate() + self.plainTextSendGate = plainTextSendGate messageService = MessageService( session: session, dataStore: dataStore, - contactService: contactService + contactService: contactService, + config: messageConfig, + ackEvents: ackEvents, + dmSendBudget: { DMSendBudget.current() }, + plainTextSendGate: plainTextSendGate ) channelService = ChannelService( session: session, dataStore: dataStore, rxLogService: rxLogService ) - settingsService = SettingsService(session: session) + settingsService = SettingsService(session: session, radioWiFiState: radioWiFiState ?? RadioWiFiState(radioID: radioID)) deviceService = DeviceService(dataStore: dataStore) advertisementService = AdvertisementService( session: session, dataStore: dataStore, contactService: contactService, - appStateProvider: appStateProvider + appStateProvider: appStateProvider, + notificationService: self.notificationService + ) + messagePollingService = MessagePollingService( + session: session, + dataStore: dataStore, + radioID: radioID, + textRulesPreference: textRulesPreference, + receiveLifetime: receiveLifetime ) - messagePollingService = MessagePollingService(session: session, dataStore: dataStore) binaryProtocolService = BinaryProtocolService( session: session, radioID: radioID, @@ -316,7 +269,10 @@ public final class ServiceContainer { session: session, remoteNodeService: remoteNodeService, dataStore: dataStore, - radioID: radioID + radioID: radioID, + plainTextSendGate: plainTextSendGate, + textRulesPreference: textRulesPreference, + receiveLifetime: receiveLifetime ) chatSendQueueService = ChatSendQueueService( @@ -324,7 +280,8 @@ public final class ServiceContainer { dataStore: dataStore, messageService: messageService, channelService: channelService, - reactionService: reactionService + reactionService: reactionService, + plainTextSendGate: plainTextSendGate ) notificationActionHandler = NotificationActionHandler( dataStore: dataStore, @@ -357,28 +314,58 @@ public final class ServiceContainer { enableAutoFetch: Bool = true, enableAdvertisementMonitoring: Bool = true ) async { - // Claim synchronously before the awaits below so an overlapping caller - // (SyncCoordinator.onConnectionEstablished racing the foreground health - // check) cannot pass the guard and double-start every monitor. + guard !isTornDown else { return } + if let eventMonitoringStartTask { + await eventMonitoringStartTask.value + return + } guard eventMonitoringState == .stopped else { return } eventMonitoringState = .starting + let worker = Task { + await performEventMonitoringStart( + radioID: radioID, + enableAutoFetch: enableAutoFetch, + enableAdvertisementMonitoring: enableAdvertisementMonitoring + ) + } + eventMonitoringStartTask = worker + await worker.value + eventMonitoringStartTask = nil + } + private func performEventMonitoringStart( + radioID: UUID, + enableAutoFetch: Bool, + enableAdvertisementMonitoring: Bool + ) async { + guard eventMonitoringState == .starting else { return } await heardRepeatsService.configure(radioID: radioID) + #if DEBUG + await testEventMonitoringStartHandler?() + #endif + guard eventMonitoringState == .starting, !isTornDown else { return } // Start event monitoring for services that need it if enableAdvertisementMonitoring { await advertisementService.startEventMonitoring(radioID: radioID) + guard eventMonitoringState == .starting, !isTornDown else { return } } await rxLogService.startEventMonitoring(radioID: radioID) + guard eventMonitoringState == .starting, !isTornDown else { return } await messageService.startEventMonitoring() + guard eventMonitoringState == .starting, !isTornDown else { return } await messageService.startAckExpiryChecking() + guard eventMonitoringState == .starting, !isTornDown else { return } await remoteNodeService.startEventMonitoring() + guard eventMonitoringState == .starting, !isTornDown else { return } // Always start message event monitoring so handlers are ready for polled messages await messagePollingService.startMessageEventMonitoring(radioID: radioID) + guard eventMonitoringState == .starting, !isTornDown else { return } if enableAutoFetch { await messagePollingService.startAutoFetch(radioID: radioID) + guard eventMonitoringState == .starting, !isTornDown else { return } } // Prune debug logs on connection @@ -402,11 +389,23 @@ public final class ServiceContainer { /// /// Call this when disconnecting from a device. func stopEventMonitoring() async { - // Claimed synchronously, mirroring startEventMonitoring, so two teardown - // paths interleaving at the awaits below cannot double-stop. - guard eventMonitoringState == .active else { return } + if let eventMonitoringStopTask { + await eventMonitoringStopTask.value + return + } + guard eventMonitoringState == .active || eventMonitoringState == .starting else { return } eventMonitoringState = .stopping + let starting = eventMonitoringStartTask + let worker = Task { + await starting?.value + await performEventMonitoringStop() + } + eventMonitoringStopTask = worker + await worker.value + eventMonitoringStopTask = nil + } + private func performEventMonitoringStop() async { await advertisementService.stopEventMonitoring() await rxLogService.stopEventMonitoring() try? await dataStore.flushPendingRxLogEntries() @@ -418,7 +417,7 @@ public final class ServiceContainer { // reconnect within the same session or expire via `ackGiveUpWindow`. await messageService.stopAckExpiryChecking() await messagePollingService.stopMessageEventMonitoring() - // RemoteNodeService event monitoring is per-session, handled internally + await remoteNodeService.stopEventMonitoring() // Flush debug log buffer await debugLogBuffer.shutdown() @@ -430,7 +429,24 @@ public final class ServiceContainer { /// so the chat send queue drains. `stopEventMonitoring()` alone does not /// cover that. func tearDown() async { + receiveLifetime.retire() + isTornDown = true + if let tearDownTask { + await tearDownTask.value + return + } + let worker = Task { await performTearDown() } + tearDownTask = worker + await worker.value + } + + private func performTearDown() async { + await plainTextSendGate.invalidate() + await remoteNodeService.beginRetirement() + await messageService.retireInlineSends() + await messageService.waitForAcknowledgementSaves() await stopEventMonitoring() + await remoteNodeService.retire() // Break the retain cycles the wired handlers form. The message // closures and the discovery event task capture this container's @@ -464,13 +480,25 @@ public final class ServiceContainer { await chatSendQueueService.shutdown() } + func prepareForIdentityImport() async { + isTornDown = true + await plainTextSendGate.invalidate() + await messageService.retireInlineSends() + await remoteNodeService.retire() + await chatSendQueueService.shutdown() + await stopEventMonitoring() + await syncCoordinator.cancelDiscoveryEventMonitoring() + } + // MARK: - Convenience Methods /// Performs initial database warm-up. /// /// Call this early during app launch to avoid lazy initialization delays. func warmUp() async throws { + await messageService.captureAcknowledgementEvents() try await dataStore.warmUp() + try await messageService.restorePendingAcknowledgements(radioID: chatSendQueueService.radioID) } /// Resets all remote node session connections. diff --git a/MC1Services/Sources/MC1Services/Services/AccessoryPickerState+Attempt.swift b/MC1Services/Sources/MC1Services/Services/AccessoryPickerState+Attempt.swift new file mode 100644 index 0000000000..60d097c46e --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/AccessoryPickerState+Attempt.swift @@ -0,0 +1,11 @@ +import Foundation + +extension AccessoryPickerState { + struct Attempt { + let id: UUID + let presentedAt: Date + let filteredDiscovery: Bool + var hasPresented = false + var outcome: Outcome + } +} diff --git a/MC1Services/Sources/MC1Services/Services/AccessoryPickerState+Outcome.swift b/MC1Services/Sources/MC1Services/Services/AccessoryPickerState+Outcome.swift new file mode 100644 index 0000000000..6512620a0a --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/AccessoryPickerState+Outcome.swift @@ -0,0 +1,14 @@ +extension AccessoryPickerState { + enum Outcome: String { + case presented + case selected + case cancelled + case cancelledAfterSelection + case orphanedAfterCancellation + case pairingFailed + case pickerRestricted + case pickerAlreadyActive + case discoveryTimeout + case connectionFailed + } +} diff --git a/MC1Services/Sources/MC1Services/Services/AccessoryPickerState+SelectionDisposition.swift b/MC1Services/Sources/MC1Services/Services/AccessoryPickerState+SelectionDisposition.swift new file mode 100644 index 0000000000..ee7951e8dd --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/AccessoryPickerState+SelectionDisposition.swift @@ -0,0 +1,8 @@ +extension AccessoryPickerState { + enum SelectionDisposition { + case selected + case removeAccessory + case unclaimed + case ignored + } +} diff --git a/MC1Services/Sources/MC1Services/Services/AccessoryPickerState.swift b/MC1Services/Sources/MC1Services/Services/AccessoryPickerState.swift new file mode 100644 index 0000000000..6377c0a195 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/AccessoryPickerState.swift @@ -0,0 +1,171 @@ +import Foundation + +@MainActor +struct AccessoryPickerState { + private enum Phase { + case idle + case awaitingSelection(Attempt, CheckedContinuation) + case callerCancelled(Attempt) + case awaitingDismissal(Attempt, Settlement) + } + + private enum Settlement { + case selected + case failed + case cleanupRequested + } + + private var phase: Phase = .idle + + var attempt: Attempt? { + switch phase { + case .idle: nil + case let .awaitingSelection(attempt, _), let .callerCancelled(attempt), let .awaitingDismissal(attempt, _): attempt + } + } + + var isActive: Bool { + attempt != nil + } + + @discardableResult + mutating func begin( + id: UUID, + presentedAt: Date, + filteredDiscovery: Bool, + continuation: CheckedContinuation + ) -> Bool { + guard !isActive else { + continuation.resume(throwing: AccessorySetupKitError.pickerAlreadyActive) + return false + } + let attempt = Attempt(id: id, presentedAt: presentedAt, filteredDiscovery: filteredDiscovery, outcome: .presented) + phase = .awaitingSelection(attempt, continuation) + return true + } + + mutating func accessoryAdded(bluetoothID: UUID?) -> SelectionDisposition { + switch phase { + case .idle: + return .unclaimed + case let .awaitingSelection(attempt, continuation): + var attempt = attempt + attempt.outcome = .selected + phase = .awaitingDismissal(attempt, .selected) + if let bluetoothID { + continuation.resume(returning: bluetoothID) + } else { + continuation.resume(throwing: AccessorySetupKitError.noBluetoothIdentifier) + } + return .selected + case var .callerCancelled(attempt): + attempt.outcome = .orphanedAfterCancellation + phase = .awaitingDismissal(attempt, .cleanupRequested) + return .removeAccessory + case .awaitingDismissal: + return .ignored + } + } + + mutating func cancel(attemptID: UUID) { + guard attempt?.id == attemptID else { return } + switch phase { + case let .awaitingSelection(attempt, continuation): + var attempt = attempt + attempt.outcome = .cancelled + phase = .callerCancelled(attempt) + continuation.resume(throwing: CancellationError()) + case let .awaitingDismissal(pending, settlement): + var attempt = pending + switch settlement { + case .selected: + attempt.outcome = .cancelledAfterSelection + phase = .awaitingDismissal(attempt, .selected) + case .cleanupRequested: + break + case .failed: + attempt.outcome = .cancelled + phase = .callerCancelled(attempt) + } + case .idle, .callerCancelled: + break + } + } + + mutating func didPresent() { + guard var attempt else { return } + attempt.hasPresented = true + switch phase { + case let .awaitingSelection(_, continuation): + phase = .awaitingSelection(attempt, continuation) + case .callerCancelled: + phase = .callerCancelled(attempt) + case let .awaitingDismissal(_, settlement): + phase = .awaitingDismissal(attempt, settlement) + case .idle: + break + } + } + + mutating func fail(_ error: AccessorySetupKitError, attemptID: UUID) { + guard var attempt, attempt.id == attemptID else { return } + switch phase { + case .awaitingDismissal(_, .selected), .awaitingDismissal(_, .cleanupRequested): + return + default: + break + } + let (outcome, presentationRejected): (Outcome, Bool) = switch error { + case .pickerRestricted: (.pickerRestricted, true) + case .pickerAlreadyActive: (.pickerAlreadyActive, true) + case .discoveryTimeout: (.discoveryTimeout, false) + case .pairingFailed: (.pairingFailed, false) + case .pickerDismissed: (.cancelled, false) + default: (.connectionFailed, false) + } + attempt.outcome = outcome + let previousPhase = phase + if presentationRejected || !attempt.hasPresented { + phase = .idle + } else if case .callerCancelled = previousPhase { + phase = .callerCancelled(attempt) + } else { + phase = .awaitingDismissal(attempt, .failed) + } + if case let .awaitingSelection(_, continuation) = previousPhase { + continuation.resume(throwing: error) + } + } + + mutating func userCancelled(attemptID: UUID) { + guard var attempt, attempt.id == attemptID else { return } + attempt.outcome = .cancelled + switch phase { + case let .awaitingSelection(_, continuation): + phase = .awaitingSelection(attempt, continuation) + case .callerCancelled: + phase = .callerCancelled(attempt) + case .idle, .awaitingDismissal: + break + } + } + + @discardableResult + mutating func dismiss() -> Attempt? { + let dismissedAttempt = attempt + let previousPhase = phase + phase = .idle + if case let .awaitingSelection(_, continuation) = previousPhase { + continuation.resume(throwing: AccessorySetupKitError.pickerDismissed) + } + return dismissedAttempt + } + + mutating func invalidate() { + let previousPhase = phase + phase = .idle + if case let .awaitingSelection(_, continuation) = previousPhase { + continuation.resume(throwing: AccessorySetupKitError.sessionInvalidated) + } + } +} diff --git a/MC1Services/Sources/MC1Services/Services/AccessorySetupKitService.swift b/MC1Services/Sources/MC1Services/Services/AccessorySetupKitService.swift index 9ca1a47c03..3439c9a3ba 100644 --- a/MC1Services/Sources/MC1Services/Services/AccessorySetupKitService.swift +++ b/MC1Services/Sources/MC1Services/Services/AccessorySetupKitService.swift @@ -15,19 +15,7 @@ func accessorySetupKitService(_ service: AccessorySetupKitService, didFailPairingForAccessoryWithID bluetoothID: UUID) } - /// Manages AccessorySetupKit session for device discovery and pairing. - /// - /// AccessorySetupKit is Apple's modern framework for Bluetooth accessory setup. - /// Starting with iOS 26, only apps using AccessorySetupKit will be relaunched - /// for Bluetooth state restoration events. - /// - /// ## Usage - /// - /// ```swift - /// let accessoryService = AccessorySetupKitService() - /// try await accessoryService.activateSession() - /// let deviceUUID = try await accessoryService.showPicker() - /// ``` + /// Owns ASK session activation and native picker callbacks. @Observable @MainActor final class AccessorySetupKitService { @@ -44,30 +32,16 @@ /// Delegate for accessory state changes weak var delegate: AccessorySetupKitServiceDelegate? - /// Pending picker result continuation (for async/await bridge) - private var pickerContinuation: CheckedContinuation? + private var pickerState = AccessoryPickerState() /// Pending activation continuation private var activationContinuation: CheckedContinuation? - private var pickerPresentedAt: Date? - private var pickerOutcome = "cancelled" - - /// Set when `showPicker`'s awaiting Task is cancelled but the system picker - /// is still presented. ASK doesn't expose a programmatic dismiss surface - /// short of `session.invalidate()`, so the next `accessoryAdded` event from - /// a user-completed pairing has no caller — the flag instructs the event - /// handler to remove the orphaned accessory immediately. - private var pickerWasCancelled = false - /// Display items accumulated across `accessoryDiscovered` events and re-sent in full on /// each `updatePicker`. Keyed by the accessory, not `bluetoothIdentifier` (a discovery /// lacks one until it pairs); `AnyHashable` keeps the iOS 26.1 type off the property. private var discoveredDisplayItems: [AnyHashable: ASPickerDisplayItem] = [:] - /// Whether the active picker opted into filtered discovery; drives the dismissal log. - private var usedFilteredDiscovery = false - /// Product image rendered once per `showPicker` and reused by the discovery handler. private var currentProductImage: UIImage? @@ -77,25 +51,8 @@ init() {} - // MARK: - Continuation Safety - - /// Safely resume the picker continuation exactly once - /// Clears continuation BEFORE resuming to prevent double-resume race conditions - private func resumePickerContinuation(with result: Result) { - guard let continuation = pickerContinuation else { return } - pickerContinuation = nil // Clear BEFORE resuming - switch result { - case let .success(uuid): - continuation.resume(returning: uuid) - case let .failure(error): - continuation.resume(throwing: error) - } - } - // MARK: - Session Management - /// Activate the AccessorySetupKit session - /// Uses Apple's recommended closure pattern to avoid AsyncStream issues func activateSession() async throws { guard session == nil else { return } @@ -106,7 +63,7 @@ self.activationContinuation = continuation newSession.activate(on: .main) { [weak self] event in - guard let self else { return } + guard let self, session === newSession else { return } handleEvent(event) // Resume activation continuation only once @@ -136,23 +93,15 @@ logger.error("ASAccessorySession invalidated") isSessionActive = false pairedAccessories = [] - // Drop the dead session so the next activateSession() builds a fresh - // one. Keeping it would make every later activate() a silent no-op - // (its guard keys on session == nil) and leave pairing wedged until - // app relaunch. + // Release the invalidated session so the next activation can create a usable one. session = nil - pickerContinuation?.resume(throwing: AccessorySetupKitError.sessionInvalidated) - pickerContinuation = nil + pickerState.invalidate() + clearPickerDisplayItems() case .accessoryAdded: if let accessory = event.accessory { - if pickerWasCancelled { - pickerWasCancelled = false - // Set to "orphanedAfterCancellation" so the next pickerDidDismiss - // log doesn't read "selected" — without this, the success branch - // below would mark outcome as "selected" even though the awaiting - // Task was already cancelled. - pickerOutcome = "orphanedAfterCancellation" + switch pickerState.accessoryAdded(bluetoothID: accessory.bluetoothIdentifier) { + case .removeAccessory: logger.info("[ASK] Removing orphaned accessory after picker cancellation: \(accessory.displayName)") Task { [weak self] in guard let self else { return } @@ -162,13 +111,15 @@ logger.warning("[ASK] Failed to remove orphaned accessory: \(error.localizedDescription)") } } - // Skip the post-add `pairedAccessories` write — `removeAccessory`'s - // own write is the correct final state for the cancelled branch. return + case .ignored: + pairedAccessories = session?.accessories ?? [] + return + case .selected, .unclaimed: + break } pairedAccessories = session?.accessories ?? [] - pickerOutcome = "selected" logger.info("Accessory added: \(accessory.displayName)") logger.info( AccessorySetupKitLogFormatter.selectionMessage( @@ -177,12 +128,6 @@ elapsed: pickerElapsedTime ) ) - - if let bluetoothID = accessory.bluetoothIdentifier { - resumePickerContinuation(with: .success(bluetoothID)) - } else { - resumePickerContinuation(with: .failure(AccessorySetupKitError.noBluetoothIdentifier)) - } } case .accessoryRemoved: @@ -201,27 +146,25 @@ case .accessoryDiscovered: // Under filtered discovery (iOS 26.1+) the picker hands each match to us so we can // relabel it with the device's advertised name before it appears for selection. - if #available(iOS 26.1, *), usedFilteredDiscovery { + if #available(iOS 26.1, *), pickerState.attempt?.filteredDiscovery == true { handleDiscoveredAccessory(event.accessory) } case .pickerDidPresent: + pickerState.didPresent() logger.info("Picker presented") case .pickerDidDismiss: + let attempt = pickerState.dismiss() logger.info( AccessorySetupKitLogFormatter.dismissalMessage( - outcome: pickerOutcome, + outcome: attempt?.outcome.rawValue ?? "cancelled", pairedCount: pairedAccessories.count, - elapsed: pickerElapsedTime, - filteredDiscovery: usedFilteredDiscovery + elapsed: attempt.map { Date().timeIntervalSince($0.presentedAt) }, + filteredDiscovery: attempt?.filteredDiscovery ?? false ) ) - pickerPresentedAt = nil - pickerOutcome = "cancelled" - // Defense-in-depth: don't rely on `showPicker` to clear the flag. - pickerWasCancelled = false - resumePickerContinuation(with: .failure(AccessorySetupKitError.pickerDismissed)) + clearPickerDisplayItems() case .pickerSetupBridging: logger.info("Picker bridging...") @@ -231,7 +174,7 @@ case .pickerSetupFailed: if let error = event.error { - pickerOutcome = "pairingFailed" + pickerState.didPresent() logger.error("Pairing failed: \(error.localizedDescription)") if let accessory = event.accessory, @@ -252,7 +195,12 @@ } } - resumePickerContinuation(with: .failure(AccessorySetupKitError.pairingFailed(error.localizedDescription))) + if let attemptID = pickerState.attempt?.id { + pickerState.fail( + AccessorySetupKitError.pairingFailed(error.localizedDescription), + attemptID: attemptID + ) + } } case .pickerSetupRename: @@ -278,12 +226,12 @@ throw AccessorySetupKitError.sessionNotActive } - guard pickerContinuation == nil else { + guard !pickerState.isActive else { throw AccessorySetupKitError.pickerAlreadyActive } discoveredDisplayItems.removeAll() - usedFilteredDiscovery = false + var usedFilteredDiscovery = false if #available(iOS 26.1, *), AccessorySetupKitDiscoveryCriteria.usesFilteredDiscovery { let settings = session.pickerDisplaySettings ?? ASPickerDisplaySettings() @@ -299,9 +247,7 @@ let productImage = createGenericProductImage() currentProductImage = productImage let displayItems = makePickerDisplayItems(productImage: productImage) - pickerPresentedAt = Date() - pickerOutcome = "presented" - pickerWasCancelled = false + let attemptID = UUID() logger.info( """ [ASK] Presenting picker on iOS \(currentOSVersion), \ @@ -315,72 +261,68 @@ return try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { continuation in - self.pickerContinuation = continuation + guard !Task.isCancelled else { + continuation.resume(throwing: CancellationError()) + return + } + guard pickerState.begin( + id: attemptID, + presentedAt: Date(), + filteredDiscovery: usedFilteredDiscovery, + continuation: continuation + ) else { return } session.showPicker(for: displayItems) { [weak self] error in guard let self else { return } Task { @MainActor in - if let error = error as? ASError { - self.logger.error("Picker error: \(error.localizedDescription)") - - switch error.code { - case .pickerRestricted: - self.pickerOutcome = "pickerRestricted" - self.resumePickerContinuation(with: .failure(AccessorySetupKitError.pickerRestricted)) - case .pickerAlreadyActive: - self.pickerOutcome = "pickerAlreadyActive" - self.resumePickerContinuation(with: .failure(AccessorySetupKitError.pickerAlreadyActive)) - case .userCancelled: - self.pickerOutcome = "cancelled" - // User explicitly cancelled (error code 700) - not an error condition - // Will be handled by pickerDidDismiss event - return - case .discoveryTimeout: - self.pickerOutcome = "discoveryTimeout" - self.resumePickerContinuation(with: .failure(AccessorySetupKitError.discoveryTimeout)) - case .connectionFailed: - self.pickerOutcome = "connectionFailed" - self.resumePickerContinuation(with: .failure(AccessorySetupKitError.connectionFailed)) - default: - self.logger.error("Unexpected picker error code: \(error.code.rawValue)") - self.pickerOutcome = "connectionFailed" - self.resumePickerContinuation(with: .failure(AccessorySetupKitError.connectionFailed)) - } - } else if let error { - self.logger.error("Picker error: \(error.localizedDescription)") - self.pickerOutcome = "pairingFailed" - self.resumePickerContinuation(with: .failure(AccessorySetupKitError.pairingFailed(error.localizedDescription))) - } + self.handlePickerError(error, attemptID: attemptID) } } } } onCancel: { [weak self] in Task { @MainActor in - self?.handlePickerCancellation() + self?.handlePickerCancellation(attemptID: attemptID) } } } - /// Surfaces task cancellation as a `CancellationError` on the awaiting `showPicker`. - /// ASK doesn't expose a programmatic picker-dismiss surface short of - /// `session.invalidate()`, so the system picker may stay visible after this fires. - /// If the user completes pairing in the orphaned picker, `accessoryAdded` will - /// observe `pickerWasCancelled` and remove the orphaned bond. - @MainActor - private func handlePickerCancellation() { - pickerWasCancelled = true - // In Race-B (accessoryAdded ran first, then cancellation), the success branch - // already set pickerOutcome to "selected". Refine it so the dismissal log - // reflects what actually happened: a user-completed selection that the - // awaiting Task no longer cared about. - if pickerOutcome == "selected" { - pickerOutcome = "cancelledAfterSelection" - } - resumePickerContinuation(with: .failure(CancellationError())) + private func handlePickerCancellation(attemptID: UUID) { + guard pickerState.attempt?.id == attemptID else { return } + pickerState.cancel(attemptID: attemptID) logger.warning("[ASK] Picker cancelled programmatically; awaiting Task unwound") } + private func handlePickerError(_ error: Error?, attemptID: UUID) { + guard let error, pickerState.attempt?.id == attemptID else { return } + logger.error("Picker error: \(error.localizedDescription)") + let mappedError: AccessorySetupKitError + if let error = error as? ASError { + switch error.code { + case .pickerRestricted: + mappedError = .pickerRestricted + case .pickerAlreadyActive: + mappedError = .pickerAlreadyActive + case .userCancelled: + pickerState.userCancelled(attemptID: attemptID) + return + case .discoveryTimeout: + mappedError = .discoveryTimeout + case .connectionFailed: + mappedError = .connectionFailed + default: + logger.error("Unexpected picker error code: \(error.code.rawValue)") + mappedError = .connectionFailed + } + } else { + mappedError = .pairingFailed(error.localizedDescription) + } + pickerState.fail(mappedError, attemptID: attemptID) + if !pickerState.isActive { + clearPickerDisplayItems() + } + } + /// Remove an accessory from the system /// Note: iOS 26 shows a confirmation dialog to the user func removeAccessory(_ accessory: ASAccessory) async throws { @@ -419,8 +361,8 @@ /// Invalidate the session func invalidateSession() { - pickerContinuation?.resume(throwing: AccessorySetupKitError.sessionInvalidated) - pickerContinuation = nil + pickerState.invalidate() + clearPickerDisplayItems() activationContinuation?.resume(throwing: AccessorySetupKitError.sessionInvalidated) activationContinuation = nil session?.invalidate() @@ -437,7 +379,12 @@ } private var pickerElapsedTime: TimeInterval? { - pickerPresentedAt.map { Date().timeIntervalSince($0) } + pickerState.attempt.map { Date().timeIntervalSince($0.presentedAt) } + } + + private func clearPickerDisplayItems() { + discoveredDisplayItems.removeAll() + currentProductImage = nil } private func makePickerDisplayItems(productImage: UIImage) -> [ASPickerDisplayItem] { @@ -485,14 +432,7 @@ } } - /// Creates a generic product image for the ASK picker - /// Per Apple docs: Container size should be 180x120 points with transparent background - /// Padding added for visual balance in picker carousel (per WWDC24 guidance) - /// Note: Device type (T1000e, T-Deck, Heltec, etc.) cannot be determined - /// until after connection via CMD_DEVICE_QUERY. - /// - /// Alternative: Could use `.withRenderingMode(.alwaysTemplate)` with `.label` color - /// for better automatic dark mode adaptation, but explicit blue tint is acceptable. + /// Uses a generic image because the radio model is unknown until CMD_DEVICE_QUERY. private func createGenericProductImage() -> UIImage { let size = CGSize(width: 180, height: 120) let renderer = UIGraphicsImageRenderer(size: size) @@ -503,7 +443,6 @@ context.fill(CGRect(origin: .zero, size: size)) // Draw centered SF Symbol with padding for visual balance - // Smaller point size (50 vs 60) creates breathing room in carousel let config = UIImage.SymbolConfiguration(pointSize: 50, weight: .regular) guard let symbol = UIImage(systemName: "antenna.radiowaves.left.and.right", withConfiguration: config)? .withTintColor(.systemBlue, renderingMode: .alwaysOriginal) else { return } diff --git a/MC1Services/Sources/MC1Services/Services/AckCodeBuilder.swift b/MC1Services/Sources/MC1Services/Services/AckCodeBuilder.swift index aff48310de..9423860247 100644 --- a/MC1Services/Sources/MC1Services/Services/AckCodeBuilder.swift +++ b/MC1Services/Sources/MC1Services/Services/AckCodeBuilder.swift @@ -4,39 +4,15 @@ import Foundation private let attemptMask: UInt8 = 0x03 private let ackCodeByteCount = 4 -/// Computes the expected ACK CRC for an outgoing direct message, mirroring -/// firmware `BaseChatMesh::sendMessage`'s derivation: -/// -/// sha256( LE32(timestamp) || byte(attempt & 0x03) || text || pubkey )[0..3] -/// -/// Used to populate `pendingAcks` *before* the send round-trip so the -/// persistent ACK listener cannot race ahead of `trackPendingAck`. -/// -/// # Firmware contract invariants -/// -/// - **Recipient is not in the hash.** Same sender + same text + same UInt32 -/// timestamp + same `attempt & 0x03` produces an identical ACK code across -/// *every* contact. Currently low-risk because regular DMs are serialized -/// through a per-radioID `dmQueue` (`SendQueue`), so -/// two regular DMs cannot complete in the same wall-clock second on one -/// radio; the reaction path bypasses that queue via the single-shot send, -/// but each reaction carries a per-target message-hash discriminator. Any -/// future feature that dispatches identical-text sends in parallel (bulk -/// send, broadcast-to-many, scripted sends, or any pipelined DM path that -/// removes the serialized `dmQueue` guarantee) must either serialize with -/// ≥1s spacing or replace `pendingAcks`'s ackCode lookup with a -/// `[Data: Set]` index in `MessageService.handleAcknowledgement`. -/// - **Attempt index is masked to two bits.** Firmware hashes `attempt & 0x03`, -/// so attempt 4 reuses attempt 0's code. This is benign for delivery -/// detection: a single message accumulates its attempt codes in a `Set` -/// (`pendingAcks` `ackCodes`), so the wrap is a no-op re-add and any returned -/// ACK still matches the right message. Firmware deliberately supports -/// `attempt > 3` in `composeMsgPacket`, appending the full attempt byte after -/// the hash so `packet_hash` stays unique. `expectedAck` allows `attempt < 5` -/// (4 direct + 1 flood); `MessageServiceConfig` keeps `maxAttempts <= 5`. -/// Cross-*message* collision is unaffected by the wrap and stays mitigated by -/// the per-radioID `dmQueue` serialization. +/// Matches `BaseChatMesh::composeMsgPacket` so ACKs can be tracked before the send returns. +/// Hash input is LE32(timestamp), attempt & 0x03, UTF-8 text, then sender public key. +/// The recipient is excluded, so identical inputs can share an ACK code across contacts. +/// Attempts 4...7 reuse codes 0...3; firmware appends the full attempt byte after the text +/// to distinguish packet hashes, while `PendingAck.ackCodes` retains each attempt's code. enum AckCodeBuilder { + /// Exclusive upper bound for a DM attempt byte. Attempts 0.. Data { precondition( - attempt < 5, - "MessageServiceConfig caps maxAttempts at 5 (4 direct + 1 flood); attempt \(attempt) exceeds the index range and would over-wrap the & 0x03 ACK mask" + attempt < attemptCount, + "DM attempt bytes run 0..<\(attemptCount); attempt \(attempt) exceeds the index range and would over-wrap the & 0x03 ACK mask" ) var input = Data() var le = timestamp.littleEndian diff --git a/MC1Services/Sources/MC1Services/Services/AdvertisementEvent.swift b/MC1Services/Sources/MC1Services/Services/AdvertisementEvent.swift index 8399d8fe5a..d1d8a900e4 100644 --- a/MC1Services/Sources/MC1Services/Services/AdvertisementEvent.swift +++ b/MC1Services/Sources/MC1Services/Services/AdvertisementEvent.swift @@ -11,7 +11,7 @@ import MeshCore public enum AdvertisementEvent: Sendable { /// A contact or discovered node was created or updated; observers should /// reload contact lists. - case contactUpdated + case contactUpdated(contact: ContactDTO? = nil, scope: ReceiveScope? = nil) /// Adopted orphan DMs created or updated a conversation row; observers must /// refresh the conversation list (mirrors `SyncDataEvent.conversationsChanged`). case conversationsChanged diff --git a/MC1Services/Sources/MC1Services/Services/AdvertisementService+DeltaSync.swift b/MC1Services/Sources/MC1Services/Services/AdvertisementService+DeltaSync.swift index 2e69735b5d..2ae11b2cff 100644 --- a/MC1Services/Sources/MC1Services/Services/AdvertisementService+DeltaSync.swift +++ b/MC1Services/Sources/MC1Services/Services/AdvertisementService+DeltaSync.swift @@ -32,15 +32,7 @@ extension AdvertisementService { return } - guard !Task.isCancelled else { - finishRound(generation: generation) - return - } - guard !isSyncingContacts else { - finishRound(generation: generation) - return - } - guard await isInForeground() else { + guard !Task.isCancelled, !isSyncingContacts, await isInForeground() else { finishRound(generation: generation) return } @@ -192,7 +184,7 @@ extension AdvertisementService { // Adopt against every drained key that now has a row — not only // insertedKeysForNotify — so a snapshot failure still links orphan DMs. let adoptedContactIDs = await adoptOrphanedMessages(for: drained, radioID: radioID) - eventBroadcaster.yield(.contactUpdated) + eventBroadcaster.yield(.contactUpdated()) // A non-nil lastMessageDate after adoption is a new/updated conversation // row; contactsVersion alone does not reload the mounted chat list. The // adopted DMs never notified at receipt (no contact then), so hand the @@ -222,8 +214,7 @@ extension AdvertisementService { /// Re-arms after a busy outcome with a short backoff so performResync-style /// claim holds do not spin at zero interval. private func scheduleBusyRetry() { - guard deltaSyncTask == nil else { return } - guard hasPendingDeltaSyncWork else { return } + guard deltaSyncTask == nil, hasPendingDeltaSyncWork else { return } deltaSyncGeneration &+= 1 let generation = deltaSyncGeneration let fireAt = ContinuousClock.now + advertSyncBusyBackoff @@ -280,7 +271,7 @@ extension AdvertisementService { ) else { continue } try await dataStore.deleteContactIfUnreferenced(id: contact.id) logger.info("Delta sync rollback: removed contact \(pubKeyHex) deleted by the radio mid-sync") - eventBroadcaster.yield(.contactUpdated) + eventBroadcaster.yield(.contactUpdated()) } catch { logger.error("Delta sync rollback failed for \(pubKeyHex): \(error.localizedDescription)") } @@ -310,6 +301,7 @@ extension AdvertisementService { let frame = ContactFrame( publicKey: contact.publicKey, type: contact.type, + typeRawValue: contact.typeRawValue, flags: contact.flags, outPathLength: contact.outPathLength, outPath: contact.outPath, @@ -396,8 +388,7 @@ extension AdvertisementService { var missing: Set = [] for publicKey in unknownAtStart { // A key the radio deleted is missing on purpose; refetching cannot bring it back. - guard !isRadioDeleted(publicKey) else { continue } - guard let exists = await contactExists(radioID: radioID, publicKey: publicKey) else { continue } + guard !isRadioDeleted(publicKey), let exists = await contactExists(radioID: radioID, publicKey: publicKey) else { continue } if !exists { missing.insert(publicKey) } @@ -484,8 +475,7 @@ extension AdvertisementService { guard let radioID = currentRadioID else { return } for publicKey in unknownAtStart { - guard !isRadioDeleted(publicKey) else { continue } - guard let exists = await contactExists(radioID: radioID, publicKey: publicKey) else { continue } + guard !isRadioDeleted(publicKey), let exists = await contactExists(radioID: radioID, publicKey: publicKey) else { continue } if !exists { let pubKeyHex = publicKey.uppercaseHexString() logger.info("Advert full refetch still missing key=\(pubKeyHex); dropping") diff --git a/MC1Services/Sources/MC1Services/Services/AdvertisementService.swift b/MC1Services/Sources/MC1Services/Services/AdvertisementService.swift index 6a7d34acd8..5ec3d88933 100644 --- a/MC1Services/Sources/MC1Services/Services/AdvertisementService.swift +++ b/MC1Services/Sources/MC1Services/Services/AdvertisementService.swift @@ -52,6 +52,7 @@ public actor AdvertisementService { let session: any AdvertisingSessionOps & SessionEventStreaming let dataStore: any PersistenceStoreProtocol let contactService: ContactService + let notificationService: NotificationService? private var eventMonitorTask: Task? /// In-flight `flushPendingDeletedKeys`. Callers wait through @@ -63,7 +64,7 @@ public actor AdvertisementService { var currentRadioID: UUID? /// When true, advert delta sync is deferred (full or manual contact sync). - /// Manual pull-to-refresh also sets this; it is invisible to `SyncCoordinator.isSyncInProgress`. + /// Manual pull-to-refresh also sets this without holding a primary sync claim. var isSyncingContacts = false /// 0x80 keys heard since the last delta sync. @@ -138,7 +139,8 @@ public actor AdvertisementService { advertSyncDebounce: Duration = .seconds(5), advertSyncMinInterval: Duration = .seconds(30), advertSyncBusyBackoff: Duration = .seconds(5), - appStateProvider: AppStateProvider? = nil + appStateProvider: AppStateProvider? = nil, + notificationService: NotificationService? = nil ) { self.session = session self.dataStore = dataStore @@ -147,6 +149,7 @@ public actor AdvertisementService { self.advertSyncMinInterval = advertSyncMinInterval self.advertSyncBusyBackoff = advertSyncBusyBackoff self.appStateProvider = appStateProvider + self.notificationService = notificationService } func isInForeground() async -> Bool { @@ -219,11 +222,13 @@ public actor AdvertisementService { // Drop the handler and bump deltaSyncGeneration before any await so the // in-flight round cannot reconcile or re-arm. deltaSyncHandler = nil - deltaSyncTask?.cancel() + let delta = deltaSyncTask + delta?.cancel() deltaSyncGeneration &+= 1 // Await `flushPendingDeletedKeys` before clearing `currentRadioID` so a queued // 0x8F cannot outlive `stopEventMonitoring`. await monitor?.value + await delta?.value await flushPendingDeletedKeys() let receiveTimes = pendingAdvertReceiveTimes await stampAdvertReceiveTimes(receiveTimes, radioID: currentRadioID) @@ -257,10 +262,13 @@ public actor AdvertisementService { await deletionFlushTask.value return } - guard !pendingDeletedKeys.isEmpty, let radioID = currentRadioID else { return } + await startDeletionFlush()?.value + } + + private func startDeletionFlush() -> Task? { + if let deletionFlushTask { return deletionFlushTask } + guard !pendingDeletedKeys.isEmpty, let radioID = currentRadioID else { return nil } - // Await this Task through `.contactDeletedCleanup` and the catch requeue, which - // run after `deleteContacts`. A store error ends this flush. let task = Task { defer { revivedDuringDeleteFlush.withLock { $0.removeAll() } @@ -270,28 +278,39 @@ public actor AdvertisementService { let keys = pendingDeletedKeys pendingDeletedKeys.removeAll() do { + var contacts: [ContactDTO] = [] + for key in keys { + if let contact = try await dataStore.fetchContact(radioID: radioID, publicKey: key) { + contacts.append(contact) + } + } let deletedIDs = try await dataStore.deleteContacts( radioID: radioID, publicKeys: keys, skippingPublicKeys: { revivedDuringDeleteFlush.withLock { $0 } } ) guard !deletedIDs.isEmpty else { continue } - logger.notice("Overwrite oldest: applying \(deletedIDs.count) deferred deletion(s)") + for contact in contacts where deletedIDs.contains(contact.id) { + lastOverwriteDeletion = ( + name: contact.name.isEmpty ? "(unnamed)" : contact.name, + pubKeyHex: contact.publicKey.prefix(6).uppercaseHexString(), time: Date() + ) + } + logger.notice("Overwrite oldest: applying \(deletedIDs.count) deletion(s)") + await notificationService?.removeDeliveredNotifications(forContactIDs: Set(deletedIDs)) eventBroadcaster.yield(.contactDeletedCleanup(contactIDs: deletedIDs)) eventBroadcaster.yield(.nodeStorageFullChanged(isFull: false)) - eventBroadcaster.yield(.contactUpdated) + eventBroadcaster.yield(.contactUpdated()) } catch { pendingDeletedKeys.formUnion(keys) pendingDeletedKeys.subtract(pendingAdvertKeys) - logger.error( - "Overwrite oldest: deferred delete flush failed: \(error.localizedDescription)" - ) + logger.error("Overwrite oldest: delete flush failed: \(error.localizedDescription)") return } } } deletionFlushTask = task - await task.value + return task } /// Records a 0x80 key for the next delta sync. @@ -361,9 +380,9 @@ public actor AdvertisementService { /// or the radio fetch / save fails. public func materializeContactForPendingAdvert( matchingPrefix prefix: Data, - radioID: UUID + scope: ReceiveScope ) async -> ContactDTO? { - guard !prefix.isEmpty else { return nil } + guard scope.isCurrent, !prefix.isEmpty else { return nil } let matches = pendingAdvertKeys.filter { $0.starts(with: prefix) } guard matches.count == 1, let publicKey = matches.first else { return nil } @@ -374,29 +393,15 @@ public actor AdvertisementService { logger.info("materialize pending advert: getContact nil key=\(pubKeyHex)") return nil } - let frame = meshContact.toContactFrame() - let saveResult = try await dataStore.insertContactIfAbsent(radioID: radioID, from: frame) - // Stamp phone recency before the returned DTO is read so a debounce-window - // insert is not prune-eligible under a stale radio lastModified. + guard scope.isCurrent, !isRadioDeleted(publicKey) else { return nil } let receivedAt = pendingAdvertReceiveTimes[publicKey] ?? Date() - do { - _ = try await dataStore.touchContactHeard( - radioID: radioID, publicKey: publicKey, at: receivedAt - ) - } catch { - logger.error( - "materialize pending advert lastHeard stamp failed key=\(pubKeyHex): \(error.localizedDescription)" - ) + guard let contact = try await dataStore.materializeContactForDirectMessage( + from: meshContact.toContactFrame(), receivedAt: receivedAt, scope: scope + ) else { return nil } + if scope.isCurrent { + eventBroadcaster.yield(.contactUpdated(contact: contact, scope: scope)) } - do { - _ = try await dataStore.upsertDiscoveredNode(radioID: radioID, from: frame) - } catch { - logger.error( - "materialize pending advert Discover upsert failed key=\(pubKeyHex): \(error.localizedDescription)" - ) - } - eventBroadcaster.yield(.contactUpdated) - return try await dataStore.fetchContact(id: saveResult.id) + return contact } catch { logger.error( "materialize pending advert failed key=\(pubKeyHex): \(error.localizedDescription)" @@ -547,7 +552,7 @@ public actor AdvertisementService { if let known { if known { - eventBroadcaster.yield(.contactUpdated) + eventBroadcaster.yield(.contactUpdated()) } else { discoverTrace.debug("B2 0x80 no local contact key=\(pubKeyHex) syncing=\(isSyncingContacts)") logger.debug("ADVERT received for unknown contact - scheduling delta sync") @@ -570,7 +575,7 @@ public actor AdvertisementService { let (node, isNew) = try await dataStore.upsertDiscoveredNode(radioID: radioID, from: contactFrame) discoverTrace.debug("B2 0x8A upsert key=\(pubKeyHex) isNew=\(isNew)") - eventBroadcaster.yield(.contactUpdated) + eventBroadcaster.yield(.contactUpdated()) // Notify only first-time discoveries, not repeat adverts for the same contact. if isNew { @@ -666,7 +671,6 @@ public actor AdvertisementService { /// Handle contact deleted event (0x8F) - device auto-deleted a contact via overwrite oldest private func handleContactDeletedEvent(publicKey: Data, radioID: UUID) async { - let fullPubKeyHex = publicKey.uppercaseHexString() let pubKeyPrefix = publicKey.prefix(6).uppercaseHexString() // ZephCore CLI `set v.contact off` also pushes 0x8F for the V-key. That is @@ -697,46 +701,7 @@ public actor AdvertisementService { return } - guard pendingDeletedKeys.remove(publicKey) != nil else { return } - - logger.debug("Overwrite oldest: device deleted contact with key \(pubKeyPrefix)...") - - do { - guard let contact = try await dataStore.fetchContact(radioID: radioID, publicKey: publicKey) else { - logger.warning("Overwrite oldest: contact not found in local database for key \(pubKeyPrefix)... (may have been deleted already)") - return - } - - let contactName = contact.name.isEmpty ? "(unnamed)" : contact.name - let contactTypeDesc = ContactType(rawValue: contact.typeRawValue).map { "\($0)" } ?? "unknown(\(contact.typeRawValue))" - let lastModifiedDate = Date(timeIntervalSince1970: TimeInterval(contact.lastModified)) - let lastAdvertDate = Date(timeIntervalSince1970: TimeInterval(contact.lastAdvertTimestamp)) - - logger.notice( - """ - Overwrite oldest: deleting contact '\(contactName)' \ - [key=\(fullPubKeyHex), type=\(contactTypeDesc), favorite=\(contact.isFavorite), \ - pathLen=\(contact.outPathLength), lastModified=\(lastModifiedDate), lastAdvert=\(lastAdvertDate)] - """ - ) - - lastOverwriteDeletion = (name: contactName, pubKeyHex: pubKeyPrefix, time: Date()) - - let contactID = contact.id - - try await dataStore.deleteContact(id: contactID) - logger.debug("Overwrite oldest: deleted contact '\(contactName)' and its messages from local database") - - eventBroadcaster.yield(.contactDeletedCleanup(contactIDs: [contactID])) - eventBroadcaster.yield(.nodeStorageFullChanged(isFull: false)) - logger.debug("Overwrite oldest: cleanup complete for '\(contactName)', storage full flag cleared") - eventBroadcaster.yield(.contactUpdated) - } catch { - pendingDeletedKeys.insert(publicKey) - logger.error( - "Overwrite oldest: failed to delete contact \(pubKeyPrefix)...: \(error.localizedDescription)" - ) - } + _ = startDeletionFlush() } /// Correlates an overwrite-oldest deletion with a replacement contact seen soon after. diff --git a/MC1Services/Sources/MC1Services/Services/AppBackupEnvelope.swift b/MC1Services/Sources/MC1Services/Services/AppBackupEnvelope.swift index 80dffab8a0..107008ab1a 100644 --- a/MC1Services/Sources/MC1Services/Services/AppBackupEnvelope.swift +++ b/MC1Services/Sources/MC1Services/Services/AppBackupEnvelope.swift @@ -6,7 +6,11 @@ import Foundation /// All model data is stored as DTO arrays; non-SwiftData items (UserDefaults) have /// dedicated fields. public struct AppBackupEnvelope: Codable, Sendable { - public static let currentVersion = 1 + /// Archives with no self telemetry. An older reader still accepts this version. + public static let legacyVersion = 1 + + /// Self telemetry requires this version so older readers cannot import it without its owner. + public static let currentVersion = 2 public let version: Int public let exportDate: Date diff --git a/MC1Services/Sources/MC1Services/Services/AppBackupService.swift b/MC1Services/Sources/MC1Services/Services/AppBackupService.swift index b1f7c107a1..9e20f597fa 100644 --- a/MC1Services/Sources/MC1Services/Services/AppBackupService.swift +++ b/MC1Services/Sources/MC1Services/Services/AppBackupService.swift @@ -34,7 +34,9 @@ public actor AppBackupService { let appVersion = Bundle.main.appVersion let appBuild = Bundle.main.appBuild + let includesSelfTelemetry = snapshot.nodeStatusSnapshots.contains { $0.selfRadioID != nil } var envelope = AppBackupEnvelope( + version: includesSelfTelemetry ? AppBackupEnvelope.currentVersion : AppBackupEnvelope.legacyVersion, exportDate: .now, appVersion: appVersion, appBuild: appBuild, diff --git a/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift b/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift index 0116b800f2..6aaf0087b5 100644 --- a/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift +++ b/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift @@ -54,6 +54,12 @@ public enum AppStorageKey: String { /// in-bubble Translate button. case translationOffersEnabled case autoDeleteStaleNodesDays + /// Initial attempts use the contact's current out path, which can be Flood. + case dmDirectAttempts + /// Zero disables the out path reset and fallback sends. + case dmFloodAttempts + /// Off keeps the known route after a timeout. A missing key means on. + case remoteFloodFallback case lastStaleCleanupDate case frequentEmojis case recentReactionEmojis @@ -63,6 +69,8 @@ public enum AppStorageKey: String { /// hardware still shows the current release's notes once. Registering it would /// suppress the sheet on a genuinely new device. case lastShownWhatsNewVersion + /// Left out of `BackupUserDefaults`, so a restored on value cannot enable collection. A missing key stays off. + case collectDebugLogs // Notification toggles read by NotificationPreferences and // NotificationPreferencesStore; all share defaultNotificationEnabled. @@ -103,6 +111,9 @@ public enum AppStorageKey: String { public static let defaultLiveActivityEnabled: Bool = true /// Days before a non-favorite node is auto-deleted; 0 disables cleanup. public static let defaultAutoDeleteStaleNodesDays: Int = 0 + public static let defaultDMDirectAttempts: Int = DMSendBudget.defaultDirectAttempts + public static let defaultDMFloodAttempts: Int = DMSendBudget.defaultFloodAttempts + public static let defaultRemoteFloodFallback: Bool = RemoteFloodFallback.defaultEnabled /// `timeIntervalSinceReferenceDate` of the last cleanup; 0 means never ran. public static let defaultLastStaleCleanupDate: Double = 0 /// Shared default for every notification toggle case. diff --git a/MC1Services/Sources/MC1Services/Services/BLETransportOpenedSignal.swift b/MC1Services/Sources/MC1Services/Services/BLETransportOpenedSignal.swift index 8769bb6c87..9731cc7df9 100644 --- a/MC1Services/Sources/MC1Services/Services/BLETransportOpenedSignal.swift +++ b/MC1Services/Sources/MC1Services/Services/BLETransportOpenedSignal.swift @@ -21,6 +21,12 @@ actor BLETransportOpenedSignal { init() {} + #if DEBUG + var waiterCountForTesting: Int { + waiters.count + } + #endif + /// Suspend until `fire()` lands. If the signal is already armed at /// call time, the call returns immediately and consumes the armed /// flag. Throws `CancellationError` if the calling task is cancelled diff --git a/MC1Services/Sources/MC1Services/Services/BackupUserDefaults.swift b/MC1Services/Sources/MC1Services/Services/BackupUserDefaults.swift index 21741b50d7..696296fd9f 100644 --- a/MC1Services/Sources/MC1Services/Services/BackupUserDefaults.swift +++ b/MC1Services/Sources/MC1Services/Services/BackupUserDefaults.swift @@ -27,6 +27,9 @@ public struct BackupUserDefaults: Codable, Sendable, Equatable { public var showIncomingHeardCount: Bool? public var showIncomingSendTime: Bool? public var autoDeleteStaleNodesDays: Int? + public var dmDirectAttempts: Int? + public var dmFloodAttempts: Int? + public var remoteFloodFallback: Bool? public var discoverySortOrder: String? public var nodesSortOrder: String? public var tracePathViewMode: String? @@ -58,19 +61,17 @@ public struct BackupUserDefaults: Codable, Sendable, Equatable { public init() {} - // MARK: - UserDefaults keys for special-cased (non-Bool/String) properties + // MARK: - UserDefaults keys for special-cased properties - private static let autoDeleteStaleNodesDaysKey = AppStorageKey.autoDeleteStaleNodesDays.rawValue private static let frequentEmojisKey = AppStorageKey.frequentEmojis.rawValue private static let recentReactionEmojisKey = AppStorageKey.recentReactionEmojis.rawValue /// Public so `AppState` (and tests) can persist via the same key without a duplicated literal. public static let regionSelectionKey = "userPrefs.region" /// Property names handled by hand-rolled branches in `snapshot`/`restore` - /// rather than the bool/string mappings. Internal solely for testability — + /// rather than the scalar mappings. Internal solely for testability — /// do not consume from non-test code. static let specialCasedPropertyNames: Set = [ - "autoDeleteStaleNodesDays", "frequentEmojis", "recentEmojis", "regionSelection" @@ -128,6 +129,7 @@ public struct BackupUserDefaults: Codable, Sendable, Equatable { (\.hasSeenRepeaterDragHint, AppStorageKey.hasSeenRepeaterDragHint.rawValue), (\.useDefaultTranslationApp, AppStorageKey.useDefaultTranslationApp.rawValue), (\.translationOffersEnabled, AppStorageKey.translationOffersEnabled.rawValue), + (\.remoteFloodFallback, AppStorageKey.remoteFloodFallback.rawValue), (\.notifyContactMessages, AppStorageKey.notifyContactMessages.rawValue), (\.notifyChannelMessages, AppStorageKey.notifyChannelMessages.rawValue), (\.notifyRoomMessages, AppStorageKey.notifyRoomMessages.rawValue), @@ -168,6 +170,18 @@ public struct BackupUserDefaults: Codable, Sendable, Equatable { Set(stringMappings.map(\.1)) } + /// See `boolMappings` for the `nonisolated(unsafe)` rationale. + private nonisolated(unsafe) static let intMappings: [(WritableKeyPath, String)] = [ + (\.autoDeleteStaleNodesDays, AppStorageKey.autoDeleteStaleNodesDays.rawValue), + (\.dmDirectAttempts, AppStorageKey.dmDirectAttempts.rawValue), + (\.dmFloodAttempts, AppStorageKey.dmFloodAttempts.rawValue), + ] + + /// Key strings used by `intMappings`. Internal solely for testability. + static var intMappingKeys: Set { + Set(intMappings.map(\.1)) + } + // MARK: - Read from UserDefaults /// Creates a snapshot by reading all known keys from UserDefaults. @@ -187,8 +201,10 @@ public struct BackupUserDefaults: Codable, Sendable, Equatable { } } - if defaults.object(forKey: Self.autoDeleteStaleNodesDaysKey) != nil { - result.autoDeleteStaleNodesDays = defaults.integer(forKey: Self.autoDeleteStaleNodesDaysKey) + for (keyPath, key) in intMappings { + if defaults.object(forKey: key) != nil { + result[keyPath: keyPath] = defaults.integer(forKey: key) + } } // frequentEmojis is stored as JSON-encoded [String] via @AppStorage Data binding @@ -228,17 +244,16 @@ public struct BackupUserDefaults: Codable, Sendable, Equatable { } } - if let value = autoDeleteStaleNodesDays, - defaults.object(forKey: Self.autoDeleteStaleNodesDaysKey) == nil { - defaults.set(value, forKey: Self.autoDeleteStaleNodesDaysKey) - setKeys.append(Self.autoDeleteStaleNodesDaysKey) + for (keyPath, key) in Self.intMappings { + if let value = self[keyPath: keyPath], defaults.object(forKey: key) == nil { + defaults.set(value, forKey: key) + setKeys.append(key) + } } - if let emojis = frequentEmojis, defaults.object(forKey: Self.frequentEmojisKey) == nil { - if let data = try? JSONEncoder().encode(emojis) { - defaults.set(data, forKey: Self.frequentEmojisKey) - setKeys.append(Self.frequentEmojisKey) - } + if let emojis = frequentEmojis, defaults.object(forKey: Self.frequentEmojisKey) == nil, let data = try? JSONEncoder().encode(emojis) { + defaults.set(data, forKey: Self.frequentEmojisKey) + setKeys.append(Self.frequentEmojisKey) } if let emojis = recentEmojis, defaults.object(forKey: Self.recentReactionEmojisKey) == nil { diff --git a/MC1Services/Sources/MC1Services/Services/BinaryProtocolService.swift b/MC1Services/Sources/MC1Services/Services/BinaryProtocolService.swift index f88ef8275d..3f55a2b52e 100644 --- a/MC1Services/Sources/MC1Services/Services/BinaryProtocolService.swift +++ b/MC1Services/Sources/MC1Services/Services/BinaryProtocolService.swift @@ -34,6 +34,7 @@ public actor BinaryProtocolService { private let session: any DiagnosticsSessionOps & SessionEventStreaming & ContactSessionOps private let radioID: UUID private let contactRadio: any ContactRadioOwning + private let defaults: UserDefaults private let logger = PersistentLogger(subsystem: "com.mc1", category: "BinaryProtocol") /// Handler for status responses (from push notifications) @@ -53,11 +54,13 @@ public actor BinaryProtocolService { public init( session: any DiagnosticsSessionOps & SessionEventStreaming & ContactSessionOps, radioID: UUID, - contactRadio: any ContactRadioOwning + contactRadio: any ContactRadioOwning, + defaults: UserDefaults = .standard ) { self.session = session self.radioID = radioID self.contactRadio = contactRadio + self.defaults = defaults } deinit { @@ -229,8 +232,8 @@ public actor BinaryProtocolService { // MARK: - Direct-path flood recovery - /// On mesh timeout, calls `resetPath` and retries once. Always resets because - /// this path has no radio-scoped contact to check for flood routing. + /// On mesh timeout, calls `resetPath` and retries once when path fallback is on. + /// This path has no radio-scoped contact to check for flood routing. private func performWithPathResetOnTimeout( publicKey: Data, operationName: String, @@ -240,6 +243,9 @@ public actor BinaryProtocolService { return try await operation() } catch let error as MeshCoreError { guard case .timeout = error else { throw BinaryProtocolError.sessionError(error) } + guard RemoteFloodFallback.isEnabled(defaults: defaults) else { + throw BinaryProtocolError.sessionError(error) + } logger.info( "\(operationName): mesh timeout; resetting path to flood and retrying once" ) diff --git a/MC1Services/Sources/MC1Services/Services/ChannelFloodScopeResolver.swift b/MC1Services/Sources/MC1Services/Services/ChannelFloodScopeResolver.swift index 9f89e45a32..9e882f9d54 100644 --- a/MC1Services/Sources/MC1Services/Services/ChannelFloodScopeResolver.swift +++ b/MC1Services/Sources/MC1Services/Services/ChannelFloodScopeResolver.swift @@ -1,34 +1,21 @@ import Foundation import MeshCore -/// Resolves the ``ResolvedFloodScope`` to push to the radio for a given conversation, -/// combining the per-channel ``ChannelFloodScope`` preference with the device-wide -/// default flood scope name and the device's un-scoped-send capability. -/// -/// - `.allRegions` + device supports un-scoped send → `.unscoped` (true override of the -/// device default via firmware sub-command 1; requires firmware v12+) -/// - `.allRegions` + device does not support un-scoped send → `.scope(.disabled)` -/// (best-effort fallback: a zero-key reset cannot override the default on older firmware, -/// so the radio still floods on its configured default) -/// - `.inherit` + device default set → `.scope(.region(default))` (radio floods on the default) -/// - `.inherit` + no device default → `.scope(.disabled)` (no scope filter) -/// - `.region(name)` → `.scope(.region(name))` (explicit per-channel override) +/// Resolves a channel preference for transmission. Inheritance clears the temporary +/// override so the radio uses its persisted default. public enum ChannelFloodScopeResolver { public static func resolve( channelFloodScope: ChannelFloodScope, - deviceDefaultFloodScopeName: String?, supportsUnscopedFloodSend: Bool ) -> ResolvedFloodScope { switch channelFloodScope { case .inherit: - if let name = deviceDefaultFloodScopeName, !name.isEmpty { - return .scope(.region(name)) - } - return .scope(.disabled) + .scope(.disabled) case .allRegions: - return supportsUnscopedFloodSend ? .unscoped : .scope(.disabled) + // Older firmware cannot override a persisted default with Unscoped. + supportsUnscopedFloodSend ? .unscoped : .scope(.disabled) case let .region(name): - return .scope(.region(name)) + .scope(.region(name)) } } } diff --git a/MC1Services/Sources/MC1Services/Services/ChannelService.swift b/MC1Services/Sources/MC1Services/Services/ChannelService.swift index b5b84d6f43..67248db3dd 100644 --- a/MC1Services/Sources/MC1Services/Services/ChannelService.swift +++ b/MC1Services/Sources/MC1Services/Services/ChannelService.swift @@ -543,6 +543,16 @@ public actor ChannelService { ) } + /// Sleeps on `MeshCoreSession.clock` when the session has one, so a test clock can elapse the retry. + private func pauseBeforeChannelRetry(milliseconds: Int) async throws { + let delay = Duration.milliseconds(milliseconds) + if let meshSession = session as? MeshCoreSession { + try await meshSession.clock.sleep(for: delay) + } else { + try await Task.sleep(for: delay) + } + } + /// Fetches a single channel from the device with retry logic for transient BLE failures. /// - Parameter index: The channel index /// - Returns: Channel info if found, nil if not configured @@ -594,7 +604,7 @@ public actor ChannelService { let jitterMs = Int.random(in: -100...100) let delayMs = baseDelayMs + jitterMs logger.info("Channel \(index) fetch timeout, retry \(attempt)/\(maxAttempts) in \(delayMs)ms") - try await Task.sleep(for: .milliseconds(delayMs)) + try await pauseBeforeChannelRetry(milliseconds: delayMs) continue } } @@ -822,7 +832,7 @@ public actor ChannelService { /// Acquires the channel operation gate, runs `operation` on this task, and releases on every exit. /// A cancelled waiter may sit until it acquires, then leaves without a command or a store write. - private func withChannelOperation( + func withChannelOperation( _ operation: () async throws -> T ) async throws -> T { await channelOperationSerializer.acquire() @@ -930,7 +940,7 @@ public actor ChannelService { errorType: .transportError, description: transportError.localizedDescription ) - case .notConnected, .connectionFailed, .deviceNotFound, .serviceNotFound, .characteristicNotFound: + case .notConnected, .connectionFailed, .deviceNotFound, .serviceNotFound, .characteristicNotFound, .cancelledBeforeSubmission: return ChannelSyncError( index: index, errorType: .transportError, diff --git a/MC1Services/Sources/MC1Services/Services/ChatCoordinator+Mutations.swift b/MC1Services/Sources/MC1Services/Services/ChatCoordinator+Mutations.swift index e0d1c2c30c..5d58893038 100644 --- a/MC1Services/Sources/MC1Services/Services/ChatCoordinator+Mutations.swift +++ b/MC1Services/Sources/MC1Services/Services/ChatCoordinator+Mutations.swift @@ -246,6 +246,7 @@ extension ChatCoordinator { dto.roundTripTime = roundTripTime } } + guard !removeHiddenOutgoingReaction(messageID: messageID) else { return } updateRenderItem(id: messageID) { item in item.with( envelope: item.envelope.with(status: status), @@ -254,6 +255,17 @@ extension ChatCoordinator { } } + @discardableResult + func removeHiddenOutgoingReaction(messageID: UUID) -> Bool { + guard let message = messagesByID[messageID], + message.isHiddenOutgoingReaction(isDM: message.contactID != nil) else { return false } + // The persisted row still occupies its page, so retain totalFetchedCount. + remove(messageID: messageID) + removeRenderItem(id: messageID) + renderStateInvalidated?() + return true + } + /// Resumes its continuation at most once. @MainActor private final class OnceResume { diff --git a/MC1Services/Sources/MC1Services/Services/ChatCoordinator+Reload.swift b/MC1Services/Sources/MC1Services/Services/ChatCoordinator+Reload.swift index 91f308c415..ab0b50501d 100644 --- a/MC1Services/Sources/MC1Services/Services/ChatCoordinator+Reload.swift +++ b/MC1Services/Sources/MC1Services/Services/ChatCoordinator+Reload.swift @@ -61,6 +61,7 @@ extension ChatCoordinator { update(messageID: id) { dto in dto = fetched } + if removeHiddenOutgoingReaction(messageID: id) { continue } refreshedIDs.append(id) } else if messagesByID[id] != nil { inconsistencyDetected = true diff --git a/MC1Services/Sources/MC1Services/Services/ChatSendAdmission.swift b/MC1Services/Sources/MC1Services/Services/ChatSendAdmission.swift new file mode 100644 index 0000000000..8ecf6ed61d --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/ChatSendAdmission.swift @@ -0,0 +1,6 @@ +/// Initial queue admission after Message creation. The Message is the creation snapshot; +/// enqueue failure has already attempted to persist `.failed` without downgrading `.delivered`. +public enum ChatSendAdmission: Sendable { + case queued(MessageDTO) + case enqueueFailed(MessageDTO, error: any Error) +} diff --git a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+Admission.swift b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+Admission.swift new file mode 100644 index 0000000000..aa94cb3550 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+Admission.swift @@ -0,0 +1,60 @@ +public extension ChatSendQueueService { + /// Creates and queues a DM. Creation errors throw; enqueue errors retain the saved Message. + /// The synchronous callback publishes the Message before queue status events can arrive. + func enqueueDirectMessage( + text: String, + to contact: ContactDTO, + onMessageCreated: (@MainActor (MessageDTO) -> Void)? = nil + ) async throws -> ChatSendAdmission { + guard contact.radioID == radioID, beginAdmission() else { + throw ChatSendQueueServiceError.notConnected + } + defer { finishAdmission() } + + let message = try await messageService.createPendingMessage(text: text, to: contact) + onMessageCreated?(message) + do { + try await enqueueDM(DirectMessageEnvelope(messageID: message.id, contactID: contact.id)) + return .queued(message) + } catch { + return await recordAdmissionFailure(message: message, error: error) + } + } + + /// Creates and queues a channel Message with the same failure and publication contract as a DM. + func enqueueChannelMessage( + text: String, + to channel: ChannelDTO, + localNodeName: String?, + onMessageCreated: (@MainActor (MessageDTO) -> Void)? = nil + ) async throws -> ChatSendAdmission { + guard channel.radioID == radioID, beginAdmission() else { + throw ChatSendQueueServiceError.notConnected + } + defer { finishAdmission() } + + let message = try await messageService.createPendingChannelMessage( + text: text, channelIndex: channel.index, radioID: channel.radioID + ) + onMessageCreated?(message) + do { + try await enqueueChannel(ChannelMessageEnvelope( + messageID: message.id, + channelIndex: channel.index, + isResend: false, + messageText: message.text, + messageTimestamp: message.timestamp, + localNodeName: localNodeName + )) + return .queued(message) + } catch { + return await recordAdmissionFailure(message: message, error: error) + } + } + + private func recordAdmissionFailure(message: MessageDTO, error: any Error) async -> ChatSendAdmission { + // A PendingSend saved before retirement remains available to reconnect hydration. + _ = try? await dataStore.updateMessageStatusUnlessDelivered(id: message.id, status: .failed) + return .enqueueFailed(message, error: error) + } +} diff --git a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift new file mode 100644 index 0000000000..addff30993 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift @@ -0,0 +1,230 @@ +import Foundation +import os + +extension ChatSendQueueService { + /// Values the channel drain closes over. The queue does not retain the service. + nonisolated struct ChannelDrainDependencies: Sendable { + let radioID: UUID + let dataStore: any MessagePersisting + let messageService: MessageService + let channelService: ChannelService + let reactionService: ReactionService + let triggers: BLETransportOpenedSignal + let logger: PersistentLogger + let osLogger: Logger + let failureCounter: FailureCounter + let config: ChatSendQueueConfig + let sendsRetired: OSAllocatedUnfairLock + } + + /// Outcome of the bump and the radio send. Both run under the channel gate. + /// `Error` returns to the awaiting task after the gate releases. + private nonisolated enum QueuedChannelTransmission: @unchecked Sendable { + case dropped + case preflightFailed(Error) + case sent(UInt32) + case radioFailed(Error, postBumpCount: Int) + } + + /// Drains one queued channel send. A database error during the bump parks outside the channel gate. + nonisolated static func sendQueuedChannel( + envelope: ChannelMessageEnvelope, + dependencies: ChannelDrainDependencies + ) async throws { + do { + guard try await validateQueuedChannel( + envelope: envelope, + radioID: dependencies.radioID, + dataStore: dependencies.dataStore, + channelService: dependencies.channelService, + triggers: dependencies.triggers, + logger: dependencies.logger, + timeout: dependencies.config.transportWaitTimeout + ) else { return } + try cancelSendIfRetired(dependencies.sendsRetired) + + switch try await transmitQueuedChannel(envelope: envelope, dependencies: dependencies) { + case .dropped: + return + case let .preflightFailed(error): + _ = try? await dependencies.dataStore.updateMessageStatusUnlessDelivered( + id: envelope.messageID, + status: .pending + ) + dependencies.logger.warning("channel drain preflight failed: \(String(describing: error))") + try await parkAndCancel( + triggers: dependencies.triggers, + logger: dependencies.logger, + messageID: envelope.messageID, + kind: "channel", + timeout: dependencies.config.transportWaitTimeout + ) + case let .sent(indexTimestamp): + if let nodeName = envelope.localNodeName { + _ = await dependencies.reactionService.indexMessage( + id: envelope.messageID, + channelIndex: envelope.channelIndex, + senderName: nodeName, + text: envelope.messageText, + timestamp: indexTimestamp + ) + } + try? await dependencies.dataStore.deletePendingSendsForMessage(messageID: envelope.messageID) + dependencies.osLogger.debug("channel drain success messageID=\(envelope.messageID)") + await dependencies.failureCounter.reset(for: envelope.messageID) + await dependencies.triggers.clear() + case let .radioFailed(error, postBumpCount): + try await handleQueuedChannelRadioFailure( + error, + postBumpCount: postBumpCount, + envelope: envelope, + dependencies: dependencies + ) + } + } catch let cancellation as CancellationError { + throw cancellation + } catch { + await dependencies.messageService.notifyMessageFailed(messageID: envelope.messageID) + throw error + } + } + + /// The bump and the radio send share the channel gate. A slot rewrite + /// deletes this pending row before it can acquire the gate and transmit. + private nonisolated static func transmitQueuedChannel( + envelope: ChannelMessageEnvelope, + dependencies: ChannelDrainDependencies + ) async throws -> QueuedChannelTransmission { + try await dependencies.channelService.withChannelOperation { () -> QueuedChannelTransmission in + let prepared: (postBumpCount: Int, preserveTimestamp: Bool) + do { + guard let result = try await preflightAndBump( + dataStore: dependencies.dataStore, + messageID: envelope.messageID, + kind: "channel", + logger: dependencies.logger, + osLogger: dependencies.osLogger + ) else { return .dropped } + prepared = (result.postBumpCount, result.preserveTimestamp) + } catch { + return .preflightFailed(error) + } + + do { + if envelope.isResend { + let timestamp = try await dependencies.messageService.resendChannelMessage( + messageID: envelope.messageID, + preserveTimestamp: prepared.preserveTimestamp + ) + return .sent(timestamp) + } + try await dependencies.messageService.sendPendingChannelMessage(messageID: envelope.messageID) + return .sent(envelope.messageTimestamp) + } catch is CancellationError { + throw CancellationError() + } catch { + return .radioFailed(error, postBumpCount: prepared.postBumpCount) + } + } + } + + private nonisolated static func handleQueuedChannelRadioFailure( + _ error: Error, + postBumpCount: Int, + envelope: ChannelMessageEnvelope, + dependencies: ChannelDrainDependencies + ) async throws { + guard isTransientChannelMessageError(error) else { + dependencies.logger.info( + "channel drain terminal messageID=\(envelope.messageID) error=\(String(describing: error))" + ) + throw error + } + if isChannelMessageNotFound(error) { + // Disambiguate pool exhaustion (transient) from a stale + // channel index (terminal) by refreshing the radio's + // view of the channel. `ChannelService.fetchChannel(index:)` + // reads from the device, so a nil result means the radio + // agrees the channel is gone (terminal). + // + // Gate on disambiguateAfterAttempts so the common + // pool-exhaustion burst (1-2 NOT_FOUNDs in a row) parks + // without an extra BLE round-trip; only persistent + // NOT_FOUND warrants the fetchChannel cost. + if postBumpCount < dependencies.config.disambiguateAfterAttempts { + dependencies.logger.info( + "channel drain NOT_FOUND below disambiguate threshold messageID=\(envelope.messageID) postBumpCount=\(postBumpCount); parking envelope" + ) + _ = try? await dependencies.dataStore.updateMessageStatusUnlessDelivered( + id: envelope.messageID, + status: .pending + ) + try await parkAndCancel( + triggers: dependencies.triggers, + logger: dependencies.logger, + messageID: envelope.messageID, + kind: "channel", + timeout: dependencies.config.transportWaitTimeout + ) + } + + let stillExists: Bool + do { + stillExists = try await dependencies.channelService.fetchChannel(index: envelope.channelIndex) != nil + await dependencies.failureCounter.reset(for: envelope.messageID) + } catch { + let failures = await dependencies.failureCounter.increment(for: envelope.messageID) + if failures >= dependencies.config.maxConsecutiveFetchChannelFailures { + dependencies.logger.warning( + "Channel drain: fetchChannel persistently failing (\(failures) consecutive) for messageID=\(envelope.messageID); marking terminal" + ) + await dependencies.failureCounter.reset(for: envelope.messageID) + throw error + } + dependencies.logger.info( + "channel drain NOT_FOUND followup fetchChannel failed: \(String(describing: error)); parking envelope (\(failures)/\(dependencies.config.maxConsecutiveFetchChannelFailures))" + ) + _ = try? await dependencies.dataStore.updateMessageStatusUnlessDelivered( + id: envelope.messageID, + status: .pending + ) + try await parkAndCancel( + triggers: dependencies.triggers, + logger: dependencies.logger, + messageID: envelope.messageID, + kind: "channel", + timeout: dependencies.config.transportWaitTimeout + ) + } + if !stillExists { + dependencies.logger.warning( + "Channel drain: NOT_FOUND confirmed by fetchChannel for messageID=\(envelope.messageID); treating as terminal (channel deleted)" + ) + await dependencies.failureCounter.reset(for: envelope.messageID) + throw error + } + // Channel still exists per device. NOT_FOUND was pool + // exhaustion. Park on the transport-open trigger. The + // effective per-attempt cadence under sustained + // exhaustion is ~37s (3.5s withPoolBackoff in-loop + + // 3.5s fetchChannel disambiguation + 30s + // transportWaitTimeout park). Transport-open only fires + // on entering `.ready`, so under a healthy connection + // the 30s park is what bounds the retry rate. + } + dependencies.logger.info( + "channel drain transient messageID=\(envelope.messageID) error=\(String(describing: error))" + ) + _ = try? await dependencies.dataStore.updateMessageStatusUnlessDelivered( + id: envelope.messageID, + status: .pending + ) + try await parkAndCancel( + triggers: dependencies.triggers, + logger: dependencies.logger, + messageID: envelope.messageID, + kind: "channel", + timeout: dependencies.config.transportWaitTimeout + ) + } +} diff --git a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift index 1fdb6cbe40..d26df2cab0 100644 --- a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift +++ b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift @@ -46,31 +46,14 @@ struct ChatSendQueueConfig { static let `default` = ChatSendQueueConfig() } -/// Owns the DM and channel send queues for a connection. Replaces the -/// per-view-model queue ownership on `ChatViewModel`. Lives on -/// `ServiceContainer`; constructed once per connection, torn down on -/// disconnect. -/// -/// Startup behaviour: `hydrate()` reads `PendingSend` rows from -/// `PersistenceStore` for the connection's radio and enqueues them. -/// `ConnectionManager` calls `hydrate()` once after building the container -/// and before exposing it to view models, so two `ChatViewModel`s -/// active during a single connection cannot trigger duplicate replay. -/// -/// Transport-open signal: the drain step suspends via -/// `withCooperativeTimeout` on the `BLETransportOpenedSignal` actor. -/// The connection-state observation started by `observeConnectionState` -/// fires the signal each time the connection enters `.ready`. Rows are -/// never deleted while waiting. `triggers.clear` is called only after a -/// successful send (not before each attempt) so that a fire signal -/// landing during a successful send doesn't get wiped before the next -/// failed send needs it. +/// Owns initial admission and durable DM and channel queues for one connection. +/// ServiceContainer retirement joins admitted work before replacement services hydrate it. @MainActor public final class ChatSendQueueService { let radioID: UUID private let config: ChatSendQueueConfig - private let dataStore: any MessagePersisting & ContactPersisting - private let messageService: MessageService + let dataStore: any MessagePersisting & ContactPersisting + let messageService: MessageService private let channelService: ChannelService private let reactionService: ReactionService private let triggers: BLETransportOpenedSignal @@ -82,19 +65,25 @@ public final class ChatSendQueueService { private let channelQueue: SendQueue private var hasHydrated = false + private var isRetired = false + /// The channel drain reads this without retaining the service. Shutdown sets it before the first suspension. + private let sendsRetired = OSAllocatedUnfairLock(initialState: false) + private var admittedWork = 0 + private var admissionWaiters: [CheckedContinuation] = [] + private var shutdownTask: Task? /// Task consuming the connection-state stream installed by /// `observeConnectionState`. Cancelled in `shutdown()`. private var connectionStateTask: Task? - // swiftlint:disable:next function_body_length init( radioID: UUID, dataStore: any MessagePersisting & ContactPersisting, messageService: MessageService, channelService: ChannelService, reactionService: ReactionService, - config: ChatSendQueueConfig = .default + config: ChatSendQueueConfig = .default, + plainTextSendGate: PlainTextSendGate? = nil ) { self.radioID = radioID self.config = config @@ -115,9 +104,11 @@ public final class ChatSendQueueService { let osLoggerRef = osLogger let failureCounter = channelFetchFailureCounter let configRef = config + let sendsRetired = self.sendsRetired dmQueue = SendQueue( send: { envelope in + var pendingSendID: UUID? // Outer catch: the queue-routed catch sites in MessageService // do not broadcast `.failed` themselves; the helper // `failMessageAndRethrow` only writes the DB state and @@ -130,17 +121,29 @@ public final class ChatSendQueueService { // transient error does not produce a `.failed`-then-`.pending` // flicker on the UI. do { + let sendLease = try await plainTextSendGate?.acquire() + func stopIssuing() async { + if let sendLease { + await plainTextSendGate?.stopIssuing(sendLease) + } + } + defer { await stopIssuing() } + try Task.checkCancellation() + try ChatSendQueueService.cancelSendIfRetired(sendsRetired) + let contact: ContactDTO switch await ChatSendQueueService.classifyRead({ try await dataStoreRef.fetchContact(id: envelope.contactID) }) { case let .found(value): contact = value case .missing: loggerRef.info("DM send queue: contact \(envelope.contactID) was deleted; dropping envelope") + await stopIssuing() try? await dataStoreRef.deletePendingSendsForMessage(messageID: envelope.messageID) try? await dataStoreRef.updateMessageStatus(id: envelope.messageID, status: .failed) return case let .transient(error): loggerRef.warning("DM drain fetchContact transient error: \(String(describing: error)); parking envelope") + await stopIssuing() try await ChatSendQueueService.parkAndCancel( triggers: triggers, logger: loggerRef, @@ -150,10 +153,8 @@ public final class ChatSendQueueService { ) } - // Pre-send gate + attemptCount bump. Persisted attemptCount - // becomes the source of truth for preserveTimestamp. Bump - // completes (and modelContext.save() commits) before any - // wire-affecting work. + // Persist the attempt after admission but before any command, so replay knows + // whether transmission may have started and must preserve the timestamp. let preserveTimestamp: Bool do { guard let result = try await ChatSendQueueService.preflightAndBump( @@ -162,10 +163,13 @@ public final class ChatSendQueueService { kind: "DM", logger: loggerRef, osLogger: osLoggerRef - ) else { return } + ) else { + return + } preserveTimestamp = result.preserveTimestamp + pendingSendID = result.pendingSendID } catch { - _ = try? await dataStoreRef.updateMessageStatusUnlessDelivered(id: envelope.messageID, status: .pending) + await stopIssuing() try await ChatSendQueueService.parkAndCancel( triggers: triggers, logger: loggerRef, @@ -176,25 +180,21 @@ public final class ChatSendQueueService { } do { - if envelope.isResend { - _ = try await messageServiceRef.resendDirectMessage( - messageID: envelope.messageID, - to: contact, - preserveTimestamp: preserveTimestamp - ) - } else { - _ = try await messageServiceRef.sendPendingDirectMessage( - messageID: envelope.messageID, - to: contact, - preserveTimestamp: preserveTimestamp - ) + let message = try await messageServiceRef.performQueuedDirectMessageSend( + messageID: envelope.messageID, + to: contact, + preserveTimestamp: preserveTimestamp, + isResend: envelope.isResend, + isSingleAttempt: envelope.isSingleAttempt, + pendingSendID: pendingSendID, + sendLease: sendLease + ) + if message.status == .delivered || message.status == .failed, let pendingSendID { + try? await dataStoreRef.deletePendingSend(id: pendingSendID) } - try? await dataStoreRef.deletePendingSendsForMessage(messageID: envelope.messageID) osLoggerRef.debug("DM drain success messageID=\(envelope.messageID)") - // Success: clear any armed trigger now that the row - // is gone. A subsequent failed send for a different - // envelope re-arms on its own when the next - // transport-open fires. + // Clear the trigger once wire work is complete; an ACK-only row + // remains durable without needing another transport-open signal. await triggers.clear() } catch is CancellationError { throw CancellationError() @@ -204,11 +204,8 @@ public final class ChatSendQueueService { throw error } loggerRef.info("DM drain transient messageID=\(envelope.messageID) error=\(String(describing: error))") - // Remap the .failed write that failMessageAndRethrow just - // made back to .pending so the bubble doesn't show - // "Failed" while the queue is silently parked. Duplicate - // prevention on the next pass is via preserveTimestamp, - // not via any boundary check. + // Remap a parked failure back to .pending so the bubble does not show Failed. + // The next pass keeps this timestamp and continues at the stored attempt byte. _ = try? await dataStoreRef.updateMessageStatusUnlessDelivered(id: envelope.messageID, status: .pending) try await ChatSendQueueService.parkAndCancel( triggers: triggers, @@ -219,17 +216,18 @@ public final class ChatSendQueueService { ) } } catch let cancellation as CancellationError { + // The replacement queue hydrates this row. A retired gate cannot retry it. + if await plainTextSendGate?.isInvalidated == true, !Task.isCancelled { return } throw cancellation } catch { + if let pendingSendID { + try? await dataStoreRef.deletePendingSend(id: pendingSendID) + } await messageServiceRef.notifyMessageFailed(messageID: envelope.messageID) throw error } }, - onError: { _, envelope in - // Permanent error path only — transient errors take the - // wait-and-retry branch above and never reach onError. - try? await dataStoreRef.deletePendingSendsForMessage(messageID: envelope.messageID) - }, + onError: { _, _ in }, onDrain: { lastError in if let lastError { loggerRef.error("DM queue drained with error: \(String(describing: lastError))") @@ -237,148 +235,22 @@ public final class ChatSendQueueService { } ) + let channelDrain = ChannelDrainDependencies( + radioID: radioID, + dataStore: dataStoreRef, + messageService: messageServiceRef, + channelService: channelServiceRef, + reactionService: reactionServiceRef, + triggers: triggers, + logger: loggerRef, + osLogger: osLoggerRef, + failureCounter: failureCounter, + config: configRef, + sendsRetired: sendsRetired + ) channelQueue = SendQueue( send: { envelope in - // Outer catch: see DM closure for rationale. Park-and-requeue - // branches throw `CancellationError`; any other escape is a - // terminal failure for the envelope and calls - // `notifyMessageFailed` exactly once. - do { - // Pre-send gate + attemptCount bump; see DM closure for rationale. - let postBumpCount: Int - let preserveTimestamp: Bool - do { - guard let result = try await ChatSendQueueService.preflightAndBump( - dataStore: dataStoreRef, - messageID: envelope.messageID, - kind: "channel", - logger: loggerRef, - osLogger: osLoggerRef - ) else { return } - postBumpCount = result.postBumpCount - preserveTimestamp = result.preserveTimestamp - } catch { - _ = try? await dataStoreRef.updateMessageStatusUnlessDelivered(id: envelope.messageID, status: .pending) - try await ChatSendQueueService.parkAndCancel( - triggers: triggers, - logger: loggerRef, - messageID: envelope.messageID, - kind: "channel", - timeout: configRef.transportWaitTimeout - ) - } - - do { - // resendChannelMessage stamps a fresh wire timestamp so the - // mesh dedup ring treats the retry as a new broadcast. - // Reactions hash off that exact timestamp via - // SHA256(text || timestamp.littleEndian), so the resent - // packet must be indexed under the post-resend value, not - // the pre-resend value captured at enqueue time. - let indexTimestamp: UInt32 - if envelope.isResend { - indexTimestamp = try await messageServiceRef.resendChannelMessage( - messageID: envelope.messageID, - preserveTimestamp: preserveTimestamp - ) - } else { - try await messageServiceRef.sendPendingChannelMessage(messageID: envelope.messageID) - indexTimestamp = envelope.messageTimestamp - } - if let nodeName = envelope.localNodeName { - _ = await reactionServiceRef.indexMessage( - id: envelope.messageID, - channelIndex: envelope.channelIndex, - senderName: nodeName, - text: envelope.messageText, - timestamp: indexTimestamp - ) - } - try? await dataStoreRef.deletePendingSendsForMessage(messageID: envelope.messageID) - osLoggerRef.debug("channel drain success messageID=\(envelope.messageID)") - await failureCounter.reset(for: envelope.messageID) - await triggers.clear() - } catch is CancellationError { - throw CancellationError() - } catch { - guard ChatSendQueueService.isTransientChannelMessageError(error) else { - loggerRef.info("channel drain terminal messageID=\(envelope.messageID) error=\(String(describing: error))") - throw error - } - if ChatSendQueueService.isChannelMessageNotFound(error) { - // Disambiguate pool exhaustion (transient) from a stale - // channel index (terminal) by refreshing the radio's - // view of the channel. `ChannelService.fetchChannel(index:)` - // reads from the device, so a nil result means the radio - // agrees the channel is gone (terminal). - // - // Gate on disambiguateAfterAttempts so the common - // pool-exhaustion burst (1-2 NOT_FOUNDs in a row) parks - // without an extra BLE round-trip; only persistent - // NOT_FOUND warrants the fetchChannel cost. - if postBumpCount < configRef.disambiguateAfterAttempts { - loggerRef.info("channel drain NOT_FOUND below disambiguate threshold messageID=\(envelope.messageID) postBumpCount=\(postBumpCount); parking envelope") - _ = try? await dataStoreRef.updateMessageStatusUnlessDelivered(id: envelope.messageID, status: .pending) - try await ChatSendQueueService.parkAndCancel( - triggers: triggers, - logger: loggerRef, - messageID: envelope.messageID, - kind: "channel", - timeout: configRef.transportWaitTimeout - ) - } - - let stillExists: Bool - do { - stillExists = try await channelServiceRef.fetchChannel(index: envelope.channelIndex) != nil - await failureCounter.reset(for: envelope.messageID) - } catch { - let failures = await failureCounter.increment(for: envelope.messageID) - if failures >= configRef.maxConsecutiveFetchChannelFailures { - loggerRef.warning("Channel drain: fetchChannel persistently failing (\(failures) consecutive) for messageID=\(envelope.messageID); marking terminal") - await failureCounter.reset(for: envelope.messageID) - throw error - } - loggerRef.info("channel drain NOT_FOUND followup fetchChannel failed: \(String(describing: error)); parking envelope (\(failures)/\(configRef.maxConsecutiveFetchChannelFailures))") - _ = try? await dataStoreRef.updateMessageStatusUnlessDelivered(id: envelope.messageID, status: .pending) - try await ChatSendQueueService.parkAndCancel( - triggers: triggers, - logger: loggerRef, - messageID: envelope.messageID, - kind: "channel", - timeout: configRef.transportWaitTimeout - ) - } - if !stillExists { - loggerRef.warning("Channel drain: NOT_FOUND confirmed by fetchChannel for messageID=\(envelope.messageID); treating as terminal (channel deleted)") - await failureCounter.reset(for: envelope.messageID) - throw error - } - // Channel still exists per device — NOT_FOUND was pool - // exhaustion. Park on the transport-open trigger. The - // effective per-attempt cadence under sustained - // exhaustion is ~37s (3.5s withPoolBackoff in-loop + - // 3.5s fetchChannel disambiguation + 30s - // transportWaitTimeout park). Transport-open only fires - // on entering `.ready`, so under a healthy connection - // the 30s park is what bounds the retry rate. - } - loggerRef.info("channel drain transient messageID=\(envelope.messageID) error=\(String(describing: error))") - _ = try? await dataStoreRef.updateMessageStatusUnlessDelivered(id: envelope.messageID, status: .pending) - try await ChatSendQueueService.parkAndCancel( - triggers: triggers, - logger: loggerRef, - messageID: envelope.messageID, - kind: "channel", - timeout: configRef.transportWaitTimeout - ) - } - } catch let cancellation as CancellationError { - throw cancellation - } catch { - await messageServiceRef.notifyMessageFailed(messageID: envelope.messageID) - throw error - } + try await ChatSendQueueService.sendQueuedChannel(envelope: envelope, dependencies: channelDrain) }, onError: { _, envelope in try? await dataStoreRef.deletePendingSendsForMessage(messageID: envelope.messageID) @@ -391,21 +263,62 @@ public final class ChatSendQueueService { ) } - /// Enqueue a DM envelope. Persists a `PendingSend` row first; the - /// queue's drain reads it back on the next send attempt. Throws - /// `ChatSendQueueServiceError.persistFailed` if the SwiftData write - /// fails so the caller can surface the failure instead of silently - /// dropping the queued send. - public func enqueueDM(_ envelope: DirectMessageEnvelope) async throws { + /// Persists the DM envelope before signaling the drain so reconnect can recover it. + func enqueueDM(_ envelope: DirectMessageEnvelope) async throws { + guard beginAdmission() else { throw CancellationError() } + defer { finishAdmission() } try await persist(PendingSendDTO(envelope: envelope, radioID: radioID)) + guard !isRetired else { throw CancellationError() } await dmQueue.enqueue(envelope) } public func enqueueChannel(_ envelope: ChannelMessageEnvelope) async throws { + guard beginAdmission() else { throw CancellationError() } + defer { finishAdmission() } try await persist(PendingSendDTO(envelope: envelope, radioID: radioID)) + guard !isRetired else { throw CancellationError() } await channelQueue.enqueue(envelope) } + public func enqueueReaction(to target: MessageDTO, emoji: String, senderName: String) async throws -> MessageDTO? { + guard target.radioID == radioID else { throw ChatSendQueueServiceError.notConnected } + guard beginAdmission() else { throw CancellationError() } + defer { finishAdmission() } + + let text: String + if target.channelIndex != nil { + guard let targetSender = target.isOutgoing ? senderName : target.senderNodeName else { return nil } + text = reactionService.buildReactionText( + emoji: emoji, targetSender: targetSender, targetText: target.text, targetTimestamp: target.reactionTimestamp + ) + } else { + text = reactionService.buildDMReactionText( + emoji: emoji, targetText: target.text, targetTimestamp: target.reactionTimestamp + ) + } + let model = Message( + radioID: radioID, contactID: target.contactID, channelIndex: target.channelIndex, + text: text, timestamp: UInt32(Date().timeIntervalSince1970), + directionRawValue: MessageDirection.outgoing.rawValue, + statusRawValue: MessageStatus.pending.rawValue + ) + model.reactionTargetMessageID = target.id + model.reactionSenderName = senderName + let pending = MessageDTO(from: model) + try await messageService.validateOutgoingReaction(pending) + guard let message = try await dataStore.admitOutgoingReaction(pending) else { return nil } + guard !isRetired else { return message } + if let channelIndex = message.channelIndex { + await channelQueue.enqueue(ChannelMessageEnvelope( + messageID: message.id, channelIndex: channelIndex, isResend: false, + messageText: message.text, messageTimestamp: message.timestamp, localNodeName: senderName + )) + } else if let contactID = message.contactID { + await dmQueue.enqueue(DirectMessageEnvelope(messageID: message.id, contactID: contactID, isSingleAttempt: true)) + } + return message + } + /// Signals the DM queue that a `PendingSend` row already exists for /// this envelope. Used by the manual retry path where /// `PersistenceStore.replacePendingSendForRetry` has already written @@ -414,14 +327,15 @@ public final class ChatSendQueueService { /// `hasPendingSend` on the next send attempt, so the in-memory /// enqueue is the only step left. public func signalDMEnqueued(_ envelope: DirectMessageEnvelope) async { + guard beginAdmission() else { return } + defer { finishAdmission() } await dmQueue.enqueue(envelope) } /// Starts observing the connection-state stream and fires the /// transport-open trigger exactly once each time the connection enters - /// `.ready`. Gating on `.ready` (not the first `isConnected` edge) keeps - /// hydrated sends parked through the initial-sync window, so they do not - /// contend with sync's reads on the radio's link. In production the container + /// `.ready`. This wakes parked retries after initial sync. Queued channel + /// sends independently verify the current slot before replay. In production the container /// is built while still `.connected`, so the `.ready` wake arrives on the /// event stream; the initial-value check only fires when the observation is /// (re)started against an already-`.ready` connection, waking drains parked in @@ -433,6 +347,7 @@ public final class ChatSendQueueService { initial: DeviceConnectionState, events: AsyncStream ) { + guard !isRetired else { return } connectionStateTask?.cancel() if initial.canDrainSendQueue { transportDidOpen() @@ -460,6 +375,7 @@ public final class ChatSendQueueService { /// to a single armed trigger on the actor. Do not extend this function /// with per-call state — the fire-and-forget shape would lose ordering. func transportDidOpen() { + guard !isRetired else { return } osLogger.debug("transportDidOpen firing trigger") Task { [triggers] in await triggers.fire() @@ -492,18 +408,15 @@ public final class ChatSendQueueService { } } - /// Combines the `hasPendingSend` gate, the top-of-drain `attemptCount` bump, - /// and the `preserveTimestamp` computation that every DM and channel drain - /// runs before any wire-affecting work. Returns nil if the row is gone - /// (terminal — abandon envelope). Throws transient errors so the caller can - /// park and retry; throws nothing on the gate-missing terminal path. + /// Prepares durable work before any radio command and preserves timestamps after the first attempt. + /// A missing row ends the drain; persistence errors let the caller park and retry. nonisolated static func preflightAndBump( dataStore: any MessagePersisting, messageID: UUID, kind: String, logger: PersistentLogger, osLogger: os.Logger - ) async throws -> (postBumpCount: Int, preserveTimestamp: Bool)? { + ) async throws -> (pendingSendID: UUID, postBumpCount: Int, preserveTimestamp: Bool)? { switch await ChatSendQueueService.classifyRead({ () async throws -> Bool? in try await dataStore.hasPendingSend(messageID: messageID) ? true : nil }) { @@ -518,20 +431,57 @@ public final class ChatSendQueueService { } let postBumpCount: Int + let pendingSendID: UUID do { - guard let bumped = try await dataStore.incrementPendingSendAttemptCount(messageID: messageID) else { + guard let bumped = try await dataStore.preparePendingSendAttempt(messageID: messageID) else { logger.info("\(kind) drain: PendingSend row gone for messageID=\(messageID); treating as terminal") return nil } - postBumpCount = bumped + postBumpCount = bumped.attemptCount + pendingSendID = bumped.pendingSendID } catch { - logger.warning("incrementPendingSendAttemptCount failed: \(String(describing: error)); parking envelope for next transport-open") + logger.warning("preparePendingSendAttempt failed: \(String(describing: error)); parking envelope for next transport-open") throw error } let preserveTimestamp = postBumpCount > 1 osLogger.debug("\(kind) drain begin messageID=\(messageID) postBumpCount=\(postBumpCount) preserveTimestamp=\(preserveTimestamp)") - return (postBumpCount: postBumpCount, preserveTimestamp: preserveTimestamp) + return (pendingSendID: pendingSendID, postBumpCount: postBumpCount, preserveTimestamp: preserveTimestamp) + } + + nonisolated static func cancelSendIfRetired(_ sendsRetired: OSAllocatedUnfairLock) throws { + if sendsRetired.withLock({ $0 }) { + throw CancellationError() + } + } + + nonisolated static func validateQueuedChannel( + envelope: ChannelMessageEnvelope, + radioID: UUID, + dataStore: any MessagePersisting, + channelService: ChannelService, + triggers: BLETransportOpenedSignal, + logger: PersistentLogger, + timeout: TimeInterval + ) async throws -> Bool { + do { + try Task.checkCancellation() + guard try await dataStore.hasPendingSend(messageID: envelope.messageID) else { return false } + guard try await channelService.getChannel(radioID: radioID, index: envelope.channelIndex) != nil else { + throw MessageServiceError.channelNotFound + } + try Task.checkCancellation() + return true + } catch MessageServiceError.channelNotFound { + _ = try await dataStore.updateMessageStatusUnlessDelivered(id: envelope.messageID, status: .failed) + throw MessageServiceError.channelNotFound + } catch { + _ = try? await dataStore.updateMessageStatusUnlessDelivered(id: envelope.messageID, status: .pending) + try await parkAndCancel( + triggers: triggers, logger: logger, messageID: envelope.messageID, + kind: "channel", timeout: timeout + ) + } } /// Awaits a transport-open trigger up to the bounded timeout, then throws @@ -565,7 +515,7 @@ public final class ChatSendQueueService { switch serviceError { case let .sessionError(underlying): return isTransientError(underlying, deviceCode: deviceCode) - case .notConnected: + case .notConnected, .persistenceError: return true case .contactNotFound, .channelNotFound, .sendFailed, .invalidRecipient, .messageTooLong: @@ -653,28 +603,19 @@ public final class ChatSendQueueService { // MARK: - Hydration - /// Called once by `ServiceContainer` after construction. Reads - /// every `PendingSend` row for this service's `radioID` and - /// enqueues each envelope. Subsequent calls are no-ops — the - /// service's hydration latch is per-instance, and one instance - /// lives per `ServiceContainer`, so two view models on the same - /// connection cannot trigger duplicate replay. - /// - /// The nullable-attemptCount scheme stores legacy-vs-current-build - /// distinction in the column itself; `PersistenceStore.warmUp()` runs - /// `purgeLegacyAttemptCountRows` before hydrate (wired in - /// `ConnectionManager.buildServicesAndSaveDevice`) so pre-migration `nil` - /// rows are deleted rather than promoted. Race-window rows (persist - /// succeeded, drain bump didn't run) sit at `attemptCount = 0`, bump to - /// `1`, and `preserveTimestamp` = false — correct, because the recipient - /// never saw the packet. + /// Hydrates this Radio ID's pending sends once per service instance before app wiring and sync. + /// `PersistenceStore.warmUp()` must purge legacy nil-attempt rows first; zero-attempt + /// rows represent unsent work and receive a fresh timestamp on their first attempt. func hydrate() async { - guard !hasHydrated else { return } + guard !hasHydrated, beginAdmission() else { return } + defer { finishAdmission() } hasHydrated = true logger.info("hydrate begin radio=\(radioID)") do { let rows = try await dataStore.fetchPendingSends(radioID: radioID) for dto in rows { + guard !isRetired else { return } + guard dto.ackDeadline == nil else { continue } osLogger.debug("hydrate enqueue messageID=\(dto.messageID) kind=\(String(describing: dto.kind)) isResend=\(dto.isResend) attemptCount=\(String(describing: dto.attemptCount))") switch dto.kind { case .dm: @@ -694,6 +635,18 @@ public final class ChatSendQueueService { } #if DEBUG + var isRetiredForTesting: Bool { + isRetired + } + + var parkedDrainCountForTesting: Int { + get async { await triggers.waiterCountForTesting } + } + + var isDMDrainingForTesting: Bool { + get async { await dmQueue.isDrainingForTesting } + } + /// Test-only: drain readiness for synchronizing tests. func awaitDrainCompletion() async { await dmQueue.awaitDrainCompletion() @@ -713,11 +666,41 @@ public final class ChatSendQueueService { /// `EventBroadcaster` subscription so a torn-down container never /// receives the next connection's edge. func shutdown() async { - connectionStateTask?.cancel() + if let shutdownTask { await shutdownTask.value; return } + sendsRetired.withLock { $0 = true } + isRetired = true + let worker = Task { await performShutdown() } + shutdownTask = worker + await worker.value + } + + private func performShutdown() async { + let observer = connectionStateTask connectionStateTask = nil + observer?.cancel() + await observer?.value + if admittedWork != 0 { + await withCheckedContinuation { admissionWaiters.append($0) } + } await dmQueue.cancelDrain() await channelQueue.cancelDrain() } + + func beginAdmission() -> Bool { + guard !isRetired else { return false } + admittedWork += 1 + return true + } + + func finishAdmission() { + admittedWork -= 1 + guard admittedWork == 0 else { return } + let waiters = admissionWaiters + admissionWaiters.removeAll() + for waiter in waiters { + waiter.resume() + } + } } /// Tracks consecutive `fetchChannel` throws inside the channel-drain diff --git a/MC1Services/Sources/MC1Services/Services/CommandAuditLogger.swift b/MC1Services/Sources/MC1Services/Services/CommandAuditLogger.swift index 4fb7bf31a3..4802036240 100644 --- a/MC1Services/Sources/MC1Services/Services/CommandAuditLogger.swift +++ b/MC1Services/Sources/MC1Services/Services/CommandAuditLogger.swift @@ -16,6 +16,15 @@ actor CommandAuditLogger { case repeater = "REPEATER" case room = "ROOM" case contact = "CONTACT" + case sensor = "SENSOR" + } + + static func target(for role: RemoteNodeRole) -> Target { + switch role { + case .repeater: .repeater + case .roomServer: .room + case .sensor: .sensor + } } // MARK: - Properties diff --git a/MC1Services/Sources/MC1Services/Services/ConfigIdentityImportFailure.swift b/MC1Services/Sources/MC1Services/Services/ConfigIdentityImportFailure.swift new file mode 100644 index 0000000000..f02fd0f06d --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/ConfigIdentityImportFailure.swift @@ -0,0 +1,5 @@ +import Foundation + +struct ConfigIdentityImportFailure: Error { + let underlying: any Error +} diff --git a/MC1Services/Sources/MC1Services/Services/ContactCleanupCoordinator.swift b/MC1Services/Sources/MC1Services/Services/ContactCleanupCoordinator.swift index 1c445c94d4..30ffce9a23 100644 --- a/MC1Services/Sources/MC1Services/Services/ContactCleanupCoordinator.swift +++ b/MC1Services/Sources/MC1Services/Services/ContactCleanupCoordinator.swift @@ -36,18 +36,16 @@ struct ContactCleanupCoordinator: ContactCleanupHandling { } // Refresh blocked names cache and delete channel messages on block - if reason == .blocked || reason == .unblocked { - if let contact = try? await dataStore.fetchContact(id: contactID) { - if reason == .blocked { - try? await dataStore.deleteChannelMessages( - fromSender: contact.name, radioID: contact.radioID - ) - } - await syncCoordinator.refreshBlockedContactsCache( - radioID: contact.radioID, dataStore: dataStore + if reason == .blocked || reason == .unblocked, let contact = try? await dataStore.fetchContact(id: contactID) { + if reason == .blocked { + try? await dataStore.deleteChannelMessages( + fromSender: contact.name, radioID: contact.radioID ) - await syncCoordinator.notifyConversationsChanged() } + await syncCoordinator.refreshBlockedContactsCache( + radioID: contact.radioID, dataStore: dataStore + ) + await syncCoordinator.notifyConversationsChanged() } if reason == .blocked { diff --git a/MC1Services/Sources/MC1Services/Services/ContactService.swift b/MC1Services/Sources/MC1Services/Services/ContactService.swift index 269eb7af40..cd4a9bcce6 100644 --- a/MC1Services/Sources/MC1Services/Services/ContactService.swift +++ b/MC1Services/Sources/MC1Services/Services/ContactService.swift @@ -240,34 +240,23 @@ public actor ContactService { await flushDeletionUpdatesIfNeeded(contactIDs: &deletedIDs, force: true) } - /// Full contact sync for a user-initiated refresh. - /// - /// Atomically waits out an advert-driven delta sync and claims the manual - /// refresh flag on the coordinator. Separate wait and claim hops leave a - /// window where a delta can take the claim after the wait returns and before - /// the flag is set; both publish `syncProgress` on the same event stream, so - /// that race jumps the pull-to-refresh counter. Callers still call - /// `AdvertisementService.setSyncingContacts(true)` first so no new delta - /// starts before this claim runs. - /// - /// - Parameter radioID: The device to sync from - /// - Returns: Sync result with count and timestamp + /// Waits out advert sync and inhibits adverts during refresh so progress events cannot interleave. + /// Callers first defer advert scheduling with `AdvertisementService.setSyncingContacts(true)`. public func syncContactsForRefresh(radioID: UUID) async throws -> ContactSyncResult { do { try await syncCoordinator?.claimManualContactSync() } catch is CancellationError { throw CancellationError() } catch { - // Wait timed out while an advert delta still held the claim. Do not - // proceed (races progress) and do not silent-skip: surface so the spinner stops. + // A timed-out advert still owns progress events, so refresh must fail before starting. throw ContactServiceError.syncInterrupted } do { let result = try await syncContacts(radioID: radioID) - await syncCoordinator?.setManualContactSyncActive(false) + await syncCoordinator?.releaseManualContactSync() return result } catch { - await syncCoordinator?.setManualContactSyncActive(false) + await syncCoordinator?.releaseManualContactSync() throw error } } diff --git a/MC1Services/Sources/MC1Services/Services/DMSendBudget.swift b/MC1Services/Sources/MC1Services/Services/DMSendBudget.swift new file mode 100644 index 0000000000..37e6f06ceb --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/DMSendBudget.swift @@ -0,0 +1,64 @@ +import Foundation + +/// Attempts on the current out path, followed by fallback attempts after one out path reset. +public struct DMSendBudget: Sendable, Equatable { + public static let defaultDirectAttempts = 4 + public static let defaultFloodAttempts = 4 + public static let directRange = 1...4 + public static let floodRange = 0...4 + /// Flood Attempts menu. Zero is stored by turning Fall Back to Flood off, not by this menu. + public static let enabledFloodRange = 1...4 + + /// Off stores zero. On stores the default only when the stored count is zero. + public static func floodAttempts(enablingFallback isOn: Bool, stored: Int) -> Int { + guard isOn else { return 0 } + guard stored > 0 else { return defaultFloodAttempts } + return stored + } + + public static func menuFloodAttempts(stored: Int) -> Int { + enabledFloodRange.contains(stored) ? stored : defaultFloodAttempts + } + + public static func clampedMenuFloodAttempts(_ value: Int) -> Int { + clamped(value, to: enabledFloodRange) + } + + static let `default` = DMSendBudget( + directAttempts: defaultDirectAttempts, + floodAttempts: defaultFloodAttempts + ) + static let singleAttempt = DMSendBudget(directAttempts: 1, floodAttempts: 0) + + public let directAttempts: Int + public let floodAttempts: Int + public var totalAttempts: Int { + directAttempts + floodAttempts + } + + public init(directAttempts: Int, floodAttempts: Int) { + self.directAttempts = Self.clampedDirectAttempts(directAttempts) + self.floodAttempts = Self.clampedFloodAttempts(floodAttempts) + } + + public static func current(defaults: UserDefaults = .standard) -> DMSendBudget { + let storedDirect = defaults.object(forKey: AppStorageKey.dmDirectAttempts.rawValue) as? Int + let storedFlood = defaults.object(forKey: AppStorageKey.dmFloodAttempts.rawValue) as? Int + return DMSendBudget( + directAttempts: storedDirect ?? defaultDirectAttempts, + floodAttempts: storedFlood ?? defaultFloodAttempts + ) + } + + public static func clampedDirectAttempts(_ value: Int) -> Int { + clamped(value, to: directRange) + } + + public static func clampedFloodAttempts(_ value: Int) -> Int { + clamped(value, to: floodRange) + } + + private static func clamped(_ value: Int, to range: ClosedRange) -> Int { + min(max(value, range.lowerBound), range.upperBound) + } +} diff --git a/MC1Services/Sources/MC1Services/Services/DebugLogBuffer.swift b/MC1Services/Sources/MC1Services/Services/DebugLogBuffer.swift index fa240d1411..ff8ae892e6 100644 --- a/MC1Services/Sources/MC1Services/Services/DebugLogBuffer.swift +++ b/MC1Services/Sources/MC1Services/Services/DebugLogBuffer.swift @@ -4,23 +4,27 @@ import os /// Actor for buffering debug log entries and flushing to persistence. /// Provides batched saves for performance and backpressure handling. public actor DebugLogBuffer { - /// The current shared buffer and the entries recorded while none exists, behind - /// one lock so `record` and the `shared` setter are atomic with respect to each - /// other: an entry either reaches the current buffer or waits in `pending` for - /// the next assignment to drain; it can't fall between the two. + /// `record` and the `shared` setter share this lock, so an entry reaches the current buffer or waits in `pending`. private struct SharedState { var buffer: DebugLogBuffer? var pending: [DebugLogEntryDTO] = [] } private static let sharedState = OSAllocatedUnfairLock(initialState: SharedState()) + /// In-progress `disableCollection` calls. The off write and `enableCollection` share this lock, so a turn-on during the wipe cannot land true. + private struct CollectionDisable { + var depth = 0 + } + + private static let collectionDisable = OSAllocatedUnfairLock(initialState: CollectionDisable()) static let maxPendingEntries = 500 - /// Shared buffer instance for app-wide logging. Reassigned on every connection - /// from `ServiceContainer.init` while `PersistentLogger` records from arbitrary - /// actors. Assigning a buffer atomically takes every entry recorded while none - /// existed (early launch, CoreBluetooth state restoration, background relaunch, - /// between connections) and delivers them to the new buffer in record order. + /// Missing `collectDebugLogs` reads as off. Checked on every `record` from `UserDefaults.standard`, the domain `@AppStorage` writes. + nonisolated static var isCollectionEnabled: Bool { + UserDefaults.standard.bool(forKey: AppStorageKey.collectDebugLogs.rawValue) + } + + /// Reassigned from `ServiceContainer.init` while `PersistentLogger` records from other actors. Assignment drains `pending` in record order. public static var shared: DebugLogBuffer? { get { sharedState.withLock { $0.buffer } } set { @@ -39,11 +43,11 @@ public actor DebugLogBuffer { } } - /// Single entry point for app-wide log delivery: hands `entry` to the current - /// shared buffer, or queues it (bounded, oldest dropped first) until one is - /// assigned. + /// Hands `entry` to the shared buffer, or queues it (oldest dropped past the bound) until one is assigned. + /// Drops it when collection is off. Only `disableCollection` discards entries already queued. static func record(_ entry: DebugLogEntryDTO) { let buffer = sharedState.withLock { state -> DebugLogBuffer? in + guard isCollectionEnabled else { return nil } if let buffer = state.buffer { return buffer } state.pending.append(entry) if state.pending.count > maxPendingEntries { @@ -55,8 +59,47 @@ public actor DebugLogBuffer { Task { await buffer.append(entry) } } - /// Empties the pending queue so tests can exercise the no-buffer window from a - /// known state. + /// Turns collection on unless `disableCollection` is in progress, which leaves the key false. + public static func enableCollection() { + let allowed = collectionDisable.withLock { $0.depth == 0 } + guard allowed else { return } + UserDefaults.standard.set(true, forKey: AppStorageKey.collectDebugLogs.rawValue) + collectionDisable.withLock { state in + guard state.depth > 0 else { return } + UserDefaults.standard.set(false, forKey: AppStorageKey.collectDebugLogs.rawValue) + } + } + + /// Sets the key false and holds it until this returns, including on throw. + /// Waits out an in-flight `saveDebugLogEntries`, drops memory, then deletes rows, so that save cannot finish after the delete. + /// A throw leaves the key false and the rows; the caller turns the key back on. + public static func disableCollection(persistenceStore: any DebugLogPersisting) async throws { + beginCollectionDisable() + defer { endCollectionDisable() } + let buffer = sharedState.withLock { state -> DebugLogBuffer? in + state.pending = [] + return state.buffer + } + if let buffer { + await buffer.relinquishForDisable() + } + try await persistenceStore.clearDebugLogEntries() + } + + private static func beginCollectionDisable() { + collectionDisable.withLock { state in + state.depth += 1 + UserDefaults.standard.set(false, forKey: AppStorageKey.collectDebugLogs.rawValue) + } + } + + private static func endCollectionDisable() { + collectionDisable.withLock { state in + state.depth -= 1 + } + } + + /// Empties `pending` so a test starts from the no-buffer window. static func resetPendingStateForTesting() { sharedState.withLock { $0.pending = [] } } @@ -71,16 +114,17 @@ public actor DebugLogBuffer { /// repeat the connect-time `pruneDebugLogEntries` on this store. private var lastPrune = Date() - /// Entries lost since the last successful save, to a save failure or the requeue - /// cap. Reported as a synthesized log entry on the next successful save, since - /// those windows are otherwise invisible in the persisted log itself. + /// Entries lost since the last successful save. The next successful save reports them, because that window is otherwise invisible. private var droppedEntryCount = 0 - /// Guards `persistDropSummaryIfNeeded` against reentrancy: `flushBuffer` runs - /// concurrently with itself via `flushNow`'s unstructured task, and two flushes - /// succeeding together must not persist duplicate summaries. + /// `flushBuffer` can overlap itself through `flushNow`. Two successes must not persist two drop summaries. private var isPersistingDropSummary = false + /// `flushBuffer` calls past the collection gate that have not returned. + /// `disableCollection` waits for zero before deleting rows, so an in-flight save cannot finish after the delete. + private var persistsInFlight = 0 + private var persistIdleWaiters: [CheckedContinuation] = [] + private static let logSubsystem = "com.mc1" private static let logCategory = "DebugLogBuffer" private static let logger = Logger(subsystem: logSubsystem, category: logCategory) @@ -90,6 +134,7 @@ public actor DebugLogBuffer { } public func append(_ entry: DebugLogEntryDTO) { + guard Self.isCollectionEnabled else { return } buffer.append(entry) if buffer.count >= Self.maxBufferSize { @@ -113,6 +158,45 @@ public actor DebugLogBuffer { await flushBuffer() } + /// Discards unflushed entries and cancels the scheduled flush without saving. + public func discardPendingEntries() { + flushTask?.cancel() + flushTask = nil + isFlushScheduled = false + buffer = [] + } + + /// Waits out in-flight saves, then drops memory. The key is already false, so a flush started during the wait does not publish. + private func relinquishForDisable() async { + flushTask?.cancel() + flushTask = nil + isFlushScheduled = false + await waitForPersistsToIdle() + discardPendingEntries() + droppedEntryCount = 0 + } + + private func waitForPersistsToIdle() async { + guard persistsInFlight > 0 else { return } + await withCheckedContinuation { continuation in + persistIdleWaiters.append(continuation) + } + } + + private func beginPersist() { + persistsInFlight += 1 + } + + private func endPersist() { + persistsInFlight -= 1 + guard persistsInFlight == 0 else { return } + let waiters = persistIdleWaiters + persistIdleWaiters.removeAll() + for waiter in waiters { + waiter.resume() + } + } + private func scheduleFlush() { guard !isFlushScheduled else { return } isFlushScheduled = true @@ -134,15 +218,24 @@ public actor DebugLogBuffer { private func flushBuffer() async { guard !buffer.isEmpty else { return } + guard Self.isCollectionEnabled else { + buffer = [] + return + } + beginPersist() + defer { endPersist() } + let entries = buffer buffer = [] do { try await dataStore.saveDebugLogEntries(entries) + guard Self.isCollectionEnabled else { return } await persistDropSummaryIfNeeded() await pruneIfDue() } catch { Self.logger.error("Failed to save debug logs: \(error.localizedDescription)") + guard Self.isCollectionEnabled else { return } // Backpressure: only re-queue if total won't exceed limit let entriesToRequeue = Array(entries.prefix(Self.maxBufferSize)) @@ -172,11 +265,8 @@ public actor DebugLogBuffer { } } - /// Persists a summary of entries dropped since the last successful save. Left - /// uncounted on failure so the loss carries forward to the next attempt instead - /// of being silently reset. Snapshots the count before the save because the - /// actor is reentrant across that await: drops recorded while the save is - /// suspended must survive, so only the reported amount is subtracted on success. + /// Reports drops since the last successful save, and leaves the count on failure so the loss carries forward. + /// Snapshots the count before the save. The actor is reentrant across that await, so only the reported amount is subtracted. private func persistDropSummaryIfNeeded() async { guard droppedEntryCount > 0, !isPersistingDropSummary else { return } isPersistingDropSummary = true diff --git a/MC1Services/Sources/MC1Services/Services/DeviceService.swift b/MC1Services/Sources/MC1Services/Services/DeviceService.swift index d176ba6042..0056abdb64 100644 --- a/MC1Services/Sources/MC1Services/Services/DeviceService.swift +++ b/MC1Services/Sources/MC1Services/Services/DeviceService.swift @@ -58,22 +58,15 @@ public actor DeviceService { ) async throws { logger.info("Updating OCV settings for device \(deviceID): preset=\(preset)") - // Fetch current device - guard var device = try await dataStore.fetchDevice(id: deviceID) else { - logger.error("Device not found: \(deviceID)") - throw DeviceServiceError.deviceNotFound - } - - // Update OCV fields - device = device.copy { - $0.ocvPreset = preset - $0.customOCVArrayString = customArray - } - - // Save to persistence + let device: DeviceDTO do { - try await dataStore.saveDevice(device) + guard let updated = try await dataStore.updateDeviceOCVSettings( + id: deviceID, preset: preset, customArray: customArray + ) else { throw DeviceServiceError.deviceNotFound } + device = updated logger.info("OCV settings saved successfully") + } catch let error as DeviceServiceError { + throw error } catch { logger.error("Failed to save OCV settings: \(error.localizedDescription)") throw DeviceServiceError.persistenceFailed(error.localizedDescription) diff --git a/MC1Services/Sources/MC1Services/Services/DirectMessageAdmission.swift b/MC1Services/Sources/MC1Services/Services/DirectMessageAdmission.swift new file mode 100644 index 0000000000..313b2f4e8f --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/DirectMessageAdmission.swift @@ -0,0 +1,8 @@ +import Foundation + +public enum DirectMessageAdmission: Sendable { + case discarded + case replay(MessageDTO) + case reaction(ContactDTO) + case saved(ContactDTO?) +} diff --git a/MC1Services/Sources/MC1Services/Services/HeardRepeatsService.swift b/MC1Services/Sources/MC1Services/Services/HeardRepeatsService.swift index c7c3cf9365..ff2d255f5b 100644 --- a/MC1Services/Sources/MC1Services/Services/HeardRepeatsService.swift +++ b/MC1Services/Sources/MC1Services/Services/HeardRepeatsService.swift @@ -130,6 +130,7 @@ public actor HeardRepeatsService { private func recordSentEcho(message: MessageDTO, entry: RxLogEntryDTO) async throws -> Int? { guard let newCount = try await dataStore.admitSentEcho( messageID: message.id, + expectedTimestamp: message.timestamp, receivedAt: entry.receivedAt, pathNodes: entry.pathNodes, pathLength: entry.pathLength, diff --git a/MC1Services/Sources/MC1Services/Services/LoginResult.swift b/MC1Services/Sources/MC1Services/Services/LoginResult.swift index 1d0d2488d8..1eea3e8b61 100644 --- a/MC1Services/Sources/MC1Services/Services/LoginResult.swift +++ b/MC1Services/Sources/MC1Services/Services/LoginResult.swift @@ -22,6 +22,10 @@ public struct LoginResult: Sendable { self.serverTime = serverTime } + public func permissionLevel(for role: RemoteNodeRole) -> RoomPermissionLevel { + role == .sensor ? (isAdmin ? .admin : .guest) : permissionLevel + } + public var permissionLevel: RoomPermissionLevel { isAdmin ? .admin : (RoomPermissionLevel(rawValue: aclPermissions ?? 0) ?? .guest) } diff --git a/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift b/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift index 69b19306ab..a50238fecf 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift @@ -210,6 +210,7 @@ public enum MessageFragmentBuilder { envInputs: EnvInputs ) -> MessageFooter { let showHop = envInputs.showIncomingHopCount && message.isFloodRouted && !message.isOutgoing + && message.hopCount != nil let showHeardCount = envInputs.showIncomingHeardCount && !message.isOutgoing && message.heardRepeats > 0 @@ -238,7 +239,7 @@ public enum MessageFragmentBuilder { let sendTimeToShow: Date? = message.senderDate return MessageFooter( showHop: showHop, - hopCount: message.hopCount, + hopCount: message.hopCount ?? 0, formattedPath: inputs.formattedPath, regionToShow: regionToShow, regionMatchNames: regionMatchNames, diff --git a/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift b/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift index fe08727b95..8b88fe21b7 100644 --- a/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift +++ b/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift @@ -29,19 +29,21 @@ actor MessagePollingService { private let session: any MeshCoreSessionProtocol private let dataStore: any PersistenceStoreProtocol + let receiveLifetime: ReceiveScope.Lifetime + let textRulesPreference: @Sendable () async -> TextRulesPreference? private let logger = PersistentLogger(subsystem: "com.mc1", category: "MessagePolling") /// Handler for incoming contact messages. /// Installed by `SyncCoordinator.wireMessageHandlers`; cleared by `clearMessageHandlers`. - private var contactMessageHandler: (@Sendable (ContactMessage, ContactDTO?, DeliveryContext) async -> Void)? + private var contactMessageHandler: (@Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void)? /// Handler for incoming channel messages. /// Installed by `SyncCoordinator.wireMessageHandlers`; cleared by `clearMessageHandlers`. - private var channelMessageHandler: (@Sendable (ChannelMessage, ChannelDTO?, DeliveryContext) async -> Void)? + private var channelMessageHandler: (@Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void)? /// Handler for signed messages (from room servers). /// Installed by `SyncCoordinator.wireMessageHandlers`; cleared by `clearMessageHandlers`. - private var signedMessageHandler: (@Sendable (ContactMessage, ContactDTO?) async -> Void)? + private var signedMessageHandler: (@Sendable (ContactMessage, ReceiveScope) async -> Void)? /// Handler for CLI responses (textType = 0x01). /// Installed by `SyncCoordinator.wireMessageHandlers`; cleared by `clearMessageHandlers`. @@ -49,6 +51,8 @@ actor MessagePollingService { /// Event monitoring task private var eventMonitorTask: Task? + private var eventSubscription: Task<(id: UUID, stream: AsyncStream), Never>? + private var isSuspendedForRadioErase = false /// Whether auto-fetch is currently enabled private var isAutoFetchEnabled = false @@ -68,10 +72,16 @@ actor MessagePollingService { init( session: any MeshCoreSessionProtocol, - dataStore: any PersistenceStoreProtocol + dataStore: any PersistenceStoreProtocol, + radioID: UUID? = nil, + textRulesPreference: @escaping @Sendable () async -> TextRulesPreference? = { nil }, + receiveLifetime: ReceiveScope.Lifetime = .init() ) { self.session = session self.dataStore = dataStore + currentRadioID = radioID + self.textRulesPreference = textRulesPreference + self.receiveLifetime = receiveLifetime } deinit { @@ -81,17 +91,17 @@ actor MessagePollingService { // MARK: - Event Handlers /// Set handler for incoming contact messages - func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext) async -> Void) { + func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void) { contactMessageHandler = handler } /// Set handler for incoming channel messages - func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext) async -> Void) { + func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void) { channelMessageHandler = handler } /// Set handler for signed messages (from room servers) - func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) { + func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ReceiveScope) async -> Void) { signedMessageHandler = handler } @@ -132,7 +142,7 @@ actor MessagePollingService { if isAutoFetchEnabled { await stopAutoFetch() } else { - stopEventMonitoring() + await stopEventMonitoring() currentRadioID = nil } } @@ -167,7 +177,7 @@ actor MessagePollingService { await session.stopAutoMessageFetching() // Stop event monitoring - stopEventMonitoring() + await stopEventMonitoring() logger.info("Auto-fetch stopped") } @@ -185,6 +195,35 @@ actor MessagePollingService { await session.startAutoMessageFetching() } + func suspendForRadioErase() async throws { + guard !isPolling else { throw MessagePollingError.pollingFailed } + guard !isSuspendedForRadioErase else { return } + isSuspendedForRadioErase = true + do { + try await session.suspendMessageFetching() + } catch { + isSuspendedForRadioErase = false + throw error + } + + // Finishing the stream lets the handler commit a reply already in its buffer. + if let eventSubscription, let eventMonitorTask { + await session.finishEvents(id: eventSubscription.value.id) + await eventMonitorTask.value + } + } + + func resumeAfterRadioErase() async { + guard isSuspendedForRadioErase, receiveLifetime.isCurrent else { return } + isSuspendedForRadioErase = false + if eventMonitorTask != nil || isAutoFetchEnabled { + startEventMonitoring() + _ = await eventSubscription?.value + } + guard receiveLifetime.isCurrent else { return } + await session.resumeMessageFetching() + } + /// Check if auto-fetch is currently enabled var isAutoFetching: Bool { isAutoFetchEnabled @@ -205,6 +244,7 @@ actor MessagePollingService { /// Poll all waiting messages from the device. /// - Returns: Count of messages retrieved func pollAllMessages() async throws -> Int { + guard !isSuspendedForRadioErase else { throw CancellationError() } isPolling = true defer { isPolling = false } var count = 0 @@ -254,23 +294,29 @@ actor MessagePollingService { /// Start monitoring MeshCore events for messages private func startEventMonitoring() { + guard !isSuspendedForRadioErase else { return } eventMonitorTask?.cancel() - - eventMonitorTask = Task { [weak self] in - guard let self else { return } - let events = await session.events(filter: EventFilter.anyContactMessage.or(.anyChannelMessage)) - + let subscription = Task { [session] in + await session.eventsTracked(filter: EventFilter.anyContactMessage.or(.anyChannelMessage)) + } + eventSubscription = subscription + eventMonitorTask = Task { [weak self, session] in + let (id, events) = await subscription.value for await event in events { - guard !Task.isCancelled else { break } + guard !Task.isCancelled, let self else { break } await handleEvent(event) } + await session.finishEvents(id: id) } } /// Stop monitoring events - private func stopEventMonitoring() { - eventMonitorTask?.cancel() + private func stopEventMonitoring() async { + let eventMonitorTaskToStop = eventMonitorTask eventMonitorTask = nil + eventSubscription = nil + eventMonitorTaskToStop?.cancel() + await eventMonitorTaskToStop?.value } /// Handle incoming MeshCore event @@ -299,45 +345,43 @@ actor MessagePollingService { private func handleContactMessage(_ message: ContactMessage, context: DeliveryContext) async { guard let radioID = currentRadioID else { logger.warning("Received message but no radio ID set") - await contactMessageHandler?(message, nil, context) return } - // Look up the sender contact - let contact = try? await dataStore.fetchContact( - radioID: radioID, - publicKeyPrefix: message.senderPublicKeyPrefix - ) - - // Route based on text type switch message.textType { case MeshTextType.cliData.rawValue: - // CLI responses from repeaters (textType = 0x01) + let contact = try? await dataStore.fetchContact( + radioID: radioID, + publicKeyPrefix: message.senderPublicKeyPrefix + ) await cliMessageHandler?(message, contact) case MeshTextType.signedPlain.rawValue: - // Signed messages from room servers (textType = 0x02) - await signedMessageHandler?(message, contact) - case MeshTextType.cliCommand.rawValue: - // Queued, not executed. Same path as plain so it is not treated as a CLI reply. - await contactMessageHandler?(message, contact, context) + guard let scope = try? await dataStore.captureReceiveScope(radioID: radioID, link: receiveLifetime) else { + return + } + await signedMessageHandler?(message, scope) default: - // Regular contact messages (textType = 0x00 or unknown) - await contactMessageHandler?(message, contact, context) + // Plain and queued CLI commands both follow ordinary DM delivery. + guard let scope = try? await dataStore.captureReceiveScope(radioID: radioID, link: receiveLifetime) else { + return + } + let preference = await textRulesPreference() + let contact = try? await dataStore.fetchContact( + radioID: radioID, + publicKeyPrefix: message.senderPublicKeyPrefix + ) + await contactMessageHandler?(message, contact, context, scope, preference) } } - /// Handle incoming channel message private func handleChannelMessage(_ message: ChannelMessage, context: DeliveryContext) async { - guard let radioID = currentRadioID else { - logger.warning("Received channel message but no radio ID set") - await channelMessageHandler?(message, nil, context) - return - } - - // Look up the channel + let arrivedAt = Date() + guard let radioID = currentRadioID, + let scope = try? await dataStore.captureReceiveScope(radioID: radioID, link: receiveLifetime) else { return } + let preference = await textRulesPreference() let channel = try? await dataStore.fetchChannel(radioID: radioID, index: message.channelIndex) - - await channelMessageHandler?(message, channel, context) + guard scope.isCurrent else { return } + await channelMessageHandler?(message, channel, context, scope, preference, arrivedAt) } } diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+ACK.swift b/MC1Services/Sources/MC1Services/Services/MessageService+ACK.swift index fe3f228465..4663a2b09e 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+ACK.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+ACK.swift @@ -50,9 +50,11 @@ public extension MessageService { /// (`stopAndFailAllPending()` does both). This is the stop variant used on /// a routine disconnect: in-flight DMs stay `.sent` so a reconnect within /// the same session can still receive the ACK. - func stopAckExpiryChecking() { - ackCheckTask?.cancel() + func stopAckExpiryChecking() async { + let worker = ackCheckTask ackCheckTask = nil + worker?.cancel() + await worker?.value } /// Checks for expired ACKs and advances their delivery state. @@ -67,32 +69,37 @@ public extension MessageService { /// /// - Throws: Database errors when updating message status func checkExpiredAcks() async throws { + await retryPendingAcknowledgementSaves() let now = Date() let window = config.ackGiveUpWindow let expiredEntries = pendingAcks.filter { _, tracking in - !tracking.isDelivered && - now.timeIntervalSince(tracking.sentAt) > max(window, tracking.timeout) + !tracking.isResolved && + now > tracking.expiresAt(giveUpWindow: window) } - for (messageID, snapshot) in expiredEntries { + for (messageID, tracking) in expiredEntries { #if DEBUG if let gate = ackExpiryWriteGateForTesting { await gate(messageID) } #endif guard let current = pendingAcks[messageID], - !current.isDelivered, - current.sentAt == snapshot.sentAt, - now.timeIntervalSince(current.sentAt) > max(window, current.timeout) else { continue } - - let didFail = try await dataStore.updateMessageStatusUnlessDelivered(id: messageID, status: .failed) - guard let removed = pendingAcks.removeValue(forKey: messageID), - !removed.isDelivered, didFail else { continue } + !current.isResolved, + current.sentAt == tracking.sentAt, + now > current.expiresAt(giveUpWindow: window) else { continue } + + let result: PendingAcknowledgementCommit + do { + result = try await commitPendingAcknowledgement(messageID: messageID, sentAt: tracking.sentAt) + } catch { + logger.error("ACK expiry check failed: \(error.localizedDescription)") + continue + } + guard case let .committed(status) = result, status == .failed else { continue } - let deadline = max(window, removed.timeout) - logger.warning("[ack-diag] give-up: failed after \(String(format: "%.1f", now.timeIntervalSince(removed.sentAt)))s window=\(window)s deadline=\(String(format: "%.1f", deadline))s livePending=\(pendingAcks.count)") - statusEventBroadcaster.yield(.failed(messageID: messageID)) + let deadline = max(window, tracking.timeout) + logger.warning("[ack-diag] give-up: failed after \(String(format: "%.1f", now.timeIntervalSince(tracking.sentAt)))s window=\(window)s deadline=\(String(format: "%.1f", deadline))s livePending=\(pendingAcks.count)") } } @@ -102,13 +109,14 @@ public extension MessageService { /// /// - Throws: Database errors when updating message status func failAllPendingMessages() async throws { - let pending = pendingAcks.filter { !$0.value.isDelivered } - pendingAcks.removeAll() - - for (messageID, _) in pending { - let didFail = try await dataStore.updateMessageStatusUnlessDelivered(id: messageID, status: .failed) - if didFail { - statusEventBroadcaster.yield(.failed(messageID: messageID)) + let pending = Array(pendingAcks) + + for (messageID, tracking) in pending { + guard pendingAcks[messageID]?.sentAt == tracking.sentAt, pendingAcks[messageID]?.isResolved == false else { continue } + do { + _ = try await commitPendingAcknowledgement(messageID: messageID, sentAt: tracking.sentAt) + } catch { + logger.error("Failed to fail pending message: \(error.localizedDescription)") } } } @@ -122,8 +130,7 @@ public extension MessageService { /// /// - Throws: Database errors when updating message status func stopAndFailAllPending() async throws { - ackCheckTask?.cancel() - ackCheckTask = nil + await stopAckExpiryChecking() try await failAllPendingMessages() } @@ -139,4 +146,74 @@ public extension MessageService { var isAckExpiryCheckingActive: Bool { ackCheckTask != nil } + + func commitLiveAcknowledgement(code: Data, tripTime: UInt32?) async -> Bool { + guard let (messageID, tracking) = pendingAcks.first(where: { + $0.value.ackCodes.contains(code) && !$0.value.isResolved + }) else { return false } + pendingAcks[messageID]?.recordAcknowledgement(code: code.ackCodeUInt32, tripTime: tripTime) + do { + _ = try await commitPendingAcknowledgement(messageID: messageID, sentAt: tracking.sentAt) + } catch { + logger.error("Failed to write delivered status: \(error.localizedDescription)") + } + return true + } + + /// Matches an ACK against attempt bytes already handed to the radio for a queued direct message. + /// The row stays queued until a match, so the give-up timer does not fail it while it is parked. + func claimQueuedDirectMessageAcknowledgement(code: Data, tripTime: UInt32?) async { + guard let senderPublicKey = await session.currentSelfInfo?.publicKey else { + await logUnmatchedAcknowledgement(code) + return + } + do { + let queued = try await dataStore.queuedDirectMessageWireAttempts() + for row in queued where row.consumedAttempts > 0 { + var prior: UInt8 = 0 + var matched = false + while prior < row.consumedAttempts { + let expected = AckCodeBuilder.expectedAck( + timestamp: row.timestamp, + attempt: prior, + text: row.text, + senderPublicKey: senderPublicKey + ) + if expected == code { + matched = true + break + } + prior += 1 + } + guard matched else { continue } + guard let message = try await dataStore.deliverQueuedDirectMessage( + pendingSendID: row.pendingSendID, + ackCode: code.ackCodeUInt32, + roundTripTime: tripTime + ) else { continue } + await discardTrackedAck(messageID: message.id) + if let contactID = message.contactID { + do { + try await dataStore.updateContactLastMessage(contactID: contactID, date: Date()) + } catch { + logger.error("Failed to update contact lastMessageDate: \(error.localizedDescription)") + } + } + await notifyOutgoingReactionAccepted(messageID: message.id) + statusEventBroadcaster.yield(.statusResolved( + messageID: message.id, status: .delivered, roundTripTime: tripTime + )) + return + } + if await commitLiveAcknowledgement(code: code, tripTime: tripTime) { return } + await logUnmatchedAcknowledgement(code) + } catch { + logger.error("Queued direct-message ACK claim failed: \(error.localizedDescription)") + } + } + + private func logUnmatchedAcknowledgement(_ code: Data) async { + let orphanSentRow = await (try? dataStore.hasOutgoingSentDM(ackCode: code.ackCodeUInt32)) ?? false + logger.warning("[ack-diag] unmatched ACK code=\(code.uppercaseHexString()) livePending=\(pendingAcks.count) orphanSentRow=\(orphanSentRow) (late post-teardown or duplicate)") + } } diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift b/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift new file mode 100644 index 0000000000..355346e1a1 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift @@ -0,0 +1,216 @@ +import Foundation + +enum PendingAcknowledgementCommit { + case committed(MessageStatus) + case unchanged +} + +extension MessageService { + func restorePendingAcknowledgements(radioID: UUID) async throws { + var restored: [UUID: PendingAck] = [:] + for row in try await dataStore.fetchPendingSends(radioID: radioID) { + guard let codes = row.ackCodes, let sentAt = row.ackSentAt, + let deadline = row.ackDeadline, let contactID = row.contactID else { continue } + guard let message = try await dataStore.fetchMessage(id: row.messageID), + message.status != .delivered, message.status != .failed else { + try await dataStore.deletePendingSend(id: row.id) + continue + } + restored[row.messageID] = PendingAck( + messageID: row.messageID, contactID: contactID, ackCodes: Set(codes), + sentAt: sentAt, timeout: deadline.timeIntervalSince(sentAt), + owner: .init(id: row.id, radioID: radioID, deadline: deadline, phase: .saved) + ) + } + let now = Date() + for (id, tracking) in restored { + if let owner = tracking.owner, owner.deadline > now { + restored[id]?.sendLeaseID = owner.id + } + } + // Reserve recovered ACK owners before hydration can admit another send. + await plainTextSendGate?.reserveRestoredAcks(Set(restored.values.compactMap(\.sendLeaseID))) + pendingAcks.merge(restored) { _, restored in restored } + } + + @discardableResult + func persistAcknowledgement(messageID: UUID, radioID: UUID, pendingSendID: UUID?) async -> Bool { + pendingAcks[messageID]?.prepareOwner( + radioID: radioID, pendingSendID: pendingSendID, giveUpWindow: config.ackGiveUpWindow + ) + if let tracking = pendingAcks[messageID], tracking.owner?.phase == .saved, + tracking.matchedAckCode != nil { + do { + _ = try await commitPendingAcknowledgement(messageID: messageID, sentAt: tracking.sentAt) + } catch { + logger.warning("ACK resolution deferred messageID=\(messageID): \(String(describing: error))") + } + return false + } + return await saveAcknowledgementOwner(messageID: messageID) + } + + private func saveAcknowledgementOwner(messageID: UUID) async -> Bool { + guard !acknowledgementSavesInFlight.contains(messageID), + let owner = pendingAcks[messageID]?.beginOwnerSave(), + let tracking = pendingAcks[messageID] else { return false } + acknowledgementSavesInFlight.insert(messageID) + defer { endAcknowledgementSave(messageID) } + + let row = PendingSendDTO( + id: owner.id, envelope: DirectMessageEnvelope(messageID: messageID, contactID: tracking.contactID), + radioID: owner.radioID, enqueuedAt: tracking.sentAt, + ackCodes: Array(tracking.ackCodes), ackSentAt: tracking.sentAt, ackDeadline: owner.deadline + ) + #if DEBUG + if let gate = acknowledgementSaveGateForTesting { await gate() } + #endif + let saved: Bool + do { + saved = try await dataStore.savePendingAcknowledgement( + row, + replacingPendingSendID: owner.phase == .saving(.convert) ? owner.id : nil, + markSent: tracking.commandAccepted + ) + } catch { + if pendingAcks[messageID]?.owner == owner, pendingAcks[messageID]?.sentAt == tracking.sentAt { + pendingAcks[messageID]?.finishOwnerSave(succeeded: false) + } + logger.warning("ACK owner save deferred messageID=\(messageID): \(String(describing: error))") + return false + } + + guard let current = pendingAcks[messageID], current.owner == owner, + current.sentAt == tracking.sentAt, !current.isResolved else { + if saved { + await cleanUpStaleAcknowledgementOwner(tracking, owner: owner) + } + return false + } + guard saved else { + await discardTrackedAck(messageID: messageID) + return false + } + + pendingAcks[messageID]?.finishOwnerSave(succeeded: true) + if current.matchedAckCode != nil { + do { + _ = try await commitPendingAcknowledgement(messageID: messageID, sentAt: current.sentAt) + return false + } catch { + logger.warning("ACK resolution deferred messageID=\(messageID): \(String(describing: error))") + return pendingAcks[messageID]?.owner?.id == owner.id + } + } + return true + } + + func retryPendingAcknowledgementSaves() async { + for messageID in pendingAcks.keys { + if await saveAcknowledgementOwner(messageID: messageID) { + await notifyOutgoingReactionAccepted(messageID: messageID) + if let status = try? await dataStore.fetchMessage(id: messageID)?.status { + statusEventBroadcaster.yield(.statusResolved(messageID: messageID, status: status, roundTripTime: nil)) + } + } + } + } + + func waitForAcknowledgementSaves() async { + guard !acknowledgementSavesInFlight.isEmpty else { return } + await withCheckedContinuation { continuation in + acknowledgementSaveWaiters.append(continuation) + } + } + + func commitPendingAcknowledgement(messageID: UUID, sentAt: Date) async throws -> PendingAcknowledgementCommit { + guard pendingAcks[messageID]?.sentAt == sentAt, + let status = pendingAcks[messageID]?.beginResolution(), + let current = pendingAcks[messageID] else { return .unchanged } + let leaseID = current.sendLeaseID + let updated: Bool + do { + updated = try await writeTerminalAcknowledgement(current, status: status) + } catch { + if pendingAcks[messageID]?.sentAt == sentAt { + pendingAcks[messageID]?.resolutionSaveFailed() + } + throw error + } + guard pendingAcks[messageID]?.sentAt == sentAt else { + return updated ? .committed(status) : .unchanged + } + pendingAcks[messageID]?.resolutionSaveSucceeded() + if current.owner == nil, let installedOwner = pendingAcks[messageID]?.owner { + await cleanUpStaleAcknowledgementOwner(current, owner: installedOwner) + } + if updated, status == .delivered { + do { + try await dataStore.updateContactLastMessage(contactID: current.contactID, date: Date()) + } catch { + logger.error("Failed to update contact lastMessageDate: \(error.localizedDescription)") + } + } + let tripTime = current.matchedTripTime + if pendingAcks[messageID]?.sentAt == sentAt { + pendingAcks.removeValue(forKey: messageID) + } + await settlePlainTextLease(leaseID) + guard updated else { return .unchanged } + switch status { + case .delivered: + await notifyOutgoingReactionAccepted(messageID: messageID) + statusEventBroadcaster.yield(.statusResolved(messageID: messageID, status: .delivered, roundTripTime: tripTime)) + case .failed: + statusEventBroadcaster.yield(.failed(messageID: messageID)) + default: + break + } + return .committed(status) + } + + private func endAcknowledgementSave(_ messageID: UUID) { + acknowledgementSavesInFlight.remove(messageID) + guard acknowledgementSavesInFlight.isEmpty else { return } + let waiters = acknowledgementSaveWaiters + acknowledgementSaveWaiters.removeAll() + for waiter in waiters { + waiter.resume() + } + } + + private func writeTerminalAcknowledgement(_ current: PendingAck, status: MessageStatus) async throws -> Bool { + if let owner = current.owner { + return try await dataStore.resolvePendingAcknowledgement( + id: owner.id, expectedDeadline: owner.deadline, status: status, + ackCode: current.matchedAckCode, roundTripTime: current.matchedTripTime + ) + } + let existing = try await dataStore.fetchMessage(id: current.messageID) + guard let existing, existing.status != .delivered, existing.status != .failed else { return false } + if status == .delivered, let code = current.matchedAckCode { + try await dataStore.updateMessageAck( + id: current.messageID, ackCode: code, status: .delivered, roundTripTime: current.matchedTripTime + ) + return try await dataStore.fetchMessage(id: current.messageID)?.status == .delivered + } + return try await dataStore.updateMessageStatusUnlessDelivered(id: current.messageID, status: .failed) + } + + private func cleanUpStaleAcknowledgementOwner(_ tracking: PendingAck, owner: PendingAck.Owner) async { + do { + if let current = pendingAcks[tracking.messageID], current.sentAt != tracking.sentAt { + try await dataStore.deletePendingSend(id: owner.id) + return + } + let message = try await dataStore.fetchMessage(id: tracking.messageID) + guard message == nil || message?.status == .delivered || message?.status == .failed else { return } + _ = try await dataStore.resolvePendingAcknowledgement( + id: owner.id, expectedDeadline: owner.deadline, status: message?.status ?? .failed, + ackCode: message?.ackCode, roundTripTime: message?.roundTripTime + ) + } catch { + logger.warning("Stale ACK owner cleanup failed messageID=\(tracking.messageID): \(String(describing: error))") + } + } +} diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift b/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift index 2d96a422e4..3e42e680de 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift @@ -14,21 +14,25 @@ extension MessageService { let device = try await dataStore.fetchDevice(radioID: radioID) let scope = ChannelFloodScopeResolver.resolve( channelFloodScope: channel?.floodScope ?? .inherit, - deviceDefaultFloodScopeName: device?.defaultFloodScopeName, supportsUnscopedFloodSend: device?.supportsUnscopedFloodSend ?? false ) - if let device, - device.firmwareVersion < Self.floodScopeMinimumFirmwareVersion, - scope == .scope(.disabled) { - try await session.sendChannelMessage(channel: channelIndex, text: text, timestamp: timestamp) + let appliedScope: ResolvedFloodScope? = if let device, + device.firmwareVersion < Self.floodScopeMinimumFirmwareVersion, + scope == .scope(.disabled) { + nil } else { + scope + } + if let appliedScope { try await session.sendChannelMessage( channel: channelIndex, text: text, timestamp: timestamp, - floodScope: scope + floodScope: appliedScope ) + } else { + try await session.sendChannelMessage(channel: channelIndex, text: text, timestamp: timestamp) } } } diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+DMRetry.swift b/MC1Services/Sources/MC1Services/Services/MessageService+DMRetry.swift new file mode 100644 index 0000000000..c859debfc2 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/MessageService+DMRetry.swift @@ -0,0 +1,531 @@ +import Foundation +import MeshCore + +private let dmAckTimeoutHeadroom: Double = 1.2 +private let millisecondsPerSecond: Double = 1000 + +extension MessageService { + // MARK: - Direct Message Retry Loop + + func sendDirectMessageWithRetryLoop( + messageID: UUID, + to contact: ContactDTO, + text: String, + timestamp: UInt32, + timeout: TimeInterval?, + budget: DMSendBudget, + sendLease: PlainTextSendGate.Lease?, + waitForAcknowledgement: Bool, + pendingSendID: UUID? = nil, + preserveTimestamp: Bool = true + ) async throws -> Data? { + let maxRetryAttempts = budget.totalAttempts - 1 + let sendDate = Date(timeIntervalSince1970: TimeInterval(timestamp)) + var lastExpectedAck: Data? + var wireAttempt = 0 + var submissions = 0 + var didResetPath = false + var commitWireTimestamp = !preserveTimestamp + var replacedDeliveryTimestamp: UInt32? + if preserveTimestamp, let pendingSendID { + guard let stored = try await dataStore.pendingSendWireAttempt(id: pendingSendID) else { return nil } + if stored >= AckCodeBuilder.attemptCount { return nil } + wireAttempt = Int(stored) + } + + if wireAttempt > 0 { + await trackConsumedDirectMessageAttempts( + messageID: messageID, + contactID: contact.id, + text: text, + timestamp: timestamp, + startingAttempt: UInt8(wireAttempt), + timeout: timeout, + sendLeaseID: sendLease?.id, + replacingDeliveredTimestamp: commitWireTimestamp + ) + } + + while submissions < budget.totalAttempts, wireAttempt < Int(AckCodeBuilder.attemptCount) { + if await directMessageSendShouldStop(messageID, replacingDeliveredTimestamp: commitWireTimestamp) { + return lastExpectedAck + } + guard !Task.isCancelled else { + throw CancellationError() + } + + if lastExpectedAck != nil, pendingAcks[messageID]?.isAwaitingAck != true { return lastExpectedAck } + + if submissions > 0 { + try await dataStore.updateMessageRetryStatus( + id: messageID, + status: .retrying, + retryAttempt: submissions - 1, + maxRetryAttempts: maxRetryAttempts + ) + statusEventBroadcaster.yield(.retrying( + messageID: messageID, + attempt: submissions - 1, + maxAttempts: maxRetryAttempts + )) + } + + if budget.floodAttempts > 0, wireAttempt >= budget.directAttempts, !didResetPath { + logger.info("Resetting path to flood before attempt \(wireAttempt)") + didResetPath = true + do { + if let contactService { + try await contactService.resetPath(radioID: contact.radioID, publicKey: contact.publicKey) + } else { + try await session.resetPath(publicKey: contact.publicKey) + _ = try await dataStore.updateContactRoute( + radioID: contact.radioID, + publicKey: contact.publicKey, + outPathLength: PacketBuilder.floodPathSentinel, + outPath: Data() + ) + } + if try await dataStore.fetchContact(radioID: contact.radioID, publicKey: contact.publicKey) != nil { + statusEventBroadcaster.yield(.routingChanged(contactID: contact.id, isFlood: true)) + } + } catch { + logger.warning("Failed to reset path: \(error.localizedDescription), continuing...") + } + } + + if submissions > 0 { + logger.info("Retry sending message: attempt \(wireAttempt + 1)/\(budget.totalAttempts)") + } + + // Precompute the expected ACK CRC before the send so the persistent + // ACK listener cannot race ahead of trackPendingAck on short direct links. + guard let senderPublicKey = await session.currentSelfInfo?.publicKey else { + throw MessageServiceError.notConnected + } + if await directMessageSendShouldStop(messageID, replacingDeliveredTimestamp: commitWireTimestamp) { + return lastExpectedAck + } + + if lastExpectedAck != nil, pendingAcks[messageID]?.isAwaitingAck != true { return lastExpectedAck } + let previousAck = pendingAcks[messageID] + let attemptByte = UInt8(wireAttempt) + + let predictedAck = AckCodeBuilder.expectedAck( + timestamp: timestamp, + attempt: attemptByte, + text: text, + senderPublicKey: senderPublicKey + ) + + // Pre-send floor must outlive one checkExpiredAcks tick; otherwise a + // BLE round-trip > 1s could let the checker expire the speculative + // entry before sendMessage returns and we overwrite the timeout with + // the authoritative sentInfo-derived value. + let preSendTimeout = max(timeout ?? config.minTimeout, checkInterval) + await trackPendingAck( + messageID: messageID, + contactID: contact.id, + ackCode: predictedAck, + timeout: preSendTimeout, + sendLeaseID: sendLease?.id, + replacingDeliveredTimestamp: commitWireTimestamp + ) + await notePlainTextLease(sendLease) + + #if DEBUG + if let gate = directMessageSubmitGateForTesting { + await gate(attemptByte) + } + #endif + if await directMessageSendShouldStop(messageID, replacingDeliveredTimestamp: commitWireTimestamp) { + return lastExpectedAck + } + guard pendingAcks[messageID]?.isAwaitingAck == true else { return lastExpectedAck } + if commitWireTimestamp { + replacedDeliveryTimestamp = try await dataStore.commitOutgoingDirectMessageTimestamp( + id: messageID, timestamp: timestamp + ) + commitWireTimestamp = false + } + + let sentInfo: MessageSentInfo? + let rollbackTimestamp = replacedDeliveryTimestamp + do { + sentInfo = try await withPoolBackoff( + transientCode: FirmwareDeviceErrorCode.directMessageTableFull, + config: config.poolBackoff, + logger: logger + ) { () async throws -> MessageSentInfo? in + try await self.submitDMCommand( + messageID: messageID, publicKey: contact.publicKey, text: text, + timestamp: sendDate, attempt: attemptByte, + replacedDeliveryTimestamp: rollbackTimestamp, pendingSendID: pendingSendID + ) + } + replacedDeliveryTimestamp = nil + } catch { + return try await recoverFailedDirectMessageAttempt( + error, + messageID: messageID, + attempt: attemptByte, + pendingSendID: pendingSendID, + previousTimestamp: replacedDeliveryTimestamp, + lastExpectedAck: lastExpectedAck, + previousAck: previousAck, + sendLeaseID: sendLease?.id, + wireAttempt: wireAttempt + ) + } + guard let sentInfo else { return lastExpectedAck } + lastExpectedAck = sentInfo.expectedAck + guard pendingAcks[messageID]?.isAwaitingAck == true else { return lastExpectedAck } + + let ackTimeout = timeout ?? max(config.minTimeout, dmAckTimeout(for: sentInfo)) + // Subscribe before the attempt byte is saved. An acknowledgement that + // arrives during that save stays buffered for the wait below. + let (subscriptionID, ackStream) = await session.eventsTracked( + filter: .acknowledgement(code: sentInfo.expectedAck) + ) + var consumed = true + let stillWaiting = await noteAcceptedDirectMessageAttempt( + messageID: messageID, + sentInfo: sentInfo, + predictedAck: predictedAck, + timeout: ackTimeout, + attempt: attemptByte, + pendingSendID: pendingSendID, + consumed: &consumed + ) + if !stillWaiting { + await session.finishEvents(id: subscriptionID) + return lastExpectedAck + } + if !waitForAcknowledgement { + await session.finishEvents(id: subscriptionID) + return nil + } + let ackEvent = await nextDirectMessageAcknowledgement(ackStream, timeout: ackTimeout) + await session.finishEvents(id: subscriptionID) + + if ackEvent != nil || pendingAcks[messageID]?.isAwaitingAck != true { + return lastExpectedAck + } + // A missed attempt-byte save is not an end-to-end ACK. The tracker still holds the predicted code. + guard consumed else { return nil } + wireAttempt += 1 + submissions += 1 + } + + logger.info("DM retry budget spent messageID=\(messageID) attempts=\(budget.totalAttempts)") + return nil + } + + private func recoverFailedDirectMessageAttempt( + _ error: Error, + messageID: UUID, + attempt: UInt8, + pendingSendID: UUID?, + previousTimestamp: UInt32?, + lastExpectedAck: Data?, + previousAck: PendingAck?, + sendLeaseID: UUID?, + wireAttempt: Int + ) async throws -> Data? { + if await directMessageSendShouldStop(messageID, replacingDeliveredTimestamp: false) { + return lastExpectedAck + } + if isDirectMessageCommandTimeout(error) { + _ = await consumeDirectMessageWireAttempt(attempt, pendingSendID: pendingSendID) + if await directMessageSendShouldStop(messageID, replacingDeliveredTimestamp: false) { + if let pendingSendID, + await (try? dataStore.fetchMessage(id: messageID))?.status == .delivered { + try? await dataStore.deletePendingSend(id: pendingSendID) + } + return lastExpectedAck + } + } else if isUnsubmittedDirectMessage(error) { + if let previousTimestamp { + _ = try await restoreDeliveredDirectMessage(messageID: messageID, previousTimestamp: previousTimestamp) + } + await discardTrackedAck(messageID: messageID) + throw error + } else if let previousTimestamp, + try await restoreRejectedDelivery( + error, messageID: messageID, pendingSendID: pendingSendID, + previousTimestamp: previousTimestamp + ) { + return lastExpectedAck + } + if lastExpectedAck != nil, !Task.isCancelled, + retainAcceptedDMAfterCommandFailure( + error, messageID: messageID, previousAck: previousAck, sendLeaseID: sendLeaseID + ) { + logger.warning("DM command issuance ended messageID=\(messageID) attempt=\(wireAttempt): \(String(describing: error))") + return pendingAcks[messageID]?.isAwaitingAck == true ? nil : lastExpectedAck + } + await discardTrackedAck(messageID: messageID) + throw error + } + + /// Returns false when this attempt is already resolved and the loop should stop. + private func noteAcceptedDirectMessageAttempt( + messageID: UUID, + sentInfo: MessageSentInfo, + predictedAck: Data, + timeout: TimeInterval, + attempt: UInt8, + pendingSendID: UUID?, + consumed: inout Bool + ) async -> Bool { + if await directMessageSendShouldStop(messageID, replacingDeliveredTimestamp: false) { + return false + } + consumed = await consumeDirectMessageWireAttempt(attempt, pendingSendID: pendingSendID) + guard pendingAcks[messageID]?.isAwaitingAck == true else { return false } + await recordDMCommandAcceptance( + messageID: messageID, sentInfo: sentInfo, predictedAck: predictedAck, timeout: timeout + ) + return true + } + + /// Reads one acknowledgement from the subscription opened before attempt bookkeeping. + private func nextDirectMessageAcknowledgement( + _ stream: AsyncStream, + timeout: TimeInterval + ) async -> MeshEvent? { + let sessionClock = (session as? MeshCoreSession)?.clock + return await withTaskGroup(of: MeshEvent?.self) { group in + group.addTask { + for await event in stream { + return event + } + return nil + } + group.addTask { + if let sessionClock { + try? await sessionClock.sleep(for: .seconds(timeout)) + } else { + try? await Task.sleep(for: .seconds(timeout)) + } + return nil + } + let result = await group.next() ?? nil + group.cancelAll() + return result + } + } + + private func submitDMCommand( + messageID: UUID, + publicKey: Data, + text: String, + timestamp: Date, + attempt: UInt8, + replacedDeliveryTimestamp: UInt32?, + pendingSendID: UUID? + ) async throws -> MessageSentInfo? { + if await directMessageSendShouldStop(messageID, replacingDeliveredTimestamp: false) { return nil } + guard pendingAcks[messageID]?.isAwaitingAck == true else { return nil } + // The last submission may have reached the radio even when its response times out. + pendingAcks[messageID]?.sentAt = Date() + do { + return try await session.sendMessage(to: publicKey.prefix(6), text: text, timestamp: timestamp, attempt: attempt) + } catch { + if isDirectMessageTableFull(error) { throw error } + if let replacedDeliveryTimestamp, + try await restoreRejectedDelivery( + error, messageID: messageID, pendingSendID: pendingSendID, + previousTimestamp: replacedDeliveryTimestamp + ) { + return nil + } + throw error + } + } + + func recordDMCommandAcceptance( + messageID: UUID, sentInfo: MessageSentInfo, predictedAck: Data, timeout: TimeInterval + ) async { + pendingAcks[messageID]?.commandAccepted = true + guard let tracking = pendingAcks[messageID], tracking.isAwaitingAck else { return } + if sentInfo.expectedAck != predictedAck { + logger.warning("DM expected ACK differs from prediction messageID=\(messageID)") + await trackPendingAck( + messageID: messageID, contactID: tracking.contactID, ackCode: sentInfo.expectedAck, timeout: timeout + ) + } else { + pendingAcks[messageID]?.sentAt = Date() + pendingAcks[messageID]?.timeout = timeout + } + } + + func dmAckTimeout(for sentInfo: MessageSentInfo) -> TimeInterval { + Double(sentInfo.suggestedTimeoutMs) / millisecondsPerSecond * dmAckTimeoutHeadroom + } + + private func retainAcceptedDMAfterCommandFailure( + _ error: Error, messageID: UUID, previousAck: PendingAck?, sendLeaseID: UUID? + ) -> Bool { + guard let error = error as? MeshCoreError else { return false } + let rejected: Bool + switch error { + case .deviceError(code: FirmwareDeviceErrorCode.directMessageTableFull): + rejected = true + case .timeout: + rejected = false + default: + return false + } + guard let previousAck, let current = pendingAcks[messageID], + current.sendLeaseID == sendLeaseID else { return true } + guard current.isAwaitingAck else { return true } + if rejected { + // A rejected command keeps the last accepted attempt's codes and deadline. + pendingAcks[messageID]?.ackCodes = previousAck.ackCodes + pendingAcks[messageID]?.sentAt = previousAck.sentAt + pendingAcks[messageID]?.timeout = previousAck.timeout + } else { + // A missing host reply leaves this attempt's predicted ACK eligible from its submission time. + let earlierDeadline = previousAck.expiresAt(giveUpWindow: config.ackGiveUpWindow) + pendingAcks[messageID]?.timeout = max(previousAck.timeout, earlierDeadline.timeIntervalSince(current.sentAt)) + } + return true + } + + /// A definite rejection did not queue the packet, so restore the delivered row and stop. + private func restoreRejectedDelivery( + _ error: Error, + messageID: UUID, + pendingSendID: UUID?, + previousTimestamp: UInt32 + ) async throws -> Bool { + guard isRejectedDirectMessageCommand(error) else { return false } + let restored = try await restoreDeliveredDirectMessage( + messageID: messageID, previousTimestamp: previousTimestamp + ) + guard restored else { return false } + if let pendingSendID { + try? await dataStore.deletePendingSend(id: pendingSendID) + } + await discardTrackedAck(messageID: messageID) + return true + } + + /// Puts the committed timestamp back and tells an open chat the row is delivered again. + private func restoreDeliveredDirectMessage(messageID: UUID, previousTimestamp: UInt32) async throws -> Bool { + let restored = try await dataStore.restoreUnacceptedDeliveredDirectMessage( + id: messageID, timestamp: previousTimestamp + ) + guard restored else { return false } + statusEventBroadcaster.yield(.statusResolved(messageID: messageID, status: .delivered, roundTripTime: nil)) + return true + } + + /// Not submitted and table full stay queued so the drain can retry them. + func parksQueuedDirectMessage(_ error: Error) -> Bool { + isUnsubmittedDirectMessage(error) || isDirectMessageTableFull(error) + } + + private func isDirectMessageTableFull(_ error: Error) -> Bool { + switch error { + case MeshCoreError.deviceError(code: FirmwareDeviceErrorCode.directMessageTableFull): + true + case let MessageServiceError.sessionError(underlying): + isDirectMessageTableFull(underlying) + default: + false + } + } + + /// A host timeout means the command may already be queued. Table full is parked, not restored. + /// Any other device error is a definite rejection. + private func isRejectedDirectMessageCommand(_ error: Error) -> Bool { + switch error { + case MeshCoreError.deviceError(code: FirmwareDeviceErrorCode.directMessageTableFull): + false + case MeshCoreError.deviceError: + true + case let MessageServiceError.sessionError(underlying): + isRejectedDirectMessageCommand(underlying) + default: + false + } + } + + private func isUnsubmittedDirectMessage(_ error: Error) -> Bool { + switch error { + case MeshCoreError.notConnected: + true + case let MessageServiceError.sessionError(underlying): + isUnsubmittedDirectMessage(underlying) + default: + false + } + } + + private func isDirectMessageCommandTimeout(_ error: Error) -> Bool { + switch error { + case MeshCoreError.timeout: + true + case let MessageServiceError.sessionError(underlying): + isDirectMessageCommandTimeout(underlying) + default: + false + } + } + + /// Attempt bytes already handed to the radio for this timestamp stay matchable before the next command. + private func trackConsumedDirectMessageAttempts( + messageID: UUID, + contactID: UUID, + text: String, + timestamp: UInt32, + startingAttempt: UInt8, + timeout: TimeInterval?, + sendLeaseID: UUID?, + replacingDeliveredTimestamp: Bool + ) async { + guard startingAttempt > 0, let senderPublicKey = await session.currentSelfInfo?.publicKey else { return } + if await directMessageSendShouldStop(messageID, replacingDeliveredTimestamp: replacingDeliveredTimestamp) { + return + } + let preSendTimeout = max(timeout ?? config.minTimeout, checkInterval) + for prior in 0.. Bool { + if pendingAcks[messageID]?.isAwaitingAck == false { return true } + if replacingDeliveredTimestamp { return false } + guard await (try? dataStore.fetchMessage(id: messageID))?.status == .delivered else { return false } + await discardTrackedAck(messageID: messageID) + return true + } + + /// Records the next byte before the ACK wait. A missing row stops further submissions of this timestamp. + func consumeDirectMessageWireAttempt(_ attempt: UInt8, pendingSendID: UUID?) async -> Bool { + guard let pendingSendID else { return true } + let next = UInt8(min(Int(attempt) + 1, Int(AckCodeBuilder.attemptCount))) + do { + return try await dataStore.setPendingSendWireAttempt(id: pendingSendID, to: next) + } catch { + logger.warning("DM wire attempt record failed messageID pendingSend=\(pendingSendID): \(error.localizedDescription)") + return false + } + } +} diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+InlineSendLifecycle.swift b/MC1Services/Sources/MC1Services/Services/MessageService+InlineSendLifecycle.swift new file mode 100644 index 0000000000..5e54fac03c --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/MessageService+InlineSendLifecycle.swift @@ -0,0 +1,22 @@ +extension MessageService { + func beginInlineSend() throws { + guard !inlineSendAdmissionClosed else { throw MessageServiceError.notConnected } + inlineSendsInFlight += 1 + } + + func endInlineSend() { + inlineSendsInFlight -= 1 + guard inlineSendsInFlight == 0 else { return } + let waiters = inlineSendWaiters + inlineSendWaiters.removeAll() + for waiter in waiters { + waiter.resume() + } + } + + func retireInlineSends() async { + inlineSendAdmissionClosed = true + guard inlineSendsInFlight > 0 else { return } + await withCheckedContinuation { inlineSendWaiters.append($0) } + } +} diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+PlainTextLease.swift b/MC1Services/Sources/MC1Services/Services/MessageService+PlainTextLease.swift new file mode 100644 index 0000000000..a52d8202fe --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/MessageService+PlainTextLease.swift @@ -0,0 +1,28 @@ +import Foundation + +extension MessageService { + func adoptPlainTextLease(_ provided: PlainTextSendGate.Lease?) async throws -> PlainTextSendGate.Lease? { + if let provided { return provided } + return try await plainTextSendGate?.acquire() + } + + func stopPlainTextLease(_ lease: PlainTextSendGate.Lease?) async { + guard let lease else { return } + await plainTextSendGate?.stopIssuing(lease) + } + + func notePlainTextLease(_ lease: PlainTextSendGate.Lease?) async { + guard let lease else { return } + await plainTextSendGate?.noteAckObligation(lease) + } + + func settlePlainTextLease(_ leaseID: UUID?) async { + guard let leaseID else { return } + await plainTextSendGate?.settleAck(PlainTextSendGate.Lease(id: leaseID)) + } + + func discardTrackedAck(messageID: UUID) async { + let leaseID = pendingAcks.removeValue(forKey: messageID)?.sendLeaseID + await settlePlainTextLease(leaseID) + } +} diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+Reactions.swift b/MC1Services/Sources/MC1Services/Services/MessageService+Reactions.swift new file mode 100644 index 0000000000..bbf953f7dd --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/MessageService+Reactions.swift @@ -0,0 +1,25 @@ +import Foundation + +extension MessageService { + func validateOutgoingReaction(_ message: MessageDTO) async throws { + if message.channelIndex != nil { + try await rejectIfChannelTextTooLong(message.text, radioID: message.radioID) + } else if let contactID = message.contactID, + let contact = try await dataStore.fetchContact(id: contactID), + contact.radioID == message.radioID { + try validateDirectMessage(text: message.text, to: contact) + } else { + throw MessageServiceError.contactNotFound + } + } + + func notifyOutgoingReactionAccepted(messageID: UUID) async { + do { + if let result = try await dataStore.completeOutgoingReaction(messageID: messageID) { + statusEventBroadcaster.yield(.reactionAccepted(messageID: result.messageID, summary: result.summary)) + } + } catch { + logger.warning("Reaction update notification deferred messageID=\(messageID): \(String(describing: error))") + } + } +} diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift index 409923fc9d..16f67dfc52 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift @@ -7,7 +7,7 @@ public extension MessageService { /// Sends a broadcast message to a channel. /// /// Channel messages are broadcast to all devices listening on the specified channel. - /// No acknowledgement is expected or tracked for channel messages. + /// A radio acknowledgement confirms acceptance for transmission. /// /// - Parameters: /// - text: The message text to broadcast. Bounded by @@ -39,6 +39,9 @@ public extension MessageService { radioID: UUID, textType: TextType = .plain ) async throws -> (id: UUID, timestamp: UInt32) { + // Keep this send in the retirement barrier through the Sent write if scope cleanup triggers recovery. + try beginInlineSend() + defer { endInlineSend() } try await rejectIfChannelTextTooLong(text, radioID: radioID) let messageID = UUID() @@ -69,13 +72,11 @@ public extension MessageService { try await failMessageAndRethrow(error, messageID: messageID) } - // Post-broadcast bookkeeping. The broadcast already left the radio, - // so a throw here must not mark `.failed` — that would lie about - // delivery. Log and continue; the message stays `.sent` (or sticks - // `.pending` if `updateMessageStatus` itself threw, which a subsequent - // ack or user retry can reconverge). No queue row exists on this - // inline path, so the "retry button hidden via missing PendingSend" - // pathology from the queue-routed path does not apply. + #if DEBUG + if let gate = inlineSendAcceptedGateForTesting { await gate() } + #endif + + // Preserve radio acceptance if updating the local record fails. do { try await dataStore.updateMessageStatus(id: messageID, status: .sent) statusEventBroadcaster.yield(.statusResolved(messageID: messageID, status: .sent, roundTripTime: nil)) @@ -83,31 +84,14 @@ public extension MessageService { try await dataStore.updateChannelLastMessage(channelID: channel.id, date: Date()) } } catch { - logger.warning("Channel post-broadcast bookkeeping failed (inline path) messageID=\(messageID) broadcast already out: \(String(describing: error))") + logger.warning("Inline channel bookkeeping failed after radio acceptance messageID=\(messageID): \(String(describing: error))") } return (id: messageID, timestamp: timestamp) } - /// Creates a pending channel message without sending it. - /// - /// Use this for optimistic UI — the message is saved immediately and can be - /// displayed in the conversation while the actual send happens in the background - /// via ``sendPendingChannelMessage(messageID:channelIndex:radioID:)``. - /// - /// - Parameters: - /// - text: The message text. Bounded by - /// `ProtocolLimits.maxChannelMessageLength(nodeNameByteCount:)`. - /// - channelIndex: The channel index to send on - /// - radioID: The device ID - /// - textType: The text type (defaults to `.plain`) - /// - /// - Returns: The created message DTO with pending status - /// - /// - Throws: - /// - `MessageServiceError.messageTooLong` if user text exceeds - /// `ProtocolLimits.maxChannelMessageLength(nodeNameByteCount:)` - func createPendingChannelMessage( + /// Validates the radio's current text budget and saves the Message before queue admission. + internal func createPendingChannelMessage( text: String, channelIndex: UInt8, radioID: UUID, @@ -157,16 +141,31 @@ public extension MessageService { radioID = message.radioID channelIndex = idx - try await withPoolBackoff(transientCode: FirmwareDeviceErrorCode.channelMessageNotFound, config: config.poolBackoff, logger: logger) { - try await sendChannelMessageWithScope( - text: message.text, - channelIndex: channelIndex, - radioID: radioID, - timestamp: Date(timeIntervalSince1970: TimeInterval(message.timestamp)) - ) + let isReaction = message.reactionTargetMessageID != nil + let alreadyAccepted = isReaction && (acceptedChannelReactions.contains(messageID) || message.status == .sent) + if !alreadyAccepted { + try await withPoolBackoff(transientCode: FirmwareDeviceErrorCode.channelMessageNotFound, config: config.poolBackoff, logger: logger) { + try await sendChannelMessageWithScope( + text: message.text, + channelIndex: channelIndex, + radioID: radioID, + timestamp: Date(timeIntervalSince1970: TimeInterval(message.timestamp)) + ) + } + if isReaction { acceptedChannelReactions.insert(messageID) } + } + do { + try await dataStore.updateMessageStatus(id: messageID, status: .sent) + if isReaction { + await notifyOutgoingReactionAccepted(messageID: messageID) + acceptedChannelReactions.remove(messageID) + } + } catch { + if isReaction { throw MessageServiceError.persistenceError(error) } + throw error } - try await dataStore.updateMessageStatus(id: messageID, status: .sent) } catch { + if case MessageServiceError.persistenceError = error { throw error } try await failMessageAndRethrow(error, messageID: messageID) } @@ -185,37 +184,16 @@ public extension MessageService { } } - /// Resend an existing channel message, incrementing its send count. - /// - /// This is used for "Send Again" - it re-transmits the same message - /// rather than creating a duplicate. Uses a new timestamp so the mesh - /// treats it as a fresh broadcast. - /// - /// - Returns: The new wire timestamp written to the message row. - /// Reaction indexing keys off this value via - /// `SHA256(text || timestamp.littleEndian)`; callers that index reactions - /// for the resent packet must pass this value rather than the pre-resend - /// timestamp from the queued envelope. + /// Resends a channel message, preserving its wire timestamp only during recovery. + /// Returns that timestamp so reaction indexing matches the send. @discardableResult func resendChannelMessage( messageID: UUID, preserveTimestamp: Bool = false ) async throws -> UInt32 { - // Broadcast .resent only after .sent is committed. The sentCommitted - // flag suppresses a spurious broadcast if catch 1 rethrows; - // failMessageAndRethrow always re-throws, so a catch-1 failure exits - // the function before the broadcast site is reached and the guard is - // belt-and-braces. The event still fires when catch 2 bookkeeping - // throws, since sentCommitted is set before catch 2 runs. Yielding - // after catch 2 and before return preserves the committed-before- - // broadcast ordering the resend tests assert. + // Publish .resent after .sent commits, even if send-count bookkeeping fails. var sentCommitted = false - // Catch 1: validation guards + timestamp update + send + status flip. - // Validation lives inside the do/catch so a missing message or missing - // channel index consistently writes `.failed` before propagating — - // paired with the queue's outer catch. Once `.sent` is committed, the - // per-attempt bookkeeping below cannot retroactively flip it. let wireTimestamp: UInt32 do { guard let message = try await dataStore.fetchMessage(id: messageID) else { @@ -236,31 +214,42 @@ public extension MessageService { } if !preserveTimestamp { - try await dataStore.updateMessageTimestamp(id: messageID, timestamp: wireTimestamp) + try await dataStore.prepareChannelMessageResend(id: messageID, timestamp: wireTimestamp) } - try await withPoolBackoff(transientCode: FirmwareDeviceErrorCode.channelMessageNotFound, config: config.poolBackoff, logger: logger) { - try await sendChannelMessageWithScope( - text: message.text, - channelIndex: channelIndex, - radioID: message.radioID, - timestamp: wireDate - ) + let isReaction = message.reactionTargetMessageID != nil + let alreadyAccepted = isReaction && ( + acceptedChannelReactions.contains(messageID) || (preserveTimestamp && message.status == .sent) + ) + if !alreadyAccepted { + try await withPoolBackoff(transientCode: FirmwareDeviceErrorCode.channelMessageNotFound, config: config.poolBackoff, logger: logger) { + try await sendChannelMessageWithScope( + text: message.text, + channelIndex: channelIndex, + radioID: message.radioID, + timestamp: wireDate + ) + } + if isReaction { acceptedChannelReactions.insert(messageID) } + } + do { + try await dataStore.updateMessageStatus(id: messageID, status: .sent) + if isReaction { + await notifyOutgoingReactionAccepted(messageID: messageID) + acceptedChannelReactions.remove(messageID) + } + } catch { + if isReaction { throw MessageServiceError.persistenceError(error) } + throw error } - try await dataStore.updateMessageStatus(id: messageID, status: .sent) sentCommitted = true } catch { + if case MessageServiceError.persistenceError = error { throw error } try await failMessageAndRethrow(error, messageID: messageID) } - // Catch 2: per-attempt bookkeeping. Status is already .sent in DB and - // the radio broadcast happened. Failures here log only — the message - // is correctly marked .sent and the missing metadata (sendCount, - // heardRepeats clear) is non-load-bearing for delivery semantics; the - // next inbound ack/repeat event will reconverge. + // Status is already .sent. A send-count failure cannot undo radio acceptance. do { _ = try await dataStore.incrementMessageSendCount(id: messageID) - try await dataStore.updateMessageHeardRepeats(id: messageID, heardRepeats: 0) - try await dataStore.deleteMessageRepeats(messageID: messageID) } catch { logger.warning("Resend post-status bookkeeping failed messageID=\(messageID) status=.sent already committed: \(String(describing: error))") } @@ -295,7 +284,7 @@ public extension MessageService { /// Cap user text so `"name: " + text` fits `maxChannelMessageTotalLength`. /// Firmware prepends the name before encrypting; an extra AES block overflows the RX log. - private func rejectIfChannelTextTooLong(_ text: String, radioID: UUID) async throws { + func rejectIfChannelTextTooLong(_ text: String, radioID: UUID) async throws { let nodeNameByteCount: Int = if let name = try? await dataStore.fetchDevice(radioID: radioID)?.nodeName { name.utf8.count } else { diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift index 0d2124d010..79734cf696 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift @@ -3,40 +3,18 @@ import MeshCore // MARK: - Send Direct Message -extension MessageService { - /// Sends a direct message to a contact with a single send attempt. - /// - /// This method sends a message once without automatic retry. Use this when you want - /// to manually control retry logic or when retry is not needed. - /// - /// - Parameters: - /// - text: The message text to send. Bounded by - /// `ProtocolLimits.maxDirectMessageLength` (150 UTF-8 bytes). - /// - contact: The recipient contact - /// - textType: The text encoding type (defaults to `.plain`) - /// - replyToID: Optional ID of message being replied to - /// - /// - Returns: The created message DTO with pending/sent status - /// - /// - Throws: - /// - `MessageServiceError.invalidRecipient` if contact is a repeater - /// - `MessageServiceError.messageTooLong` if text exceeds `ProtocolLimits.maxDirectMessageLength` - /// - `MessageServiceError.sessionError` if MeshCore send fails - /// - /// # Example - /// - /// ```swift - /// let message = try await messageService.sendDirectMessage( - /// text: "Hello!", - /// to: contact - /// ) - /// ``` - public func sendDirectMessage( +public extension MessageService { + /// Sends once; end-to-end ACK tracking continues after the method returns. + func sendDirectMessage( text: String, to contact: ContactDTO, textType: TextType = .plain, replyToID: UUID? = nil ) async throws -> MessageDTO { + // Counted before `session.sendMessage`. `RequestContext` releases its slot + // before resuming this caller, and `retireInlineSends` waits without cancelling it. + try beginInlineSend() + defer { endInlineSend() } try validateDirectMessage(text: text, to: contact) let messageID = UUID() @@ -53,13 +31,50 @@ extension MessageService { ) try await dataStore.saveMessage(messageDTO) + // Persist before admission so a reply waiting on another send survives process death. + let pendingSendID = UUID() + do { + _ = try await dataStore.insertPendingSendAssigningSequence( + PendingSendDTO( + id: pendingSendID, + envelope: DirectMessageEnvelope(messageID: messageID, contactID: contact.id, isSingleAttempt: true), + radioID: contact.radioID + ) + ) + } catch { + statusEventBroadcaster.yield(.failed(messageID: messageID)) + try await failMessageAndRethrow(error, messageID: messageID) + } + + var sendLease: PlainTextSendGate.Lease? + defer { await stopPlainTextLease(sendLease) } + defer { + if pendingAcks[messageID]?.owner == nil { + // A row that already records an ACK deadline belongs to delivery tracking. + // Deleting it would drop a send the radio has accepted. + let stillUnsent: Bool = if let rows = try? await dataStore.fetchPendingSends(radioID: contact.radioID) { + rows.first { $0.id == pendingSendID }?.ackDeadline == nil + } else { + true + } + if stillUnsent { + try? await dataStore.deletePendingSend(id: pendingSendID) + } + } + } let predictedAck: Data let sentInfo: MessageSentInfo do { - // Precompute the expected ACK before the send so the persistent - // listener cannot race trackPendingAck on short direct links (same - // pattern used by the retry loop). Reactions and quick replies - // flow through this path and otherwise lose ACKs on fast links. + sendLease = try await adoptPlainTextLease(nil) + if sendLease != nil, try await dataStore.fetchMessage(id: messageID) == nil { + throw CancellationError() + } + // A restart must preserve this timestamp once the command may have reached the radio. + guard let attempted = try await dataStore.preparePendingSendAttempt(messageID: messageID), + attempted.pendingSendID == pendingSendID else { + throw CancellationError() + } + // Track the predicted ACK before sending so a fast reply cannot outrun registration. guard let senderPublicKey = await session.currentSelfInfo?.publicKey else { throw MessageServiceError.notConnected } @@ -69,15 +84,15 @@ extension MessageService { text: text, senderPublicKey: senderPublicKey ) - // Pre-send floor must outlive one checkExpiredAcks tick, otherwise - // a slow BLE round-trip could let the checker expire the - // speculative entry before the authoritative timeout lands. - trackPendingAck( + // Keep speculative tracking alive until the command returns its ACK timeout. + await trackPendingAck( messageID: messageID, contactID: contact.id, ackCode: predictedAck, - timeout: checkInterval + timeout: checkInterval, + sendLeaseID: sendLease?.id ) + await notePlainTextLease(sendLease) do { sentInfo = try await withPoolBackoff(transientCode: FirmwareDeviceErrorCode.directMessageTableFull, config: config.poolBackoff, logger: logger) { @@ -88,7 +103,7 @@ extension MessageService { ) } } catch { - pendingAcks.removeValue(forKey: messageID) + await discardTrackedAck(messageID: messageID) throw error } } catch { @@ -96,28 +111,23 @@ extension MessageService { try await failMessageAndRethrow(error, messageID: messageID) } - let ackTimeout = TimeInterval(sentInfo.suggestedTimeoutMs) / 1000.0 * 1.2 + #if DEBUG + if let gate = inlineSendAcceptedGateForTesting { await gate() } + #endif - if sentInfo.expectedAck != predictedAck { - logger.warning( - "expectedAck mismatch for \(messageID) attempt 0: predicted \(predictedAck.uppercaseHexString()) vs firmware \(sentInfo.expectedAck.uppercaseHexString()); merging firmware code" - ) - trackPendingAck( - messageID: messageID, - contactID: contact.id, - ackCode: sentInfo.expectedAck, - timeout: ackTimeout - ) - } else { - pendingAcks[messageID]?.timeout = ackTimeout - pendingAcks[messageID]?.sentAt = Date() - } + let ackTimeout = dmAckTimeout(for: sentInfo) - // Post-send bookkeeping. The radio accepted the send, so a throw here - // must not mark `.failed` or drop the pendingAcks entry; the genuine - // end-to-end ACK or the expiry checker owns the terminal state now, - // mirroring the channel send path. + await recordDMCommandAcceptance( + messageID: messageID, sentInfo: sentInfo, predictedAck: predictedAck, timeout: ackTimeout + ) + _ = await consumeDirectMessageWireAttempt(0, pendingSendID: pendingSendID) + + // The radio accepted the send; bookkeeping errors must leave terminal status + // to the end-to-end ACK or expiry checker. do { + await persistAcknowledgement( + messageID: messageID, radioID: contact.radioID, pendingSendID: pendingSendID + ) // updateMessageAck preserves `.delivered`, so writing `.sent` here // is a no-op when the listener already won the race. try await dataStore.updateMessageAck( @@ -139,46 +149,9 @@ extension MessageService { // MARK: - Send with Automatic Retry - /// Sends a direct message with automatic retry and flood routing fallback. - /// - /// This is the recommended method for sending messages. It automatically: - /// 1. Attempts direct routing up to `maxAttempts` times - /// 2. Switches to flood routing after `floodAfter` attempts - /// 3. Makes up to `maxFloodAttempts` using flood routing - /// 4. Returns immediately when ACK is received - /// - /// The message is saved to the database immediately and the `onMessageCreated` - /// callback is invoked, allowing the UI to update before the send completes. - /// - /// - Parameters: - /// - text: The message text to send. Bounded by - /// `ProtocolLimits.maxDirectMessageLength` (150 UTF-8 bytes). - /// - contact: The recipient contact - /// - textType: The text encoding type (defaults to `.plain`) - /// - replyToID: Optional ID of message being replied to - /// - timeout: Custom timeout in seconds (0 = use device-suggested timeout) - /// - onMessageCreated: Callback invoked after message is saved to database - /// - /// - Returns: The message DTO with final delivery status (delivered or failed) - /// - /// - Throws: - /// - `MessageServiceError.invalidRecipient` if contact is a repeater - /// - `MessageServiceError.messageTooLong` if text exceeds `ProtocolLimits.maxDirectMessageLength` - /// - `MessageServiceError.sessionError` if MeshCore send fails - /// - /// # Example - /// - /// ```swift - /// let message = try await messageService.sendMessageWithRetry( - /// text: "Hello!", - /// to: contact - /// ) { savedMessage in - /// // Update UI immediately with pending message - /// await updateConversation(with: savedMessage) - /// } - /// // Message is now delivered or failed - /// ``` - public func sendMessageWithRetry( + /// Uses one `DMSendBudget` snapshot, resetting the out path once before fallback attempts. + /// The radio selects the out path for each attempt, including after the reset. + func sendMessageWithRetry( text: String, to contact: ContactDTO, textType: TextType = .plain, @@ -187,6 +160,8 @@ extension MessageService { onMessageCreated: (@Sendable (MessageDTO) async -> Void)? = nil ) async throws -> MessageDTO { try validateDirectMessage(text: text, to: contact) + let sendLease = try await adoptPlainTextLease(nil) + defer { await stopPlainTextLease(sendLease) } let messageID = UUID() let timestamp = UInt32(Date().timeIntervalSince1970) @@ -211,15 +186,15 @@ extension MessageService { // Run app-layer retry loop with UI notifications do { - let sentInfo = try await sendDirectMessageWithRetryLoop( + let acknowledgedCode = try await sendDirectMessageWithRetryLoop( messageID: messageID, - contactID: contact.id, - radioID: contact.radioID, - publicKey: contact.publicKey, + to: contact, text: text, - timestamp: Date(timeIntervalSince1970: TimeInterval(timestamp)), - timestampRaw: timestamp, - timeout: timeout > 0 ? timeout : nil + timestamp: timestamp, + timeout: timeout > 0 ? timeout : nil, + budget: dmSendBudgetProvider(), + sendLease: sendLease, + waitForAcknowledgement: true ) return try await finalizeSend( @@ -227,7 +202,7 @@ extension MessageService { contactID: contact.id, radioID: contact.radioID, publicKey: contact.publicKey, - sentInfo: sentInfo, + acknowledgedCode: acknowledgedCode, initialPathLength: initialPathLength ) } catch { @@ -236,19 +211,8 @@ extension MessageService { } } - /// Creates a pending message without sending it. - /// - /// Use this when you want to show the message in the UI immediately - /// and drain it later via ``sendPendingDirectMessage(messageID:to:preserveTimestamp:)``. - /// - /// - Parameters: - /// - text: The message text - /// - contact: The recipient contact - /// - textType: The type of text content (default: .plain) - /// - replyToID: Optional ID of message being replied to - /// - /// - Returns: The created message DTO with pending status - public func createPendingMessage( + /// Saves the pending Message and updates contact recency before the caller publishes it. + internal func createPendingMessage( text: String, to contact: ContactDTO, textType: TextType = .plain, @@ -274,56 +238,56 @@ extension MessageService { return messageDTO } - /// Drains a `.pending` DM through the app-layer retry loop. Does not - /// bump `sendCount` or broadcast `.resent`; both bubble-affecting side - /// effects belong to - /// ``resendDirectMessage(messageID:to:preserveTimestamp:)``. - /// - /// - Parameter preserveTimestamp: True when a prior drain attempt may - /// already have placed the packet on the wire (queue auto-park-and- - /// retry), so the recipient's dedup ring catches the duplicate - /// rather than rendering it twice. False on the first drain, where - /// a fresh timestamp keeps mesh repeaters from filtering the packet. - public func sendPendingDirectMessage( + /// Drains a pending direct message without bumping sendCount or broadcasting `.resent`. + /// - Parameter preserveTimestamp: True continues at the stored attempt byte. False starts a new timestamp at attempt 0. + func sendPendingDirectMessage( messageID: UUID, to contact: ContactDTO, - preserveTimestamp: Bool = false + preserveTimestamp: Bool = false, + pendingSendID: UUID? = nil ) async throws -> MessageDTO { try await performQueuedDirectMessageSend( messageID: messageID, to: contact, preserveTimestamp: preserveTimestamp, - isResend: false + isResend: false, + isSingleAttempt: false, + pendingSendID: pendingSendID, + sendLease: nil ) } - /// Resends an already-sent DM. Re-runs the app-layer retry loop, - /// increments `sendCount`, and broadcasts `.resent` so the bubble - /// surfaces "Sent N times". - /// - /// - Parameter preserveTimestamp: True on queue auto-park-and-retry - /// of the resend; false on the first drain attempt so the wire - /// packet hashes distinctly from the original and clears repeater - /// dedup rings. - public func resendDirectMessage( + /// Resends a direct message, increments sendCount, and broadcasts `.resent`. + /// - Parameter preserveTimestamp: True continues at the stored attempt byte. False starts a new timestamp at attempt 0. + func resendDirectMessage( messageID: UUID, to contact: ContactDTO, - preserveTimestamp: Bool = false + preserveTimestamp: Bool = false, + pendingSendID: UUID? = nil ) async throws -> MessageDTO { try await performQueuedDirectMessageSend( messageID: messageID, to: contact, preserveTimestamp: preserveTimestamp, - isResend: true + isResend: true, + isSingleAttempt: false, + pendingSendID: pendingSendID, + sendLease: nil ) } - private func performQueuedDirectMessageSend( + internal func performQueuedDirectMessageSend( messageID: UUID, to contact: ContactDTO, preserveTimestamp: Bool, - isResend: Bool + isResend: Bool, + isSingleAttempt: Bool, + pendingSendID: UUID?, + sendLease providedLease: PlainTextSendGate.Lease? ) async throws -> MessageDTO { + let sendLease = try await adoptPlainTextLease(providedLease) + defer { await stopPlainTextLease(sendLease) } + guard !inFlightRetries.contains(messageID) else { logger.warning("Send already in progress for message: \(messageID)") throw MessageServiceError.sendFailed("Retry already in progress") @@ -337,40 +301,57 @@ extension MessageService { guard let existingMessage = try await dataStore.fetchMessage(id: messageID) else { throw MessageServiceError.sendFailed("Message not found") } + if isSingleAttempt, !isResend, existingMessage.status == .delivered || existingMessage.status == .failed { + return existingMessage + } - // Fresh timestamp on first drain — mesh repeaters deduplicate by - // packet content, so reusing the original would be dropped. Queue - // auto-retry passes preserveTimestamp: true so the duplicate landing - // on a recipient that already saw the first send gets caught by - // their dedup ring rather than rendered as a second copy. - let wireTimestamp: Date - let wireTimestampRaw: UInt32 + // The mesh seen table keys on ciphertext hash. A preserved timestamp continues + // at the next unused attempt byte. A new timestamp is a new packet on this message. + let wireTimestamp: UInt32 if preserveTimestamp { - wireTimestampRaw = existingMessage.timestamp - wireTimestamp = Date(timeIntervalSince1970: TimeInterval(wireTimestampRaw)) + if existingMessage.status == .delivered { + return existingMessage + } + if let pendingSendID { + guard let stored = try await dataStore.pendingSendWireAttempt(id: pendingSendID) else { + guard let current = try await dataStore.fetchMessage(id: messageID) else { + throw MessageServiceError.sendFailed("Message not found") + } + return current + } + if stored >= AckCodeBuilder.attemptCount { + return try await handOffExhaustedDirectMessage( + messageID: messageID, + contact: contact, + message: existingMessage, + pendingSendID: pendingSendID + ) + } + } + wireTimestamp = existingMessage.timestamp } else { - wireTimestamp = Date() - wireTimestampRaw = UInt32(wireTimestamp.timeIntervalSince1970) - try await dataStore.updateMessageTimestamp(id: messageID, timestamp: wireTimestampRaw) + wireTimestamp = UInt32(Date().timeIntervalSince1970) } do { - let sentInfo = try await sendDirectMessageWithRetryLoop( + let acknowledgedCode = try await sendDirectMessageWithRetryLoop( messageID: messageID, - contactID: contact.id, - radioID: contact.radioID, - publicKey: contact.publicKey, + to: contact, text: existingMessage.text, timestamp: wireTimestamp, - timestampRaw: wireTimestampRaw, - timeout: nil + timeout: nil, + budget: isSingleAttempt || existingMessage.reactionTargetMessageID != nil ? .singleAttempt : dmSendBudgetProvider(), + sendLease: sendLease, + waitForAcknowledgement: existingMessage.reactionTargetMessageID == nil, + pendingSendID: pendingSendID, + preserveTimestamp: preserveTimestamp ) // Bump only on a confirmed successful resend so sendCount counts // landed user-initiated sends, not queue-driven attempts; // bookkeeping failures log because the on-air retransmission // already happened. - if isResend, sentInfo != nil { + if isResend, acknowledgedCode != nil { do { _ = try await dataStore.incrementMessageSendCount(id: messageID) } catch { @@ -383,13 +364,14 @@ extension MessageService { contactID: contact.id, radioID: contact.radioID, publicKey: contact.publicKey, - sentInfo: sentInfo, - initialPathLength: initialPathLength + acknowledgedCode: acknowledgedCode, + initialPathLength: initialPathLength, + pendingSendID: pendingSendID ) // Broadcast after the DB write so the downstream refetch sees both // the bumped sendCount and the committed terminal status. - if isResend, sentInfo != nil { + if isResend, acknowledgedCode != nil { statusEventBroadcaster.yield(.resent(messageID: messageID)) } @@ -398,202 +380,59 @@ extension MessageService { if error is CancellationError || Task.isCancelled { // ChatSendQueueService replays a cancelled send, so this must not mark the message failed. // Drop the tracked ACK so checkExpiredAcks cannot fail the row after the wait ends. - pendingAcks.removeValue(forKey: messageID) + await discardTrackedAck(messageID: messageID) throw CancellationError() } - try await failMessageAndRethrow(error, messageID: messageID) + if case MessageServiceError.persistenceError = error { throw error } + // Not submitted and table full stay queued. Failing a restored delivery throws + // CancellationError, and the drain would retry that send immediately. + if parksQueuedDirectMessage(error) { + await discardTrackedAck(messageID: messageID) + throw error + } + try await failMessageAndRethrow(error, messageID: messageID, pendingSendID: pendingSendID) } } - // MARK: - Direct Message Retry Loop - - /// Sends a direct message with app-layer retry logic and UI notifications. - /// - /// This function manages the retry loop at the app layer (instead of delegating to MeshCore) - /// to provide per-attempt UI feedback. On each attempt, it: - /// - Updates the message status in the database - /// - Broadcasts `.retrying` for UI retry progress - /// - Switches to flood routing after `floodAfter` failed attempts - /// - Broadcasts `.routingChanged` when routing switches - /// - /// - Parameters: - /// - messageID: The message ID for status updates - /// - contactID: The contact ID for routing change notifications - /// - radioID: The device ID for saving contact updates - /// - publicKey: The full 32-byte destination public key - /// - text: The message text - /// - timestamp: The message timestamp (must remain constant across retries) - /// - timestampRaw: The same timestamp as a `UInt32` epoch-seconds value. The - /// caller must pass the same integer it used to build `timestamp: Date` — - /// resampling inside the loop would break expected-ACK precomputation, - /// since the firmware hash is keyed off the exact `UInt32` that ends up - /// on the wire. - /// - timeout: Optional custom timeout per attempt (nil = use device suggested) - /// - /// - Returns: `MessageSentInfo` if ACK received, `nil` if all attempts exhausted - /// - Throws: `MeshCoreError` if send fails with unrecoverable error - private func sendDirectMessageWithRetryLoop( + /// Installs an acknowledgement owner for attempts already handed to the radio. + /// A missing sender key throws before any write so the queue can retry the handoff. + private func handOffExhaustedDirectMessage( messageID: UUID, - contactID: UUID, - radioID: UUID, - publicKey: Data, - text: String, - timestamp: Date, - timestampRaw: UInt32, - timeout: TimeInterval? - ) async throws -> MessageSentInfo? { - var attempts = 0 - var floodAttempts = 0 - var isFloodMode = false - - while attempts < config.maxAttempts, !isFloodMode || floodAttempts < config.maxFloodAttempts { - // Check for task cancellation - guard !Task.isCancelled else { - throw CancellationError() - } - - // Update database and notify UI of retry status (only after first attempt fails) - if attempts > 0 { - try await dataStore.updateMessageRetryStatus( - id: messageID, - status: .retrying, - retryAttempt: attempts - 1, - maxRetryAttempts: config.maxAttempts - 1 - ) - statusEventBroadcaster.yield(.retrying(messageID: messageID, attempt: attempts - 1, maxAttempts: config.maxAttempts - 1)) - } - - // Switch to flood routing after floodAfter direct attempts - if attempts == config.floodAfter, !isFloodMode { - logger.info("Resetting path to flood after \(attempts) failed attempts") - do { - if let contactService { - try await contactService.resetPath(radioID: radioID, publicKey: publicKey) - } else { - try await session.resetPath(publicKey: publicKey) - _ = try await dataStore.updateContactRoute( - radioID: radioID, - publicKey: publicKey, - outPathLength: PacketBuilder.floodPathSentinel, - outPath: Data() - ) - } - isFloodMode = true - - if try await dataStore.fetchContact(radioID: radioID, publicKey: publicKey) != nil { - statusEventBroadcaster.yield(.routingChanged(contactID: contactID, isFlood: true)) - } - } catch { - logger.warning("Failed to reset path: \(error.localizedDescription), continuing...") - // Continue anyway - device might handle it - isFloodMode = true - } - } - - if attempts > 0 { - logger.info("Retry sending message: attempt \(attempts + 1)/\(config.maxAttempts)") - } - - // Precompute the expected ACK CRC before the send so the persistent - // ACK listener cannot race ahead of trackPendingAck on short direct links. - guard let senderPublicKey = await session.currentSelfInfo?.publicKey else { - throw MessageServiceError.notConnected - } - - let predictedAck = AckCodeBuilder.expectedAck( - timestamp: timestampRaw, - attempt: UInt8(attempts), - text: text, + contact: ContactDTO, + message: MessageDTO, + pendingSendID: UUID + ) async throws -> MessageDTO { + guard let senderPublicKey = await session.currentSelfInfo?.publicKey else { + throw MessageServiceError.notConnected + } + var ackCodes = Set() + for attempt in 0.. 1s could let the checker expire the speculative - // entry before sendMessage returns and we overwrite the timeout with - // the authoritative sentInfo-derived value. - let preSendTimeout = max(timeout ?? config.minTimeout, checkInterval) - trackPendingAck( - messageID: messageID, - contactID: contactID, - ackCode: predictedAck, - timeout: preSendTimeout - ) - - let sentInfo: MessageSentInfo - do { - sentInfo = try await withPoolBackoff(transientCode: FirmwareDeviceErrorCode.directMessageTableFull, config: config.poolBackoff, logger: logger) { - try await session.sendMessage( - to: publicKey.prefix(6), - text: text, - timestamp: timestamp, - attempt: UInt8(attempts) - ) - } - } catch { - // Drop the whole speculative entry on send failure. A partial - // remove would leave an empty-codes PendingAck visible to - // checkExpiredAcks if failMessageAndRethrow is ever bypassed. - pendingAcks.removeValue(forKey: messageID) - throw error - } - - // If the persistent ACK listener consumed our predicted ACK during - // sendMessage's cross-actor suspension, the entry is already - // removed or marked delivered. Short-circuit before waitForEvent - // so the retry loop doesn't clobber .delivered via - // updateMessageRetryStatus and broadcast a duplicate DM. - guard let tracked = pendingAcks[messageID], !tracked.isDelivered else { - return sentInfo - } - - let ackTimeout = timeout ?? max( - config.minTimeout, - Double(sentInfo.suggestedTimeoutMs) / 1000.0 * 1.2 - ) - - if sentInfo.expectedAck != predictedAck { - logger.warning( - "expectedAck mismatch for \(messageID) attempt \(attempts): predicted \(predictedAck.uppercaseHexString()) vs firmware \(sentInfo.expectedAck.uppercaseHexString()); merging firmware code" - ) - trackPendingAck( - messageID: messageID, - contactID: contactID, - ackCode: sentInfo.expectedAck, - timeout: ackTimeout - ) - } else { - // Re-stamp sentAt so checkExpiredAcks measures timeout from - // send-return, not from the speculative insert. - pendingAcks[messageID]?.timeout = ackTimeout - pendingAcks[messageID]?.sentAt = Date() - } - - let ackEvent = await session.waitForEvent( - filter: .acknowledgement(code: sentInfo.expectedAck), - timeout: ackTimeout - ) - - if ackEvent != nil { - logger.info("Message acknowledged on attempt \(attempts + 1)") - return sentInfo - } - - // Listener may have consumed the ACK between the pre-send guard - // and waitForEvent's subscription becoming active; re-check before - // retrying so we don't resend a DM the firmware already delivered. - if pendingAcks[messageID]?.isDelivered != false { - return sentInfo - } - - // ACK timeout - increment counters and retry - attempts += 1 - if isFloodMode { - floodAttempts += 1 - } + )) } - - logger.warning("Message delivery failed after \(attempts) attempts") - return nil + let ackTimeout = max(config.minTimeout, config.ackGiveUpWindow) + let sentAt = Date() + pendingAcks[messageID] = PendingAck( + messageID: messageID, + contactID: contact.id, + ackCodes: ackCodes, + sentAt: sentAt, + timeout: ackTimeout + ) + let saved = await persistAcknowledgement( + messageID: messageID, radioID: contact.radioID, pendingSendID: pendingSendID + ) + guard let current = try await dataStore.fetchMessage(id: messageID) else { + throw MessageServiceError.sendFailed("Message not found") + } + if saved, current.status == .sent { + statusEventBroadcaster.yield(.statusResolved(messageID: messageID, status: .sent, roundTripTime: nil)) + } + return current } // MARK: - Routing Change Detection @@ -640,25 +479,34 @@ extension MessageService { // MARK: - Private Helpers - /// Records a new expected-ACK code for a message awaiting delivery. - /// - /// On the first call for a given `messageID` this creates the entry; on - /// subsequent retry attempts it adds the new `ackCode` to the same entry's - /// `ackCodes` set and resets both `sentAt` and the timeout window to the - /// latest attempt so `checkExpiredAcks` does not fail the in-flight retry. - func trackPendingAck(messageID: UUID, contactID: UUID, ackCode: Data, timeout: TimeInterval) { - // Diagnostic: the firmware ACK CRC is derived from (timestamp, attempt, - // text, sender key) with no recipient, so identical text sent in the - // same second to different contacts produces the same code. Counting - // collisions across distinct in-flight messages measures how often a - // delivery confirmation could be attributed to the wrong message. + /// Accumulates expected ACK codes while awaiting delivery and renews the attempt's timing. + /// `checkExpiredAcks` then preserves the in-flight retry until its deadline. + internal func trackPendingAck( + messageID: UUID, + contactID: UUID, + ackCode: Data, + timeout: TimeInterval, + sendLeaseID: UUID? = nil, + replacingDeliveredTimestamp: Bool = false + ) async { + if !replacingDeliveredTimestamp, + await (try? dataStore.fetchMessage(id: messageID))?.status == .delivered { + return + } + // ACK CRCs omit the recipient, so identical text sent in one second can collide across Contacts. + // Log collisions to diagnose acknowledgements attributed to the wrong DM. if let colliding = pendingAcks.first(where: { $0.key != messageID && $0.value.ackCodes.contains(ackCode) }) { logger.warning("[ack-diag] ackCode collision: code=\(ackCode.uppercaseHexString()) shared by messages \(colliding.key) and \(messageID)") } if var existing = pendingAcks[messageID] { + guard existing.isAwaitingAck else { return } existing.ackCodes.insert(ackCode) existing.sentAt = Date() existing.timeout = timeout + existing.resetOwner() + if let sendLeaseID { + existing.sendLeaseID = sendLeaseID + } pendingAcks[messageID] = existing } else { pendingAcks[messageID] = PendingAck( @@ -666,56 +514,44 @@ extension MessageService { contactID: contactID, ackCodes: [ackCode], sentAt: Date(), - timeout: timeout + timeout: timeout, + sendLeaseID: sendLeaseID ) } } - private func validateDirectMessage(text: String, to contact: ContactDTO) throws { - guard contact.type != .repeater else { throw MessageServiceError.invalidRecipient } + func validateDirectMessage(text: String, to contact: ContactDTO) throws { + guard contact.type != .repeater, contact.type != .sensor else { throw MessageServiceError.invalidRecipient } guard text.utf8.count <= ProtocolLimits.maxDirectMessageLength else { throw MessageServiceError.messageTooLong } } - func finalizeSend( + internal func finalizeSend( messageID: UUID, contactID: UUID, radioID: UUID, publicKey: Data, - sentInfo: MessageSentInfo?, - initialPathLength: UInt8 + acknowledgedCode: Data?, + initialPathLength: UInt8, + pendingSendID: UUID? = nil ) async throws -> MessageDTO { - // Peek the pendingAcks entry without taking ownership. A missing entry - // means `handleAcknowledgement` already processed the ACK (it removes - // the entry on delivery) or `checkExpiredAcks` already failed and - // removed it; an `isDelivered == true` entry means the listener marked - // it mid-flight. In those cases the owner holds the terminal write - // (including `roundTripTime`) and we drop any residual entry and skip - // the DB update here. + // A missing or resolved entry leaves terminal bookkeeping with the ACK listener + // or expiry checker, including the committed round-trip time. let tracking = pendingAcks[messageID] - if tracking == nil || tracking?.isDelivered == true { - pendingAcks.removeValue(forKey: messageID) - } else if let sentInfo { - // The retry loop's waitForEvent matched the ACK. Take ownership and - // record the legitimate `.sent` -> `.delivered` upgrade. + if tracking == nil || tracking?.isResolved == true { + let leaseID = tracking?.sendLeaseID pendingAcks.removeValue(forKey: messageID) - try await dataStore.updateMessageAck( - id: messageID, - ackCode: sentInfo.expectedAck.ackCodeUInt32, - status: .delivered - ) - try await dataStore.updateContactLastMessage(contactID: contactID, date: Date()) - statusEventBroadcaster.yield(.statusResolved(messageID: messageID, status: .delivered, roundTripTime: nil)) + await settlePlainTextLease(leaseID) } else { - // Retry budget spent without an ACK. Neither fail the row nor remove - // the entry: `checkExpiredAcks` owns the give-up at - // max(ackGiveUpWindow, last attempt's ACK timeout), so a - // late-but-legitimate ACK can still upgrade the row. - // `clearRetryingToSent` rolls any `.retrying` status back to `.sent` - // and is terminal-safe: it no-ops if the checker already failed the - // row in the loop's await-gap, so the row stays `.failed` there. - let movedToSent = try await dataStore.clearRetryingToSent(id: messageID) - if movedToSent { + if let acknowledgedCode, tracking?.isAwaitingAck == true { + pendingAcks[messageID]?.recordAcknowledgement(code: acknowledgedCode.ackCodeUInt32, tripTime: nil) + } + // Command issuance ended; durable ACK ownership preserves late matches + // and retries a failed owner save without submitting another command. + let saved = await persistAcknowledgement( + messageID: messageID, radioID: radioID, pendingSendID: pendingSendID + ) + if saved, await (try? dataStore.fetchMessage(id: messageID))?.status == .sent { statusEventBroadcaster.yield(.statusResolved(messageID: messageID, status: .sent, roundTripTime: nil)) } } @@ -728,6 +564,9 @@ extension MessageService { guard let message = try await dataStore.fetchMessage(id: messageID) else { throw MessageServiceError.sendFailed("Failed to fetch message") } + if message.reactionTargetMessageID != nil { + await notifyOutgoingReactionAccepted(messageID: messageID) + } return message } diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+SendHelpers.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendHelpers.swift index 6a328b7e48..4f611fc3cb 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendHelpers.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendHelpers.swift @@ -38,8 +38,8 @@ func withPoolBackoff( } extension MessageService { - func failMessageAndRethrow(_ error: Error, messageID: UUID) async throws -> Never { - pendingAcks.removeValue(forKey: messageID) + func failMessageAndRethrow(_ error: Error, messageID: UUID, pendingSendID: UUID? = nil) async throws -> Never { + await discardTrackedAck(messageID: messageID) // Persistence layer absorbs `.delivered`: if the listener won the race // before the throw path runs, the row stays delivered. Same invariant as // updateMessageRetryStatus and updateMessageAck. The Bool return is @@ -49,7 +49,14 @@ extension MessageService { // above this call; queue-routed catch sites delegate to the queue's // outer catch, which calls `notifyMessageFailed` exactly once on any // non-`CancellationError` escape. - _ = try await dataStore.updateMessageStatusUnlessDelivered(id: messageID, status: .failed) + if let pendingSendID { + let failed = try await dataStore.resolvePendingAcknowledgement( + id: pendingSendID, expectedDeadline: nil, status: .failed, ackCode: nil, roundTripTime: nil + ) + guard failed else { throw CancellationError() } + } else { + _ = try await dataStore.updateMessageStatusUnlessDelivered(id: messageID, status: .failed) + } if let meshError = error as? MeshCoreError { throw MessageServiceError.sessionError(meshError) } diff --git a/MC1Services/Sources/MC1Services/Services/MessageService.swift b/MC1Services/Sources/MC1Services/Services/MessageService.swift index 0064d0b0e7..bd8763e5cc 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService.swift @@ -41,6 +41,9 @@ public actor MessageService { let session: any MeshCoreSessionProtocol let dataStore: any PersistenceStoreProtocol let config: MessageServiceConfig + /// Read once at the start of each DM retry loop. + let dmSendBudgetProvider: @Sendable () -> DMSendBudget + let plainTextSendGate: PlainTextSendGate? /// Contact service for path management (optional - retry with reset requires this). /// Injected by `ServiceContainer` at construction. @@ -52,15 +55,47 @@ public actor MessageService { /// CRCs accumulated across retry attempts, so a late ACK from any attempt /// can still mark the message delivered. var pendingAcks: [UUID: PendingAck] = [:] + /// Keeps teardown waiting for store writes even if their trackers disappear. + var acknowledgementSavesInFlight: Set = [] + var inlineSendsInFlight = 0 + var inlineSendAdmissionClosed = false + var inlineSendWaiters: [CheckedContinuation] = [] + + var acknowledgementSaveWaiters: [CheckedContinuation] = [] #if DEBUG /// Runs before each expired entry's status write. A renewal of a later /// candidate can land while the checker is still on an earlier one. var ackExpiryWriteGateForTesting: (@Sendable (UUID) async -> Void)? + var inlineSendAcceptedGateForTesting: (@Sendable () async -> Void)? + /// Runs after an owner save is entered and before its store commit. + var acknowledgementSaveGateForTesting: (@Sendable () async -> Void)? + /// Runs after consumed attempt codes are tracked and before the radio command. + var directMessageSubmitGateForTesting: (@Sendable (UInt8) async -> Void)? func setAckExpiryWriteGateForTesting(_ gate: (@Sendable (UUID) async -> Void)?) { ackExpiryWriteGateForTesting = gate } + + func setInlineSendAcceptedGateForTesting(_ gate: (@Sendable () async -> Void)?) { + inlineSendAcceptedGateForTesting = gate + } + + func setAcknowledgementSaveGateForTesting(_ gate: (@Sendable () async -> Void)?) { + acknowledgementSaveGateForTesting = gate + } + + func setDirectMessageSubmitGateForTesting(_ gate: (@Sendable (UInt8) async -> Void)?) { + directMessageSubmitGateForTesting = gate + } + + var acknowledgementSaveWaiterCountForTesting: Int { + acknowledgementSaveWaiters.count + } + + var inlineSendWaiterCountForTesting: Int { + inlineSendWaiters.count + } #endif /// Multicast broadcaster for outbound-message lifecycle events. @@ -75,12 +110,15 @@ public actor MessageService { /// Task for listening to session events private var eventListenerTask: Task? + private var bufferedAckEvents: AsyncStream? /// Interval between ACK expiry checks (in seconds) var checkInterval: TimeInterval = 5.0 /// Tracks message IDs currently being retried to prevent concurrent retry attempts var inFlightRetries: Set = [] + /// A failed local acceptance save must not retransmit a reaction the radio already accepted. + var acceptedChannelReactions: Set = [] // MARK: - Initialization @@ -95,12 +133,18 @@ public actor MessageService { session: any MeshCoreSessionProtocol, dataStore: any PersistenceStoreProtocol, contactService: ContactService?, - config: MessageServiceConfig = .default + config: MessageServiceConfig = .default, + ackEvents: AsyncStream? = nil, + dmSendBudget: @escaping @Sendable () -> DMSendBudget = { .default }, + plainTextSendGate: PlainTextSendGate? = nil ) { self.session = session self.dataStore = dataStore self.contactService = contactService self.config = config + dmSendBudgetProvider = dmSendBudget + self.plainTextSendGate = plainTextSendGate + bufferedAckEvents = ackEvents } /// Whether a contact service was injected at construction. @@ -110,6 +154,12 @@ public actor MessageService { // MARK: - Event Listening + func captureAcknowledgementEvents() async { + if bufferedAckEvents == nil { + bufferedAckEvents = await session.events(filter: .anyAcknowledgement) + } + } + /// Starts the session ACK event listener. /// /// Subscribes to `.anyAcknowledgement` events on the session and routes @@ -124,13 +174,15 @@ public actor MessageService { /// which has its own `stopAckExpiryChecking()` / `stopAndFailAllPending()` /// counterparts. `ServiceContainer` pairs both lifecycles together; direct /// callers must do the same. - public func startEventMonitoring() { - eventListenerTask?.cancel() - + public func startEventMonitoring() async { + await stopEventMonitoring() + await captureAcknowledgementEvents() + guard let events = bufferedAckEvents else { return } + bufferedAckEvents = nil eventListenerTask = Task { [weak self] in guard let self else { return } - for await event in await session.events(filter: .anyAcknowledgement) { + for await event in events { guard !Task.isCancelled else { break } if case let .acknowledgement(code, tripTime) = event { @@ -146,70 +198,19 @@ public actor MessageService { /// expiry checker — for that, call `stopAckExpiryChecking()` (just stop /// the checker, used on a routine disconnect) or `stopAndFailAllPending()` /// (stop the checker and fail every in-flight DM, for explicit full teardown). - public func stopEventMonitoring() { - eventListenerTask?.cancel() + public func stopEventMonitoring() async { + let eventListenerTaskToStop = eventListenerTask eventListenerTask = nil + eventListenerTaskToStop?.cancel() + await eventListenerTaskToStop?.value } // MARK: - ACK Handling - /// Processes an acknowledgement from the session event stream. - /// - /// Finds the in-flight message whose accumulated `ackCodes` contains this - /// CRC, marks it delivered, writes the delivery status + round-trip time - /// to the database, and removes the entry. This is the sole DB writer for - /// delivered status on the late-ACK path. + /// A live tracker matches first. A queued row matches an attempt byte already handed to the radio. func handleAcknowledgement(code: Data, tripTime: UInt32?) async { - guard let (messageID, tracking) = pendingAcks.first(where: { - $0.value.ackCodes.contains(code) && !$0.value.isDelivered - }) else { - // Diagnostic: the firmware delivered an end-to-end ACK we have no - // live entry for. This is either a genuinely late ACK that arrived - // after the message was already failed and removed, or a duplicate - // for an already-delivered message. `orphanSentRow` flags a `.sent` - // DM that lost its pending entry to a teardown and would otherwise - // show "Sent" forever; its field rate informs whether a - // reconnect-time orphan sweep is worth adding. - let orphanSentRow = await (try? dataStore.hasOutgoingSentDM(ackCode: code.ackCodeUInt32)) ?? false - logger.warning("[ack-diag] unmatched ACK code=\(code.uppercaseHexString()) livePending=\(pendingAcks.count) orphanSentRow=\(orphanSentRow) (late post-teardown or duplicate)") - return - } - - pendingAcks[messageID]?.isDelivered = true - - // Persist `tripTime` only when firmware supplied it. Date()-based - // fallbacks against `tracking.sentAt` would be wrong in either - // direction once retries reset the timestamp, so we prefer a nil - // `roundTripTime` over a fabricated value. - let ackCodeUInt32 = code.ackCodeUInt32 - - do { - try await dataStore.updateMessageAck( - id: messageID, - ackCode: ackCodeUInt32, - status: .delivered, - roundTripTime: tripTime - ) - } catch { - logger.error("Failed to write delivered status: \(error.localizedDescription)") - } - - do { - try await dataStore.updateContactLastMessage(contactID: tracking.contactID, date: Date()) - } catch { - logger.error("Failed to update contact lastMessageDate: \(error.localizedDescription)") - } - - pendingAcks.removeValue(forKey: messageID) - - statusEventBroadcaster.yield(.statusResolved(messageID: messageID, status: .delivered, roundTripTime: tripTime)) - - // Diagnostic: how long the ACK took relative to the last send attempt - // (sentAt is re-stamped per retry), the firmware-reported round trip, - // and how many other entries were in flight. Distinguishes late-but- - // arriving ACKs from never-arriving ones and measures table pressure. - let ackDelta = Date().timeIntervalSince(tracking.sentAt) - logger.info("[ack-diag] ACK matched deltaSinceLastSend=\(String(format: "%.2f", ackDelta))s firmwareTrip=\(tripTime.map { "\($0)ms" } ?? "nil") livePending=\(pendingAcks.count)") + if await commitLiveAcknowledgement(code: code, tripTime: tripTime) { return } + await claimQueuedDirectMessageAcknowledgement(code: code, tripTime: tripTime) } // MARK: - Status Events diff --git a/MC1Services/Sources/MC1Services/Services/MessageServiceConfig.swift b/MC1Services/Sources/MC1Services/Services/MessageServiceConfig.swift index ebfbaa0043..cf898fadee 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageServiceConfig.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageServiceConfig.swift @@ -1,7 +1,7 @@ import Foundation /// Tuning for the `withPoolBackoff` helper that absorbs short bursts of -/// firmware pool-exhaustion errors before parking the envelope. +/// firmware pool-exhaustion errors before ACK handoff or queue recovery. struct PoolBackoffConfig { /// Maximum in-loop retries before re-throwing the transient `deviceError`. let attemptCap: Int @@ -38,15 +38,6 @@ struct MessageServiceConfig { /// Whether to use flood routing when user manually retries a failed message let floodFallbackOnRetry: Bool - /// Maximum total send attempts for automatic retry - let maxAttempts: Int - - /// Maximum attempts to make after switching to flood routing - let maxFloodAttempts: Int - - /// Number of direct attempts before switching to flood routing - let floodAfter: Int - /// Minimum timeout in seconds (floor for device-suggested timeout) let minTimeout: TimeInterval @@ -68,21 +59,12 @@ struct MessageServiceConfig { init( floodFallbackOnRetry: Bool = true, - maxAttempts: Int = 5, - maxFloodAttempts: Int = 1, - floodAfter: Int = 4, minTimeout: TimeInterval = 0, triggerPathDiscoveryAfterFlood: Bool = true, ackGiveUpWindow: TimeInterval = 30, poolBackoff: PoolBackoffConfig = .default ) { - // 5 = 4 direct + 1 flood. AckCodeBuilder.expectedAck documents why attempt - // indices through 4 stay ACK-unambiguous; past that the cap bounds airtime. - precondition(maxAttempts <= 5, "maxAttempts must be <= 5 (4 direct + 1 flood)") self.floodFallbackOnRetry = floodFallbackOnRetry - self.maxAttempts = maxAttempts - self.maxFloodAttempts = maxFloodAttempts - self.floodAfter = floodAfter self.minTimeout = minTimeout self.triggerPathDiscoveryAfterFlood = triggerPathDiscoveryAfterFlood self.ackGiveUpWindow = ackGiveUpWindow diff --git a/MC1Services/Sources/MC1Services/Services/MessageServiceError.swift b/MC1Services/Sources/MC1Services/Services/MessageServiceError.swift index d3f63552ca..41a6274481 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageServiceError.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageServiceError.swift @@ -17,6 +17,7 @@ public enum MessageServiceError: Error, Sendable { case messageTooLong /// Underlying MeshCore session error case sessionError(MeshCoreError) + case persistenceError(any Error) } extension MessageServiceError: LocalizedError { @@ -29,6 +30,7 @@ extension MessageServiceError: LocalizedError { case .invalidRecipient: "Cannot send messages to this recipient." case .messageTooLong: "Message exceeds the maximum allowed length." case let .sessionError(e): e.localizedDescription + case let .persistenceError(error): error.localizedDescription } } } diff --git a/MC1Services/Sources/MC1Services/Services/MessageStatusEvent.swift b/MC1Services/Sources/MC1Services/Services/MessageStatusEvent.swift index 6d899dbd57..addd1538fe 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageStatusEvent.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageStatusEvent.swift @@ -25,4 +25,5 @@ public enum MessageStatusEvent: Sendable { case routingChanged(contactID: UUID, isFlood: Bool) /// A message failed after exhausting retries or a terminal send error. case failed(messageID: UUID) + case reactionAccepted(messageID: UUID, summary: String) } diff --git a/MC1Services/Sources/MC1Services/Services/NodeConfigImportPlanner.swift b/MC1Services/Sources/MC1Services/Services/NodeConfigImportPlanner.swift index d84fafcc28..d15c98c34b 100644 --- a/MC1Services/Sources/MC1Services/Services/NodeConfigImportPlanner.swift +++ b/MC1Services/Sources/MC1Services/Services/NodeConfigImportPlanner.swift @@ -57,8 +57,8 @@ struct ConfigImportPlan: Equatable { /// Validates a `MeshCoreNodeConfig` against the device's capabilities and current channel /// state, returning a ready-to-execute ``ConfigImportPlan`` or throwing the first problem. /// -/// Pure and synchronous so it is unit-testable without a live `MeshCoreSession` — mirrors the -/// `resolveEffectiveRadioID` seam pattern. Only sections present in `sections` are planned. +/// Pure and synchronous so it is unit-testable without a live `MeshCoreSession`. +/// Only sections present in `sections` are planned. func planConfigImport( config: MeshCoreNodeConfig, sections: ConfigSections, diff --git a/MC1Services/Sources/MC1Services/Services/NodeConfigService.swift b/MC1Services/Sources/MC1Services/Services/NodeConfigService.swift index 2f0b95ece6..c9c47f47e9 100644 --- a/MC1Services/Sources/MC1Services/Services/NodeConfigService.swift +++ b/MC1Services/Sources/MC1Services/Services/NodeConfigService.swift @@ -86,17 +86,19 @@ public struct ImportPreview: Sendable { /// Exports device configuration to `MeshCoreNodeConfig` and imports it back, /// handling section filtering, other-params merging, and safe import ordering. public actor NodeConfigService { - private let session: any MeshCoreSessionProtocol - private let settingsService: SettingsService - private let channelService: ChannelService + private var session: any MeshCoreSessionProtocol + private var settingsService: SettingsService + private var channelService: ChannelService private let dataStore: any PersistenceStoreProtocol - private let contactRadio: (any ContactRadioOwning)? + private var contactRadio: (any ContactRadioOwning)? /// Injected by `ServiceContainer` at construction. private weak var syncCoordinator: SyncCoordinator? private let logger = Logger(subsystem: "com.mc1", category: "NodeConfigService") - /// Called after a config import restores a private key, so the connection layer can - /// reconcile device identity. Installed by `ConnectionManager.buildServicesAndSaveDevice`. - private var onPostIdentityImport: (@Sendable () async throws -> UUID?)? + private var onIdentityImport: (@Sendable (Data) async throws -> UUID?)? + private var importIsRunning = false + private var publicAdmissionRetired = false + private var importedRadioID: UUID? + private var onImportFinished: (@Sendable () async throws -> Void)? public init( session: any MeshCoreSessionProtocol, @@ -114,15 +116,28 @@ public actor NodeConfigService { self.contactRadio = contactRadio } - /// Wires a late-bound callback that fires after `importIdentity` succeeds. - /// The callback is responsible for reconciling the radio's restored - /// `publicKey` with any ghost `Device` row left by a prior "remove from MC1". - /// Its return value, when non-nil, replaces the `radioID` used by all - /// subsequent steps in `importConfig` (channels, contacts). - public func setOnPostIdentityImport( - _ callback: (@Sendable () async throws -> UUID?)? - ) { - onPostIdentityImport = callback + func setIdentityImportHandler(_ handler: @escaping @Sendable (Data) async throws -> UUID?) { + onIdentityImport = handler + } + + func adoptImportRuntime( + session: MeshCoreSession, settingsService: SettingsService, + channelService: ChannelService, syncCoordinator: SyncCoordinator, + contactRadio: any ContactRadioOwning, onImportFinished: @escaping @Sendable () async throws -> Void + ) -> Bool { + guard importIsRunning else { return false } + self.session = session + self.settingsService = settingsService + self.channelService = channelService + self.syncCoordinator = syncCoordinator + self.contactRadio = contactRadio + publicAdmissionRetired = true + self.onImportFinished = onImportFinished + return true + } + + func retirePublicAdmission() { + publicAdmissionRetired = true } /// Whether a sync coordinator was injected at construction. @@ -136,11 +151,18 @@ public actor NodeConfigService { /// - Parameter sections: Which sections to include in the export. /// - Returns: A populated config struct. public func exportConfig(sections: ConfigSections) async throws -> MeshCoreNodeConfig { - let selfInfo = try await settingsService.getSelfInfo() + guard !publicAdmissionRetired else { throw CancellationError() } + let capturedSession = session + let settings = settingsService + let configuration = await settings.configurationSessionForRead() + guard !publicAdmissionRetired else { throw CancellationError() } + let selfInfo = try await settings.getSelfInfo(using: configuration) + guard !publicAdmissionRetired else { throw CancellationError() } var config = MeshCoreNodeConfig() if sections.nodeIdentity { + guard !publicAdmissionRetired else { throw CancellationError() } config.name = selfInfo.name config.publicKey = selfInfo.publicKey.hexString // Hardened firmware disables private-key export (`featureDisabled`). Emit name + @@ -148,7 +170,7 @@ public actor NodeConfigService { // (transient BLE timeout, device error, cancellation) propagates, so the user sees // the export fail and retries instead of saving an identity backup missing its key. do { - let privateKey = try await settingsService.exportPrivateKey() + let privateKey = try await settings.exportPrivateKey(using: configuration) config.privateKey = privateKey.hexString } catch SettingsServiceError.sessionError(.featureDisabled) { logger.warning("Private key export disabled by firmware; exporting identity without it") @@ -171,13 +193,18 @@ public actor NodeConfigService { } if sections.channels { - let capabilities = try await settingsService.queryDevice() - config.channels = try await exportChannels(maxChannels: UInt8(capabilities.maxChannels)) + guard !publicAdmissionRetired else { throw CancellationError() } + let capabilities = try await settings.queryDevice(using: configuration) + config.channels = try await exportChannels(maxChannels: UInt8(capabilities.maxChannels), using: capturedSession) } if sections.contacts { - let meshContacts = try await session.getContacts(since: nil) - config.contacts = meshContacts.map { Self.buildContactConfig(from: $0) } + guard !publicAdmissionRetired else { throw CancellationError() } + let meshContacts = try await capturedSession.getContacts(since: nil) + let exportable = meshContacts.filter { + !VContactIdentity.isVContact(publicKey: $0.publicKey, selfPublicKey: selfInfo.publicKey) + } + config.contacts = exportable.map { Self.buildContactConfig(from: $0) } } return config @@ -203,66 +230,90 @@ public actor NodeConfigService { radioID: UUID, onProgress: (@Sendable (ImportProgress) -> Void)? = nil ) async throws { + guard !publicAdmissionRetired, !importIsRunning else { throw CancellationError() } + importIsRunning = true + importedRadioID = nil + defer { importIsRunning = false; importedRadioID = nil } // Read + validate/plan phase (non-destructive): rejects a poison/malformed config before any write. let plan = try await buildImportPlan(config, sections: sections) // Execute phase, driven through the testable `executeConfigImport` seam. The actor supplies // the concrete write closures; the sequencing, progress, and cancellation live in the seam. - let coordinator = syncCoordinator - try await executeConfigImport( - plan: plan, sections: sections, radioID: radioID, - writers: makeWriters(), logger: logger, onProgress: onProgress, - notifyContactsChanged: { await coordinator?.notifyContactsChanged() } - ) + do { + try await executeConfigImport( + plan: plan, sections: sections, radioID: radioID, + writers: makeWriters(), logger: logger, onProgress: onProgress, + notifyContactsChanged: { [weak self] in await self?.notifyImportedContactsChanged() } + ) + } catch { + try? await finishImportRuntime() + throw error + } + try await finishImportRuntime() + } + + private func finishImportRuntime() async throws { + let completion = onImportFinished + onImportFinished = nil + try await completion?() } - /// Builds the concrete write closures `executeConfigImport` calls, capturing this actor's - /// services. Each closure performs exactly one device (and, for contacts, database) write. + /// Resolves the admitted importer's current runtime at each selected stage. private func makeWriters() -> ConfigImportWriters { - let settings = settingsService - let channels = channelService - let session = session - let store = dataStore - let contactRadio = contactRadio - let logger = logger - let callback = onPostIdentityImport - return ConfigImportWriters( - getSelfInfo: { try await settings.getSelfInfo() }, - importPrivateKey: { try await settings.importPrivateKey($0) }, - setNodeName: { try await settings.setNodeName($0) }, - setLocation: { try await settings.setLocation(latitude: $0, longitude: $1) }, + ConfigImportWriters( + getSelfInfo: { [self] in try await settingsService.getSelfInfo() }, + importPrivateKey: { [self] key in try await importConfigPrivateKey(key) }, + setNodeName: { [self] in try await settingsService.setNodeName($0) }, + setLocation: { [self] in try await settingsService.setLocation(latitude: $0, longitude: $1) }, setOtherParams: { [self] in try await importOtherParams($0) }, - resolveEffectiveRadioID: { - try await resolveEffectiveRadioID(original: $0, didImportPrivateKey: $1, callback: callback) + resolveEffectiveRadioID: { [self] original, didImport in + if didImport, let resolved = await importedRadioID { return resolved } + return original }, - setRadioParams: { radio in - try await settings.applyImportedRadioParams(radio) + setRadioParams: { [self] radio in + try await settingsService.applyImportedRadioParams(radio) }, - setTxPower: { try await settings.setTxPower($0) }, - setChannel: { radioID, write in - try await channels.setChannelWithSecret( - radioID: radioID, index: write.index, name: write.name, secret: write.secret - ) + setTxPower: { [self] in try await settingsService.setTxPower($0) }, + setChannel: { [self] radioID, write in + try await importConfigChannel(radioID: radioID, write: write) }, - addContact: { radioID, contact in - if let contactRadio { - try await contactRadio.importRadioContact(radioID: radioID, contact: contact) - return - } - try await session.addContact(contact) - // The device add is the irreversible change. The local row is an idempotent - // (radioID, publicKey) upsert that the next contacts sync reconciles, so a save - // failure here must not mask that the contact already landed on the device. - do { - let frame = contact.toContactFrame() - _ = try await store.saveContact(radioID: radioID, from: frame) - } catch { - logger.error("Contact added to device but local save failed; next sync will reconcile: \(error.localizedDescription)") - } + addContact: { [self] radioID, contact in + try await importConfigContact(radioID: radioID, contact: contact) } ) } + private func importConfigPrivateKey(_ key: Data) async throws { + if let onIdentityImport { + importedRadioID = try await onIdentityImport(key) + } else { + try await settingsService.importPrivateKey(key) + } + } + + private func importConfigChannel(radioID: UUID, write: ConfigImportPlan.ChannelWrite) async throws { + try await channelService.setChannelWithSecret( + radioID: radioID, index: write.index, name: write.name, secret: write.secret + ) + } + + private func importConfigContact(radioID: UUID, contact: MeshContact) async throws { + if let contactRadio { + try await contactRadio.importRadioContact(radioID: radioID, contact: contact) + return + } + try await session.addContact(contact) + do { + _ = try await dataStore.saveContact(radioID: radioID, from: contact.toContactFrame()) + } catch { + logger.error("Contact added to device but local save failed; next sync will reconcile: \(error.localizedDescription)") + } + } + + private func notifyImportedContactsChanged() async { + await syncCoordinator?.notifyContactsChanged() + } + /// Total destructive steps for progress reporting, derived entirely from the resolved plan so the /// bar reflects post-dedup channel/contact counts and validated sections rather than raw config. /// @@ -304,40 +355,56 @@ public actor NodeConfigService { _ config: MeshCoreNodeConfig, sections: ConfigSections ) async throws -> ConfigImportPlan { - let capabilities = try await settingsService.queryDevice() + guard !publicAdmissionRetired else { throw CancellationError() } + let capturedSession = session + let settings = settingsService + let configuration = await settings.configurationSessionForRead() + guard !publicAdmissionRetired else { throw CancellationError() } + let capabilities = try await settings.queryDevice(using: configuration) + guard !publicAdmissionRetired else { throw CancellationError() } let maxChannels = UInt8(capabilities.maxChannels) let maxContacts = Int(capabilities.maxContacts) let existingChannels = sections.channels - ? try await readExistingChannels(maxChannels: maxChannels) + ? try await readExistingChannels(maxChannels: maxChannels, using: capturedSession) : [] + guard !publicAdmissionRetired else { throw CancellationError() } - // Existing contacts credit firmware updates (which consume no slot) against free capacity, - // so an over-capacity import is rejected up front instead of failing partway through the - // writes. The full records (not just keys) also let the planner drop contacts the device - // already stores byte-for-byte, sparing a redundant /contacts3 commit per unchanged contact. - // ZephCore's virtual V-contact is streamed in GET_CONTACTS but uses no real table slot, so - // exclude it from occupancy; never ADD its derived key either (when V is disabled the - // firmware no longer intercepts ADD and would store it as a real contact). + // Full records let the planner skip a contact the device already stores unchanged. + // The V-contact uses no slot. Omit the live key and the file public key's V-contact; + // contact writes run after the private key changes identity. var existingContacts: [String: MeshContact] = try await sections.contacts ? Dictionary( - session.getContacts(since: nil).map { ($0.publicKey.hexString, $0) }, + capturedSession.getContacts(since: nil).map { ($0.publicKey.hexString, $0) }, uniquingKeysWith: { _, latest in latest } ) : [:] + guard !publicAdmissionRetired else { throw CancellationError() } // Self-info is shared by V-contact capacity filtering and max TX power. let selfInfo = (sections.contacts || sections.radioSettings) - ? try await settingsService.getSelfInfo() + ? try await settings.getSelfInfo(using: configuration) : nil + guard !publicAdmissionRetired else { throw CancellationError() } var planConfig = config - if sections.contacts, let selfPublicKey = selfInfo?.publicKey, - let vKey = VContactIdentity.publicKey(forSelfPublicKey: selfPublicKey) { - let vKeyHex = vKey.hexString - existingContacts.removeValue(forKey: vKeyHex) + if sections.contacts { + var selfKeys: [Data] = [] + if let selfPublicKey = selfInfo?.publicKey { + selfKeys.append(selfPublicKey) + if let vKey = VContactIdentity.publicKey(forSelfPublicKey: selfPublicKey) { + existingContacts.removeValue(forKey: vKey.hexString) + } + } + if let publicKeyHex = planConfig.publicKey, + let fileKey = Data(hexString: publicKeyHex), + fileKey.count == ProtocolLimits.publicKeySize { + selfKeys.append(fileKey) + } if let contacts = planConfig.contacts { - planConfig.contacts = contacts.filter { $0.publicKey.lowercased() != vKeyHex.lowercased() } + planConfig.contacts = contacts.filter { + !VContactIdentity.isVContact(publicKeyHex: $0.publicKey, selfPublicKeys: selfKeys) + } } } @@ -359,11 +426,14 @@ public actor NodeConfigService { } /// Reads every channel slot from the device and classifies it as configured or empty. - private func readExistingChannels(maxChannels: UInt8) async throws -> [DeviceChannelSlot] { + private func readExistingChannels( + maxChannels: UInt8, using capturedSession: any MeshCoreSessionProtocol + ) async throws -> [DeviceChannelSlot] { var slots: [DeviceChannelSlot] = [] for index in 0 as UInt8.. [MeshCoreNodeConfig.ChannelConfig] { + private func exportChannels( + maxChannels: UInt8, using capturedSession: any MeshCoreSessionProtocol + ) async throws -> [MeshCoreNodeConfig.ChannelConfig] { var channels: [MeshCoreNodeConfig.ChannelConfig] = [] for index in 0.. UUID?)? -) async throws -> UUID { - guard didImportPrivateKey, let cb = callback else { - return original - } - if let reconciled = try await cb() { - return reconciled - } - return original -} - // MARK: - Execute Orchestration (testable seam) /// The concrete device/database write operations `executeConfigImport` performs, one per closure. @@ -479,14 +530,8 @@ func txPowerNeedsWrite(_ radio: MeshCoreNodeConfig.RadioSettings, current: SelfI radio.txPower != current.txPower } -/// Executes a validated `ConfigImportPlan` in safe order: identity (so a private-key import can -/// reassign the radioID before channels/contacts are keyed by it), then position, other params, -/// channels, contacts, and radio last. Each `progress(...)` is emitted only after its write -/// succeeds, so "no progress reported" reliably means "nothing was written" — a first-write failure -/// surfaces as a clean failure, not a partial one. -/// -/// Extracted as a free function taking write closures (mirroring `resolveEffectiveRadioID`) so the -/// ordering, progress, and cancellation behavior are unit-testable without a live session. +/// Applies identity before partition-scoped writes and radio settings last to preserve connectivity. +/// Progress follows acknowledged writes; the identity owner separately reports an unknown wire outcome. func executeConfigImport( plan: ConfigImportPlan, sections: ConfigSections, @@ -514,7 +559,12 @@ func executeConfigImport( var effectiveRadioID = radioID if let privateKey = plan.importPrivateKey { try checkCancellation() - try await writers.importPrivateKey(privateKey) + do { + try await writers.importPrivateKey(privateKey) + } catch let failure as ConfigIdentityImportFailure { + progress(.privateKey) + throw failure.underlying + } progress(.privateKey) logger.info("Imported private key") } diff --git a/MC1Services/Sources/MC1Services/Services/NodeSnapshotService.swift b/MC1Services/Sources/MC1Services/Services/NodeSnapshotService.swift index 1b9f9e4af9..5a3d203dee 100644 --- a/MC1Services/Sources/MC1Services/Services/NodeSnapshotService.swift +++ b/MC1Services/Sources/MC1Services/Services/NodeSnapshotService.swift @@ -36,6 +36,42 @@ public actor NodeSnapshotService { } } + public func recordSelfTelemetry( + deviceID: UUID, + radioID: UUID, + nodePublicKey: Data, + telemetry: [TelemetrySnapshotEntry]?, + location: NodeLocationFix? + ) async -> UUID? { + do { + return try await dataStore.recordSelfTelemetrySnapshot( + deviceID: deviceID, + radioID: radioID, + nodePublicKey: nodePublicKey, + telemetry: telemetry, + location: location + ) + } catch { + logger.error("Failed to record self telemetry: \(error)") + return nil + } + } + + public func fetchSelfTelemetry( + radioID: UUID, + nodePublicKey: Data + ) async -> [NodeStatusSnapshotDTO] { + do { + return try await dataStore.fetchSelfTelemetrySnapshots( + radioID: radioID, + nodePublicKey: nodePublicKey + ) + } catch { + logger.error("Failed to fetch self telemetry: \(error)") + return [] + } + } + /// The neighbor baseline for a node: the previous neighbor-bearing snapshot (for /// the SNR delta) plus every neighbor prefix seen across history (for the "New" /// badge). Skips status- or telemetry-only rows and the current in-window capture. diff --git a/MC1Services/Sources/MC1Services/Services/NotificationActionHandler.swift b/MC1Services/Sources/MC1Services/Services/NotificationActionHandler.swift index 4f8218cb45..f87f393bfb 100644 --- a/MC1Services/Sources/MC1Services/Services/NotificationActionHandler.swift +++ b/MC1Services/Sources/MC1Services/Services/NotificationActionHandler.swift @@ -227,7 +227,7 @@ public final class NotificationActionHandler { guard !isMuted else { return } - let truncatedPreview = Self.reactionPreview(for: message.text) + let truncatedPreview = Self.reactionPreview(for: MECPCatalog.displayText(message.text)) let body = notificationService.strings?.reactionNotificationBody( emoji: latestReaction.emoji, messagePreview: truncatedPreview diff --git a/MC1Services/Sources/MC1Services/Services/NotificationService.swift b/MC1Services/Sources/MC1Services/Services/NotificationService.swift index 27b05f776c..b4f78964fc 100644 --- a/MC1Services/Sources/MC1Services/Services/NotificationService.swift +++ b/MC1Services/Sources/MC1Services/Services/NotificationService.swift @@ -298,16 +298,30 @@ public final class NotificationService: NSObject { // MARK: - Sending Notifications + /// Space-joined MECP reading, then the sender prefix. Decode runs on `messageText` + /// alone so a channel body is never parsed as `Ada: MECP/…`. + nonisolated static func arrivalBody( + messageText: String, + senderName: String? = nil, + bundle: Bundle = .main + ) -> String { + let body = MECPCatalog.displayText(messageText, bundle: bundle) + if let senderName { + return "\(senderName): \(body)" + } + return body + } + /// Posts a notification for a direct message. public func postDirectMessageNotification( from contactName: String, contactID: UUID, messageText: String, messageID: UUID, - isMuted: Bool = false + isMuted: Bool = false, + scope: ReceiveScope? = nil ) async { - guard !isMuted else { return } - guard isAuthorized else { return } + guard !isMuted, scope?.isCurrent != false, isAuthorized else { return } // Check granular preference (uses cached preferences) guard preferences.contactMessagesEnabled else { return } @@ -318,7 +332,7 @@ public final class NotificationService: NSObject { let content = UNMutableNotificationContent() content.title = contactName - content.body = messageText + content.body = Self.arrivalBody(messageText: messageText) content.sound = preferences.soundEnabled ? .default : nil content.categoryIdentifier = NotificationCategory.directMessage.rawValue content.userInfo = [ @@ -361,11 +375,10 @@ public final class NotificationService: NSObject { messageText: String, messageID: UUID, notificationLevel: NotificationLevel, - hasSelfMention: Bool + hasSelfMention: Bool, + scope: ReceiveScope ) async { - guard notificationLevel != .muted else { return } - guard notificationLevel != .mentionsOnly || hasSelfMention else { return } - guard isAuthorized else { return } + guard scope.isCurrent, notificationLevel != .muted, notificationLevel != .mentionsOnly || hasSelfMention, isAuthorized else { return } // Check granular preference (uses cached preferences) guard preferences.channelMessagesEnabled else { return } @@ -375,11 +388,7 @@ public final class NotificationService: NSObject { let content = UNMutableNotificationContent() content.title = channelName - if let sender = senderName { - content.body = "\(sender): \(messageText)" - } else { - content.body = messageText - } + content.body = Self.arrivalBody(messageText: messageText, senderName: senderName) content.sound = preferences.soundEnabled ? .default : nil content.categoryIdentifier = NotificationCategory.channelMessage.rawValue content.userInfo = [ @@ -421,10 +430,10 @@ public final class NotificationService: NSObject { senderName: String?, messageText: String, messageID: UUID, - notificationLevel: NotificationLevel + notificationLevel: NotificationLevel, + scope: ReceiveScope? = nil ) async { - guard notificationLevel != .muted else { return } - guard isAuthorized else { return } + guard notificationLevel != .muted, isAuthorized else { return } // Check granular preference guard preferences.roomMessagesEnabled else { return } @@ -434,11 +443,7 @@ public final class NotificationService: NSObject { let content = UNMutableNotificationContent() content.title = roomName - if let sender = senderName { - content.body = "\(sender): \(messageText)" - } else { - content.body = messageText - } + content.body = Self.arrivalBody(messageText: messageText, senderName: senderName) content.sound = preferences.soundEnabled ? .default : nil content.categoryIdentifier = NotificationCategory.roomMessage.rawValue content.userInfo = [ @@ -459,6 +464,7 @@ public final class NotificationService: NSObject { trigger: nil ) + guard scope?.isCurrent != false else { return } do { try await UNUserNotificationCenter.current().add(request) } catch { @@ -487,7 +493,7 @@ public final class NotificationService: NSObject { // Per-type filtering switch contactType { - case .chat: guard preferences.discoveryContactEnabled else { return } + case .chat, .sensor: guard preferences.discoveryContactEnabled else { return } case .repeater: guard preferences.discoveryRepeaterEnabled else { return } case .room: guard preferences.discoveryRoomEnabled else { return } } @@ -527,6 +533,7 @@ public final class NotificationService: NSObject { case .chat: "New Contact Discovered" case .repeater: "New Repeater Discovered" case .room: "New Room Discovered" + case .sensor: "New Sensor Discovered" } } @@ -596,9 +603,7 @@ public final class NotificationService: NSObject { deviceName: String, batteryPercentage: Int ) async { - guard isAuthorized else { return } - - guard preferences.lowBatteryEnabled else { return } + guard isAuthorized, preferences.lowBatteryEnabled else { return } let content = UNMutableNotificationContent() content.title = stringProvider?.lowBatteryTitle ?? "Low Battery" diff --git a/MC1Services/Sources/MC1Services/Services/PendingAck.swift b/MC1Services/Sources/MC1Services/Services/PendingAck.swift index f1fa272a15..9ee67b0922 100644 --- a/MC1Services/Sources/MC1Services/Services/PendingAck.swift +++ b/MC1Services/Sources/MC1Services/Services/PendingAck.swift @@ -1,20 +1,144 @@ import Foundation -/// Tracks pending ACKs for a single outgoing direct message across retry attempts. -/// -/// The firmware hashes the retry attempt index into the expected-ACK CRC, so a -/// single logical message can produce multiple `ackCodes` (one per attempt). -/// All attempts for the same message share one `PendingAck` entry. -/// -/// DM-only: channel/room broadcasts do not generate ACKs and are not tracked here. +/// Tracks a DM's ACK codes across retry attempts. +/// `RoomServerService` waits for Room post ACKs separately. struct PendingAck { + struct Owner: Equatable { + enum WriteKind { + case insert, convert + } + + enum Phase: Equatable { + case pending(WriteKind) + case saving(WriteKind) + case saved + } + + let id: UUID + let radioID: UUID + let deadline: Date + fileprivate(set) var phase: Phase + } + + struct Evidence { + let code: UInt32 + let tripTime: UInt32? + } + + enum Resolution { + case awaitingAck + case matched(Evidence) + case savingDelivery(Evidence) + case savingFailure(Evidence?) + case resolved + } + let messageID: UUID let contactID: UUID var ackCodes: Set var sentAt: Date - /// The latest send attempt's ACK-wait derived from the firmware's `est_timeout` hint. - /// `checkExpiredAcks` reads this as the per-attempt floor on the give-up deadline - /// so a slow high-spreading-factor round-trip is not failed while still in flight. + /// Per-attempt ACK wait derived from the firmware's `est_timeout` hint. + /// Expiry uses it as a floor so a slow round trip is not failed in flight. var timeout: TimeInterval - var isDelivered: Bool = false + private(set) var resolution: Resolution = .awaitingAck + private(set) var owner: Owner? + /// Admission lease for this ACK. A restored live ACK uses its persisted owner ID. + var sendLeaseID: UUID? + /// True after the radio returns `RESP_CODE_SENT` for this timestamp. + var commandAccepted = false + + var isAwaitingAck: Bool { + if case .awaitingAck = resolution { return true } + return false + } + + var isResolved: Bool { + if case .resolved = resolution { return true } + return false + } + + private var matchedEvidence: Evidence? { + switch resolution { + case let .matched(evidence), let .savingDelivery(evidence): evidence + case let .savingFailure(evidence): evidence + case .awaitingAck, .resolved: nil + } + } + + var matchedAckCode: UInt32? { + matchedEvidence?.code + } + + var matchedTripTime: UInt32? { + matchedEvidence?.tripTime + } + + mutating func recordAcknowledgement(code: UInt32, tripTime: UInt32?) { + let evidence = Evidence(code: code, tripTime: tripTime) + switch resolution { + case .awaitingAck: + resolution = .matched(evidence) + case .savingFailure(nil): + resolution = .savingFailure(evidence) + case .matched, .savingDelivery, .savingFailure, .resolved: + break + } + } + + mutating func prepareOwner(radioID: UUID, pendingSendID: UUID?, giveUpWindow: TimeInterval) { + guard owner == nil, !isResolved else { return } + owner = Owner( + id: pendingSendID ?? UUID(), radioID: radioID, + deadline: expiresAt(giveUpWindow: giveUpWindow), + phase: .pending(pendingSendID == nil ? .insert : .convert) + ) + } + + mutating func resetOwner() { + owner = nil + } + + mutating func beginOwnerSave() -> Owner? { + guard !isResolved, case let .pending(kind) = owner?.phase else { return nil } + owner?.phase = .saving(kind) + return owner + } + + mutating func finishOwnerSave(succeeded: Bool) { + guard case let .saving(kind) = owner?.phase else { return } + owner?.phase = succeeded ? .saved : .pending(kind) + } + + mutating func beginResolution() -> MessageStatus? { + if let owner, owner.phase != .saved { return nil } + switch resolution { + case .awaitingAck: + resolution = .savingFailure(nil) + return .failed + case let .matched(evidence): + resolution = .savingDelivery(evidence) + return .delivered + case .savingDelivery, .savingFailure, .resolved: + return nil + } + } + + mutating func resolutionSaveFailed() { + switch resolution { + case let .savingDelivery(evidence): + resolution = .matched(evidence) + case let .savingFailure(evidence): + resolution = evidence.map(Resolution.matched) ?? .awaitingAck + case .awaitingAck, .matched, .resolved: + break + } + } + + mutating func resolutionSaveSucceeded() { + resolution = .resolved + } + + func expiresAt(giveUpWindow: TimeInterval) -> Date { + owner?.deadline ?? sentAt.addingTimeInterval(max(giveUpWindow, timeout)) + } } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Acknowledgements.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Acknowledgements.swift new file mode 100644 index 0000000000..5248c79237 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Acknowledgements.swift @@ -0,0 +1,95 @@ +import Foundation +import SwiftData + +public extension PersistenceStore { + func savePendingAcknowledgement( + _ dto: PendingSendDTO, replacingPendingSendID: UUID?, markSent: Bool = true + ) async throws -> Bool { + try commitPendingRxLogEntries() + let messageID = dto.messageID + let messagePredicate = #Predicate { $0.id == messageID } + guard let message = try modelContext.fetch(FetchDescriptor(predicate: messagePredicate)).first, + message.radioID == dto.radioID, message.channelIndex == nil, + message.status != .delivered, + // A failed row is eligible when this save converts its queued send. + message.status != .failed || replacingPendingSendID != nil else { return false } + + let row: PendingSend + if let replacingPendingSendID { + let targetID = replacingPendingSendID + let predicate = #Predicate { $0.id == targetID } + guard let existing = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first, + existing.messageID == messageID, existing.radioID == dto.radioID, + existing.ackDeadline == nil else { return false } + row = existing + } else { + let pendingPredicate = #Predicate { $0.messageID == messageID } + guard try modelContext.fetch(FetchDescriptor(predicate: pendingPredicate)).isEmpty else { return false } + let scopedRadioID = dto.radioID + let radioPredicate = #Predicate { $0.radioID == scopedRadioID } + var sequenceDescriptor = FetchDescriptor( + predicate: radioPredicate, sortBy: [SortDescriptor(\.sequence, order: .reverse)] + ) + sequenceDescriptor.fetchLimit = 1 + let latest = try modelContext.fetch(sequenceDescriptor).first + row = PendingSend(dto: dto) + row.sequence = (latest?.sequence ?? 0) + 1 + modelContext.insert(row) + } + row.ackCodes = dto.ackCodes + row.ackSentAt = dto.ackSentAt + row.ackDeadline = dto.ackDeadline + if markSent { + message.status = .sent + } else if message.status == .failed { + // Give-up and a late acknowledgement skip a row that is already failed. + message.status = .pending + } + do { + _ = try stageOutgoingReaction(message) + #if DEBUG + try savePendingAcknowledgementFaultInjection?() + #endif + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + return true + } + + func resolvePendingAcknowledgement( + id: UUID, expectedDeadline: Date?, status: MessageStatus, ackCode: UInt32?, roundTripTime: UInt32? + ) async throws -> Bool { + try commitPendingRxLogEntries() + let targetID = id + let predicate = #Predicate { $0.id == targetID } + guard let row = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first, + row.ackDeadline == expectedDeadline else { return false } + let messageID = row.messageID + let messagePredicate = #Predicate { $0.id == messageID } + let message = try modelContext.fetch(FetchDescriptor(predicate: messagePredicate)).first + let shouldUpdate = message != nil && message?.status != .delivered && message?.status != .failed + if shouldUpdate, let message { + message.status = status + if status == .failed { message.failureSeen = false } + if let ackCode { message.ackCode = ackCode } + if let roundTripTime { message.roundTripTime = roundTripTime } + } + do { + if let message { _ = try stageOutgoingReaction(message) } + if row.ackDeadline != nil { modelContext.delete(row) } + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + return shouldUpdate + } + + #if DEBUG + func setSavePendingAcknowledgementFaultInjection(_ hook: (@Sendable () throws -> Void)?) { + savePendingAcknowledgementFaultInjection = hook + } + #endif +} diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift index ad54daa20f..93b344946d 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift @@ -82,13 +82,8 @@ extension PersistenceStore { _ dtos: [DeviceDTO], existingKeys: Set ) throws -> (inserted: Int, skipped: Int) { - // Assign a fresh Device.id on insert: the backup UUID was `CBPeripheral.identifier` - // from the source phone, and `Device.id` is `@Attribute(.unique)`. Reusing the - // backup UUID here could collide with a live local peripheral identifier and - // trigger SwiftData's upsert, silently overwriting the current Device row. - // Child records key by `radioID`, not `Device.id`, so the fresh id breaks no - // linkage; `ConnectionManager.buildServicesAndSaveDevice` cleans up the stub - // row when the user reconnects to the real radio. + // Remint Device ID to avoid upserting a local row with the source phone's handle. + // Children retain their Radio ID; public-key reconciliation reconnects the imported record. insertUnique( dtos, existingKeys: existingKeys, @@ -130,6 +125,9 @@ extension PersistenceStore { inserted += 1 } + for radioID in Set(dtos.map(\.radioID)) { + try bindRecentlyBlockedContacts(radioID: radioID) + } return (inserted, skipped, merged, contactIDsByKey) } @@ -309,8 +307,7 @@ extension PersistenceStore { existingKeys: Set, existingIDsByKey: [String: [UUID]] ) throws -> ( - inserted: Int, - skipped: Int, + counts: PerTypeCounts, messageIDByBackupID: [UUID: UUID], skippedIncomingParents: [(localMessageID: UUID, dto: MessageDTO)] ) { @@ -319,9 +316,11 @@ extension PersistenceStore { var knownIDs = Set(existingIDsByKey.values.flatMap(\.self)) var messageIDByBackupID: [UUID: UUID] = [:] var skippedIncomingParents: [(localMessageID: UUID, dto: MessageDTO)] = [] + var skippedOutgoingMessages: [MessageDTO] = [] var toInsert: [MessageDTO] = [] toInsert.reserveCapacity(dtos.count) var skipped = 0 + var merged = 0 // Pass 1: resolve duplicates and build the backup→local ID remap. Doing this // before any insert lets pass 2 rewrite replyToID onto winning local UUIDs, @@ -336,6 +335,8 @@ extension PersistenceStore { } if dto.direction == .incoming { skippedIncomingParents.append((localMessageID: winning ?? dto.id, dto: dto)) + } else { + skippedOutgoingMessages.append(dto) } skipped += 1 continue @@ -357,12 +358,25 @@ extension PersistenceStore { if let replyTo = dto.replyToID, let winning = messageIDByBackupID[replyTo] { dto.replyToID = winning } + if let targetID = dto.reactionTargetMessageID, let winning = messageIDByBackupID[targetID] { + dto.reactionTargetMessageID = winning + } modelContext.insert(Message(dto: dto)) } + for var dto in skippedOutgoingMessages { + if let targetID = dto.reactionTargetMessageID, let winning = messageIDByBackupID[targetID] { + dto.reactionTargetMessageID = winning + } + let id = dto.id + let predicate = #Predicate { $0.id == id } + if let message = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first, mergeBackupMetadata(into: message, from: dto) { + merged += 1 + } + } + return ( - inserted: toInsert.count, - skipped: skipped, + counts: PerTypeCounts(inserted: toInsert.count, merged: merged, skipped: skipped), messageIDByBackupID: messageIDByBackupID, skippedIncomingParents: skippedIncomingParents ) @@ -454,8 +468,7 @@ extension PersistenceStore { continue } - guard let foreignPath, foreignPath != parent.pathNodes else { continue } - guard extrasByMessage[localID, default: []].insert(foreignPath).inserted else { continue } + guard let foreignPath, foreignPath != parent.pathNodes, extrasByMessage[localID, default: []].insert(foreignPath).inserted else { continue } modelContext.insert(MessageRepeat( dto: MessageRepeatDTO( messageID: localID, @@ -643,14 +656,42 @@ extension PersistenceStore { @discardableResult func batchInsertNodeStatusSnapshots( _ dtos: [NodeStatusSnapshotDTO], - existingKeys: Set + existingKeys: Set, + existingIDs: Set, + radioIDMapping: [UUID: UUID] ) throws -> (inserted: Int, skipped: Int) { - insertUnique( - dtos, - existingKeys: existingKeys, - key: { nodeStatusSnapshotKey(nodePublicKey: $0.nodePublicKey, timestamp: $0.timestamp) }, - construct: NodeStatusSnapshot.init(dto:) - ) + let devices = try modelContext.fetch(FetchDescriptor()) + let validRadioIDs = Set(devices.map(\.radioID)) + var knownKeys = existingKeys + var knownIDs = existingIDs + var inserted = 0 + + for incoming in dtos { + let owner: UUID? + if let incomingOwner = incoming.selfRadioID { + // A backup made before ghost reconciliation must not overwrite the adopted owner. + guard !knownIDs.contains(incoming.id), + let remapped = radioIDMapping[incomingOwner], + validRadioIDs.contains(remapped) else { continue } + owner = remapped + } else { + owner = nil + } + + let key = nodeStatusSnapshotKey( + nodePublicKey: incoming.nodePublicKey, + timestamp: incoming.timestamp, + selfRadioID: owner + ) + guard knownKeys.insert(key).inserted else { continue } + + let snapshot = NodeStatusSnapshot(dto: incoming) + snapshot.selfRadioID = owner + modelContext.insert(snapshot) + knownIDs.insert(incoming.id) + inserted += 1 + } + return (inserted, dtos.count - inserted) } @discardableResult diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupHelpers.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupHelpers.swift index b9ba6edd27..24e28d94b1 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupHelpers.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupHelpers.swift @@ -99,15 +99,13 @@ extension PersistenceStore { "\(radioID)-\(publicKey.base64EncodedString())" } - func nodeStatusSnapshotKey(nodePublicKey: Data, timestamp: Date) -> String { - // Use milliseconds (Int) to stay stable across JSON `.secondsSince1970` - // encode/decode roundtrips — Double.bitPattern can drift on roundtrip - // even when the two Dates compare equal. - // Two distinct snapshots for one node within the same millisecond intentionally - // coalesce (the second is counted as skipped). This is acceptable, rare diagnostic - // coalescing; the id is deliberately not part of the key so re-import stays idempotent. + func nodeStatusSnapshotKey(nodePublicKey: Data, timestamp: Date, selfRadioID: UUID?) -> String { + // Millisecond precision keeps keys stable across JSON date round trips. let milliseconds = Int(timestamp.timeIntervalSince1970 * 1000) - return "\(nodePublicKey.base64EncodedString())-\(milliseconds)" + let base = "\(nodePublicKey.base64EncodedString())-\(milliseconds)" + // Include the Radio ID so self readings cannot merge with remote history. + guard let selfRadioID else { return base } + return "\(selfRadioID.uuidString)-\(base)" } /// Rewrite the contact-UUID segment of a DM dedup key. Only the `dm-{uuid}-` prefix @@ -185,6 +183,19 @@ extension PersistenceStore { // MARK: - Merge pre-existing rows from backup metadata extension PersistenceStore { + func mergeBackupMetadata(into message: Message, from dto: MessageDTO) -> Bool { + var changed = false + if message.reactionTargetMessageID == nil, let targetID = dto.reactionTargetMessageID { + message.reactionTargetMessageID = targetID + changed = true + } + if message.reactionSenderName == nil, let senderName = dto.reactionSenderName { + message.reactionSenderName = senderName + changed = true + } + return changed + } + func mergeBackupMetadata(into contact: Contact, from dto: ContactDTO) -> Bool { var changed = false if contact.nickname == nil, let backupNickname = dto.nickname { diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift index 7be09ac9a2..8328458574 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift @@ -83,12 +83,24 @@ public extension PersistenceStore { return Set(senders.map { blockedChannelSenderKey(radioID: $0.radioID, name: $0.name) }) } - func existingNodeStatusSnapshotKeys() throws -> Set { + func existingNodeStatusSnapshotIdentity() throws -> (keys: Set, ids: Set) { let descriptor = FetchDescriptor() let snapshots = try modelContext.fetch(descriptor) - return Set(snapshots.map { - nodeStatusSnapshotKey(nodePublicKey: $0.nodePublicKey, timestamp: $0.timestamp) - }) + var keys = Set() + var ids = Set() + keys.reserveCapacity(snapshots.count) + ids.reserveCapacity(snapshots.count) + for snapshot in snapshots { + keys.insert( + nodeStatusSnapshotKey( + nodePublicKey: snapshot.nodePublicKey, + timestamp: snapshot.timestamp, + selfRadioID: snapshot.selfRadioID + ) + ) + ids.insert(snapshot.id) + } + return (keys, ids) } func existingDiscoveredNodeKeys(radioIDs: Set) throws -> Set { @@ -130,9 +142,7 @@ public extension PersistenceStore { modelContext.autosaveEnabled = false defer { - if !didCommit { - modelContext.rollback() - } + if !didCommit { modelContext.rollback() } modelContext.autosaveEnabled = originalAutosaveEnabled } @@ -257,7 +267,7 @@ public extension PersistenceStore { existingKeys: messageLookups.keys, existingIDsByKey: messageLookups.idsByKey ) - result.record(.messages, inserted: messageResult.inserted, skipped: messageResult.skipped, dropped: droppedChildren.messages) + result.record(.messages, inserted: messageResult.counts.inserted, merged: messageResult.counts.merged, skipped: messageResult.counts.skipped, dropped: droppedChildren.messages) let messageIDMapping = messageResult.messageIDByBackupID let allMessageIDs = Set(messages.map { messageIDMapping[$0.id] ?? $0.id }) @@ -319,10 +329,12 @@ public extension PersistenceStore { ) result.record(.blockedChannelSenders, inserted: blockedResult.inserted, skipped: blockedResult.skipped) - let existingSnapshotKeys = try existingNodeStatusSnapshotKeys() + let snapshotIdentity = try existingNodeStatusSnapshotIdentity() let snapshotResult = try batchInsertNodeStatusSnapshots( envelope.nodeStatusSnapshots, - existingKeys: existingSnapshotKeys + existingKeys: snapshotIdentity.keys, + existingIDs: snapshotIdentity.ids, + radioIDMapping: radioMap.mapping ) result.record(.nodeStatusSnapshots, inserted: snapshotResult.inserted, skipped: snapshotResult.skipped) @@ -351,6 +363,7 @@ public extension PersistenceStore { #endif try modelContext.save() didCommit = true + publishRecentlyBlockedChange() #if DEBUG backupImportPostCommitHook?() diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+ChannelReceive.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+ChannelReceive.swift new file mode 100644 index 0000000000..9f4e92386d --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+ChannelReceive.swift @@ -0,0 +1,50 @@ +import Foundation + +public extension PersistenceStore { + func shouldSuppressChannelMessage( + _ message: MessageDTO, + frame: ChannelMessage, + channel: ChannelDTO, + scope: ReceiveScope, + preference: TextRulesPreference? + ) async throws -> Bool { + guard scope.isCurrent, scope.radioID == message.radioID else { return true } + guard let conversationID = channel.textRulesID else { return false } + guard let current = try fetchChannel(radioID: message.radioID, index: frame.channelIndex), + current.textRulesID == conversationID else { return true } + + let identity = RecentlyBlockedMessageDTO.Identity( + radioID: message.radioID, + conversationID: conversationID, + senderPrefix: nil, + senderTimestamp: UInt32(frame.senderTimestamp.timeIntervalSince1970), + textType: frame.textType, + wireText: Data(frame.text.utf8) + ) + if try hasRecentlyBlockedMessage(identity) { return true } + + let kind = TextRulesPreference.channelKind(isPublic: current.isPublicChannel, name: current.name) + let key = TextRulesPreference.Key(radioID: message.radioID, conversationID: conversationID) + guard let preference, + !preference.rules.isEmpty, + preference.effective(for: kind, key: key, override: current.textRulesOverride).isOn else { return false } + + let fields = ChannelMessageFormat.originalFields(frame.text) + let isReaction = ReactionParser.isReactionText(message.text, isDM: false) + guard let match = preference.firstMatch(body: isReaction ? nil : fields.body, sender: fields.sender) else { + return false + } + if !isReaction { + try recordRecentlyBlockedMessage(RecentlyBlockedMessageDTO( + identity: identity, + arrivedAt: message.createdAt, + body: fields.body, + sender: fields.sender, + conversationName: current.name, + radioName: fetchDevice(radioID: message.radioID)?.nodeName, + match: match + )) + } + return true + } +} diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Channels.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Channels.swift index 65d5bd0793..95c6b7ad21 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Channels.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Channels.swift @@ -301,9 +301,20 @@ public extension PersistenceStore { /// Stages message, PendingSend, Reaction, and MessageRepeat deletes as registered /// objects so a caller's `rollback()` restores them. Chunked under SQLITE_MAX_VARIABLE_NUMBER. + /// A channel pending row for this slot is removed even when its message is already gone. private func _deleteMessagesForChannelWithoutSaving(radioID: UUID, channelIndex: UInt8) throws { let targetRadioID = radioID let targetChannelIndex: UInt8? = channelIndex + let channelKind = PendingSendKind.channel.rawValue + let pendingPredicate = #Predicate { row in + row.radioID == targetRadioID + && row.channelIndex == targetChannelIndex + && row.kindRawValue == channelKind + } + for row in try modelContext.fetch(FetchDescriptor(predicate: pendingPredicate)) { + modelContext.delete(row) + } + let messagePredicate = #Predicate { message in message.radioID == targetRadioID && message.channelIndex == targetChannelIndex } @@ -334,6 +345,8 @@ public extension PersistenceStore { private func applyRadioChannelInfo(_ info: ChannelInfo, to row: Channel) throws { if row.secret != info.secret { try _deleteMessagesForChannelWithoutSaving(radioID: row.radioID, channelIndex: row.index) + row.textRulesID = UUID() + row.textRulesOverrideRawValue = TextRulesPreference.Override.inherit.rawValue row.lastMessageDate = nil row.unreadCount = 0 row.unreadMentionCount = 0 diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Connection.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Connection.swift new file mode 100644 index 0000000000..ff824960bb --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Connection.swift @@ -0,0 +1,95 @@ +import Foundation +import SwiftData + +extension PersistenceStore { + /// Applies an accepted field update without yielding between the fresh read and save. + @discardableResult + func updateConnectionDevice(id: UUID, update: @Sendable (DeviceDTO) -> DeviceDTO?) throws -> Bool { + guard let current = try fetchDevice(id: id), let updated = update(current) else { return false } + try saveDevice(updated) + return true + } + + /// Registers authenticated radio observations while preserving the store's current local state. + func registerConnectionDevice(_ observation: DeviceDTO, bluetoothPeripheralID: UUID?) throws -> DeviceDTO { + let current = try fetchDevice(id: observation.id) ?? fetchDevice(publicKey: observation.publicKey) + guard try !isRadioErasePending(current?.radioID ?? observation.radioID) else { + throw ConnectionError.deviceNotFound + } + let merged: DeviceDTO = if let current { + current.copy { + $0.id = observation.id + if let bluetoothPeripheralID { + $0.connectionMethods = $0.connectionMethods.map { method in + guard case let .bluetooth(_, displayName) = method else { return method } + return .bluetooth(peripheralUUID: bluetoothPeripheralID, displayName: displayName) + } + } + $0.publicKey = observation.publicKey + $0.nodeName = observation.nodeName + $0.firmwareVersion = observation.firmwareVersion + $0.firmwareVersionString = observation.firmwareVersionString + $0.manufacturerName = observation.manufacturerName + $0.buildDate = observation.buildDate + $0.maxContacts = observation.maxContacts + $0.maxChannels = observation.maxChannels + $0.frequency = observation.frequency + $0.bandwidth = observation.bandwidth + $0.spreadingFactor = observation.spreadingFactor + $0.codingRate = observation.codingRate + $0.txPower = observation.txPower + $0.maxTxPower = observation.maxTxPower + $0.latitude = observation.latitude + $0.longitude = observation.longitude + $0.blePin = observation.blePin + $0.manualAddContacts = observation.manualAddContacts + $0.autoAddConfig = observation.autoAddConfig + $0.autoAddMaxHops = observation.autoAddMaxHops + $0.multiAcks = observation.multiAcks + $0.telemetryModeBase = observation.telemetryModeBase + $0.telemetryModeLoc = observation.telemetryModeLoc + $0.telemetryModeEnv = observation.telemetryModeEnv + $0.advertLocationPolicy = observation.advertLocationPolicy + $0.clientRepeat = observation.clientRepeat + $0.pathHashMode = observation.pathHashMode + if $0.ocvPreset == nil { $0.ocvPreset = observation.ocvPreset } + if !observation.clientRepeat { + $0.preRepeatFrequency = nil + $0.preRepeatBandwidth = nil + $0.preRepeatSpreadingFactor = nil + $0.preRepeatCodingRate = nil + } + } + } else { + observation.copy { + $0.isActive = false + $0.connectionMethods = [] + } + } + try saveDevice(merged) + if let current, current.id != merged.id { try deleteDevice(id: current.id) } + return merged + } + + /// Selects from a fresh row so a delayed connection cannot restore old preferences or endpoints. + func selectConnectionDevice(id: UUID, method: ConnectionMethod?) throws -> DeviceDTO { + guard let current = try fetchDevice(id: id) else { throw PersistenceStoreError.deviceNotFound } + guard try !isRadioErasePending(current.radioID) else { throw ConnectionError.deviceNotFound } + let selected = current.copy { + if let method { + $0.connectionMethods.removeAll { $0.isBluetooth == method.isBluetooth } + $0.connectionMethods.append(method) + } + } + try saveDevice(selected) + try setActiveDevice(id: id) + return try fetchDevice(id: id) ?? selected + } + + func clearActiveConnection() throws { + for device in try modelContext.fetch(FetchDescriptor()) { + device.isActive = false + } + try modelContext.save() + } +} diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Contacts.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Contacts.swift index 057db5bc8a..e24288b42d 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Contacts.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Contacts.swift @@ -116,6 +116,7 @@ public extension PersistenceStore { /// Save or update a contact from a ContactFrame. /// Returns the contact id and whether the row was newly inserted (`isNew`). func saveContact(radioID: UUID, from frame: ContactFrame) throws -> (id: UUID, isNew: Bool) { + try commitPendingRxLogEntries() let targetRadioID = radioID let targetKey = frame.publicKey let predicate = #Predicate { contact in @@ -136,7 +137,7 @@ public extension PersistenceStore { isNew = true } - try modelContext.save() + try saveContactChangesBindingRecentlyBlocked(radioID: radioID) return (id: contact.id, isNew: isNew) } @@ -145,6 +146,7 @@ public extension PersistenceStore { @discardableResult func batchSaveContacts(radioID: UUID, from frames: [ContactFrame]) async throws -> Int { guard !frames.isEmpty else { return 0 } + try commitPendingRxLogEntries() let referenceDate = Date() let targetRadioID = radioID @@ -170,7 +172,7 @@ public extension PersistenceStore { } } - try modelContext.save() + try saveContactChangesBindingRecentlyBlocked(radioID: radioID) return frames.count } @@ -188,6 +190,7 @@ public extension PersistenceStore { /// Save or update a contact from DTO func saveContact(_ dto: ContactDTO) throws { + try commitPendingRxLogEntries() let targetID = dto.id let predicate = #Predicate { contact in contact.id == targetID @@ -201,11 +204,12 @@ public extension PersistenceStore { modelContext.insert(Contact(dto: dto)) } - try modelContext.save() + try saveContactChangesBindingRecentlyBlocked(radioID: dto.radioID) } @discardableResult func insertContactIfAbsent(radioID: UUID, from frame: ContactFrame) throws -> (id: UUID, isNew: Bool) { + try commitPendingRxLogEntries() let targetRadioID = radioID let targetKey = frame.publicKey let predicate = #Predicate { contact in @@ -220,7 +224,7 @@ public extension PersistenceStore { let contact = Contact(radioID: radioID, from: frame) modelContext.insert(contact) - try modelContext.save() + try saveContactChangesBindingRecentlyBlocked(radioID: radioID) return (id: contact.id, isNew: true) } @@ -378,17 +382,21 @@ public extension PersistenceStore { try commitPendingRxLogEntries() do { try _stageOverwriteOldestCascade(contactID: id) + try stageRecentlyBlockedContactDeletion(contactID: id) let targetID = id let predicate = #Predicate { contact in contact.id == targetID } if let contact = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first { + let radioID = contact.radioID modelContext.delete(contact) + try bindRecentlyBlockedContacts(radioID: radioID) } #if DEBUG try deleteContactsFaultInjection?() #endif try modelContext.save() + publishRecentlyBlockedChange() } catch { modelContext.rollback() throw error @@ -439,14 +447,17 @@ public extension PersistenceStore { if skippingPublicKeys().contains(publicKey) { continue } let contactID = contact.id try _stageOverwriteOldestCascade(contactID: contactID) + try stageRecentlyBlockedContactDeletion(contactID: contactID) modelContext.delete(contact) deletedIDs.append(contactID) } if !deletedIDs.isEmpty { + try bindRecentlyBlockedContacts(radioID: radioID) #if DEBUG try deleteContactsFaultInjection?() #endif try modelContext.save() + publishRecentlyBlockedChange() } } catch { modelContext.rollback() @@ -458,7 +469,7 @@ public extension PersistenceStore { /// Insert-only rollback: probe for messages and delete in one ModelActor /// region with no suspension between them. Prefer an orphan contact over a /// cascade that wipes a concurrent DM. - func deleteContactIfUnreferenced(id: UUID) throws { + func deleteContactIfUnreferenced(id: UUID) async throws { let targetID = id let messagePredicate = #Predicate { message in message.contactID == targetID @@ -468,6 +479,7 @@ public extension PersistenceStore { if try modelContext.fetch(messageDescriptor).first != nil { return } + guard try !hasRecentlyBlockedContactReference(contactID: id) else { return } try deleteContact(id: id) } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Devices.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Devices.swift index c922fd9355..55e90adae1 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Devices.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Devices.swift @@ -91,6 +91,17 @@ public extension PersistenceStore { try modelContext.save() } + /// Updates local OCV fields without replacing connection identity or inserting a row. + func updateDeviceOCVSettings(id: UUID, preset: String, customArray: String?) throws -> DeviceDTO? { + guard let device = try fetchDevice(id: id) else { return nil } + let updated = device.copy { + $0.ocvPreset = preset + $0.customOCVArrayString = customArray + } + try saveDevice(updated) + return updated + } + /// Set a device as active (deactivates others) func setActiveDevice(id: UUID) throws { // Deactivate all devices first @@ -138,115 +149,6 @@ public extension PersistenceStore { try modelContext.save() } - func updateDeviceNodeName(radioID: UUID, name: String) throws { - try updateExistingDevice(radioID: radioID) { $0.nodeName = name } - } - - func updateDeviceCoordinates(radioID: UUID, latitude: Double, longitude: Double) throws { - try updateExistingDevice(radioID: radioID) { - $0.latitude = latitude - $0.longitude = longitude - } - } - - func updateDeviceRadio( - radioID: UUID, - frequency: UInt32, - bandwidth: UInt32, - spreadingFactor: UInt8, - codingRate: UInt8, - appliedRadioPresetID: String? - ) throws { - try updateExistingDevice(radioID: radioID) { - $0.frequency = frequency - $0.bandwidth = bandwidth - $0.spreadingFactor = spreadingFactor - $0.codingRate = codingRate - $0.appliedRadioPresetID = appliedRadioPresetID - } - } - - func updateDeviceTxPower(radioID: UUID, txPower: Int8) throws { - try updateExistingDevice(radioID: radioID) { $0.txPower = txPower } - } - - func updateDeviceObservation(radioID: UUID, mapped: DeviceDTO) throws { - try updateExistingDevice(radioID: radioID) { device in - device.publicKey = mapped.publicKey - device.nodeName = mapped.nodeName - device.latitude = mapped.latitude - device.longitude = mapped.longitude - device.frequency = mapped.frequency - device.bandwidth = mapped.bandwidth - device.spreadingFactor = mapped.spreadingFactor - device.codingRate = mapped.codingRate - device.txPower = mapped.txPower - device.manualAddContacts = mapped.manualAddContacts - device.multiAcks = mapped.multiAcks - device.telemetryModeBase = mapped.telemetryModeBase - device.telemetryModeLoc = mapped.telemetryModeLoc - device.telemetryModeEnv = mapped.telemetryModeEnv - device.advertLocationPolicy = mapped.advertLocationPolicy - device.appliedRadioPresetID = mapped.appliedRadioPresetID - } - } - - func updateDeviceOtherParams(radioID: UUID, intent: OtherParamsIntent) throws { - try updateExistingDevice(radioID: radioID) { device in - if let manualAddContacts = intent.manualAddContacts { - device.manualAddContacts = manualAddContacts - } - if let telemetryModeBase = intent.telemetryModeBase { - device.telemetryModeBase = telemetryModeBase - } - if let telemetryModeLocation = intent.telemetryModeLocation { - device.telemetryModeLoc = telemetryModeLocation - } - if let telemetryModeEnvironment = intent.telemetryModeEnvironment { - device.telemetryModeEnv = telemetryModeEnvironment - } - if let advertisementLocationPolicy = intent.advertisementLocationPolicy { - device.advertLocationPolicy = advertisementLocationPolicy - } - if let multiAcks = intent.multiAcks { - device.multiAcks = multiAcks - } - } - } - - func updateDeviceClientRepeat(radioID: UUID, enabled: Bool) throws { - try updateExistingDevice(radioID: radioID) { $0.clientRepeat = enabled } - } - - func updateDevicePathHashMode(radioID: UUID, mode: UInt8) throws { - try updateExistingDevice(radioID: radioID) { $0.pathHashMode = mode } - } - - func updateDeviceAutoAdd(radioID: UUID, config: UInt8, maxHops: UInt8) throws { - try updateExistingDevice(radioID: radioID) { - $0.autoAddConfig = config - $0.autoAddMaxHops = maxHops - } - } - - func updateDeviceDefaultFloodScopeName(radioID: UUID, name: String?) throws { - try updateExistingDevice(radioID: radioID) { $0.defaultFloodScopeName = name } - } - - private func updateExistingDevice(radioID: UUID, _ body: (Device) -> Void) throws { - let targetRadioID = radioID - let predicate = #Predicate { device in - device.radioID == targetRadioID - } - var descriptor = FetchDescriptor(predicate: predicate) - descriptor.fetchLimit = 1 - guard let device = try modelContext.fetch(descriptor).first else { - throw PersistenceStoreError.deviceNotFound - } - body(device) - try modelContext.save() - } - /// Adds a known region to a device if not already present func addDeviceKnownRegion(radioID: UUID, region: String) throws { let targetRadioID = radioID @@ -291,8 +193,17 @@ public extension PersistenceStore { /// RX log entries, discovered nodes, contacts, messages, channels, and saved trace paths. /// Does NOT delete the Device record itself. func deleteDeviceData(id: UUID) throws { - try _deleteAllDeviceData(id: id) - try modelContext.save() + guard let radioID = try fetchDevice(id: id)?.radioID else { return } + try commitPendingRxLogEntries() + do { + try stageDeleteAllDeviceData(radioID: radioID) + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + retireReceiveScope(radioID: radioID) + publishRecentlyBlockedChange() } /// Delete a device record only. Does NOT delete associated data. @@ -361,16 +272,21 @@ public extension PersistenceStore { /// Delete a device and all its associated data atomically (single save). /// Use for factory reset and explicit "delete all data" user action. func deleteDeviceAndData(id: UUID) throws { - try _deleteAllDeviceData(id: id) - - let targetID = id - let devicePredicate = #Predicate { device in - device.id == targetID - } - if let device = try modelContext.fetch(FetchDescriptor(predicate: devicePredicate)).first { - modelContext.delete(device) + guard let radioID = try fetchDevice(id: id)?.radioID else { return } + try commitPendingRxLogEntries() + do { + try stageDeleteAllDeviceData(radioID: radioID) + let predicate = #Predicate { $0.id == id } + if let device = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first { + modelContext.delete(device) + } + try modelContext.save() + } catch { + modelContext.rollback() + throw error } - try modelContext.save() + retireReceiveScope(radioID: radioID) + publishRecentlyBlockedChange() } /// Looks for a ghost `Device` row whose `publicKey` matches `newPublicKey` @@ -397,30 +313,73 @@ public extension PersistenceStore { /// - newPublicKey: The radio's `selfInfo.publicKey` after `importPrivateKey`. /// - Returns: The new `radioID` if reconciliation occurred, otherwise `nil`. func reconcileGhostIdentity(currentDeviceID: UUID, newPublicKey: Data) throws -> UUID? { + guard let current = try identityDevice(id: currentDeviceID), + try !isRadioErasePending(current.radioID) else { return nil } + try commitPendingRxLogEntries() + do { + guard let adoption = try stageGhostIdentity(current: current, newPublicKey: newPublicKey) else { return nil } + try saveIdentityChanges(retiring: adoption.abandonedRadioID) + return adoption.radioID + } catch { + modelContext.rollback() + throw error + } + } + + /// Saves an authenticated identity observation and its canonical partition in one actor turn. + func importConnectionIdentity( + deviceID: UUID, expectedRadioID: UUID, expectedPublicKey: Data, selfInfo: SelfInfo? + ) throws -> DeviceDTO? { + guard let current = try identityDevice(id: deviceID), + current.radioID == expectedRadioID, current.publicKey == expectedPublicKey, + !current.connectionMethods.isEmpty, + try !isRadioErasePending(current.radioID) else { return nil } + guard let selfInfo else { return DeviceDTO(from: current) } + try commitPendingRxLogEntries() + do { + current.apply(DeviceDTO(from: current).updating(from: selfInfo)) + let adoption = try stageGhostIdentity(current: current, newPublicKey: selfInfo.publicKey) + try saveIdentityChanges(retiring: adoption?.abandonedRadioID) + return DeviceDTO(from: current) + } catch { + modelContext.rollback() + throw error + } + } + + private func identityDevice(id: UUID) throws -> Device? { + let lookupID = id + let predicate = #Predicate { $0.id == lookupID } + var descriptor = FetchDescriptor(predicate: predicate) + descriptor.fetchLimit = 1 + return try modelContext.fetch(descriptor).first + } + + private func stageGhostIdentity( + current: Device, newPublicKey: Data + ) throws -> (radioID: UUID, abandonedRadioID: UUID?)? { let lookupKey = newPublicKey - let lookupID = currentDeviceID + let lookupID = current.id let ghostPredicate = #Predicate { device in device.publicKey == lookupKey && device.id != lookupID && device.isActive == false } var ghostDescriptor = FetchDescriptor(predicate: ghostPredicate) ghostDescriptor.fetchLimit = 1 - guard let ghost = try modelContext.fetch(ghostDescriptor).first else { return nil } - - // Defensive: refuse to delete a row that still carries a Bluetooth method. - // It's a real saved-but-inactive device (per `setActiveDevice` semantics), - // not a ghost. Returning nil here is safe — no reconciliation, no data loss. - if ghost.connectionMethods.contains(where: \.isBluetooth) { - return nil + guard let ghost = try modelContext.fetch(ghostDescriptor).first, + !ghost.connectionMethods.contains(where: \.isBluetooth) else { return nil } + let departingRadioID = current.radioID + let newRadioID = ghost.radioID + guard try !isRadioErasePending(newRadioID) else { throw PersistenceStoreError.deviceNotFound } + if departingRadioID != newRadioID { + try reassignSelfTelemetrySnapshots(from: departingRadioID, to: newRadioID) } - - let currentPredicate = #Predicate { device in - device.id == lookupID + let oldOwner = #Predicate { $0.radioID == departingRadioID && $0.id != lookupID } + let abandoned = try departingRadioID != newRadioID && + modelContext.fetchCount(FetchDescriptor(predicate: oldOwner)) == 0 + if abandoned { + try retireTextRulesIdentities(radioID: departingRadioID) + try stageRecentlyBlockedDeletion(radioID: departingRadioID) } - var currentDescriptor = FetchDescriptor(predicate: currentPredicate) - currentDescriptor.fetchLimit = 1 - guard let current = try modelContext.fetch(currentDescriptor).first else { return nil } - - let newRadioID = ghost.radioID current.radioID = newRadioID current.publicKey = newPublicKey current.connectionMethods = ConnectionMethod.canonicalized(current.connectionMethods) @@ -429,25 +388,26 @@ public extension PersistenceStore { let wifi = ConnectionMethod.canonicalized(ghost.connectionMethods).first(where: \.isWiFi) { current.connectionMethods.insert(wifi, at: 0) } - modelContext.delete(ghost) - try modelContext.save() - return newRadioID + return (newRadioID, abandoned ? departingRadioID : nil) } - /// Stages deletion of all device-scoped data without calling save(). - /// Used by both `deleteDeviceData` and `deleteDeviceAndData` to compose - /// operations while maintaining single-save atomicity. - private func _deleteAllDeviceData(id: UUID) throws { - // Look up the Device's radioID since child records are keyed by radioID, not BLE UUID - let targetBLEID = id - let devicePredicate = #Predicate { device in - device.id == targetBLEID - } - guard let device = try modelContext.fetch(FetchDescriptor(predicate: devicePredicate)).first else { - return + private func saveIdentityChanges(retiring abandonedRadioID: UUID?) throws { + #if DEBUG + try identityReconciliationFaultInjection?() + #endif + try modelContext.save() + if let abandonedRadioID { + retireReceiveScope(radioID: abandonedRadioID) + publishRecentlyBlockedChange() } - let targetRadioID = device.radioID + } + + /// Stages radio-scoped deletion independently of the lifetime of its Device row. + func stageDeleteAllDeviceData(radioID targetRadioID: UUID) throws { + try stageRecentlyBlockedDeletion(radioID: targetRadioID) + + try deleteSelfTelemetrySnapshots(radioID: targetRadioID) // Delete reactions (references messages via messageID) let reactionPredicate = #Predicate { reaction in @@ -479,7 +439,7 @@ public extension PersistenceStore { modelContext.delete(session) } - // Delete NodeStatusSnapshots only when no other session references that node + // Delete remote history only when no other session references the public key. for pubKey in sessionPublicKeys { let remainingPredicate = #Predicate { session in session.publicKey == pubKey @@ -487,11 +447,11 @@ public extension PersistenceStore { let remainingCount = try modelContext.fetchCount(FetchDescriptor(predicate: remainingPredicate)) guard remainingCount == 0 else { continue } - let snapshotPredicate = #Predicate { snapshot in - snapshot.nodePublicKey == pubKey - } - let snapshots = try modelContext.fetch(FetchDescriptor(predicate: snapshotPredicate)) - for snapshot in snapshots { + let key = pubKey + let snapshots = try modelContext.fetch( + FetchDescriptor(predicate: #Predicate { $0.nodePublicKey == key }) + ) + for snapshot in snapshots where snapshot.selfRadioID == nil { modelContext.delete(snapshot) } } @@ -585,7 +545,27 @@ public extension PersistenceStore { } } + /// Stages deletion of self telemetry alongside the Device's other data. + private func deleteSelfTelemetrySnapshots(radioID: UUID) throws { + let snapshots = try modelContext.fetch(FetchDescriptor()) + for snapshot in snapshots where snapshot.selfRadioID == radioID { + modelContext.delete(snapshot) + } + } + + /// Moves self telemetry with the Device so it remains deletable after ghost adoption. + private func reassignSelfTelemetrySnapshots(from sourceRadioID: UUID, to adoptedRadioID: UUID) throws { + let snapshots = try modelContext.fetch(FetchDescriptor()) + for snapshot in snapshots where snapshot.selfRadioID == sourceRadioID { + snapshot.selfRadioID = adoptedRadioID + } + } + #if DEBUG + func setIdentityReconciliationFaultInjection(_ hook: (@Sendable () throws -> Void)?) { + identityReconciliationFaultInjection = hook + } + func setFetchDeviceByIDFaultInjection(_ hook: (@Sendable () throws -> Void)?) { fetchDeviceByIDFaultInjection = hook } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Diagnostics.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Diagnostics.swift index 5a6e67e4c4..64d7f5c957 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Diagnostics.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Diagnostics.swift @@ -554,6 +554,8 @@ public extension PersistenceStore { // MARK: - Node Status Snapshots + private static let snapshotFetchBatchSize = 32 + func saveNodeStatusSnapshot( nodePublicKey: Data, batteryMillivolts: UInt16?, @@ -623,27 +625,18 @@ public extension PersistenceStore { } func fetchLatestNodeStatusSnapshot(nodePublicKey: Data) throws -> NodeStatusSnapshotDTO? { - var descriptor = FetchDescriptor( - predicate: #Predicate { $0.nodePublicKey == nodePublicKey }, - sortBy: [SortDescriptor(\.timestamp, order: .reverse)] - ) - descriptor.fetchLimit = 1 - return try modelContext.fetch(descriptor).first.map(NodeStatusSnapshotDTO.init) + try latestSnapshot(nodePublicKey: nodePublicKey, selfRadioID: nil).map(NodeStatusSnapshotDTO.init) } func fetchNodeStatusSnapshots(nodePublicKey: Data, since: Date?) throws -> [NodeStatusSnapshotDTO] { - let descriptor = if let since { - FetchDescriptor( - predicate: #Predicate { $0.nodePublicKey == nodePublicKey && $0.timestamp >= since }, - sortBy: [SortDescriptor(\.timestamp)] - ) - } else { - FetchDescriptor( - predicate: #Predicate { $0.nodePublicKey == nodePublicKey }, - sortBy: [SortDescriptor(\.timestamp)] - ) - } - return try modelContext.fetch(descriptor).map(NodeStatusSnapshotDTO.init) + try snapshots(nodePublicKey: nodePublicKey, selfRadioID: nil, since: since).map(NodeStatusSnapshotDTO.init) + } + + func fetchSelfTelemetrySnapshots( + radioID: UUID, + nodePublicKey: Data + ) throws -> [NodeStatusSnapshotDTO] { + try snapshots(nodePublicKey: nodePublicKey, selfRadioID: radioID, since: nil).map(NodeStatusSnapshotDTO.init) } func updateSnapshotNeighbors(id: UUID, neighbors: [NeighborSnapshotEntry]) throws { @@ -679,21 +672,7 @@ public extension PersistenceStore { try modelContext.save() } - /// Atomically capture a status, telemetry, and/or neighbor snapshot for a node. - /// - /// The fetch-latest decision and the insert-or-enrich both run in this single - /// `@ModelActor` method body with no `await`, so two concurrent captures - /// serialize and the second observes the first's row — there is no window for a - /// duplicate in-window insert. Keeping the body suspension-free is the whole - /// point; an `await` here would reopen that race. Mirrors the same-isolation - /// guarantee `insertPendingSendAssigningSequence` relies on. - /// - /// Within `NodeSnapshotPolicy.minimumInterval` of the latest snapshot the - /// capture enriches that row: status fields are applied only when the row is - /// still telemetry-only (`uptimeSeconds == nil`), preserving the - /// one-status-point-per-window throttle; telemetry and neighbor arrays are - /// applied whenever supplied. A location fix is first-wins: it is written - /// only when the row has none yet. Outside the window a new snapshot is inserted. + /// Coalesces remote captures in one store turn so concurrent reads share the same window. func recordNodeStatusSnapshot( nodePublicKey: Data, status: NodeStatusMetrics?, @@ -701,14 +680,104 @@ public extension PersistenceStore { neighbors: [NeighborSnapshotEntry]?, location: NodeLocationFix? ) throws -> UUID { - var latestDescriptor = FetchDescriptor( - predicate: #Predicate { $0.nodePublicKey == nodePublicKey }, - sortBy: [SortDescriptor(\.timestamp, order: .reverse)] + let capturedAt = Date.now + let latest = try latestSnapshot( + nodePublicKey: nodePublicKey, + selfRadioID: nil, + since: capturedAt.addingTimeInterval(-NodeSnapshotPolicy.minimumInterval) + ) + return try insertOrEnrichSnapshot( + latest: latest, + capturedAt: capturedAt, + nodePublicKey: nodePublicKey, + selfRadioID: nil, + status: status, + telemetry: telemetry, + neighbors: neighbors, + location: location ) - latestDescriptor.fetchLimit = 1 + } - if let latest = try modelContext.fetch(latestDescriptor).first, - latest.timestamp.distance(to: .now) < NodeSnapshotPolicy.minimumInterval { + func recordSelfTelemetrySnapshot( + deviceID: UUID, + radioID: UUID, + nodePublicKey: Data, + telemetry: [TelemetrySnapshotEntry]?, + location: NodeLocationFix? + ) throws -> UUID? { + let targetID = deviceID + var descriptor = FetchDescriptor(predicate: #Predicate { $0.id == targetID }) + descriptor.fetchLimit = 1 + // Keep the identity check and write in one turn so deletion cannot interleave. + guard let device = try modelContext.fetch(descriptor).first, + device.radioID == radioID, device.publicKey == nodePublicKey else { return nil } + let capturedAt = Date.now + let latest = try latestSnapshot( + nodePublicKey: nodePublicKey, + selfRadioID: radioID, + since: capturedAt.addingTimeInterval(-NodeSnapshotPolicy.minimumInterval) + ) + // Give the first fix its own row so History uses the time it was captured. + let addsFirstFix = location != nil && latest?.latitude == nil + return try insertOrEnrichSnapshot( + latest: addsFirstFix ? nil : latest, + capturedAt: capturedAt, + nodePublicKey: nodePublicKey, + selfRadioID: radioID, + status: nil, + telemetry: telemetry, + neighbors: nil, + location: location + ) + } + + private func latestSnapshot( + nodePublicKey: Data, + selfRadioID: UUID?, + since: Date? = nil + ) throws -> NodeStatusSnapshot? { + var descriptor = snapshotDescriptor(nodePublicKey: nodePublicKey, since: since, order: .reverse) + if since != nil || modelContext.hasChanges { + return try modelContext.fetch(descriptor).first { $0.selfRadioID == selfRadioID } + } + descriptor.includePendingChanges = false + let rows = try modelContext.fetch(descriptor, batchSize: Self.snapshotFetchBatchSize) + return rows.first { $0.selfRadioID == selfRadioID } + } + + /// Match the optional owner in Swift to include legacy nil-owner rows. + private func snapshots(nodePublicKey: Data, selfRadioID: UUID?, since: Date?) throws -> [NodeStatusSnapshot] { + let descriptor = snapshotDescriptor(nodePublicKey: nodePublicKey, since: since, order: .forward) + return try modelContext.fetch(descriptor).filter { $0.selfRadioID == selfRadioID } + } + + private func snapshotDescriptor( + nodePublicKey: Data, + since: Date?, + order: SortOrder + ) -> FetchDescriptor { + let key = nodePublicKey + let sortBy = [SortDescriptor(\NodeStatusSnapshot.timestamp, order: order)] + if let since { + return FetchDescriptor( + predicate: #Predicate { $0.nodePublicKey == key && $0.timestamp >= since }, + sortBy: sortBy + ) + } + return FetchDescriptor(predicate: #Predicate { $0.nodePublicKey == key }, sortBy: sortBy) + } + + private func insertOrEnrichSnapshot( + latest: NodeStatusSnapshot?, + capturedAt: Date, + nodePublicKey: Data, + selfRadioID: UUID?, + status: NodeStatusMetrics?, + telemetry: [TelemetrySnapshotEntry]?, + neighbors: [NeighborSnapshotEntry]?, + location: NodeLocationFix? + ) throws -> UUID { + if let latest, latest.timestamp.distance(to: capturedAt) < NodeSnapshotPolicy.minimumInterval { if let status, latest.uptimeSeconds == nil { latest.apply(status) } @@ -718,9 +787,6 @@ public extension PersistenceStore { if let neighbors { latest.neighborSnapshots = neighbors } - // Location is first-wins, unlike telemetry/neighbors: the in-window row is - // stamped with the first capture's timestamp, so writing a later fix here - // would mis-plot it in time, and a later no-fix would erase a good fix. if let location, latest.latitude == nil { latest.latitude = location.latitude latest.longitude = location.longitude @@ -731,7 +797,9 @@ public extension PersistenceStore { } let snapshot = NodeStatusSnapshot( + timestamp: capturedAt, nodePublicKey: nodePublicKey, + selfRadioID: selfRadioID, telemetryEntries: telemetry ) if let status { diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+DirectMessageReceive.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+DirectMessageReceive.swift new file mode 100644 index 0000000000..b56cd3d0a9 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+DirectMessageReceive.swift @@ -0,0 +1,182 @@ +import Foundation +import SwiftData + +public extension PersistenceStore { + func admitDirectMessage( + _ message: MessageDTO, + wireTextType: UInt8, + contact capturedContact: ContactDTO?, + scope: ReceiveScope, + preference: TextRulesPreference? + ) async throws -> DirectMessageAdmission { + guard scope.radioID == message.radioID, scope.isCurrent else { return .discarded } + let contact: ContactDTO? + if let capturedContact { + guard let current = try fetchCurrentDirectMessageContact(capturedContact, scope: scope) else { + return .discarded + } + contact = current + } else { + contact = nil + } + + let wireTimestamp = message.senderTimestamp ?? message.timestamp + let body = Data(message.text.utf8) + if let saved = try savedDirectMessage(message, timestamp: wireTimestamp, body: body) { + return .replay(saved) + } + + let identity = RecentlyBlockedMessageDTO.Identity( + radioID: message.radioID, + conversationID: nil, + senderPrefix: message.senderKeyPrefix, + senderTimestamp: wireTimestamp, + textType: wireTextType, + wireText: body + ) + if try hasRecentlyBlockedMessage(identity) { return .discarded } + + let isReaction = contact != nil && ReactionParser.isReactionText(message.text, isDM: true) + let key = contact?.textRulesID.map { + TextRulesPreference.Key(radioID: message.radioID, conversationID: $0) + } + if let preference, + !preference.rules.isEmpty, + contact?.isBlocked != true, + preference.effective(for: .directMessage, key: key, override: contact?.textRulesOverride ?? .inherit).isOn { + let sender = try uniqueDirectMessageSender(message) + if let match = preference.firstMatch(body: isReaction ? nil : message.text, sender: sender?.displayName) { + if !isReaction { + try recordRecentlyBlockedMessage(RecentlyBlockedMessageDTO( + identity: identity, + arrivedAt: message.createdAt, + body: message.text, + sender: sender?.displayName, + conversationName: contact?.displayName, + radioName: fetchDevice(radioID: message.radioID)?.nodeName, + match: match, + contactID: sender?.id + )) + } + return .discarded + } + } + + if isReaction, let contact { return .reaction(contact) } + try saveMessage(message) + return .saved(contact) + } + + func currentDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope) async throws -> ContactDTO? { + try fetchCurrentDirectMessageContact(contact, scope: scope) + } + + func materializeContactForDirectMessage( + from frame: ContactFrame, + receivedAt: Date, + scope: ReceiveScope + ) async throws -> ContactDTO? { + guard scope.isCurrent else { return nil } + + let result = try insertContactIfAbsent(radioID: scope.radioID, from: frame) + _ = try touchContactHeard(radioID: scope.radioID, publicKey: frame.publicKey, at: receivedAt) + _ = try upsertDiscoveredNode(radioID: scope.radioID, from: frame) + return try fetchContact(id: result.id) + } + + func touchDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope, at date: Date) async throws { + guard try fetchCurrentDirectMessageContact(contact, scope: scope) != nil else { return } + _ = try touchContactHeard(radioID: scope.radioID, publicKey: contact.publicKey, at: date) + } + + func updateContactAfterDirectMessage( + _ message: MessageDTO, + contact: ContactDTO, + scope: ReceiveScope, + isViewingContact: Bool + ) async throws -> ContactDTO? { + guard let current = try fetchCurrentDirectMessageContact(contact, scope: scope) else { return nil } + try updateContactLastMessage(contactID: current.id, date: message.createdAt) + if !isViewingContact, !current.isBlocked { + try incrementUnreadCount(contactID: current.id) + if message.containsSelfMention { + try incrementUnreadMentionCount(contactID: current.id) + } + } + return current + } + + func admitDirectMessageReaction( + _ reaction: ReactionDTO, + contact: ContactDTO, + scope: ReceiveScope + ) async throws -> ReactionAdmission? { + guard reaction.contactID == contact.id, reaction.radioID == scope.radioID, + try fetchCurrentDirectMessageContact(contact, scope: scope) != nil else { + return nil + } + return try admitReaction(reaction) + } +} + +private extension PersistenceStore { + static let directMessageSenderPrefixLength = 6 + + func fetchCurrentDirectMessageContact(_ contact: ContactDTO, scope: ReceiveScope) throws -> ContactDTO? { + guard scope.isCurrent, contact.radioID == scope.radioID, + let current = try fetchContact(id: contact.id), + current.radioID == scope.radioID, current.textRulesID == contact.textRulesID else { + return nil + } + return current + } + + func uniqueDirectMessageSender(_ message: MessageDTO) throws -> ContactDTO? { + guard let prefix = message.senderKeyPrefix, prefix.count == Self.directMessageSenderPrefixLength else { + return nil + } + let radioID = message.radioID + let descriptor = FetchDescriptor(predicate: #Predicate { $0.radioID == radioID }) + let matches = try modelContext.fetch(descriptor).lazy.filter { $0.publicKey.starts(with: prefix) }.prefix(2) + return matches.count == 1 ? matches.first.map { ContactDTO(from: $0) } : nil + } + + func savedDirectMessage(_ incoming: MessageDTO, timestamp: UInt32, body: Data) throws -> MessageDTO? { + guard let prefix = incoming.senderKeyPrefix, prefix.count == Self.directMessageSenderPrefixLength else { + return nil + } + let radioID = incoming.radioID + let incomingDirection = MessageDirection.incoming.rawValue + let type = incoming.textType.rawValue + let senderPrefix: Data? = prefix + let senderTimestamp: UInt32? = timestamp + let text = incoming.text + + if let key = incoming.deduplicationKey, + let saved = try fetchMessage(deduplicationKey: key, radioID: radioID), + saved.direction == .incoming, saved.channelIndex == nil, + saved.senderKeyPrefix == prefix, saved.textType == incoming.textType, + (saved.senderTimestamp ?? (saved.timestampCorrected ? nil : saved.timestamp)) == timestamp, + saved.text.utf8.elementsEqual(body) { + return saved + } + + let corrected = #Predicate { + $0.radioID == radioID && $0.senderKeyPrefix == senderPrefix && $0.senderTimestamp == senderTimestamp && + $0.directionRawValue == incomingDirection && $0.channelIndex == nil && $0.textTypeRawValue == type && + $0.text == text + } + let original = #Predicate { + $0.radioID == radioID && $0.senderKeyPrefix == senderPrefix && $0.timestamp == timestamp && + $0.senderTimestamp == nil && !$0.timestampCorrected && + $0.directionRawValue == incomingDirection && $0.channelIndex == nil && $0.textTypeRawValue == type && + $0.text == text + } + for predicate in [corrected, original] { + if let row = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first(where: { $0.text.utf8.elementsEqual(body) }) { + return MessageDTO(from: row) + } + } + return nil + } +} diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift index f9ae6069e6..7ac735a935 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift @@ -397,8 +397,19 @@ public extension PersistenceStore { try modelContext.save() } + func saveReceivedChannelMessage(_ dto: MessageDTO, scope: ReceiveScope, conversationID: UUID?) async throws -> Bool { + guard scope.isCurrent, scope.radioID == dto.radioID else { return false } + if let conversationID, let index = dto.channelIndex, + try fetchChannel(radioID: dto.radioID, index: index)?.textRulesID != conversationID { + return false + } + try saveMessage(dto) + return true + } + /// Update message status func updateMessageStatus(id: UUID, status: MessageStatus) throws { + try commitPendingRxLogEntries() let targetID = id let predicate = #Predicate { message in message.id == targetID @@ -411,7 +422,16 @@ public extension PersistenceStore { message.failureSeen = false } message.status = status - try modelContext.save() + do { + _ = try stageOutgoingReaction(message) + #if DEBUG + try updateMessageStatusFaultInjection?(id, status) + #endif + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } } } @@ -437,7 +457,13 @@ public extension PersistenceStore { message.failureSeen = false } message.status = status - try modelContext.save() + do { + _ = try stageOutgoingReaction(message) + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } return true } @@ -449,6 +475,7 @@ public extension PersistenceStore { /// row, so it can never resurrect a row the expiry checker already failed or /// downgrade a delivered row. Returns `true` when the row moved to `.sent`. func clearRetryingToSent(id: UUID) throws -> Bool { + try commitPendingRxLogEntries() let targetID = id let predicate = #Predicate { message in message.id == targetID @@ -462,7 +489,13 @@ public extension PersistenceStore { return false } message.status = .sent - try modelContext.save() + do { + _ = try stageOutgoingReaction(message) + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } return true } @@ -511,6 +544,57 @@ public extension PersistenceStore { } } + func commitOutgoingDirectMessageTimestamp(id: UUID, timestamp: UInt32) async throws -> UInt32? { + let targetID = id + let predicate = #Predicate { message in + message.id == targetID + } + var descriptor = FetchDescriptor(predicate: predicate) + descriptor.fetchLimit = 1 + guard let message = try modelContext.fetch(descriptor).first else { return nil } + let replacedTimestamp = message.status == .delivered ? message.timestamp : nil + message.timestamp = timestamp + if replacedTimestamp != nil { + message.status = .pending + } + do { + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + return replacedTimestamp + } + + func restoreUnacceptedDeliveredDirectMessage(id: UUID, timestamp: UInt32) async throws -> Bool { + let targetID = id + let predicate = #Predicate { message in + message.id == targetID + } + var descriptor = FetchDescriptor(predicate: predicate) + descriptor.fetchLimit = 1 + guard let message = try modelContext.fetch(descriptor).first else { return false } + if message.status == .delivered { return true } + guard message.status == .pending else { return false } + message.timestamp = timestamp + message.status = .delivered + // The queued bump is undone with the timestamp, so the next drain commits this send again. + let scopedMessageID = id + let queuedPredicate = #Predicate { row in + row.messageID == scopedMessageID && row.ackDeadline == nil + } + if let row = try modelContext.fetch(FetchDescriptor(predicate: queuedPredicate)).first { + row.attemptCount = Self.initialAttemptCount + } + do { + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + return true + } + /// Update message ACK info. /// /// Both `.delivered` and `.failed` are terminal for this write: once the @@ -533,7 +617,13 @@ public extension PersistenceStore { message.ackCode = ackCode message.status = status message.roundTripTime = roundTripTime - try modelContext.save() + do { + _ = try stageOutgoingReaction(message) + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } } } @@ -567,18 +657,26 @@ public extension PersistenceStore { } } - /// Updates the heard repeats count for a message - func updateMessageHeardRepeats(id: UUID, heardRepeats: Int) throws { - let targetID = id - let predicate = #Predicate { message in - message.id == targetID + func prepareChannelMessageResend(id: UUID, timestamp: UInt32) throws { + try commitPendingRxLogEntries() + guard let message = try fetchMessageModel(id: id) else { + throw PersistenceStoreError.messageNotFound } - var descriptor = FetchDescriptor(predicate: predicate) - descriptor.fetchLimit = 1 - - if let message = try modelContext.fetch(descriptor).first { - message.heardRepeats = heardRepeats + let targetMessageID = id + let predicate = #Predicate { $0.messageID == targetMessageID } + do { + for repeat_ in try modelContext.fetch(FetchDescriptor(predicate: predicate)) { + modelContext.delete(repeat_) + } + message.timestamp = timestamp + message.heardRepeats = 0 + #if DEBUG + try prepareChannelMessageResendSaveFaultInjection?() + #endif try modelContext.save() + } catch { + modelContext.rollback() + throw error } } @@ -610,7 +708,17 @@ public extension PersistenceStore { /// Delete a message and its reactions func deleteMessage(id: UUID) throws { + _ = try deleteMessageReturningCount(id: id) + } + + /// Reports all removed message rows so callers can refresh a changed reaction chain. + func deleteMessageAndCount(id: UUID) async throws -> Int { + try deleteMessageReturningCount(id: id) + } + + private func deleteMessageReturningCount(id: UUID) throws -> Int { let targetID = id + var deletedMessageCount = try deleteOutgoingReactionsWithoutSaving(targetMessageIDs: [id]) // Cascade PendingSend outside the `if let message` guard. An orphan // PendingSend (no matching Message row) can exist via several paths: @@ -638,8 +746,10 @@ public extension PersistenceStore { reaction.messageID == targetID }) modelContext.delete(message) + deletedMessageCount += 1 } try modelContext.save() + return deletedMessageCount } /// Delete all channel messages from a specific sender for a device. @@ -658,6 +768,7 @@ public extension PersistenceStore { let messageIDs = try modelContext.fetch(FetchDescriptor(predicate: messagePredicate)).map(\.id) if !messageIDs.isEmpty { + try deleteOutgoingReactionsWithoutSaving(targetMessageIDs: messageIDs) try _deletePendingSendsForMessageIDsWithoutSaving(messageIDs: messageIDs) // Cascade MessageRepeat alongside Reaction. Bulk `delete(model:where:)` // bypasses the `@Relationship(deleteRule: .cascade)` declared on @@ -773,21 +884,6 @@ public extension PersistenceStore { return results.map { MessageRepeatDTO(from: $0) } } - /// Deletes all repeats for a given message. - func deleteMessageRepeats(messageID: UUID) throws { - let targetMessageID = messageID - let predicate = #Predicate { repeat_ in - repeat_.messageID == targetMessageID - } - let descriptor = FetchDescriptor(predicate: predicate) - - let results = try modelContext.fetch(descriptor) - for repeat_ in results { - modelContext.delete(repeat_) - } - try modelContext.save() - } - /// Checks if a repeat already exists for the given RX log entry. func messageRepeatExists(rxLogEntryID: UUID) throws -> Bool { let targetID: UUID? = rxLogEntryID @@ -856,6 +952,7 @@ public extension PersistenceStore { func admitSentEcho( messageID: UUID, + expectedTimestamp: UInt32, receivedAt: Date, pathNodes: Data, pathLength: UInt8, @@ -866,6 +963,7 @@ public extension PersistenceStore { guard let message = try fetchMessageModel(id: messageID) else { throw PersistenceStoreError.messageNotFound } + guard message.timestamp == expectedTimestamp else { return nil } if let rxLogEntryID, try messageRepeatExists(rxLogEntryID: rxLogEntryID) { return nil } @@ -924,6 +1022,18 @@ public extension PersistenceStore { // MARK: - Reactions func admitReaction(_ dto: ReactionDTO) throws -> ReactionAdmission? { + try commitPendingRxLogEntries() + do { + guard let admission = try admitReactionWithoutSaving(dto) else { return nil } + try modelContext.save() + return admission + } catch { + modelContext.rollback() + throw error + } + } + + internal func admitReactionWithoutSaving(_ dto: ReactionDTO) throws -> ReactionAdmission? { let messageID = dto.messageID let messagePredicate = #Predicate { $0.id == messageID } var messageDescriptor = FetchDescriptor(predicate: messagePredicate) @@ -938,15 +1048,19 @@ public extension PersistenceStore { let inserted = try modelContext.fetchCount(FetchDescriptor(predicate: existsPredicate)) == 0 if inserted { modelContext.insert(Reaction(dto: dto)) - try modelContext.save() } let reactions = try fetchReactions(for: messageID, limit: ReactionParser.summaryRowLimit) let summary = ReactionParser.buildSummary(from: reactions) message.reactionSummary = summary - try modelContext.save() return ReactionAdmission(messageID: messageID, summary: summary, inserted: inserted) } + #if DEBUG + func setUpdateMessageStatusFaultInjection(_ hook: (@Sendable (UUID, MessageStatus) throws -> Void)?) { + updateMessageStatusFaultInjection = hook + } + #endif + /// Saves a new reaction func saveReaction(_ dto: ReactionDTO) throws { let reaction = Reaction( diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+OutgoingReactions.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+OutgoingReactions.swift new file mode 100644 index 0000000000..36cec2c74f --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+OutgoingReactions.swift @@ -0,0 +1,143 @@ +import Foundation +import SwiftData + +public extension PersistenceStore { + func admitOutgoingReaction(_ message: MessageDTO) async throws -> MessageDTO? { + guard message.direction == .outgoing, message.status == .pending, + let senderName = message.reactionSenderName, + let details = outgoingReactionDetails(message), + let target = try outgoingReactionTarget(message), + details.messageHash == ReactionParser.generateMessageHash( + text: target.text, timestamp: target.senderTimestamp ?? target.timestamp + ) else { return nil } + guard try !reactionExists(messageID: target.id, senderName: senderName, emoji: details.emoji) else { + return nil + } + + let targetID: UUID? = target.id + let sender: String? = senderName + let predicate = #Predicate { + $0.reactionTargetMessageID == targetID && $0.reactionSenderName == sender + } + for existing in try modelContext.fetch(FetchDescriptor(predicate: predicate)) { + guard outgoingReactionDetails(MessageDTO(from: existing))?.emoji == details.emoji else { continue } + if try hasPendingSend(messageID: existing.id) { return nil } + } + + try commitPendingRxLogEntries() + do { + let pending: PendingSendDTO + if let contactID = message.contactID { + pending = PendingSendDTO( + envelope: DirectMessageEnvelope(messageID: message.id, contactID: contactID, isSingleAttempt: true), + radioID: message.radioID + ) + } else if let channelIndex = message.channelIndex { + pending = PendingSendDTO( + envelope: ChannelMessageEnvelope( + messageID: message.id, channelIndex: channelIndex, isResend: false, + messageText: message.text, messageTimestamp: message.timestamp, localNodeName: senderName + ), + radioID: message.radioID + ) + } else { + return nil + } + modelContext.insert(Message(dto: message)) + _ = try insertPendingSendAssigningSequenceWithoutSaving(pending) + try modelContext.save() + return message + } catch { + modelContext.rollback() + throw error + } + } + + func completeOutgoingReaction(messageID: UUID) async throws -> ReactionAdmission? { + try commitPendingRxLogEntries() + let id = messageID + let predicate = #Predicate { $0.id == id } + guard let message = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first else { return nil } + do { + guard let admission = try stageOutgoingReaction(message) else { return nil } + try modelContext.save() + return admission + } catch { + modelContext.rollback() + throw error + } + } +} + +extension PersistenceStore { + /// Stages the badge with the accepted status so neither can commit alone. + func stageOutgoingReaction(_ message: Message) throws -> ReactionAdmission? { + guard message.status == .sent || message.status == .delivered, + message.direction == .outgoing, + let senderName = message.reactionSenderName else { return nil } + let dto = MessageDTO(from: message) + guard let details = outgoingReactionDetails(dto), + let target = try outgoingReactionTarget(dto) else { return nil } + return try admitReactionWithoutSaving(ReactionDTO( + messageID: target.id, + emoji: details.emoji, + senderName: senderName, + messageHash: details.messageHash, + rawText: message.text, + receivedAt: message.createdAt, + channelIndex: message.channelIndex, + contactID: message.contactID, + radioID: message.radioID + )) + } + + /// Removing a target also removes its queued wire messages and durable send work. + @discardableResult + func deleteOutgoingReactionsWithoutSaving(targetMessageIDs: [UUID]) throws -> Int { + var remainingTargetIDs = targetMessageIDs + var visitedTargetIDs: Set = [] + var deletedMessageCount = 0 + while let targetMessageID = remainingTargetIDs.popLast() { + guard visitedTargetIDs.insert(targetMessageID).inserted else { continue } + let targetID: UUID? = targetMessageID + let predicate = #Predicate { $0.reactionTargetMessageID == targetID } + for message in try modelContext.fetch(FetchDescriptor(predicate: predicate)) { + let messageID = message.id + remainingTargetIDs.append(messageID) + try _deletePendingSendsForMessageIDsWithoutSaving(messageIDs: [messageID]) + try modelContext.delete(model: Reaction.self, where: #Predicate { $0.messageID == messageID }) + modelContext.delete(message) + deletedMessageCount += 1 + } + } + return deletedMessageCount + } + + private func outgoingReactionDetails(_ message: MessageDTO) -> (emoji: String, messageHash: String)? { + if message.channelIndex != nil, let parsed = ReactionParser.parse(message.text) { + return (parsed.emoji, parsed.messageHash) + } + if message.contactID != nil, let parsed = ReactionParser.parseDM(message.text) { + return (parsed.emoji, parsed.messageHash) + } + return nil + } + + private func outgoingReactionTarget(_ message: MessageDTO) throws -> Message? { + guard let targetID = message.reactionTargetMessageID else { return nil } + let predicate = #Predicate { $0.id == targetID } + guard let target = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first, + target.radioID == message.radioID, + target.contactID == message.contactID, + target.channelIndex == message.channelIndex else { return nil } + if let contactID = message.contactID { + guard message.channelIndex == nil, + try fetchContact(id: contactID)?.radioID == message.radioID else { return nil } + } else if let channelIndex = message.channelIndex { + guard try fetchChannel(radioID: message.radioID, index: channelIndex) != nil else { return nil } + } else { + return nil + } + return target + } +} diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+PendingSends.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+PendingSends.swift index f8d3bb96d7..9934e5dee1 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+PendingSends.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+PendingSends.swift @@ -3,6 +3,7 @@ import os import SwiftData public extension PersistenceStore { + static let initialAttemptCount = 0 private static let pendingSendLogger = Logger( subsystem: "com.mc1", category: "PersistenceStore.PendingSends" @@ -30,12 +31,17 @@ public extension PersistenceStore { existing.contactID = dto.contactID existing.channelIndex = dto.channelIndex existing.isResend = dto.isResend + existing.isSingleAttempt = dto.isSingleAttempt existing.messageText = dto.messageText existing.messageTimestamp = dto.messageTimestamp existing.localNodeName = dto.localNodeName existing.sequence = dto.sequence existing.enqueuedAt = dto.enqueuedAt existing.attemptCount = dto.attemptCount + existing.nextWireAttempt = dto.nextWireAttempt + existing.ackCodes = dto.ackCodes + existing.ackSentAt = dto.ackSentAt + existing.ackDeadline = dto.ackDeadline } else { modelContext.insert(PendingSend(dto: dto)) } @@ -52,7 +58,16 @@ public extension PersistenceStore { /// concurrent enqueues from main never see the same `max+1`. This is /// the production enqueue path; `upsertPendingSend(_:)` above is /// reserved for tests and explicit-sequence scenarios. - func insertPendingSendAssigningSequence(_ dto: PendingSendDTO) throws -> Int { + func insertPendingSendAssigningSequence(_ dto: PendingSendDTO) async throws -> Int { + #if DEBUG + try await pendingSendInsertHandler?() + #endif + let assignedSequence = try insertPendingSendAssigningSequenceWithoutSaving(dto) + try modelContext.save() + return assignedSequence + } + + internal func insertPendingSendAssigningSequenceWithoutSaving(_ dto: PendingSendDTO) throws -> Int { let scopedRadioID = dto.radioID let radioPredicate = #Predicate { row in row.radioID == scopedRadioID @@ -68,28 +83,11 @@ public extension PersistenceStore { let inserted = PendingSend(dto: dto) inserted.sequence = assignedSequence modelContext.insert(inserted) - try modelContext.save() return assignedSequence } - /// Atomically replaces any existing `PendingSend` rows for the given - /// `messageID`, flips the matching `Message.status` to `.pending` - /// (unless already `.delivered`), and inserts the new `PendingSendDTO`. - /// All three operations land in a single `modelContext.save()` so a - /// crash mid-call cannot leave the row at `.pending` with no - /// `PendingSend` available for replay. The manual DM retry path uses - /// this to keep the queue authoritative for retries while the prior - /// multi-await sequence (delete + status flip + enqueue) had crash - /// windows that stranded `.pending` rows. - /// - /// `.delivered` is intentionally preserved — a late-arriving ACK that - /// landed while the user was reaching for the retry button must not be - /// clobbered. The `PendingSend` row is still inserted; the queue's - /// drain-time `hasPendingSend` gate notices the row but `MessageService` - /// short-circuits the wire send for an already-delivered message. - /// - /// Returns the assigned per-radio sequence number, matching the - /// `insertPendingSendAssigningSequence(_:)` contract. + /// Replaces this message's pending rows in one save, so a crash cannot leave `.pending` with no row. + /// `.delivered` stays `.delivered` until the new packet commits its timestamp immediately before the command. func replacePendingSendForRetry( messageID: UUID, dto: PendingSendDTO @@ -173,26 +171,20 @@ public extension PersistenceStore { } } - /// Delete every `PendingSend` row whose `radioID` does not match any - /// known `Device` row. Returns the number of rows deleted. An orphan row - /// can never drain (`fetchPendingSends(radioID:)` filters by radio and - /// the radio is gone), so leaving it on disk only wastes space. - /// - /// **Precondition (callers must satisfy):** every paired Device row, - /// including the one currently being constructed, must already be - /// persisted before this runs. The production wiring at - /// `ConnectionManager.buildServicesAndSaveDevice` saves the Device row - /// before invoking warmUp, so this precondition holds for the in-progress - /// radio as well as every previously-paired one. The doc-comment exists - /// to head off future refactors that might invoke warmUp ahead of the - /// Device save — in that order, an in-flight new-pair Device whose row - /// hasn't been flushed yet would have its enqueued PendingSends wrongly - /// classified as orphans. + /// Deletes pending sends only when both the Device and matching Message are absent. + /// Persist newly paired Device records first; identity reassociation may leave valid + /// unsent history under the previous Radio ID. @discardableResult func purgeOrphanPendingSends() throws -> Int { let knownRadioIDs = try Set(modelContext.fetch(FetchDescriptor()).map(\.radioID)) let allRows = try modelContext.fetch(FetchDescriptor()) - let orphans = allRows.filter { !knownRadioIDs.contains($0.radioID) } + var orphans: [PendingSend] = [] + for row in allRows where !knownRadioIDs.contains(row.radioID) { + let messageID = row.messageID + let radioID = row.radioID + let predicate = #Predicate { $0.id == messageID && $0.radioID == radioID } + if try modelContext.fetchCount(FetchDescriptor(predicate: predicate)) == 0 { orphans.append(row) } + } guard !orphans.isEmpty else { return 0 } for row in orphans { modelContext.delete(row) @@ -319,36 +311,161 @@ public extension PersistenceStore { return rows.count } - /// Increments the `attemptCount` for the `PendingSend` row matching - /// `messageID`. Returns the new count, or `nil` if no row matched. - /// Throws on SwiftData read/write failure — callers must treat a thrown - /// error as transient (park + retry) and `nil` as terminal (deleted row). - /// - /// `warmUp`'s purge runs before hydrate, so a `nil` row reaching increment - /// time would indicate the purge step was skipped (programmer error). The - /// `?? 0` fallback degrades gracefully without pretending the row had - /// prior drain attempts. + func pendingSendWireAttempt(id: UUID) async throws -> UInt8? { + guard let row = try pendingSendRow(id: id), row.ackDeadline == nil else { return nil } + return row.nextWireAttempt + } + + /// A missing id or an ACK owner writes nothing and does not create a row. + func setPendingSendWireAttempt(id: UUID, to next: UInt8) async throws -> Bool { + guard let row = try pendingSendRow(id: id), row.ackDeadline == nil else { return false } + row.nextWireAttempt = next + do { + #if DEBUG + try await pendingSendWireAttemptSaveFaultInjection?() + #endif + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + return true + } + + /// Queued direct messages that already handed attempt bytes to the radio, in sequence order. + /// Uses the live message timestamp and text. Skips channel messages and rows already delivered. + func queuedDirectMessageWireAttempts() async throws -> [QueuedDirectMessageWireAttempt] { + let dmKind = PendingSendKind.dm.rawValue + let predicate = #Predicate { row in + row.ackDeadline == nil && row.kindRawValue == dmKind + } + let rows = try modelContext.fetch(FetchDescriptor( + predicate: predicate, + sortBy: [SortDescriptor(\.sequence, order: .forward)] + )) + var attempts: [QueuedDirectMessageWireAttempt] = [] + for row in rows where row.nextWireAttempt > 0 { + let messageID = row.messageID + let messagePredicate = #Predicate { message in + message.id == messageID + } + var descriptor = FetchDescriptor(predicate: messagePredicate) + descriptor.fetchLimit = 1 + guard let message = try modelContext.fetch(descriptor).first else { continue } + guard message.channelIndex == nil, message.status != .delivered else { continue } + attempts.append(QueuedDirectMessageWireAttempt( + pendingSendID: row.id, + messageID: messageID, + timestamp: message.timestamp, + text: message.text, + consumedAttempts: row.nextWireAttempt + )) + } + return attempts + } + + /// Marks this queued direct message delivered and deletes its row in one save. + /// A host timeout may have written `.failed` while the row still holds the offered byte. + func deliverQueuedDirectMessage( + pendingSendID: UUID, + ackCode: UInt32, + roundTripTime: UInt32? + ) async throws -> MessageDTO? { + guard let row = try pendingSendRow(id: pendingSendID), + row.ackDeadline == nil, row.kind == .dm else { return nil } + let messageID = row.messageID + let messagePredicate = #Predicate { message in + message.id == messageID + } + var descriptor = FetchDescriptor(predicate: messagePredicate) + descriptor.fetchLimit = 1 + guard let message = try modelContext.fetch(descriptor).first, + message.channelIndex == nil, message.status != .delivered else { return nil } + message.status = .delivered + message.ackCode = ackCode + if let roundTripTime { + message.roundTripTime = roundTripTime + } + modelContext.delete(row) + do { + _ = try stageOutgoingReaction(message) + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + return MessageDTO(from: message) + } + + private func pendingSendRow(id: UUID) throws -> PendingSend? { + let target = id + let predicate = #Predicate { row in + row.id == target + } + var descriptor = FetchDescriptor(predicate: predicate) + descriptor.fetchLimit = 1 + return try modelContext.fetch(descriptor).first + } + + /// Restores eligible unsent DMs and increments the queued row's attempt count in one save. + /// Returns nil if no queued row remains. A persistence error leaves preparation retryable. @discardableResult - func incrementPendingSendAttemptCount(messageID: UUID) throws -> Int? { + func preparePendingSendAttempt(messageID: UUID) async throws -> (pendingSendID: UUID, attemptCount: Int)? { #if DEBUG - try incrementPendingSendAttemptCountFaultInjection?() + await pendingSendAttemptHandler?() + try preparePendingSendAttemptFaultInjection?() #endif + try commitPendingRxLogEntries() let scopedMessageID = messageID let predicate = #Predicate { row in - row.messageID == scopedMessageID + row.messageID == scopedMessageID && row.ackDeadline == nil } - var descriptor = FetchDescriptor(predicate: predicate) + var descriptor = FetchDescriptor(predicate: predicate, sortBy: [SortDescriptor(\.sequence)]) descriptor.fetchLimit = 1 guard let row = try modelContext.fetch(descriptor).first else { return nil } - let nextCount = (row.attemptCount ?? 0) + 1 - row.attemptCount = nextCount - try modelContext.save() - return nextCount + do { + if row.kind == .dm, row.attemptCount == Self.initialAttemptCount, !row.isResend, !row.isSingleAttempt { + let radioID = row.radioID + let messagePredicate = #Predicate { $0.id == scopedMessageID && $0.radioID == radioID } + if let message = try modelContext.fetch(FetchDescriptor(predicate: messagePredicate)).first, + message.reactionTargetMessageID == nil, message.status == .failed { + // Admission can fail after the durable write. Restore unsent DMs so ACK + // persistence can record acceptance and delivery on their first attempt. + message.status = .pending + } + } + let nextCount = (row.attemptCount ?? Self.initialAttemptCount) + 1 + row.attemptCount = nextCount + #if DEBUG + try pendingSendAttemptSaveFaultInjection?(messageID) + #endif + try modelContext.save() + return (row.id, nextCount) + } catch { + modelContext.rollback() + throw error + } } #if DEBUG - func setIncrementPendingSendAttemptCountFaultInjection(_ hook: (@Sendable () throws -> Void)?) { - incrementPendingSendAttemptCountFaultInjection = hook + func setPendingSendAttemptHandler(_ handler: (@Sendable () async -> Void)?) { + pendingSendAttemptHandler = handler + } + + func setPendingSendInsertHandler(_ handler: (@Sendable () async throws -> Void)?) { + pendingSendInsertHandler = handler + } + + func setPreparePendingSendAttemptFaultInjection(_ hook: (@Sendable () throws -> Void)?) { + preparePendingSendAttemptFaultInjection = hook + } + + func setPendingSendAttemptSaveFaultInjection(_ hook: (@Sendable (UUID) throws -> Void)?) { + pendingSendAttemptSaveFaultInjection = hook + } + + func setPendingSendWireAttemptSaveFaultInjection(_ hook: (@Sendable () async throws -> Void)?) { + pendingSendWireAttemptSaveFaultInjection = hook } #endif } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+RadioErase.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+RadioErase.swift new file mode 100644 index 0000000000..26e881d6d3 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+RadioErase.swift @@ -0,0 +1,115 @@ +import Foundation +import SwiftData + +extension PersistenceStore { + public func captureReceiveScope(radioID: UUID, link: ReceiveScope.Lifetime) async throws -> ReceiveScope? { + guard link.isCurrent, try !isRadioErasePending(radioID) else { return nil } + if let partition = receivePartitions[radioID] { + return ReceiveScope(radioID: radioID, link: link, partition: partition) + } + guard try fetchDevice(radioID: radioID) != nil else { return nil } + try backfillTextRulesIdentities(radioID: radioID) + let partition = ReceiveScope.Lifetime() + receivePartitions[radioID] = partition + return ReceiveScope(radioID: radioID, link: link, partition: partition) + } + + func retireReceiveScope(radioID: UUID) { + receivePartitions.removeValue(forKey: radioID)?.retire() + } + + func fetchPendingRadioErases() throws -> [PendingRadioEraseDTO] { + try modelContext.fetch(FetchDescriptor()).map(PendingRadioEraseDTO.init) + } + + func isRadioErasePending(_ radioID: UUID) throws -> Bool { + if let pendingEraseRadioIDs { + return pendingEraseRadioIDs.contains(radioID) + } + let pending = try Set(fetchPendingRadioErases().map(\.radioID)) + pendingEraseRadioIDs = pending + return pending.contains(radioID) + } + + func beginRadioErase(_ device: DeviceDTO, isFactoryReset: Bool = false) throws -> PendingRadioEraseDTO { + let radioID = device.radioID + if let existing = try pendingRadioErase(radioID) { + return PendingRadioEraseDTO(existing) + } + guard try fetchDevice(id: device.id)?.radioID == radioID else { + throw PersistenceStoreError.deviceNotFound + } + let target = PendingRadioEraseDTO( + radioID: radioID, + deviceID: device.id, + pairingID: device.bluetoothPeripheralID ?? device.id, + radioName: device.nodeName, + isFactoryReset: isFactoryReset + ) + try commitPendingRxLogEntries() + do { + modelContext.insert(PendingRadioErase(target)) + #if DEBUG + try beginRadioEraseFaultInjection?() + #endif + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + pendingEraseRadioIDs?.insert(radioID) + retireReceiveScope(radioID: radioID) + return target + } + + func cancelRadioErase(radioID: UUID) throws { + guard let target = try pendingRadioErase(radioID) else { return } + try commitPendingRxLogEntries() + do { + modelContext.delete(target) + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + pendingEraseRadioIDs?.remove(radioID) + } + + func completeRadioErase(radioID: UUID) throws { + guard let target = try pendingRadioErase(radioID) else { return } + try commitPendingRxLogEntries() + do { + try stageDeleteAllDeviceData(radioID: radioID) + #if DEBUG + try completeRadioEraseFaultInjection?() + #endif + let devices = try modelContext.fetch(FetchDescriptor(predicate: #Predicate { $0.radioID == radioID })) + for device in devices { + modelContext.delete(device) + } + modelContext.delete(target) + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + pendingEraseRadioIDs?.remove(radioID) + publishRecentlyBlockedChange() + } + + private func pendingRadioErase(_ radioID: UUID) throws -> PendingRadioErase? { + var descriptor = FetchDescriptor(predicate: #Predicate { $0.radioID == radioID }) + descriptor.fetchLimit = 1 + return try modelContext.fetch(descriptor).first + } + + #if DEBUG + func setRadioEraseFaults( + begin: (@Sendable () throws -> Void)?, + complete: (@Sendable () throws -> Void)? + ) { + beginRadioEraseFaultInjection = begin + completeRadioEraseFaultInjection = complete + } + #endif +} diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+RecentlyBlocked.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+RecentlyBlocked.swift new file mode 100644 index 0000000000..c1257ef3be --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+RecentlyBlocked.swift @@ -0,0 +1,75 @@ +import Foundation +import SwiftData + +public extension PersistenceStore { + nonisolated func recentlyBlockedUpdates() -> AsyncStream { + recentlyBlockedChanges.subscribe(bufferingPolicy: .bufferingNewest(1)) + } + + internal func publishRecentlyBlockedChange() { + recentlyBlockedChanges.yield(()) + } + + func recentlyBlockedMessages() throws -> [RecentlyBlockedMessageDTO] { + try sortedRecentlyBlockedMessages().map(RecentlyBlockedMessageDTO.init(from:)) + } + + func recentlyBlockedCount() throws -> Int { + try modelContext.fetchCount(FetchDescriptor()) + } + + func hasRecentlyBlockedMessages(radioID: UUID, conversationID: UUID) async throws -> Bool { + let predicate = #Predicate { + $0.radioID == radioID && $0.conversationID == conversationID + } + var descriptor = FetchDescriptor(predicate: predicate) + descriptor.fetchLimit = 1 + return try !modelContext.fetch(descriptor).isEmpty + } + + internal func hasRecentlyBlockedMessage(_ identity: RecentlyBlockedMessageDTO.Identity) throws -> Bool { + let radioID = identity.radioID + let timestamp = identity.senderTimestamp + let predicate = #Predicate { + $0.radioID == radioID && $0.senderTimestamp == timestamp + } + return try modelContext.fetch(FetchDescriptor(predicate: predicate)).contains { + $0.identity == identity + } + } + + internal func recordRecentlyBlockedMessage(_ entry: RecentlyBlockedMessageDTO) throws { + guard try !hasRecentlyBlockedMessage(entry.identity) else { return } + try commitPendingRxLogEntries() + + do { + let rows = try modelContext.fetch(FetchDescriptor()) + let entry = try RecentlyBlockedMessage(entry) + let sorted = (rows + [entry]).sorted(by: Self.isMoreRecent) + modelContext.insert(entry) + for expired in sorted.dropFirst(Self.recentlyBlockedRetentionLimit) { + modelContext.delete(expired) + } + #if DEBUG + try recordRecentlyBlockedFaultInjection?() + #endif + try modelContext.save() + publishRecentlyBlockedChange() + } catch { + modelContext.rollback() + throw error + } + } + + private func sortedRecentlyBlockedMessages() throws -> [RecentlyBlockedMessage] { + try modelContext.fetch(FetchDescriptor()).sorted(by: Self.isMoreRecent) + } + + private static func isMoreRecent(_ left: RecentlyBlockedMessage, _ right: RecentlyBlockedMessage) -> Bool { + if left.arrivedAt == right.arrivedAt { + left.id.uuidString > right.id.uuidString + } else { + left.arrivedAt > right.arrivedAt + } + } +} diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+RecentlyBlockedOwnership.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+RecentlyBlockedOwnership.swift new file mode 100644 index 0000000000..b539936951 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+RecentlyBlockedOwnership.swift @@ -0,0 +1,69 @@ +import Foundation +import SwiftData + +extension PersistenceStore { + func stageRecentlyBlockedDeletion(radioID: UUID) throws { + let rows = try modelContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.radioID == radioID } + )) + for row in rows { + modelContext.delete(row) + } + } + + func stageRecentlyBlockedRoomDeletion(radioID: UUID, conversationID: UUID) throws { + let rows = try modelContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.radioID == radioID && $0.conversationID == conversationID } + )) + for row in rows { + modelContext.delete(row) + } + } + + func stageRecentlyBlockedContactDeletion(contactID: UUID) throws { + let rows = try modelContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.contactID == contactID } + )) + for row in rows { + modelContext.delete(row) + } + } + + func hasRecentlyBlockedContactReference(contactID: UUID) throws -> Bool { + var descriptor = FetchDescriptor(predicate: #Predicate { $0.contactID == contactID }) + descriptor.fetchLimit = 1 + return try !modelContext.fetch(descriptor).isEmpty + } + + @discardableResult + func bindRecentlyBlockedContacts(radioID: UUID) throws -> Bool { + let unbound = try modelContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.radioID == radioID && $0.conversationID == nil && $0.contactID == nil } + )) + guard !unbound.isEmpty else { return false } + + let contacts = try modelContext.fetch(FetchDescriptor(predicate: #Predicate { $0.radioID == radioID })) + let prefixLength = 6 + let contactsByPrefix = Dictionary(grouping: contacts) { Data($0.publicKey.prefix(prefixLength)) } + var changed = false + for row in unbound { + guard let prefix = row.senderPrefix, + let matches = contactsByPrefix[prefix], + matches.count == 1, let contact = matches.first else { continue } + row.contactID = contact.id + changed = true + } + return changed + } + + func saveContactChangesBindingRecentlyBlocked(radioID: UUID) throws { + do { + let changed = try bindRecentlyBlockedContacts(radioID: radioID) + try modelContext.save() + if changed { publishRecentlyBlockedChange() } + } catch { + modelContext.rollback() + throw error + } + } +} diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+RoomReceive.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+RoomReceive.swift new file mode 100644 index 0000000000..5b9c07aa8a --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+RoomReceive.swift @@ -0,0 +1,105 @@ +import Foundation +import SwiftData + +extension PersistenceStore { + func receiveRoomPost( + _ post: RoomMessageDTO, + in room: RemoteNodeSessionDTO, + scope: ReceiveScope, + preference: TextRulesPreference? + ) throws -> (message: RoomMessageDTO?, recovered: Bool) { + guard scope.isCurrent, scope.radioID == room.radioID else { return (nil, false) } + + let sessionID = room.id + var roomDescriptor = FetchDescriptor(predicate: #Predicate { $0.id == sessionID }) + roomDescriptor.fetchLimit = 1 + guard let session = try modelContext.fetch(roomDescriptor).first, + session.radioID == room.radioID, + session.textRulesID == room.textRulesID else { return (nil, false) } + + let key = post.deduplicationKey + let candidates = try modelContext.fetch(FetchDescriptor(predicate: #Predicate { + $0.sessionID == sessionID && $0.deduplicationKey == key + })) + let alreadySaved = candidates.contains { + $0.timestamp == post.timestamp && + $0.authorKeyPrefix == post.authorKeyPrefix && + $0.text.utf8.elementsEqual(post.text.utf8) + } + let identity = RecentlyBlockedMessageDTO.Identity( + radioID: room.radioID, + conversationID: room.textRulesID, + senderPrefix: post.authorKeyPrefix, + senderTimestamp: post.timestamp, + textType: TextType.signedPlain.rawValue, + wireText: Data(post.text.utf8) + ) + if try alreadySaved || hasRecentlyBlockedMessage(identity) { + return try (nil, recoverRoom(session)) + } + + let displayName = try findContactNameByKeyPrefix(post.authorKeyPrefix) + if !post.isFromSelf, + let preference, + let conversationID = room.textRulesID, + preference.effective( + for: .room, + key: .init(radioID: room.radioID, conversationID: conversationID), + override: session.textRulesOverride + ).isOn { + let matchingName = try uniqueRoomAuthorName(post.authorKeyPrefix, radioID: room.radioID) + if let match = preference.firstMatch(body: post.text, sender: matchingName) { + let radioName = try fetchDevice(radioID: room.radioID)?.nodeName + try recordRecentlyBlockedMessage(RecentlyBlockedMessageDTO( + identity: identity, + arrivedAt: post.createdAt, + body: post.text, + sender: matchingName ?? displayName, + conversationName: session.name, + radioName: radioName, + match: match + )) + return try (nil, recoverRoom(session)) + } + } + + try commitPendingRxLogEntries() + let recovered = !session.isConnected + let message = RoomMessage(dto: post) + message.authorName = displayName + modelContext.insert(message) + session.isConnected = true + session.lastSyncTimestamp = max(session.lastSyncTimestamp, post.timestamp) + session.lastMessageDate = post.createdAt + if !post.isFromSelf { session.unreadCount += 1 } + do { + try modelContext.save() + return (RoomMessageDTO(from: message), recovered) + } catch { + modelContext.rollback() + throw error + } + } + + private func recoverRoom(_ room: RemoteNodeSession) throws -> Bool { + guard !room.isConnected else { return false } + try commitPendingRxLogEntries() + room.isConnected = true + do { + try modelContext.save() + return true + } catch { + modelContext.rollback() + throw error + } + } + + private func uniqueRoomAuthorName(_ prefix: Data, radioID: UUID) throws -> String? { + let descriptor = FetchDescriptor(predicate: #Predicate { $0.radioID == radioID }) + let matches = try modelContext.fetch(descriptor).lazy + .filter { $0.publicKey.prefix(prefix.count) == prefix } + .prefix(2) + guard matches.count == 1 else { return nil } + return matches.first?.displayName + } +} diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Rooms.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Rooms.swift index dbed549ba4..69d13d721c 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Rooms.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Rooms.swift @@ -199,26 +199,34 @@ public extension PersistenceStore { /// Delete remote node session and all associated room messages func deleteRemoteNodeSession(id: UUID) throws { - let targetID = id + try commitPendingRxLogEntries() + do { + let targetID = id - // Delete associated room messages - let messagePredicate = #Predicate { message in - message.sessionID == targetID - } - let messages = try modelContext.fetch(FetchDescriptor(predicate: messagePredicate)) - for message in messages { - modelContext.delete(message) - } + let messagePredicate = #Predicate { message in + message.sessionID == targetID + } + let messages = try modelContext.fetch(FetchDescriptor(predicate: messagePredicate)) + for message in messages { + modelContext.delete(message) + } - // Delete the session - let sessionPredicate = #Predicate { session in - session.id == targetID - } - if let session = try modelContext.fetch(FetchDescriptor(predicate: sessionPredicate)).first { - modelContext.delete(session) - } + let sessionPredicate = #Predicate { session in + session.id == targetID + } + if let session = try modelContext.fetch(FetchDescriptor(predicate: sessionPredicate)).first { + if let conversationID = session.textRulesID { + try stageRecentlyBlockedRoomDeletion(radioID: session.radioID, conversationID: conversationID) + } + modelContext.delete(session) + } - try modelContext.save() + try modelContext.save() + publishRecentlyBlockedChange() + } catch { + modelContext.rollback() + throw error + } } /// Mark a room session as connected. Called when an incoming message proves diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+TextRulesConversations.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+TextRulesConversations.swift new file mode 100644 index 0000000000..5e31aebe44 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+TextRulesConversations.swift @@ -0,0 +1,172 @@ +import Foundation +import SwiftData + +public extension PersistenceStore { + func fetchChannelForInfo(id: UUID) throws -> ChannelDTO? { + guard let channel = try fetchChannel(id: id) else { return nil } + guard channel.textRulesID == nil, + try !isRadioErasePending(channel.radioID), + try fetchDevice(radioID: channel.radioID) != nil else { return channel } + try backfillTextRulesIdentities(radioID: channel.radioID) + return try fetchChannel(id: id) + } + + func textRulesConversations(kind: TextRulesPreference.Kind? = nil) throws -> [TextRulesPreference.Conversation] { + var namesByRadio: [UUID: String] = [:] + for device in try fetchDevices() where namesByRadio[device.radioID] == nil { + guard try !isRadioErasePending(device.radioID) else { continue } + namesByRadio[device.radioID] = device.nodeName + try backfillTextRulesIdentities(radioID: device.radioID) + } + + var conversations: [TextRulesPreference.Conversation] = [] + for (radioID, radioName) in namesByRadio { + if kind != .directMessage && kind != .room { + for channel in try fetchChannels(radioID: radioID) { + let channelKind = TextRulesPreference.channelKind(isPublic: channel.isPublicChannel, name: channel.name) + guard kind == nil || channelKind == kind, let localID = channel.textRulesID else { continue } + conversations.append(.init( + key: .init(radioID: radioID, conversationID: localID), + kind: channelKind, name: channel.name, radioName: radioName, override: channel.textRulesOverride + )) + } + } + if kind == nil || kind == .directMessage { + for contact in try fetchContacts(radioID: radioID) where contact.type == .chat { + guard let localID = contact.textRulesID else { continue } + conversations.append(.init( + key: .init(radioID: radioID, conversationID: localID), + kind: .directMessage, name: contact.displayName, radioName: radioName, override: contact.textRulesOverride + )) + } + } + if kind == nil || kind == .room { + for room in try fetchRemoteNodeSessions(radioID: radioID) where room.isRoom { + guard let localID = room.textRulesID else { continue } + conversations.append(.init( + key: .init(radioID: radioID, conversationID: localID), + kind: .room, name: room.name, radioName: radioName, override: room.textRulesOverride + )) + } + } + } + return conversations.sorted { + if $0.name != $1.name { return $0.name.localizedStandardCompare($1.name) == .orderedAscending } + return $0.radioName.localizedStandardCompare($1.radioName) == .orderedAscending + } + } + + func textRulesConversation( + kind: TextRulesPreference.Kind, + key: TextRulesPreference.Key + ) throws -> TextRulesPreference.Conversation? { + let radioID = key.radioID + let conversationID = key.conversationID + guard try !isRadioErasePending(radioID), let device = try fetchDevice(radioID: radioID) else { return nil } + let name: String + let choice: TextRulesPreference.Override + switch kind { + case .directMessage: + let predicate = #Predicate { $0.radioID == radioID && $0.textRulesID == conversationID } + guard let contact = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first else { return nil } + name = contact.displayName + choice = contact.textRulesOverride + case .room: + let predicate = #Predicate { $0.radioID == radioID && $0.textRulesID == conversationID } + guard let room = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first else { return nil } + name = room.name + choice = room.textRulesOverride + case .publicChannel, .hashtagChannel, .privateChannel: + let predicate = #Predicate { $0.radioID == radioID && $0.textRulesID == conversationID } + guard let channel = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first else { return nil } + name = channel.name + choice = channel.textRulesOverride + } + return .init(key: key, kind: kind, name: name, radioName: device.nodeName, override: choice) + } + + func setTextRulesOverride( + _ choice: TextRulesPreference.Override, + kind: TextRulesPreference.Kind, + key: TextRulesPreference.Key + ) throws { + let radioID = key.radioID + let conversationID = key.conversationID + guard try !isRadioErasePending(radioID), try fetchDevice(radioID: radioID) != nil else { + throw PersistenceStoreError.deviceNotFound + } + try commitPendingRxLogEntries() + do { + switch kind { + case .directMessage: + let predicate = #Predicate { $0.radioID == radioID && $0.textRulesID == conversationID } + guard let contact = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first else { + throw PersistenceStoreError.contactNotFound + } + contact.textRulesOverrideRawValue = choice.rawValue + case .room: + let predicate = #Predicate { $0.radioID == radioID && $0.textRulesID == conversationID } + guard let room = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first else { + throw PersistenceStoreError.remoteNodeSessionNotFound + } + room.textRulesOverrideRawValue = choice.rawValue + case .publicChannel, .hashtagChannel, .privateChannel: + let predicate = #Predicate { $0.radioID == radioID && $0.textRulesID == conversationID } + guard let channel = try modelContext.fetch(FetchDescriptor(predicate: predicate)).first else { + throw PersistenceStoreError.channelNotFound + } + channel.textRulesOverrideRawValue = choice.rawValue + } + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + } +} + +extension PersistenceStore { + func backfillTextRulesIdentities(radioID: UUID) throws { + let channels = try modelContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.radioID == radioID && $0.textRulesID == nil } + )) + let contacts = try modelContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.radioID == radioID && $0.textRulesID == nil } + )) + let sessions = try modelContext.fetch(FetchDescriptor( + predicate: #Predicate { $0.radioID == radioID && $0.textRulesID == nil } + )) + guard !channels.isEmpty || !contacts.isEmpty || !sessions.isEmpty else { return } + try commitPendingRxLogEntries() + do { + for channel in channels { + channel.textRulesID = UUID() + } + for contact in contacts { + contact.textRulesID = UUID() + } + for session in sessions { + session.textRulesID = UUID() + } + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + } + + func retireTextRulesIdentities(radioID: UUID) throws { + for channel in try modelContext.fetch(FetchDescriptor(predicate: #Predicate { $0.radioID == radioID })) { + channel.textRulesID = nil + channel.textRulesOverrideRawValue = TextRulesPreference.Override.inherit.rawValue + } + for contact in try modelContext.fetch(FetchDescriptor(predicate: #Predicate { $0.radioID == radioID })) { + contact.textRulesID = nil + contact.textRulesOverrideRawValue = TextRulesPreference.Override.inherit.rawValue + } + for room in try modelContext.fetch(FetchDescriptor(predicate: #Predicate { $0.radioID == radioID })) { + room.textRulesID = nil + room.textRulesOverrideRawValue = TextRulesPreference.Override.inherit.rawValue + } + } +} diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift index 4eca662121..1e0f8a9013 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift @@ -65,6 +65,12 @@ public actor PersistenceStore: ModelActor, PersistenceStoreProtocol { self.modelContainer = modelContainer } + var receivePartitions: [UUID: ReceiveScope.Lifetime] = [:] + var pendingEraseRadioIDs: Set? + + public static let recentlyBlockedRetentionLimit = 100 + nonisolated let recentlyBlockedChanges = EventBroadcaster() + var rxLogEntryCountsByDevice: [UUID: Int] = [:] var unsavedRxLogInsertCount = 0 var rxLogFlushTask: Task? @@ -84,6 +90,9 @@ public actor PersistenceStore: ModelActor, PersistenceStoreProtocol { } #if DEBUG + var pendingSendInsertHandler: (@Sendable () async throws -> Void)? + var pendingSendAttemptHandler: (@Sendable () async -> Void)? + var identityReconciliationFaultInjection: (@Sendable () throws -> Void)? /// Inserts since the last RxLog-initiated `modelContext.save()`. Does not /// count piggyback saves from other store APIs. var rxLogInitiatedSaveCount = 0 @@ -109,20 +118,29 @@ public actor PersistenceStore: ModelActor, PersistenceStoreProtocol { /// they can assert post-commit behaviour of `importBackup`. var backupImportPostCommitHook: (@Sendable () -> Void)? - /// Test-only fault injection fired at the top of - /// `incrementPendingSendAttemptCount`. Tests use it to verify the - /// bump-failure park-and-requeue path in `ChatSendQueueService`'s drain - /// closures — a real SwiftData save failure here is otherwise hard to - /// provoke from a well-formed row. - var incrementPendingSendAttemptCountFaultInjection: (@Sendable () throws -> Void)? + var preparePendingSendAttemptFaultInjection: (@Sendable () throws -> Void)? + var pendingSendAttemptSaveFaultInjection: (@Sendable (UUID) throws -> Void)? + var pendingSendWireAttemptSaveFaultInjection: (@Sendable () async throws -> Void)? + var prepareChannelMessageResendSaveFaultInjection: (@Sendable () throws -> Void)? /// Test-only hook at the top of `fetchDevice(id:)`. The pairing query skips that id on throw. var fetchDeviceByIDFaultInjection: (@Sendable () throws -> Void)? + var beginRadioEraseFaultInjection: (@Sendable () throws -> Void)? + var completeRadioEraseFaultInjection: (@Sendable () throws -> Void)? + /// Test-only hook at the top of `fetchContactIDs`. A throw leaves that fetch unfinished. var fetchContactIDsFaultInjection: (@Sendable () throws -> Void)? + var recordRecentlyBlockedFaultInjection: (@Sendable () throws -> Void)? + + public func setRecordRecentlyBlockedFaultInjection(_ hook: (@Sendable () throws -> Void)?) { + recordRecentlyBlockedFaultInjection = hook + } + var updateContactLastMessageFaultInjection: (@Sendable () throws -> Void)? + var updateMessageStatusFaultInjection: (@Sendable (UUID, MessageStatus) throws -> Void)? + var savePendingAcknowledgementFaultInjection: (@Sendable () throws -> Void)? func setDeleteContactsFaultInjection(_ hook: (@Sendable () throws -> Void)?) { deleteContactsFaultInjection = hook @@ -147,7 +165,9 @@ public actor PersistenceStore: ModelActor, PersistenceStoreProtocol { DiscoveredNode.self, NodeStatusSnapshot.self, BlockedChannelSender.self, - PendingSend.self + PendingRadioErase.self, + PendingSend.self, + RecentlyBlockedMessage.self ]) /// Creates a ModelContainer for the app. @@ -174,6 +194,11 @@ public actor PersistenceStore: ModelActor, PersistenceStoreProtocol { /// Int8 flood sentinel. DTO still exposes UInt8 via truncatingIfNeeded. /// - v8→v9: Added Contact.isPinned (Bool, default false). Channel.isFavorite and /// RemoteNodeSession.isFavorite renamed to isPinned via originalName (same column). + /// - v9→v10: Added local Text Rules identities, review entries, and pending radio erase targets. + /// Added NodeStatusSnapshot.selfRadioID (UUID?, default nil). Existing rows + /// stay remote history. Self telemetry rows store the Device's radioID. + /// - v10→v11: Added PendingSend.nextWireAttempt (UInt8, default 0). Existing rows + /// migrate to 0 with no backfill from attemptCount, so one in-flight row can replay attempt 0. public static func createContainer(inMemory: Bool = false) throws -> ModelContainer { if !inMemory { let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! @@ -196,14 +221,8 @@ public actor PersistenceStore: ModelActor, PersistenceStoreProtocol { // Perform a simple fetch to trigger modelContext initialization _ = try modelContext.fetchCount(FetchDescriptor()) - // Both inner operations are idempotent under their own predicates: - // purgeOrphanPendingSends filters by absence of a matching - // Device.radioID and returns an empty row set once Device rows catch - // up; purgeLegacyAttemptCountRows filters by `attemptCount == nil` - // and returns empty after the first purge across the lifetime of - // the storage. Running both on every connect costs an empty fetch and - // self-heals the "erase device then re-pair" path — a process-level - // latch would suppress that recovery. + // Repeat both idempotent purges on each connection so removal and re-pairing + // can recover without requiring a process restart. let logger = Logger(subsystem: "com.mc1", category: "PersistenceStore.warmUp") do { try purgeOrphanPendingSends() @@ -253,7 +272,7 @@ public actor PersistenceStore: ModelActor, PersistenceStoreProtocol { let isNew: Bool if let existingNode = existing.first { existingNode.name = frame.name - existingNode.typeRawValue = frame.type.rawValue + existingNode.typeRawValue = frame.typeRawValue existingNode.lastHeard = Date() existingNode.lastAdvertTimestamp = frame.lastAdvertTimestamp existingNode.latitude = frame.latitude @@ -267,7 +286,7 @@ public actor PersistenceStore: ModelActor, PersistenceStoreProtocol { radioID: radioID, publicKey: frame.publicKey, name: frame.name, - typeRawValue: frame.type.rawValue, + typeRawValue: frame.typeRawValue, lastAdvertTimestamp: frame.lastAdvertTimestamp, latitude: frame.latitude, longitude: frame.longitude, diff --git a/MC1Services/Sources/MC1Services/Services/PlainTextSendGate.swift b/MC1Services/Sources/MC1Services/Services/PlainTextSendGate.swift new file mode 100644 index 0000000000..25919886de --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PlainTextSendGate.swift @@ -0,0 +1,130 @@ +import Foundation + +/// Serializes plain-text sends until both command issuance and ACK tracking finish. +/// An early ACK cannot admit another sender while the current command is suspended. +actor PlainTextSendGate { + struct Lease: Sendable, Hashable { + let id: UUID + } + + private struct Owner { + let lease: Lease + var issuingCommands: Bool + var ackPending: Bool + var sawResolution: Bool + } + + private struct Waiter { + let id: UUID + let continuation: CheckedContinuation + } + + private var owner: Owner? + private var restoredAckLeaseIDs: Set = [] + private var waiters: [Waiter] = [] + private(set) var isInvalidated = false + + private var canAdmit: Bool { + owner == nil && restoredAckLeaseIDs.isEmpty + } + + #if DEBUG + var waiterCountForTesting: Int { + waiters.count + } + + var ownerLeaseIDForTesting: UUID? { + owner?.lease.id + } + #endif + + func acquire() async throws -> Lease { + try Task.checkCancellation() + if isInvalidated { throw CancellationError() } + if canAdmit { + return claim() + } + + let waiterID = UUID() + return try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + if isInvalidated || Task.isCancelled { + continuation.resume(throwing: CancellationError()) + return + } + waiters.append(Waiter(id: waiterID, continuation: continuation)) + } + } onCancel: { + Task { await self.cancelWaiter(waiterID) } + } + } + + func reserveRestoredAcks(_ leaseIDs: Set) { + guard !isInvalidated else { return } + restoredAckLeaseIDs.formUnion(leaseIDs) + } + + /// Preserves an earlier resolution when send bookkeeping arrives after an ACK. + func noteAckObligation(_ lease: Lease) { + guard var current = owner, current.lease == lease, !current.sawResolution else { return } + current.ackPending = true + owner = current + } + + func settleAck(_ lease: Lease) { + if restoredAckLeaseIDs.remove(lease.id) != nil { + admitNext() + return + } + guard var current = owner, current.lease == lease else { return } + current.sawResolution = true + current.ackPending = false + owner = current + releaseIfIdle() + } + + /// The owner will issue no further commands. A pending ACK keeps the lease. + func stopIssuing(_ lease: Lease) { + guard var current = owner, current.lease == lease, current.issuingCommands else { return } + current.issuingCommands = false + owner = current + releaseIfIdle() + } + + /// Cancels admission without cancelling an in-flight command, whose caller still owns its completion. + func invalidate() { + isInvalidated = true + owner = nil + restoredAckLeaseIDs.removeAll() + let pending = waiters + waiters.removeAll() + for waiter in pending { + waiter.continuation.resume(throwing: CancellationError()) + } + } + + private func claim() -> Lease { + let lease = Lease(id: UUID()) + owner = Owner(lease: lease, issuingCommands: true, ackPending: false, sawResolution: false) + return lease + } + + private func releaseIfIdle() { + guard let current = owner, !current.issuingCommands, !current.ackPending else { return } + owner = nil + admitNext() + } + + private func admitNext() { + guard !isInvalidated, canAdmit, !waiters.isEmpty else { return } + let waiter = waiters.removeFirst() + let lease = claim() + waiter.continuation.resume(returning: lease) + } + + private func cancelWaiter(_ id: UUID) { + guard let index = waiters.firstIndex(where: { $0.id == id }) else { return } + let waiter = waiters.remove(at: index) + waiter.continuation.resume(throwing: CancellationError()) + } +} diff --git a/MC1Services/Sources/MC1Services/Services/RadioCLIReply.swift b/MC1Services/Sources/MC1Services/Services/RadioCLIReply.swift index 1d108f3ad3..41cf80f732 100644 --- a/MC1Services/Sources/MC1Services/Services/RadioCLIReply.swift +++ b/MC1Services/Sources/MC1Services/Services/RadioCLIReply.swift @@ -1,6 +1,6 @@ import Foundation -/// One Radio CLI reply, classified after trailing CR and LF are removed. +/// A framed Radio CLI value preserves its payload; reply markers ignore trailing CR and LF. public enum RadioCLIReply: Sendable, Equatable { case unknownCommand case error(String) @@ -16,24 +16,24 @@ public enum RadioCLIReply: Sendable, Equatable { public static let notConnected = "(not connected)" public init(text: String) { - let text = Self.strippingTrailingLineEndings(text) - if text == "Unknown command" { + let marker = Self.strippingTrailingLineEndings(text) + if marker == "Unknown command" { self = .unknownCommand return } - if text.hasPrefix("Error") || text.hasPrefix("ERROR") || text.hasPrefix("ERR") { - self = .error(text) + if marker.hasPrefix("Error") || marker.hasPrefix("ERROR") || marker.hasPrefix("ERR") { + self = .error(marker) return } if text.hasPrefix("> ") { self = .value(String(text.dropFirst(2))) return } - if text.hasPrefix("OK") { - self = .ok(text) + if marker.hasPrefix("OK") { + self = .ok(marker) return } - self = .other(text) + self = .other(marker) } /// Drops trailing U+000D and U+000A scalars. `"\r\n"` is one `Character`, diff --git a/MC1Services/Sources/MC1Services/Services/RadioWiFiBinding.swift b/MC1Services/Sources/MC1Services/Services/RadioWiFiBinding.swift new file mode 100644 index 0000000000..a53ee376e9 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/RadioWiFiBinding.swift @@ -0,0 +1,12 @@ +import Foundation + +/// An immutable certificate namespace for one SettingsService WiFi context. +public struct RadioWiFiBinding: Sendable { + public let contextID: UUID + public let state: RadioWiFiState + + init(state: RadioWiFiState) { + contextID = UUID() + self.state = state + } +} diff --git a/MC1Services/Sources/MC1Services/Services/RadioWiFiCommandResult.swift b/MC1Services/Sources/MC1Services/Services/RadioWiFiCommandResult.swift new file mode 100644 index 0000000000..a0c2a3c6ef --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/RadioWiFiCommandResult.swift @@ -0,0 +1,9 @@ +import Foundation + +struct RadioWiFiCommandResult: Sendable { + let contextID: UUID + let reply: String? + let revision: UInt64? + let outcome: RadioWiFiState.MutationOutcome + let error: (any Error)? +} diff --git a/MC1Services/Sources/MC1Services/Services/RadioWiFiCredentialBaseline.swift b/MC1Services/Sources/MC1Services/Services/RadioWiFiCredentialBaseline.swift new file mode 100644 index 0000000000..7d188e961e --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/RadioWiFiCredentialBaseline.swift @@ -0,0 +1,41 @@ +import Foundation + +/// A known credential pair from one editor, service, and stable mutation revision. +public struct RadioWiFiCredentialBaseline: Sendable { + public static let minSSIDBytes = 1 + public static let maxSSIDBytes = 32 + public static let maxPasswordBytes = 63 + private static let nullByte: UInt8 = 0 + public let contextID: UUID + public let radioID: UUID + public let editorID: UUID + public let revision: UInt64 + public let ssid: String + public let password: String + let readID: UUID + + public static func isRepresentable(_ text: String) -> Bool { + !text.utf8.contains(nullByte) + } + + public static func hasSameBytes(_ first: String, _ second: String) -> Bool { + first.utf8.elementsEqual(second.utf8) + } + + public static func validCredentials(ssid: String, password: String) -> Bool { + (minSSIDBytes...maxSSIDBytes).contains(ssid.utf8.count) && password.utf8.count <= maxPasswordBytes + && isRepresentable(ssid) && isRepresentable(password) + } + + func updating(ssid: String, password: String, revision: UInt64) -> Self { + Self( + contextID: contextID, + radioID: radioID, + editorID: editorID, + revision: revision, + ssid: ssid, + password: password, + readID: readID + ) + } +} diff --git a/MC1Services/Sources/MC1Services/Services/RadioWiFiEnabledReceipt.swift b/MC1Services/Sources/MC1Services/Services/RadioWiFiEnabledReceipt.swift new file mode 100644 index 0000000000..32f48a1f5b --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/RadioWiFiEnabledReceipt.swift @@ -0,0 +1,9 @@ +import Foundation + +/// A typed enabled change carries the settlement of its captured WiFi context. +public struct RadioWiFiEnabledReceipt: Sendable { + public let contextID: UUID + public let revision: UInt64? + public let outcome: RadioWiFiState.MutationOutcome + public let error: (any Error)? +} diff --git a/MC1Services/Sources/MC1Services/Services/RadioWiFiMutationReceipt.swift b/MC1Services/Sources/MC1Services/Services/RadioWiFiMutationReceipt.swift new file mode 100644 index 0000000000..9dc2f61b7b --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/RadioWiFiMutationReceipt.swift @@ -0,0 +1,13 @@ +import Foundation + +/// Acknowledged effects are kept even when a later credential command fails. +public struct RadioWiFiMutationReceipt: Sendable { + public let contextID: UUID + public let ssidAccepted: Bool + public let passwordAccepted: Bool + public let revision: UInt64? + public let uncertain: Bool + public let error: (any Error)? + /// Kept only by the current editor; never emitted as a settings event. + public let updatedBaseline: RadioWiFiCredentialBaseline? +} diff --git a/MC1Services/Sources/MC1Services/Services/RadioWiFiReadResult.swift b/MC1Services/Sources/MC1Services/Services/RadioWiFiReadResult.swift new file mode 100644 index 0000000000..72f0017d5d --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/RadioWiFiReadResult.swift @@ -0,0 +1,15 @@ +import Foundation + +/// Confirmed nonsecret fields survive a later failed CLI read in the same context. +public struct RadioWiFiReadResult: Sendable { + public let contextID: UUID + public let radioID: UUID + public let revision: UInt64 + public let enabled: Bool + public let networkName: String? + public let networkNameWasRead: Bool + public let associated: Bool? + public let ipAddress: String? + public let ipAddressWasRead: Bool + public let error: (any Error)? +} diff --git a/MC1Services/Sources/MC1Services/Services/RadioWiFiResetObservation.swift b/MC1Services/Sources/MC1Services/Services/RadioWiFiResetObservation.swift new file mode 100644 index 0000000000..2ee56475f5 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/RadioWiFiResetObservation.swift @@ -0,0 +1,35 @@ +import Foundation + +public struct RadioWiFiResetObservation: Sendable { + let uptimeSeconds: UInt32 + let startedAt: ContinuousClock.Instant + let completedAt: ContinuousClock.Instant + + private static let millisecondsPerSecond: UInt64 = 1000 + private static let millisPeriod = UInt64(UInt32.max) + 1 + private static let observationToleranceSeconds = 2.0 + private static let elapsedDriftAllowance = 0.01 + private static let attosecondsPerSecond = 1e18 + + func provesReset(since earlier: Self) -> Bool { + guard startedAt >= earlier.completedAt else { return false } + let duration = earlier.startedAt.duration(to: completedAt).components + let elapsed = Double(duration.seconds) + Double(duration.attoseconds) / Self.attosecondsPerSecond + let upperBound = elapsed + Self.observationToleranceSeconds + elapsed * Self.elapsedDriftAllowance + let periodSeconds = Double(Self.millisPeriod) / Double(Self.millisecondsPerSecond) + guard upperBound < periodSeconds, Double(uptimeSeconds) <= upperBound else { return false } + let earlierLow = UInt64(earlier.uptimeSeconds) * Self.millisecondsPerSecond + let laterLow = UInt64(uptimeSeconds) * Self.millisecondsPerSecond + guard earlierLow < Self.millisPeriod, laterLow < Self.millisPeriod else { return false } + let earlierHigh = min(earlierLow + Self.millisecondsPerSecond - 1, Self.millisPeriod - 1) + let laterHigh = min(laterLow + Self.millisecondsPerSecond - 1, Self.millisPeriod - 1) + let minimumProgression: UInt64 = if laterLow <= earlierHigh, laterHigh >= earlierLow { + 0 + } else if laterLow > earlierHigh { + laterLow - earlierHigh + } else { + Self.millisPeriod - earlierHigh + laterLow + } + return Double(minimumProgression) / Double(Self.millisecondsPerSecond) > upperBound + } +} diff --git a/MC1Services/Sources/MC1Services/Services/RadioWiFiSnapshot.swift b/MC1Services/Sources/MC1Services/Services/RadioWiFiSnapshot.swift new file mode 100644 index 0000000000..56191f2c93 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/RadioWiFiSnapshot.swift @@ -0,0 +1,19 @@ +import Foundation + +public enum RadioWiFiSnapshot: Sendable { + static let enabledValue = "1" + static let disabledValue = "0" + static let connectedStatus = "connected" + + public struct Probe: Sendable { + public let enabled: Bool + let contextID: UUID + public let revision: UInt64 + } + + public enum Capability: Sendable { + case supported(Probe) + case unavailable + case busy + } +} diff --git a/MC1Services/Sources/MC1Services/Services/RadioWiFiState.swift b/MC1Services/Sources/MC1Services/Services/RadioWiFiState.swift new file mode 100644 index 0000000000..b226b9ac1b --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/RadioWiFiState.swift @@ -0,0 +1,149 @@ +import Foundation + +/// In-process WiFi mutation and apply evidence for one Radio ID. +@MainActor +public final class RadioWiFiState { + public nonisolated let radioID: UUID + public private(set) var revision: UInt64 = 0 + public private(set) var rebootPending = false + private var mutations: Set = [] + private var expectedReboot: ExpectedReboot? + private var admissionClosed = false + private var settlementWaiters: [CheckedContinuation] = [] + + public nonisolated init(radioID: UUID) { + self.radioID = radioID + } + + public struct MutationToken: Sendable { + let id: UUID + let revision: UInt64 + } + + public enum MutationOutcome: Sendable { + case accepted + case rejected + case uncertain + } + + private struct ExpectedReboot { + let id: UUID + let contextID: UUID + let revision: UInt64 + let observation: RadioWiFiResetObservation? + var submitted = false + var linkEnded = false + } + + public var expectedRebootID: UUID? { + expectedReboot?.id + } + + public func stableRevision() -> UInt64? { + mutations.isEmpty && !admissionClosed ? revision : nil + } + + public func beginMutation(expectedRevision: UInt64?) -> MutationToken? { + guard !admissionClosed else { return nil } + if let expectedRevision { + guard mutations.isEmpty, revision == expectedRevision else { return nil } + } + expectedReboot = nil + revision &+= 1 + let token = MutationToken(id: UUID(), revision: revision) + mutations.insert(token.id) + return token + } + + public func isUncontended(_ token: MutationToken) -> Bool { + !admissionClosed && mutations.count == 1 && mutations.contains(token.id) && revision == token.revision + } + + @discardableResult + public func settle(_ token: MutationToken, outcome: MutationOutcome) -> UInt64? { + let uncontended = isUncontended(token) + guard mutations.remove(token.id) != nil else { return nil } + revision &+= 1 + switch outcome { + case .accepted, .uncertain: + rebootPending = true + case .rejected: + break + } + if mutations.isEmpty { + let waiters = settlementWaiters + settlementWaiters.removeAll() + for waiter in waiters { + waiter.resume() + } + } + return uncontended && mutations.isEmpty ? revision : nil + } + + func closeAdmission() { + admissionClosed = true + expectedReboot = nil + } + + func openAdmission() { + admissionClosed = false + } + + func waitForMutationSettlement() async { + guard !mutations.isEmpty else { return } + await withCheckedContinuation { settlementWaiters.append($0) } + } + + func adoptCanonicalEvidence(rebootPending inherited: Bool) { + rebootPending = rebootPending || inherited + revision &+= 1 + expectedReboot = nil + } + + public func prepareExpectedReboot( + contextID: UUID, expectedRevision: UInt64? = nil, observation: RadioWiFiResetObservation? = nil + ) -> UUID? { + if let expectedRevision, expectedRevision != revision { return nil } + guard !admissionClosed, rebootPending, mutations.isEmpty else { return nil } + let id = UUID() + expectedReboot = ExpectedReboot(id: id, contextID: contextID, revision: revision, observation: observation) + return id + } + + public func completeRebootSubmission(id: UUID, succeeded: Bool) { + guard expectedReboot?.id == id else { return } + if succeeded { + expectedReboot?.submitted = true + } else { + expectedReboot = nil + } + } + + public func noteLinkEnded(contextID: UUID) { + guard expectedReboot?.contextID == contextID else { return } + expectedReboot?.linkEnded = true + } + + public func cancelExpectedReboot() { + expectedReboot = nil + } + + @discardableResult + public func clearExpectedReboot( + id: UUID, contextID: UUID, readRevision: UInt64, observation: RadioWiFiResetObservation? = nil + ) -> Bool { + guard let candidate = expectedReboot, + candidate.id == id, + candidate.contextID != contextID, + candidate.submitted, + candidate.linkEnded, + !admissionClosed, + let before = candidate.observation, let observation, observation.provesReset(since: before), + mutations.isEmpty, + candidate.revision == revision, + readRevision == revision else { return false } + rebootPending = false + expectedReboot = nil + return true + } +} diff --git a/MC1Services/Sources/MC1Services/Services/ReactionService.swift b/MC1Services/Sources/MC1Services/Services/ReactionService.swift index 8e65bc471d..4b51ddb790 100644 --- a/MC1Services/Sources/MC1Services/Services/ReactionService.swift +++ b/MC1Services/Sources/MC1Services/Services/ReactionService.swift @@ -20,6 +20,7 @@ public struct PendingDMReaction: Sendable { public let rawText: String public let radioID: UUID public let receivedAt: Date + public let directMessage: (scope: ReceiveScope, contact: ContactDTO)? } /// Result of persisting a reaction @@ -195,7 +196,8 @@ public actor ReactionService { /// Logs errors instead of silently discarding them. public func persistReactionAndUpdateSummary( _ reaction: ReactionDTO, - using dataStore: any PersistenceStoreProtocol + using dataStore: any PersistenceStoreProtocol, + directMessage: (scope: ReceiveScope, contact: ContactDTO)? = nil ) async -> ReactionPersistResult? { #if DEBUG if let hold = reactionAdmitHoldForTesting { @@ -203,9 +205,12 @@ public actor ReactionService { } #endif do { - guard let admission = try await dataStore.admitReaction(reaction), admission.inserted else { - return nil + let admission: ReactionAdmission? = if let (scope, contact) = directMessage { + try await dataStore.admitDirectMessageReaction(reaction, contact: contact, scope: scope) + } else { + try await dataStore.admitReaction(reaction) } + guard let admission, admission.inserted else { return nil } return ReactionPersistResult(messageID: admission.messageID, summary: admission.summary) } catch { logger.error("Failed to save reaction for message \(reaction.messageID): \(error.localizedDescription)") @@ -256,8 +261,10 @@ public actor ReactionService { contactID: UUID, senderName: String, rawText: String, - radioID: UUID + radioID: UUID, + directMessage: (scope: ReceiveScope, contact: ContactDTO)? = nil ) { + guard directMessage?.scope.isCurrent != false else { return } let key = PendingDMReactionKey(contactID: contactID, messageHash: parsed.messageHash) let pending = PendingDMReaction( parsed: parsed, @@ -265,7 +272,8 @@ public actor ReactionService { senderName: senderName, rawText: rawText, radioID: radioID, - receivedAt: Date() + receivedAt: Date(), + directMessage: directMessage ) if pendingDMReactions[key] != nil { diff --git a/MC1Services/Sources/MC1Services/Services/RemoteCLINoReplyCommand.swift b/MC1Services/Sources/MC1Services/Services/RemoteCLINoReplyCommand.swift index 13ed7a7988..b65348c93e 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteCLINoReplyCommand.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteCLINoReplyCommand.swift @@ -3,20 +3,33 @@ import Foundation /// A repeater or room command that gets no reply. /// Matched on the lowercased, trimmed verb, or that verb plus a space. `poweroffx` does not match. public enum RemoteCLINoReplyCommand: Sendable, Equatable { + private static let rebootVerb = "reboot" + private static let clockRebootVerb = "clkreboot" + private static let powerOffVerb = "poweroff" + private static let shutdownVerb = "shutdown" + private static let ignoredSpace: UInt8 = 0x20 case reboot case powerOff public init?(_ command: String) { let normalized = command.lowercased().trimmingCharacters(in: .whitespacesAndNewlines) - if Self.matches(normalized, verb: "reboot") || Self.matches(normalized, verb: "clkreboot") { + if Self.matches(normalized, verb: Self.rebootVerb) || Self.matches(normalized, verb: Self.clockRebootVerb) { self = .reboot - } else if Self.matches(normalized, verb: "poweroff") || Self.matches(normalized, verb: "shutdown") { + } else if Self.matches(normalized, verb: Self.powerOffVerb) || Self.matches(normalized, verb: Self.shutdownVerb) { self = .powerOff } else { return nil } } + /// Sensor firmware matches lowercase prefixes after removing leading ASCII spaces. + public static func sensorCommand(_ command: String) -> Self? { + let wire = String(decoding: command.utf8.drop(while: { $0 == Self.ignoredSpace }), as: UTF8.self) + if wire.hasPrefix(Self.rebootVerb) || wire.hasPrefix(Self.clockRebootVerb) { return .reboot } + if wire.hasPrefix(Self.powerOffVerb) || wire.hasPrefix(Self.shutdownVerb) { return .powerOff } + return nil + } + private static func matches(_ normalized: String, verb: String) -> Bool { normalized == verb || normalized.hasPrefix(verb + " ") } diff --git a/MC1Services/Sources/MC1Services/Services/RemoteCLISlot.swift b/MC1Services/Sources/MC1Services/Services/RemoteCLISlot.swift new file mode 100644 index 0000000000..b527fb0f05 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/RemoteCLISlot.swift @@ -0,0 +1,91 @@ +import Foundation + +/// Holds a destination's FIFO slot across reply completion and recovery retries. +struct RemoteCLISlot { + struct Request { + let id: UUID + let command: String + let wirePrefix: String + let acceptsAnyResponse: Bool + let continuation: CheckedContinuation + let worker: Task + } + + struct Waiter { + let id: UUID + let continuation: CheckedContinuation + } + + private enum State { + case held + case exchanging(Request) + } + + private(set) var ownerID: UUID + private var state: State = .held + private var waiters: [Waiter] = [] + + init(ownerID: UUID) { + self.ownerID = ownerID + } + + var pendingRequest: Request? { + switch state { + case let .exchanging(request): request + case .held: nil + } + } + + var waiterCount: Int { + waiters.count + } + + mutating func beginExchange(_ request: Request) { + switch state { + case .held: + state = .exchanging(request) + case .exchanging: + preconditionFailure("CLI submission requires an unoccupied exchange") + } + } + + func isCurrentRequest(requestID: UUID) -> Bool { + pendingRequest?.id == requestID + } + + /// Clear request ownership before cancelling the worker so cancellation cannot resume it again. + mutating func claimCompletion(requestID: UUID) -> CheckedContinuation? { + guard let request = pendingRequest, request.id == requestID else { return nil } + state = .held + request.worker.cancel() + return request.continuation + } + + mutating func enqueue(_ waiter: Waiter) { + waiters.append(waiter) + } + + mutating func removeWaiter(id: UUID) -> Waiter? { + guard let index = waiters.firstIndex(where: { $0.id == id }) else { return nil } + return waiters.remove(at: index) + } + + mutating func advance() -> Waiter? { + precondition(pendingRequest == nil, "CLI handoff requires a completed exchange") + guard !waiters.isEmpty else { return nil } + let next = waiters.removeFirst() + ownerID = next.id + return next + } + + mutating func cancelAll() { + if let request = pendingRequest { + claimCompletion(requestID: request.id)?.resume(throwing: CancellationError()) + } + let cancelled = waiters + waiters.removeAll() + for waiter in cancelled { + waiter.continuation.resume(throwing: CancellationError()) + } + } +} diff --git a/MC1Services/Sources/MC1Services/Services/RemoteFloodFallback.swift b/MC1Services/Sources/MC1Services/Services/RemoteFloodFallback.swift new file mode 100644 index 0000000000..984aa3c2b3 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/RemoteFloodFallback.swift @@ -0,0 +1,12 @@ +import Foundation + +public enum RemoteFloodFallback { + public static let defaultEnabled = true + + /// `UserDefaults.bool(forKey:)` is false when the key is absent, so a missing key stays on. + public static func isEnabled(defaults: UserDefaults = .standard) -> Bool { + let key = AppStorageKey.remoteFloodFallback.rawValue + guard defaults.object(forKey: key) != nil else { return defaultEnabled } + return defaults.bool(forKey: key) + } +} diff --git a/MC1Services/Sources/MC1Services/Services/RemoteLoginAttempt.swift b/MC1Services/Sources/MC1Services/Services/RemoteLoginAttempt.swift new file mode 100644 index 0000000000..e2330d07fe --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/RemoteLoginAttempt.swift @@ -0,0 +1,68 @@ +import Foundation +import MeshCore + +/// Owns one login until its caller finishes, including persistence after a reply. +struct RemoteLoginAttempt { + struct Completion { + let attemptID: UUID + let sessionID: UUID + let continuation: CheckedContinuation + } + + private struct Pending { + let continuation: CheckedContinuation + let worker: Task + } + + private enum State { + case preparing + case submitting(Pending) + case awaitingResponse(Pending) + case completing + } + + let id = UUID() + let sessionID: UUID + private var state: State = .preparing + + init(sessionID: UUID) { + self.sessionID = sessionID + } + + var isAwaitingResult: Bool { + switch state { + case .submitting, .awaitingResponse: true + case .preparing, .completing: false + } + } + + mutating func beginSubmission( + continuation: CheckedContinuation, worker: Task + ) { + guard case .preparing = state else { + preconditionFailure("Login submission requires a preparing attempt") + } + state = .submitting(Pending(continuation: continuation, worker: worker)) + } + + @discardableResult + mutating func didSubmit() -> Bool { + guard case let .submitting(pending) = state else { return false } + state = .awaitingResponse(pending) + return true + } + + /// Transfers completion before cancelling the worker; an early reply can win during submission. + mutating func claimCompletion() -> Completion? { + let pending: Pending + switch state { + case let .submitting(value), let .awaitingResponse(value): + pending = value + case .preparing, .completing: + return nil + } + state = .completing + pending.worker.cancel() + return Completion(attemptID: id, sessionID: sessionID, continuation: pending.continuation) + } +} diff --git a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+CLI.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+CLI.swift index 44442c54d7..e6fe710cee 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+CLI.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+CLI.swift @@ -1,20 +1,14 @@ import Foundation import MeshCore -extension RemoteNodeService { - private static let cliIgnoredSpace: UInt8 = 0x20 +public extension RemoteNodeService { + internal static let cliIgnoredSpace: UInt8 = 0x20 // MARK: - CLI Commands - /// Send a CLI command to a remote node and wait for its response (admin only). - /// Replies to structured `get` queries must parse to their expected shape; - /// anything else waiting in the mesh is dropped instead of misattributed. - /// - Parameters: - /// - sessionID: The remote node session ID. - /// - command: The CLI command to send. - /// - timeout: Hard maximum time to wait for response (default 10 seconds). - /// - Returns: The CLI response text from the remote node. - public func sendCLICommand( + /// Send a CLI command through an admin session. + /// Legacy replies must match the expected response shape to avoid adopting stale responses. + func sendCLICommand( sessionID: UUID, command: String, timeout: Duration = .seconds(10) @@ -27,15 +21,8 @@ extension RemoteNodeService { ) } - /// Send a raw CLI command to a remote node (admin only). The next reply from - /// the node is delivered verbatim without shape validation. Used by CLI - /// terminals and commands whose reply format is free-form. - /// - Parameters: - /// - sessionID: The remote node session ID. - /// - command: The CLI command to send. - /// - timeout: Hard maximum time to wait for response (default 10 seconds). - /// - Returns: The raw response text from the remote node. - public func sendRawCLICommand( + /// Send a CLI command through an admin session, accepting free-form legacy replies. + func sendRawCLICommand( sessionID: UUID, command: String, timeout: Duration = .seconds(10) @@ -53,8 +40,7 @@ extension RemoteNodeService { return response } - /// Shared send path: acquires the node's CLI slot so exactly one command is - /// in flight per node, then performs the exchange. + /// Hold the destination's CLI slot through authorization and any Direct-to-Flood retry. private func performCLICommand( sessionID: UUID, command: String, @@ -69,22 +55,47 @@ extension RemoteNodeService { throw RemoteNodeError.permissionDenied } - let command = RemoteCLICommandRewriter.rewrite(command) + let command = remoteSession.isSensor + ? String(decoding: command.utf8.drop(while: { $0 == Self.cliIgnoredSpace }), as: UTF8.self) + : RemoteCLICommandRewriter.rewrite(command) + if remoteSession.isSensor { try SensorSetting.validateCommand(command) } - // Log CLI command (with password redaction) await auditLogger.logCLICommand( publicKey: remoteSession.publicKey, command: command, - target: .repeater + target: CommandAuditLogger.target(for: remoteSession.role) ) - let destinationPrefix = Data(remoteSession.publicKey.prefix(6)) - let requestID = UUID() + let destinationPrefix = Data(remoteSession.publicKey.prefix(Self.cliPublicKeyPrefixLength)) + let ownerID = UUID() - try await acquireCLISlot(for: destinationPrefix, waiterID: requestID) - defer { releaseCLISlot(for: destinationPrefix) } + try await acquireCLISlot(for: destinationPrefix, waiterID: ownerID) + defer { releaseCLISlot(for: destinationPrefix, ownerID: ownerID) } try Task.checkCancellation() + if remoteSession.isSensor { + _ = try await requireSensorAdmin(sessionID: sessionID) + try validateCLISlot(for: destinationPrefix, ownerID: ownerID) + if RemoteCLINoReplyCommand.sensorCommand(command) != nil { + do { + _ = try await session.sendCommand( + to: remoteSession.publicKey, command: makeCLIWirePrefix() + command, textType: .cliData + ) + } catch is CancellationError { + throw CancellationError() + } catch let error as MeshCoreError { + throw RemoteNodeError.sessionError(error) + } + await disconnect(sessionID: sessionID) + return "" + } + return try await performCLIExchange( + publicKey: remoteSession.publicKey, destinationPrefix: destinationPrefix, + command: command, acceptsAnyResponse: true, timeout: timeout, + ownerID: ownerID, textType: .cliData + ) + } + // A no-reply command is sent once. Path reset and resend would repeat it. if RemoteCLINoReplyCommand(command) != nil { return try await performCLIExchange( @@ -93,7 +104,7 @@ extension RemoteNodeService { command: command, acceptsAnyResponse: acceptsAnyResponse, timeout: timeout, - requestID: requestID, + ownerID: ownerID, textType: .cliData ) } @@ -109,7 +120,7 @@ extension RemoteNodeService { command: command, acceptsAnyResponse: acceptsAnyResponse, timeout: timeout, - requestID: requestID, + ownerID: ownerID, textType: .cliData ) } @@ -117,17 +128,17 @@ extension RemoteNodeService { /// Sends a Radio CLI command to a chat contact. The contact runs it only after granting this radio Remote CLI. /// A missing reply is a timeout, not a reason to reset the contact's direct path. - public func sendRadioCLICommand( + func sendRadioCLICommand( to publicKey: Data, command: String, timeout: Duration ) async throws -> String { - let destinationPrefix = Data(publicKey.prefix(6)) - let requestID = UUID() + let destinationPrefix = Data(publicKey.prefix(Self.cliPublicKeyPrefixLength)) + let ownerID = UUID() await auditLogger.logCLICommand(publicKey: publicKey, command: command, target: .contact) - try await acquireCLISlot(for: destinationPrefix, waiterID: requestID) - defer { releaseCLISlot(for: destinationPrefix) } + try await acquireCLISlot(for: destinationPrefix, waiterID: ownerID) + defer { releaseCLISlot(for: destinationPrefix, ownerID: ownerID) } try Task.checkCancellation() return try await performCLIExchange( @@ -136,152 +147,11 @@ extension RemoteNodeService { command: command, acceptsAnyResponse: false, timeout: timeout, - requestID: requestID, + ownerID: ownerID, textType: .cliCommand ) } - /// Register the pending request, send the command, and poll the device for - /// the reply until it arrives or the effective timeout elapses. - private func performCLIExchange( - publicKey: Data, - destinationPrefix: Data, - command: String, - acceptsAnyResponse: Bool, - timeout: Duration, - requestID: UUID, - textType: MeshCore.TextType - ) async throws -> String { - let command = String(decoding: command.utf8.drop(while: { $0 == Self.cliIgnoredSpace }), as: UTF8.self) - let wirePrefix = makeCLIWirePrefix() - return try await withTaskCancellationHandler { - try await withCheckedThrowingContinuation { continuation in - guard !Task.isCancelled else { - continuation.resume(throwing: CancellationError()) - return - } - pendingCLIRequests[destinationPrefix] = PendingCLIRequest( - id: requestID, - command: command, - wirePrefix: wirePrefix, - acceptsAnyResponse: acceptsAnyResponse, - continuation: continuation - ) - - pendingCLIRequests[destinationPrefix]?.workerTask = Task { [self] in - let sentInfo: MessageSentInfo - do { - try Task.checkCancellation() - sentInfo = try await session.sendCommand( - to: publicKey, - command: wirePrefix + command, - textType: textType - ) - } catch is CancellationError { - if let failed = takePendingCLIRequest(for: destinationPrefix, requestID: requestID) { - failed.continuation.resume(throwing: CancellationError()) - } - return - } catch { - if let failed = takePendingCLIRequest(for: destinationPrefix, requestID: requestID) { - let meshError = error as? MeshCoreError ?? MeshCoreError.connectionLost(underlying: error) - failed.continuation.resume(throwing: RemoteNodeError.sessionError(meshError)) - } - return - } - - let effectiveTimeout = RemoteOperationTimeoutPolicy.cliTimeout(for: sentInfo, requestedTimeout: timeout) - let deadline = ContinuousClock.now.advanced(by: effectiveTimeout) - while ContinuousClock.now < deadline { - guard pendingCLIRequests[destinationPrefix]?.id == requestID else { - return // Request was resumed by handleCLIResponse or cancelled - } - - let remaining = deadline - .now - let pollDuration = min(RemoteOperationTimeoutPolicy.pollInterval, remaining) - do { - _ = try await session.getMessage(timeout: max(0.1, timeInterval(for: pollDuration))) - } catch is CancellationError { - if let stopped = takePendingCLIRequest(for: destinationPrefix, requestID: requestID) { - stopped.continuation.resume(throwing: CancellationError()) - } - return - } catch { - // A single poll can miss the reply. The deadline is the timeout. - } - } - - if let timedOut = takePendingCLIRequest(for: destinationPrefix, requestID: requestID) { - timedOut.continuation.resume(throwing: RemoteNodeError.timeout) - } - } - } - } onCancel: { [weak self] in - Task { [weak self] in - await self?.cancelPendingCLIRequest(for: destinationPrefix, requestID: requestID) - } - } - } - - /// Remove and return the pending request if it is still the given one. - func takePendingCLIRequest(for prefix: Data, requestID: UUID) -> PendingCLIRequest? { - guard let pending = pendingCLIRequests[prefix], pending.id == requestID else { return nil } - pendingCLIRequests[prefix] = nil - // Taken first, so the worker's cancellation path does not resume this continuation. - pending.workerTask?.cancel() - return pending - } - - // MARK: - CLI Slot - - /// Wait for the node's CLI slot (FIFO). Throws `CancellationError` if the - /// calling task is cancelled while waiting. - private func acquireCLISlot(for prefix: Data, waiterID: UUID) async throws { - try Task.checkCancellation() - guard cliSlotBusy.contains(prefix) else { - cliSlotBusy.insert(prefix) - return - } - - try await withTaskCancellationHandler { - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - guard !Task.isCancelled else { - continuation.resume(throwing: CancellationError()) - return - } - cliSlotWaiters[prefix, default: []].append(CLISlotWaiter(id: waiterID, continuation: continuation)) - } - } onCancel: { [weak self] in - Task { [weak self] in - await self?.cancelCLISlotWaiter(for: prefix, waiterID: waiterID) - } - } - } - - /// Hand the slot to the next waiter, or free it when none are queued. - private func releaseCLISlot(for prefix: Data) { - if var waiters = cliSlotWaiters[prefix], !waiters.isEmpty { - let next = waiters.removeFirst() - cliSlotWaiters[prefix] = waiters.isEmpty ? nil : waiters - next.continuation.resume() - } else { - cliSlotBusy.remove(prefix) - } - } - - /// Cancel a queued slot waiter when its calling task is cancelled. - private func cancelCLISlotWaiter(for prefix: Data, waiterID: UUID) { - guard var waiters = cliSlotWaiters[prefix], - let index = waiters.firstIndex(where: { $0.id == waiterID }) else { - return - } - - let cancelled = waiters.remove(at: index) - cliSlotWaiters[prefix] = waiters.isEmpty ? nil : waiters - cancelled.continuation.resume(throwing: CancellationError()) - } - - /// Clear stored password if command is an admin password change. private func handlePasswordChangeIfNeeded(command: String, sessionID: UUID) async { let lower = command.lowercased().trimmingCharacters(in: .whitespaces) diff --git a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+CLIExchange.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+CLIExchange.swift new file mode 100644 index 0000000000..3904e426dd --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+CLIExchange.swift @@ -0,0 +1,171 @@ +import Foundation +import MeshCore + +extension RemoteNodeService { + private static let minimumCLIPollTimeout: TimeInterval = 0.1 + + func performCLIExchange( + publicKey: Data, + destinationPrefix: Data, + command: String, + acceptsAnyResponse: Bool, + timeout: Duration, + ownerID: UUID, + textType: MeshCore.TextType + ) async throws -> String { + try validateCLISlot(for: destinationPrefix, ownerID: ownerID) + let command = String(decoding: command.utf8.drop(while: { $0 == Self.cliIgnoredSpace }), as: UTF8.self) + let wirePrefix = makeCLIWirePrefix() + let requestID = UUID() + return try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + guard !Task.isCancelled else { + continuation.resume(throwing: CancellationError()) + return + } + let worker = Task { [self] in + await runCLIExchange( + publicKey: publicKey, prefix: destinationPrefix, command: command, + wirePrefix: wirePrefix, timeout: timeout, requestID: requestID, textType: textType + ) + } + cliSlots[destinationPrefix]?.beginExchange(RemoteCLISlot.Request( + id: requestID, + command: command, + wirePrefix: wirePrefix, + acceptsAnyResponse: acceptsAnyResponse, + continuation: continuation, + worker: worker + )) + } + } onCancel: { [weak self] in + Task { [weak self] in + await self?.cancelPendingCLIRequest(for: destinationPrefix, requestID: requestID) + } + } + } + + private func runCLIExchange( + publicKey: Data, prefix: Data, command: String, wirePrefix: String, + timeout: Duration, requestID: UUID, textType: MeshCore.TextType + ) async { + let sentInfo: MessageSentInfo + do { + try Task.checkCancellation() + sentInfo = try await session.sendCommand( + to: publicKey, + command: wirePrefix + command, + textType: textType + ) + } catch is CancellationError { + cancelPendingCLIRequest(for: prefix, requestID: requestID) + return + } catch { + let meshError = error as? MeshCoreError ?? MeshCoreError.connectionLost(underlying: error) + cliSlots[prefix]?.claimCompletion(requestID: requestID)?.resume( + throwing: RemoteNodeError.sessionError(meshError) + ) + return + } + + guard cliSlots[prefix]?.isCurrentRequest(requestID: requestID) == true else { return } + let effectiveTimeout = RemoteOperationTimeoutPolicy.cliTimeout(for: sentInfo, requestedTimeout: timeout) + let deadline = ContinuousClock.now.advanced(by: effectiveTimeout) + while ContinuousClock.now < deadline { + guard cliSlots[prefix]?.isCurrentRequest(requestID: requestID) == true else { return } + + let remaining = deadline - .now + let pollDuration = min(RemoteOperationTimeoutPolicy.pollInterval, remaining) + do { + _ = try await session.getMessage(timeout: max(Self.minimumCLIPollTimeout, timeInterval(for: pollDuration))) + } catch is CancellationError { + cancelPendingCLIRequest(for: prefix, requestID: requestID) + return + } catch { + // A single poll can miss the reply. The deadline is the timeout. + } + } + + cliSlots[prefix]?.claimCompletion(requestID: requestID)?.resume(throwing: RemoteNodeError.timeout) + } + + private func cancelPendingCLIRequest(for prefix: Data, requestID: UUID) { + cliSlots[prefix]?.claimCompletion(requestID: requestID)?.resume(throwing: CancellationError()) + } + + // MARK: - CLI Slot + + func validateCLISlot(for prefix: Data, ownerID: UUID) throws { + try Task.checkCancellation() + guard !isRetired else { throw RemoteNodeError.notConnected } + guard cliSlots[prefix]?.ownerID == ownerID else { throw CancellationError() } + } + + func acquireCLISlot(for prefix: Data, waiterID: UUID) async throws { + try Task.checkCancellation() + guard !isRetired else { throw RemoteNodeError.notConnected } + guard cliSlots[prefix] != nil else { + cliSlots[prefix] = RemoteCLISlot(ownerID: waiterID) + return + } + + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + guard !Task.isCancelled else { + continuation.resume(throwing: CancellationError()) + return + } + cliSlots[prefix]?.enqueue(RemoteCLISlot.Waiter(id: waiterID, continuation: continuation)) + } + } onCancel: { [weak self] in + Task { [weak self] in + await self?.cancelCLISlotWaiter(for: prefix, waiterID: waiterID) + } + } + } + + func releaseCLISlot(for prefix: Data, ownerID: UUID) { + guard cliSlots[prefix]?.ownerID == ownerID else { return } + if let next = cliSlots[prefix]?.advance() { + next.continuation.resume() + } else { + cliSlots[prefix] = nil + } + } + + private func cancelCLISlotWaiter(for prefix: Data, waiterID: UUID) { + cliSlots[prefix]?.removeWaiter(id: waiterID)?.continuation.resume(throwing: CancellationError()) + } + + /// Match echoed wire prefixes; older firmware replies use single-flight shape validation. + func handleCLIResponse(_ message: ContactMessage) { + let prefix = Data(message.senderPublicKeyPrefix.prefix(Self.cliPublicKeyPrefixLength)) + + guard let pending = cliSlots[prefix]?.pendingRequest else { + logger.debug("Unmatched CLI response (no pending request), length \(message.text.count)") + return + } + + let responseText: String + if let echoed = CLIResponse.splitEchoedPrefix(message.text) { + guard echoed.prefix == pending.wirePrefix else { + logger.warning( + "Dropping stale CLI response with prefix \(echoed.prefix) while awaiting \(pending.wirePrefix)" + ) + return + } + responseText = echoed.body + } else { + guard pending.acceptsAnyResponse + || CLIResponse.isPlausibleResponse(message.text, forQuery: pending.command) else { + logger.warning( + "Dropping CLI response that doesn't match pending command, length \(message.text.count)" + ) + return + } + responseText = message.text + } + + cliSlots[prefix]?.claimCompletion(requestID: pending.id)?.resume(returning: responseText) + } +} diff --git a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift index 1fd312cb00..24ebf5113e 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift @@ -1,11 +1,13 @@ import Foundation import MeshCore +private let loginPublicKeyPrefixLength = 6 + public extension RemoteNodeService { // MARK: - Login /// Login to a remote node. - /// Works for both room servers and repeaters. + /// Works for sensors, repeaters, and room servers. /// - Parameters: /// - sessionID: The remote session ID. /// - password: Optional password (uses stored password if nil). @@ -17,6 +19,8 @@ public extension RemoteNodeService { pathLength: UInt8 = 0, onTimeoutKnown: (@Sendable (Int) async -> Void)? = nil ) async throws -> LoginResult { + try Task.checkCancellation() + guard !isRetired else { throw RemoteNodeError.notConnected } guard let remoteSession = try await dataStore.fetchRemoteNodeSession(id: sessionID) else { throw RemoteNodeError.sessionNotFound } @@ -31,105 +35,110 @@ public extension RemoteNodeService { throw RemoteNodeError.passwordNotFound } - let prefix = Data(remoteSession.publicKey.prefix(6)) - - // Cancel any existing pending login for this prefix - if let existing = pendingLogins.removeValue(forKey: prefix) { - let prefixHex = prefix.map { String(format: "%02x", $0) }.joined() - logger.warning("Overwriting pending login for prefix \(prefixHex)") - pendingLoginTimeoutTasks.removeValue(forKey: prefix)?.cancel() - existing.continuation.resume(throwing: RemoteNodeError.cancelled) + guard pwd.utf8.count <= ProtocolLimits.maxRemotePasswordBytes else { throw RemoteNodeError.invalidPasswordLength } + try Task.checkCancellation() + guard !isRetired else { throw RemoteNodeError.notConnected } + let prefix = Data(remoteSession.publicKey.prefix(loginPublicKeyPrefixLength)) + cancelPendingLogin(for: prefix) + let attempt = RemoteLoginAttempt(sessionID: sessionID) + let attemptID = attempt.id + loginAttempts[prefix] = attempt + defer { + if loginAttempts[prefix]?.id == attemptID { loginAttempts[prefix] = nil } } - // Log login request - let targetType: CommandAuditLogger.Target = remoteSession.isRoom ? .room : .repeater + let targetType: CommandAuditLogger.Target = CommandAuditLogger.target(for: remoteSession.role) await auditLogger.logLoginRequest(target: targetType, publicKey: remoteSession.publicKey, pathLength: pathLength) - // Register continuation BEFORE sending to avoid race condition with loginSuccess event let prefixHex = prefix.map { String(format: "%02x", $0) }.joined() logger.info("login: registering pending login for prefix \(prefixHex)") return try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { continuation in - pendingLogins[prefix] = PendingLogin(sessionID: sessionID, continuation: continuation) - - let timeoutTask = Task { [self] in - let sentInfo: MessageSentInfo - do { - sentInfo = try await sendLoginHealingIfNeeded( - publicKey: remoteSession.publicKey, - radioID: remoteSession.radioID, - password: pwd - ) - } catch { - // Cancellation means this task no longer owns the continuation: whoever - // cancelled it (an overlapping login for this prefix, or cancelPendingLogin - // on outer-task cancellation) has already resumed and removed it. - guard !Task.isCancelled else { return } - pendingLoginTimeoutTasks.removeValue(forKey: prefix) - if let pending = pendingLogins.removeValue(forKey: prefix) { - let rnError = (error as? RemoteNodeError) - ?? .sessionError(error as? MeshCoreError ?? .connectionLost(underlying: error)) - pending.continuation.resume(throwing: rnError) - } - return - } - - let timeout = RemoteOperationTimeoutPolicy.loginTimeout(for: sentInfo, pathLength: pathLength) - logger.info("login: send succeeded, starting \(timeout) timeout for prefix \(prefixHex)") - - if let onTimeoutKnown { - let timeoutSeconds = max(1, Int(timeInterval(for: timeout).rounded(.up))) - await onTimeoutKnown(timeoutSeconds) - } - - // Retransmit while waiting for loginSuccess, spaced at least one - // firmware-suggested RTT so multi-hop paths are not flooded mid-flight. - let deadline = ContinuousClock.now.advanced(by: timeout) - let retransmitInterval = max( - RemoteOperationTimeoutPolicy.loginRetransmitInterval, - .milliseconds(Int(sentInfo.suggestedTimeoutMs)) + guard !Task.isCancelled, loginAttempts[prefix]?.id == attemptID, !isRetired else { + continuation.resume(throwing: RemoteNodeError.cancelled) + return + } + // Registration and worker installation share one actor turn so a reply can claim either send phase. + let worker = Task { [self] in + await runLoginAttempt( + remoteSession, password: pwd, prefix: prefix, attemptID: attemptID, + pathLength: pathLength, onTimeoutKnown: onTimeoutKnown ) - var retransmitCount = 0 - while !Task.isCancelled { - let remaining = deadline - ContinuousClock.now - guard remaining > .zero else { break } - let sleepFor = remaining < retransmitInterval ? remaining : retransmitInterval - try? await Task.sleep(for: sleepFor) - guard !Task.isCancelled else { return } - guard pendingLogins[prefix] != nil else { - logger.info("login: continuation consumed for prefix \(prefixHex); stopping retransmits") - return - } - if ContinuousClock.now >= deadline { break } - retransmitCount += 1 - do { - logger.info("login: retransmit #\(retransmitCount) for prefix \(prefixHex)") - _ = try await session.sendLogin(to: remoteSession.publicKey, password: pwd) - } catch is CancellationError { - return - } catch { - logger.warning( - "login: retransmit #\(retransmitCount) failed for \(prefixHex): \(error.localizedDescription)" - ) - } - } - - guard !Task.isCancelled else { return } - if let pending = pendingLogins.removeValue(forKey: prefix) { - logger.warning("Login timeout after \(timeout) for session \(sessionID), prefix \(prefixHex)") - pendingLoginTimeoutTasks.removeValue(forKey: prefix) - pending.continuation.resume(throwing: RemoteNodeError.timeout) - } else { - logger.info("login: timeout elapsed but continuation already consumed for prefix \(prefixHex)") - } } - pendingLoginTimeoutTasks[prefix] = timeoutTask + loginAttempts[prefix]?.beginSubmission(continuation: continuation, worker: worker) } } onCancel: { [weak self] in Task { [weak self] in - await self?.cancelPendingLogin(for: prefix) + await self?.cancelPendingLogin(for: prefix, attemptID: attemptID) + } + } + } + + private func runLoginAttempt( + _ remoteSession: RemoteNodeSessionDTO, password: String, prefix: Data, attemptID: UUID, + pathLength: UInt8, onTimeoutKnown: (@Sendable (Int) async -> Void)? + ) async { + let sentInfo: MessageSentInfo + do { + sentInfo = try await sendLoginHealingIfNeeded( + publicKey: remoteSession.publicKey, radioID: remoteSession.radioID, password: password + ) + } catch { + guard !Task.isCancelled, !isRetired else { return } + let rnError = (error as? RemoteNodeError) + ?? .sessionError(error as? MeshCoreError ?? .connectionLost(underlying: error)) + claimLoginCompletion(for: prefix, attemptID: attemptID)?.continuation.resume(throwing: rnError) + return + } + + guard !Task.isCancelled, loginAttempts[prefix]?.id == attemptID, !isRetired, + loginAttempts[prefix]?.didSubmit() == true else { return } + let prefixHex = prefix.map { String(format: "%02x", $0) }.joined() + let timeout = RemoteOperationTimeoutPolicy.loginTimeout(for: sentInfo, pathLength: pathLength) + logger.info("login: send succeeded, starting \(timeout) timeout for prefix \(prefixHex)") + + if let onTimeoutKnown { + let timeoutSeconds = max(1, Int(timeInterval(for: timeout).rounded(.up))) + await onTimeoutKnown(timeoutSeconds) + } + guard !Task.isCancelled, loginAttempts[prefix]?.id == attemptID, !isRetired, + loginAttempts[prefix]?.isAwaitingResult == true else { return } + + let deadline = ContinuousClock.now.advanced(by: timeout) + let retransmitInterval = max( + RemoteOperationTimeoutPolicy.loginRetransmitInterval, + .milliseconds(Int(sentInfo.suggestedTimeoutMs)) + ) + var retransmitCount = 0 + while !Task.isCancelled { + let remaining = deadline - ContinuousClock.now + guard remaining > .zero else { break } + let sleepFor = remaining < retransmitInterval ? remaining : retransmitInterval + try? await Task.sleep(for: sleepFor) + guard !Task.isCancelled, loginAttempts[prefix]?.id == attemptID, !isRetired, + loginAttempts[prefix]?.isAwaitingResult == true else { return } + if ContinuousClock.now >= deadline { break } + retransmitCount += 1 + do { + logger.info("login: retransmit #\(retransmitCount) for \(prefixHex)") + _ = try await session.sendLogin(to: remoteSession.publicKey, password: password) + } catch is CancellationError { + return + } catch { + logger.warning("login: retransmit #\(retransmitCount) failed for \(prefixHex): \(error.localizedDescription)") } } + + guard !Task.isCancelled, !isRetired else { return } + if let completion = claimLoginCompletion(for: prefix, attemptID: attemptID) { + logger.warning("Login timeout after \(timeout) for session \(remoteSession.id), prefix \(prefixHex)") + completion.continuation.resume(throwing: RemoteNodeError.timeout) + } + } + + private func claimLoginCompletion(for prefix: Data, attemptID: UUID? = nil) -> RemoteLoginAttempt.Completion? { + if let attemptID, loginAttempts[prefix]?.id != attemptID { return nil } + return loginAttempts[prefix]?.claimCompletion() } /// Sends the login; if the radio reports the contact is missing from its table, pushes the local @@ -184,257 +193,49 @@ public extension RemoteNodeService { /// Handle login result push from device. internal func handleLoginResult(_ result: LoginResult, fromPublicKeyPrefix: Data) async { - guard fromPublicKeyPrefix.count >= 6 else { + guard fromPublicKeyPrefix.count >= loginPublicKeyPrefixLength else { logger.warning("Login result has invalid prefix length: \(fromPublicKeyPrefix.count)") return } - let prefix = Data(fromPublicKeyPrefix.prefix(6)) + let prefix = Data(fromPublicKeyPrefix.prefix(loginPublicKeyPrefixLength)) let prefixHex = prefix.map { String(format: "%02x", $0) }.joined() - let pendingKeys = pendingLogins.keys.map { $0.map { String(format: "%02x", $0) }.joined() } + let pendingKeys = loginAttempts.filter(\.value.isAwaitingResult).keys.map { $0.map { String(format: "%02x", $0) }.joined() } logger.info("handleLoginResult: looking for prefix \(prefixHex), pending keys: \(pendingKeys)") - guard let pending = pendingLogins.removeValue(forKey: prefix) else { + guard let completion = claimLoginCompletion(for: prefix) else { logger.warning("Login result with no pending request. Prefix: \(prefixHex)") return } - pendingLoginTimeoutTasks.removeValue(forKey: prefix)?.cancel() logger.info("handleLoginResult: found continuation for prefix \(prefixHex)") - let continuation = pending.continuation - - if result.success { - // Update session state - do { - guard let remoteSession = try await dataStore.fetchRemoteNodeSession(id: pending.sessionID) else { - logger.error("handleLoginResult: no session found for \(pending.sessionID) - database may be corrupted") - continuation.resume(returning: result) - return - } - - // Log successful login - let targetType: CommandAuditLogger.Target = remoteSession.isRoom ? .room : .repeater - await auditLogger.logLoginSuccess(target: targetType, publicKey: prefix, isAdmin: result.isAdmin) - let permission = result.permissionLevel - - logger.info("handleLoginResult: updating session \(remoteSession.id) isConnected=true, permission=\(permission.rawValue)") - - try await dataStore.updateRemoteNodeSessionConnection( - id: remoteSession.id, - isConnected: true, - permissionLevel: permission - ) - - // Verify the update succeeded - if let verifySession = try await dataStore.fetchRemoteNodeSession(id: remoteSession.id) { - if verifySession.isConnected { - logger.info("handleLoginResult: verified session \(remoteSession.id) isConnected=true") - } else { - logger.error("handleLoginResult: session \(remoteSession.id) still shows isConnected=false after update!") - } - } - - // Notify UI of session state change - eventBroadcaster.yield(.sessionStateChanged(sessionID: remoteSession.id, isConnected: true)) - - keepAliveIntervals[remoteSession.id] = Self.defaultKeepAliveInterval - } catch { - logger.error("handleLoginResult: failed to update session state: \(error)") + do { + guard !isRetired else { throw RemoteNodeError.cancelled } + guard let remoteSession = try await dataStore.fetchRemoteNodeSession(id: completion.sessionID) else { + throw RemoteNodeError.sessionNotFound } - continuation.resume(returning: result) - } else { - // Log failed login - // Try to determine target type from existing session - if let remoteSession = try? await dataStore.fetchRemoteNodeSession(id: pending.sessionID) { - let targetType: CommandAuditLogger.Target = remoteSession.isRoom ? .room : .repeater - await auditLogger.logLoginFailed(target: targetType, publicKey: prefix, reason: "authentication failed") - } else { - await auditLogger.logLoginFailed(target: .repeater, publicKey: prefix, reason: "authentication failed") + guard loginAttempts[prefix]?.id == completion.attemptID, !isRetired else { throw RemoteNodeError.cancelled } + let target = CommandAuditLogger.target(for: remoteSession.role) + guard result.success else { + await auditLogger.logLoginFailed(target: target, publicKey: prefix, reason: "authentication failed") + throw RemoteNodeError.loginFailed("authentication failed") } - continuation.resume(throwing: RemoteNodeError.loginFailed("authentication failed")) - } - } - - // MARK: - Keep-Alive (Room Servers) - - /// Start periodic keep-alive for a room server session. - /// Sends an immediate keep-alive on start (for connectivity check + sync_since update), - /// then continues at the configured interval. Transient failures are retried up to - /// `KeepAliveRetryPolicy.maxConsecutiveFailures` times before disconnecting. - private func startKeepAlive(sessionID: UUID, publicKey: Data) { - stopKeepAlive(sessionID: sessionID) - - let interval = keepAliveIntervals[sessionID] ?? Self.defaultKeepAliveInterval - - // The actor retains this task via keepAliveTasks, so the loop captures - // self weakly and rebinds per tick; a strong capture would keep the - // actor (and its session/dataStore) alive for the app lifetime. - let task = Task { [weak self] in - var consecutiveFailures = 0 - - while !Task.isCancelled { - guard let tick = await self?.performKeepAliveTick( - sessionID: sessionID, - publicKey: publicKey, - consecutiveFailures: consecutiveFailures - ), tick.shouldContinue else { return } - consecutiveFailures = tick.consecutiveFailures - - try? await Task.sleep(for: interval) + await auditLogger.logLoginSuccess(target: target, publicKey: prefix, isAdmin: result.isAdmin) + guard loginAttempts[prefix]?.id == completion.attemptID, !isRetired else { throw RemoteNodeError.cancelled } + try await dataStore.updateRemoteNodeSessionConnection( + id: remoteSession.id, + isConnected: true, + permissionLevel: result.permissionLevel(for: remoteSession.role) + ) + guard loginAttempts[prefix]?.id == completion.attemptID, !isRetired else { + // A cancelled store turn may already have committed; retire it unless a new login owns the row. + if loginAttempts[prefix] == nil { try? await dataStore.markSessionDisconnected(remoteSession.id) } + throw RemoteNodeError.cancelled } - } - - keepAliveTasks[sessionID] = task - } - - /// Runs one keep-alive attempt for the loop in `startKeepAlive`. - /// Returns whether the loop should continue and the updated failure count. - private func performKeepAliveTick( - sessionID: UUID, - publicKey: Data, - consecutiveFailures: Int - ) async -> (shouldContinue: Bool, consecutiveFailures: Int) { - var failures = consecutiveFailures - do { - try await sendKeepAliveIfDirectRouted(sessionID: sessionID, publicKey: publicKey) - KeepAliveRetryPolicy.recordSuccess(consecutiveFailures: &failures) - return (shouldContinue: true, consecutiveFailures: failures) + eventBroadcaster.yield(.sessionStateChanged(sessionID: remoteSession.id, isConnected: true)) + if remoteSession.isRoom { keepAliveIntervals[remoteSession.id] = Self.defaultKeepAliveInterval } + completion.continuation.resume(returning: result) } catch { - let action = KeepAliveRetryPolicy.evaluate(error: error, consecutiveFailures: &failures) - switch action { - case .stop: - break - case .skip: - logger.info("Skipping keep-alive for flood-routed session \(sessionID)") - case .retryNextInterval: - let reason = KeepAliveRetryPolicy.failureReason(for: error) - logger.warning("Keep-alive \(failures)/\(KeepAliveRetryPolicy.maxConsecutiveFailures) failed for \(sessionID): \(reason)") - case .disconnect, .disconnectNow: - let reason = KeepAliveRetryPolicy.failureReason(for: error) - logger.warning("Keep-alive failed for \(sessionID): \(reason)") - do { - try await dataStore.markSessionDisconnected(sessionID) - } catch { - logger.error("Failed to persist disconnected state for session \(sessionID): \(error)") - } - eventBroadcaster.yield(.sessionStateChanged(sessionID: sessionID, isConnected: false)) - } - return (shouldContinue: !action.shouldExitLoop, consecutiveFailures: failures) + completion.continuation.resume(throwing: error) } } - - /// Stop keep-alive for a session - internal func stopKeepAlive(sessionID: UUID) { - keepAliveTasks[sessionID]?.cancel() - keepAliveTasks.removeValue(forKey: sessionID) - } - - /// Send keep-alive only if the session has a direct routing path. - private func sendKeepAliveIfDirectRouted(sessionID: UUID, publicKey: Data) async throws { - // Fetch session to get radioID - guard let remoteSession = try await dataStore.fetchRemoteNodeSession(id: sessionID) else { - throw RemoteNodeError.sessionNotFound - } - - // Check contact's routing status - guard let contact = try await dataStore.fetchContact(radioID: remoteSession.radioID, publicKey: publicKey) else { - throw RemoteNodeError.contactNotFound - } - - // Keep-alive only works with direct routing - if contact.isFloodRouted { - throw RemoteNodeError.floodRouted - } - - // Log keep-alive - let targetType: CommandAuditLogger.Target = remoteSession.isRoom ? .room : .repeater - await auditLogger.logKeepAlive(target: targetType, publicKey: publicKey) - - // Send keep-alive with sync_since for force-resync hint - do { - _ = try await session.sendKeepAlive(to: publicKey, syncSince: remoteSession.lastSyncTimestamp) - } catch let error as MeshCoreError { - throw RemoteNodeError.sessionError(error) - } - } - - /// Public method to send keep-alive (for manual refresh). - func sendKeepAlive(sessionID: UUID) async throws { - guard let remoteSession = try await dataStore.fetchRemoteNodeSession(id: sessionID) else { - throw RemoteNodeError.sessionNotFound - } - try await sendKeepAliveIfDirectRouted(sessionID: sessionID, publicKey: remoteSession.publicKey) - } - - /// Start keep-alive for a room session (called when room view appears). - func startSessionKeepAlive(sessionID: UUID, publicKey: Data) { - startKeepAlive(sessionID: sessionID, publicKey: publicKey) - } - - /// Stop keep-alive for a room session (called when room view disappears). - func stopSessionKeepAlive(sessionID: UUID) { - stopKeepAlive(sessionID: sessionID) - } - - // MARK: - History Sync - - /// Request message history from a room server. - func requestHistorySync(sessionID: UUID) async throws { - guard let remoteSession = try await dataStore.fetchRemoteNodeSession(id: sessionID) else { - throw RemoteNodeError.sessionNotFound - } - - guard remoteSession.isRoom else { - throw RemoteNodeError.invalidResponse - } - - // Check for direct route - guard let contact = try await dataStore.fetchContact(radioID: remoteSession.radioID, publicKey: remoteSession.publicKey) else { - throw RemoteNodeError.contactNotFound - } - - if contact.isFloodRouted { - throw RemoteNodeError.floodRouted - } - - // Request status (which triggers sync) - do { - let contactType: ContactType = remoteSession.isRoom ? .room : .repeater - _ = try await session.requestStatus(from: remoteSession.publicKey, type: contactType) - } catch let error as MeshCoreError { - throw RemoteNodeError.sessionError(error) - } - - logger.info("Requested history sync for room \(remoteSession.name)") - } - - // MARK: - Logout - - /// Explicitly logout from a remote node. - func logout(sessionID: UUID) async throws { - guard let remoteSession = try await dataStore.fetchRemoteNodeSession(id: sessionID) else { - throw RemoteNodeError.sessionNotFound - } - - // Log logout - let targetType: CommandAuditLogger.Target = remoteSession.isRoom ? .room : .repeater - await auditLogger.logLogout(target: targetType, publicKey: remoteSession.publicKey) - - stopKeepAlive(sessionID: sessionID) - - do { - try await session.sendLogout(to: remoteSession.publicKey) - } catch { - // Ignore errors - we're disconnecting anyway - logger.info("Logout send failed (ignoring): \(error)") - } - - try await dataStore.updateRemoteNodeSessionConnection( - id: sessionID, - isConnected: false, - permissionLevel: .guest - ) - - // Notify UI of session state change - eventBroadcaster.yield(.sessionStateChanged(sessionID: sessionID, isConnected: false)) - } } diff --git a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+PathRecovery.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+PathRecovery.swift index 89a9eee651..7b30824b3f 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+PathRecovery.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+PathRecovery.swift @@ -4,10 +4,8 @@ import MeshCore extension RemoteNodeService { // MARK: - Direct-path flood recovery - /// CLI path recovery: run `operation`, and on a direct-path mesh timeout reset - /// the contact path to flood and run once more. Already-flood contacts skip - /// reset. A failed reset rethrows the original timeout. Binary admin waits use - /// `performBinaryExchange` instead. + /// On a direct-path mesh timeout, reset to flood and retry once when path fallback is on. + /// A failed reset rethrows the original timeout. Binary admin waits use `performBinaryExchange`. func performWithDirectPathFloodRecovery( radioID: UUID, publicKey: Data, @@ -17,7 +15,8 @@ extension RemoteNodeService { do { return try await operation() } catch { - guard Self.isMeshTimeout(error), await isDirectRouted(radioID: radioID, publicKey: publicKey) else { + guard Self.isMeshTimeout(error), await isDirectRouted(radioID: radioID, publicKey: publicKey), + RemoteFloodFallback.isEnabled(defaults: defaults) else { throw error } diff --git a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Reconnection.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Reconnection.swift index 0383227c55..f09e8acb2b 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Reconnection.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Reconnection.swift @@ -1,24 +1,24 @@ import Foundation public extension RemoteNodeService { - // MARK: - BLE Disconnection + // MARK: - Link Disconnection - /// Called when BLE connection is lost. - /// Marks all connected sessions as disconnected, stops keep-alive timers, - /// and broadcasts `RemoteNodeEvent.sessionStateChanged` for each. - /// Returns the set of session IDs that were connected, for re-auth on reconnect. - func handleBLEDisconnection() async -> Set { + /// Stops remote work and publishes disconnected sessions, returning their IDs + /// so only previously connected sessions are re-authenticated after link recovery. + func handleLinkDisconnection(radioID: UUID) async -> Set { + beginRetirement() + await stopEventMonitoring() let connectedSessions: [RemoteNodeSessionDTO] do { - connectedSessions = try await dataStore.fetchConnectedRemoteNodeSessions() + connectedSessions = try await dataStore.fetchRemoteNodeSessions(radioID: radioID).filter(\.isConnected) } catch { - logger.error("Failed to fetch connected sessions for BLE disconnection: \(error)") + logger.error("Failed to fetch connected sessions for Link disconnection: \(error)") return [] } guard !connectedSessions.isEmpty else { return [] } - logger.info("BLE disconnection: marking \(connectedSessions.count) session(s) disconnected") + logger.info("Link disconnection: marking \(connectedSessions.count) session(s) disconnected") var sessionIDs: Set = [] for session in connectedSessions { @@ -35,25 +35,24 @@ public extension RemoteNodeService { return sessionIDs } - // MARK: - BLE Reconnection + // MARK: - Link Reconnection - /// Called when BLE connection is re-established. - /// Re-authenticates sessions that were connected before BLE loss. - /// - Parameter sessionIDs: Session IDs from `handleBLEDisconnection()`. - /// If empty (e.g., after app restart), no sessions are re-authenticated; - /// the user can manually reconnect. - func handleBLEReconnection(sessionIDs: Set) async { + /// Re-authenticates the sessions captured before link loss. + /// An empty set leaves reconnection to the user. + func handleLinkReconnection(radioID: UUID, sessionIDs: Set) async { guard !isReauthenticating else { logger.info("Skipping re-auth: already in progress") return } - guard !sessionIDs.isEmpty else { return } + guard !sessionIDs.isEmpty, !isRetired else { return } + isReauthenticating = true + defer { isReauthenticating = false } // Fetch current session state for each ID var sessionsToReauth: [RemoteNodeSessionDTO] = [] for id in sessionIDs { - if let session = try? await dataStore.fetchRemoteNodeSession(id: id) { + if let session = try? await dataStore.fetchRemoteNodeSession(id: id), session.radioID == radioID { sessionsToReauth.append(session) } else { logger.warning("Session \(id) not found for re-auth, skipping") @@ -62,35 +61,24 @@ public extension RemoteNodeService { guard !sessionsToReauth.isEmpty else { return } - logger.info("BLE reconnection: re-authenticating \(sessionsToReauth.count) session(s)") - isReauthenticating = true - defer { isReauthenticating = false } - - await withTaskGroup(of: Void.self) { group in - for remoteSession in sessionsToReauth { - group.addTask { [self] in - let previousPermission = remoteSession.permissionLevel - do { - let result = try await login(sessionID: remoteSession.id) - let newPermission = result.permissionLevel - if newPermission < previousPermission { - logger.warning( - "Re-auth returned degraded permission for session \(remoteSession.id): " - + "\(previousPermission) -> \(newPermission), marking disconnected" - ) - try? await dataStore.markSessionDisconnected(remoteSession.id) - eventBroadcaster.yield(.sessionStateChanged(sessionID: remoteSession.id, isConnected: false)) - } - } catch { - logger.warning("Re-auth failed for session \(remoteSession.id): \(error)") - do { - try await dataStore.markSessionDisconnected(remoteSession.id) - } catch { - logger.error("Failed to persist disconnected state for session \(remoteSession.id): \(error)") - } - eventBroadcaster.yield(.sessionStateChanged(sessionID: remoteSession.id, isConnected: false)) - } + logger.info("Link reconnection: re-authenticating \(sessionsToReauth.count) session(s)") + for remoteSession in sessionsToReauth { + guard !Task.isCancelled, !isRetired else { return } + let previousPermission = remoteSession.permissionLevel + do { + let result = try await login(sessionID: remoteSession.id) + guard !Task.isCancelled, !isRetired else { return } + let permission = result.permissionLevel(for: remoteSession.role) + if permission < previousPermission { + await disconnect(sessionID: remoteSession.id) } + } catch RemoteNodeError.cancelled { + // A newer login for this node can supersede background re-authentication. + continue + } catch { + guard !Task.isCancelled, !isRetired else { return } + await disconnect(sessionID: remoteSession.id) + logger.warning("Re-auth failed for session \(remoteSession.id): \(error)") } } } diff --git a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+RoomKeepAlive.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+RoomKeepAlive.swift new file mode 100644 index 0000000000..ad1d0f2892 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+RoomKeepAlive.swift @@ -0,0 +1,121 @@ +import Foundation +import MeshCore + +extension RemoteNodeService { + func sendScheduledKeepAlive(sessionID: UUID, publicKey: Data) async throws { + try Task.checkCancellation() + guard let room = try await dataStore.fetchRemoteNodeSession(id: sessionID), + room.publicKey == publicKey, + room.isRoom, + radioID == nil || radioID == room.radioID else { + throw RemoteNodeError.sessionNotFound + } + guard let scope = try await dataStore.captureReceiveScope(radioID: room.radioID, link: receiveLifetime) else { + throw CancellationError() + } + + let key = room.textRulesID ?? room.id + let needsRecovery: Bool + if roomKeepAliveSchedules[key]?.recoverySubmitted.withLock({ $0 }) == true { + needsRecovery = false + } else { + let preference = await textRulesPreference() + let rulesAreOn = preference?.effective( + for: .room, + key: .init(radioID: room.radioID, conversationID: key), + override: room.textRulesOverride + ).isOn == true + if rulesAreOn { + needsRecovery = true + } else { + needsRecovery = await (try? dataStore.hasRecentlyBlockedMessages(radioID: room.radioID, conversationID: key)) == true + } + } + + try Task.checkCancellation() + let schedule = keepAliveSchedule(for: room) + if let recovery = schedule.recovery { + try await recovery.value + return + } + if schedule.refresh != nil { return } + let recoverySubmitted = schedule.recoverySubmitted.withLock { $0 } + if recoverySubmitted || !needsRecovery { + try await transmitRoomKeepAlive(room, scope: scope, schedule: schedule, useBookmark: !recoverySubmitted) + return + } + + let recovery = Task { + defer { roomKeepAliveSchedules[key]?.recovery = nil } + try await transmitRoomKeepAlive(room, scope: scope, schedule: schedule, useBookmark: true, markRecovery: true) + } + roomKeepAliveSchedules[key]?.recovery = recovery + try await recovery.value + } + + func refreshRoom(_ room: RemoteNodeSessionDTO) async throws { + guard room.isRoom else { throw RemoteNodeError.invalidResponse } + guard radioID == nil || radioID == room.radioID else { throw RemoteNodeError.notConnected } + guard let scope = try await dataStore.captureReceiveScope(radioID: room.radioID, link: receiveLifetime) else { + throw CancellationError() + } + + let key = room.textRulesID ?? room.id + let schedule = keepAliveSchedule(for: room) + if let refresh = schedule.refresh { + try await refresh.value + return + } + + let refresh = Task { + defer { roomKeepAliveSchedules[key]?.refresh = nil } + // A distinct refresh reads the bookmark after an in-flight automatic rewind. + _ = await schedule.recovery?.result + try await transmitRoomKeepAlive(room, scope: scope, schedule: schedule, useBookmark: true) + } + roomKeepAliveSchedules[key]?.refresh = refresh + try await refresh.value + } + + private func keepAliveSchedule(for room: RemoteNodeSessionDTO) -> RoomKeepAliveSchedule { + let key = room.textRulesID ?? room.id + let schedule = roomKeepAliveSchedules[key] ?? RoomKeepAliveSchedule(sessionID: room.id) + roomKeepAliveSchedules[key] = schedule + return schedule + } + + private func transmitRoomKeepAlive( + _ room: RemoteNodeSessionDTO, + scope: ReceiveScope, + schedule: RoomKeepAliveSchedule, + useBookmark: Bool, + markRecovery: Bool = false + ) async throws { + await auditLogger.logKeepAlive(target: .room, publicKey: room.publicKey) + do { + _ = try await session.sendKeepAlive(to: room.publicKey, syncSince: { [dataStore] in + guard scope.isCurrent, schedule.lifetime.isCurrent else { throw CancellationError() } + guard let contact = try await dataStore.fetchContact(radioID: room.radioID, publicKey: room.publicKey) else { + throw RemoteNodeError.contactNotFound + } + guard !contact.isFloodRouted else { throw RemoteNodeError.floodRouted } + guard let current = try await dataStore.fetchRemoteNodeSession(id: room.id), + current.radioID == room.radioID, + current.textRulesID == room.textRulesID else { + throw RemoteNodeError.sessionNotFound + } + return useBookmark ? current.lastSyncTimestamp : 0 + }, beforeSend: { + guard scope.isCurrent, schedule.lifetime.isCurrent else { throw CancellationError() } + if markRecovery { + schedule.recoverySubmitted.withLock { $0 = true } + } + }) + } catch let error as MeshCoreError { + if markRecovery, error.deviceErrorCode == .tableFull { + schedule.recoverySubmitted.withLock { $0 = false } + } + throw RemoteNodeError.sessionError(error) + } + } +} diff --git a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Sensor.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Sensor.swift new file mode 100644 index 0000000000..a9050765fc --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Sensor.swift @@ -0,0 +1,121 @@ +import Foundation +import MeshCore + +public extension RemoteNodeService { + private static let sensorListCommand = "sensor list" + private static let sensorGetPrefix = "sensor get " + private static let sensorRebootCommand = "reboot" + + func connectSensor( + radioID: UUID, + contact: ContactDTO, + password: String?, + rememberPassword: Bool, + requireAdmin: Bool, + pathLength: UInt8, + onTimeoutKnown: (@Sendable (Int) async -> Void)? + ) async throws -> RemoteNodeSessionDTO { + guard contact.type == .sensor, radioID == contact.radioID else { throw RemoteNodeError.invalidResponse } + try Task.checkCancellation() + let attemptID = UUID() + sensorConnectAttempts[contact.id] = attemptID + defer { + if sensorConnectAttempts[contact.id] == attemptID { sensorConnectAttempts[contact.id] = nil } + } + let created = try await createSession(radioID: radioID, contact: contact, sensorAttemptID: attemptID) + do { + guard sensorConnectAttempts[contact.id] == attemptID, !isRetired else { throw RemoteNodeError.cancelled } + let result = try await login( + sessionID: created.id, password: password, pathLength: pathLength, onTimeoutKnown: onTimeoutKnown + ) + try Task.checkCancellation() + guard sensorConnectAttempts[contact.id] == attemptID, !isRetired else { throw RemoteNodeError.cancelled } + guard !requireAdmin || result.isAdmin else { throw RemoteNodeError.permissionDenied } + guard let updated = try await dataStore.fetchRemoteNodeSession(id: created.id), + updated.isSensor, updated.isConnected else { throw RemoteNodeError.notConnected } + try Task.checkCancellation() + guard sensorConnectAttempts[contact.id] == attemptID, !isRetired else { throw RemoteNodeError.cancelled } + if rememberPassword, let password { + try await keychainService.storePassword(password, forNodeKey: contact.publicKey) + } else if !rememberPassword { + try await keychainService.deletePassword(forNodeKey: contact.publicKey) + } + try Task.checkCancellation() + guard sensorConnectAttempts[contact.id] == attemptID, !isRetired else { throw RemoteNodeError.cancelled } + return updated + } catch { + // Only this attempt may retire its session; an older cancellation cannot disconnect a newer login. + if sensorConnectAttempts[contact.id] == attemptID { await disconnect(sessionID: created.id) } + throw error + } + } + + func fetchSensorSettings(sessionID: UUID) async throws -> [SensorSetting] { + _ = try await requireSensorAdmin(sessionID: sessionID) + var settings: [SensorSetting] = [] + var keys: Set = [] + var expectedTotal: Int? + var offset = 0 + while true { + try Task.checkCancellation() + let command = offset == 0 ? Self.sensorListCommand : "\(Self.sensorListCommand) \(offset)" + let response = try await sendRawCLICommand(sessionID: sessionID, command: command) + let page = try SensorSettingsResponseParser.list(response, offset: offset) + guard expectedTotal == nil || expectedTotal == page.total else { throw RemoteNodeError.invalidResponse } + expectedTotal = page.total + for setting in page.settings { + guard keys.insert(setting.key).inserted else { throw RemoteNodeError.invalidResponse } + settings.append(setting) + } + guard let next = page.next else { return settings } + offset = next + } + } + + func setSensorSetting(sessionID: UUID, setting: SensorSetting, value: String) async throws -> SensorSetting { + let command = try setting.command(setting: value) + _ = try await requireSensorAdmin(sessionID: sessionID) + let response: String + do { + response = try await sendRawCLICommand(sessionID: sessionID, command: command) + } catch RemoteNodeError.timeout { + throw RemoteNodeError.sensorOutcomeUnknown + } catch RemoteNodeError.sessionError { + throw RemoteNodeError.sensorOutcomeUnknown + } + do { + try SensorSettingsResponseParser.accepted(response) + } catch RemoteNodeError.sensorSettingRejected { + throw RemoteNodeError.sensorSettingRejected + } catch { + throw RemoteNodeError.sensorOutcomeUnknown + } + do { + let verified = try await sendRawCLICommand(sessionID: sessionID, command: Self.sensorGetPrefix + setting.key) + guard try SensorSettingsResponseParser.value(verified) == value else { throw RemoteNodeError.sensorOutcomeUnknown } + return SensorSetting(key: setting.key, value: value) + } catch is CancellationError { + throw CancellationError() + } catch { + throw RemoteNodeError.sensorOutcomeUnknown + } + } + + func rebootSensor(sessionID: UUID) async throws { + _ = try await sendRawCLICommand(sessionID: sessionID, command: Self.sensorRebootCommand) + } +} + +extension RemoteNodeService { + func requireSensorAdmin(sessionID: UUID) async throws -> RemoteNodeSessionDTO { + try Task.checkCancellation() + guard !isRetired else { throw RemoteNodeError.notConnected } + guard let current = try await dataStore.fetchRemoteNodeSession(id: sessionID), current.isSensor else { + throw RemoteNodeError.sessionNotFound + } + try Task.checkCancellation() + guard current.isConnected else { throw RemoteNodeError.notConnected } + guard current.isAdmin else { throw RemoteNodeError.permissionDenied } + return current + } +} diff --git a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+SessionManagement.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+SessionManagement.swift new file mode 100644 index 0000000000..518ea27d0a --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+SessionManagement.swift @@ -0,0 +1,186 @@ +import Foundation +import MeshCore + +public extension RemoteNodeService { + // MARK: - Keep-Alive (Room Servers) + + /// Start periodic keep-alive for a room server session. + /// Sends an immediate keep-alive on start (for connectivity check + sync_since update), + /// then continues at the configured interval. Transient failures are retried up to + /// `KeepAliveRetryPolicy.maxConsecutiveFailures` times before disconnecting. + private func startKeepAlive(sessionID: UUID, publicKey: Data) { + guard !isRetired else { return } + stopKeepAlive(sessionID: sessionID) + + let interval = keepAliveIntervals[sessionID] ?? Self.defaultKeepAliveInterval + + // The actor retains this task via keepAliveTasks, so the loop captures + // self weakly and rebinds per tick; a strong capture would keep the + // actor (and its session/dataStore) alive for the app lifetime. + let task = Task { [weak self] in + var consecutiveFailures = 0 + + while !Task.isCancelled { + guard let tick = await self?.performKeepAliveTick( + sessionID: sessionID, + publicKey: publicKey, + consecutiveFailures: consecutiveFailures + ), tick.shouldContinue else { return } + consecutiveFailures = tick.consecutiveFailures + + try? await Task.sleep(for: interval) + } + } + + keepAliveTasks[sessionID] = task + } + + /// Runs one keep-alive attempt for the loop in `startKeepAlive`. + /// Returns whether the loop should continue and the updated failure count. + private func performKeepAliveTick( + sessionID: UUID, + publicKey: Data, + consecutiveFailures: Int + ) async -> (shouldContinue: Bool, consecutiveFailures: Int) { + var failures = consecutiveFailures + do { + try await sendScheduledKeepAlive(sessionID: sessionID, publicKey: publicKey) + KeepAliveRetryPolicy.recordSuccess(consecutiveFailures: &failures) + return (shouldContinue: true, consecutiveFailures: failures) + } catch { + let action = KeepAliveRetryPolicy.evaluate(error: error, consecutiveFailures: &failures) + switch action { + case .stop: + break + case .skip: + logger.info("Skipping keep-alive for flood-routed session \(sessionID)") + case .retryNextInterval: + let reason = KeepAliveRetryPolicy.failureReason(for: error) + logger.warning("Keep-alive \(failures)/\(KeepAliveRetryPolicy.maxConsecutiveFailures) failed for \(sessionID): \(reason)") + case .disconnect, .disconnectNow: + let reason = KeepAliveRetryPolicy.failureReason(for: error) + logger.warning("Keep-alive failed for \(sessionID): \(reason)") + do { + try await dataStore.markSessionDisconnected(sessionID) + } catch { + logger.error("Failed to persist disconnected state for session \(sessionID): \(error)") + } + eventBroadcaster.yield(.sessionStateChanged(sessionID: sessionID, isConnected: false)) + } + return (shouldContinue: !action.shouldExitLoop, consecutiveFailures: failures) + } + } + + /// Stop keep-alive for a session + internal func stopKeepAlive(sessionID: UUID) { + guard let worker = keepAliveTasks.removeValue(forKey: sessionID) else { return } + worker.cancel() + retiredKeepAliveTasks.append(worker) + } + + /// Send a manual keep-alive for a directly routed session. + func sendKeepAlive(sessionID: UUID) async throws { + guard let remoteSession = try await dataStore.fetchRemoteNodeSession(id: sessionID) else { + throw RemoteNodeError.sessionNotFound + } + + guard !remoteSession.isSensor else { throw RemoteNodeError.invalidResponse } + if remoteSession.isRoom { + try await refreshRoom(remoteSession) + return + } + + let publicKey = remoteSession.publicKey + guard let contact = try await dataStore.fetchContact(radioID: remoteSession.radioID, publicKey: publicKey) else { + throw RemoteNodeError.contactNotFound + } + + guard !contact.isFloodRouted else { throw RemoteNodeError.floodRouted } + + await auditLogger.logKeepAlive(target: .repeater, publicKey: publicKey) + + do { + _ = try await session.sendKeepAlive(to: publicKey, syncSince: remoteSession.lastSyncTimestamp) + } catch let error as MeshCoreError { + throw RemoteNodeError.sessionError(error) + } + } + + /// Start keep-alive for a room session (called when room view appears). + func startSessionKeepAlive(sessionID: UUID, publicKey: Data) { + startKeepAlive(sessionID: sessionID, publicKey: publicKey) + } + + /// Stop keep-alive for a room session (called when room view disappears). + func stopSessionKeepAlive(sessionID: UUID) { + stopKeepAlive(sessionID: sessionID) + } + + // MARK: - History Sync + + /// Request message history from a room server. + func requestHistorySync(sessionID: UUID) async throws { + guard let remoteSession = try await dataStore.fetchRemoteNodeSession(id: sessionID) else { + throw RemoteNodeError.sessionNotFound + } + + guard remoteSession.isRoom else { + throw RemoteNodeError.invalidResponse + } + + // Check for direct route + guard let contact = try await dataStore.fetchContact(radioID: remoteSession.radioID, publicKey: remoteSession.publicKey) else { + throw RemoteNodeError.contactNotFound + } + + if contact.isFloodRouted { + throw RemoteNodeError.floodRouted + } + + // Request status (which triggers sync) + do { + let contactType: ContactType = .room + _ = try await session.requestStatus(from: remoteSession.publicKey, type: contactType) + } catch let error as MeshCoreError { + throw RemoteNodeError.sessionError(error) + } + + logger.info("Requested history sync for room \(remoteSession.name)") + } + + // MARK: - Logout + + /// Explicitly logout from a remote node. + func logout(sessionID: UUID) async throws { + guard let remoteSession = try await dataStore.fetchRemoteNodeSession(id: sessionID) else { + throw RemoteNodeError.sessionNotFound + } + + if remoteSession.isSensor { + await disconnect(sessionID: sessionID) + return + } + + // Log logout + let targetType: CommandAuditLogger.Target = CommandAuditLogger.target(for: remoteSession.role) + await auditLogger.logLogout(target: targetType, publicKey: remoteSession.publicKey) + + stopKeepAlive(sessionID: sessionID) + + do { + try await session.sendLogout(to: remoteSession.publicKey) + } catch { + // Ignore errors - we're disconnecting anyway + logger.info("Logout send failed (ignoring): \(error)") + } + + try await dataStore.updateRemoteNodeSessionConnection( + id: sessionID, + isConnected: false, + permissionLevel: .guest + ) + + // Notify UI of session state change + eventBroadcaster.yield(.sessionStateChanged(sessionID: sessionID, isConnected: false)) + } +} diff --git a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Telemetry.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Telemetry.swift index 566e4f6b6e..3bc91ace86 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Telemetry.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Telemetry.swift @@ -10,7 +10,9 @@ public extension RemoteNodeService { throw RemoteNodeError.sessionNotFound } - let targetType: CommandAuditLogger.Target = remoteSession.isRoom ? .room : .repeater + guard !remoteSession.isSensor else { throw RemoteNodeError.invalidResponse } + + let targetType = CommandAuditLogger.target(for: remoteSession.role) await auditLogger.logStatusRequest(target: targetType, publicKey: remoteSession.publicKey) do { @@ -40,7 +42,7 @@ public extension RemoteNodeService { throw RemoteNodeError.sessionNotFound } - let targetType: CommandAuditLogger.Target = remoteSession.isRoom ? .room : .repeater + let targetType = CommandAuditLogger.target(for: remoteSession.role) await auditLogger.logTelemetryRequest(target: targetType, publicKey: remoteSession.publicKey) do { @@ -66,6 +68,8 @@ public extension RemoteNodeService { throw RemoteNodeError.sessionNotFound } + guard !remoteSession.isSensor else { throw RemoteNodeError.invalidResponse } + do { let effectiveTimeout = timeout ?? RemoteOperationTimeoutPolicy.binaryMaximum return try await withTimeout(effectiveTimeout, operationName: "remoteOwnerInfo") { diff --git a/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift index f81a1ece55..e62d3598eb 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift @@ -12,7 +12,7 @@ private let cliResponseTextType: UInt8 = 0x01 // MARK: - Remote Node Service /// Shared service for remote node operations. -/// Handles login, keep-alive, status, telemetry, and CLI for both room servers and repeaters. +/// Handles authentication and commands for sensors, repeaters, and room servers. public actor RemoteNodeService { // MARK: - Properties @@ -20,67 +20,47 @@ public actor RemoteNodeService { let dataStore: any PersistenceStoreProtocol let keychainService: KeychainService let contactRadioOwner: ContactRadioOwner + let textRulesPreference: @Sendable () async -> TextRulesPreference? + let receiveLifetime: ReceiveScope.Lifetime + let radioID: UUID? + let defaults: UserDefaults let logger = PersistentLogger(subsystem: "com.mc1", category: "RemoteNode") let auditLogger = CommandAuditLogger() - struct PendingLogin { - /// Session that called `login`, so a prefix match cannot update another radio's row. - let sessionID: UUID - let continuation: CheckedContinuation - } - - /// Pending login continuations keyed by 6-byte public key prefix. - /// Using 6-byte prefix matches MeshCore protocol format for login results. - var pendingLogins: [Data: PendingLogin] = [:] - - /// Timeout tasks for pending logins, keyed by 6-byte public key prefix. - /// Cancelled when login succeeds/fails before timeout. - var pendingLoginTimeoutTasks: [Data: Task] = [:] - - /// The in-flight CLI request for a node. `acceptsAnyResponse` marks raw - /// passthrough commands whose reply shape can't be validated. `wirePrefix` - /// is the correlation token prepended to the command on the wire; firmware - /// reflects it back at the start of the reply. - struct PendingCLIRequest { - let id: UUID - let command: String - let wirePrefix: String - let acceptsAnyResponse: Bool - let continuation: CheckedContinuation - var workerTask: Task? - } + var isRetired = false + /// Login ownership keyed by the public key prefix carried in login responses. + var loginAttempts: [Data: RemoteLoginAttempt] = [:] + var sensorConnectAttempts: [UUID: UUID] = [:] - /// The single in-flight CLI request per node, keyed by 6-byte public key - /// prefix. Replies echoing the request's wire prefix are attributed - /// deterministically; unprefixed replies (firmware that predates the echo) - /// fall back to single-flight shape validation, and foreign-prefixed - /// replies are stale by definition and dropped. - var pendingCLIRequests: [Data: PendingCLIRequest] = [:] + /// CLI slot ownership and FIFO admission keyed by the response's public key prefix. + var cliSlots: [Data: RemoteCLISlot] = [:] + static let cliPublicKeyPrefixLength = 6 /// Cycling counter for CLI wire prefixes ("00|" through "FF|"). var cliPrefixCounter: UInt8 = 0 - /// A task queued for a node's CLI slot while another command is in flight. - struct CLISlotWaiter { - let id: UUID - let continuation: CheckedContinuation - } - - /// Nodes whose CLI slot is held by an in-flight command. - var cliSlotBusy: Set = [] - - /// FIFO waiters for a node's CLI slot, keyed by 6-byte public key prefix. - var cliSlotWaiters: [Data: [CLISlotWaiter]] = [:] - /// Keep-alive timer tasks var keepAliveTasks: [UUID: Task] = [:] + var retiredKeepAliveTasks: [Task] = [] + private var retirementTask: Task? + + /// Recovery and refresh outlive timer restarts on this Link record. + struct RoomKeepAliveSchedule { + let sessionID: UUID + let lifetime = ReceiveScope.Lifetime() + let recoverySubmitted = OSAllocatedUnfairLock(initialState: false) + var recovery: Task? + var refresh: Task? + } + + var roomKeepAliveSchedules: [UUID: RoomKeepAliveSchedule] = [:] /// Keep-alive intervals per session (from login response, in seconds) /// Default to 90 seconds if not specified var keepAliveIntervals: [UUID: Duration] = [:] static let defaultKeepAliveInterval: Duration = .seconds(90) - /// Reentrancy guard for BLE reconnection handling + /// Reentrancy guard for Link reconnection handling var isReauthenticating = false /// Event monitoring task @@ -128,12 +108,20 @@ public actor RemoteNodeService { session: any RemoteAccessSessionOps & SessionEventStreaming & ContactSessionOps, dataStore: any PersistenceStoreProtocol, keychainService: KeychainService, - contactRadioOwner: ContactRadioOwner = ContactRadioOwner() + contactRadioOwner: ContactRadioOwner = ContactRadioOwner(), + textRulesPreference: @escaping @Sendable () async -> TextRulesPreference? = { nil }, + receiveLifetime: ReceiveScope.Lifetime = .init(), + radioID: UUID? = nil, + defaults: UserDefaults = .standard ) { self.session = session self.dataStore = dataStore self.keychainService = keychainService self.contactRadioOwner = contactRadioOwner + self.textRulesPreference = textRulesPreference + self.receiveLifetime = receiveLifetime + self.radioID = radioID + self.defaults = defaults } deinit { @@ -147,6 +135,7 @@ public actor RemoteNodeService { /// Start monitoring MeshCore events for login results public func startEventMonitoring() { + guard !isRetired else { return } eventMonitorTask?.cancel() eventMonitorTask = Task { [weak self] in @@ -173,9 +162,11 @@ public actor RemoteNodeService { } /// Stop monitoring events - public func stopEventMonitoring() { - eventMonitorTask?.cancel() + public func stopEventMonitoring() async { + let worker = eventMonitorTask eventMonitorTask = nil + worker?.cancel() + await worker?.value } /// Handle incoming MeshCore event @@ -214,43 +205,6 @@ public actor RemoteNodeService { } } - /// Handle CLI response from a contact message. The wire prefix echoed by - /// firmware attributes a reply deterministically; an unprefixed reply falls - /// back to single-flight shape validation for older firmware, and a reply - /// echoing a different prefix belongs to an earlier command and is dropped. - private func handleCLIResponse(_ message: ContactMessage) { - let prefix = Data(message.senderPublicKeyPrefix.prefix(6)) - - guard let pending = pendingCLIRequests[prefix] else { - logger.debug("Unmatched CLI response (no pending request), length \(message.text.count)") - return - } - - let responseText: String - if let echoed = CLIResponse.splitEchoedPrefix(message.text) { - guard echoed.prefix == pending.wirePrefix else { - logger.warning( - "Dropping stale CLI response with prefix \(echoed.prefix) while awaiting \(pending.wirePrefix)" - ) - return - } - responseText = echoed.body - } else { - // Firmware without prefix echo: fall back to shape validation. - guard pending.acceptsAnyResponse - || CLIResponse.isPlausibleResponse(message.text, forQuery: pending.command) else { - logger.warning( - "Dropping CLI response that doesn't match pending command, length \(message.text.count)" - ) - return - } - responseText = message.text - } - - _ = takePendingCLIRequest(for: prefix, requestID: pending.id) - pending.continuation.resume(returning: responseText) - } - /// Returns the next cycling CLI wire prefix ("00|" through "FF|"). func makeCLIWirePrefix() -> String { defer { cliPrefixCounter &+= 1 } @@ -262,16 +216,11 @@ public actor RemoteNodeService { return TimeInterval(seconds) + TimeInterval(attoseconds) / 1e18 } - func cancelPendingLogin(for prefix: Data) { - pendingLoginTimeoutTasks.removeValue(forKey: prefix)?.cancel() - if let pending = pendingLogins.removeValue(forKey: prefix) { - pending.continuation.resume(throwing: RemoteNodeError.cancelled) - } - } - - func cancelPendingCLIRequest(for prefix: Data, requestID: UUID) { - guard let cancelled = takePendingCLIRequest(for: prefix, requestID: requestID) else { return } - cancelled.continuation.resume(throwing: CancellationError()) + func cancelPendingLogin(for prefix: Data, attemptID: UUID? = nil) { + if let attemptID, loginAttempts[prefix]?.id != attemptID { return } + guard var attempt = loginAttempts.removeValue(forKey: prefix) else { return } + // A claimed result owns its continuation until persistence settles; removal only revokes its authority. + attempt.claimCompletion()?.continuation.resume(throwing: RemoteNodeError.cancelled) } // MARK: - Session Management @@ -281,6 +230,15 @@ public actor RemoteNodeService { radioID: UUID, contact: ContactDTO ) async throws -> RemoteNodeSessionDTO { + try await createSession(radioID: radioID, contact: contact, sensorAttemptID: nil) + } + + func createSession( + radioID: UUID, + contact: ContactDTO, + sensorAttemptID: UUID? + ) async throws -> RemoteNodeSessionDTO { + try validateSessionCreation(contactID: contact.id, sensorAttemptID: sensorAttemptID) guard let role = RemoteNodeRole(contactType: contact.type) else { throw RemoteNodeError.invalidResponse } @@ -295,6 +253,7 @@ public actor RemoteNodeService { await hold() } #endif + try validateSessionCreation(contactID: contact.id, sensorAttemptID: sensorAttemptID) let saved = try await dataStore.reuseOrCreateRemoteNodeSession( RoomSessionPresentation( radioID: radioID, @@ -305,15 +264,28 @@ public actor RemoteNodeService { longitude: contact.longitude ) ) + try validateSessionCreation(contactID: contact.id, sensorAttemptID: sensorAttemptID) logger.info("createSession: saved session \(saved.id) for \(pubKeyHex), isConnected=\(saved.isConnected)") return saved } + private func validateSessionCreation(contactID: UUID, sensorAttemptID: UUID?) throws { + try Task.checkCancellation() + guard !isRetired else { throw RemoteNodeError.notConnected } + if let sensorAttemptID, sensorConnectAttempts[contactID] != sensorAttemptID { throw RemoteNodeError.cancelled } + } + /// Remove a session and its associated data public func removeSession(id: UUID, publicKey: Data) async throws { stopKeepAlive(sessionID: id) try await keychainService.deletePassword(forNodeKey: publicKey) try await dataStore.deleteRemoteNodeSession(id: id) + for (key, schedule) in roomKeepAliveSchedules where schedule.sessionID == id { + schedule.lifetime.retire() + schedule.recovery?.cancel() + schedule.refresh?.cancel() + roomKeepAliveSchedules.removeValue(forKey: key) + } } /// Check if a password is stored for a contact's public key. @@ -358,18 +330,48 @@ public actor RemoteNodeService { public func stopAllKeepAlives() { for task in keepAliveTasks.values { task.cancel() + retiredKeepAliveTasks.append(task) } keepAliveTasks.removeAll() - // Resume parked logins before dropping their timeout tasks; otherwise the - // continuation that would have resumed them is gone and the caller hangs. - for prefix in Array(pendingLogins.keys) { + for prefix in Array(loginAttempts.keys) { cancelPendingLogin(for: prefix) } } + func beginRetirement() { + guard !isRetired else { return } + isRetired = true + sensorConnectAttempts.removeAll() + stopAllKeepAlives() + let slots = cliSlots.values + cliSlots.removeAll() + for var slot in slots { + slot.cancelAll() + } + } + + func retire() async { + if let retirementTask { + await retirementTask.value + return + } + + beginRetirement() + let workers = retiredKeepAliveTasks + retiredKeepAliveTasks.removeAll() + let drain = Task { + await stopEventMonitoring() + for worker in workers { + await worker.value + } + } + retirementTask = drain + await drain.value + } + /// Number of login continuations currently parked. Exposed for teardown tests. var pendingLoginCount: Int { - pendingLogins.count + loginAttempts.values.count(where: \.isAwaitingResult) } } diff --git a/MC1Services/Sources/MC1Services/Services/RoomServerService.swift b/MC1Services/Sources/MC1Services/Services/RoomServerService.swift index 2e4a9fbd1a..b67569365f 100644 --- a/MC1Services/Sources/MC1Services/Services/RoomServerService.swift +++ b/MC1Services/Sources/MC1Services/Services/RoomServerService.swift @@ -35,8 +35,10 @@ public actor RoomServerService { private let session: any RemoteAccessSessionOps private let remoteNodeService: RemoteNodeService - private let dataStore: any PersistenceStoreProtocol + private let dataStore: PersistenceStore + private let textRulesPreference: @Sendable () async -> TextRulesPreference? private let radioID: UUID + private let receiveLifetime: ReceiveScope.Lifetime private let logger = PersistentLogger(subsystem: "com.mc1", category: "RoomServer") private let auditLogger = CommandAuditLogger() @@ -44,8 +46,10 @@ public actor RoomServerService { /// Set from SelfInfo when device connects. private var selfPublicKeyPrefix: Data? - /// Configuration for retry behavior (shared with MessageService) - private let config: MessageServiceConfig + private static let initialSendAttempts = 4 + private static let fallbackSendAttempts = 1 + private static let totalSendAttempts = initialSendAttempts + fallbackSendAttempts + private let plainTextSendGate: PlainTextSendGate? /// Multicast broadcaster for status-update and connection-recovery events. private nonisolated let eventBroadcaster = EventBroadcaster() @@ -53,20 +57,27 @@ public actor RoomServerService { /// Tracks message IDs currently being retried to prevent concurrent retry attempts private var inFlightRetries: Set = [] + private static let wireTimestampStep: TimeInterval = 1 + private var lastWireTimestampByRoom: [Data: TimeInterval] = [:] + // MARK: - Initialization init( session: any RemoteAccessSessionOps, remoteNodeService: RemoteNodeService, - dataStore: any PersistenceStoreProtocol, + dataStore: PersistenceStore, radioID: UUID, - config: MessageServiceConfig = MessageServiceConfig() + plainTextSendGate: PlainTextSendGate? = nil, + textRulesPreference: @escaping @Sendable () async -> TextRulesPreference? = { nil }, + receiveLifetime: ReceiveScope.Lifetime = .init() ) { self.session = session self.remoteNodeService = remoteNodeService self.dataStore = dataStore self.radioID = radioID - self.config = config + self.plainTextSendGate = plainTextSendGate + self.textRulesPreference = textRulesPreference + self.receiveLifetime = receiveLifetime } /// Set self public key prefix from SelfInfo. @@ -182,6 +193,12 @@ public actor RoomServerService { try await remoteNodeService.removeSession(id: sessionID, publicKey: publicKey) } + /// Requests a fresh replay from this room's saved bookmark. + public func refreshMessages(for room: RemoteNodeSessionDTO) async throws { + guard room.radioID == radioID else { throw RoomServerError.notConnected } + try await remoteNodeService.refreshRoom(room) + } + // MARK: - Message Posting /// Post a message to a room server. @@ -194,13 +211,7 @@ public actor RoomServerService { /// - text: The message text /// - Returns: The saved message DTO public func postMessage(sessionID: UUID, text: String) async throws -> RoomMessageDTO { - guard let remoteSession = try await dataStore.fetchRemoteNodeSession(id: sessionID) else { - throw RoomServerError.sessionNotFound - } - - guard remoteSession.canPost else { - throw RoomServerError.permissionDenied - } + let remoteSession = try await postableRoomSession(id: sessionID) let timestamp = Date() let messageID = UUID() @@ -215,7 +226,7 @@ public actor RoomServerService { timestamp: UInt32(timestamp.timeIntervalSince1970), isFromSelf: true, status: .pending, - maxRetryAttempts: config.maxAttempts + maxRetryAttempts: Self.totalSendAttempts ) try await dataStore.saveRoomMessage(messageDTO) @@ -227,65 +238,7 @@ public actor RoomServerService { Task { [weak self] in guard let self else { return } - // Send message with retry logic - // NOTE: sendMessageWithRetry requires full 32-byte public key for path reset - do { - let sentInfo = try await session.sendMessageWithRetry( - to: remoteSession.publicKey, // Full 32-byte key required - text: text, - timestamp: timestamp, - maxAttempts: config.maxAttempts, - floodAfter: config.floodAfter, - maxFloodAttempts: config.maxFloodAttempts - ) - - if let sentInfo { - // Success - update to delivered - let ackCodeUInt32 = sentInfo.expectedAck.ackCodeUInt32 - // Handle database errors gracefully - don't lose send success state - do { - try await dataStore.updateRoomMessageStatus( - id: messageID, - status: .delivered, - ackCode: ackCodeUInt32, - roundTripTime: UInt32(sentInfo.suggestedTimeoutMs) - ) - } catch { - logger.error("Failed to update message status after successful send: \(error)") - } - eventBroadcaster.yield(.statusUpdated(messageID: messageID, status: .delivered)) - } else { - // All retries exhausted — radio transmitted but no ACK received. - // Mark as sent (not failed) since the message likely reached the room server. - do { - try await dataStore.updateRoomMessageStatus( - id: messageID, - status: .sent, - ackCode: nil, - roundTripTime: nil - ) - } catch { - logger.error("Failed to update message status to sent: \(error)") - } - eventBroadcaster.yield(.statusUpdated(messageID: messageID, status: .sent)) - } - // Update sort date only (no sync bookmark — avoids clock skew issues) - try? await dataStore.updateRoomActivity(sessionID) - } catch { - // Send failed with error — do not update activity - do { - try await dataStore.updateRoomMessageStatus( - id: messageID, - status: .failed, - ackCode: nil, - roundTripTime: nil - ) - } catch let dbError { - logger.error("Failed to update message status after send error: \(dbError)") - } - eventBroadcaster.yield(.statusUpdated(messageID: messageID, status: .failed)) - logger.warning("Room message send failed: \(error)") - } + await performRoomMessageSend(id: messageID, room: remoteSession) } // Return pending message immediately so UI can display it @@ -313,9 +266,7 @@ public actor RoomServerService { throw RoomServerError.sendFailed("Message is not in failed state") } - guard let remoteSession = try await dataStore.fetchRemoteNodeSession(id: message.sessionID) else { - throw RoomServerError.sessionNotFound - } + let remoteSession = try await postableRoomSession(id: message.sessionID) // Update to pending/retrying let newRetryAttempt = message.retryAttempt + 1 @@ -323,52 +274,43 @@ public actor RoomServerService { id: id, status: .pending, retryAttempt: newRetryAttempt, - maxRetryAttempts: config.maxAttempts + maxRetryAttempts: Self.totalSendAttempts ) eventBroadcaster.yield(.statusUpdated(messageID: id, status: .pending)) - // Retry send with retry logic - // NOTE: sendMessageWithRetry requires full 32-byte public key for path reset + await performRoomMessageSend(id: id, room: remoteSession) + + guard let updatedMessage = try await dataStore.fetchRoomMessage(id: id) else { + throw RoomServerError.sendFailed("Failed to fetch message after retry") + } + return updatedMessage + } + + private func performRoomMessageSend(id: UUID, room: RemoteNodeSessionDTO) async { do { - let sentInfo = try await session.sendMessageWithRetry( - to: remoteSession.publicKey, // Full 32-byte key required - text: message.text, - timestamp: Date(), - maxAttempts: config.maxAttempts, - floodAfter: config.floodAfter, - maxFloodAttempts: config.maxFloodAttempts - ) - - if let sentInfo { - let ackCodeUInt32 = sentInfo.expectedAck.ackCodeUInt32 - do { - try await dataStore.updateRoomMessageStatus( - id: id, - status: .delivered, - ackCode: ackCodeUInt32, - roundTripTime: UInt32(sentInfo.suggestedTimeoutMs) - ) - } catch { - logger.error("Failed to update message status after successful retry: \(error)") + let sendLease = try await plainTextSendGate?.acquire() + defer { + if let sendLease { + await plainTextSendGate?.stopIssuing(sendLease) } - eventBroadcaster.yield(.statusUpdated(messageID: id, status: .delivered)) - } else { - // All retries exhausted — radio transmitted but no ACK received. - // Mark as sent (not failed) since the message likely reached the room server. - do { - try await dataStore.updateRoomMessageStatus( - id: id, - status: .sent, - ackCode: nil, - roundTripTime: nil - ) - } catch { - logger.error("Failed to update message status to sent: \(error)") - } - eventBroadcaster.yield(.statusUpdated(messageID: id, status: .sent)) } - // Update sort date so room moves to top of conversation list - try? await dataStore.updateRoomActivity(message.sessionID) + let sentInfo = try await sendRoomMessage(id: id, roomPublicKey: room.publicKey) + let status: MessageStatus = sentInfo == nil ? .sent : .delivered + + // The radio accepted the post even when every ACK wait expired. + // A status-write failure must not turn that acceptance into a failed send. + do { + try await dataStore.updateRoomMessageStatus( + id: id, + status: status, + ackCode: sentInfo?.expectedAck.ackCodeUInt32, + roundTripTime: sentInfo.map { UInt32($0.suggestedTimeoutMs) } + ) + } catch { + logger.error("Failed to update room message status after send: \(error)") + } + eventBroadcaster.yield(.statusUpdated(messageID: id, status: status)) + try? await dataStore.updateRoomActivity(room.id) } catch { do { try await dataStore.updateRoomMessageStatus( @@ -378,16 +320,51 @@ public actor RoomServerService { roundTripTime: nil ) } catch let dbError { - logger.error("Failed to update message status after retry error: \(dbError)") + logger.error("Failed to update room message status after send error: \(dbError)") } eventBroadcaster.yield(.statusUpdated(messageID: id, status: .failed)) - logger.warning("Room message retry failed: \(error)") + logger.warning("Room message send failed: \(error)") } + } - guard let updatedMessage = try await dataStore.fetchRoomMessage(id: id) else { - throw RoomServerError.sendFailed("Failed to fetch message after retry") + private func postableRoomSession(id: UUID) async throws -> RemoteNodeSessionDTO { + guard let room = try await dataStore.fetchRemoteNodeSession(id: id) else { + throw RoomServerError.sessionNotFound } - return updatedMessage + guard room.canPost else { throw RoomServerError.permissionDenied } + return room + } + + private func sendRoomMessage(id: UUID, roomPublicKey: Data) async throws -> MessageSentInfo? { + // The room treats equal timestamps as retries. Wait for the next wall-clock + // second to avoid sending a future timestamp. + let now = Date().timeIntervalSince1970 + let second = now.rounded(.down) + if lastWireTimestampByRoom[roomPublicKey] == second { + try await Task.sleep(for: .seconds(second + Self.wireTimestampStep - now)) + } + + guard let message = try await dataStore.fetchRoomMessage(id: id) else { + throw RoomServerError.sendFailed("Message not found") + } + if let plainTextSendGate, await plainTextSendGate.isInvalidated { + throw CancellationError() + } + let room = try await postableRoomSession(id: message.sessionID) + let timestamp = Date().timeIntervalSince1970.rounded(.down) + if let previous = lastWireTimestampByRoom[room.publicKey], timestamp <= previous { + throw RoomServerError.sendFailed("Room timestamp did not advance") + } + lastWireTimestampByRoom[room.publicKey] = timestamp + + return try await session.sendMessageWithRetry( + to: room.publicKey, + text: message.text, + timestamp: Date(timeIntervalSince1970: timestamp), + maxAttempts: Self.totalSendAttempts, + floodAfter: Self.initialSendAttempts, + maxFloodAttempts: Self.fallbackSendAttempts + ) } // MARK: - Incoming Messages @@ -414,69 +391,53 @@ public actor RoomServerService { authorPrefix: Data, text: String ) async throws -> RoomMessageDTO? { - guard let remoteSession = try await dataStore.fetchRemoteNodeSessions(radioID: radioID) - .first(where: { $0.publicKey.prefix(6) == senderPublicKeyPrefix && $0.isRoom }) else { + guard let scope = try await dataStore.captureReceiveScope(radioID: radioID, link: receiveLifetime) else { return nil } + return try await handleIncomingMessage( + senderPublicKeyPrefix: senderPublicKeyPrefix, + timestamp: timestamp, + authorPrefix: authorPrefix, + text: text, + scope: scope + )?.message + } - // Receiving any message (even duplicate) proves session is active - if !remoteSession.isConnected { - let recovered = await (try? dataStore.markRoomSessionConnected(remoteSession.id)) ?? false - if recovered { - eventBroadcaster.yield(.connectionRecovered(sessionID: remoteSession.id)) - } + func handleIncomingMessage( + senderPublicKeyPrefix: Data, + timestamp: UInt32, + authorPrefix: Data, + text: String, + scope: ReceiveScope + ) async throws -> (message: RoomMessageDTO, room: RemoteNodeSessionDTO)? { + let arrivedAt = Date() + let preference = await textRulesPreference() + guard scope.isCurrent, scope.radioID == radioID, + let room = try await dataStore.fetchRemoteNodeSessions(radioID: radioID) + .first(where: { $0.publicKey.prefix(6) == senderPublicKeyPrefix && $0.isRoom }) else { + return nil } - // Generate deduplication key - let dedupKey = RoomMessage.generateDeduplicationKey( - timestamp: timestamp, + let post = RoomMessageDTO( + sessionID: room.id, authorKeyPrefix: authorPrefix, - text: text + text: text, + timestamp: timestamp, + createdAt: arrivedAt, + isFromSelf: selfPublicKeyPrefix == authorPrefix ) - - // Check for duplicate using deduplication key - if try await dataStore.isDuplicateRoomMessage( - sessionID: remoteSession.id, - deduplicationKey: dedupKey - ) { - return nil + let result = try await dataStore.receiveRoomPost(post, in: room, scope: scope, preference: preference) + guard scope.isCurrent else { return nil } + if result.recovered { + eventBroadcaster.yield(.connectionRecovered(sessionID: room.id)) } - - // Log room message received (metadata only, no content) + guard let message = result.message else { return nil } await auditLogger.logRoomMessageReceived( roomPublicKey: senderPublicKeyPrefix, authorPrefix: authorPrefix, messageLength: text.count ) - - // Defensive check: room servers shouldn't push our own messages back - let isFromSelf = selfPublicKeyPrefix?.prefix(4) == authorPrefix.prefix(4) - if isFromSelf { - logger.info("Received self message from room server (unexpected)") - } - - let authorName = try await resolveAuthorName(keyPrefix: authorPrefix) - - let messageDTO = RoomMessageDTO( - sessionID: remoteSession.id, - authorKeyPrefix: authorPrefix, - authorName: authorName, - text: text, - timestamp: timestamp, - isFromSelf: isFromSelf - ) - - try await dataStore.saveRoomMessage(messageDTO) - - // Update sync bookmark and sort date - try await dataStore.updateRoomActivity(remoteSession.id, syncTimestamp: timestamp) - - // Increment unread count if not from self - if !isFromSelf { - try await dataStore.incrementRoomUnreadCount(remoteSession.id) - } - - return messageDTO + return (message, room) } // MARK: - Message Retrieval @@ -521,12 +482,6 @@ public actor RoomServerService { // MARK: - Private Helpers - private func resolveAuthorName(keyPrefix: Data) async throws -> String? { - // Try to find contact with matching public key prefix - // Returns nil if no matching contact found - try await dataStore.findContactNameByKeyPrefix(keyPrefix) - } - /// Attempt to sync history, using advert path first, then falling back to path discovery. private func syncHistoryIfPossible(sessionID: UUID) async { do { diff --git a/MC1Services/Sources/MC1Services/Services/RxLogService.swift b/MC1Services/Sources/MC1Services/Services/RxLogService.swift index ab0cb1f6e7..060fdcd7cb 100644 --- a/MC1Services/Sources/MC1Services/Services/RxLogService.swift +++ b/MC1Services/Sources/MC1Services/Services/RxLogService.swift @@ -95,10 +95,12 @@ public actor RxLogService { // Build known-regions cache (and channel/contact secrets). await loadSecretsFromDatabase(radioID: radioID, generation: generation) + guard !Task.isCancelled else { return } // Subscribe before reprocess. EventDispatcher only buffers for existing // subscribers; awaiting full reprocess here would drop live RX. let events = await session.events(filter: .rxLogData) + guard !Task.isCancelled else { return } // Sibling reprocess so the for-await loop drains while store work runs. await self.launchRegionReprocessTask() @@ -153,11 +155,15 @@ public actor RxLogService { } /// Stop monitoring events. - public func stopEventMonitoring() { - eventMonitorTask?.cancel() + public func stopEventMonitoring() async { + let eventMonitorTaskToStop = eventMonitorTask eventMonitorTask = nil - regionReprocessTask?.cancel() + eventMonitorTaskToStop?.cancel() + let regionReprocessTaskToStop = regionReprocessTask regionReprocessTask = nil + regionReprocessTaskToStop?.cancel() + await eventMonitorTaskToStop?.value + await regionReprocessTaskToStop?.value } /// Returns a fresh multicast stream of newly persisted entries. @@ -271,8 +277,7 @@ public actor RxLogService { isReprocessingDMs = true defer { isReprocessingDMs = false } - guard let radioID, let myPrivateKey else { return } - guard !contactPublicKeysByPrefix.isEmpty else { return } + guard let radioID, let myPrivateKey, !contactPublicKeysByPrefix.isEmpty else { return } let cutoff = Date().addingTimeInterval(-60) diff --git a/MC1Services/Sources/MC1Services/Services/SendQueue.swift b/MC1Services/Sources/MC1Services/Services/SendQueue.swift index ef9ee48069..acf267b6e4 100644 --- a/MC1Services/Sources/MC1Services/Services/SendQueue.swift +++ b/MC1Services/Sources/MC1Services/Services/SendQueue.swift @@ -60,6 +60,10 @@ actor SendQueue { pending.count } + var isDrainingForTesting: Bool { + processingTask != nil + } + /// Await the current drain pass to completion. If no drain is in /// progress this returns immediately. Used by tests to synchronize /// on the drain task without polling — production consumers observe @@ -69,20 +73,12 @@ actor SendQueue { } #endif - /// Cancel the in-flight drain task and suppress the auto-respawn that - /// would otherwise follow a `CancellationError` re-insertion. The - /// current send closure's next `await` propagates `CancellationError`, - /// which the `catch is CancellationError` branch handles by - /// re-inserting the envelope; `taskCompleted` then observes - /// `Task.isCancelled` and skips its respawn so the queue goes - /// dormant. A subsequent `enqueue(_:)` schedules a fresh drain task - /// because `processingTask` is back to `nil`. - /// - /// Provided so test teardown can release a SendQueue whose send - /// closure suspends, and so a future production teardown does not - /// leak the actor through an unbounded respawn cycle. - func cancelDrain() { - processingTask?.cancel() + /// Cancels and joins the drain before its service graph is replaced. + /// Cancelled sends are requeued without respawning; a later enqueue can restart the drain. + func cancelDrain() async { + let worker = processingTask + worker?.cancel() + await worker?.value } private func ensureDraining() { diff --git a/MC1Services/Sources/MC1Services/Services/SensorSettingsResponseParser.swift b/MC1Services/Sources/MC1Services/Services/SensorSettingsResponseParser.swift new file mode 100644 index 0000000000..5a7bb485ba --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/SensorSettingsResponseParser.swift @@ -0,0 +1,64 @@ +import Foundation + +/// Parses CommonCLI sensor replies without normalizing firmware keys or values. +enum SensorSettingsResponseParser { + private static let emptyListResponse = "no custom var" + private static let listCountSuffix = " vars" + private static let nextPagePrefix = "... next:" + private static let valuePrefix = "> " + private static let missingValueResponse = "null" + private static let acceptedSetResponse = "ok" + private static let rejectedSetResponse = "can't find custom var" + + struct Page: Sendable, Equatable { + let total: Int + let settings: [SensorSetting] + let next: Int? + } + + static func list(_ response: String, offset: Int) throws -> Page { + if response == emptyListResponse, offset == 0 { + return Page(total: 0, settings: [], next: nil) + } + var lines = response.components(separatedBy: "\n") + if lines.last == "" { lines.removeLast() } + guard let header = lines.first, header.hasSuffix(Self.listCountSuffix), + let total = Int(header.dropLast(Self.listCountSuffix.count)), total > 0, + offset >= 0, offset < total else { throw RemoteNodeError.invalidResponse } + lines.removeFirst() + var next: Int? + if let last = lines.last, last.hasPrefix(Self.nextPagePrefix) { + guard let parsed = Int(last.dropFirst(Self.nextPagePrefix.count)) else { throw RemoteNodeError.invalidResponse } + next = parsed + lines.removeLast() + } + var keys: Set = [] + let settings = try lines.map { line in + guard let separator = line.firstIndex(of: "=") else { throw RemoteNodeError.invalidResponse } + let key = String(line[.. offset, next < total else { throw RemoteNodeError.invalidResponse } + } else { + guard end == total else { throw RemoteNodeError.invalidResponse } + } + return Page(total: total, settings: settings, next: next) + } + + static func value(_ response: String) throws -> String? { + if response == missingValueResponse { return nil } + guard response.hasPrefix(valuePrefix) else { throw RemoteNodeError.invalidResponse } + return String(response.dropFirst(valuePrefix.count)) + } + + static func accepted(_ response: String) throws { + guard response == acceptedSetResponse else { + if response == rejectedSetResponse { throw RemoteNodeError.sensorSettingRejected } + throw RemoteNodeError.invalidResponse + } + } +} diff --git a/MC1Services/Sources/MC1Services/Services/SettingsEvent.swift b/MC1Services/Sources/MC1Services/Services/SettingsEvent.swift index ceb4c98141..e9e46ecdfd 100644 --- a/MC1Services/Sources/MC1Services/Services/SettingsEvent.swift +++ b/MC1Services/Sources/MC1Services/Services/SettingsEvent.swift @@ -45,4 +45,5 @@ public enum SettingsEvent: Sendable { case pathHashModeUpdated(UInt8) case allowedRepeatFreqUpdated([MeshCore.FrequencyRange]) case defaultFloodScopeUpdated(String?) + case radioWiFiChanged(revision: UInt64) } diff --git a/MC1Services/Sources/MC1Services/Services/SettingsService+RadioWiFi.swift b/MC1Services/Sources/MC1Services/Services/SettingsService+RadioWiFi.swift new file mode 100644 index 0000000000..5fa44e699c --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/SettingsService+RadioWiFi.swift @@ -0,0 +1,114 @@ +import Foundation +import MeshCore + +public extension SettingsService { + func probeRadioWiFiSettings(expectedContextID: UUID? = nil) async throws -> RadioWiFiSnapshot.Capability { + let binding = radioWiFiBinding + let capturedSession = session + guard expectedContextID == nil || expectedContextID == binding.contextID, + !radioWiFiOperationsRetired, + let revision = await binding.state.stableRevision(), + await radioWiFiReadIsCurrent(revision: revision) else { return .busy } + let value = try await getRadioCLIValue(RadioCLIKey.wifiEnabled, session: capturedSession) + guard await radioWiFiReadIsCurrent(revision: revision) else { return .busy } + guard let value else { return .unavailable } + let enabled: Bool + switch value.trimmingCharacters(in: .whitespacesAndNewlines) { + case RadioWiFiSnapshot.enabledValue: enabled = true + case RadioWiFiSnapshot.disabledValue: enabled = false + default: throw SettingsServiceError.invalidResponse + } + return .supported(RadioWiFiSnapshot.Probe( + enabled: enabled, contextID: binding.contextID, revision: revision + )) + } + + func readRadioWiFiObservation(probe: RadioWiFiSnapshot.Probe) async -> RadioWiFiReadResult? { + let binding = radioWiFiBinding + let capturedSession = session + guard probe.contextID == binding.contextID, + await radioWiFiReadIsCurrent(revision: probe.revision) else { return nil } + var networkName: String? + var networkNameWasRead = false + var associated: Bool? + var ipAddress: String? + var ipAddressWasRead = false + var failure: (any Error)? + do { + guard let ssid = try await getRadioCLIValue(RadioCLIKey.wifiSSID, session: capturedSession) else { + throw SettingsServiceError.invalidResponse + } + guard await radioWiFiReadIsCurrent(revision: probe.revision) else { return nil } + networkName = Self.radioWiFiNetworkName(ssid) + networkNameWasRead = true + guard let status = try await getRadioCLIValue(RadioCLIKey.wifiStatus, session: capturedSession) else { + throw SettingsServiceError.invalidResponse + } + guard await radioWiFiReadIsCurrent(revision: probe.revision) else { return nil } + associated = status.trimmingCharacters(in: .whitespacesAndNewlines) == RadioWiFiSnapshot.connectedStatus + guard let ip = try await getRadioCLIValue(RadioCLIKey.wifiIP, session: capturedSession) else { + throw SettingsServiceError.invalidResponse + } + guard await radioWiFiReadIsCurrent(revision: probe.revision) else { return nil } + ipAddress = ip.isEmpty || ip == RadioCLIReply.notConnected ? nil : ip + ipAddressWasRead = true + } catch { + guard await radioWiFiReadIsCurrent(revision: probe.revision) else { return nil } + failure = error + } + return RadioWiFiReadResult( + contextID: binding.contextID, radioID: binding.state.radioID, revision: probe.revision, + enabled: probe.enabled, networkName: networkName, networkNameWasRead: networkNameWasRead, + associated: associated, ipAddress: ipAddress, ipAddressWasRead: ipAddressWasRead, error: failure + ) + } + + func readRadioWiFiCredentials( + editorID: UUID, expectedContextID: UUID? = nil + ) async throws -> RadioWiFiCredentialBaseline? { + try Task.checkCancellation() + let binding = radioWiFiBinding + let capturedSession = session + guard !radioWiFiOperationsRetired, + expectedContextID == nil || expectedContextID == binding.contextID else { return nil } + radioWiFiEditorID = editorID + radioWiFiEditorRead = nil + guard let revision = await binding.state.stableRevision(), + await radioWiFiReadIsCurrent(revision: revision), + radioWiFiEditorID == editorID else { return nil } + try Task.checkCancellation() + let ssid = try await getRadioCLIValue(RadioCLIKey.wifiSSID, session: capturedSession) + try Task.checkCancellation() + guard radioWiFiEditorID == editorID, + await radioWiFiReadIsCurrent(revision: revision) else { return nil } + let password = try await getRadioCLIValue(RadioCLIKey.wifiPassword, session: capturedSession) + try Task.checkCancellation() + guard radioWiFiEditorID == editorID, + await radioWiFiReadIsCurrent(revision: revision) else { return nil } + guard let ssid, let password else { throw SettingsServiceError.invalidResponse } + let readID = UUID() + radioWiFiEditorRead = (id: readID, revision: revision) + return RadioWiFiCredentialBaseline( + contextID: binding.contextID, radioID: binding.state.radioID, + editorID: editorID, revision: revision, ssid: Self.radioWiFiNetworkName(ssid) ?? "", + password: password, readID: readID + ) + } + + func closeRadioWiFiEditor(editorID: UUID) { + if radioWiFiEditorID == editorID { + radioWiFiEditorID = nil + radioWiFiEditorRead = nil + } + } + + internal func radioWiFiReadIsCurrent(revision: UInt64) async -> Bool { + guard !radioWiFiOperationsRetired else { return false } + let currentRevision = await radioWiFiState.stableRevision() + return !radioWiFiOperationsRetired && currentRevision == revision + } + + internal static func radioWiFiNetworkName(_ value: String) -> String? { + value.isEmpty || value == RadioCLIReply.notSet ? nil : value + } +} diff --git a/MC1Services/Sources/MC1Services/Services/SettingsService+RadioWiFiCommands.swift b/MC1Services/Sources/MC1Services/Services/SettingsService+RadioWiFiCommands.swift new file mode 100644 index 0000000000..5e57d4a0ae --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/SettingsService+RadioWiFiCommands.swift @@ -0,0 +1,50 @@ +import Foundation + +public extension SettingsService { + func clearRadioWiFi( + expectedContextID: UUID, expectedRevision: UInt64 + ) async throws -> RadioWiFiReadResult? { + let result = try await sendTrackedRadioWiFiCommand( + "set \(RadioCLIKey.wifiClear)", expectedContextID: expectedContextID, + expectedRevision: expectedRevision, correlated: true + ) + try Self.validateRadioCLIWrite(result.reply) + guard case let .supported(probe) = try await probeRadioWiFiSettings(expectedContextID: expectedContextID) else { + return nil + } + return await readRadioWiFiObservation(probe: probe) + } + + @discardableResult + func setRadioWiFiEnabled( + _ enabled: Bool, expectedContextID: UUID, expectedRevision: UInt64 + ) async throws -> UInt64? { + let receipt = try await changeRadioWiFiEnabled( + enabled, expectedContextID: expectedContextID, expectedRevision: expectedRevision + ) + if let error = receipt.error { throw error } + return receipt.revision + } + + func changeRadioWiFiEnabled( + _ enabled: Bool, expectedContextID: UUID, expectedRevision: UInt64 + ) async throws -> RadioWiFiEnabledReceipt { + let value = enabled ? RadioWiFiSnapshot.enabledValue : RadioWiFiSnapshot.disabledValue + let result = try await performTrackedRadioWiFiCommand( + "set \(RadioCLIKey.wifiEnabled) \(value)", expectedContextID: expectedContextID, + expectedRevision: expectedRevision, correlated: true + ) + var failure = result.error + if failure == nil { + do { + guard let reply = result.reply else { throw SettingsServiceError.invalidResponse } + try Self.validateRadioCLIWrite(reply) + } catch { + failure = error + } + } + return RadioWiFiEnabledReceipt( + contextID: result.contextID, revision: result.revision, outcome: result.outcome, error: failure + ) + } +} diff --git a/MC1Services/Sources/MC1Services/Services/SettingsService+RadioWiFiMutations.swift b/MC1Services/Sources/MC1Services/Services/SettingsService+RadioWiFiMutations.swift new file mode 100644 index 0000000000..242725a69d --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/SettingsService+RadioWiFiMutations.swift @@ -0,0 +1,287 @@ +import Foundation +import MeshCore + +extension SettingsService { + enum RadioWiFiWorkResult: Sendable { + case raw(RadioWiFiCommandResult) + case credentials(RadioWiFiMutationReceipt) + case reboot + } + + func sendTrackedRadioWiFiCommand( + _ command: String, expectedContextID: UUID? = nil, expectedRevision: UInt64? = nil, + replyPrefix: String? = nil, correlated: Bool = false + ) async throws -> (reply: String, revision: UInt64?) { + let result = try await performTrackedRadioWiFiCommand( + command, expectedContextID: expectedContextID, expectedRevision: expectedRevision, + replyPrefix: replyPrefix, correlated: correlated + ) + if let error = result.error { throw error } + guard let reply = result.reply else { throw SettingsServiceError.invalidResponse } + return (reply, result.revision) + } + + func performTrackedRadioWiFiCommand( + _ command: String, expectedContextID: UUID? = nil, expectedRevision: UInt64? = nil, + replyPrefix: String? = nil, correlated: Bool = false + ) async throws -> RadioWiFiCommandResult { + try Task.checkCancellation() + let binding = radioWiFiBinding + let capturedSession = session + guard !radioWiFiOperationsRetired, + expectedContextID == nil || expectedContextID == binding.contextID, + let token = await binding.state.beginMutation(expectedRevision: expectedRevision) else { + throw CancellationError() + } + guard !radioWiFiOperationsRetired else { + await binding.state.settle(token, outcome: .rejected) + throw CancellationError() + } + let worker = Task { + try await self.performRawRadioWiFiCommand( + command, token: token, binding: binding, capturedSession: capturedSession, + requiresUncontended: expectedRevision != nil, replyPrefix: replyPrefix, correlated: correlated + ) + } + radioWiFiWorkers[token.id] = worker + await emitRadioWiFiChanged() + guard case let .raw(result) = try await worker.value else { throw SettingsServiceError.invalidResponse } + return result + } + + public func saveRadioWiFiCredentials( + ssid: String, + password: String, + baseline: RadioWiFiCredentialBaseline, + editorID: UUID, + ownerIsCurrent: @escaping @MainActor @Sendable () -> Bool + ) async throws -> RadioWiFiMutationReceipt { + try Task.checkCancellation() + let binding = radioWiFiBinding + let capturedSession = session + guard !radioWiFiOperationsRetired, + baseline.contextID == binding.contextID, + baseline.radioID == binding.state.radioID, + baseline.editorID == editorID, + radioWiFiEditorRead?.id == baseline.readID, + radioWiFiEditorRead?.revision == baseline.revision, + radioWiFiEditorID == editorID else { throw CancellationError() } + guard RadioWiFiCredentialBaseline.validCredentials(ssid: ssid, password: password) else { + throw SettingsServiceError.invalidResponse + } + guard let token = await binding.state.beginMutation(expectedRevision: baseline.revision) else { + throw CancellationError() + } + guard !radioWiFiOperationsRetired else { + await binding.state.settle(token, outcome: .rejected) + throw CancellationError() + } + let worker: Task = Task { + await self.performRadioWiFiSave( + ssid: ssid, password: password, baseline: baseline, token: token, + binding: binding, capturedSession: capturedSession, ownerIsCurrent: ownerIsCurrent + ) + } + radioWiFiWorkers[token.id] = worker + await emitRadioWiFiChanged() + guard case let .credentials(receipt) = try await worker.value else { + throw SettingsServiceError.invalidResponse + } + return receipt + } + + @discardableResult + public func confirmExpectedRadioWiFiReboot( + id: UUID, + expectedRadioID: UUID, + ownerIsCurrent: @MainActor @Sendable () -> Bool + ) async -> Bool { + let binding = radioWiFiBinding + let capturedSession = session + guard !radioWiFiOperationsRetired, + binding.state.radioID == expectedRadioID, + let revision = await binding.state.stableRevision(), + await radioWiFiReadIsCurrent(revision: revision) else { return false } + let observation = await readRadioWiFiResetObservation(using: capturedSession) + guard await radioWiFiReadIsCurrent(revision: revision) else { return false } + let cleared = await MainActor.run { + ownerIsCurrent() && binding.state.clearExpectedReboot( + id: id, contextID: binding.contextID, readRevision: revision, observation: observation + ) + } + if cleared { await emitRadioWiFiChanged() } + return cleared + } + + private func performRawRadioWiFiCommand( + _ command: String, + token: RadioWiFiState.MutationToken, + binding: RadioWiFiBinding, + capturedSession: any ConfigurationSessionOps, + requiresUncontended: Bool, + replyPrefix: String?, + correlated: Bool + ) async throws -> RadioWiFiWorkResult { + var attempted = false + do { + guard !radioWiFiOperationsRetired else { throw CancellationError() } + if requiresUncontended { + guard await binding.state.isUncontended(token), !radioWiFiOperationsRetired else { + throw CancellationError() + } + } + attempted = true + let reply = if correlated { + try await sendCorrelatedRadioCLI(command, using: capturedSession) + } else { + try await sendCapturedRadioCLI(command, using: capturedSession) + } + let classificationText: String = if let replyPrefix, reply.hasPrefix(replyPrefix) { + String(reply.dropFirst(replyPrefix.count)) + } else { + reply + } + let outcome: RadioWiFiState.MutationOutcome = switch RadioCLIReply(text: classificationText) { + case .ok, .value: .accepted + case .error, .unknownCommand: .rejected + case .other: .uncertain + } + let revision = await binding.state.settle(token, outcome: outcome) + await emitRadioWiFiChanged() + radioWiFiWorkers[token.id] = nil + return .raw(RadioWiFiCommandResult( + contextID: binding.contextID, reply: reply, revision: revision, outcome: outcome, error: nil + )) + } catch { + let rejected = !attempted || Self.radioCLIWasRejectedBeforeAcceptance(error) + let outcome: RadioWiFiState.MutationOutcome = rejected ? .rejected : .uncertain + let revision = await binding.state.settle(token, outcome: outcome) + await emitRadioWiFiChanged() + radioWiFiWorkers[token.id] = nil + return .raw(RadioWiFiCommandResult( + contextID: binding.contextID, reply: nil, revision: revision, outcome: outcome, error: error + )) + } + } + + private func performRadioWiFiSave( + ssid: String, + password: String, + baseline: RadioWiFiCredentialBaseline, + token: RadioWiFiState.MutationToken, + binding: RadioWiFiBinding, + capturedSession: any ConfigurationSessionOps, + ownerIsCurrent: @MainActor @Sendable () -> Bool + ) async -> RadioWiFiWorkResult { + var ssidAccepted = false + var passwordAccepted = false + var uncertain = false + var failure: (any Error)? + var attempted = false + do { + try await requireRadioWiFiSaveOwner(baseline: baseline, token: token, binding: binding, ownerIsCurrent: ownerIsCurrent) + let passwordChanged = !RadioWiFiCredentialBaseline.hasSameBytes(password, baseline.password) + if !RadioWiFiCredentialBaseline.hasSameBytes(ssid, baseline.ssid) || passwordChanged { + attempted = true + let reply = try await sendCorrelatedRadioCLI("set \(RadioCLIKey.wifiSSID) \(ssid)", using: capturedSession) + try Self.validateRadioCLIWrite(reply) + attempted = false + ssidAccepted = true + } + if passwordChanged { + try await requireRadioWiFiSaveOwner(baseline: baseline, token: token, binding: binding, ownerIsCurrent: ownerIsCurrent) + attempted = true + let reply = try await sendCorrelatedRadioCLI("set \(RadioCLIKey.wifiPassword) \(password)", using: capturedSession) + try Self.validateRadioCLIWrite(reply) + attempted = false + passwordAccepted = true + } + } catch { + failure = error + if Self.radioCLIWasRejectedBeforeAcceptance(error) { + uncertain = false + } else { + uncertain = attempted + } + } + let outcome: RadioWiFiState.MutationOutcome = uncertain ? .uncertain + : (ssidAccepted || passwordAccepted ? .accepted : .rejected) + let revision = await binding.state.settle(token, outcome: outcome) + var updatedBaseline: RadioWiFiCredentialBaseline? + if radioWiFiEditorID == baseline.editorID, radioWiFiEditorRead?.id == baseline.readID { + if let revision, !uncertain { + radioWiFiEditorRead = (id: baseline.readID, revision: revision) + updatedBaseline = baseline.updating( + ssid: ssidAccepted ? ssid : baseline.ssid, + password: passwordAccepted ? password : baseline.password, + revision: revision + ) + } else { + radioWiFiEditorRead = nil + } + } + await emitRadioWiFiChanged() + radioWiFiWorkers[token.id] = nil + return .credentials(RadioWiFiMutationReceipt( + contextID: binding.contextID, + ssidAccepted: ssidAccepted, + passwordAccepted: passwordAccepted, + revision: revision, + uncertain: uncertain, + error: failure, + updatedBaseline: updatedBaseline + )) + } + + private func requireRadioWiFiSaveOwner( + baseline: RadioWiFiCredentialBaseline, + token: RadioWiFiState.MutationToken, + binding: RadioWiFiBinding, + ownerIsCurrent: @MainActor @Sendable () -> Bool + ) async throws { + let current = await MainActor.run { ownerIsCurrent() && binding.state.isUncontended(token) } + guard current, + !radioWiFiOperationsRetired, + radioWiFiEditorID == baseline.editorID, + radioWiFiEditorRead?.id == baseline.readID else { throw CancellationError() } + } + + static func radioCLIWasRejectedBeforeAcceptance(_ error: any Error) -> Bool { + guard let error = error as? SettingsServiceError else { return false } + switch error { + case .radioCLIRejected, .sessionError(.invalidInput): return true + default: return false + } + } + + func sendCorrelatedRadioCLI(_ command: String, using capturedSession: any ConfigurationSessionOps) async throws -> String { + do { + return try await capturedSession.runCorrelatedCliCommand(command) + } catch let error as MeshCoreError { + throw SettingsServiceError.sessionError(error) + } + } + + func sendCapturedRadioCLI(_ command: String, using capturedSession: any ConfigurationSessionOps) async throws -> String { + do { + return try await capturedSession.runCliCommand(command) + } catch let error as MeshCoreError { + throw SettingsServiceError.sessionError(error) + } + } + + func emitRadioWiFiChanged() async { + let revision = await radioWiFiState.revision + eventContinuation?.yield(.radioWiFiChanged(revision: revision)) + } + + public func retireRadioWiFiOperations() async { + radioWiFiOperationsRetired = true + radioWiFiEditorID = nil + radioWiFiEditorRead = nil + let workers = Array(radioWiFiWorkers.values) + for worker in workers { + _ = try? await worker.value + } + } +} diff --git a/MC1Services/Sources/MC1Services/Services/SettingsService+RadioWiFiReboot.swift b/MC1Services/Sources/MC1Services/Services/SettingsService+RadioWiFiReboot.swift new file mode 100644 index 0000000000..d801e061cc --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/SettingsService+RadioWiFiReboot.swift @@ -0,0 +1,66 @@ +import Foundation +import MeshCore + +extension SettingsService { + /// Reboot the device. + public func reboot() async throws { + try await reboot(expectedContextID: nil, expectedRevision: nil) + } + + public func reboot(expectedContextID: UUID, expectedRevision: UInt64) async throws { + try await reboot(expectedContextID: Optional(expectedContextID), expectedRevision: Optional(expectedRevision)) + } + + private func reboot(expectedContextID: UUID?, expectedRevision: UInt64?) async throws { + try Task.checkCancellation() + let binding = radioWiFiBinding + guard !radioWiFiOperationsRetired, + expectedContextID == nil || expectedContextID == binding.contextID else { throw CancellationError() } + let capturedSession = session + let workerID = UUID() + let worker = Task { + try await self.performRadioWiFiReboot( + workerID: workerID, binding: binding, capturedSession: capturedSession, expectedRevision: expectedRevision + ) + } + radioWiFiWorkers[workerID] = worker + guard case .reboot = try await worker.value else { throw SettingsServiceError.invalidResponse } + } + + private func performRadioWiFiReboot( + workerID: UUID, binding: RadioWiFiBinding, capturedSession: any ConfigurationSessionOps, + expectedRevision: UInt64? + ) async throws -> RadioWiFiWorkResult { + defer { radioWiFiWorkers[workerID] = nil } + guard !radioWiFiOperationsRetired else { throw CancellationError() } + let requiresProof = await binding.state.rebootPending + let observation = requiresProof ? await readRadioWiFiResetObservation(using: capturedSession) : nil + guard !radioWiFiOperationsRetired else { throw CancellationError() } + let candidate = await binding.state.prepareExpectedReboot( + contextID: binding.contextID, expectedRevision: expectedRevision, observation: observation + ) + do { + guard !radioWiFiOperationsRetired, expectedRevision == nil || candidate != nil else { + throw CancellationError() + } + try await capturedSession.reboot() + if let candidate { await binding.state.completeRebootSubmission(id: candidate, succeeded: true) } + await emitRadioWiFiChanged() + return .reboot + } catch let error as MeshCoreError { + if let candidate { await binding.state.completeRebootSubmission(id: candidate, succeeded: false) } + await emitRadioWiFiChanged() + throw SettingsServiceError.sessionError(error) + } catch { + if let candidate { await binding.state.completeRebootSubmission(id: candidate, succeeded: false) } + await emitRadioWiFiChanged() + throw error + } + } + + func readRadioWiFiResetObservation(using capturedSession: any ConfigurationSessionOps) async -> RadioWiFiResetObservation? { + let started = ContinuousClock.now + guard let stats = try? await capturedSession.getStatsCore() else { return nil } + return RadioWiFiResetObservation(uptimeSeconds: stats.uptimeSeconds, startedAt: started, completedAt: .now) + } +} diff --git a/MC1Services/Sources/MC1Services/Services/SettingsService.swift b/MC1Services/Sources/MC1Services/Services/SettingsService.swift index ed30aed561..2bbb47972c 100644 --- a/MC1Services/Sources/MC1Services/Services/SettingsService.swift +++ b/MC1Services/Sources/MC1Services/Services/SettingsService.swift @@ -7,7 +7,21 @@ import os /// Service for managing device settings via MeshCore session. /// Handles radio configuration, node settings, Bluetooth settings, and device info. public actor SettingsService { - private let session: any ConfigurationSessionOps + let session: any ConfigurationSessionOps + public nonisolated let radioWiFiBinding: RadioWiFiBinding + public nonisolated var radioWiFiContextID: UUID { + radioWiFiBinding.contextID + } + + public nonisolated var radioWiFiState: RadioWiFiState { + radioWiFiBinding.state + } + + var radioWiFiOperationsRetired = false + var radioWiFiEditorID: UUID? + // Only a fresh read or an uncontended mutation receipt advances this certificate. + var radioWiFiEditorRead: (id: UUID, revision: UInt64)? + var radioWiFiWorkers: [UUID: Task] = [:] let logger = PersistentLogger(subsystem: "com.mc1", category: "SettingsService") /// Orders radio-parameter writes, path-hash work that belongs to a preset, and publication. @@ -21,13 +35,28 @@ public actor SettingsService { var eventContinuation: AsyncStream.Continuation? private var eventSubscriptionID: UUID? + #if DEBUG + private var testSelfInfoResultHandler: (@Sendable () async -> Void)? + + func setTestSelfInfoResultHandler(_ handler: (@Sendable () async -> Void)?) { + testSelfInfoResultHandler = handler + } + #endif + public init(session: any ConfigurationSessionOps) { self.session = session + radioWiFiBinding = RadioWiFiBinding(state: RadioWiFiState(radioID: UUID())) + } + + public init(session: any ConfigurationSessionOps, radioWiFiState: RadioWiFiState) { + self.session = session + radioWiFiBinding = RadioWiFiBinding(state: radioWiFiState) } - /// True after this connection accepts a `set wifi.` line. - /// A new service starts false, and nothing here clears the flag. - public private(set) var radioWiFiRebootPending = false + /// Apply evidence survives replacement services for the same Radio ID. + public var radioWiFiRebootPending: Bool { + get async { await radioWiFiState.rebootPending } + } /// Stream of settings change events. /// Only one active subscriber is supported. Subsequent calls replace the previous subscriber. @@ -271,15 +300,6 @@ public actor SettingsService { } } - /// Reboot the device - public func reboot() async throws { - do { - try await session.reboot() - } catch let error as MeshCoreError { - throw SettingsServiceError.sessionError(error) - } - } - /// Asks the paired radio to cut power. /// A CLI reply means the board stayed on. Only silence after a submitted frame counts as powered off. public func powerOff() async throws { @@ -311,8 +331,12 @@ public actor SettingsService { /// Query device capabilities public func queryDevice() async throws -> DeviceCapabilities { + try await queryDevice(using: session) + } + + func queryDevice(using capturedSession: any ConfigurationSessionOps) async throws -> DeviceCapabilities { do { - return try await session.queryDevice() + return try await capturedSession.queryDevice() } catch let error as MeshCoreError { throw SettingsServiceError.sessionError(error) } @@ -320,8 +344,19 @@ public actor SettingsService { /// Get self info by sending appStart public func getSelfInfo() async throws -> MeshCore.SelfInfo { + try await getSelfInfo(using: session) + } + + func getSelfInfo(using capturedSession: any ConfigurationSessionOps) async throws -> MeshCore.SelfInfo { + #if DEBUG + let resultHandler = testSelfInfoResultHandler + #endif do { - return try await session.sendAppStart() + let selfInfo = try await capturedSession.sendAppStart() + #if DEBUG + await resultHandler?() + #endif + return selfInfo } catch let error as MeshCoreError { throw SettingsServiceError.sessionError(error) } @@ -526,10 +561,34 @@ public actor SettingsService { } } - public func runCliCommand(_ command: String) async throws -> String { - let reply = try await sendRadioCLI(command) - noteWiFiRebootPending(command: command, reply: reply) - return reply + private enum RadioCLISyntax { + static let spaceByte: UInt8 = 0x20 + static let pipeByte: UInt8 = 0x7C + static let prefixMarkerOffset = 2 + static let prefixByteCount = 3 + static let minimumPrefixedByteCount = 5 + static let wifiSetterPrefix = "set wifi." + } + + public func runCliCommand(_ command: String, expectedContextID: UUID? = nil) async throws -> String { + let binding = radioWiFiBinding + let capturedSession = session + guard !radioWiFiOperationsRetired, + expectedContextID == nil || expectedContextID == binding.contextID else { throw CancellationError() } + var effectiveBytes = command.utf8.drop(while: { $0 == RadioCLISyntax.spaceByte }) + var replyPrefix: String? + if effectiveBytes.count >= RadioCLISyntax.minimumPrefixedByteCount, + effectiveBytes[effectiveBytes.index(effectiveBytes.startIndex, offsetBy: RadioCLISyntax.prefixMarkerOffset)] + == RadioCLISyntax.pipeByte { + replyPrefix = String(decoding: effectiveBytes.prefix(RadioCLISyntax.prefixByteCount), as: UTF8.self) + effectiveBytes = effectiveBytes.dropFirst(RadioCLISyntax.prefixByteCount) + } + if String(decoding: effectiveBytes, as: UTF8.self).hasPrefix(RadioCLISyntax.wifiSetterPrefix) { + return try await sendTrackedRadioWiFiCommand( + command, expectedContextID: binding.contextID, replyPrefix: replyPrefix + ).reply + } + return try await sendCapturedRadioCLI(command, using: capturedSession) } /// CommonCLI prints this, then the key, for an unknown get. @@ -538,7 +597,11 @@ public actor SettingsService { /// Read one Radio CLI key. `nil` means this build has no such key. public func getRadioCLIValue(_ key: String) async throws -> String? { - let reply = try await sendRadioCLI("get \(key)") + try await getRadioCLIValue(key, session: session) + } + + func getRadioCLIValue(_ key: String, session: any ConfigurationSessionOps) async throws -> String? { + let reply = try await sendCorrelatedRadioCLI("get \(key)", using: session) switch RadioCLIReply(text: reply) { case let .value(value): return value @@ -561,8 +624,15 @@ public actor SettingsService { } else { "set \(key)" } - let reply = try await sendRadioCLI(command) - noteWiFiRebootPending(command: command, reply: reply) + let reply: String = if key.hasPrefix("wifi.") { + try await sendTrackedRadioWiFiCommand(command, correlated: true).reply + } else { + try await sendCorrelatedRadioCLI(command, using: session) + } + try Self.validateRadioCLIWrite(reply) + } + + static func validateRadioCLIWrite(_ reply: String) throws { switch RadioCLIReply(text: reply) { case .ok, .value: return @@ -575,25 +645,6 @@ public actor SettingsService { } } - private func sendRadioCLI(_ command: String) async throws -> String { - do { - return try await session.runCliCommand(command) - } catch let error as MeshCoreError { - throw SettingsServiceError.sessionError(error) - } - } - - private func noteWiFiRebootPending(command: String, reply: String) { - let line = command.trimmingCharacters(in: .whitespacesAndNewlines) - guard line.hasPrefix("set wifi.") else { return } - switch RadioCLIReply(text: reply) { - case .ok, .value: - radioWiFiRebootPending = true - case .error, .unknownCommand, .other: - break - } - } - public func getDeviceGPSState() async throws -> DeviceGPSState { let vars = try await getCustomVars() return Self.deviceGPSState(from: vars) @@ -633,13 +684,21 @@ public actor SettingsService { /// Export private key from device public func exportPrivateKey() async throws -> Data { + try await exportPrivateKey(using: session) + } + + func exportPrivateKey(using capturedSession: any ConfigurationSessionOps) async throws -> Data { do { - return try await session.exportPrivateKey() + return try await capturedSession.exportPrivateKey() } catch let error as MeshCoreError { throw SettingsServiceError.sessionError(error) } } + func configurationSessionForRead() -> any ConfigurationSessionOps { + session + } + /// Import private key to device public func importPrivateKey(_ key: Data) async throws { do { diff --git a/MC1Services/Sources/MC1Services/Simulator/MockDataProvider+ChannelMessages.swift b/MC1Services/Sources/MC1Services/Simulator/MockDataProvider+ChannelMessages.swift index 0212865f46..d12cd3dc9c 100644 --- a/MC1Services/Sources/MC1Services/Simulator/MockDataProvider+ChannelMessages.swift +++ b/MC1Services/Sources/MC1Services/Simulator/MockDataProvider+ChannelMessages.swift @@ -10,6 +10,7 @@ extension MockDataProvider { case bayAreaChannelIndex: return bayAreaChannelMessages(now: now) case trailCrewChannelIndex: return trailCrewChannelMessages(now: now) case meshHQChannelIndex: return meshHQChannelMessages(now: now) + case emergencyChannelIndex: return emergencyChannelMessages(now: now) default: return [] } } @@ -186,6 +187,78 @@ extension MockDataProvider { ] } + /// Wire strings for `#emergency`. `MECP/5/M01` does not decode. The two + /// newest incoming rows are unread, matching the channel's unread count. + private static func emergencyChannelMessages(now: Date) -> [MessageDTO] { + let path = encodePathLen(hashSize: 1, hopCount: 1) + return [ + emergencyIncoming( + "C4000000-0000-0000-0000-000000000001", + now.addingTimeInterval(-800), + "MECP/0/M01 M02 T04 3pax 37.7849,-122.4094 @1430 @en", + sender: "Alice Chen", snr: 8.4, path: path + ), + emergencyIncoming( + "C4000000-0000-0000-0000-000000000002", + now.addingTimeInterval(-500), + "MECP/1/R03 15", + sender: "Bob Martinez", snr: 7.1, path: path + ), + emergencyIncoming( + "C4000000-0000-0000-0000-000000000003", + now.addingTimeInterval(-300), + "MECP/5/M01", + sender: "Hannah Lee", snr: 6.4, path: path + ), + MockMessageFactory.message( + id: UUID(uuidString: "C4000000-0000-0000-0000-000000000004")!, + createdAt: now.addingTimeInterval(-120), + text: "MECP/1/R02", + direction: .outgoing, + status: .sent, + channelIndex: emergencyChannelIndex, + ackCode: 50004, + pathLength: path + ), + emergencyIncoming( + "C4000000-0000-0000-0000-000000000005", + now.addingTimeInterval(-40), + "MECP/3/H07 4pax", + sender: "Frank Wilson", snr: 5.8, path: path, + isRead: false + ), + emergencyIncoming( + "C4000000-0000-0000-0000-000000000006", + now.addingTimeInterval(-10), + "MECP/2/P03 S01 2pax", + sender: "Carol Diaz", snr: 9.2, path: path, + isRead: false + ) + ] + } + + private static func emergencyIncoming( + _ id: String, + _ createdAt: Date, + _ text: String, + sender: String, + snr: Double, + path: UInt8, + isRead: Bool = true + ) -> MessageDTO { + MockMessageFactory.message( + id: UUID(uuidString: id)!, + createdAt: createdAt, + text: text, + direction: .incoming, + channelIndex: emergencyChannelIndex, + pathLength: path, + snr: snr, + senderNodeName: sender, + isRead: isRead + ) + } + /// Builds an incoming channel message, resolving the slot index from the id prefix. private static func channelIncoming( _ id: String, diff --git a/MC1Services/Sources/MC1Services/Simulator/MockDataProvider+Channels.swift b/MC1Services/Sources/MC1Services/Simulator/MockDataProvider+Channels.swift index bdac182e4d..fb6fc726c0 100644 --- a/MC1Services/Sources/MC1Services/Simulator/MockDataProvider+Channels.swift +++ b/MC1Services/Sources/MC1Services/Simulator/MockDataProvider+Channels.swift @@ -59,6 +59,19 @@ extension MockDataProvider { unreadCount: meshHQUnreadCount, notificationLevel: .all, isPinned: false + ), + // Hashtag channel. The secret is the hash of the name, including the `#`. + ChannelDTO( + id: emergencyChannelID, + radioID: simulatorDeviceID, + index: emergencyChannelIndex, + name: "#emergency", + secret: ChannelService.hashSecret("#emergency"), + isEnabled: true, + lastMessageDate: now.addingTimeInterval(-10), + unreadCount: 2, + notificationLevel: .all, + isPinned: false ) ] } diff --git a/MC1Services/Sources/MC1Services/Simulator/MockDataProvider+Contacts.swift b/MC1Services/Sources/MC1Services/Simulator/MockDataProvider+Contacts.swift index ec211212c1..1fa57be58f 100644 --- a/MC1Services/Sources/MC1Services/Simulator/MockDataProvider+Contacts.swift +++ b/MC1Services/Sources/MC1Services/Simulator/MockDataProvider+Contacts.swift @@ -6,6 +6,27 @@ public extension MockDataProvider { let now = Date() return [ + ContactDTO( + id: creekSensorID, + radioID: simulatorDeviceID, + publicKey: mockPublicKey(seed: 0x94), + name: "Creek Sensor", + typeRawValue: ContactType.sensor.rawValue, + flags: 0, + outPathLength: 0, + outPath: Data(), + lastAdvertTimestamp: UInt32(now.timeIntervalSince1970), + latitude: 37.78, + longitude: -122.42, + lastModified: UInt32(now.timeIntervalSince1970), + lastHeardTimestamp: nil, + nickname: nil, + isBlocked: false, + isMuted: false, + isFavorite: false, + lastMessageDate: nil, + unreadCount: 0 + ), // Alice Chen - chat, normal, 3 unread, 2 hops ContactDTO( id: aliceChenID, diff --git a/MC1Services/Sources/MC1Services/Simulator/MockDataProvider.swift b/MC1Services/Sources/MC1Services/Simulator/MockDataProvider.swift index 61b071989b..e273b4c5d8 100644 --- a/MC1Services/Sources/MC1Services/Simulator/MockDataProvider.swift +++ b/MC1Services/Sources/MC1Services/Simulator/MockDataProvider.swift @@ -21,6 +21,7 @@ public enum MockDataProvider { public static let hannahLeeID = UUID(uuidString: "00000000-0000-0000-0000-000000000080")! public static let northRidgeRepeaterID = UUID(uuidString: "00000000-0000-0000-0000-000000000091")! public static let twinPeaksRepeaterID = UUID(uuidString: "00000000-0000-0000-0000-000000000092")! + public static let creekSensorID = UUID(uuidString: "00000000-0000-0000-0000-000000000094")! public static let oaklandRepeaterID = UUID(uuidString: "00000000-0000-0000-0000-000000000093")! /// Byte 0 of `mockPublicKey(seed:)`. A 1-byte hop hash of this value matches that repeater only. @@ -33,12 +34,14 @@ public enum MockDataProvider { public static let bayAreaChannelID = UUID(uuidString: "000000C0-0000-0000-0000-000000000001")! public static let trailCrewChannelID = UUID(uuidString: "000000C0-0000-0000-0000-000000000002")! public static let meshHQChannelID = UUID(uuidString: "000000C0-0000-0000-0000-000000000003")! + public static let emergencyChannelID = UUID(uuidString: "000000C0-0000-0000-0000-000000000004")! /// Channel slot indices (mirror firmware slot positions) public static let publicChannelIndex: UInt8 = 0 public static let bayAreaChannelIndex: UInt8 = 1 public static let trailCrewChannelIndex: UInt8 = 2 public static let meshHQChannelIndex: UInt8 = 3 + public static let emergencyChannelIndex: UInt8 = 4 /// Message IDs referenced by more than one seed helper (reaction / repeat / /// link-preview targets) so the builders and the post-save mutators agree. diff --git a/MC1Services/Sources/MC1Services/Simulator/SimulatorConnectionMode.swift b/MC1Services/Sources/MC1Services/Simulator/SimulatorConnectionMode.swift index 14fdf1834b..eff7697759 100644 --- a/MC1Services/Sources/MC1Services/Simulator/SimulatorConnectionMode.swift +++ b/MC1Services/Sources/MC1Services/Simulator/SimulatorConnectionMode.swift @@ -125,10 +125,12 @@ final class SimulatorConnectionMode { guard try await dataStore.fetchLatestNodeStatusSnapshot(nodePublicKey: nodeKey) == nil else { return } - let existingKeys = try await dataStore.existingNodeStatusSnapshotKeys() + let identity = try await dataStore.existingNodeStatusSnapshotIdentity() try await dataStore.batchInsertNodeStatusSnapshots( MockDataProvider.nodeStatusSnapshots, - existingKeys: existingKeys + existingKeys: identity.keys, + existingIDs: identity.ids, + radioIDMapping: [:] ) } } diff --git a/MC1Services/Sources/MC1Services/Sync/ConnectionManager+SyncRetry.swift b/MC1Services/Sources/MC1Services/Sync/ConnectionManager+SyncRetry.swift index faaa3828d2..1ddcd5e71c 100644 --- a/MC1Services/Sources/MC1Services/Sync/ConnectionManager+SyncRetry.swift +++ b/MC1Services/Sources/MC1Services/Sync/ConnectionManager+SyncRetry.swift @@ -24,12 +24,16 @@ extension ConnectionManager { /// handleDisconnect zeroes syncActivityCount independently, and the onEnded callback's /// guard (syncActivityCount > 0) prevents underflow. func cancelResyncLoop() { + if let resyncTask { retiringWorkers.append(resyncTask) } + resyncSlotID = nil resyncTask?.cancel() resyncTask = nil resyncAttemptCount = 0 } func cancelChannelRetry() { + if let channelRetryTask { retiringWorkers.append(channelRetryTask) } + channelRetrySlotID = nil channelRetryTask?.cancel() channelRetryTask = nil } @@ -52,6 +56,7 @@ extension ConnectionManager { context: String = "", forceFullSync: Bool = false ) async -> FullSyncResult? { + guard self.services === services, services.isAcceptingRuntimeWork else { return nil } let channelSyncConfig = currentChannelSyncConfig(for: radioID, transportType: transportType) do { let result = try await services.syncCoordinator.onConnectionEstablished( @@ -62,6 +67,7 @@ extension ConnectionManager { platformName: "\(detectedPlatform)" ) + guard self.services === services, services.isAcceptingRuntimeWork, connectionIntent.wantsConnection else { return nil } if !result.channelRetryIndices.isEmpty { scheduleChannelOnlyRetry( radioID: radioID, @@ -78,7 +84,7 @@ extension ConnectionManager { return result } catch { // Don't start resync if user disconnected while sync was in progress - guard connectionIntent.wantsConnection else { return nil } + guard connectionIntent.wantsConnection, self.services === services, services.isAcceptingRuntimeWork else { return nil } let prefix = context.isEmpty ? "" : "\(context): " logger.warning("\(prefix)Initial sync failed, starting resync loop: \(error.localizedDescription)") startResyncLoop(radioID: radioID, services: services, transportType: transportType, forceFullSync: forceFullSync) @@ -99,117 +105,50 @@ extension ConnectionManager { transportType: TransportType = .bluetooth, forceFullSync: Bool = false ) { - guard self.services === services else { return } - resyncTask?.cancel() + guard let link = installedLink, link.services === services, ownsRuntime(link) else { return } + cancelResyncLoop() + let slot = UUID() + resyncSlotID = slot resyncAttemptCount = 0 - - // Note: No [weak self] needed - Task is stored property, self is @MainActor class. - // Task inherits MainActor isolation, no retain cycle risk. - resyncTask = Task { - // Hold sync activity for the entire resync loop so the "Syncing" pill stays visible. - // Must be inside the task body: placing it before task assignment introduced a - // suspension point where resyncTask was still nil, breaking the dedup guard in - // checkSyncHealth(). + resyncTask = Task { @MainActor in + defer { + if self.resyncSlotID == slot { + self.resyncTask = nil + self.resyncSlotID = nil + self.resyncAttemptCount = 0 + } + } await services.syncCoordinator.beginResyncActivity() - var didEndResyncActivity = false - - while !Task.isCancelled { - try? await Task.sleep(for: Self.resyncInterval) - guard !Task.isCancelled else { break } - - // Fence on services identity so a loop orphaned by a later reconnect - // cycle neither resyncs nor disconnects against a container the manager - // has since replaced; without it the exhaustion branch below could tear - // down a healthy successor connection. - guard connectionIntent.wantsConnection, - connectionState.isOperational, - self.services === services else { break } - - resyncAttemptCount += 1 - logger.info("Resync attempt \(resyncAttemptCount)/\(Self.maxResyncAttempts)") - - let channelSyncConfig = self.currentChannelSyncConfig(for: radioID, transportType: transportType) + var ended = false + for attempt in 1...Self.maxResyncAttempts { + do { try await reconnectionClock.sleep(for: Self.resyncInterval) } catch { break } + guard self.ownsRuntime(link), self.resyncSlotID == slot, !Task.isCancelled else { break } + self.resyncAttemptCount = attempt + let config = self.currentChannelSyncConfig(for: radioID, transportType: transportType) let result = await services.syncCoordinator.performResync( - radioID: radioID, - dependencies: services.syncDependencies, - forceFullSync: forceFullSync, - channelSyncConfig: channelSyncConfig, - platformName: "\(self.detectedPlatform)" + radioID: radioID, dependencies: services.syncDependencies, forceFullSync: forceFullSync, + channelSyncConfig: config, platformName: "\(self.detectedPlatform)" ) - + guard self.ownsRuntime(link), self.resyncSlotID == slot, !Task.isCancelled else { break } if let result, result.isConnectionUsable { - logger.info("Resync succeeded") - resyncAttemptCount = 0 - - // Run post-sync hooks deferred when initial sync failed. - // Guard each await: disconnect(), device switch, or a new - // reconnect cycle may have torn down the connection. - guard !Task.isCancelled, - connectionIntent.wantsConnection, - connectionState.isOperational, - self.services === services else { break } - - // Promote before the post-sync hooks, matching promoteToReady's - // ordering: room re-auth is a bounded but multi-second await, and - // holding the "Syncing" pill and the send queue's .ready gate - // through it delays the user for work that isn't sync. - // Not using promoteToReady() because: (1) its guards (services identity, - // connectionIntent) are already checked above, and (2) it would re-run - // time sync and onDeviceSynced, duplicating the resync loop's own post-sync work. await services.syncCoordinator.endResyncActivity(succeeded: true) - didEndResyncActivity = true - connectionState = .ready - - await syncDeviceTimeIfNeeded() - - guard !Task.isCancelled, - connectionIntent.wantsConnection, - connectionState.isOperational, - self.services === services else { break } - - // Re-authenticate room sessions before onDeviceSynced to avoid - // BLE contention with stale node cleanup's fire-and-forget Task. - let sessionIDs = sessionsAwaitingReauth - if !sessionIDs.isEmpty { - await services.remoteNodeService.handleBLEReconnection(sessionIDs: sessionIDs) - } - - guard !Task.isCancelled, - connectionIntent.wantsConnection, - connectionState.isOperational, - self.services === services else { break } - - // Only clear consumed IDs after confirming the loop is still valid. - // Any IDs appended during the await (via teardownSessionForReconnect) survive. - sessionsAwaitingReauth.subtract(sessionIDs) - - await onDeviceSynced?(result.hasCleanRecipientData) - + ended = true + guard self.ownsRuntime(link), self.resyncSlotID == slot, !Task.isCancelled else { break } + _ = await self.completeSync(link, syncResult: result) break } - - if resyncAttemptCount >= Self.maxResyncAttempts { - logger.warning("Resync failed \(Self.maxResyncAttempts) times, disconnecting") + if attempt == Self.maxResyncAttempts { await services.syncCoordinator.endResyncActivity(succeeded: false) - didEndResyncActivity = true - onResyncFailed?() - await disconnect(reason: .resyncFailed) - break + ended = true + guard self.ownsRuntime(link), self.resyncSlotID == slot, !Task.isCancelled else { break } + self.onResyncFailed?(link.snapshot) + Task { @MainActor in + guard self.ownsRuntime(link) else { return } + await self.disconnect(reason: .resyncFailed) + } } } - - // Catch-all for cancellation or guard exits - if !didEndResyncActivity { - await services.syncCoordinator.endResyncActivity(succeeded: false) - } - - // Only nil resyncTask if this task wasn't cancelled. When startResyncLoop() - // is called while a previous loop is running, it cancels the old task and - // assigns a new one. The old task's catch-all must not nil resyncTask or it - // would destroy the replacement. - if !Task.isCancelled { - resyncTask = nil - } + if !ended { await services.syncCoordinator.endResyncActivity(succeeded: false) } } } @@ -220,11 +159,13 @@ extension ConnectionManager { services: ServiceContainer, indices: [UInt8] ) { - guard self.services === services else { return } + guard self.services === services, services.isAcceptingRuntimeWork else { return } let initialIndices = Array(Set(indices)).sorted() guard !initialIndices.isEmpty else { return } - channelRetryTask?.cancel() + cancelChannelRetry() + let slot = UUID() + channelRetrySlotID = slot channelRetryTask = Task { var pendingIndices = initialIndices @@ -242,7 +183,7 @@ extension ConnectionManager { guard connectionIntent.wantsConnection, connectionState.isOperational, - self.services === services else { break } + self.services === services, services.isAcceptingRuntimeWork else { break } logger.info("Channel-only retry \(attempt)/\(Self.maxChannelRetryAttempts) for \(pendingIndices.count) channel(s)") let result = await services.syncCoordinator.retryChannels( @@ -251,6 +192,7 @@ extension ConnectionManager { indices: pendingIndices ) + guard !Task.isCancelled, self.services === services, channelRetrySlotID == slot else { return } if result.isComplete { logger.info("Channel-only retry recovered all pending channels") pendingIndices = [] @@ -264,11 +206,12 @@ extension ConnectionManager { } } - if !Task.isCancelled { + if channelRetrySlotID == slot { if !pendingIndices.isEmpty { logger.warning("Channel-only retry exhausted with \(pendingIndices.count) retryable channel(s) still pending") } channelRetryTask = nil + channelRetrySlotID = nil } } } diff --git a/MC1Services/Sources/MC1Services/Sync/SyncClaim.swift b/MC1Services/Sources/MC1Services/Sync/SyncClaim.swift new file mode 100644 index 0000000000..a34cb63ed9 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Sync/SyncClaim.swift @@ -0,0 +1,4 @@ +enum SyncClaim: Equatable, Sendable { + case ordinary + case advert +} diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+Claims.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+Claims.swift new file mode 100644 index 0000000000..da276f47f4 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+Claims.swift @@ -0,0 +1,110 @@ +extension SyncCoordinator { + /// Exceeds `SessionConfiguration.contactStreamHardTimeout` so large tables can finish, + /// while a stalled advert cannot suspend foreground sync indefinitely. + static let advertContactSyncWaitTimeout: Duration = .seconds(200) + + static let advertContactSyncWaitTimedOutMessage = + "Timed out waiting for background contact sync" + + func claimOrdinarySync() async throws -> Bool { + try await waitForAdvertContactSync() + guard primarySyncClaim == nil else { return false } + primarySyncClaim = .ordinary + return true + } + + func claimAdvertContactSync() -> Bool { + guard primarySyncClaim == nil, !manualContactSyncActive else { return false } + primarySyncClaim = .advert + return true + } + + func releaseSyncClaim() { + primarySyncClaim = nil + let waiters = advertSyncWaiters + advertSyncWaiters = [] + for waiter in waiters { + waiter.continuation.resume() + } + } + + /// Waits for advert ownership to clear; cancellation and timeout leave the claim intact. + func waitForAdvertContactSync( + timeout: Duration? = nil + ) async throws { + let bound = timeout + ?? advertContactSyncWaitTimeoutOverride + ?? Self.advertContactSyncWaitTimeout + let deadline = ContinuousClock.now + bound + + while primarySyncClaim == .advert { + try Task.checkCancellation() + + let remaining = deadline - ContinuousClock.now + if remaining <= .zero { + logger.warning("Timed out waiting for advert contact sync to release claim") + throw SyncCoordinatorError.syncFailed(Self.advertContactSyncWaitTimedOutMessage) + } + + let waiterID = nextAdvertSyncWaiterID + nextAdvertSyncWaiterID &+= 1 + try await waitForAdvertClaimRelease(id: waiterID, timeout: remaining) + } + } + + /// Waits out an advert claim and sets manual inhibition in the same actor turn, + /// so another advert cannot enter between the wait and claim. + func claimManualContactSync( + timeout: Duration? = nil + ) async throws { + try await waitForAdvertContactSync(timeout: timeout) + manualContactSyncActive = true + } + + func releaseManualContactSync() { + manualContactSyncActive = false + } + + func setAdvertContactSyncWaitTimeoutOverride(_ timeout: Duration?) { + advertContactSyncWaitTimeoutOverride = timeout + } + + private func waitForAdvertClaimRelease(id: UInt64, timeout: Duration) async throws { + try await withThrowingTaskGroup(of: Void.self) { group in + group.addTask { + try await self.suspendUntilAdvertClaimReleased(id: id) + } + group.addTask { + try await Task.sleep(for: timeout) + throw SyncCoordinatorError.syncFailed(Self.advertContactSyncWaitTimedOutMessage) + } + try await group.next() + group.cancelAll() + } + } + + private func suspendUntilAdvertClaimReleased(id: UInt64) async throws { + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + if Task.isCancelled { + continuation.resume(throwing: CancellationError()) + return + } + // Claim may have cleared between the while check and registration. + if primarySyncClaim != .advert { + continuation.resume() + return + } + advertSyncWaiters.append(AdvertSyncWaiter(id: id, continuation: continuation)) + } + } onCancel: { + Task { await self.finishAdvertSyncWaiter(id: id, error: CancellationError()) } + } + } + + private func finishAdvertSyncWaiter(id: UInt64, error: Error) { + guard let index = advertSyncWaiters.firstIndex(where: { $0.id == id }) else { return } + let waiter = advertSyncWaiters.remove(at: index) + waiter.continuation.resume(throwing: error) + } +} diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+HandlerHelpers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+HandlerHelpers.swift index 6d6672a9a1..4ec3a51d48 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+HandlerHelpers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+HandlerHelpers.swift @@ -31,6 +31,7 @@ extension SyncCoordinator { do { if let channelIndex { + let rxEntry: RxLogEntryDTO? if let channelDeduplicationKey { let raw = try await dependencies.dataStore.fetchRxLogEntries( radioID: radioID, @@ -38,22 +39,22 @@ extension SyncCoordinator { senderTimestamp: senderTimestamp ) let decoded = await dependencies.rxLogService.decodedEntries(raw) - if let rxEntry = ChannelRXCorrelation.matching( - decoded, - deduplicationKey: channelDeduplicationKey - ).first { - let pathLength = rxEntry.pathLength - let pathNodes = rxEntry.pathNodes - logger.info("Correlated channel message to RxLogEntry: pathLength=\(pathLength), pathNodes=\(pathNodes.count) bytes") - return RxLogLookupResult( - pathNodes: pathNodes, - pathLength: pathLength, - packetHash: rxEntry.packetHash, - routeType: rxEntry.routeType, - regionScope: rxEntry.regionScope, - regionScopeMatches: rxEntry.regionScopeMatches - ) - } + rxEntry = ChannelRXCorrelation.matching(decoded, deduplicationKey: channelDeduplicationKey).first + } else { + rxEntry = nil + } + if let rxEntry { + let pathLength = rxEntry.pathLength + let pathNodes = rxEntry.pathNodes + logger.info("Correlated channel message to RxLogEntry: pathLength=\(pathLength), pathNodes=\(pathNodes.count) bytes") + return RxLogLookupResult( + pathNodes: pathNodes, + pathLength: pathLength, + packetHash: rxEntry.packetHash, + routeType: rxEntry.routeType, + regionScope: rxEntry.regionScope, + regionScopeMatches: rxEntry.regionScopeMatches + ) } logger.warning("No RxLogEntry found for channel \(channelIndex), senderTimestamp: \(senderTimestamp)") } else if let rxEntry = try await dependencies.dataStore.findRxLogEntry( @@ -114,34 +115,27 @@ extension SyncCoordinator { ) } - /// Increments unread counts and posts a notification for a direct message. func updateDMUnreadsAndNotify( messageDTO: MessageDTO, - contactID: UUID, - contact: ContactDTO?, - messageText: String, - hasSelfMention: Bool, - dependencies: SyncDependencies + contact: ContactDTO, + dependencies: SyncDependencies, + scope: ReceiveScope ) async throws { // A mounted conversation does not mean its messages are visible in the background. let isInForeground = await dependencies.appStateProvider?.isInForeground ?? true let activeContactID = await dependencies.notificationService.activeContactID - let isViewingContact = isInForeground && activeContactID == contactID - if !isViewingContact { - try await dependencies.dataStore.incrementUnreadCount(contactID: contactID) - - // Increment unread mention count if message contains self-mention - if hasSelfMention { - try await dependencies.dataStore.incrementUnreadMentionCount(contactID: contactID) - } - } + let isViewingContact = isInForeground && activeContactID == contact.id + guard let current = try await dependencies.dataStore.updateContactAfterDirectMessage( + messageDTO, contact: contact, scope: scope, isViewingContact: isViewingContact + ), !current.isBlocked, scope.isCurrent else { return } await dependencies.notificationService.postDirectMessageNotification( - from: contact?.displayName ?? "Unknown", - contactID: contactID, - messageText: messageText, + from: current.displayName, + contactID: current.id, + messageText: messageDTO.text, messageID: messageDTO.id, - isMuted: contact?.isMuted ?? false + isMuted: current.isMuted, + scope: scope ) await dependencies.notificationService.updateBadgeCount() } @@ -150,14 +144,10 @@ extension SyncCoordinator { func updateChannelUnreadsAndNotify( messageDTO: MessageDTO, channel: ChannelDTO?, - channelIndex: UInt8, - senderNodeName: String?, - messageText: String, - timestamp: UInt32, - hasSelfMention: Bool, - radioID: UUID, - dependencies: SyncDependencies + dependencies: SyncDependencies, + scope: ReceiveScope ) async throws { + guard scope.isCurrent, let channelIndex = messageDTO.channelIndex else { return } if let channelID = channel?.id { // A mounted conversation does not mean its messages are visible in the background. let isInForeground = await dependencies.appStateProvider?.isInForeground ?? true @@ -165,36 +155,43 @@ extension SyncCoordinator { let activeRadioID = await dependencies.notificationService.activeChannelRadioID let isViewingChannel = isInForeground && activeIndex == channel?.index && activeRadioID == channel?.radioID if !isViewingChannel { + guard scope.isCurrent else { return } try await dependencies.dataStore.incrementChannelUnreadCount(channelID: channelID) // Increment unread mention count if message contains self-mention - if hasSelfMention { + if messageDTO.containsSelfMention, scope.isCurrent { try await dependencies.dataStore.incrementChannelUnreadMentionCount(channelID: channelID) } } } + guard scope.isCurrent else { return } if Self.shouldPostChannelNotification(forResolvedChannel: channel) { await dependencies.notificationService.postChannelMessageNotification( channelName: channel?.name ?? "Channel \(channelIndex)", channelIndex: channelIndex, - radioID: radioID, - senderName: senderNodeName, - messageText: messageText, + radioID: messageDTO.radioID, + senderName: messageDTO.senderNodeName, + messageText: messageDTO.text, messageID: messageDTO.id, notificationLevel: channel?.notificationLevel ?? .all, - hasSelfMention: hasSelfMention + hasSelfMention: messageDTO.containsSelfMention, + scope: scope ) - } else { + } else if channel == nil { recordUnresolvedChannel( channelIndex: channelIndex, - radioID: radioID, - senderTimestamp: timestamp + radioID: messageDTO.radioID, + senderTimestamp: messageDTO.reactionTimestamp ) } + guard scope.isCurrent else { return } await dependencies.notificationService.updateBadgeCount() // Broadcast for real-time chat updates - dataEventBroadcaster.yield(.channelMessageReceived(message: messageDTO, channelIndex: channelIndex)) + guard scope.isCurrent else { return } + dataEventBroadcaster.yield(.channelMessageReceived( + message: messageDTO, channelIndex: channelIndex, scope: scope + )) } private func recordUnresolvedChannel( diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift index 6076b606f2..87d4d1d770 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift @@ -28,14 +28,15 @@ extension SyncCoordinator { // MARK: - Contact Message Handler private func wireContactMessageHandler(dependencies: SyncDependencies, radioID: UUID, selfNodeName: String) async { - await dependencies.messagePollingService.setContactMessageHandler { [weak self] message, contact, context in - guard let self else { return } + await dependencies.messagePollingService.setContactMessageHandler { [weak self] message, contact, context, scope, preference in + guard let self, scope.radioID == radioID, scope.isCurrent else { return } await handleIncomingMessage( kind: .direct(message, contact: contact), context: context, dependencies: dependencies, - radioID: radioID, - selfNodeName: selfNodeName + selfNodeName: selfNodeName, + scope: scope, + preference: preference ) } } @@ -43,14 +44,16 @@ extension SyncCoordinator { // MARK: - Channel Message Handler private func wireChannelMessageHandler(dependencies: SyncDependencies, radioID: UUID, selfNodeName: String) async { - await dependencies.messagePollingService.setChannelMessageHandler { [weak self] message, channel, context in - guard let self else { return } + await dependencies.messagePollingService.setChannelMessageHandler { [weak self] message, channel, context, scope, preference, arrivedAt in + guard let self, scope.radioID == radioID, scope.isCurrent else { return } await handleIncomingMessage( kind: .channel(message, channel: channel), + receivedAt: arrivedAt, context: context, dependencies: dependencies, - radioID: radioID, - selfNodeName: selfNodeName + selfNodeName: selfNodeName, + scope: scope, + preference: preference ) } } @@ -78,16 +81,15 @@ extension SyncCoordinator { private func resolveDirectContactIfNeeded( _ kind: IncomingMessageKind, dependencies: SyncDependencies, - radioID: UUID + scope: ReceiveScope ) async -> IncomingMessageKind { guard case let .direct(message, contact) = kind, contact == nil else { return kind } let prefix = message.senderPublicKeyPrefix - guard !prefix.isEmpty else { return kind } - - guard let materialized = await dependencies.advertisementService - .materializeContactForPendingAdvert(matchingPrefix: prefix, radioID: radioID) + guard !prefix.isEmpty, + let materialized = await dependencies.advertisementService + .materializeContactForPendingAdvert(matchingPrefix: prefix, scope: scope) else { return kind } @@ -99,7 +101,8 @@ extension SyncCoordinator { private func harvestAndRefreshChannelMessage( messageDTO: MessageDTO, radioID: UUID, - dependencies: SyncDependencies + dependencies: SyncDependencies, + scope: ReceiveScope ) async throws -> MessageDTO { guard let channelIndex = messageDTO.channelIndex else { return messageDTO } let stamp = messageDTO.senderTimestamp ?? messageDTO.timestamp @@ -110,6 +113,7 @@ extension SyncCoordinator { senderTimestamp: stamp ) let decoded = await dependencies.rxLogService.decodedEntries(raw) + guard scope.isCurrent else { return messageDTO } await dependencies.heardRepeatsService.harvestIncomingPaths( for: messageDTO, decodedCandidates: decoded @@ -125,14 +129,14 @@ extension SyncCoordinator { /// True when a row already owns this content key. A known distinct channel path /// is recorded as an extra; a nil path is unknown and is not written as one. - private func recordArrivalAndSkipDuplicate( - resolvedKind: IncomingMessageKind, + private func recordChannelArrivalAndSkipDuplicate( deduplicationKey: String, radioID: UUID, rxResult: RxLogLookupResult, snr: Double?, receiveTime: Date, - dependencies: SyncDependencies + dependencies: SyncDependencies, + scope: ReceiveScope ) async -> Bool { do { guard let existing = try await dependencies.dataStore.fetchMessage( @@ -141,11 +145,8 @@ extension SyncCoordinator { ) else { return false } - if case .channel = resolvedKind { - guard let path = rxResult.pathNodes else { - logger.info("Skipping duplicate \(resolvedKind.logLabel) message") - return true - } + guard scope.isCurrent else { return true } + if let path = rxResult.pathNodes { await dependencies.heardRepeatsService.recordDistinctPathIfNeeded( message: existing, pathNodes: path, @@ -156,7 +157,7 @@ extension SyncCoordinator { rxLogEntryID: nil ) } - logger.info("Skipping duplicate \(resolvedKind.logLabel) message") + logger.info("Skipping duplicate channel message") return true } catch { logger.warning("Dedup check failed, proceeding with save: \(error)") @@ -169,16 +170,20 @@ extension SyncCoordinator { /// short-circuit, persistence, unread/notification updates, and UI refresh. private func handleIncomingMessage( kind: IncomingMessageKind, + receivedAt: Date = .now, context: DeliveryContext, dependencies: SyncDependencies, - radioID: UUID, - selfNodeName: String + selfNodeName: String, + scope: ReceiveScope, + preference: TextRulesPreference? ) async { + guard scope.isCurrent else { return } + let radioID = scope.radioID // A DM can land in the advert delta-sync debounce window before the local // Contact row exists. Materialize from a pending 0x80 key so unread, // notification, and Chats-list updates use the live path exactly once. let resolvedKind = await resolveDirectContactIfNeeded( - kind, dependencies: dependencies, radioID: radioID + kind, dependencies: dependencies, scope: scope ) // Per-kind wire fields. Channel messages embed the sender as a @@ -221,7 +226,7 @@ extension SyncCoordinator { let timestamp = UInt32(senderTimestampDate.timeIntervalSince1970) // Correct invalid timestamps (sender clock wrong) - let receiveTime = Date() + let receiveTime = receivedAt let (finalTimestamp, timestampCorrected) = Self.correctTimestampIfNeeded(timestamp, receiveTime: receiveTime) if timestampCorrected { logger.debug("Corrected invalid \(resolvedKind.logLabel) message timestamp from \(Date(timeIntervalSince1970: TimeInterval(timestamp))) to \(receiveTime)") @@ -309,52 +314,38 @@ extension SyncCoordinator { regionScopeMatches: rxResult.regionScopeMatches ) - if await recordArrivalAndSkipDuplicate( - resolvedKind: resolvedKind, - deduplicationKey: deduplicationKey, - radioID: radioID, - rxResult: rxResult, - snr: snr, - receiveTime: receiveTime, - dependencies: dependencies - ) { - return - } - - // Stamp before the reaction early return so bodies and reactions both count. - if case let .direct(_, contact) = resolvedKind, let contact { - do { - _ = try await dependencies.dataStore.touchContactHeard( - radioID: radioID, - publicKey: contact.publicKey, - at: Date() - ) - } catch { - logger.error( - "lastHeard stamp failed for inbound DM: \(error.localizedDescription)" - ) - } - } - switch resolvedKind { case let .direct(_, contact): - // Check if this is a DM reaction - if let contact, - await handleDMReaction( - text: text, - contact: contact, - radioID: radioID, - dependencies: dependencies - ) { + await receiveDirectMessage( + messageDTO, wireTextType: textTypeRaw, contact: contact, + scope: scope, preference: preference, dependencies: dependencies + ) + + case let .channel(message, channel): + if await recordChannelArrivalAndSkipDuplicate( + deduplicationKey: deduplicationKey, + radioID: radioID, + rxResult: rxResult, + snr: snr, + receiveTime: receiveTime, + dependencies: dependencies, + scope: scope + ) { return } - case let .channel(message, _): - // Discard messages from blocked senders + guard scope.isCurrent else { return } if isBlockedSender(senderNodeName) { return } - - // Check if this is a reaction + do { + if let channel, try await dependencies.dataStore.shouldSuppressChannelMessage( + messageDTO, frame: message, channel: channel, scope: scope, preference: preference + ) { return } + } catch { + logger.error("Failed to evaluate channel Text Rules: \(error)") + return + } + guard scope.isCurrent else { return } if await handleChannelReaction( text: text, channelIndex: message.channelIndex, @@ -366,58 +357,89 @@ extension SyncCoordinator { ) { return } - } - - do { - try await dependencies.dataStore.saveMessage(messageDTO) - var savedDTO = messageDTO - if case .channel = resolvedKind { - savedDTO = try await harvestAndRefreshChannelMessage( + do { + await runTestBeforeMessageSave(messageDTO) + guard try await dependencies.dataStore.saveReceivedChannelMessage( + messageDTO, scope: scope, conversationID: channel?.textRulesID + ), + scope.isCurrent else { return } + let savedDTO = try await harvestAndRefreshChannelMessage( messageDTO: messageDTO, radioID: radioID, - dependencies: dependencies - ) - } - - switch resolvedKind { - case let .direct(_, contact): - try await indexAndNotifyDirectMessage( - messageDTO: savedDTO, - contact: contact, - messageText: text, - timestamp: timestamp, - hasSelfMention: hasSelfMention, dependencies: dependencies, - radioID: radioID + scope: scope ) - case let .channel(message, channel): try await indexAndNotifyChannelMessage( messageDTO: savedDTO, channel: channel, - channelIndex: message.channelIndex, - senderNodeName: senderNodeName, - messageText: text, - timestamp: timestamp, - hasSelfMention: hasSelfMention, dependencies: dependencies, - radioID: radioID + scope: scope ) + await notifyConversationsChanged(scope: scope) + } catch { + logger.error("Failed to save channel message: \(error)") } + } + } - // Notify conversation list of changes - await notifyConversationsChanged() - - // Broadcast for real-time chat updates - if case let .direct(_, contact) = resolvedKind, let contact { - dataEventBroadcaster.yield(.directMessageReceived(message: savedDTO, contact: contact)) + private func receiveDirectMessage( + _ message: MessageDTO, + wireTextType: UInt8, + contact: ContactDTO?, + scope: ReceiveScope, + preference: TextRulesPreference?, + dependencies: SyncDependencies + ) async { + do { + await runTestBeforeMessageSave(message) + let admission = try await dependencies.dataStore.admitDirectMessage( + message, wireTextType: wireTextType, contact: contact, scope: scope, preference: preference + ) + guard scope.isCurrent else { return } + switch admission { + case .discarded: + return + case let .replay(saved): + logger.debug("Skipping replay of direct message \(saved.id)") + case let .reaction(contact): + await stampDirectMessageContact(contact, message: message, scope: scope, dependencies: dependencies) + _ = await handleDMReaction( + text: message.text, + contact: contact, + radioID: message.radioID, + dependencies: dependencies, + scope: scope + ) + case let .saved(contact): + if let contact { + await stampDirectMessageContact(contact, message: message, scope: scope, dependencies: dependencies) + try await indexAndNotifyDirectMessage( + messageDTO: message, + contact: contact, + dependencies: dependencies, + scope: scope + ) + guard await (try? dependencies.dataStore.currentDirectMessageContact(contact, scope: scope)) != nil, + scope.isCurrent else { return } + dataEventBroadcaster.yield(.directMessageReceived(message: message, contact: contact, scope: scope)) + } + await notifyConversationsChanged(scope: scope) } } catch { - switch resolvedKind { - case .direct: - logger.error("Failed to save contact message: \(error)") - case .channel: - logger.error("Failed to save channel message: \(error)") - } + logger.error("Failed to process incoming direct message: \(error)") + } + } + + private func stampDirectMessageContact( + _ contact: ContactDTO, + message: MessageDTO, + scope: ReceiveScope, + dependencies: SyncDependencies + ) async { + do { + try await dependencies.dataStore.touchDirectMessageContact(contact, scope: scope, at: message.createdAt) + } catch { + logger.error("lastHeard stamp failed for inbound DM: \(error.localizedDescription)") } } @@ -425,55 +447,39 @@ extension SyncCoordinator { /// bookkeeping, and unread/notification updates. private func indexAndNotifyDirectMessage( messageDTO: MessageDTO, - contact: ContactDTO?, - messageText: String, - timestamp: UInt32, - hasSelfMention: Bool, + contact: ContactDTO, dependencies: SyncDependencies, - radioID: UUID + scope: ReceiveScope ) async throws { - // Index DM message for reaction targeting - if let contact { - let pendingMatches = await dependencies.reactionService.indexDMMessage( - id: messageDTO.id, + let pendingMatches = await dependencies.reactionService.indexDMMessage( + id: messageDTO.id, + contactID: contact.id, + text: messageDTO.text, + timestamp: messageDTO.reactionTimestamp + ) + for pending in pendingMatches { + let reactionDTO = ReactionDTO( + messageID: messageDTO.id, + emoji: pending.parsed.emoji, + senderName: pending.senderName, + messageHash: pending.parsed.messageHash, + rawText: pending.rawText, contactID: contact.id, - text: messageText, - timestamp: timestamp + radioID: scope.radioID ) - - // Process pending reactions that now have their target - for pending in pendingMatches { - let reactionDTO = ReactionDTO( - messageID: messageDTO.id, - emoji: pending.parsed.emoji, - senderName: pending.senderName, - messageHash: pending.parsed.messageHash, - rawText: pending.rawText, - contactID: contact.id, - radioID: radioID - ) - if await persistReactionIfNew(reactionDTO, dependencies: dependencies) { - logger.debug("Processed pending DM reaction \(pending.parsed.emoji)") - } - } - } - - // Update contact's last message date - if let contactID = contact?.id { - try await dependencies.dataStore.updateContactLastMessage(contactID: contactID, date: Date()) - } - - // Only increment unread count, post notification, and update badge for non-blocked contacts - if let contactID = contact?.id, contact?.isBlocked != true { - try await updateDMUnreadsAndNotify( - messageDTO: messageDTO, - contactID: contactID, - contact: contact, - messageText: messageText, - hasSelfMention: hasSelfMention, - dependencies: dependencies + await persistReactionIfNew( + reactionDTO, + dependencies: dependencies, + directMessage: pending.directMessage ?? (scope, contact) ) } + + try await updateDMUnreadsAndNotify( + messageDTO: messageDTO, + contact: contact, + dependencies: dependencies, + scope: scope + ) } /// Post-save side effects for a channel message: reaction indexing, channel @@ -481,27 +487,22 @@ extension SyncCoordinator { private func indexAndNotifyChannelMessage( messageDTO: MessageDTO, channel: ChannelDTO?, - channelIndex: UInt8, - senderNodeName: String?, - messageText: String, - timestamp: UInt32, - hasSelfMention: Bool, dependencies: SyncDependencies, - radioID: UUID + scope: ReceiveScope ) async throws { - // Index message for reaction matching and process any pending reactions - // Use original timestamp for indexing so pending reactions can match - if let senderName = senderNodeName { + guard scope.isCurrent, let channelIndex = messageDTO.channelIndex else { return } + // Use the sender timestamp so pending reactions match corrected-clock messages. + if let senderName = messageDTO.senderNodeName { let pendingMatches = await dependencies.reactionService.indexMessage( id: messageDTO.id, channelIndex: channelIndex, senderName: senderName, - text: messageText, - timestamp: timestamp + text: messageDTO.text, + timestamp: messageDTO.reactionTimestamp ) - // Process any pending reactions that now have their target for pending in pendingMatches { + guard scope.isCurrent else { return } let reactionDTO = ReactionDTO( messageID: messageDTO.id, emoji: pending.parsed.emoji, @@ -515,23 +516,17 @@ extension SyncCoordinator { } } - // Update channel's last message date + guard scope.isCurrent else { return } if let channelID = channel?.id { try await dependencies.dataStore.updateChannelLastMessage(channelID: channelID, date: Date()) } - // Only update unread count, badges, and notify UI for non-blocked senders - if !isBlockedSender(senderNodeName) { + if !isBlockedSender(messageDTO.senderNodeName) { try await updateChannelUnreadsAndNotify( messageDTO: messageDTO, channel: channel, - channelIndex: channelIndex, - senderNodeName: senderNodeName, - messageText: messageText, - timestamp: timestamp, - hasSelfMention: hasSelfMention, - radioID: radioID, - dependencies: dependencies + dependencies: dependencies, + scope: scope ) } } @@ -539,50 +534,50 @@ extension SyncCoordinator { // MARK: - Signed Message Handler private func wireSignedMessageHandler(dependencies: SyncDependencies) async { - await dependencies.messagePollingService.setSignedMessageHandler { [weak self] message, _ in + await dependencies.messagePollingService.setSignedMessageHandler { [weak self] message, scope in guard let self else { return } - await handleIncomingSignedMessage(message, dependencies: dependencies) + await handleIncomingSignedMessage(message, scope: scope, dependencies: dependencies) } } - /// Persists a signed room message via `RoomServerService`, then posts the - /// notification and refreshes the UI when the message was new. - private func handleIncomingSignedMessage(_ message: ContactMessage, dependencies: SyncDependencies) async { - // For signed room messages, the signature contains the 4-byte author key prefix + private func handleIncomingSignedMessage( + _ message: ContactMessage, + scope: ReceiveScope, + dependencies: SyncDependencies + ) async { + // For signed room messages, the signature contains the 4-byte author key prefix. guard let authorPrefix = message.signature?.prefix(4), authorPrefix.count == 4 else { logger.warning("Dropping signed message: missing or invalid author prefix") return } let timestamp = UInt32(message.senderTimestamp.timeIntervalSince1970) - do { - let savedMessage = try await dependencies.roomServerService.handleIncomingMessage( - senderPublicKeyPrefix: message.senderPublicKeyPrefix, - timestamp: timestamp, - authorPrefix: Data(authorPrefix), - text: message.text + guard let saved = try await dependencies.roomServerService.handleIncomingMessage( + senderPublicKeyPrefix: message.senderPublicKeyPrefix, + timestamp: timestamp, + authorPrefix: Data(authorPrefix), + text: message.text, + scope: scope + ), let room = try await dependencies.dataStore.fetchRemoteNodeSession(id: saved.room.id), + room.radioID == saved.room.radioID, + room.textRulesID == saved.room.textRulesID, + scope.isCurrent else { return } + + await dependencies.notificationService.postRoomMessageNotification( + roomName: room.name, + sessionID: saved.message.sessionID, + senderName: saved.message.authorName, + messageText: saved.message.text, + messageID: saved.message.id, + notificationLevel: room.notificationLevel, + scope: scope ) - - // If message was saved (not a duplicate), notify UI and post notification - if let savedMessage { - // Fetch session for room name and mute status - let session = try? await dependencies.dataStore.fetchRemoteNodeSession(id: savedMessage.sessionID) - - // Post notification for room message - await dependencies.notificationService.postRoomMessageNotification( - roomName: session?.name ?? "Room", - sessionID: savedMessage.sessionID, - senderName: savedMessage.authorName, - messageText: savedMessage.text, - messageID: savedMessage.id, - notificationLevel: session?.notificationLevel ?? .all - ) - await dependencies.notificationService.updateBadgeCount() - - await notifyConversationsChanged() - dataEventBroadcaster.yield(.roomMessageReceived(savedMessage)) - } + guard scope.isCurrent else { return } + await dependencies.notificationService.updateBadgeCount() + await notifyConversationsChanged(scope: scope) + guard scope.isCurrent else { return } + dataEventBroadcaster.yield(.roomMessageReceived(saved.message, roomID: room.textRulesID, scope: scope)) } catch { logger.error("Failed to handle room message: \(error)") } @@ -693,9 +688,11 @@ extension SyncCoordinator { /// Cancels the discovery event task so it releases the service references /// it captures. Called by `ServiceContainer.tearDown()`. - func cancelDiscoveryEventMonitoring() { - discoveryEventsTask?.cancel() + func cancelDiscoveryEventMonitoring() async { + let worker = discoveryEventsTask discoveryEventsTask = nil + worker?.cancel() + await worker?.value } // MARK: - Static Helpers diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift index 2682f749cb..5d4a292817 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift @@ -13,7 +13,8 @@ extension SyncCoordinator { @discardableResult func persistReactionIfNew( _ reactionDTO: ReactionDTO, - dependencies: SyncDependencies + dependencies: SyncDependencies, + directMessage: (scope: ReceiveScope, contact: ContactDTO)? = nil ) async -> Bool { let exists = try? await dependencies.dataStore.reactionExists( messageID: reactionDTO.messageID, @@ -25,9 +26,17 @@ extension SyncCoordinator { if let result = await dependencies.reactionService.persistReactionAndUpdateSummary( reactionDTO, - using: dependencies.dataStore + using: dependencies.dataStore, + directMessage: directMessage ) { - dataEventBroadcaster.yield(.reactionReceived(messageID: result.messageID, summary: result.summary)) + if let (scope, contact) = directMessage { + guard await (try? dependencies.dataStore.currentDirectMessageContact(contact, scope: scope)) != nil, + scope.isCurrent else { return false } + } + dataEventBroadcaster.yield(.reactionReceived( + messageID: result.messageID, summary: result.summary, + scope: directMessage?.scope, contact: directMessage?.contact + )) } return true @@ -40,8 +49,12 @@ extension SyncCoordinator { text: String, contact: ContactDTO, radioID: UUID, - dependencies: SyncDependencies + dependencies: SyncDependencies, + scope: ReceiveScope? = nil ) async -> Bool { + guard scope?.isCurrent != false else { return true } + let directMessage = scope.map { (scope: $0, contact: contact) } + // Try meshcore-open v3 format if let mcoReaction = MeshCoreOpenReactionParser.parse(text) { return await handleMCODMReaction( @@ -49,7 +62,8 @@ extension SyncCoordinator { rawText: text, contact: contact, radioID: radioID, - dependencies: dependencies + dependencies: dependencies, + directMessage: directMessage ) } @@ -60,7 +74,8 @@ extension SyncCoordinator { rawText: text, contact: contact, radioID: radioID, - dependencies: dependencies + dependencies: dependencies, + directMessage: directMessage ) } @@ -80,7 +95,7 @@ extension SyncCoordinator { contactID: contact.id, radioID: radioID ) - if await persistReactionIfNew(reactionDTO, dependencies: dependencies) { + if await persistReactionIfNew(reactionDTO, dependencies: dependencies, directMessage: directMessage) { logger.debug("Saved DM reaction \(parsed.emoji) to message \(targetMessageID)") } @@ -106,7 +121,7 @@ extension SyncCoordinator { contactID: contact.id, radioID: radioID ) - if await persistReactionIfNew(reactionDTO, dependencies: dependencies) { + if await persistReactionIfNew(reactionDTO, dependencies: dependencies, directMessage: directMessage) { logger.debug("Saved DM reaction \(parsed.emoji) to message \(targetMessage.id) (from DB)") } @@ -119,7 +134,8 @@ extension SyncCoordinator { contactID: contact.id, senderName: contact.displayName, rawText: text, - radioID: radioID + radioID: radioID, + directMessage: directMessage ) logger.debug("Queued pending DM reaction \(parsed.emoji)") @@ -269,7 +285,8 @@ extension SyncCoordinator { rawText: String, contact: ContactDTO, radioID: UUID, - dependencies: SyncDependencies + dependencies: SyncDependencies, + directMessage: (scope: ReceiveScope, contact: ContactDTO)? ) async -> Bool { let timestampWindow = reactionTimestampWindow() @@ -304,7 +321,7 @@ extension SyncCoordinator { contactID: contact.id, radioID: radioID ) - if await persistReactionIfNew(reactionDTO, dependencies: dependencies) { + if await persistReactionIfNew(reactionDTO, dependencies: dependencies, directMessage: directMessage) { logger.debug("Saved MCO DM reaction \(mcoReaction.emoji) to message \(candidate.id)") } return true @@ -386,7 +403,8 @@ extension SyncCoordinator { rawText: String, contact: ContactDTO, radioID: UUID, - dependencies: SyncDependencies + dependencies: SyncDependencies, + directMessage: (scope: ReceiveScope, contact: ContactDTO)? ) async -> Bool { let timestampWindow = reactionTimestampWindow( anchor: v1Reaction.timestampSeconds @@ -417,7 +435,7 @@ extension SyncCoordinator { contactID: contact.id, radioID: radioID ) - if await persistReactionIfNew(reactionDTO, dependencies: dependencies) { + if await persistReactionIfNew(reactionDTO, dependencies: dependencies, directMessage: directMessage) { logger.debug("Saved MCO v1 DM reaction \(v1Reaction.emoji) to message \(candidate.id)") } return true diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+Sync.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+Sync.swift index 2a26919fe7..c8505e64f7 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+Sync.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+Sync.swift @@ -29,15 +29,6 @@ extension SyncCoordinator { /// normal drift. static let contactWatermarkPlausibilitySkew: TimeInterval = 2 * 24 * 60 * 60 - /// Bound for waiting out an advert-owned contact-sync claim. - /// Above `SessionConfiguration.contactStreamHardTimeout` (180s) so a large - /// contact table can finish streaming, but a wedged wait cannot hang forever. - static let advertContactSyncWaitTimeout: Duration = .seconds(200) - - /// Developer-facing reason when the advert claim wait hits its bound. - static let advertContactSyncWaitTimedOutMessage = - "Timed out waiting for background contact sync" - /// How to use a stored contact-sync watermark for one fetch round. /// Does not rewrite storage — only decides the `since` filter for this round. enum ContactWatermarkUse: Equatable, Sendable { @@ -114,16 +105,11 @@ extension SyncCoordinator { channelSyncConfig: ChannelSyncConfig = .none, platformName: String = "unknown" ) async throws -> FullSyncResult { - try await waitForAdvertContactSync() - - // Prevent concurrent syncs — actor-local flag avoids the TOCTOU window - // that existed when guarding via `await state.isSyncing` - guard !isSyncInProgress else { + guard try await claimOrdinarySync() else { logger.warning("performFullSync called while already syncing, ignoring duplicate") return .skipped } - isSyncInProgress = true - defer { isSyncInProgress = false } + defer { releaseSyncClaim() } return try await runFullSync( radioID: radioID, @@ -140,10 +126,7 @@ extension SyncCoordinator { ) } - /// Full-sync body without the `isSyncInProgress` claim. Callers must hold - /// the claim already: `performFullSync` takes it per call, while - /// `onConnectionEstablished` claims it before its handler-wiring awaits so - /// racing connection setups cannot double-wire. + /// Requires an ordinary claim; connection setup also holds it while wiring handlers. private func runFullSync( radioID: UUID, dataStore: any PersistenceStoreProtocol, @@ -353,17 +336,12 @@ extension SyncCoordinator { ) async throws -> FullSyncResult { logger.info("Connection established for device \(radioID)") - try await waitForAdvertContactSync() - - // Claim synchronously before the wiring awaits below. A read-only guard - // let two racing calls (rapid auto-reconnect cycles) both pass and - // double-wire handlers; the claim makes the loser skip immediately. - guard !isSyncInProgress else { + // Claim before handler wiring suspends so concurrent setup cannot double-wire. + guard try await claimOrdinarySync() else { logger.warning("onConnectionEstablished called while already syncing, ignoring duplicate") return .skipped } - isSyncInProgress = true - defer { isSyncInProgress = false } + defer { releaseSyncClaim() } // Suppress message notifications during sync to avoid flooding user on reconnect // Unread counts and badges still update - only system notifications are suppressed @@ -469,15 +447,12 @@ extension SyncCoordinator { "[Sync] onDisconnected called - syncState: \(String(describing: currentState)), hasEndedSyncActivity: \(hasEndedSyncActivity)" ) - // Safety net: clear sync guard flags on disconnect and wake any waiters so - // pull-to-refresh / full-sync cannot stay suspended after the connection drops. - if isSyncInProgress { - logger.warning("isSyncInProgress still true at disconnect — clearing as safety net") + // Wake waiters so refresh cannot stay suspended after the connection drops. + if primarySyncClaim != nil { + logger.warning("Sync claim still held at disconnect — releasing as safety net") } - isSyncInProgress = false - advertContactSyncActive = false - manualContactSyncActive = false - resumeAllAdvertSyncWaiters() + releaseSyncClaim() + releaseManualContactSync() // The next session must prove its own full contact fetch before delta sync runs. fullContactSyncCompletedRadioID = nil @@ -799,145 +774,19 @@ extension SyncCoordinator { return contactResult } - /// Suspends while an advert-driven delta sync holds the claim. - /// - /// Background advert work must not turn a full sync, connection setup, or - /// channel-only retry into a silent skip, and must not interleave its - /// `ContactServiceEvent.syncProgress` events with a user-initiated refresh. - /// - /// Throws `CancellationError` when the calling task is cancelled, and - /// `SyncCoordinatorError.syncFailed` when `timeout` elapses while the claim - /// is still held. On timeout the caller must not proceed into the radio - /// pipeline (that races progress events) and must not return a silent skip - /// for user-initiated work (the wait exists to stop that). Surface an error - /// so the spinner stops and the user can retry. - func waitForAdvertContactSync( - timeout: Duration? = nil - ) async throws { - let bound = timeout - ?? advertContactSyncWaitTimeoutOverride - ?? Self.advertContactSyncWaitTimeout - let deadline = ContinuousClock.now + bound - - while isSyncInProgress, advertContactSyncActive { - try Task.checkCancellation() - - let remaining = deadline - ContinuousClock.now - if remaining <= .zero { - logger.warning("Timed out waiting for advert contact sync to release claim") - throw SyncCoordinatorError.syncFailed(Self.advertContactSyncWaitTimedOutMessage) - } - - let waiterID = nextAdvertSyncWaiterID - nextAdvertSyncWaiterID &+= 1 - try await waitForAdvertClaimRelease(id: waiterID, timeout: remaining) - } - } - - /// Waits out an advert claim, then marks a user-initiated contact refresh - /// active in the same actor turn so no delta can interleave between observe - /// and claim (separate wait and claim hops leave that window). - func claimManualContactSync( - timeout: Duration? = nil - ) async throws { - try await waitForAdvertContactSync(timeout: timeout) - manualContactSyncActive = true - } - - /// Marks a user-initiated contact refresh so advert delta sync returns `.busy`. - func setManualContactSyncActive(_ active: Bool) { - manualContactSyncActive = active - } - - /// Test hook: shortens the advert claim wait bound used by default parameters. - func setAdvertContactSyncWaitTimeoutOverride(_ timeout: Duration?) { - advertContactSyncWaitTimeoutOverride = timeout - } - - /// Suspends until the advert claim clears, the wait is cancelled, or `timeout` elapses. - private func waitForAdvertClaimRelease(id: UInt64, timeout: Duration) async throws { - try await withThrowingTaskGroup(of: Void.self) { group in - group.addTask { - try await self.suspendUntilAdvertClaimReleased(id: id) - } - group.addTask { - try await Task.sleep(for: timeout) - throw SyncCoordinatorError.syncFailed(Self.advertContactSyncWaitTimedOutMessage) - } - // First finisher wins: claim release, cancel, or timeout. - try await group.next() - group.cancelAll() - } - } - - /// Parks one waiter until resume, cancel, or timeout-driven cancellation. - private func suspendUntilAdvertClaimReleased(id: UInt64) async throws { - try await withTaskCancellationHandler { - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - if Task.isCancelled { - continuation.resume(throwing: CancellationError()) - return - } - // Claim may have cleared between the while check and registration. - if !(isSyncInProgress && advertContactSyncActive) { - continuation.resume() - return - } - advertSyncWaiters.append(AdvertSyncWaiter(id: id, continuation: continuation)) - } - } onCancel: { - Task { await self.finishAdvertSyncWaiter(id: id, error: CancellationError()) } - } - } - - /// Resumes one waiter if it is still registered (cancel/timeout path). - private func finishAdvertSyncWaiter(id: UInt64, error: Error) { - guard let index = advertSyncWaiters.firstIndex(where: { $0.id == id }) else { return } - let waiter = advertSyncWaiters.remove(at: index) - waiter.continuation.resume(throwing: error) - } - - /// Resumes every advert-claim waiter. Used when the claim clears or on disconnect. - private func resumeAllAdvertSyncWaiters() { - let waiters = advertSyncWaiters - advertSyncWaiters = [] - for waiter in waiters { - waiter.continuation.resume() - } - } - - /// Advert-driven contact delta sync. Claims `isSyncInProgress` as advert-owned - /// so full sync waits rather than skips. - /// - /// Both modes need proof that a full contact fetch already succeeded for this - /// radio. Without it, writing a watermark here would make later full syncs - /// incremental and leave ghost contacts the device no longer has. An empty - /// radio stamps no watermark, so a completed full fetch grants entry on its - /// own and the round fetches from epoch zero until the first contact stamps one. - /// - /// - Parameter fullRefetch: When true, uses the epoch-0 prune-free full fetch. - /// When false, uses the stored watermark. + /// Requires a prior full contact fetch so advert watermarks cannot bypass initial pruning. + /// `fullRefetch` reads from epoch zero without pruning; an empty completed full fetch also admits adverts. func performAdvertContactSync( fullRefetch: Bool, radioID: UUID, dataStore: any PersistenceStoreProtocol, contactService: some ContactServiceProtocol ) async -> AdvertContactSyncOutcome { - guard !manualContactSyncActive else { - logger.info("Advert contact sync deferred because a manual contact refresh is active") - return .busy - } - guard !isSyncInProgress else { - logger.info("Advert contact sync deferred because sync is already active") + guard claimAdvertContactSync() else { + logger.info("Advert contact sync deferred because sync or a manual contact refresh is active") return .busy } - isSyncInProgress = true - advertContactSyncActive = true - defer { - isSyncInProgress = false - advertContactSyncActive = false - resumeAllAdvertSyncWaiters() - } + defer { releaseSyncClaim() } do { let device = try await dataStore.fetchDevice(radioID: radioID) @@ -1011,7 +860,19 @@ extension SyncCoordinator { } do { - try await waitForAdvertContactSync() + guard try await claimOrdinarySync() else { + logger.info("Channel-only retry skipped because sync is already active") + return ChannelSyncResult( + channelsSynced: 0, + errors: indices.map { + ChannelSyncError( + index: $0, + errorType: .circuitBreaker, + description: "Skipped because sync is already active" + ) + } + ) + } } catch is CancellationError { return ChannelSyncResult( channelsSynced: 0, @@ -1033,22 +894,7 @@ extension SyncCoordinator { ) } - guard !isSyncInProgress else { - logger.info("Channel-only retry skipped because sync is already active") - return ChannelSyncResult( - channelsSynced: 0, - errors: indices.map { - ChannelSyncError( - index: $0, - errorType: .circuitBreaker, - description: "Skipped because sync is already active" - ) - } - ) - } - - isSyncInProgress = true - defer { isSyncInProgress = false } + defer { releaseSyncClaim() } logger.info("[Sync] State → .syncing(.channels) (channel-only retry)") await setState(.syncing(progress: SyncProgress(phase: .channels, current: 0, total: indices.count))) diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator.swift index 43882abdee..f329989c8d 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator.swift @@ -120,18 +120,11 @@ public actor SyncCoordinator { let logger = PersistentLogger(subsystem: "com.mc1", category: "SyncCoordinator") - /// Actor-local guard against concurrent sync execution. - /// Checked and set synchronously (no `await`) to eliminate the TOCTOU window - /// that existed when guarding via the `@MainActor`-isolated `state` property. - var isSyncInProgress = false - - /// True while `performAdvertContactSync` holds `isSyncInProgress`. Full sync, - /// connection setup, and channel-only retry wait for this claim instead of skipping. - var advertContactSyncActive = false - - /// True while a user-initiated contact refresh holds the radio pipeline. - /// Advert delta sync returns `.busy` so it retries on the debounce rather - /// than racing progress events with pull-to-refresh. + /// Actor-local ownership, claimed synchronously before sync work suspends. + var primarySyncClaim: SyncClaim? + + /// Inhibits advert sync during manual refresh so their progress events cannot interleave. + /// Ordinary sync admission is independent of this inhibition. var manualContactSyncActive = false /// Continuations held by `waitForAdvertContactSync` until the advert claim clears. @@ -251,6 +244,13 @@ public actor SyncCoordinator { /// Nil stands in for a thrown sync. A completed result keeps its eligibility. var performResyncOverride: ((_ radioID: UUID, _ dependencies: SyncDependencies) async -> FullSyncResult?)? + /// Runs immediately before the real message save. Nil leaves that save unchanged. + var testBeforeMessageSave: (@Sendable (MessageDTO) async -> Void)? + + func setTestBeforeMessageSave(_ hook: (@Sendable (MessageDTO) async -> Void)?) { + testBeforeMessageSave = hook + } + /// Sets the test override for `performResync`. func setPerformResyncOverride( _ override: @escaping @Sendable (_ radioID: UUID, _ dependencies: SyncDependencies) async -> FullSyncResult? @@ -259,6 +259,13 @@ public actor SyncCoordinator { } #endif + /// Parks an admitted save when a test hook is installed. Release builds return immediately. + func runTestBeforeMessageSave(_ message: MessageDTO) async { + #if DEBUG + await testBeforeMessageSave?(message) + #endif + } + // MARK: - Initialization init() {} @@ -365,7 +372,10 @@ public actor SyncCoordinator { /// Notify that conversations data changed (triggers UI refresh) @MainActor - public func notifyConversationsChanged() { + public func notifyConversationsChanged( + scope: ReceiveScope? = nil + ) { + guard scope?.isCurrent != false else { return } conversationsVersion += 1 dataEventBroadcaster.yield(.conversationsChanged) } diff --git a/MC1Services/Sources/MC1Services/Sync/SyncDataEvent.swift b/MC1Services/Sources/MC1Services/Sync/SyncDataEvent.swift index b06850dba2..d46fad8ad8 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncDataEvent.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncDataEvent.swift @@ -12,11 +12,15 @@ public enum SyncDataEvent: Sendable { /// Conversations data changed; observers should reload chat lists. case conversationsChanged /// An incoming direct message was persisted for a known contact. - case directMessageReceived(message: MessageDTO, contact: ContactDTO) + case directMessageReceived(message: MessageDTO, contact: ContactDTO, scope: ReceiveScope) /// An incoming channel message was persisted. - case channelMessageReceived(message: MessageDTO, channelIndex: UInt8) + case channelMessageReceived( + message: MessageDTO, channelIndex: UInt8, scope: ReceiveScope + ) /// An incoming signed room message was persisted. - case roomMessageReceived(RoomMessageDTO) + case roomMessageReceived(RoomMessageDTO, roomID: UUID?, scope: ReceiveScope) /// A reaction was persisted and its target message's summary updated. - case reactionReceived(messageID: UUID, summary: String) + case reactionReceived( + messageID: UUID, summary: String, scope: ReceiveScope? = nil, contact: ContactDTO? = nil + ) } diff --git a/MC1Services/Sources/MC1Services/Transport/BLEIngressDiagnostics.swift b/MC1Services/Sources/MC1Services/Transport/BLEIngressDiagnostics.swift new file mode 100644 index 0000000000..207fbb2d7b --- /dev/null +++ b/MC1Services/Sources/MC1Services/Transport/BLEIngressDiagnostics.swift @@ -0,0 +1,18 @@ +import Foundation + +/// Counts transport ingress before protocol parsing, scoped to one installed receive stream. +struct BLEIngressDiagnostics: Sendable, Equatable { + let deviceID: UUID + let instanceID: String + let connectionGeneration: UInt64 + let streamSequence: UInt64 + let binding: String? + var acceptedFrames = 0 + var droppedFrames = 0 + var rejectedFrames = 0 + var terminatedFrames = 0 + + var context: String { + "device=\(deviceID.uuidString.prefix(8)) instance=\(instanceID) generation=\(connectionGeneration) stream=\(streamSequence) binding=\(binding ?? "none")" + } +} diff --git a/MC1Services/Sources/MC1Services/Transport/BLELifecycleEvent.swift b/MC1Services/Sources/MC1Services/Transport/BLELifecycleEvent.swift new file mode 100644 index 0000000000..fecd561d8a --- /dev/null +++ b/MC1Services/Sources/MC1Services/Transport/BLELifecycleEvent.swift @@ -0,0 +1,16 @@ +import Foundation + +public enum BLELifecycleEvent: Sendable { + case autoReconnecting(BLELifecycleOrigin, errorInfo: String) + case reconnected(BLELifecycleOrigin) + case disconnected(BLELifecycleOrigin, error: BLEError?) + case remoteLinkLost(BLELifecycleOrigin) + + public var origin: BLELifecycleOrigin { + switch self { + case let .autoReconnecting(origin, _), let .reconnected(origin), + let .disconnected(origin, _), let .remoteLinkLost(origin): + origin + } + } +} diff --git a/MC1Services/Sources/MC1Services/Transport/BLELifecycleOrigin.swift b/MC1Services/Sources/MC1Services/Transport/BLELifecycleOrigin.swift new file mode 100644 index 0000000000..36eb757f42 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Transport/BLELifecycleOrigin.swift @@ -0,0 +1,14 @@ +import Foundation + +/// Physical provenance captured when the BLE actor accepts a lifecycle event. +public struct BLELifecycleOrigin: Sendable, Equatable { + public let deviceID: UUID + public let generation: UInt64 + public let eventTime: CFAbsoluteTime + + public init(deviceID: UUID, generation: UInt64, eventTime: CFAbsoluteTime) { + self.deviceID = deviceID + self.generation = generation + self.eventTime = eventTime + } +} diff --git a/MC1Services/Sources/MC1Services/Transport/BLEOperationClock.swift b/MC1Services/Sources/MC1Services/Transport/BLEOperationClock.swift new file mode 100644 index 0000000000..f0416bcad0 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Transport/BLEOperationClock.swift @@ -0,0 +1,10 @@ +/// Keeps write pacing and operation deadlines on the same monotonic time source. +struct BLEOperationClock: Sendable { + let now: @Sendable () -> ContinuousClock.Instant + let sleep: @Sendable (Duration) async throws -> Void + + static let continuous = BLEOperationClock( + now: { .now }, + sleep: { try await Task.sleep(for: $0) } + ) +} diff --git a/MC1Services/Sources/MC1Services/Transport/BLEStateMachine+CBDelegate.swift b/MC1Services/Sources/MC1Services/Transport/BLEStateMachine+CBDelegate.swift index 89ac809a38..7122456e79 100644 --- a/MC1Services/Sources/MC1Services/Transport/BLEStateMachine+CBDelegate.swift +++ b/MC1Services/Sources/MC1Services/Transport/BLEStateMachine+CBDelegate.swift @@ -5,23 +5,8 @@ import os // MARK: - Delegate Handler -/// Bridges CoreBluetooth delegate callbacks to the actor. -/// -/// This class is necessary because actors cannot directly conform to -/// Objective-C delegate protocols. All callbacks dispatch to the actor. -/// -/// ## Callback ordering (C11) -/// Control callbacks (didConnect, didDiscoverServices, etc.) are forwarded via -/// unstructured `Task {}`, which does not guarantee FIFO ordering on the actor. -/// This is safe because each handler validates the expected phase before proceeding. -/// An out-of-order callback (e.g., didDiscoverServices arriving before didConnect -/// has been processed) will fail the phase guard and be ignored. The timeout -/// mechanism will then retry the operation. -/// -/// For data reception (`didUpdateValueFor`), data is yielded directly to an AsyncStream -/// continuation rather than spawning Tasks. This preserves the ordering guaranteed by -/// the serial CBCentralManager queue, avoiding the race conditions that occur when -/// multiple unstructured Tasks compete for actor access with priority-based scheduling. +/// Validates native callback origins before forwarding control events to the actor. +/// Receive values yield under the ingress lock on the serial central queue to preserve order. final class BLEDelegateHandler: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate, @unchecked Sendable { weak var stateMachine: BLEStateMachine? @@ -29,35 +14,85 @@ final class BLEDelegateHandler: NSObject, CBCentralManagerDelegate, CBPeripheral /// Lock-protected continuation for yielding received data directly. /// Using OSAllocatedUnfairLock ensures thread-safe access from the CBCentralManager queue. - private let dataContinuationLock = OSAllocatedUnfairLock.Continuation?>(initialState: nil) - - /// FIFO of sequence numbers for `.withResponse` writes issued but not yet - /// acknowledged. CoreBluetooth delivers exactly one `didWriteValueFor` per - /// write request, in issue order, on the serial queue, so popping the head - /// tags each callback with the sequence of the write that produced it. - /// Tagging at write time (not delivery time) lets a callback that arrives - /// after its write already timed out be recognized as the old write instead - /// of being mistaken for the current one. - private let issuedWriteSequencesLock = OSAllocatedUnfairLock<[UInt64]>(initialState: []) - - /// Records a write's sequence as issued. The actor calls this immediately - /// before `writeValue` so the callback can never outrun the record. - func recordIssuedWriteSequence(_ sequence: UInt64) { - issuedWriteSequencesLock.withLock { $0.append(sequence) } - } - - /// Drops all recorded write sequences. Called when pending writes are - /// cancelled (disconnect, auto-reconnect teardown), where the outstanding - /// callbacks either never arrive or no longer have a continuation; a stale - /// entry left behind would mis-tag the next connection's first callback. + private struct Ingress: Sendable { + let continuation: AsyncStream.Continuation + let peripheral: ObjectIdentifier + let characteristic: ObjectIdentifier + var diagnostics: BLEIngressDiagnostics + } + + private let dataContinuationLock = OSAllocatedUnfairLock(initialState: nil) + private static let ingressReportInterval = 64 + + private struct IssuedWrite: Sendable { + let sequence: UInt64 + let peripheral: ObjectIdentifier + let characteristic: ObjectIdentifier + } + + /// Validate native origin before consuming the issued-write order. + private let issuedWriteSequencesLock = OSAllocatedUnfairLock<[IssuedWrite]>(initialState: []) + + func recordIssuedWriteSequence(_ sequence: UInt64, peripheral: CBPeripheral, characteristic: CBCharacteristic) { + let write = IssuedWrite( + sequence: sequence, peripheral: ObjectIdentifier(peripheral), characteristic: ObjectIdentifier(characteristic) + ) + issuedWriteSequencesLock.withLock { $0.append(write) } + } + func clearIssuedWriteSequences() { issuedWriteSequencesLock.withLock { $0.removeAll() } } - /// Sets the data continuation for direct yielding from delegate callbacks. - /// Call this when transitioning to connected state. - func setDataContinuation(_ continuation: AsyncStream.Continuation?) { - dataContinuationLock.withLock { $0 = continuation } + var ingressDiagnostics: BLEIngressDiagnostics? { + dataContinuationLock.withLock { $0?.diagnostics } + } + + func setDataContinuation( + _ continuation: AsyncStream.Continuation, + peripheral: CBPeripheral, + characteristic: CBCharacteristic, + instanceID: String, + generation: UInt64, + streamSequence: UInt64, + binding: String? + ) { + let ingress = Ingress( + continuation: continuation, + peripheral: ObjectIdentifier(peripheral), + characteristic: ObjectIdentifier(characteristic), + diagnostics: BLEIngressDiagnostics( + deviceID: peripheral.identifier, instanceID: instanceID, connectionGeneration: generation, + streamSequence: streamSequence, binding: binding + ) + ) + let previous = dataContinuationLock.withLock { current in + defer { current = ingress } + return current?.diagnostics + } + reportFinishedIngress(previous) + logger.info("[BLE] Ingress installed \(ingress.diagnostics.context)") + } + + func clearDataContinuation() { + let previous = dataContinuationLock.withLock { current in + defer { current = nil } + return current?.diagnostics + } + reportFinishedIngress(previous) + } + + private func reportFinishedIngress(_ diagnostics: BLEIngressDiagnostics?) { + guard let diagnostics else { return } + logger.info("[BLE] Ingress finished \(diagnostics.context) accepted=\(diagnostics.acceptedFrames) dropped=\(diagnostics.droppedFrames) rejected=\(diagnostics.rejectedFrames) terminated=\(diagnostics.terminatedFrames)") + } + + private func generation(for peripheral: CBPeripheral) -> UInt64? { + let origin = ObjectIdentifier(peripheral) + return dataContinuationLock.withLock { ingress in + guard ingress?.peripheral == origin else { return nil } + return ingress?.diagnostics.connectionGeneration + } } // MARK: - CBCentralManagerDelegate @@ -68,13 +103,17 @@ final class BLEDelegateHandler: NSObject, CBCentralManagerDelegate, CBPeripheral } func centralManager(_ central: CBCentralManager, willRestoreState dict: [String: Any]) { - guard let sm = stateMachine else { return } // Extract peripheral synchronously before crossing actor boundary guard let peripherals = dict[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral], let peripheral = peripherals.first else { return } - Task { await sm.handleWillRestoreState(peripheral) } + _ = restoreState(from: peripheral) + } + + func restoreState(from peripheral: CBPeripheral) -> Task? { + guard let sm = stateMachine else { return nil } + return Task { await sm.handleWillRestoreState(peripheral) } } func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, @@ -137,29 +176,81 @@ final class BLEDelegateHandler: NSObject, CBCentralManagerDelegate, CBPeripheral logger.debug("[BLE] didUpdateValueFor: empty data from \(peripheral.identifier.uuidString.prefix(8)), char: \(characteristic.uuid.uuidString.prefix(8))") return } - _ = dataContinuationLock.withLock { $0?.yield(data) } + let origin = ObjectIdentifier(peripheral) + let characteristicOrigin = ObjectIdentifier(characteristic) + let report = dataContinuationLock.withLock { current -> String? in + guard var ingress = current else { return nil } + defer { current = ingress } + guard ingress.peripheral == origin, ingress.characteristic == characteristicOrigin else { + ingress.diagnostics.rejectedFrames += 1 + let rejected = ingress.diagnostics.rejectedFrames + guard rejected == 1 || rejected.isMultiple(of: Self.ingressReportInterval) else { return nil } + return "[BLE] Ingress rejected origin \(ingress.diagnostics.context) rejected=\(rejected)" + } + switch ingress.continuation.yield(data) { + case .enqueued: + ingress.diagnostics.acceptedFrames += 1 + return nil + case .dropped: + ingress.diagnostics.droppedFrames += 1 + let dropped = ingress.diagnostics.droppedFrames + guard dropped == 1 || dropped.isMultiple(of: Self.ingressReportInterval) else { return nil } + return "[BLE] Ingress dropped frame \(ingress.diagnostics.context) reason=buffer-full dropped=\(dropped)" + case .terminated: + ingress.diagnostics.terminatedFrames += 1 + let terminated = ingress.diagnostics.terminatedFrames + guard terminated == 1 || terminated.isMultiple(of: Self.ingressReportInterval) else { return nil } + return "[BLE] Ingress terminated frame \(ingress.diagnostics.context) reason=stream-terminated terminated=\(terminated)" + @unknown default: + return nil + } + } + if let report { logger.warning(report) } } func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) { - guard let sm = stateMachine else { return } - Task { await sm.handleDidReadRSSI(RSSI: RSSI, error: error) } + _ = readRSSI(from: peripheral, RSSI: RSSI, error: error) + } + + func readRSSI(from peripheral: CBPeripheral, RSSI: NSNumber, error: Error?) -> Task? { + guard let sm = stateMachine, let generation = generation(for: peripheral) else { return nil } + return Task { await sm.handleDidReadRSSI(peripheral, RSSI: RSSI, error: error, generation: generation) } } func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { guard let sm = stateMachine else { return } - // Pop the oldest unacknowledged write's sequence (callbacks arrive in - // issue order on this serial queue) so the callback is tagged with the - // write that produced it, not whichever write is current by delivery time. - let seq = issuedWriteSequencesLock.withLock { $0.isEmpty ? nil : $0.removeFirst() } - guard let seq else { - logger.debug("[BLE] didWriteValueFor with no recorded write, ignoring") + let origin = ObjectIdentifier(peripheral) + let characteristicOrigin = ObjectIdentifier(characteristic) + let (sequence, rejectedOrigin) = issuedWriteSequencesLock.withLock { writes -> (UInt64?, Bool) in + guard let first = writes.first else { return (nil, false) } + guard first.peripheral == origin, first.characteristic == characteristicOrigin else { return (nil, true) } + return (writes.removeFirst().sequence, false) + } + guard let seq = sequence else { + if rejectedOrigin { + logger.warning("[BLE] ACK rejected origin \(ingressDiagnostics?.context ?? "stream=none") reason=originMismatch") + } else { + logger.debug("[BLE] didWriteValueFor with no recorded write, ignoring") + } return } Task { await sm.handleDidWriteValue(peripheral, characteristic: characteristic, error: error, writeSequence: seq) } } func peripheralIsReady(toSendWriteWithoutResponse peripheral: CBPeripheral) { - guard let sm = stateMachine else { return } - Task { await sm.handlePeripheralReadyForWriteWithoutResponse() } + _ = readyForWrite(from: peripheral) + } + + func readyForWrite(from peripheral: CBPeripheral) -> Task? { + guard let sm = stateMachine else { return nil } + let generation = generation(for: peripheral) + return Task { + if let generation { + await sm.handlePeripheralReadyForWriteWithoutResponse(peripheral, generation: generation) + } + #if DEBUG + await sm.noteWriteReadinessHandled(peripheral.identifier) + #endif + } } } diff --git a/MC1Services/Sources/MC1Services/Transport/BLEStateMachine+CallbackHandlers.swift b/MC1Services/Sources/MC1Services/Transport/BLEStateMachine+CallbackHandlers.swift index 3964339bb3..df0f6243ac 100644 --- a/MC1Services/Sources/MC1Services/Transport/BLEStateMachine+CallbackHandlers.swift +++ b/MC1Services/Sources/MC1Services/Transport/BLEStateMachine+CallbackHandlers.swift @@ -27,6 +27,7 @@ extension BLEStateMachine { // Cancel any poweredOff grace period — Bluetooth is now available bluetoothPowerOffGraceTask?.cancel() bluetoothPowerOffGraceTask = nil + bluetoothPowerOffGraceID = nil // Resume waiting continuation if any if case let .waitingForBluetooth(continuation) = phase { @@ -58,20 +59,13 @@ extension BLEStateMachine { // A freshly created CBCentralManager may briefly report poweredOff // before settling on poweredOn. Start a grace period instead of // failing immediately, so the initialization can complete. - if bluetoothPowerOffGraceTask == nil { - logger.info("[BLE] poweredOff during waitingForBluetooth — starting grace period") - bluetoothPowerOffGraceTask = Task { - try? await Task.sleep(for: .seconds(1)) - guard !Task.isCancelled else { return } - self.handleBluetoothPowerOffGraceExpired() - } - } + startBluetoothPowerOffGraceIfNeeded() } else { // Not waiting — cancel any active operation immediately let deviceID = phase.deviceID cancelCurrentOperation(with: BLEError.bluetoothPoweredOff) if let deviceID { - onDisconnection?(deviceID, nil) + notifyDisconnection(deviceID, nil) } } @@ -86,15 +80,29 @@ extension BLEStateMachine { } } + func startBluetoothPowerOffGraceIfNeeded() { + guard bluetoothPowerOffGraceTask == nil else { return } + let graceID = UUID() + bluetoothPowerOffGraceID = graceID + logger.info("[BLE] poweredOff during waitingForBluetooth — starting grace period") + bluetoothPowerOffGraceTask = Task { + try? await operationClock.sleep(Self.bluetoothPowerOffGrace) + guard !Task.isCancelled else { return } + self.handleBluetoothPowerOffGraceExpired(id: graceID) + } + } + /// Called when the poweredOff grace period expires without poweredOn arriving. - private func handleBluetoothPowerOffGraceExpired() { + private func handleBluetoothPowerOffGraceExpired(id: UUID) { + guard bluetoothPowerOffGraceID == id else { return } bluetoothPowerOffGraceTask = nil + bluetoothPowerOffGraceID = nil guard case .waitingForBluetooth = phase else { return } logger.info("[BLE] poweredOff grace period expired — Bluetooth is off") let deviceID = phase.deviceID cancelCurrentOperation(with: BLEError.bluetoothPoweredOff) if let deviceID { - onDisconnection?(deviceID, nil) + notifyDisconnection(deviceID, nil) } } @@ -108,13 +116,13 @@ extension BLEStateMachine { } if case let .restoringState(peripheral) = phase { transition(to: .idle) - onDisconnection?(peripheral.identifier, nil) + notifyDisconnection(peripheral.identifier, nil) } // Auto-reconnect waits indefinitely on the OS pending connect, which can // never complete once Bluetooth is unavailable; tear down explicitly. if case let .autoReconnecting(peripheral, _, _) = phase { transition(to: .idle) - onDisconnection?(peripheral.identifier, error) + notifyDisconnection(peripheral.identifier, error) } } @@ -133,12 +141,10 @@ extension BLEStateMachine { reconnectPolicy.episodeBegan() transition(to: .autoReconnecting(peripheral: peripheral, tx: nil, rx: nil)) - // State-restoration paths claim the reconnect cycle here so the coordinator's - // strict completion guard accepts the eventual onReconnection. The adoption - // path already claimed via startAdoptingLastSystemConnectedPeripheralIfAvailable - // and passes .adoption to skip and avoid double-claiming. + // Restoration claims the reconnect cycle here; adoption already claimed it + // before emitting its lifecycle event. if source == .stateRestoration { - onAutoReconnecting?(peripheral.identifier, "state-restoration") + notifyAutoReconnecting(peripheral.identifier, "state-restoration") } if peripheral.state == .connected { @@ -157,6 +163,14 @@ extension BLEStateMachine { } func handleWillRestoreState(_ peripheral: CBPeripheral) { + switch phase { + case .idle, .waitingForBluetooth, .restoringState: + break + default: + logger.info("[BLE] Restoration stood down for active owner instance=\(instanceID) generation=\(connectionGeneration) phase=\(phase.name)") + if phase.deviceID != peripheral.identifier { cancelUnexpectedPeripheral(peripheral) } + return + } let pState = peripheralStateString(peripheral.state) logger.info("[BLE] State restoration callback: \(peripheral.identifier.uuidString.prefix(8)), state: \(pState)") @@ -271,7 +285,7 @@ extension BLEStateMachine { logger.warning("Auto-reconnect connect failures exhausted budget for \(peripheral.identifier) - transitioning to idle") } transition(to: .idle) - onDisconnection?(peripheral.identifier, teardownError) + notifyDisconnection(peripheral.identifier, teardownError) } return } @@ -397,7 +411,7 @@ extension BLEStateMachine { handleFullDisconnect(deviceID: deviceID, error: error, eventTime: eventTime) return } - onRemoteLinkLost?(deviceID, eventTime) + notifyRemoteLinkLost(deviceID, eventTime) logger.info("[BLE] iOS auto-reconnect started: \(deviceID.uuidString.prefix(8)), will attempt automatic reconnection") @@ -435,7 +449,7 @@ extension BLEStateMachine { armAutoReconnectDiscoveryTimeout(for: peripheral, generation: connectionGeneration) // Notify handler so UI can show "connecting" state - onAutoReconnecting?(deviceID, errorInfo) + notifyAutoReconnecting(deviceID, errorInfo, eventTime: eventTime) } /// Handles a full (non-reconnecting) disconnection. @@ -446,13 +460,11 @@ extension BLEStateMachine { break case .connected, .autoReconnecting: - // Unexpected disconnection. Map through makeConnectionError like the - // sibling onDisconnection sites so bond invalidation arriving here still - // surfaces as the typed BLEError.authenticationFailed; nil stays nil to - // keep a clean disconnect distinguishable from a failure. - onRemoteLinkLost?(deviceID, eventTime) + // Preserve bond-invalidation errors as `BLEError.authenticationFailed`; + // a nil error still represents a clean disconnect. + notifyRemoteLinkLost(deviceID, eventTime) cancelCurrentOperation(with: BLEError.notConnected) - onDisconnection?(deviceID, error.map { ReconnectPolicy.makeConnectionError($0) }) + notifyDisconnection(deviceID, error.map { ReconnectPolicy.makeConnectionError($0) }, eventTime: eventTime) default: // Disconnection during connection attempt @@ -471,7 +483,7 @@ extension BLEStateMachine { if let error { logger.warning("Auto-reconnect service discovery failed: \(error.localizedDescription)") transition(to: .idle) - onDisconnection?(expected.identifier, ReconnectPolicy.makeConnectionError(error)) + notifyDisconnection(expected.identifier, ReconnectPolicy.makeConnectionError(error)) return } @@ -528,7 +540,7 @@ extension BLEStateMachine { if let error { logger.warning("Auto-reconnect characteristic discovery failed: \(error.localizedDescription)") transition(to: .idle) - onDisconnection?(expected.identifier, ReconnectPolicy.makeConnectionError(error)) + notifyDisconnection(expected.identifier, ReconnectPolicy.makeConnectionError(error)) return } @@ -638,7 +650,7 @@ extension BLEStateMachine { if let error { logger.warning("Auto-reconnect notification subscription failed: \(error.localizedDescription)") transition(to: .idle) - onDisconnection?(peripheral.identifier, ReconnectPolicy.makeConnectionError(error)) + notifyDisconnection(peripheral.identifier, ReconnectPolicy.makeConnectionError(error)) return } @@ -669,7 +681,7 @@ extension BLEStateMachine { ) // Pass continuation to delegate handler for direct yielding (preserves ordering) - delegateHandler.setDataContinuation(continuation) + installDataContinuation(continuation, peripheral: peripheral, rx: rx) transition(to: .connected( peripheral: peripheral, @@ -680,7 +692,7 @@ extension BLEStateMachine { startRSSIKeepalive(for: peripheral) logger.info("[BLE] iOS auto-reconnect complete: \(peripheral.identifier.uuidString.prefix(8))") - onReconnection?(peripheral.identifier, stream) + notifyReconnection(peripheral.identifier, stream) } func handleDidWriteValue(_ peripheral: CBPeripheral, characteristic: CBCharacteristic, error: Error?, writeSequence: UInt64) { @@ -720,10 +732,16 @@ extension BLEStateMachine { continuation.resume() } - earliestNextWrite = ContinuousClock.now.advanced(by: .seconds(writePacingDelay)) + earliestNextWrite = operationClock.now().advanced(by: .seconds(writePacingDelay)) resumeNextWriteWaiter() } + func handleDidReadRSSI(_ peripheral: CBPeripheral, RSSI: NSNumber, error: Error?, generation: UInt64) { + guard case let .connected(expected, _, _, _) = phase, + expected === peripheral, connectionGeneration == generation else { return } + handleDidReadRSSI(RSSI: RSSI, error: error) + } + func handleDidReadRSSI(RSSI: NSNumber, error: Error?) { if let error { consecutiveRSSIFailures += 1 diff --git a/MC1Services/Sources/MC1Services/Transport/BLEStateMachine+LifecycleOrigin.swift b/MC1Services/Sources/MC1Services/Transport/BLEStateMachine+LifecycleOrigin.swift new file mode 100644 index 0000000000..eb7360f20e --- /dev/null +++ b/MC1Services/Sources/MC1Services/Transport/BLEStateMachine+LifecycleOrigin.swift @@ -0,0 +1,36 @@ +import Foundation + +extension BLEStateMachine { + var lifecycleOrigin: BLELifecycleOrigin? { + guard let deviceID = phase.deviceID else { return nil } + return BLELifecycleOrigin(deviceID: deviceID, generation: connectionGeneration, eventTime: connectionGenerationStartTime) + } + + func setLifecycleEventHandler(_ handler: @escaping @Sendable (BLELifecycleEvent, AsyncStream?) -> Void) { + onLifecycleEvent = handler + } + + func notifyDisconnection(_ deviceID: UUID, _ error: Error?, eventTime: CFAbsoluteTime = CFAbsoluteTimeGetCurrent()) { + activeSessionBinding?.revoke() + let origin = BLELifecycleOrigin(deviceID: deviceID, generation: connectionGeneration, eventTime: eventTime) + let classified = error.map { ($0 as? BLEError) ?? ReconnectPolicy.makeConnectionError($0) } + onLifecycleEvent?(.disconnected(origin, error: classified), nil) + } + + func notifyRemoteLinkLost(_ deviceID: UUID, _ eventTime: CFAbsoluteTime) { + activeSessionBinding?.revoke() + let origin = BLELifecycleOrigin(deviceID: deviceID, generation: connectionGeneration, eventTime: eventTime) + onLifecycleEvent?(.remoteLinkLost(origin), nil) + } + + func notifyAutoReconnecting(_ deviceID: UUID, _ errorInfo: String, eventTime: CFAbsoluteTime = CFAbsoluteTimeGetCurrent()) { + activeSessionBinding?.revoke() + let origin = BLELifecycleOrigin(deviceID: deviceID, generation: connectionGeneration, eventTime: eventTime) + onLifecycleEvent?(.autoReconnecting(origin, errorInfo: errorInfo), nil) + } + + func notifyReconnection(_ deviceID: UUID, _ stream: AsyncStream) { + let origin = BLELifecycleOrigin(deviceID: deviceID, generation: connectionGeneration, eventTime: CFAbsoluteTimeGetCurrent()) + onLifecycleEvent?(.reconnected(origin), stream) + } +} diff --git a/MC1Services/Sources/MC1Services/Transport/BLEStateMachine.swift b/MC1Services/Sources/MC1Services/Transport/BLEStateMachine.swift index dbcad80206..bf158d7989 100644 --- a/MC1Services/Sources/MC1Services/Transport/BLEStateMachine.swift +++ b/MC1Services/Sources/MC1Services/Transport/BLEStateMachine.swift @@ -2,6 +2,7 @@ @preconcurrency import CoreBluetooth import Dispatch import Foundation +import MeshCore /// Manages BLE connections using an explicit state machine. /// @@ -24,17 +25,18 @@ actor BLEStateMachine: BLEStateMachineProtocol { /// Converts CBPeripheralState to readable string for diagnostics nonisolated func peripheralStateString(_ state: CBPeripheralState) -> String { switch state { - case .disconnected: return "disconnected" - case .connecting: return "connecting" - case .connected: return "connected" - case .disconnecting: return "disconnecting" - @unknown default: return "unknown(\(state.rawValue))" + case .disconnected: "disconnected" + case .connecting: "connecting" + case .connected: "connected" + case .disconnecting: "disconnecting" + @unknown default: "unknown(\(state.rawValue))" } } // MARK: - State var phase: BLEPhase = .idle + private var disconnectTask: (id: UUID, generation: UInt64, task: Task)? /// Tracks when the current phase started (for timing diagnostics) var phaseStartTime: Date = .init() @@ -58,6 +60,12 @@ actor BLEStateMachine: BLEStateMachineProtocol { /// extend the bond shield. Cleared in cleanupPhaseResources on exit from /// `.connected` and explicitly on preserve-path stack teardown. var appSessionLiveDeviceID: UUID? + var activeSessionBinding: SessionTransportBinding? + private var dataStreamSequence: UInt64 = 0 + + private var appSessionLogContext: String { + "instance=\(instanceID) generation=\(connectionGeneration) stream=\(dataStreamSequence)" + } /// Expose current phase for testing var currentPhase: BLEPhase { @@ -105,6 +113,7 @@ actor BLEStateMachine: BLEStateMachineProtocol { // MARK: - Configuration + let operationClock: BLEOperationClock private let stateRestorationID = "com.pocketmesh.ble.central" private let connectionTimeout: TimeInterval let serviceDiscoveryTimeout: TimeInterval @@ -141,7 +150,16 @@ actor BLEStateMachine: BLEStateMachineProtocol { var pendingWriteSequence: UInt64 = 0 /// Queue of tasks waiting to write (serializes concurrent sends) - private var writeWaiters: [CheckedContinuation] = [] + private struct WriteWaiter { + let id: UUID + let continuation: CheckedContinuation + } + + private var writeWaiters: [WriteWaiter] = [] + + var queuedWriteCount: Int { + writeWaiters.count + } /// Tracks the current write timeout task so it can be cancelled when write completes var writeTimeoutTask: Task? @@ -159,11 +177,21 @@ actor BLEStateMachine: BLEStateMachineProtocol { /// backstop, so a sender never hangs across a disconnect or a peripheral that goes silent. /// Single slot: the pipeline issues one Write Command at a time. private var writeWithoutResponseReadyContinuation: CheckedContinuation? + private var writeWithoutResponseReadyBinding: SessionTransportBinding? + + #if DEBUG + var testWriteReadinessHandled: (@Sendable (UUID) -> Void)? + + func noteWriteReadinessHandled(_ deviceID: UUID) { + testWriteReadinessHandled?(deviceID) + } + #endif /// Backstop timeout for `writeWithoutResponseReadyContinuation`: fails a parked sender if /// the peripheral never re-signals readiness and no disconnect arrives, so a stuck Write /// Command cannot defeat the session's pipeline timeout and hang the channel sync. private var writeWithoutResponseReadyTimeoutTask: Task? + private var writeWithoutResponseReadyID: UUID? /// Error recorded when a `.discoveryComplete` phase is torn down before /// `connect()` adopts it, so the in-flight connect surfaces the real @@ -194,6 +222,10 @@ actor BLEStateMachine: BLEStateMachineProtocol { /// Grace period task for poweredOff during waitingForBluetooth. /// Allows CBCentralManager initialization to settle (poweredOff → poweredOn). var bluetoothPowerOffGraceTask: Task? + var bluetoothPowerOffGraceID: UUID? + private var bluetoothWaitID: UUID? + static let bluetoothPowerOffGrace: Duration = .seconds(1) + private static let disconnectSettleDelay: Duration = .milliseconds(100) // MARK: - Scanning (orthogonal to connection lifecycle) @@ -204,14 +236,7 @@ actor BLEStateMachine: BLEStateMachineProtocol { // MARK: - Callbacks - /// Installed by `ConnectionManager.init` (via `iOSBLETransport.setDisconnectionHandler`). - var onDisconnection: (@Sendable (UUID, Error?) -> Void)? - /// Peripheral link loss with the CoreBluetooth event time. Not fired for local - /// shutdown or the phone's own Bluetooth power-off. - var onRemoteLinkLost: (@Sendable (UUID, CFAbsoluteTime) -> Void)? - /// Installed by `ConnectionManager.init` (via `iOSBLETransport.setReconnectionHandler`, - /// which wraps it to capture the data stream before the handler runs). - var onReconnection: (@Sendable (UUID, AsyncStream) -> Void)? + var onLifecycleEvent: (@Sendable (BLELifecycleEvent, AsyncStream?) -> Void)? /// Fired when an existing bond verification was refreshed while a live app /// session is present. Installed by `ConnectionManager.wireTransportHandlers`. var onBondRefreshed: (@Sendable (UUID) -> Void)? @@ -219,14 +244,7 @@ actor BLEStateMachine: BLEStateMachineProtocol { var onBluetoothStateChange: (@Sendable (CBManagerState) -> Void)? /// Installed by `ConnectionManager.init`. var onBluetoothPoweredOn: (@Sendable () -> Void)? - /// Called when entering iOS auto-reconnecting phase. - /// The device has disconnected but iOS will attempt automatic reconnection. - /// Note: The MeshCore session is invalid at this point and will be rebuilt upon successful reconnection. - /// Installed by `ConnectionManager.init`. - var onAutoReconnecting: (@Sendable (UUID, String) -> Void)? - - /// Distinguishes the call site driving `handleRestoredPeripheral` so the function - /// fires `onAutoReconnecting` only when no upstream caller has already claimed the cycle. + /// Distinguishes restoration from an adoption whose lifecycle event was already sent. enum RestoredPeripheralSource { case stateRestoration case adoption @@ -247,14 +265,23 @@ actor BLEStateMachine: BLEStateMachineProtocol { serviceDiscoveryTimeout: TimeInterval = 40.0, autoReconnectDiscoveryTimeout: TimeInterval = 15.0, writeTimeout: TimeInterval = 5.0, - writePacingDelay: TimeInterval = 0 + writePacingDelay: TimeInterval = 0, + centralManager: CBCentralManager? = nil, + operationClock: BLEOperationClock = .continuous ) { + self.operationClock = operationClock self.connectionTimeout = connectionTimeout self.serviceDiscoveryTimeout = serviceDiscoveryTimeout self.autoReconnectDiscoveryTimeout = autoReconnectDiscoveryTimeout self.writeTimeout = writeTimeout self.writePacingDelay = writePacingDelay delegateHandler = BLEDelegateHandler() + earliestNextWrite = operationClock.now() + if let centralManager { + self.centralManager = centralManager + isActivated = true + delegateHandler.stateMachine = self + } } /// Sets the write pacing delay for ESP32 compatibility. @@ -263,6 +290,11 @@ actor BLEStateMachine: BLEStateMachineProtocol { writePacingDelay = delay } + func setWritePacingDelay(_ delay: TimeInterval, sessionBinding: SessionTransportBinding) { + guard activeSessionBinding === sessionBinding else { return } + try? sessionBinding.performIfActive { writePacingDelay = delay } + } + /// Activates the BLE state machine, creating the CBCentralManager. /// Call once during app initialization. Safe to call multiple times. func activate() { @@ -422,21 +454,6 @@ actor BLEStateMachine: BLEStateMachineProtocol { // MARK: - Event Handler Registration - /// Sets a handler for disconnection events - func setDisconnectionHandler(_ handler: @escaping @Sendable (UUID, Error?) -> Void) { - onDisconnection = handler - } - - func setRemoteLinkLostHandler(_ handler: @escaping @Sendable (UUID, CFAbsoluteTime) -> Void) { - onRemoteLinkLost = handler - } - - /// Sets a handler for reconnection events. - /// The handler receives the device ID and the data stream for receiving data. - func setReconnectionHandler(_ handler: @escaping @Sendable (UUID, AsyncStream) -> Void) { - onReconnection = handler - } - /// Sets a handler for Bluetooth state changes func setBluetoothStateChangeHandler(_ handler: @escaping @Sendable (CBManagerState) -> Void) { onBluetoothStateChange = handler @@ -447,12 +464,6 @@ actor BLEStateMachine: BLEStateMachineProtocol { onBluetoothPoweredOn = handler } - /// Sets a handler for auto-reconnecting events. - /// Called when device disconnects but iOS is attempting automatic reconnection. - func setAutoReconnectingHandler(_ handler: @escaping @Sendable (UUID, String) -> Void) { - onAutoReconnecting = handler - } - /// Records a verified encrypted session. An exhausted encryption-timeout /// budget within the grace window then continues the episode rather than /// tearing down. `ConnectionManager` seeds and refreshes this stamp. @@ -460,6 +471,13 @@ actor BLEStateMachine: BLEStateMachineProtocol { reconnectPolicy.recordBondVerification(deviceID: deviceID, at: date) } + func recordBondVerification(deviceID: UUID, at date: Date, sessionBinding: SessionTransportBinding) { + guard activeSessionBinding === sessionBinding else { return } + try? sessionBinding.performIfActive { + reconnectPolicy.recordBondVerification(deviceID: deviceID, at: date) + } + } + /// Clears a device's bond-verification record when its pairing is /// forgotten, so a stale verification cannot shield the next episode. func clearBondVerification(deviceID: UUID) { @@ -470,6 +488,36 @@ actor BLEStateMachine: BLEStateMachineProtocol { appSessionLiveDeviceID = deviceID } + func setSessionBinding(_ binding: SessionTransportBinding) { + try? binding.performIfActive { + if let previous = activeSessionBinding, previous !== binding { + previous.revoke() + cancelUnsubmittedWrites(sessionBinding: previous) + } + activeSessionBinding = binding + } + } + + func setAppSessionLive(deviceID: UUID?, sessionBinding: SessionTransportBinding) { + let binding = String(describing: ObjectIdentifier(sessionBinding)) + let currentBinding = activeSessionBinding.map { String(describing: ObjectIdentifier($0)) } ?? "none" + guard activeSessionBinding === sessionBinding else { + logger.info("[BLE] Session live rejected binding=\(binding) currentBinding=\(currentBinding) reason=bindingMismatch \(appSessionLogContext)") + return + } + if let deviceID { + do { + try sessionBinding.performIfActive { appSessionLiveDeviceID = deviceID } + logger.info("[BLE] Session live binding=\(binding) device=\(deviceID.uuidString.prefix(8)) \(appSessionLogContext)") + } catch { + logger.info("[BLE] Session live rejected binding=\(binding) currentBinding=\(currentBinding) reason=revoked \(appSessionLogContext)") + } + } else { + appSessionLiveDeviceID = nil + logger.info("[BLE] Session revoked binding=\(binding) \(appSessionLogContext)") + } + } + func hasBondVerification(deviceID: UUID) -> Bool { reconnectPolicy.bondVerificationDates[deviceID] != nil } @@ -536,6 +584,7 @@ actor BLEStateMachine: BLEStateMachineProtocol { /// `BLEError.bluetoothUnauthorized` if access is denied /// `BLEError.bluetoothPoweredOff` if Bluetooth is off and doesn't turn on func waitForPoweredOn() async throws { + try Task.checkCancellation() activate() // Already powered on @@ -554,21 +603,37 @@ actor BLEStateMachine: BLEStateMachineProtocol { // Wait for state change (.unknown, .resetting, and .poweredOff reach here). // poweredOff is included because a freshly created CBCentralManager may // briefly report poweredOff before settling on poweredOn. - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - guard case .idle = phase else { - continuation.resume(throwing: BLEError.connectionFailed("Already in operation")) - return + let waitID = UUID() + try await withTaskCancellationHandler { + try Task.checkCancellation() + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + guard case .idle = phase else { + continuation.resume(throwing: BLEError.connectionFailed("Already in operation")) + return + } + bluetoothWaitID = waitID + transition(to: .waitingForBluetooth(continuation: continuation)) + if centralManager.state == .poweredOff { + startBluetoothPowerOffGraceIfNeeded() + } } - transition(to: .waitingForBluetooth(continuation: continuation)) + } onCancel: { + Task { await self.cancelBluetoothWait(id: waitID) } } } + private func cancelBluetoothWait(id: UUID) { + guard bluetoothWaitID == id, case .waitingForBluetooth = phase else { return } + cancelCurrentOperation(with: CancellationError()) + } + /// Connects to a BLE device and returns a data stream. /// /// - Parameter deviceID: UUID of the device to connect to /// - Returns: AsyncStream of data received from the device /// - Throws: BLEError if connection fails - func connect(to deviceID: UUID) async throws -> AsyncStream { + func connect(to deviceID: UUID, sessionBinding: SessionTransportBinding? = nil) async throws -> AsyncStream { + try sessionBinding?.checkActive() logger.info("Connect requested for device: \(deviceID)") // Ensure we're in idle state @@ -584,6 +649,7 @@ actor BLEStateMachine: BLEStateMachineProtocol { // Wait for Bluetooth try await waitForPoweredOn() + try sessionBinding?.checkActive() // Re-validate after the suspension: state restoration or a poweredOn // callback can claim the machine (e.g. .autoReconnecting) while waiting, @@ -605,7 +671,8 @@ actor BLEStateMachine: BLEStateMachineProtocol { logger.info("[BLE] Connection generation advanced to \(connectionGeneration) for device: \(deviceID.uuidString.prefix(8))") // Connect and discover services (continuation spans entire discovery chain) - try await connectToPeripheral(peripheral) + try await connectToPeripheral(peripheral, sessionBinding: sessionBinding) + try sessionBinding?.checkActive() // Create data stream and transition to connected let (stream, continuation) = AsyncStream.makeStream( @@ -620,7 +687,7 @@ actor BLEStateMachine: BLEStateMachineProtocol { } // Pass continuation to delegate handler for direct yielding (preserves ordering) - delegateHandler.setDataContinuation(continuation) + installDataContinuation(continuation, peripheral: peripheral, rx: rx) transition(to: .connected( peripheral: peripheral, @@ -641,9 +708,9 @@ actor BLEStateMachine: BLEStateMachineProtocol { /// /// - Parameter data: Data to send /// - Throws: BLEError if not connected or write fails - func send(_ data: Data) async throws { + func send(_ data: Data, sessionBinding: SessionTransportBinding? = nil) async throws { logger.debug("[BLE] send: \(data.count) bytes") - try await claimWriteSlot(data: data) + try await claimWriteSlot(data: data, sessionBinding: sessionBinding) } /// Whether the connected peripheral's write characteristic supports ATT Write Commands. @@ -673,57 +740,73 @@ actor BLEStateMachine: BLEStateMachineProtocol { /// deliberately skips `writePacingDelay` — that delay protects the ESP32 RX queue during /// `.withResponse` bursts, and Write Commands are an nRF52-only path. A radio whose write /// characteristic does not advertise the capability degrades to the acknowledged path. - func sendWithoutResponse(_ data: Data) async throws { + func sendWithoutResponse(_ data: Data, sessionBinding: SessionTransportBinding? = nil) async throws { + try Task.checkCancellation() + try sessionBinding?.checkActive() let myGeneration = connectionGeneration guard case let .connected(peripheral, _, _, _) = phase, peripheral.state == .connected else { - throw BLEError.notConnected + throw MeshTransportError.notConnected } guard txSupportsWriteWithoutResponse else { - try await claimWriteSlot(data: data) + try await claimWriteSlot(data: data, sessionBinding: sessionBinding) return } - try await awaitWriteWithoutResponseReadiness(alreadyReady: peripheral.canSendWriteWithoutResponse) - - // Re-validate after a possible suspension: the connection may have dropped while parked. - guard case let .connected(readyPeripheral, readyTx, _, _) = phase, - readyPeripheral.state == .connected, - connectionGeneration == myGeneration else { - throw BLEError.notConnected + while true { + try await awaitWriteWithoutResponseReadiness( + alreadyReady: peripheral.canSendWriteWithoutResponse, sessionBinding: sessionBinding + ) + try Task.checkCancellation() + guard case let .connected(readyPeripheral, readyTx, _, _) = phase, + readyPeripheral.state == .connected, + connectionGeneration == myGeneration else { + throw MeshTransportError.notConnected + } + guard readyPeripheral.canSendWriteWithoutResponse else { continue } + if let sessionBinding { + try sessionBinding.performIfActive { + readyPeripheral.writeValue(data, for: readyTx, type: .withoutResponse) + } + } else { + readyPeripheral.writeValue(data, for: readyTx, type: .withoutResponse) + } + return } - - readyPeripheral.writeValue(data, for: readyTx, type: .withoutResponse) } /// Serializes concurrent writes by waiting for any pending write to complete, /// then claims the write slot and issues the BLE write. - private func claimWriteSlot(data: Data) async throws { + private func claimWriteSlot(data: Data, sessionBinding: SessionTransportBinding?) async throws { let myGeneration = connectionGeneration + var claimedWrite = false + defer { + // A cancelled caller can wake after leaving the queue; it still owes the next handoff. + if !claimedWrite, connectionGeneration == myGeneration, pendingWriteContinuation == nil { + resumeNextWriteWaiter() + } + } while true { + try sessionBinding?.checkActive() guard connectionGeneration == myGeneration else { - throw BLEError.notConnected + throw MeshTransportError.notConnected } // Pacing: wait until earliestNextWrite. - if writePacingDelay > 0, ContinuousClock.now < earliestNextWrite { - try await Task.sleep(until: earliestNextWrite, clock: .continuous) + if writePacingDelay > 0, operationClock.now() < earliestNextWrite { + try await operationClock.sleep(operationClock.now().duration(to: earliestNextWrite)) try Task.checkCancellation() guard connectionGeneration == myGeneration else { - throw BLEError.notConnected + throw MeshTransportError.notConnected } } try Task.checkCancellation() - guard case let .connected(peripheral, _, _, _) = phase else { - throw BLEError.notConnected - } - - guard peripheral.state == .connected else { - throw BLEError.notConnected + guard case let .connected(peripheral, _, _, _) = phase, peripheral.state == .connected else { + throw MeshTransportError.notConnected } // Wait for any pending write to complete (serializes concurrent sends). @@ -737,8 +820,17 @@ actor BLEStateMachine: BLEStateMachineProtocol { } else { logger.debug("[BLE] Write queued, depth: \(queueDepth)") } - await withCheckedContinuation { (waiter: CheckedContinuation) in - writeWaiters.append(waiter) + let waiterID = UUID() + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + guard !Task.isCancelled else { + continuation.resume(throwing: CancellationError()) + return + } + writeWaiters.append(WriteWaiter(id: waiterID, continuation: continuation)) + } + } onCancel: { + Task { await self.cancelWriteWaiter(id: waiterID) } } continue } @@ -748,33 +840,47 @@ actor BLEStateMachine: BLEStateMachineProtocol { guard case let .connected(currentPeripheral, currentTx, _, _) = self.phase, currentPeripheral.state == .connected, self.pendingWriteContinuation == nil else { - continuation.resume(throwing: BLEError.notConnected) + continuation.resume(throwing: MeshTransportError.notConnected) return } + claimedWrite = true self.writeSequenceNumber += 1 let currentSeq = self.writeSequenceNumber self.pendingWriteSequence = currentSeq self.pendingWriteContinuation = continuation // Record the sequence before issuing the write so didWriteValue // can tag its callback with the originating write - self.delegateHandler.recordIssuedWriteSequence(currentSeq) - currentPeripheral.writeValue(data, for: currentTx, type: .withResponse) + do { + if let sessionBinding { + try sessionBinding.performIfActive { + self.delegateHandler.recordIssuedWriteSequence(currentSeq, peripheral: currentPeripheral, characteristic: currentTx) + currentPeripheral.writeValue(data, for: currentTx, type: .withResponse) + } + } else { + self.delegateHandler.recordIssuedWriteSequence(currentSeq, peripheral: currentPeripheral, characteristic: currentTx) + currentPeripheral.writeValue(data, for: currentTx, type: .withResponse) + } + } catch { + self.pendingWriteContinuation = nil + continuation.resume(throwing: error) + self.resumeNextWriteWaiter() + return + } // Cancel any previous timeout task and create a new one let seq = self.pendingWriteSequence self.writeTimeoutTask?.cancel() self.writeTimeoutTask = Task { - try? await Task.sleep(for: .seconds(self.writeTimeout)) - guard !Task.isCancelled else { return } - guard self.pendingWriteSequence == seq else { return } + try? await self.operationClock.sleep(.seconds(self.writeTimeout)) + guard !Task.isCancelled, self.pendingWriteSequence == seq else { return } if let pending = self.pendingWriteContinuation { self.logger.warning("[BLE] Write timeout: seq=\(seq), elapsed=\(self.writeTimeout)s") self.pendingWriteContinuation = nil self.consecutiveQueuedWrites = 0 pending.resume(throwing: BLEError.operationTimeout) self.writeTimeoutTask = nil - self.earliestNextWrite = ContinuousClock.now.advanced(by: .seconds(self.writePacingDelay)) + self.earliestNextWrite = operationClock.now().advanced(by: .seconds(self.writePacingDelay)) self.resumeNextWriteWaiter() } } @@ -788,53 +894,86 @@ actor BLEStateMachine: BLEStateMachineProtocol { func resumeNextWriteWaiter() { guard !writeWaiters.isEmpty else { return } let waiter = writeWaiters.removeFirst() - waiter.resume() + waiter.continuation.resume() } - /// Parks the caller until the peripheral can accept another Write Command. Returns - /// immediately when `alreadyReady`. Otherwise suspends on a single continuation that is - /// resumed by `handlePeripheralReadyForWriteWithoutResponse()`, released on teardown by - /// `cancelPendingWriteOperations`, or failed by a timeout backstop — so a peripheral that - /// stops signalling readiness cannot hang the sender past the per-write timeout. - func awaitWriteWithoutResponseReadiness(alreadyReady: Bool) async throws { + private func cancelWriteWaiter(id: UUID) { + guard let index = writeWaiters.firstIndex(where: { $0.id == id }) else { return } + writeWaiters.remove(at: index).continuation.resume(throwing: CancellationError()) + } + + /// Waits for Write Command readiness, with teardown cancellation and a per-write timeout + /// so a peripheral that stops signalling cannot leave the sender suspended. + func awaitWriteWithoutResponseReadiness( + alreadyReady: Bool, sessionBinding: SessionTransportBinding? = nil + ) async throws { + try Task.checkCancellation() + try sessionBinding?.checkActive() guard !alreadyReady else { return } let timeout = writeTimeout - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - // The pipeline issues one Write Command at a time, so the slot is normally free. - // Release any stale waiter rather than leak it if that invariant is ever broken. - if let stale = writeWithoutResponseReadyContinuation { - writeWithoutResponseReadyContinuation = nil - writeWithoutResponseReadyTimeoutTask?.cancel() - writeWithoutResponseReadyTimeoutTask = nil - stale.resume(throwing: BLEError.notConnected) - } - writeWithoutResponseReadyContinuation = continuation - writeWithoutResponseReadyTimeoutTask = Task { [weak self] in - try? await Task.sleep(for: .seconds(timeout)) - guard !Task.isCancelled else { return } - await self?.timeoutWriteWithoutResponseReadiness() + let waitID = UUID() + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + guard !Task.isCancelled else { + continuation.resume(throwing: CancellationError()) + return + } + completeWriteWithoutResponseReadiness(error: MeshTransportError.notConnected) + writeWithoutResponseReadyID = waitID + writeWithoutResponseReadyContinuation = continuation + writeWithoutResponseReadyBinding = sessionBinding + writeWithoutResponseReadyTimeoutTask = Task { [weak self] in + try? await self?.operationClock.sleep(.seconds(timeout)) + guard !Task.isCancelled else { return } + await self?.timeoutWriteWithoutResponseReadiness(id: waitID) + } } + } onCancel: { + Task { await self.cancelWriteWithoutResponseReadiness(id: waitID) } } } - /// Fails a parked `sendWithoutResponse` caller when the peripheral has not re-signalled - /// readiness within the backstop interval. A no-op when no caller is parked. - private func timeoutWriteWithoutResponseReadiness() { - guard let continuation = writeWithoutResponseReadyContinuation else { return } - writeWithoutResponseReadyContinuation = nil - writeWithoutResponseReadyTimeoutTask = nil + private func timeoutWriteWithoutResponseReadiness(id: UUID) { + guard writeWithoutResponseReadyID == id else { return } logger.warning("[BLE] Write-without-response readiness timeout after \(writeTimeout)s") - continuation.resume(throwing: BLEError.operationTimeout) + completeWriteWithoutResponseReadiness(error: BLEError.operationTimeout) + } + + private func cancelWriteWithoutResponseReadiness(id: UUID) { + guard writeWithoutResponseReadyID == id else { return } + completeWriteWithoutResponseReadiness(error: CancellationError()) + } + + func cancelUnsubmittedWrites(sessionBinding: SessionTransportBinding) { + guard writeWithoutResponseReadyBinding === sessionBinding else { return } + completeWriteWithoutResponseReadiness(error: MeshTransportError.cancelledBeforeSubmission) } - /// Resumes a parked `sendWithoutResponse` caller when CoreBluetooth reports the peripheral - /// can accept another Write Command. A no-op when no caller is parked. - func handlePeripheralReadyForWriteWithoutResponse() { + private func completeWriteWithoutResponseReadiness(error: Error? = nil) { guard let continuation = writeWithoutResponseReadyContinuation else { return } writeWithoutResponseReadyContinuation = nil + writeWithoutResponseReadyID = nil + writeWithoutResponseReadyBinding = nil writeWithoutResponseReadyTimeoutTask?.cancel() writeWithoutResponseReadyTimeoutTask = nil - continuation.resume() + if let error { continuation.resume(throwing: error) } else { continuation.resume() } + } + + /// Resumes a parked sender only when its current peripheral can accept a Write Command. + func handlePeripheralReadyForWriteWithoutResponse(_ peripheral: CBPeripheral) { + guard case let .connected(current, _, _, _) = phase, + current === peripheral, + current.canSendWriteWithoutResponse else { return } + resumeWriteWithoutResponseReadiness() + } + + func handlePeripheralReadyForWriteWithoutResponse(_ peripheral: CBPeripheral, generation: UInt64) { + guard connectionGeneration == generation else { return } + handlePeripheralReadyForWriteWithoutResponse(peripheral) + } + + func resumeWriteWithoutResponseReadiness() { + completeWriteWithoutResponseReadiness() } /// Records whether the resolved write characteristic advertises Write-Without-Response. @@ -854,6 +993,7 @@ actor BLEStateMachine: BLEStateMachineProtocol { // Cancel all timeout tasks bluetoothPowerOffGraceTask?.cancel() bluetoothPowerOffGraceTask = nil + bluetoothPowerOffGraceID = nil autoReconnectDiscoveryTimeoutTask?.cancel() autoReconnectDiscoveryTimeoutTask = nil serviceDiscoveryTimeoutTask?.cancel() @@ -879,18 +1019,19 @@ actor BLEStateMachine: BLEStateMachineProtocol { case let .subscribingToNotifications(_, _, _, continuation): continuation.resume(throwing: CancellationError()) case let .connected(_, _, _, dataContinuation): - delegateHandler.setDataContinuation(nil) + delegateHandler.clearDataContinuation() dataContinuation.finish() default: break } let deviceID = phase.deviceID + bluetoothWaitID = nil phase = .idle phaseStartTime = Date() if let deviceID { - onDisconnection?(deviceID, nil) + notifyDisconnection(deviceID, nil) } } @@ -943,12 +1084,57 @@ actor BLEStateMachine: BLEStateMachineProtocol { // callers must call shutdown() explicitly before dropping the actor reference. /// Disconnects from the current device. - func disconnect() async { + func disconnect(expectedGeneration: UInt64? = nil) async { + await disconnect( + generation: expectedGeneration ?? connectionGeneration, sessionBinding: nil, pendingOnly: false + ) + } + + func disconnect(sessionBinding: SessionTransportBinding) async { + await disconnect(generation: connectionGeneration, sessionBinding: sessionBinding, pendingOnly: false) + } + + func cancelPendingEstablishment(sessionBinding: SessionTransportBinding) async { + await disconnect(generation: connectionGeneration, sessionBinding: sessionBinding, pendingOnly: true) + } + + private func permitsDisconnect(sessionBinding: SessionTransportBinding?, pendingOnly: Bool) -> Bool { + if let sessionBinding, activeSessionBinding !== sessionBinding { return false } + guard pendingOnly else { return true } + switch phase { + case .waitingForBluetooth, .connecting, .discoveringServices, .discoveringCharacteristics, + .subscribingToNotifications, .discoveryComplete: + return true + default: + return false + } + } + + private func disconnect(generation: UInt64, sessionBinding: SessionTransportBinding?, pendingOnly: Bool) async { + guard generation == connectionGeneration, + permitsDisconnect(sessionBinding: sessionBinding, pendingOnly: pendingOnly) else { return } + if let disconnectTask, disconnectTask.generation == generation { + await disconnectTask.task.value + return + } + let id = UUID() + let worker = Task { + await performDisconnect(generation: generation, sessionBinding: sessionBinding, pendingOnly: pendingOnly) + } + disconnectTask = (id, generation, worker) + await worker.value + if disconnectTask?.id == id { disconnectTask = nil } + } + + private func performDisconnect(generation: UInt64, sessionBinding: SessionTransportBinding?, pendingOnly: Bool) async { + guard generation == connectionGeneration, + permitsDisconnect(sessionBinding: sessionBinding, pendingOnly: pendingOnly) else { return } logger.info("Disconnect requested") // Cancel Bluetooth power-off grace period bluetoothPowerOffGraceTask?.cancel() bluetoothPowerOffGraceTask = nil + bluetoothPowerOffGraceID = nil // Cancel write timeout task writeTimeoutTask?.cancel() @@ -956,17 +1142,16 @@ actor BLEStateMachine: BLEStateMachineProtocol { // Reset queue tracking consecutiveQueuedWrites = 0 - earliestNextWrite = .now + earliestNextWrite = operationClock.now() - // Cancel pending write + // The pending continuation already called writeValue. Queued waiters have not. if let pending = pendingWriteContinuation { pendingWriteContinuation = nil pending.resume(throwing: BLEError.notConnected) } - // Resume all write waiters (they'll fail on the .connected check) while !writeWaiters.isEmpty { - writeWaiters.removeFirst().resume() + writeWaiters.removeFirst().continuation.resume(throwing: MeshTransportError.notConnected) } // Get peripheral before cancelling @@ -985,31 +1170,16 @@ actor BLEStateMachine: BLEStateMachineProtocol { centralManager.cancelPeripheralConnection(peripheral) // Wait briefly for disconnection to complete - try? await Task.sleep(for: .milliseconds(100)) + try? await operationClock.sleep(Self.disconnectSettleDelay) } + guard generation == connectionGeneration, + permitsDisconnect(sessionBinding: sessionBinding, pendingOnly: false) else { return } transition(to: .idle) logger.info("Disconnect complete") } - /// Switches to a different device. - /// - /// Disconnects from current device (if any) and connects to the new one. - /// - /// - Parameter deviceID: UUID of the new device to connect to - /// - Returns: AsyncStream of data from the new device - /// - Throws: BLEError if connection fails - func switchDevice(to deviceID: UUID) async throws -> AsyncStream { - logger.info("Switch device requested: \(deviceID)") - - // Disconnect current device - await disconnect() - - // Connect to new device - return try await connect(to: deviceID) - } - - private func connectToPeripheral(_ peripheral: CBPeripheral) async throws { + private func connectToPeripheral(_ peripheral: CBPeripheral, sessionBinding: SessionTransportBinding?) async throws { let pState = peripheralStateString(peripheral.state) logger.info("[BLE] Connecting to peripheral: \(peripheral.identifier.uuidString.prefix(8)), currentState: \(pState), timeout: \(connectionTimeout)s, autoReconnect: enabled") @@ -1032,7 +1202,19 @@ actor BLEStateMachine: BLEStateMachineProtocol { CBConnectPeripheralOptionNotifyOnNotificationKey: true, CBConnectPeripheralOptionEnableAutoReconnect: true ] - centralManager.connect(peripheral, options: options) + do { + if let sessionBinding { + try sessionBinding.performIfActive { + centralManager.connect(peripheral, options: options) + } + } else { + centralManager.connect(peripheral, options: options) + } + } catch { + timeoutTask.cancel() + transition(to: .idle) + continuation.resume(throwing: error) + } } } @@ -1089,6 +1271,15 @@ extension BLEStateMachine { } } + func installDataContinuation(_ continuation: AsyncStream.Continuation, peripheral: CBPeripheral, rx: CBCharacteristic) { + dataStreamSequence &+= 1 + let binding = activeSessionBinding.map { String(describing: ObjectIdentifier($0)) } + delegateHandler.setDataContinuation( + continuation, peripheral: peripheral, characteristic: rx, instanceID: instanceID, + generation: connectionGeneration, streamSequence: dataStreamSequence, binding: binding + ) + } + /// Replaces the connected phase's data stream with a fresh one and returns it, /// or returns nil when not `.connected`. /// @@ -1104,14 +1295,29 @@ extension BLEStateMachine { /// background keepalive on every rebuild), and the outgoing continuation is /// dropped without finish() because its consumer is already cancelled and /// continuation deinit terminates the dead storage. - func renewDataStream() -> AsyncStream? { + func renewDataStream(sessionBinding: SessionTransportBinding? = nil) -> AsyncStream? { + if let sessionBinding { + guard activeSessionBinding === sessionBinding, sessionBinding.isActive else { return nil } + } guard case let .connected(peripheral, tx, rx, _) = phase else { return nil } let (stream, continuation) = AsyncStream.makeStream( of: Data.self, bufferingPolicy: .bufferingOldest(512) ) - phase = .connected(peripheral: peripheral, tx: tx, rx: rx, dataContinuation: continuation) - delegateHandler.setDataContinuation(continuation) + do { + if let sessionBinding { + try sessionBinding.performIfActive { + phase = .connected(peripheral: peripheral, tx: tx, rx: rx, dataContinuation: continuation) + installDataContinuation(continuation, peripheral: peripheral, rx: rx) + } + } else { + phase = .connected(peripheral: peripheral, tx: tx, rx: rx, dataContinuation: continuation) + installDataContinuation(continuation, peripheral: peripheral, rx: rx) + } + } catch { + continuation.finish() + return nil + } return stream } @@ -1136,6 +1342,12 @@ extension BLEStateMachine { } switch oldPhase { + case .waitingForBluetooth: + bluetoothWaitID = nil + bluetoothPowerOffGraceTask?.cancel() + bluetoothPowerOffGraceTask = nil + bluetoothPowerOffGraceID = nil + case let .connecting(_, _, timeoutTask): timeoutTask.cancel() @@ -1149,7 +1361,7 @@ extension BLEStateMachine { // because that path keeps the phase `.connected`. appSessionLiveDeviceID = nil // Clear delegate handler's continuation first to stop data flow - delegateHandler.setDataContinuation(nil) + delegateHandler.clearDataContinuation() dataContinuation.finish() default: @@ -1164,7 +1376,7 @@ extension BLEStateMachine { writeTimeoutTask?.cancel() writeTimeoutTask = nil consecutiveQueuedWrites = 0 - earliestNextWrite = .now + earliestNextWrite = operationClock.now() // Outstanding write callbacks either never arrive (link dropped) or // find no continuation; their recorded sequences must not survive to // mis-tag the next connection's first write callback. @@ -1175,12 +1387,21 @@ extension BLEStateMachine { pending.resume(throwing: error) } + let unsubmitted = Self.unsubmittedWriteError(error) while !writeWaiters.isEmpty { - writeWaiters.removeFirst().resume() + writeWaiters.removeFirst().continuation.resume(throwing: unsubmitted) } // Release a Write-Command sender parked on backpressure so it doesn't hang past the drop. - handlePeripheralReadyForWriteWithoutResponse() + resumeWriteWithoutResponseReadiness() + } + + /// A queued waiter has not called `writeValue`. `BLEError.notConnected` after that call stays a submitted write. + private static func unsubmittedWriteError(_ error: Error) -> Error { + if let ble = error as? BLEError, case .notConnected = ble { + return MeshTransportError.notConnected + } + return error } /// Cancels the current operation, resuming any pending continuation with an error. @@ -1313,7 +1534,7 @@ extension BLEStateMachine { ) centralManager.cancelPeripheralConnection(peripheral) transition(to: .idle) - onDisconnection?(peripheral.identifier, teardownError) + notifyDisconnection(peripheral.identifier, teardownError) } } } diff --git a/MC1Services/Sources/MC1Services/Transport/BLEStateMachineProtocol.swift b/MC1Services/Sources/MC1Services/Transport/BLEStateMachineProtocol.swift index 8cffc031d7..3dcac18a2f 100644 --- a/MC1Services/Sources/MC1Services/Transport/BLEStateMachineProtocol.swift +++ b/MC1Services/Sources/MC1Services/Transport/BLEStateMachineProtocol.swift @@ -2,6 +2,7 @@ @preconcurrency import CoreBluetooth import Foundation +import MeshCore /// Protocol for BLE state machine operations used by ConnectionManager. /// Enables dependency injection for testing. @@ -48,17 +49,6 @@ public protocol BLEStateMachineProtocol: Actor { /// Activates the central manager if needed. func activate() - /// Sets a handler for auto-reconnecting events. - /// Called when device disconnects but iOS is attempting automatic reconnection. - /// - Parameters: - /// - deviceID: The disconnected device ID. - /// - errorInfo: Best-effort error summary from CoreBluetooth. - func setAutoReconnectingHandler(_ handler: @escaping @Sendable (UUID, String) -> Void) - - /// Peripheral link loss with the CoreBluetooth event time. - /// Not fired for local shutdown or the phone's own Bluetooth power-off. - func setRemoteLinkLostHandler(_ handler: @escaping @Sendable (UUID, CFAbsoluteTime) -> Void) - /// Sets a handler called when Bluetooth powers on func setBluetoothPoweredOnHandler(_ handler: @escaping @Sendable () -> Void) @@ -67,6 +57,7 @@ public protocol BLEStateMachineProtocol: Actor { /// budget. Seeded from persistence at wiring time and refreshed after every /// verified session. func recordBondVerification(deviceID: UUID, at date: Date) + func recordBondVerification(deviceID: UUID, at date: Date, sessionBinding: SessionTransportBinding) /// Clears a device's bond-verification record when its pairing is /// forgotten, so a stale verification cannot shield the next episode. @@ -76,6 +67,7 @@ public protocol BLEStateMachineProtocol: Actor { /// `deviceID` (non-nil) or that no session is live (nil). Awaited from /// ConnectionManager so RSSI bond refresh cannot race a stale flag. func setAppSessionLive(deviceID: UUID?) + func setAppSessionLive(deviceID: UUID?, sessionBinding: SessionTransportBinding) /// Whether the given device currently has a bond-verification stamp. Used by /// ConnectionManager to re-validate before persisting an RSSI bond refresh. @@ -98,6 +90,7 @@ public protocol BLEStateMachineProtocol: Actor { /// Sets the delay between write operations for pacing. func setWritePacingDelay(_ delay: TimeInterval) + func setWritePacingDelay(_ delay: TimeInterval, sessionBinding: SessionTransportBinding) /// Sets a handler called when a device is discovered during scanning. func setDeviceDiscoveredHandler(_ handler: @escaping @Sendable (UUID, String?, Int) -> Void) diff --git a/MC1Services/Sources/MC1Services/Transport/ReconnectPolicy.swift b/MC1Services/Sources/MC1Services/Transport/ReconnectPolicy.swift index 3f16803869..3f47f546f9 100644 --- a/MC1Services/Sources/MC1Services/Transport/ReconnectPolicy.swift +++ b/MC1Services/Sources/MC1Services/Transport/ReconnectPolicy.swift @@ -97,7 +97,7 @@ struct ReconnectPolicy { /// `didFailToConnect` already consumed the pending connect; tearing /// down would leave only a watchdog whose sleep freezes when suspended. case continueEpisodeAfterBudget(reason: BudgetHoldReason) - /// End the episode, surfacing `error` through `onDisconnection`. + /// End the episode, surfacing `error` through `BLELifecycleEvent.disconnected`. case tearDown(error: BLEError, reason: TeardownReason) } @@ -179,7 +179,7 @@ struct ReconnectPolicy { case waitForPendingConnect /// Give discovery another window instead of tearing down a live link. case extendDiscoveryWindow(extensionCount: Int, budget: Int) - /// End the episode, surfacing `error` through `onDisconnection`. + /// End the episode, surfacing `error` through `BLELifecycleEvent.disconnected`. case tearDown(error: BLEError) } diff --git a/MC1Services/Sources/MC1Services/Transport/iOSBLETransport.swift b/MC1Services/Sources/MC1Services/Transport/iOSBLETransport.swift index 8aae33588c..a719d149ed 100644 --- a/MC1Services/Sources/MC1Services/Transport/iOSBLETransport.swift +++ b/MC1Services/Sources/MC1Services/Transport/iOSBLETransport.swift @@ -11,7 +11,6 @@ import os /// - **State restoration**: Background app relaunch via CoreBluetooth restoration /// - **Auto-reconnect**: iOS 17+ automatic reconnection handling /// - **Proper cleanup**: Continuation and resource management on all transitions -/// - **Device switching**: Switch between devices without full disconnect/reconnect /// /// ## Usage /// @@ -22,14 +21,14 @@ import os /// await transport.setDeviceID(deviceUUID) /// try await transport.connect() /// -/// // Switch to a different device -/// try await transport.switchDevice(to: otherDeviceUUID) /// ``` actor iOSBLETransport: MeshTransport { private let logger = PersistentLogger(subsystem: "com.mc1", category: "iOSBLETransport") private let stateMachine: BLEStateMachine private var deviceID: UUID? + private var sessionBinding: SessionTransportBinding? + private var physicalCloseTask: (id: UUID, task: Task)? /// Lock-protected data stream storage. /// Using a lock allows synchronous access from BLEStateMachine callbacks without spawning Tasks. @@ -44,6 +43,32 @@ actor iOSBLETransport: MeshTransport { self.stateMachine = stateMachine ?? BLEStateMachine() } + func makeSessionTransport(deviceID: UUID, binding: SessionTransportBinding) async -> SessionBoundTransport { + if let physicalCloseTask { await physicalCloseTask.task.value } + do { + try binding.performIfActive { + if sessionBinding !== binding { sessionBinding?.revoke() } + self.deviceID = deviceID + sessionBinding = binding + } + await stateMachine.setSessionBinding(binding) + } catch { + return SessionBoundTransport(transport: self, binding: binding) + } + return SessionBoundTransport(transport: self, binding: binding) + } + + var lifecycleOrigin: BLELifecycleOrigin? { + get async { await stateMachine.lifecycleOrigin } + } + + func setLifecycleHandler(_ handler: @escaping @Sendable (BLELifecycleEvent) -> Void) async { + await stateMachine.setLifecycleEventHandler { [dataStreamLock] event, stream in + if let stream { dataStreamLock.withLock { $0 = stream } } + handler(event) + } + } + // MARK: - Configuration /// Sets the device UUID to connect to. @@ -53,30 +78,6 @@ actor iOSBLETransport: MeshTransport { deviceID = id } - /// Sets a handler for disconnection events. - /// - /// - Parameter handler: Called when the device disconnects, with the device ID and optional error. - func setDisconnectionHandler(_ handler: @escaping @Sendable (UUID, Error?) -> Void) async { - await stateMachine.setDisconnectionHandler(handler) - } - - /// Sets a handler for reconnection events. - /// - /// When iOS auto-reconnect completes, the transport captures the data stream - /// and then calls your handler. The `receivedData` property will be ready - /// when your handler is called. - /// - /// - Parameter handler: Called when iOS auto-reconnect completes successfully. - func setReconnectionHandler(_ handler: @escaping @Sendable (UUID) -> Void) async { - await stateMachine.setReconnectionHandler { [dataStreamLock, logger] deviceID, stream in - // Capture the stream synchronously using lock (no Task spawning). - // This ensures the stream is available before any handler code runs. - logger.info("[BLE] Auto-reconnect stream captured for device: \(deviceID.uuidString.prefix(8))") - dataStreamLock.withLock { $0 = stream } - handler(deviceID) - } - } - // MARK: - MeshTransport Protocol /// Whether the transport is currently connected to a device. @@ -91,17 +92,22 @@ actor iOSBLETransport: MeshTransport { dataStreamLock.withLock { $0 } ?? AsyncStream { $0.finish() } } - /// Connects to the configured device. - /// - /// This method is idempotent: if already connected to the same device, - /// it returns without error. Use ``switchDevice(to:)`` to change devices. - /// - /// - Throws: `BLEError.deviceNotFound` if no device ID is set. - /// - Throws: `BLEError.connectionFailed` if connected to a different device. - /// - Throws: `BLEError` for connection failures. + /// Connects to the configured radio; repeated connects to the same Device ID are no-ops. + /// Connecting to a different Device ID requires disconnecting first. func connect() async throws { + try await performConnect(sessionBinding: nil) + } + + func connect(sessionBinding: SessionTransportBinding) async throws { + guard self.sessionBinding === sessionBinding else { throw CancellationError() } + try await performConnect(sessionBinding: sessionBinding) + } + + private func performConnect(sessionBinding: SessionTransportBinding?) async throws { + try sessionBinding?.checkActive() + let configuredDeviceID = deviceID let connectedID = await stateMachine.connectedDeviceID - let effectiveDeviceID = deviceID ?? connectedID + let effectiveDeviceID = configuredDeviceID ?? connectedID guard let deviceID = effectiveDeviceID else { logger.warning("[BLE] connect() called with no device ID set") @@ -110,34 +116,74 @@ actor iOSBLETransport: MeshTransport { // Already connected - check if it's the same device if await stateMachine.isConnected { + try sessionBinding?.checkActive() if connectedID == deviceID { logger.info("Already connected to device: \(deviceID)") return } else { - throw BLEError.connectionFailed("Already connected to different device: \(connectedID?.uuidString ?? "unknown"). Use switchDevice() instead.") + throw BLEError.connectionFailed("Already connected to different device: \(connectedID?.uuidString ?? "unknown"). Disconnect before connecting to a different device.") } } logger.info("Connecting to device: \(deviceID)") - let stream = try await stateMachine.connect(to: deviceID) + let stream = try await stateMachine.connect(to: deviceID, sessionBinding: sessionBinding) + try sessionBinding?.checkActive() logger.info("[BLE] Stream captured for device: \(deviceID.uuidString.prefix(8))") dataStreamLock.withLock { $0 = stream } } /// Disconnects from the current device. func disconnect() async { - logger.info("Disconnecting") - await stateMachine.disconnect() - dataStreamLock.withLock { $0 = nil } + await closePhysicalTransport() } - /// Replaces the stored data stream with a fresh one from the state machine. - /// - /// Call before constructing a session over an existing link whose previous - /// session was stopped: the stop cancelled the old stream's shared storage, - /// and this slot is otherwise rewritten only on connect, switchDevice, and - /// auto-reconnect completion. A declined renewal (not connected) leaves the - /// slot untouched and is logged so a failing rebuild is attributable. + func disconnect(sessionBinding: SessionTransportBinding) async { + guard self.sessionBinding === sessionBinding else { return } + await closePhysicalTransport() + } + + func cancelPendingEstablishment(sessionBinding: SessionTransportBinding) async { + guard self.sessionBinding === sessionBinding else { return } + await stateMachine.cancelPendingEstablishment(sessionBinding: sessionBinding) + } + + func cancelUnsubmittedWrites(sessionBinding: SessionTransportBinding) async { + await stateMachine.cancelUnsubmittedWrites(sessionBinding: sessionBinding) + } + + private func closePhysicalTransport() async { + if let physicalCloseTask { + await physicalCloseTask.task.value + return + } + let id = UUID() + let owner = sessionBinding + owner?.revoke() + let worker = Task { + if let owner { + await stateMachine.disconnect(sessionBinding: owner) + } else { + await stateMachine.disconnect() + } + } + physicalCloseTask = (id, worker) + await worker.value + guard physicalCloseTask?.id == id else { return } + if sessionBinding === owner { + dataStreamLock.withLock { $0 = nil } + } + physicalCloseTask = nil + } + + func receivedData(sessionBinding: SessionTransportBinding) -> AsyncStream { + guard self.sessionBinding === sessionBinding, sessionBinding.isActive else { + return AsyncStream { $0.finish() } + } + return receivedData + } + + /// Renews the receive stream before reusing a connected link for a new session. + /// Stopping the previous session cancelled the old stream's shared storage. func refreshDataStream() async { guard let stream = await stateMachine.renewDataStream() else { let phaseName = await stateMachine.currentPhase.name @@ -148,15 +194,27 @@ actor iOSBLETransport: MeshTransport { dataStreamLock.withLock { $0 = stream } } + func refreshDataStream(sessionBinding: SessionTransportBinding) async { + guard self.sessionBinding === sessionBinding, sessionBinding.isActive, + let stream = await stateMachine.renewDataStream(sessionBinding: sessionBinding), + self.sessionBinding === sessionBinding, sessionBinding.isActive else { return } + dataStreamLock.withLock { $0 = stream } + } + /// Sends data to the connected device. /// /// - Parameter data: The data to send. - /// - Throws: `BLEError.notConnected` if not connected. + /// - Throws: `MeshTransportError.notConnected` before `writeValue`, or `BLEError.notConnected` after it. /// - Throws: `BLEError.writeError` if the write fails. func send(_ data: Data) async throws { try await stateMachine.send(data) } + func send(_ data: Data, sessionBinding: SessionTransportBinding) async throws { + guard self.sessionBinding === sessionBinding else { throw CancellationError() } + try await stateMachine.send(data, sessionBinding: sessionBinding) + } + /// Whether the connected radio's write characteristic advertises Write-Without-Response. var supportsWriteWithoutResponse: Bool { get async { await stateMachine.supportsWriteWithoutResponse } @@ -165,29 +223,20 @@ actor iOSBLETransport: MeshTransport { /// Sends data as an unacknowledged ATT Write Command, enabling request pipelining. /// /// - Parameter data: The data to send. - /// - Throws: `BLEError.notConnected` if not connected. + /// - Throws: `MeshTransportError.notConnected` before `writeValue`, or `BLEError.notConnected` after it. func sendWithoutResponse(_ data: Data) async throws { try await stateMachine.sendWithoutResponse(data) } + func sendWithoutResponse(_ data: Data, sessionBinding: SessionTransportBinding) async throws { + guard self.sessionBinding === sessionBinding else { throw CancellationError() } + try await stateMachine.sendWithoutResponse(data, sessionBinding: sessionBinding) + } + // MARK: - Extended API /// UUID of the currently connected device, or nil if not connected. var connectedDeviceID: UUID? { get async { await stateMachine.connectedDeviceID } } - - /// Switches to a different device. - /// - /// Disconnects from the current device (if any) and connects to the new one. - /// More efficient than separate disconnect/connect calls. - /// - /// - Parameter deviceID: UUID of the new device to connect to. - /// - Throws: `BLEError` if connection fails. - func switchDevice(to deviceID: UUID) async throws { - logger.info("Switching to device: \(deviceID)") - self.deviceID = deviceID - let stream = try await stateMachine.switchDevice(to: deviceID) - dataStreamLock.withLock { $0 = stream } - } } diff --git a/MC1Services/Sources/MC1Services/Transport/iOSMeshTransport.swift b/MC1Services/Sources/MC1Services/Transport/iOSMeshTransport.swift index 365d4c2d72..3c982c9064 100644 --- a/MC1Services/Sources/MC1Services/Transport/iOSMeshTransport.swift +++ b/MC1Services/Sources/MC1Services/Transport/iOSMeshTransport.swift @@ -6,16 +6,18 @@ import MeshCore /// targets a place to inject a mock transport while leaving the platform-agnostic /// `MeshTransport` contract unchanged. public protocol iOSMeshTransport: MeshTransport { - func setDeviceID(_ id: UUID) async - func switchDevice(to deviceID: UUID) async throws - func setDisconnectionHandler(_ handler: @escaping @Sendable (UUID, Error?) -> Void) async - func setReconnectionHandler(_ handler: @escaping @Sendable (UUID) -> Void) async + func makeSessionTransport(deviceID: UUID, binding: SessionTransportBinding) async -> SessionBoundTransport + func cancelPendingEstablishment(sessionBinding: SessionTransportBinding) async + func cancelUnsubmittedWrites(sessionBinding: SessionTransportBinding) async + func setLifecycleHandler(_ handler: @escaping @Sendable (BLELifecycleEvent) -> Void) async + var lifecycleOrigin: BLELifecycleOrigin? { get async } /// Re-vends `receivedData` for a session rebuild over the existing link. /// A stopped predecessor session's receive-loop cancellation terminates the /// vended stream's shared storage, so without a refresh the next session /// iterates a dead stream and its handshake times out. func refreshDataStream() async + func refreshDataStream(sessionBinding: SessionTransportBinding) async } extension iOSBLETransport: iOSMeshTransport {} diff --git a/MC1Services/Sources/MC1Services/Utilities/ChannelMessageFormat.swift b/MC1Services/Sources/MC1Services/Utilities/ChannelMessageFormat.swift index e0e4349601..2f1b8bf3d6 100644 --- a/MC1Services/Sources/MC1Services/Utilities/ChannelMessageFormat.swift +++ b/MC1Services/Sources/MC1Services/Utilities/ChannelMessageFormat.swift @@ -22,4 +22,13 @@ enum ChannelMessageFormat { let messageText = String(text[afterColon...]).trimmingCharacters(in: .whitespaces) return (senderName, messageText) } + + /// Removes the sender delimiter and its single framing space for rule matching. + static func originalFields(_ text: String) -> (sender: String?, body: String) { + guard let colon = text.firstIndex(of: ":"), colon != text.startIndex else { + return (nil, text) + } + let body = text[text.index(after: colon)...] + return (String(text[..` is the reserved terminator and is stripped /// from the name on emit; the name may legitimately contain `:`. public enum ContactShareUtilities { diff --git a/MC1Services/Sources/MC1Services/Utilities/VContactIdentity.swift b/MC1Services/Sources/MC1Services/Utilities/VContactIdentity.swift index 94c24326cf..3f036a7607 100644 --- a/MC1Services/Sources/MC1Services/Utilities/VContactIdentity.swift +++ b/MC1Services/Sources/MC1Services/Utilities/VContactIdentity.swift @@ -32,4 +32,14 @@ public enum VContactIdentity { guard publicKey.count == ProtocolLimits.publicKeySize else { return false } return publicKey == Self.publicKey(forSelfPublicKey: selfPublicKey) } + + /// Whether `publicKeyHex` is the V-contact for any of `selfPublicKeys`. + /// Either hex case matches. An unparseable key returns false so validation still sees it. + public static func isVContact(publicKeyHex: String, selfPublicKeys: [Data]) -> Bool { + guard let publicKey = Data(hexString: publicKeyHex), + publicKey.count == ProtocolLimits.publicKeySize else { + return false + } + return selfPublicKeys.contains { isVContact(publicKey: publicKey, selfPublicKey: $0) } + } } diff --git a/MC1Services/Tests/MC1ServicesTests/AdvertisementCleanupContractTests.swift b/MC1Services/Tests/MC1ServicesTests/AdvertisementCleanupContractTests.swift new file mode 100644 index 0000000000..9414eb9cb3 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/AdvertisementCleanupContractTests.swift @@ -0,0 +1,264 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing +import UserNotifications + +@Suite("Advertisement cleanup contract") +@MainActor +struct AdvertisementCleanupContractTests { + @Test(arguments: [false, true]) + func `committed deletion removes captured notifications without a presentation subscriber`(foreground: Bool) async throws { + let fixture = try await Fixture(foreground: foreground) + do { + let contact = try await fixture.addContact(seed: 41) + fixture.recorder.addRequests(contactID: contact.id, prefix: "deleted") + fixture.recorder.addRequests(contactID: UUID(), prefix: "unrelated") + await fixture.transport.inject(Data([ResponseCode.contactDeleted.rawValue]) + contact.publicKey) + try await fixture.waitUntil { + if foreground { + return try await fixture.store.fetchContact(id: contact.id) == nil + } + return await fixture.service.pendingDeletedKeys.contains(contact.publicKey) + } + + await fixture.service.stopEventMonitoring() + + #expect(try await fixture.store.fetchContact(id: contact.id) == nil) + #expect(try await fixture.store.fetchMessages(contactID: contact.id, limit: 10, offset: 0).isEmpty) + #expect(Set(fixture.recorder.removed) == ["deleted-dm", "deleted-reaction"]) + #expect(fixture.recorder.requests.map(\.identifier).sorted() == ["unrelated-dm", "unrelated-reaction"]) + #expect(fixture.recorder.badges.isEmpty) + _ = try await fixture.session.getTime() + } catch { + await fixture.cleanup() + throw error + } + await fixture.cleanup() + } + + @Test(arguments: [false, true]) + func `held system cleanup does not block deletion admission or trace presentation`(deferred: Bool) async throws { + let fixture = try await Fixture(foreground: !deferred) + let first = try await fixture.addContact(seed: 42) + let second = try await fixture.addContact(seed: 43) + fixture.recorder.addRequests(contactID: first.id, prefix: "first") + fixture.recorder.addRequests(contactID: second.id, prefix: "second") + fixture.recorder.addRequests(contactID: UUID(), prefix: "unrelated") + fixture.recorder.holdNextSnapshot = true + let events = fixture.service.events() + let receipt = Receipt() + let listener = Task { + for await event in events { + if case .traceResponse = event { receipt.traceSeen = true } + } + } + var flush: Task? + var stop: Task? + do { + await fixture.transport.inject(Data([ResponseCode.contactDeleted.rawValue]) + first.publicKey) + if deferred { + try await fixture.waitUntil { await fixture.service.pendingDeletedKeys.contains(first.publicKey) } + await fixture.scene.setIsInForeground(true) + flush = Task { await fixture.service.handleReturnToForeground() } + } + try await fixture.waitUntil { fixture.recorder.snapshotIsHeld } + #expect(try await fixture.store.fetchContact(id: first.id) == nil) + if deferred { await fixture.scene.setIsInForeground(false) } + await fixture.transport.inject(Data([ResponseCode.contactDeleted.rawValue]) + second.publicKey) + var trace = Data([ResponseCode.traceData.rawValue, 0, 0, 0]) + for value: UInt32 in [999, 888] { + trace.append(withUnsafeBytes(of: value.littleEndian) { Data($0) }) + } + trace.append(0x28) + await fixture.transport.inject(trace) + try await fixture.waitUntil { + await fixture.service.pendingDeletedKeys.contains(second.publicKey) && receipt.traceSeen + } + #expect(try await fixture.store.fetchContact(id: second.id) != nil) + stop = Task { + await fixture.service.stopEventMonitoring() + receipt.stopped = true + } + let endedEarly = await fixture.observedWithin(.milliseconds(80)) { receipt.stopped } + #expect(!endedEarly) + fixture.recorder.releaseSnapshot() + await flush?.value + await stop?.value + await fixture.service.stopEventMonitoring() + #expect(try await fixture.store.fetchContact(id: second.id) == nil) + #expect(Set(fixture.recorder.removed) == ["first-dm", "first-reaction", "second-dm", "second-reaction"]) + #expect(fixture.recorder.removed.count == 4) + #expect(fixture.recorder.requests.map(\.identifier).sorted() == ["unrelated-dm", "unrelated-reaction"]) + #expect(fixture.recorder.badges.isEmpty) + _ = try await fixture.session.getTime() + } catch { + fixture.recorder.releaseSnapshot() + await flush?.value + await fixture.cleanup() + await stop?.value + await listener.value + throw error + } + await fixture.cleanup() + await listener.value + } + + @Test(arguments: DeletionControl.allCases) + func `uncommitted or skipped deletion removes no notification`(control: DeletionControl) async throws { + let mock = MockPersistenceStore() + let fixture = try await Fixture(foreground: false, store: mock) + var flush: Task? + do { + let contact = try await fixture.addContact(seed: 44) + fixture.recorder.addRequests(contactID: contact.id, prefix: "preserved") + let key = control == .empty ? Data(repeating: 45, count: 32) : contact.publicKey + await fixture.transport.inject(Data([ResponseCode.contactDeleted.rawValue]) + key) + try await fixture.waitUntil { await fixture.service.pendingDeletedKeys.contains(key) } + if control == .failed { await mock.setStubbedDeleteContactError(ControlError.storeUnavailable) } + if control == .revived { await mock.holdNextDeleteContacts() } + await fixture.scene.setIsInForeground(true) + flush = Task { await fixture.service.handleReturnToForeground() } + if control == .revived { + try await fixture.waitUntil { await mock.isDeleteContactsHeld } + await fixture.transport.inject(Data([ResponseCode.advertisement.rawValue]) + key) + try await fixture.waitUntil { await fixture.service.pendingAdvertKeys.contains(key) } + await mock.releaseDeleteContacts() + } + await flush?.value + await fixture.service.stopEventMonitoring() + #expect(fixture.recorder.removed.isEmpty) + #expect(fixture.recorder.loads == 0) + #expect(try await fixture.store.fetchContact(id: contact.id) != nil) + _ = try await fixture.session.getTime() + } catch { + await mock.releaseDeleteContacts() + await flush?.value + await fixture.cleanup() + throw error + } + await fixture.cleanup() + } + + enum DeletionControl: CaseIterable, Sendable { case failed, empty, revived } + private enum ControlError: Error { case storeUnavailable, expired } + + @MainActor + private final class Receipt { + var traceSeen = false + var stopped = false + } + + @MainActor + private final class Fixture { + let radioID = UUID() + let transport = ConnectionTestRadioTransport() + let session: MeshCoreSession + let store: any PersistenceStoreProtocol + let scene: MockAppStateProvider + let service: AdvertisementService + let recorder = Recorder() + let defaults: UserDefaults + let suite = "test.cleanup-contract.\(UUID())" + + init(foreground: Bool, store suppliedStore: (any PersistenceStoreProtocol)? = nil) async throws { + defaults = try #require(UserDefaults(suiteName: suite)) + if let suppliedStore { + store = suppliedStore + } else { + store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + } + scene = MockAppStateProvider(isInForeground: foreground) + session = MeshCoreSession(transport: transport) + let notificationService = NotificationService(notificationDefaults: defaults, systemOperations: recorder.operations) + let contacts = ContactService(session: session, dataStore: store, syncCoordinator: nil, cleanupCoordinator: nil) + service = AdvertisementService( + session: session, dataStore: store, contactService: contacts, + appStateProvider: scene, notificationService: notificationService + ) + try await session.start() + await service.startEventMonitoring(radioID: radioID) + try await waitUntil { await self.session.subscriberCountForTest > 0 } + } + + func addContact(seed: UInt8) async throws -> ContactDTO { + let frame = ContactFrame( + publicKey: Data(repeating: seed, count: 32), type: .chat, flags: 0, + outPathLength: 0, outPath: Data(), name: "Contact", lastAdvertTimestamp: 0, + latitude: 0, longitude: 0, lastModified: 0 + ) + let saved = try await store.saveContact(radioID: radioID, from: frame) + try await store.saveMessage(MessageDTO.testDirectMessage(radioID: radioID, contactID: saved.id, text: "message")) + return try #require(await store.fetchContact(id: saved.id)) + } + + func waitUntil(_ predicate: @MainActor () async throws -> Bool) async throws { + guard try await observedWithin(.seconds(1), predicate) else { throw ControlError.expired } + } + + func observedWithin(_ duration: Duration, _ predicate: @MainActor () async throws -> Bool) async rethrows -> Bool { + let deadline = ContinuousClock.now.advanced(by: duration) + while try await !predicate() { + guard ContinuousClock.now < deadline else { return false } + try? await Task.sleep(for: .milliseconds(1)) + } + return true + } + + func cleanup() async { + recorder.releaseSnapshot() + await service.stopEventMonitoring() + service.finishEvents() + await session.stop() + await session.waitForQuiescence() + #expect(await session.subscriberCountForTest == 0) + defaults.removePersistentDomain(forName: suite) + } + } + + @MainActor + private final class Recorder { + var requests: [UNNotificationRequest] = [] + var removed: [String] = [] + var badges: [Int] = [] + var loads = 0 + var holdNextSnapshot = false + var snapshotIsHeld = false + var snapshotWaiter: CheckedContinuation? + + func addRequests(contactID: UUID, prefix: String) { + for type in ["dm", "reaction"] { + let content = UNMutableNotificationContent() + content.userInfo = ["contactID": contactID.uuidString, "type": type] + requests.append(UNNotificationRequest(identifier: "\(prefix)-\(type)", content: content, trigger: nil)) + } + } + + func releaseSnapshot() { + snapshotWaiter?.resume() + snapshotWaiter = nil + snapshotIsHeld = false + holdNextSnapshot = false + } + + var operations: NotificationService.SystemOperations { + .init( + setBadgeCount: { self.badges.append($0) }, + deliveredRequests: { + self.loads += 1 + if self.holdNextSnapshot { + self.holdNextSnapshot = false + self.snapshotIsHeld = true + await withCheckedContinuation { self.snapshotWaiter = $0 } + self.snapshotIsHeld = false + } + return self.requests + }, + removeDeliveredNotifications: { identifiers in + self.removed.append(contentsOf: identifiers) + self.requests.removeAll { identifiers.contains($0.identifier) } + } + ) + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/AdvertisementDeltaDrainContractTests.swift b/MC1Services/Tests/MC1ServicesTests/AdvertisementDeltaDrainContractTests.swift new file mode 100644 index 0000000000..6812203f4c --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/AdvertisementDeltaDrainContractTests.swift @@ -0,0 +1,88 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("Advertisement delta drain contract") +@MainActor +struct AdvertisementDeltaDrainContractTests { + @Test + func `stop joins admitted delta effects`() async throws { + let radioID = UUID() + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let transport = ConnectionTestRadioTransport() + let session = MeshCoreSession(transport: transport) + let contacts = ContactService(session: session, dataStore: store, syncCoordinator: nil, cleanupCoordinator: nil) + let adverts = AdvertisementService( + session: session, dataStore: store, contactService: contacts, + advertSyncDebounce: .zero, advertSyncMinInterval: .zero, advertSyncBusyBackoff: .zero + ) + let gate = Gate() + let receipt = Receipt() + let key = Data(repeating: 0x34, count: ProtocolLimits.publicKeySize) + let frame = ContactFrame( + publicKey: key, type: .chat, flags: 0, outPathLength: 0, outPath: Data(), + name: "Admitted", lastAdvertTimestamp: 0, latitude: 0, longitude: 0, lastModified: 0 + ) + var stopping: Task? + do { + try await session.start() + await adverts.setDeltaSyncHandler { _ in + await gate.wait() + _ = try? await store.saveContact(radioID: radioID, from: frame) + return .synced + } + await adverts.startEventMonitoring(radioID: radioID) + try await waitUntil("actual advert subscription should be installed") { + await session.subscriberCountForTest > 0 + } + await transport.inject(Data([ResponseCode.advertisement.rawValue]) + key) + try await waitUntil("actual advert should enter its admitted delta handler") { await gate.isWaiting } + stopping = Task { + await adverts.stopEventMonitoring() + receipt.stopped = true + } + try await waitUntil("stop should revoke new delta admission") { await adverts.deltaSyncHandler == nil } + try? await Task.sleep(for: .milliseconds(50)) + #expect(!receipt.stopped, "Cancellation alone cannot settle admitted store work") + await gate.release() + await stopping?.value + #expect(try await store.fetchContact(radioID: radioID, publicKey: key) != nil) + #expect(await adverts.deltaSyncTask == nil) + _ = try await session.getTime() + } catch { + await gate.release() + await stopping?.value + await adverts.stopEventMonitoring() + adverts.finishEvents() + await session.stop() + await session.waitForQuiescence() + throw error + } + adverts.finishEvents() + await session.stop() + await session.waitForQuiescence() + #expect(await session.subscriberCountForTest == 0) + } + + @MainActor + private final class Receipt { var stopped = false } + + private actor Gate { + private var waiter: CheckedContinuation? + private var isReleased = false + private(set) var isWaiting = false + func wait() async { + guard !isReleased else { return } + isWaiting = true + await withCheckedContinuation { waiter = $0 } + isWaiting = false + } + + func release() { + isReleased = true + waiter?.resume() + waiter = nil + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/AdvertisementServiceTests.swift b/MC1Services/Tests/MC1ServicesTests/AdvertisementServiceTests.swift index 9cd62c04cc..0b41764575 100644 --- a/MC1Services/Tests/MC1ServicesTests/AdvertisementServiceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/AdvertisementServiceTests.swift @@ -366,6 +366,7 @@ struct AdvertisementServiceTests { #expect(await waitForEventProcessing(service, session: session)) #expect(await service.contactsDeletedDuringSync.contains(key)) let round = try #require(await service.deltaSyncTask) + await service.flushPendingDeletedKeys() await hold.release() await round.value @@ -1272,8 +1273,11 @@ struct AdvertisementServiceTests { #expect(deleted) // Teardown cancels the round and clears the handler while the commit runs. - await service.stopEventMonitoring() + let stopping = Task { await service.stopEventMonitoring() } + let handlerDropped = await waitUntil { await service.deltaSyncHandler == nil } + #expect(handlerDropped) await hold.release() + await stopping.value let committed = await waitUntil { await marker.committed } #expect(committed) @@ -2159,6 +2163,7 @@ struct AdvertisementServiceTests { // A DM in the debounce window needs a Contact row immediately so the live // notify path can run. Materialize from the pending 0x80 key. let store = try await makeStore() + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) let session = MockMeshCoreSession() let service = makeService(session: session, store: store) @@ -2175,7 +2180,7 @@ struct AdvertisementServiceTests { let prefix = Data(key.prefix(6)) let contact = try #require( - await service.materializeContactForPendingAdvert(matchingPrefix: prefix, radioID: radioID) + await service.materializeContactForPendingAdvert(matchingPrefix: prefix, scope: scope) ) #expect(contact.publicKey == key) #expect(contact.name == "DebounceNode") @@ -2188,9 +2193,41 @@ struct AdvertisementServiceTests { await service.stopEventMonitoring() } + @Test + func `materializeContactForPendingAdvert discards response after partition retirement`() async throws { + let store = try await makeStore() + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) + let device = try #require(await store.fetchDevice(radioID: radioID)) + let session = MockMeshCoreSession() + let service = makeService(session: session, store: store) + let key = makePublicKey(seed: 0xB8) + await service.recordPendingAdvertKey(key) + await session.setStubbedContact(makeMeshContact(publicKey: key, name: "Retired"), for: key) + await session.holdNextGetContact(for: key) + let task = Task { + await service.materializeContactForPendingAdvert(matchingPrefix: Data(key.prefix(6)), scope: scope) + } + + let held = await waitUntil { await session.isGetContactHeld(for: key) } + do { + try #require(held) + _ = try await store.beginRadioErase(device) + } catch { + await session.releaseGetContact(for: key) + task.cancel() + throw error + } + + await session.releaseGetContact(for: key) + #expect(await task.value == nil) + #expect(try await store.fetchContact(radioID: radioID, publicKey: key) == nil) + #expect(try await store.fetchDiscoveredNodes(radioID: radioID).isEmpty) + } + @Test func `materializeContactForPendingAdvert returns nil without pending match`() async throws { let store = try await makeStore() + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) let session = MockMeshCoreSession() let service = makeService(session: session, store: store) let key = makePublicKey(seed: 0x8E) @@ -2199,7 +2236,7 @@ struct AdvertisementServiceTests { await startMonitoring(service, session: session) let result = await service.materializeContactForPendingAdvert( matchingPrefix: Data(key.prefix(6)), - radioID: radioID + scope: scope ) #expect(result == nil) #expect(await session.getContactPublicKeys.isEmpty) @@ -2209,6 +2246,7 @@ struct AdvertisementServiceTests { @Test func `materializeContactForPendingAdvert returns nil on multi-match prefix`() async throws { let store = try await makeStore() + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) let session = MockMeshCoreSession() let service = makeService(session: session, store: store) @@ -2223,7 +2261,7 @@ struct AdvertisementServiceTests { await service.recordPendingAdvertKey(keyB) let result = await service.materializeContactForPendingAdvert( matchingPrefix: Data([0xAB]), - radioID: radioID + scope: scope ) #expect(result == nil) #expect(await session.getContactPublicKeys.isEmpty) @@ -2795,6 +2833,7 @@ struct AdvertisementServiceTests { @Test func `materializeContactForPendingAdvert still works while backgrounded`() async throws { let store = try await makeStore() + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) let session = MockMeshCoreSession() let scene = MockAppStateProvider(isInForeground: false) let service = makeService(session: session, store: store, appStateProvider: scene) @@ -2812,7 +2851,7 @@ struct AdvertisementServiceTests { let contact = try #require( await service.materializeContactForPendingAdvert( - matchingPrefix: Data(key.prefix(6)), radioID: radioID + matchingPrefix: Data(key.prefix(6)), scope: scope ) ) #expect(contact.publicKey == key) @@ -3433,11 +3472,12 @@ struct AdvertisementServiceTests { } await startMonitoring(service, session: session) + let attemptsBeforeFailure = await store.deleteContactsCallCount await store.setStubbedDeleteContactError(AdvertisementServiceTestError.storeUnavailable) await session.yieldEvent(.contactDeleted(publicKey: key)) let requeued = await waitUntil { - let attempted = await store.deletedContactIDs.contains(saved.id) + let attempted = await store.deleteContactsCallCount > attemptsBeforeFailure let queued = await service.pendingDeletedKeys.contains(key) return attempted && queued } diff --git a/MC1Services/Tests/MC1ServicesTests/AppBackupEnvelopeTests.swift b/MC1Services/Tests/MC1ServicesTests/AppBackupEnvelopeTests.swift index e01d665725..4deb5102c0 100644 --- a/MC1Services/Tests/MC1ServicesTests/AppBackupEnvelopeTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/AppBackupEnvelopeTests.swift @@ -307,6 +307,99 @@ struct AppBackupEnvelopeTests { #expect(decoded.showInlineImages == false) } + @Test + func `snapshot of flood 0 restores as 0 and an empty suite reads 4 and 4`() throws { + let sourceName = "test.dmBudget.source.\(UUID().uuidString)" + let source = try #require(UserDefaults(suiteName: sourceName)) + defer { source.removePersistentDomain(forName: sourceName) } + source.set(0, forKey: AppStorageKey.dmFloodAttempts.rawValue) + + let snapshot = BackupUserDefaults.snapshot(from: source) + #expect(snapshot.dmDirectAttempts == nil) + #expect(snapshot.dmFloodAttempts == 0) + + let destinationName = "test.dmBudget.destination.\(UUID().uuidString)" + let destination = try #require(UserDefaults(suiteName: destinationName)) + defer { destination.removePersistentDomain(forName: destinationName) } + let empty = BackupUserDefaults.snapshot(from: destination) + #expect(empty.dmDirectAttempts == nil) + #expect(empty.dmFloodAttempts == nil) + let missing = DMSendBudget.current(defaults: destination) + #expect(missing.directAttempts == 4) + #expect(missing.floodAttempts == 4) + + snapshot.restore(to: destination) + #expect(destination.object(forKey: AppStorageKey.dmDirectAttempts.rawValue) == nil) + #expect(destination.object(forKey: AppStorageKey.dmFloodAttempts.rawValue) != nil) + #expect(destination.integer(forKey: AppStorageKey.dmFloodAttempts.rawValue) == 0) + let restored = DMSendBudget.current(defaults: destination) + #expect(restored.directAttempts == 4) + #expect(restored.floodAttempts == 0) + #expect(restored.totalAttempts == 4) + } + + @Test + func `restoring preferences preserves a saved 2 and 0 budget`() throws { + let decoded = try JSONDecoder().decode( + BackupUserDefaults.self, from: Data(#"{"hasCompletedOnboarding":true}"#.utf8) + ) + let suiteName = "test.dmBudget.legacy.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + defaults.set(2, forKey: AppStorageKey.dmDirectAttempts.rawValue) + defaults.set(0, forKey: AppStorageKey.dmFloodAttempts.rawValue) + + let setKeys = decoded.restore(to: defaults) + #expect(!setKeys.contains(AppStorageKey.dmDirectAttempts.rawValue)) + #expect(!setKeys.contains(AppStorageKey.dmFloodAttempts.rawValue)) + let budget = DMSendBudget.current(defaults: defaults) + #expect(budget.directAttempts == 2) + #expect(budget.floodAttempts == 0) + #expect(budget.totalAttempts == 2) + + var incoming = BackupUserDefaults() + incoming.dmDirectAttempts = 4 + incoming.dmFloodAttempts = 4 + let incomingSetKeys = incoming.restore(to: defaults) + #expect(incomingSetKeys.isEmpty) + let retained = DMSendBudget.current(defaults: defaults) + #expect(retained.directAttempts == 2) + #expect(retained.floodAttempts == 0) + } + + @Test + func `explicit remote flood fallback false round-trips and a legacy envelope does not write it`() throws { + var prefs = BackupUserDefaults() + prefs.remoteFloodFallback = false + let data = try JSONEncoder().encode(prefs) + let decoded = try JSONDecoder().decode(BackupUserDefaults.self, from: data) + #expect(decoded.remoteFloodFallback == false) + + let suiteName = "test.remoteFlood.false.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + let snapshot = BackupUserDefaults.snapshot(from: defaults) + #expect(snapshot.remoteFloodFallback == nil) + decoded.restore(to: defaults) + let key = AppStorageKey.remoteFloodFallback.rawValue + #expect(defaults.object(forKey: key) != nil) + #expect(defaults.bool(forKey: key) == false) + #expect(RemoteFloodFallback.isEnabled(defaults: defaults) == false) + + let legacy = try JSONDecoder().decode( + BackupUserDefaults.self, + from: Data(#"{"hasCompletedOnboarding":true}"#.utf8) + ) + #expect(legacy.remoteFloodFallback == nil) + let legacySuite = "test.remoteFlood.legacy.\(UUID().uuidString)" + let legacyDefaults = try #require(UserDefaults(suiteName: legacySuite)) + defer { legacyDefaults.removePersistentDomain(forName: legacySuite) } + let setKeys = legacy.restore(to: legacyDefaults) + #expect(!setKeys.contains(key)) + #expect(legacyDefaults.object(forKey: key) == nil) + #expect(RemoteFloodFallback.isEnabled(defaults: legacyDefaults)) + } + @Test func `Legacy envelope without showIncomingSendTime decodes to nil and restore skips it`() throws { // A backup predating the toggle has no key. decodeIfPresent must yield nil, diff --git a/MC1Services/Tests/MC1ServicesTests/AppBackupServiceTests.swift b/MC1Services/Tests/MC1ServicesTests/AppBackupServiceTests.swift index 46ad10a5f5..5f56dfdb5c 100644 --- a/MC1Services/Tests/MC1ServicesTests/AppBackupServiceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/AppBackupServiceTests.swift @@ -160,7 +160,7 @@ struct AppBackupServiceTests { // MARK: - Version and source bundle @Test - func `Envelope contains expected version`() async throws { + func `Export without self telemetry uses version 1`() async throws { let radioID = UUID() let store = try await PersistenceStore.createTestDataStore(radioID: radioID) @@ -168,7 +168,54 @@ struct AppBackupServiceTests { let result = try await service.export(persistenceStore: store) let envelope = try parseBackup(data: result.data) - #expect(envelope.version == AppBackupEnvelope.currentVersion) + #expect(envelope.version == 1) + } + + @Test + func `Export uses version 2 when self telemetry is present and both versions import`() async throws { + let radioID = UUID() + let store = try await PersistenceStore.createTestDataStore(radioID: radioID) + let device = try #require(try await store.fetchDevice(id: radioID)) + _ = try await store.recordSelfTelemetrySnapshot( + deviceID: device.id, + radioID: device.radioID, + nodePublicKey: device.publicKey, + telemetry: [TelemetrySnapshotEntry(channel: 1, type: "voltage", value: 4.2)], + location: NodeLocationFix(latitude: 47.6062, longitude: -122.3321, altitude: 8) + ) + + let service = AppBackupService() + let exported = try await parseBackup(data: service.export(persistenceStore: store).data) + #expect(exported.version == 2) + #expect(exported.nodeStatusSnapshots.contains { $0.selfRadioID == radioID && $0.latitude == 47.6062 }) + + let restored = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let selfImport = try await service.importBackup(envelope: exported, into: restored) + #expect(selfImport.nodeStatusSnapshotsInserted == 1) + let selfRows = try await restored.fetchSelfTelemetrySnapshots( + radioID: radioID, + nodePublicKey: device.publicKey + ) + #expect(selfRows.first?.selfRadioID == radioID) + #expect(selfRows.first?.altitude == 8) + + let legacySnapshot = NodeStatusSnapshotDTO.testSnapshot() + let legacyEnvelope = AppBackupEnvelope.test( + version: 1, + devices: [DeviceDTO.testDevice(id: radioID, radioID: radioID)], + nodeStatusSnapshots: [legacySnapshot] + ) + let legacyData = try makeBackupJSONEncoder().encode(legacyEnvelope).zlibCompressed() + let legacy = try parseBackup(data: legacyData) + + let legacyStore = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let legacyImport = try await service.importBackup(envelope: legacy, into: legacyStore) + #expect(legacyImport.nodeStatusSnapshotsInserted == 1) + let remote = try await legacyStore.fetchNodeStatusSnapshots( + nodePublicKey: legacySnapshot.nodePublicKey, + since: nil + ) + #expect(remote.first?.selfRadioID == nil) } // MARK: - Import: into empty store diff --git a/MC1Services/Tests/MC1ServicesTests/BLEReconnectionCoordinatorOwnershipPortTests.swift b/MC1Services/Tests/MC1ServicesTests/BLEReconnectionCoordinatorOwnershipPortTests.swift new file mode 100644 index 0000000000..c507b6750a --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/BLEReconnectionCoordinatorOwnershipPortTests.swift @@ -0,0 +1,57 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Reconnect retry completion ownership") +@MainActor +struct BLEReconnectionCoordinatorOwnershipPortTests { + enum Outcome: CaseIterable { + case success + case failure + case cancellation + } + + @Test(arguments: Outcome.allCases) + func `held second rebuild cannot change a newer same-radio cycle`(outcome: Outcome) async throws { + try await withReconnectionHarness { harness in + let old = harness.begin() + let oldGate = harness.gate() + let newGate = harness.gate() + var oldCalls = 0 + var secondEntered = false + harness.coordinator.onRebuild = { cycle in + harness.rebuilds.append(cycle) + if cycle == old { + oldCalls += 1 + if oldCalls == 1 { throw BLEReconnectionTestHarness.RebuildError.failed } + secondEntered = true + await oldGate.wait() + switch outcome { + case .success: return + case .failure: throw BLEReconnectionTestHarness.RebuildError.failed + case .cancellation: throw CancellationError() + } + } + await newGate.wait() + } + let oldCompletion = harness.complete(old) + try await waitUntil("first failed rebuild should enter its retry delay") { harness.clock.sleeperCount == 1 } + harness.clock.advance(by: .seconds(2)) + try await waitUntil("the second rebuild must enter before supersession") { secondEntered } + let next = harness.begin(deviceID: old.deviceID, requestID: old.requestID) + let nextCompletion = harness.complete(next) + try await waitUntil("the new cycle must own its held rebuild") { harness.rebuilds == [old, old, next] } + oldGate.open() + await oldCompletion.value + #expect(harness.coordinator.currentCycle == next) + #expect(harness.coordinator.isRebuilding(next)) + #expect(harness.exhausted.isEmpty) + #expect(harness.timeouts.isEmpty) + #expect(harness.clock.sleeperCount == 0) + newGate.open() + await nextCompletion.value + #expect(harness.coordinator.currentCycle == nil) + #expect(harness.exhausted.isEmpty) + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/BLEReconnectionCoordinatorTests.swift b/MC1Services/Tests/MC1ServicesTests/BLEReconnectionCoordinatorTests.swift index 4a3c8a3a70..d2d5c8ba64 100644 --- a/MC1Services/Tests/MC1ServicesTests/BLEReconnectionCoordinatorTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/BLEReconnectionCoordinatorTests.swift @@ -1,765 +1,230 @@ import Foundation @testable import MC1Services -import MeshCoreTestSupport import Testing @Suite("BLEReconnectionCoordinator Tests") @MainActor struct BLEReconnectionCoordinatorTests { - // MARK: - Test Helpers - - private func createCoordinator( - delegate: MockReconnectionDelegate? = nil, - uiTimeoutDuration: TimeInterval = 10, - maxConnectingUIWindow: TimeInterval = 60, - clock: (any Clock)? = nil - ) -> (BLEReconnectionCoordinator, MockReconnectionDelegate) { - let coordinator = BLEReconnectionCoordinator( - uiTimeoutDuration: uiTimeoutDuration, - maxConnectingUIWindow: maxConnectingUIWindow, - clock: clock - ) - let mockDelegate = delegate ?? MockReconnectionDelegate() - coordinator.delegate = mockDelegate - return (coordinator, mockDelegate) - } - - // MARK: - handleEnteringAutoReconnect Tests - - @Test - func `entering auto-reconnect sets state to .connecting when user wants connection`() async { - let (coordinator, delegate) = createCoordinator() - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - - await coordinator.handleEnteringAutoReconnect(deviceID: UUID()) - - #expect(delegate.connectionState == .connecting) - } - - @Test - func `entering auto-reconnect tears down session`() async { - let (coordinator, delegate) = createCoordinator() - delegate.connectionIntent = .wantsConnection() - - await coordinator.handleEnteringAutoReconnect(deviceID: UUID()) - - #expect(delegate.teardownSessionCallCount == 1) - } - - @Test - func `entering auto-reconnect notifies the loss before tearing down the session`() async { - let (coordinator, delegate) = createCoordinator() - delegate.connectionIntent = .wantsConnection() - - await coordinator.handleEnteringAutoReconnect(deviceID: UUID()) - - #expect(delegate.notifyAutoReconnectStartedCallCount == 1) - #expect(delegate.callOrder == ["notifyAutoReconnectStarted", "teardown"]) - } - - @Test - func `entering auto-reconnect does not notify the loss when the user disconnected`() async { - let (coordinator, delegate) = createCoordinator() - delegate.connectionIntent = .userDisconnected - delegate.connectionState = .disconnected - - await coordinator.handleEnteringAutoReconnect(deviceID: UUID()) - - #expect(delegate.notifyAutoReconnectStartedCallCount == 0) - } - - @Test - func `entering auto-reconnect is ignored when intent is .userDisconnected`() async { - let (coordinator, delegate) = createCoordinator() - delegate.connectionIntent = .userDisconnected - delegate.connectionState = .disconnected - - await coordinator.handleEnteringAutoReconnect(deviceID: UUID()) - - #expect(delegate.connectionState == .disconnected, "State should not change when user disconnected") - #expect(delegate.teardownSessionCallCount == 0, "Session should not be torn down") - #expect(delegate.disconnectTransportCallCount == 1, "Transport should be disconnected") - } - @Test - func `entering auto-reconnect is ignored when intent is .none`() async { - let (coordinator, delegate) = createCoordinator() - delegate.connectionIntent = .none - delegate.connectionState = .disconnected - - await coordinator.handleEnteringAutoReconnect(deviceID: UUID()) - - #expect(delegate.connectionState == .disconnected) - #expect(delegate.disconnectTransportCallCount == 1) - } - - // MARK: - handleReconnectionComplete Tests - - @Test - func `completion during reconnect notification prevents stale session teardown`() async { - let (coordinator, delegate) = createCoordinator() - let deviceID = UUID() - delegate.connectionIntent = .wantsConnection() - delegate.onNotifyAutoReconnectStarted = { - await coordinator.handleReconnectionComplete(deviceID: deviceID) - } - - let generation = await coordinator.handleEnteringAutoReconnect(deviceID: deviceID) - - #expect(generation == 1) - #expect(coordinator.reconnectGeneration == 2) - #expect(delegate.rebuildSessionCalls == [deviceID]) - #expect(delegate.teardownSessionCallCount == 0) - #expect(coordinator.reconnectingDeviceID == nil) - coordinator.cancelTimeout() - } - - // - // The coordinator only accepts a completion for a cycle it explicitly claimed - // via handleEnteringAutoReconnect. Each happy-path test below claims first to - // mirror the production wiring (setAutoReconnectingHandler always fires before - // setReconnectionHandler for the same cycle). - - @Test - func `reconnection complete keeps state .connecting when claim matches`() async { - let deviceID = UUID() - let (coordinator, delegate) = createCoordinator() - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - - await coordinator.handleEnteringAutoReconnect(deviceID: deviceID) - - await coordinator.handleReconnectionComplete(deviceID: deviceID) - - #expect(delegate.connectionState == .connecting) - } - - @Test - func `reconnection complete calls rebuildSession when claim matches`() async { - let deviceID = UUID() - let (coordinator, delegate) = createCoordinator() - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - - await coordinator.handleEnteringAutoReconnect(deviceID: deviceID) - - await coordinator.handleReconnectionComplete(deviceID: deviceID) - - #expect(delegate.rebuildSessionCalls.count == 1) - #expect(delegate.rebuildSessionCalls.first == deviceID) - } - - @Test - func `reconnection complete is ignored when no entry was claimed`() async { - let (coordinator, delegate) = createCoordinator() - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .disconnected - - // No prior handleEnteringAutoReconnect — claim is nil. This mirrors the - // pairing race where the entry handler was suppressed but a late completion - // still arrives. - await coordinator.handleReconnectionComplete(deviceID: UUID()) - - #expect(delegate.connectionState == .disconnected, "Should not transition without claim") - #expect(delegate.rebuildSessionCalls.isEmpty, "Should not rebuild without claim") - } - - @Test - func `reconnection complete is ignored when intent is .userDisconnected`() async { - let deviceID = UUID() - let (coordinator, delegate) = createCoordinator() - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - await coordinator.handleEnteringAutoReconnect(deviceID: deviceID) - - // Now the user disconnects mid-reconnect. - delegate.connectionIntent = .userDisconnected - - await coordinator.handleReconnectionComplete(deviceID: deviceID) - - #expect(delegate.rebuildSessionCalls.isEmpty, "Should not rebuild when user disconnected") - #expect(delegate.disconnectTransportCallCount == 1, "Should disconnect transport") - } - - @Test - func `reconnection complete is ignored when already .ready`() async { - let deviceID = UUID() - let (coordinator, delegate) = createCoordinator() - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - await coordinator.handleEnteringAutoReconnect(deviceID: deviceID) - - // Force state back to .ready (e.g., a parallel resync promoted the session). - delegate.connectionState = .ready - - await coordinator.handleReconnectionComplete(deviceID: deviceID) - - #expect(delegate.connectionState == .ready, "Should not change state when already ready") - #expect(delegate.rebuildSessionCalls.isEmpty, "Should not rebuild when already ready") - } - - @Test - func `reconnection complete is ignored when .syncing (session alive, resync running)`() async { - let deviceID = UUID() - let (coordinator, delegate) = createCoordinator() - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - await coordinator.handleEnteringAutoReconnect(deviceID: deviceID) - - // Simulate a parallel resync promoting the session to .syncing. - delegate.connectionState = .syncing - - await coordinator.handleReconnectionComplete(deviceID: deviceID) - - #expect(delegate.connectionState == .syncing, "Should not change state when syncing") - #expect(delegate.rebuildSessionCalls.isEmpty, "Should not rebuild when syncing") - } - - @Test - func `reconnection complete handles rebuild failure`() async { - let deviceID = UUID() - let (coordinator, delegate) = createCoordinator() - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - delegate.rebuildSessionShouldThrow = true - - await coordinator.handleEnteringAutoReconnect(deviceID: deviceID) - await coordinator.handleReconnectionComplete(deviceID: deviceID) - - #expect(delegate.handleReconnectionFailureCallCount == 1) - } - - @Test - func `cycle claim is held across first-fail retry gap until failure returns`() async throws { - let deviceID = UUID() - let clock = TestClock() - let (coordinator, delegate) = createCoordinator(clock: clock) - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - // First rebuild fails, second (retry) also fails → handleReconnectionFailure. - delegate.rebuildSessionThrowCount = 2 - - var claimDuringFailure: UUID? - delegate.onHandleReconnectionFailure = { - claimDuringFailure = coordinator.reconnectingDeviceID - } - - await coordinator.handleEnteringAutoReconnect(deviceID: deviceID) - // After first throw, claim must still be held (would be nil if clear ran early). - async let completion: Void = coordinator.handleReconnectionComplete(deviceID: deviceID) - try await waitUntil("failed rebuild should park before retrying") { - clock.sleeperCount == 1 - } - #expect(coordinator.reconnectingDeviceID == deviceID) - - clock.advance(by: .seconds(2)) - await completion - - #expect(delegate.handleReconnectionFailureCallCount == 1) - #expect(claimDuringFailure == deviceID) - #expect(coordinator.reconnectingDeviceID == nil) - } - - @Test - func `overlapping completions for the same device start only one rebuild`() async throws { - let deviceID = UUID() - let (coordinator, delegate) = createCoordinator() - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - delegate.rebuildSessionHold = true - delegate.onRebuildSession = { [weak delegate] in - // A duplicate rebuild must finish so the count assertion can report it. - if let delegate, delegate.rebuildSessionCalls.count > 1 { - delegate.rebuildSessionHold = false + func `begin captures the request and each same-radio cycle is distinct`() async { + await withReconnectionHarness { harness in + let deviceID = UUID() + let requestID = UUID() + let first = harness.begin(deviceID: deviceID, requestID: requestID) + let second = harness.begin(deviceID: deviceID, requestID: requestID) + + #expect(first.deviceID == deviceID) + #expect(first.requestID == requestID) + #expect(first.id != second.id) + #expect(first.generation < second.generation) + #expect(!harness.coordinator.isCurrent(first)) + #expect(harness.coordinator.currentCycle == second) + #expect(harness.clock.sleeperCount == 0) + #expect(harness.rebuilds.isEmpty && harness.timeouts.isEmpty && harness.exhausted.isEmpty) + } + } + + @Test + func `completion during reconnect notification preserves the rebuilt session`() async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + _ = try await env.connect(.bluetooth) + let request = try #require(env.manager.desiredRequest) + let previous = try #require(env.manager.currentConnection) + let origin = try #require(await env.ble.lifecycleOrigin) + env.manager.onAutoReconnectStarted = { _ in + let cycle = try? #require(env.manager.reconnectionCoordinator.currentCycle) + if let cycle { await env.manager.reconnectionCoordinator.complete(cycle) } } - } - - await coordinator.handleEnteringAutoReconnect(deviceID: deviceID) - - async let first: Void = coordinator.handleReconnectionComplete(deviceID: deviceID) - // Wait until first rebuild is parked inside the hold. - try await waitUntil("first rebuild should be held") { - delegate.rebuildSessionHoldContinuation != nil - } - await coordinator.handleReconnectionComplete(deviceID: deviceID) - // Release the held rebuild. - delegate.rebuildSessionHold = false - delegate.rebuildSessionHoldContinuation?.resume() - await first - - #expect(delegate.rebuildSessionCalls.count == 1) - } - - @Test - func `already-connected completion during rebuild does not drop cycle claim`() async throws { - // Production rebuildSession sets .connected early. A second completion in - // that window must not clearActiveCycle or health single-flight is lost. - let deviceID = UUID() - let clock = TestClock() - let (coordinator, delegate) = createCoordinator(clock: clock) - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - delegate.rebuildSessionThrowCount = 2 - - var claimDuringFailure: UUID? - delegate.onHandleReconnectionFailure = { - claimDuringFailure = coordinator.reconnectingDeviceID - } - delegate.onRebuildSession = { - // Mirror production: surface .connected during rebuild. - delegate.connectionState = .connected - } - await coordinator.handleEnteringAutoReconnect(deviceID: deviceID) - async let first: Void = coordinator.handleReconnectionComplete(deviceID: deviceID) - try await waitUntil("failed connected rebuild should park before retrying") { - clock.sleeperCount == 1 - } - // Second completion while first is in flight and state is .connected. - await coordinator.handleReconnectionComplete(deviceID: deviceID) - #expect(coordinator.reconnectingDeviceID == deviceID) - #expect(delegate.rebuildSessionCalls.count == 1) + await env.manager.enterBLERecovery(request, origin: origin) - clock.advance(by: .seconds(2)) - await first - #expect(claimDuringFailure == deviceID) - #expect(delegate.handleReconnectionFailureCallCount == 1) + #expect(env.manager.connectionState == .ready) + #expect(env.manager.connectionRequestID == previous.requestID) + #expect(env.manager.currentConnection?.generation != previous.generation) + #expect(env.manager.reconnectionCoordinator.currentCycle == nil) + #expect(await env.ble.connectCount == 1) + #expect(try await env.manager.session?.getTime() != nil) + } catch { await env.close(); throw error } + await env.close() } @Test - func `successful rebuild does not clear a newer cycle claim after supersession`() async { - let deviceA = UUID() - let deviceB = UUID() - let (coordinator, delegate) = createCoordinator() - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready + func `completion only rebuilds the current cycle`() async { + await withReconnectionHarness { harness in + let first = harness.begin() + let second = harness.begin() + await harness.coordinator.complete(first) + #expect(harness.rebuilds.isEmpty) + #expect(harness.coordinator.currentCycle == second) - await coordinator.handleEnteringAutoReconnect(deviceID: deviceA) - - var enteredSuperseding = false - delegate.onRebuildSession = { - guard !enteredSuperseding else { return } - enteredSuperseding = true - // Mid-rebuild: a newer auto-reconnect cycle claims device B. - await coordinator.handleEnteringAutoReconnect(deviceID: deviceB) + await harness.coordinator.complete(second) + #expect(harness.rebuilds == [second]) + #expect(harness.coordinator.currentCycle == nil) + await harness.coordinator.complete(second) + #expect(harness.rebuilds == [second]) } - - await coordinator.handleReconnectionComplete(deviceID: deviceA) - - // Newer cycle must still hold its claim; clearing on stale success would wipe it. - #expect(coordinator.reconnectingDeviceID == deviceB) } @Test - func `stale device completion does not cancel active timeout`() async throws { - let activeDevice = UUID() - let staleDevice = UUID() - let (coordinator, delegate) = createCoordinator(uiTimeoutDuration: 0.1) - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - - await coordinator.handleEnteringAutoReconnect(deviceID: activeDevice) - #expect(delegate.connectionState == .connecting) - - // Stale completion for a different device should be rejected - await coordinator.handleReconnectionComplete(deviceID: staleDevice) + func `overlapping completions start one rebuild and preserve subsequent liveness`() async throws { + try await withReconnectionHarness { harness in + let cycle = harness.begin() + let gate = harness.gate() + harness.onRebuild = { _ in await gate.wait() } + let first = harness.complete(cycle) + try await waitUntil("first rebuild should enter its gate") { harness.rebuilds == [cycle] } + await harness.coordinator.complete(cycle) + #expect(harness.coordinator.currentCycle == cycle) + #expect(harness.rebuilds == [cycle]) + gate.open() + await first.value - // Timeout should still fire because it was not canceled - try await waitUntil("Timeout should still fire after stale completion") { - delegate.connectionState == .disconnected + harness.onRebuild = nil + let next = harness.begin() + await harness.coordinator.complete(next) + #expect(harness.rebuilds == [cycle, next]) + #expect(harness.coordinator.currentCycle == nil) } - - #expect(delegate.connectionState == .disconnected, "Timeout should still fire after stale completion") - #expect(delegate.rebuildSessionCalls.isEmpty, "Should not rebuild for stale device") } - // MARK: - UI Timeout Tests - @Test - func `UI timeout transitions to disconnected after duration`() async throws { - let (coordinator, delegate) = createCoordinator(uiTimeoutDuration: 0.1) - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - - await coordinator.handleEnteringAutoReconnect(deviceID: UUID()) - #expect(delegate.connectionState == .connecting) - - // Wait for timeout to fire and transition state - try await waitUntil("Timeout should transition to disconnected") { - delegate.connectionState == .disconnected + func `first rebuild failure retries after two seconds`() async throws { + try await withReconnectionHarness { harness in + harness.remainingFailures = 1 + let cycle = harness.begin() + let completion = harness.complete(cycle) + try await waitUntil("retry should wait on the injected clock") { harness.clock.sleeperCount == 1 } + harness.clock.advance(by: .seconds(1)) + #expect(harness.rebuilds == [cycle]) + #expect(harness.coordinator.currentCycle == cycle) + harness.clock.advance(by: .seconds(1)) + await completion.value + #expect(harness.rebuilds == [cycle, cycle]) + #expect(harness.exhausted.isEmpty) + #expect(harness.coordinator.currentCycle == nil) } - - #expect(delegate.connectionState == .disconnected) - #expect(delegate.connectedDeviceWasCleared == true) - #expect(delegate.notifyConnectionLostCallCount == 1) } @Test - func `UI timeout is cancelled when reconnection completes`() async throws { - let deviceID = UUID() - let (coordinator, delegate) = createCoordinator() - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - - await coordinator.handleEnteringAutoReconnect(deviceID: deviceID) - let timeoutTask = try #require(coordinator.uiTimeoutTaskForTest) - #expect(delegate.connectionState == .connecting) - - // Complete reconnection before timeout (same device) - await coordinator.handleReconnectionComplete(deviceID: deviceID) - - await timeoutTask.value - #expect(timeoutTask.isCancelled) - - // Should be .connecting from reconnection complete, not .disconnected from timeout - #expect(delegate.connectionState == .connecting) - #expect(delegate.notifyConnectionLostCallCount == 0) - } - - // MARK: - Stale Retry Tests - - @Test - func `stale rebuild retry is aborted when new reconnect cycle starts during delay`() async throws { - let deviceID = UUID() - let clock = TestClock() - let (coordinator, delegate) = createCoordinator(clock: clock) - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - delegate.rebuildSessionShouldThrow = true - - // Claim the first cycle so the completion is accepted. - await coordinator.handleEnteringAutoReconnect(deviceID: deviceID) - - // Start first reconnection — rebuild fails and the retry parks on the clock. - let firstReconnectTask = Task { - await coordinator.handleReconnectionComplete(deviceID: deviceID) - } - - // Wait for the first rebuild to fail, then for the stale retry to park on the - // clock. Parking is the readiness signal: bumping the generation before it would - // race the retry, so gate on it rather than on wall-clock timing. - try await waitUntil("First rebuild should have been attempted") { - delegate.rebuildSessionCalls.count == 1 - } - try await waitUntil("Stale retry should park on the injected clock") { - clock.sleeperCount == 1 - } - - // Start a new reconnect cycle during the delay — this bumps the generation counter. - // Re-claim the cycle since the prior completion cleared reconnectingDeviceID. - delegate.rebuildSessionShouldThrow = false - await coordinator.handleEnteringAutoReconnect(deviceID: deviceID) - await coordinator.handleReconnectionComplete(deviceID: deviceID) - - // Release the retry: it wakes, sees the stale generation, and aborts. - clock.advance(by: .seconds(2)) - await firstReconnectTask.value - - // Should have exactly 2 rebuild calls: first (failed) + new cycle (succeeded). - // The stale retry should have been aborted by the generation check. - #expect(delegate.rebuildSessionCalls.count == 2, "Stale retry should have been aborted") - #expect(delegate.handleReconnectionFailureCallCount == 0, "No failure handler since new cycle succeeded") - } - - // MARK: - Max Connecting Window Tests - - @Test - func `UI timeout disconnects when max connecting window exceeded`() async throws { - let (coordinator, delegate) = createCoordinator( - uiTimeoutDuration: 0.05, - maxConnectingUIWindow: 0.15 - ) - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - delegate.stubbedBLEPhaseIsAutoReconnecting = true - - await coordinator.handleEnteringAutoReconnect(deviceID: UUID()) - - // Wait for max connecting window to expire and disconnect - try await waitUntil("Max connecting window should trigger disconnect") { - delegate.connectionState == .disconnected - } - - #expect(delegate.connectionState == .disconnected) - #expect(delegate.notifyConnectionLostCallCount == 1) - } - - @Test - func `same-device completion is accepted after UI timeout while transport auto-reconnects`() async throws { - let deviceID = UUID() - let (coordinator, delegate) = createCoordinator( - uiTimeoutDuration: 0.05, - maxConnectingUIWindow: 0.15 - ) - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - delegate.stubbedBLEPhaseIsAutoReconnecting = true - - await coordinator.handleEnteringAutoReconnect(deviceID: deviceID) - - try await waitUntil("UI timeout should transition presentation to disconnected") { - delegate.connectionState == .disconnected - } - - await coordinator.handleReconnectionComplete(deviceID: deviceID) - - #expect(delegate.rebuildSessionCalls == [deviceID]) - #expect(delegate.connectionState == .connecting) - } - - @Test - func `UI timeout clears cycle when transport stops auto-reconnecting`() async throws { - let deviceID = UUID() - let (coordinator, delegate) = createCoordinator(uiTimeoutDuration: 0.05) - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - delegate.stubbedBLEPhaseIsAutoReconnecting = false - - await coordinator.handleEnteringAutoReconnect(deviceID: deviceID) - - try await waitUntil("UI timeout should transition to disconnected") { - delegate.connectionState == .disconnected - } - - await coordinator.handleReconnectionComplete(deviceID: deviceID) - - #expect(delegate.rebuildSessionCalls.isEmpty) - } - - @Test - func `different-device completion is rejected after UI timeout`() async throws { - let activeDeviceID = UUID() - let staleDeviceID = UUID() - let (coordinator, delegate) = createCoordinator( - uiTimeoutDuration: 0.05, - maxConnectingUIWindow: 0.15 - ) - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - delegate.stubbedBLEPhaseIsAutoReconnecting = true - - await coordinator.handleEnteringAutoReconnect(deviceID: activeDeviceID) - - try await waitUntil("UI timeout should transition presentation to disconnected") { - delegate.connectionState == .disconnected - } - - await coordinator.handleReconnectionComplete(deviceID: staleDeviceID) - - #expect(delegate.rebuildSessionCalls.isEmpty) - #expect(delegate.connectionState == .disconnected) - } - - @Test - func `user-disconnected completion after UI timeout remains rejected`() async throws { - let deviceID = UUID() - let (coordinator, delegate) = createCoordinator( - uiTimeoutDuration: 0.05, - maxConnectingUIWindow: 0.15 - ) - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - delegate.stubbedBLEPhaseIsAutoReconnecting = true - - await coordinator.handleEnteringAutoReconnect(deviceID: deviceID) - - try await waitUntil("UI timeout should transition presentation to disconnected") { - delegate.connectionState == .disconnected - } - - delegate.connectionIntent = .userDisconnected - await coordinator.handleReconnectionComplete(deviceID: deviceID) - - #expect(delegate.rebuildSessionCalls.isEmpty) - #expect(delegate.disconnectTransportCallCount == 1) - } - - // MARK: - cancelTimeout Tests - - @Test - func `UI timeout re-arms if BLE is still auto-reconnecting`() async throws { - let (coordinator, delegate) = createCoordinator(uiTimeoutDuration: 0.1) - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - delegate.stubbedBLEPhaseIsAutoReconnecting = true - var transportQueryCount = 0 - delegate.onIsTransportAutoReconnecting = { - transportQueryCount += 1 - } - - let deviceID = UUID() - await coordinator.handleEnteringAutoReconnect(deviceID: deviceID) - let firstTimeout = try #require(coordinator.uiTimeoutTaskForTest) - await firstTimeout.value - let rearmedTimeout = try #require(coordinator.uiTimeoutTaskForTest) - #expect(transportQueryCount >= 1) - #expect(rearmedTimeout != firstTimeout) - #expect(!rearmedTimeout.isCancelled) - - // Should still be .connecting because BLE is auto-reconnecting - #expect(delegate.connectionState == .connecting) - #expect(delegate.notifyConnectionLostCallCount == 0) - coordinator.cancelTimeout() - await rearmedTimeout.value - } - - @Test - func `UI timeout fires normally when BLE is not auto-reconnecting`() async throws { - let (coordinator, delegate) = createCoordinator(uiTimeoutDuration: 0.1) - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - delegate.stubbedBLEPhaseIsAutoReconnecting = false - - await coordinator.handleEnteringAutoReconnect(deviceID: UUID()) - - try await waitUntil("Timeout should fire when BLE is not auto-reconnecting") { - delegate.connectionState == .disconnected - } - - #expect(delegate.connectionState == .disconnected) - #expect(delegate.notifyConnectionLostCallCount == 1) - } - - @Test - func `UI timeout aborts when reconnection completes during its transport query`() async throws { - let deviceID = UUID() - let (coordinator, delegate) = createCoordinator(uiTimeoutDuration: 0.05) - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - delegate.stubbedBLEPhaseIsAutoReconnecting = false - - await coordinator.handleEnteringAutoReconnect(deviceID: deviceID) - let timeoutTask = try #require(coordinator.uiTimeoutTaskForTest) - - // Run handleReconnectionComplete while the timeout body is suspended on - // isTransportAutoReconnecting(), the reentrancy window where a stale - // timeout could clobber the freshly completed reconnection. - delegate.onIsTransportAutoReconnecting = { [weak coordinator, weak delegate] in - delegate?.onIsTransportAutoReconnecting = nil - await coordinator?.handleReconnectionComplete(deviceID: deviceID) - } - - await timeoutTask.value - #expect(delegate.rebuildSessionCalls == [deviceID]) - - #expect(delegate.connectionState == .connecting, "Stale timeout must not clobber the completed reconnection") - #expect(delegate.notifyConnectionLostCallCount == 0) - #expect(delegate.connectedDeviceWasCleared == false) - } - - @Test - func `cancelTimeout prevents timeout from firing`() async throws { - let (coordinator, delegate) = createCoordinator() - delegate.connectionIntent = .wantsConnection() - delegate.connectionState = .ready - - await coordinator.handleEnteringAutoReconnect(deviceID: UUID()) - let timeoutTask = try #require(coordinator.uiTimeoutTaskForTest) - coordinator.cancelTimeout() - await timeoutTask.value - #expect(timeoutTask.isCancelled) - - // State should remain .connecting (timeout was cancelled) - #expect(delegate.connectionState == .connecting) - } -} - -// MARK: - Mock Delegate - -@MainActor -private final class MockReconnectionDelegate: BLEReconnectionDelegate { - var connectionIntent: ConnectionIntent = .none - var connectionState: DeviceConnectionState = .disconnected - - var teardownSessionCallCount = 0 - var rebuildSessionCalls: [UUID] = [] - var rebuildSessionShouldThrow = false - /// When > 0, the next N rebuildSession calls throw then decrement. - var rebuildSessionThrowCount = 0 - /// When true, rebuildSession parks until `rebuildSessionHold` is set false - /// and the continuation is resumed. - var rebuildSessionHold = false - var rebuildSessionHoldContinuation: CheckedContinuation? - var disconnectTransportCallCount = 0 - var notifyConnectionLostCallCount = 0 - var notifyAutoReconnectStartedCallCount = 0 - var handleReconnectionFailureCallCount = 0 - /// Records delegate calls in order so tests can assert the auto-reconnect - /// notification lands before session teardown. - private(set) var callOrder: [String] = [] - var connectedDeviceWasCleared = false - var stubbedBLEPhaseIsAutoReconnecting = false - /// Runs inside `isTransportAutoReconnecting()` so tests can interleave work - /// at that suspension point before the stubbed value is returned. - var onIsTransportAutoReconnecting: (@MainActor () async -> Void)? - var onHandleReconnectionFailure: (@MainActor () async -> Void)? - var onRebuildSession: (@MainActor () async -> Void)? - var onNotifyAutoReconnectStarted: (@MainActor () async -> Void)? - - func setConnectionState(_ state: DeviceConnectionState) { - connectionState = state - } - - func setConnectedDevice(_ device: DeviceDTO?) { - if device == nil { - connectedDeviceWasCleared = true - } - } - - func teardownSessionForReconnect() async { - teardownSessionCallCount += 1 - callOrder.append("teardown") - } - - func notifyAutoReconnectStarted() async { - notifyAutoReconnectStartedCallCount += 1 - callOrder.append("notifyAutoReconnectStarted") - await onNotifyAutoReconnectStarted?() - } - - func rebuildSession(deviceID: UUID) async throws { - rebuildSessionCalls.append(deviceID) - if let onRebuildSession { - await onRebuildSession() - } - if rebuildSessionHold { - await withCheckedContinuation { (cont: CheckedContinuation) in - rebuildSessionHoldContinuation = cont + func `retry exhaustion holds the cycle through cleanup then releases it`() async throws { + try await withReconnectionHarness { harness in + harness.remainingFailures = 2 + let cycle = harness.begin() + var claimDuringExhaustion: BLEReconnectionCoordinator.Cycle? + harness.onExhausted = { _ in + claimDuringExhaustion = harness.coordinator.currentCycle + harness.coordinator.clear() } + let completion = harness.complete(cycle) + try await waitUntil("retry should park") { harness.clock.sleeperCount == 1 } + harness.clock.advance(by: .seconds(2)) + await completion.value + #expect(claimDuringExhaustion == cycle) + #expect(harness.exhausted == [cycle]) + #expect(harness.coordinator.currentCycle == nil) + let next = harness.begin() + await harness.coordinator.complete(next) + #expect(harness.rebuilds == [cycle, cycle, next]) + } + } + + @Test + func `same-cycle completion during retry does not admit another rebuild`() async throws { + try await withReconnectionHarness { harness in + harness.remainingFailures = 2 + let cycle = harness.begin() + let completion = harness.complete(cycle) + try await waitUntil("retry should park") { harness.clock.sleeperCount == 1 } + await harness.coordinator.complete(cycle) + #expect(harness.rebuilds == [cycle]) + #expect(harness.coordinator.currentCycle == cycle) + harness.clock.advance(by: .seconds(2)) + await completion.value + #expect(harness.rebuilds == [cycle, cycle]) + #expect(harness.exhausted == [cycle]) + } + } + + @Test + func `a newer cycle cancels a sleeping retry without clearing its claim`() async throws { + try await withReconnectionHarness { harness in + harness.remainingFailures = 1 + let old = harness.begin() + let completion = harness.complete(old) + try await waitUntil("old retry should park") { harness.clock.sleeperCount == 1 } + let next = harness.begin(deviceID: old.deviceID, requestID: old.requestID) + await completion.value + #expect(harness.clock.sleeperCount == 0) + #expect(harness.coordinator.currentCycle == next) + #expect(harness.exhausted.isEmpty) + await harness.coordinator.complete(next) + #expect(harness.rebuilds == [old, next]) + } + } + + @Test + func `old held rebuild completion cannot clear a newer in-flight cycle`() async throws { + try await withReconnectionHarness { harness in + let old = harness.begin() + let oldGate = harness.gate() + let newGate = harness.gate() + harness.onRebuild = { cycle in + if cycle == old { + await oldGate.wait() + } else { + await newGate.wait() + } + } + let oldCompletion = harness.complete(old) + try await waitUntil("old rebuild should enter") { harness.rebuilds == [old] } + let next = harness.begin() + let newCompletion = harness.complete(next) + try await waitUntil("new rebuild should enter") { harness.rebuilds == [old, next] } + oldGate.open() + await oldCompletion.value + #expect(harness.coordinator.currentCycle == next) + await harness.coordinator.complete(next) + #expect(harness.rebuilds == [old, next]) + newGate.open() + await newCompletion.value + #expect(harness.coordinator.currentCycle == nil) + #expect(harness.exhausted.isEmpty) + } + } + + @Test + func `clear during a held failed rebuild suppresses retry and exhaustion`() async throws { + try await withReconnectionHarness { harness in + harness.remainingFailures = 1 + let cycle = harness.begin() + let gate = harness.gate() + harness.onRebuild = { _ in await gate.wait() } + let completion = harness.complete(cycle) + try await waitUntil("rebuild should enter") { harness.rebuilds == [cycle] } + harness.coordinator.clear() + gate.open() + await completion.value + #expect(harness.rebuilds == [cycle]) + #expect(harness.exhausted.isEmpty) + #expect(harness.clock.sleeperCount == 0) + #expect(harness.coordinator.currentCycle == nil) + } + } + + @Test + func `supersession during exhaustion preserves the newer cycle`() async throws { + try await withReconnectionHarness { harness in + harness.remainingFailures = 2 + let cycle = harness.begin() + var next: BLEReconnectionCoordinator.Cycle? + harness.onExhausted = { _ in next = harness.begin() } + let completion = harness.complete(cycle) + try await waitUntil("retry should park") { harness.clock.sleeperCount == 1 } + harness.clock.advance(by: .seconds(2)) + await completion.value + #expect(harness.coordinator.currentCycle == next) + #expect(next != nil) } - if rebuildSessionThrowCount > 0 { - rebuildSessionThrowCount -= 1 - throw ReconnectionTestError.rebuildFailed - } - if rebuildSessionShouldThrow { - throw ReconnectionTestError.rebuildFailed - } - } - - func disconnectTransport() async { - disconnectTransportCallCount += 1 - } - - func notifyConnectionLost() async { - notifyConnectionLostCallCount += 1 - } - - func handleReconnectionFailure() async { - handleReconnectionFailureCallCount += 1 - if let onHandleReconnectionFailure { - await onHandleReconnectionFailure() - } - } - - func isTransportAutoReconnecting() async -> Bool { - if let hook = onIsTransportAutoReconnecting { - await hook() - } - return stubbedBLEPhaseIsAutoReconnecting } } - -private enum ReconnectionTestError: Error { - case rebuildFailed -} diff --git a/MC1Services/Tests/MC1ServicesTests/BLEReconnectionTimeoutTests.swift b/MC1Services/Tests/MC1ServicesTests/BLEReconnectionTimeoutTests.swift new file mode 100644 index 0000000000..082df79cb6 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/BLEReconnectionTimeoutTests.swift @@ -0,0 +1,183 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("BLE reconnect presentation timeout") +@MainActor +struct BLEReconnectionTimeoutTests { + @Test + func `timeout ends a cycle when OS auto-reconnect has stopped`() async throws { + try await withReconnectionHarness(uiTimeout: 1) { harness in + let cycle = harness.begin() + harness.coordinator.armTimeout(cycle) + try await waitUntil("timeout should park") { harness.clock.sleeperCount == 1 } + harness.clock.advance(by: .seconds(1)) + try await waitUntil("timeout should be delivered") { harness.timeouts == [cycle] } + #expect(harness.coordinator.currentCycle == nil) + await harness.coordinator.complete(cycle) + #expect(harness.rebuilds.isEmpty) + } + } + + @Test + func `OS auto-reconnect accepts late completion after the UI window ends`() async throws { + try await withReconnectionHarness(uiTimeout: 1, maxUIWindow: 1) { harness in + harness.autoReconnecting = true + let cycle = harness.begin() + harness.coordinator.armTimeout(cycle) + try await waitUntil("timeout should park") { harness.clock.sleeperCount == 1 } + harness.clock.advance(by: .seconds(1)) + try await waitUntil("UI timeout should be delivered") { harness.timeouts == [cycle] } + #expect(harness.coordinator.currentCycle == cycle) + await harness.coordinator.complete(cycle) + #expect(harness.rebuilds == [cycle]) + #expect(harness.coordinator.currentCycle == nil) + } + } + + @Test + func `active OS auto-reconnect rearms only inside the maximum UI window`() async throws { + try await withReconnectionHarness(uiTimeout: 1, maxUIWindow: 3) { harness in + harness.autoReconnecting = true + let cycle = harness.begin() + harness.coordinator.armTimeout(cycle) + for _ in 0..<2 { + try await waitUntil("timeout should park before advancing") { harness.clock.sleeperCount == 1 } + harness.clock.advance(by: .seconds(1)) + try await waitUntil("active auto-reconnect should rearm") { harness.clock.sleeperCount == 1 } + #expect(harness.timeouts.isEmpty) + } + harness.clock.advance(by: .seconds(1)) + try await waitUntil("maximum window should end the presentation") { harness.timeouts == [cycle] } + #expect(harness.coordinator.currentCycle == cycle) + #expect(harness.clock.sleeperCount == 0) + } + } + + @Test + func `a timeout query returning after replacement cannot expire the newer cycle`() async throws { + try await withReconnectionHarness(uiTimeout: 1) { harness in + let old = harness.begin() + let gate = harness.gate() + var queryEntered = false + harness.onAutoReconnectQuery = { + queryEntered = true + await gate.wait() + } + harness.coordinator.armTimeout(old) + try await waitUntil("old timeout should park") { harness.clock.sleeperCount == 1 } + harness.clock.advance(by: .seconds(1)) + try await waitUntil("old timeout should enter its transport query") { queryEntered } + let next = harness.begin() + harness.coordinator.armTimeout(next) + harness.onAutoReconnectQuery = nil + gate.open() + try await waitUntil("new timeout should remain armed") { harness.clock.sleeperCount == 1 } + #expect(harness.coordinator.currentCycle == next) + #expect(harness.timeouts.isEmpty) + await harness.coordinator.complete(next) + #expect(harness.rebuilds == [next]) + } + } + + @Test + func `completion during the timeout transport query suppresses its stale result`() async throws { + try await withReconnectionHarness(uiTimeout: 1) { harness in + let cycle = harness.begin() + harness.onAutoReconnectQuery = { await harness.coordinator.complete(cycle) } + harness.coordinator.armTimeout(cycle) + try await waitUntil("timeout should park") { harness.clock.sleeperCount == 1 } + harness.clock.advance(by: .seconds(1)) + try await waitUntil("rebuild should complete during the query") { + harness.rebuilds == [cycle] && harness.coordinator.currentCycle == nil + } + #expect(harness.timeouts.isEmpty) + #expect(harness.clock.sleeperCount == 0) + } + } + + @Test + func `late timeout arming after completion leaves no timer`() async { + await withReconnectionHarness { harness in + let cycle = harness.begin() + await harness.coordinator.complete(cycle) + harness.coordinator.armTimeout(cycle) + #expect(harness.clock.sleeperCount == 0) + #expect(harness.coordinator.currentCycle == nil) + } + } + + @Test + func `late entry cannot arm a timer while its rebuild is in flight`() async throws { + try await withReconnectionHarness { harness in + let cycle = harness.begin() + let gate = harness.gate() + harness.onRebuild = { _ in await gate.wait() } + let completion = harness.complete(cycle) + try await waitUntil("rebuild should enter its gate") { harness.rebuilds == [cycle] } + harness.coordinator.armTimeout(cycle) + #expect(harness.clock.sleeperCount == 0) + gate.open() + await completion.value + } + } + + @Test + func `cancelTimeout drains the timer without ending its cycle`() async throws { + try await withReconnectionHarness(uiTimeout: 1) { harness in + let cycle = harness.begin() + harness.coordinator.armTimeout(cycle) + try await waitUntil("timeout should park") { harness.clock.sleeperCount == 1 } + harness.coordinator.cancelTimeout() + #expect(harness.clock.sleeperCount == 0) + harness.clock.advance(by: .seconds(1)) + #expect(harness.timeouts.isEmpty) + #expect(harness.coordinator.currentCycle == cycle) + } + } + + @Test + func `restartTimeout preserves the request and resets only its UI window`() async throws { + try await withReconnectionHarness(uiTimeout: 1, maxUIWindow: 3) { harness in + harness.autoReconnecting = true + let cycle = harness.begin() + harness.coordinator.armTimeout(cycle) + try await waitUntil("timeout should park") { harness.clock.sleeperCount == 1 } + harness.clock.advance(by: .seconds(2)) + try await waitUntil("timeout should rearm") { harness.clock.sleeperCount == 1 } + harness.coordinator.restartTimeout(deviceID: cycle.deviceID) + try await waitUntil("restarted timeout should park") { harness.clock.sleeperCount == 1 } + harness.clock.advance(by: .seconds(2)) + try await waitUntil("restarted UI window should still rearm") { harness.clock.sleeperCount == 1 } + #expect(harness.timeouts.isEmpty) + #expect(harness.coordinator.currentCycle == cycle) + harness.clock.advance(by: .seconds(1)) + try await waitUntil("restarted maximum window should end") { harness.timeouts == [cycle] } + } + } + + @Test + func `restartTimeout never invents a request or replaces another cycle`() async { + await withReconnectionHarness { harness in + harness.coordinator.restartTimeout(deviceID: UUID()) + #expect(harness.coordinator.currentCycle == nil) + let cycle = harness.begin() + harness.coordinator.restartTimeout(deviceID: UUID()) + #expect(harness.coordinator.currentCycle == cycle) + #expect(harness.clock.sleeperCount == 0) + } + } + + @Test + func `stale timeout arming preserves the current timer`() async throws { + try await withReconnectionHarness(uiTimeout: 1) { harness in + let old = harness.begin() + let next = harness.begin() + harness.coordinator.armTimeout(next) + try await waitUntil("current timeout should park") { harness.clock.sleeperCount == 1 } + harness.coordinator.armTimeout(old) + harness.clock.advance(by: .seconds(1)) + try await waitUntil("only current timeout should be delivered") { harness.timeouts == [next] } + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests+OutgoingReactionMetadata.swift b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests+OutgoingReactionMetadata.swift new file mode 100644 index 0000000000..0a09916d47 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests+OutgoingReactionMetadata.swift @@ -0,0 +1,63 @@ +import Foundation +@testable import MC1Services +import Testing + +extension BackupIntegrationTests { + @Test + func `metadata-only outgoing reaction import reports restored changes once`() async throws { + let radioID = UUID() + let destination = try await PersistenceStore.createTestDataStore(radioID: radioID) + let channel = ChannelDTO.testChannel(radioID: radioID) + try await destination.saveChannel(channel) + let target = MessageDTO.testChannelMessage(radioID: radioID, channelIndex: channel.index, text: "Target") + let reaction = MessageDTO.testChannelMessage(radioID: radioID, channelIndex: channel.index, text: "Reaction") + try await destination.saveMessage(target) + try await destination.saveMessage(reaction) + var backupReaction = reaction + backupReaction.reactionTargetMessageID = target.id + backupReaction.reactionSenderName = "Nate" + + let suiteName = "test.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { UserDefaults().removePersistentDomain(forName: suiteName) } + var preferences = BackupUserDefaults() + preferences.hasCompletedOnboarding = true + preferences.selectedThemeID = "marine" + preferences.restore(to: defaults) + let envelope = AppBackupEnvelope.test( + devices: [.testDevice(id: radioID, radioID: radioID)], + channels: [channel], messages: [target, backupReaction], userDefaults: preferences + ) + let service = AppBackupService() + + let firstImportDefaults = try #require(UserDefaults(suiteName: suiteName)) + let firstResult = try await service.importBackup( + envelope: envelope, into: destination, defaults: firstImportDefaults + ) + + #expect(firstResult.totalInserted == 0) + #expect(firstResult.messagesSkipped == 2) + #expect(firstResult.counts[.messages]?.merged == 1) + #expect(firstResult.totalMerged == 1) + #expect(firstResult.userDefaultsRestored == false) + #expect(firstResult.hasRestoredChanges) + let restored = try #require(try await destination.fetchMessage(id: reaction.id)) + #expect(restored.reactionTargetMessageID == target.id) + #expect(restored.reactionSenderName == "Nate") + + let secondImportDefaults = try #require(UserDefaults(suiteName: suiteName)) + let secondResult = try await service.importBackup( + envelope: envelope, into: destination, defaults: secondImportDefaults + ) + + #expect(secondResult.totalInserted == 0) + #expect(secondResult.messagesSkipped == 2) + #expect(secondResult.counts[.messages]?.merged == 0) + #expect(secondResult.totalMerged == 0) + #expect(secondResult.userDefaultsRestored == false) + #expect(secondResult.hasRestoredChanges == false) + let unchanged = try #require(try await destination.fetchMessage(id: reaction.id)) + #expect(unchanged.reactionTargetMessageID == target.id) + #expect(unchanged.reactionSenderName == "Nate") + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests+PendingAcknowledgements.swift b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests+PendingAcknowledgements.swift new file mode 100644 index 0000000000..1a69a81813 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests+PendingAcknowledgements.swift @@ -0,0 +1,38 @@ +import Foundation +@testable import MC1Services +import Testing + +extension BackupIntegrationTests { + @Test + func `ACK ownership stays local while the existing envelope round trips message history`() async throws { + let radioID = UUID() + let source = try await PersistenceStore.createTestDataStore(radioID: radioID) + let contact = ContactDTO.testContact(radioID: radioID) + try await source.saveContact(contact) + let message = MessageDTO.testDirectMessage(radioID: radioID, contactID: contact.id, ackCode: 123) + try await source.saveMessage(message) + let sentAt = Date() + let owner = PendingSendDTO( + envelope: DirectMessageEnvelope(messageID: message.id, contactID: contact.id, isSingleAttempt: true), radioID: radioID, + ackCodes: [Data([1, 2, 3, 4])], ackSentAt: sentAt, ackDeadline: sentAt.addingTimeInterval(60) + ) + #expect(try await source.savePendingAcknowledgement(owner, replacingPendingSendID: nil)) + let service = AppBackupService() + let exported = try await service.export(persistenceStore: source) + let envelope = try parseBackup(data: exported.data) + let json = try String(decoding: makeBackupJSONEncoder().encode(envelope), as: UTF8.self) + #expect(!json.contains("ackCodes")) + #expect(!json.contains("ackSentAt")) + #expect(!json.contains("ackDeadline")) + #expect(!json.contains("pendingSends")) + #expect(!json.contains("isSingleAttempt")) + #expect(envelope.messages.first?.id == message.id) + #expect(envelope.messages.first?.ackCode == 123) + let destination = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + _ = try await service.importBackup(envelope: envelope, into: destination) + #expect(try await destination.fetchMessage(id: message.id)?.ackCode == 123) + #expect(try await destination.fetchPendingSends(radioID: radioID).isEmpty) + #expect(try await source.fetchPendingSends(radioID: radioID).first?.ackCodes == owner.ackCodes) + #expect(try await source.fetchPendingSends(radioID: radioID).first?.isSingleAttempt == true) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift index 446fbc9d09..30f23455bb 100644 --- a/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift @@ -8,6 +8,98 @@ import Testing /// exercising the complete data flow rather than manually constructed envelopes. @Suite("BackupIntegration") struct BackupIntegrationTests { + @Test + func `backup restores conversations without local text rule selections`() async throws { + let radioID = UUID() + let source = try await PersistenceStore.createTestDataStore(radioID: radioID) + try await source.saveContact(.testContact(radioID: radioID)) + try await source.saveChannel(.testChannel(radioID: radioID)) + try await source.saveRemoteNodeSessionDTO(.testSession(radioID: radioID)) + let originals = try await source.textRulesConversations() + #expect(originals.count == 3) + for conversation in originals { + try await source.setTextRulesOverride(.on, kind: conversation.kind, key: conversation.key) + } + + let service = AppBackupService() + let exported = try await service.export(persistenceStore: source) + let encoded = try exported.data.zlibDecompressed(maxUncompressedBytes: maxBackupUncompressedBytes) + let json = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) + for collection in ["contacts", "channels", "remoteNodeSessions"] { + let row = try #require((json[collection] as? [[String: Any]])?.first) + #expect(row["textRulesID"] == nil) + #expect(row["textRulesOverride"] == nil) + } + let envelope = try parseBackup(data: exported.data) + let contact = try #require(envelope.contacts.first) + let channel = try #require(envelope.channels.first) + let room = try #require(envelope.remoteNodeSessions.first) + #expect(contact.textRulesID == nil) + #expect(channel.textRulesID == nil) + #expect(room.textRulesID == nil) + #expect(contact.textRulesOverride == .inherit) + #expect(channel.textRulesOverride == .inherit) + #expect(room.textRulesOverride == .inherit) + + let destination = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + _ = try await service.importBackup(envelope: envelope, into: destination) + let restored = try await destination.textRulesConversations() + #expect(restored.count == originals.count) + for conversation in restored { + #expect(conversation.override == .inherit) + #expect(!originals.contains { $0.key == conversation.key }) + } + } + + @Test(arguments: [RemoteNodeRole.sensor, .repeater, .roomServer]) + func `remote roles and legacy pins survive envelope import`(role: RemoteNodeRole) async throws { + let radioID = UUID() + let store = try await PersistenceStore.createTestDataStore(radioID: radioID) + let original = RemoteNodeSessionDTO.testSession(radioID: radioID, role: role, + isConnected: true, permissionLevel: .admin, isPinned: true) + try await store.saveRemoteNodeSessionDTO(original) + let service = AppBackupService() + let exported = try await service.export(persistenceStore: store) + let exportedEnvelope = try parseBackup(data: exported.data) + let exportedJSON = try makeBackupJSONEncoder().encode(exportedEnvelope) + var json = try #require(JSONSerialization.jsonObject(with: exportedJSON) as? [String: Any]) + var rows = try #require(json["remoteNodeSessions"] as? [[String: Any]]) + rows[0].removeValue(forKey: "isPinned") + rows[0]["isFavorite"] = true + json["remoteNodeSessions"] = rows + let legacy = try JSONSerialization.data(withJSONObject: json) + let envelope = try parseBackup(data: legacy.zlibCompressed()) + let destination = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + _ = try await service.importBackup(envelope: envelope, into: destination) + let restored = try #require(try await destination.fetchRemoteNodeSessions(radioID: radioID).first) + #expect(restored.role == role) + #expect(!restored.isConnected) + #expect(restored.isPinned) + rows[0]["isPinned"] = false + json["remoteNodeSessions"] = rows + let explicitFalse = try parseBackup(data: JSONSerialization.data(withJSONObject: json).zlibCompressed()) + #expect(explicitFalse.remoteNodeSessions[0].isPinned == false) + } + + @Test(arguments: [UInt8(4), UInt8(0x7F)]) + func `sensor and unknown contact and discovery types survive backup`(raw: UInt8) async throws { + let radioID = UUID() + let store = try await PersistenceStore.createTestDataStore(radioID: radioID) + let contact = ContactDTO.testContact(radioID: radioID, typeRawValue: raw) + try await store.saveContact(contact) + let frame = ContactFrame(publicKey: contact.publicKey, type: ContactType(rawValue: raw) ?? .chat, + typeRawValue: raw, flags: 0, outPathLength: 0xFF, outPath: Data(), + name: "Sensor", lastAdvertTimestamp: 0, latitude: 0, longitude: 0, lastModified: 0) + _ = try await store.upsertDiscoveredNode(radioID: radioID, from: frame) + let service = AppBackupService() + let exported = try await service.export(persistenceStore: store) + let envelope = try parseBackup(data: exported.data) + let destination = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + _ = try await service.importBackup(envelope: envelope, into: destination) + #expect(try await destination.fetchAllContacts(radioID: radioID).first?.typeRawValue == raw) + #expect(try await destination.fetchDiscoveredNodes(radioID: radioID).first?.typeRawValue == raw) + } + @Test @MainActor func `legacy WiFi ordering survives backup round trip without changing the selected endpoint`() async throws { @@ -182,18 +274,18 @@ struct BackupIntegrationTests { /// `decodeIfPresent` legacy path). An unmodeled type byte must survive verbatim so a /// future refactor can't silently re-collapse it onto a modeled `ContactType`. @Test - func `Unmodeled contact type byte (0x04) survives DTO encode → decode round-trip`() throws { - let dto = ContactDTO.testContact(typeRawValue: 0x04) + func `Unmodeled contact type byte (0x7F) survives DTO encode → decode round-trip`() throws { + let dto = ContactDTO.testContact(typeRawValue: 0x7F) let encoded = try JSONEncoder().encode(dto) let decoded = try JSONDecoder().decode(ContactDTO.self, from: encoded) - #expect(decoded.typeRawValue == 0x04) + #expect(decoded.typeRawValue == 0x7F) #expect(decoded.type == .chat) } /// Full envelope path: an unmodeled type byte must survive export → import into a fresh store, /// not just an isolated DTO round-trip. @Test - func `Unmodeled contact type byte (0x04) survives full backup export → import`() async throws { + func `Unmodeled contact type byte (0x7F) survives full backup export → import`() async throws { let radioID = UUID() let sourceStore = try await PersistenceStore.createTestDataStore(radioID: radioID) @@ -201,7 +293,7 @@ struct BackupIntegrationTests { radioID: radioID, publicKey: Data(repeating: 0xAB, count: 32), name: "FutureType", - typeRawValue: 0x04 + typeRawValue: 0x7F ) try await sourceStore.saveContact(contact) @@ -214,7 +306,7 @@ struct BackupIntegrationTests { _ = try await service.importBackup(envelope: envelope, into: destStore) let destContacts = try await destStore.fetchAllContacts(radioID: radioID) - #expect(destContacts.first?.typeRawValue == 0x04) + #expect(destContacts.first?.typeRawValue == 0x7F) #expect(destContacts.first?.type == .chat) } @@ -2409,6 +2501,249 @@ struct BackupIntegrationTests { #expect(decoded.longitude == -122.4194) } + @Test + func `Self telemetry owner and coordinates survive DTO encode and decode`() throws { + let owner = UUID() + let dto = NodeStatusSnapshotDTO.testSnapshot( + nodePublicKey: Data(repeating: 0xAB, count: 32), + selfRadioID: owner, + latitude: 47.6062, + longitude: -122.3321, + altitude: 15 + ) + let decoded = try JSONDecoder().decode(NodeStatusSnapshotDTO.self, from: JSONEncoder().encode(dto)) + #expect(decoded.selfRadioID == owner) + #expect(decoded.latitude == 47.6062) + #expect(decoded.longitude == -122.3321) + #expect(decoded.altitude == 15) + } + + @Test + func `Legacy snapshot envelope without a self owner decodes it as nil`() throws { + let dto = NodeStatusSnapshotDTO.testSnapshot( + selfRadioID: UUID(), + latitude: 47.6062, + longitude: -122.3321 + ) + let encoded = try JSONEncoder().encode(dto) + var json = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) + json.removeValue(forKey: "selfRadioID") + let stripped = try JSONSerialization.data(withJSONObject: json) + let decoded = try JSONDecoder().decode(NodeStatusSnapshotDTO.self, from: stripped) + #expect(decoded.selfRadioID == nil) + #expect(decoded.latitude == 47.6062) + #expect(decoded.batteryMillivolts == 3800) + } + + @Test + func `Import remaps a self telemetry owner and keeps a same-key remote row`() async throws { + let sharedKey = Data(repeating: 0xD1, count: 32) + let nodeKey = Data(repeating: 0xD2, count: 32) + let localRadioID = UUID() + let backupRadioID = UUID() + let timestamp = Date(timeIntervalSince1970: 1_700_000_900) + let container = try PersistenceStore.createContainer(inMemory: true) + let dest = PersistenceStore(modelContainer: container) + try await dest.saveDevice(DeviceDTO.testDevice(id: UUID(), radioID: localRadioID, publicKey: sharedKey)) + + let selfRow = NodeStatusSnapshotDTO.testSnapshot( + timestamp: timestamp, + nodePublicKey: nodeKey, + selfRadioID: backupRadioID, + batteryMillivolts: nil, + uptimeSeconds: nil, + telemetryEntries: [TelemetrySnapshotEntry(channel: 1, type: "voltage", value: 4.1)], + latitude: 47.6062, + longitude: -122.3321, + altitude: 12 + ) + let remoteRow = NodeStatusSnapshotDTO.testSnapshot( + timestamp: timestamp, + nodePublicKey: nodeKey, + batteryMillivolts: 3700, + uptimeSeconds: 60 + ) + let envelope = AppBackupEnvelope.test( + devices: [DeviceDTO.testDevice(id: UUID(), radioID: backupRadioID, publicKey: sharedKey)], + nodeStatusSnapshots: [selfRow, remoteRow] + ) + + let result = try await AppBackupService().importBackup(envelope: envelope, into: dest) + #expect(result.nodeStatusSnapshotsInserted == 2) + + let selfRows = try await dest.fetchSelfTelemetrySnapshots( + radioID: localRadioID, + nodePublicKey: nodeKey + ) + #expect(selfRows.count == 1) + #expect(selfRows.first?.selfRadioID == localRadioID) + #expect(selfRows.first?.latitude == 47.6062) + #expect(selfRows.first?.altitude == 12) + let remote = try await dest.fetchNodeStatusSnapshots(nodePublicKey: nodeKey, since: nil) + #expect(remote.count == 1) + #expect(remote.first?.selfRadioID == nil) + #expect(remote.first?.uptimeSeconds == 60) + let unmapped = try await dest.fetchSelfTelemetrySnapshots( + radioID: backupRadioID, + nodePublicKey: nodeKey + ) + #expect(unmapped.isEmpty) + } + + @Test + func `Import skips a self telemetry owner that does not resolve to a device`() async throws { + let radioID = UUID() + let dest = try await PersistenceStore.createTestDataStore(radioID: radioID) + let orphan = NodeStatusSnapshotDTO.testSnapshot( + nodePublicKey: Data(repeating: 0xE1, count: 32), + selfRadioID: UUID(), + latitude: 47.6, + longitude: -122.3 + ) + let envelope = AppBackupEnvelope.test( + devices: [DeviceDTO.testDevice(id: radioID, radioID: radioID)], + nodeStatusSnapshots: [orphan] + ) + + let result = try await AppBackupService().importBackup(envelope: envelope, into: dest) + #expect(result.nodeStatusSnapshotsInserted == 0) + #expect(result.nodeStatusSnapshotsSkipped == 1) + let exported = try await dest.fetchBackupExportSnapshot() + #expect(exported.nodeStatusSnapshots.contains { $0.id == orphan.id } == false) + } + + @Test + func `Repeated self telemetry import does not duplicate or rewrite a row`() async throws { + let radioID = UUID() + let nodeKey = Data(repeating: 0xE2, count: 32) + let timestamp = Date(timeIntervalSince1970: 1_700_000_950) + let dest = try await PersistenceStore.createTestDataStore(radioID: radioID) + let original = NodeStatusSnapshotDTO.testSnapshot( + timestamp: timestamp, + nodePublicKey: nodeKey, + selfRadioID: radioID, + latitude: 47.6062, + longitude: -122.3321, + altitude: 9 + ) + let envelope = AppBackupEnvelope.test( + devices: [DeviceDTO.testDevice(id: radioID, radioID: radioID)], + nodeStatusSnapshots: [original] + ) + let service = AppBackupService() + let first = try await service.importBackup(envelope: envelope, into: dest) + #expect(first.nodeStatusSnapshotsInserted == 1) + + let second = try await service.importBackup(envelope: envelope, into: dest) + #expect(second.nodeStatusSnapshotsInserted == 0) + #expect(second.nodeStatusSnapshotsSkipped == 1) + + let replay = NodeStatusSnapshotDTO.testSnapshot( + timestamp: timestamp, + nodePublicKey: nodeKey, + selfRadioID: radioID, + latitude: 1, + longitude: 2 + ) + let replayEnvelope = AppBackupEnvelope.test( + devices: [DeviceDTO.testDevice(id: radioID, radioID: radioID)], + nodeStatusSnapshots: [replay] + ) + let third = try await service.importBackup(envelope: replayEnvelope, into: dest) + #expect(third.nodeStatusSnapshotsInserted == 0) + #expect(third.nodeStatusSnapshotsSkipped == 1) + + let rows = try await dest.fetchSelfTelemetrySnapshots(radioID: radioID, nodePublicKey: nodeKey) + #expect(rows.count == 1) + #expect(rows.first?.id == original.id) + #expect(rows.first?.latitude == 47.6062) + } + + @Test + func `Deleting a restored device removes its remapped self telemetry from the next export`() async throws { + let localRadioID = UUID() + let backupRadioID = UUID() + let publicKey = Data(repeating: 0x01, count: 32) + let dest = try await PersistenceStore.createTestDataStore(radioID: localRadioID) + let snapshot = NodeStatusSnapshotDTO.testSnapshot( + nodePublicKey: publicKey, + selfRadioID: backupRadioID, + latitude: 47.6062, + longitude: -122.3321, + altitude: 4 + ) + let envelope = AppBackupEnvelope.test( + devices: [DeviceDTO.testDevice(id: UUID(), radioID: backupRadioID, publicKey: publicKey)], + nodeStatusSnapshots: [snapshot] + ) + let service = AppBackupService() + let imported = try await service.importBackup(envelope: envelope, into: dest) + #expect(imported.nodeStatusSnapshotsInserted == 1) + + try await dest.deleteDeviceAndData(id: localRadioID) + let exported = try await parseBackup(data: service.export(persistenceStore: dest).data) + #expect(exported.nodeStatusSnapshots.contains { $0.id == snapshot.id } == false) + #expect(exported.version == AppBackupEnvelope.legacyVersion) + } + + @Test + func `Reimporting a pre-reconciliation backup keeps the adopted self telemetry owner`() async throws { + let currentID = UUID() + let departingRadioID = UUID() + let adoptedRadioID = UUID() + let departingKey = Data(repeating: 0x11, count: 32) + let adoptedKey = Data(repeating: 0x22, count: 32) + let container = try PersistenceStore.createContainer(inMemory: true) + let store = PersistenceStore(modelContainer: container) + let current = DeviceDTO.testDevice( + id: currentID, + radioID: departingRadioID, + publicKey: departingKey, + isActive: true + ) + try await store.saveDevice(current) + let snapshotID = try #require( + try await store.recordSelfTelemetrySnapshot( + deviceID: currentID, + radioID: departingRadioID, + nodePublicKey: departingKey, + telemetry: [TelemetrySnapshotEntry(channel: 1, type: "voltage", value: 4.4)], + location: NodeLocationFix(latitude: 36.1, longitude: -115.1, altitude: 600) + ) + ) + + let service = AppBackupService() + let before = try await parseBackup(data: service.export(persistenceStore: store).data) + #expect(before.version == AppBackupEnvelope.currentVersion) + #expect(before.nodeStatusSnapshots.first?.id == snapshotID) + #expect(before.nodeStatusSnapshots.first?.selfRadioID == departingRadioID) + + let ghost = DeviceDTO.testDevice( + radioID: adoptedRadioID, + publicKey: adoptedKey, + isActive: false + ).copy { $0.connectionMethods = [] } + try await store.saveDevice(ghost) + let adopted = try await store.reconcileGhostIdentity(currentDeviceID: currentID, newPublicKey: adoptedKey) + #expect(adopted == adoptedRadioID) + + let reimport = try await service.importBackup(envelope: before, into: store) + #expect(reimport.nodeStatusSnapshotsInserted == 0) + #expect(reimport.nodeStatusSnapshotsSkipped == 1) + let kept = try await store.fetchSelfTelemetrySnapshots( + radioID: adoptedRadioID, + nodePublicKey: departingKey + ) + #expect(kept.count == 1) + #expect(kept.first?.id == snapshotID) + #expect(kept.first?.selfRadioID == adoptedRadioID) + #expect(kept.first?.latitude == 36.1) + + try await store.deleteDeviceAndData(id: currentID) + let after = try await store.fetchBackupExportSnapshot() + #expect(after.nodeStatusSnapshots.contains { $0.id == snapshotID } == false) + } + /// Full envelope path: the six counters must survive export → import into a fresh store. @Test func `Node status packet-type counters survive full backup export → import`() async throws { @@ -3722,12 +4057,12 @@ struct BackupIntegrationTests { @Test func `Legacy envelope without regionSelection decodes as nil`() throws { - let legacyJSON = """ + let legacyJSON = try #require(""" { "hasCompletedOnboarding": true, "mapStyleSelection": "topo" } - """.data(using: .utf8)! + """.data(using: .utf8)) let decoded = try JSONDecoder().decode(BackupUserDefaults.self, from: legacyJSON) #expect(decoded.regionSelection == nil) #expect(decoded.hasCompletedOnboarding == true) @@ -3781,12 +4116,12 @@ struct BackupIntegrationTests { @Test func `Legacy envelope without translationTargetLanguage decodes as nil`() throws { - let legacyJSON = """ + let legacyJSON = try #require(""" { "hasCompletedOnboarding": true, "mapStyleSelection": "topo" } - """.data(using: .utf8)! + """.data(using: .utf8)) let decoded = try JSONDecoder().decode(BackupUserDefaults.self, from: legacyJSON) #expect(decoded.translationTargetLanguage == nil) } @@ -3806,12 +4141,12 @@ struct BackupIntegrationTests { @Test func `Legacy envelope without useDefaultTranslationApp decodes as nil`() throws { - let legacyJSON = """ + let legacyJSON = try #require(""" { "hasCompletedOnboarding": true, "mapStyleSelection": "topo" } - """.data(using: .utf8)! + """.data(using: .utf8)) let decoded = try JSONDecoder().decode(BackupUserDefaults.self, from: legacyJSON) #expect(decoded.useDefaultTranslationApp == nil) } @@ -3836,6 +4171,44 @@ struct BackupIntegrationTests { #expect(defaults.bool(forKey: AppStorageKey.useDefaultTranslationApp.rawValue) == true) } + // MARK: - DM attempt budget backup contract + + @Test + func `DM attempt budget including explicit zero survives a full backup envelope`() throws { + var preferences = BackupUserDefaults() + preferences.dmDirectAttempts = 2 + preferences.dmFloodAttempts = 0 + let original = AppBackupEnvelope.test(version: AppBackupEnvelope.legacyVersion, userDefaults: preferences) + let encoded = try makeBackupJSONEncoder().encode(original) + let envelope = try parseBackup(data: encoded.zlibCompressed()) + let decoded = try #require(envelope.userDefaults) + #expect(decoded == preferences) + + let suiteName = "test.dmBudget.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + decoded.restore(to: defaults) + + let budget = DMSendBudget.current(defaults: defaults) + #expect(budget.directAttempts == 2) + #expect(budget.floodAttempts == 0) + } + + @Test + func `legacy backup envelope preserves missing DM attempt settings`() throws { + let original = AppBackupEnvelope.test(version: AppBackupEnvelope.legacyVersion) + let encoded = try makeBackupJSONEncoder().encode(original) + var json = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) + json["userDefaults"] = ["hasCompletedOnboarding": true] + let legacy = try JSONSerialization.data(withJSONObject: json).zlibCompressed() + + let decoded = try parseBackup(data: legacy) + let preferences = try #require(decoded.userDefaults) + #expect(preferences.hasCompletedOnboarding == true) + #expect(preferences.dmDirectAttempts == nil) + #expect(preferences.dmFloodAttempts == nil) + } + // MARK: - Message.regionScope round-trip @Test @@ -4136,6 +4509,8 @@ struct BackupIntegrationTests { timestampCorrected: true, senderTimestamp: 1_699_999_999, reactionSummary: "👍:3,❤️:2", + reactionTargetMessageID: UUID(), + reactionSenderName: "Nate", routeType: .tcDirect, regionScope: "Germany" ) @@ -4181,6 +4556,125 @@ struct BackupIntegrationTests { #expect(imported.reactionSummary == "👍:2") } + @Test + func `outgoing reaction metadata survives backup export and import without replay work`() async throws { + let radioID = UUID() + let source = try await PersistenceStore.createTestDataStore(radioID: radioID) + let channel = ChannelDTO.testChannel(radioID: radioID) + try await source.saveChannel(channel) + let target = MessageDTO.testChannelMessage(radioID: radioID, channelIndex: channel.index, text: "Target") + try await source.saveMessage(target) + var reaction = MessageDTO.testChannelMessage(radioID: radioID, channelIndex: channel.index, text: "Reaction") + reaction.reactionTargetMessageID = target.id + reaction.reactionSenderName = "Nate" + try await source.saveMessage(reaction) + + let service = AppBackupService() + let exported = try await service.export(persistenceStore: source) + let envelope = try parseBackup(data: exported.data) + let encoded = try #require(envelope.messages.first { $0.id == reaction.id }) + #expect(encoded.reactionTargetMessageID == target.id) + #expect(encoded.reactionSenderName == "Nate") + let destination = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + _ = try await service.importBackup(envelope: envelope, into: destination) + let restored = try #require(try await destination.fetchMessage(id: reaction.id)) + #expect(restored.reactionTargetMessageID == target.id) + #expect(restored.reactionSenderName == "Nate") + #expect(try await destination.fetchPendingSends(radioID: radioID).isEmpty) + } + + @Test + func `legacy backup messages without outgoing reaction metadata decode with nil defaults`() async throws { + let radioID = UUID() + let source = try await PersistenceStore.createTestDataStore(radioID: radioID) + var message = MessageDTO.testDirectMessage(radioID: radioID) + message.reactionTargetMessageID = UUID() + message.reactionSenderName = "Nate" + try await source.saveMessage(message) + let exported = try await AppBackupService().export(persistenceStore: source) + let current = try parseBackup(data: exported.data) + let encoded = try makeBackupJSONEncoder().encode(current) + var json = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) + var rows = try #require(json["messages"] as? [[String: Any]]) + rows[0].removeValue(forKey: "reactionTargetMessageID") + rows[0].removeValue(forKey: "reactionSenderName") + json["messages"] = rows + + let legacy = try parseBackup(data: JSONSerialization.data(withJSONObject: json).zlibCompressed()) + let decoded = try #require(legacy.messages.first) + #expect(decoded.reactionTargetMessageID == nil) + #expect(decoded.reactionSenderName == nil) + let destination = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + _ = try await AppBackupService().importBackup(envelope: legacy, into: destination) + let restored = try #require(try await destination.fetchMessage(id: message.id)) + #expect(restored.reactionTargetMessageID == nil) + #expect(restored.reactionSenderName == nil) + } + + @Test(arguments: [false, true]) + func `reaction metadata remaps a merged target and only fills missing local fields`(hasLocalMetadata: Bool) async throws { + let radioID = UUID() + let destination = try await PersistenceStore.createTestDataStore(radioID: radioID) + let contact = ContactDTO.testContact(radioID: radioID) + try await destination.saveContact(contact) + var localTarget = MessageDTO.testDirectMessage( + radioID: radioID, contactID: contact.id, text: "Target", direction: .incoming + ) + localTarget.deduplicationKey = "reaction-target-remap" + try await destination.saveMessage(localTarget) + let otherTarget = MessageDTO.testDirectMessage(radioID: radioID, contactID: contact.id, text: "Other target") + try await destination.saveMessage(otherTarget) + var localReaction = MessageDTO.testDirectMessage(radioID: radioID, contactID: contact.id, text: "Reaction") + if hasLocalMetadata { + localReaction.reactionTargetMessageID = otherTarget.id + localReaction.reactionSenderName = "Local" + } + try await destination.saveMessage(localReaction) + var backupTarget = localTarget + backupTarget.id = UUID() + var backupReaction = localReaction + backupReaction.reactionTargetMessageID = backupTarget.id + backupReaction.reactionSenderName = "Nate" + let envelope = AppBackupEnvelope.test( + devices: [.testDevice(id: radioID, radioID: radioID)], + contacts: [contact], messages: [backupReaction, backupTarget] + ) + + _ = try await AppBackupService().importBackup(envelope: envelope, into: destination) + + let restored = try #require(try await destination.fetchMessage(id: localReaction.id)) + #expect(restored.reactionTargetMessageID == (hasLocalMetadata ? otherTarget.id : localTarget.id)) + #expect(restored.reactionSenderName == (hasLocalMetadata ? "Local" : "Nate")) + } + + @Test + func `a newly imported outgoing reaction targets the winning local message`() async throws { + let radioID = UUID() + let destination = try await PersistenceStore.createTestDataStore(radioID: radioID) + let contact = ContactDTO.testContact(radioID: radioID) + try await destination.saveContact(contact) + var target = MessageDTO.testDirectMessage( + radioID: radioID, contactID: contact.id, text: "Target", direction: .incoming + ) + target.deduplicationKey = "new-reaction-target-remap" + try await destination.saveMessage(target) + var backupTarget = target + backupTarget.id = UUID() + var reaction = MessageDTO.testDirectMessage(radioID: radioID, contactID: contact.id, text: "Reaction") + reaction.reactionTargetMessageID = backupTarget.id + reaction.reactionSenderName = "Nate" + let envelope = AppBackupEnvelope.test( + devices: [.testDevice(id: radioID, radioID: radioID)], + contacts: [contact], messages: [reaction, backupTarget] + ) + + _ = try await AppBackupService().importBackup(envelope: envelope, into: destination) + + let restored = try #require(try await destination.fetchMessage(id: reaction.id)) + #expect(restored.reactionTargetMessageID == target.id) + #expect(restored.reactionSenderName == "Nate") + } + // MARK: - selectedThemeID backup contract @Test @@ -4194,9 +4688,9 @@ struct BackupIntegrationTests { @Test func `Legacy envelope without selectedThemeID decodes as nil`() throws { - let legacyJSON = """ + let legacyJSON = try #require(""" { "hasCompletedOnboarding": true, "mapStyleSelection": "topo" } - """.data(using: .utf8)! + """.data(using: .utf8)) let decoded = try JSONDecoder().decode(BackupUserDefaults.self, from: legacyJSON) #expect(decoded.selectedThemeID == nil) #expect(decoded.hasCompletedOnboarding == true) @@ -4227,9 +4721,9 @@ struct BackupIntegrationTests { @Test func `Legacy envelope without appColorSchemePreference decodes as nil`() throws { - let legacyJSON = """ + let legacyJSON = try #require(""" { "hasCompletedOnboarding": true, "mapStyleSelection": "topo" } - """.data(using: .utf8)! + """.data(using: .utf8)) let decoded = try JSONDecoder().decode(BackupUserDefaults.self, from: legacyJSON) #expect(decoded.appColorSchemePreference == nil) } diff --git a/MC1Services/Tests/MC1ServicesTests/BackupUserDefaultsCoverageTests.swift b/MC1Services/Tests/MC1ServicesTests/BackupUserDefaultsCoverageTests.swift index b4167d9d32..a81e26c15a 100644 --- a/MC1Services/Tests/MC1ServicesTests/BackupUserDefaultsCoverageTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/BackupUserDefaultsCoverageTests.swift @@ -72,6 +72,7 @@ struct BackupUserDefaultsCoverageTests { let allOptional = allOptionalPropertyNames() let covered = BackupUserDefaults.boolMappingKeys .union(BackupUserDefaults.stringMappingKeys) + .union(BackupUserDefaults.intMappingKeys) .union(BackupUserDefaults.specialCasedPropertyNames) let uncovered = allOptional.subtracting(covered) @@ -80,9 +81,9 @@ struct BackupUserDefaultsCoverageTests { #expect(uncovered.isEmpty, """ Optional properties not covered by any mapping or allow-list: \(uncovered.sorted()). Either: - (a) add to boolMappings/stringMappings if Bool?/String?, or + (a) add to boolMappings/stringMappings/intMappings if Bool?/String?/Int?, or (b) hand-roll snapshot/restore branches and add to specialCasedPropertyNames. - See BackupUserDefaults.boolMappings / stringMappings / specialCasedPropertyNames. + See BackupUserDefaults.boolMappings / stringMappings / intMappings / specialCasedPropertyNames. """) #expect(staleAllowList.isEmpty, """ diff --git a/MC1Services/Tests/MC1ServicesTests/BondLossPairingRecoveryTests.swift b/MC1Services/Tests/MC1ServicesTests/BondLossPairingRecoveryTests.swift index bd2b065a51..0ad4ada686 100644 --- a/MC1Services/Tests/MC1ServicesTests/BondLossPairingRecoveryTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/BondLossPairingRecoveryTests.swift @@ -2,9 +2,7 @@ import CoreBluetooth import Foundation @testable import MC1Services import MeshCore -import MeshCoreTestSupport import ObjectiveC -import SwiftData import Testing /// A radio that loses its bond mid-session is recovered through the guided @@ -18,135 +16,107 @@ import Testing struct BondLossPairingRecoveryTests { private static let radioPublicKey = Data(repeating: 0x7B, count: 32) - private static let testCapabilities = DeviceCapabilities( - firmwareVersion: 9, - maxContacts: 100, - maxChannels: 8, - blePin: 0, - firmwareBuild: "01 Jan 2025", - model: "T-Deck", - version: "v1.13.0" - ) - - private static func makeSelfInfo(publicKey: Data = radioPublicKey) -> SelfInfo { - SelfInfo( - advertisementType: 0, - txPower: 20, - maxTxPower: 20, - publicKey: publicKey, - latitude: 0, - longitude: 0, - multiAcks: 2, - advertisementLocationPolicy: 0, - telemetryModeEnvironment: 0, - telemetryModeLocation: 0, - telemetryModeBase: 2, - manualAddContacts: false, - radioFrequency: 915.0, - radioBandwidth: 250.0, - radioSpreadingFactor: 10, - radioCodingRate: 5, - name: "TestNode" - ) - } - - /// A never-connected session so the up-front `getAutoAddConfig` roundtrip - /// fails fast; the connect ceremony swallows it and proceeds. - private func makeOfflineSession() -> MeshCoreSession { - MeshCoreSession( - transport: SimulatorMockTransport(), - configuration: SessionConfiguration(defaultTimeout: 0.5, clientIdentifier: "BondLossRecoveryTest") - ) - } - @Test func `removeFailedPairing keeps the radio's data reachable when the same radio re-pairs`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - - // First connect: fresh pairing mints a radioID for this publicKey. - let firstBLEID = UUID() - let firstConnect = try await manager.buildServicesAndSaveDevice( - deviceID: firstBLEID, - session: makeOfflineSession(), - selfInfo: Self.makeSelfInfo(), - capabilities: Self.testCapabilities - ) - let originalRadioID = firstConnect.radioID - let store = firstConnect.services.dataStore - - // Seed the per-radio children a synced radio accumulates. - let contactID = UUID() - let contact = ContactDTO( - id: contactID, - radioID: originalRadioID, - publicKey: Data((0.. [Data] { + var packet = Data([ResponseCode.contact.rawValue]) + packet.append(contact.publicKey) + packet.append(contentsOf: [ContactType.chat.rawValue, 0, 0xFF]) + packet.append(Data(repeating: 0, count: 64)) + let name = Data(contact.name.utf8.prefix(31)) + packet.append(name) + packet.append(Data(repeating: 0, count: 32 - name.count)) + packet.append(Data(repeating: 0, count: 16)) + return [Data([ResponseCode.contactStart.rawValue, 1, 0, 0, 0]), packet, Data([ResponseCode.contactEnd.rawValue, 1, 0, 0, 0])] } @Test @@ -165,7 +135,7 @@ struct BondLossPairingRecoveryTests { try await manager.persistenceStore.saveDevice(device) manager.persistConnection(deviceID: peripheralID, radioID: radioID, deviceName: device.nodeName) - await manager.removeFailedPairing(deviceID: peripheralID) + try await manager.removeFailedPairing(deviceID: peripheralID) let rows = try await manager.persistenceStore.fetchDevices() #expect(rows.map(\.id) == [peripheralID]) @@ -260,7 +230,7 @@ struct BondLossPairingRecoveryTests { LastConnectionStore(defaults: defaults).persistBondVerification(deviceID: deviceB) // removeFailedPairing is the async forget path; must clear B even though A is last-connected. - await env.manager.removeFailedPairing(deviceID: deviceB) + try await env.manager.removeFailedPairing(deviceID: deviceB) #expect(await env.stateMachine.recordedBondVerifications[deviceB] == nil) let store = LastConnectionStore(defaults: defaults) @@ -298,8 +268,9 @@ struct BondLossPairingRecoveryTests { await sm.appDidBecomeActive() await sm.primeBondClearAutoReconnecting(peripheral: peripheral) let recorder = BondClearDisconnectionRecorder() - await sm.setDisconnectionHandler { id, error in - recorder.append(deviceID: id, error: error) + await sm.setLifecycleEventHandler { event, _ in + guard case let .disconnected(origin, error) = event else { return } + recorder.append(deviceID: origin.deviceID, error: error) } let encryptionTimedOut = NSError( domain: CBErrorDomain, diff --git a/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityAdmissionTests.swift b/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityAdmissionTests.swift new file mode 100644 index 0000000000..01b3fc805d --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityAdmissionTests.swift @@ -0,0 +1,93 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Canonical identity admission") +@MainActor +struct CanonicalIdentityAdmissionTests { + @Test + func `old queue admission closes before the private key reaches firmware`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let services = try #require(harness.manager.services) + let oldQueue = services.chatSendQueueService + let pending = try await services.messageService.createPendingChannelMessage( + text: "Old partition draft", channelIndex: 0, radioID: harness.deviceA.radioID + ) + await harness.bluetooth.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + await harness.bluetooth.holdReplies(for: .importPrivateKey) + let importing = harness.track(Task { + try await services.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + }) + try await waitUntil("private key should reach firmware while its acknowledgement is held") { + await harness.bluetooth.sentData.contains { $0.first == CommandCode.importPrivateKey.rawValue } + } + var acceptedOldEnqueue = false + do { + try await oldQueue.enqueueChannel(ChannelMessageEnvelope( + messageID: pending.id, channelIndex: 0, isResend: false, + messageText: pending.text, messageTimestamp: pending.timestamp, localNodeName: "Old radio" + )) + acceptedOldEnqueue = true + } catch is CancellationError {} + #expect(!acceptedOldEnqueue) + #expect(try await harness.manager.persistenceStore.fetchPendingSends(radioID: harness.deviceA.radioID) + .contains { $0.messageID == pending.id } == false) + await harness.bluetooth.releaseReplies(for: .importPrivateKey) + try await importing.value + let sent = await harness.bluetooth.sentData + let importIndex = try #require(sent.firstIndex { $0.first == CommandCode.importPrivateKey.rawValue }) + #expect(!sent.dropFirst(importIndex + 1).contains { $0.first == CommandCode.sendChannelMessage.rawValue }) + #expect(harness.manager.connectedDevice?.radioID == harness.deviceB.radioID) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } + + @Test + func `cancelled import waiter cannot abandon accepted canonical evidence transfer`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let services = try #require(harness.manager.services) + _ = try await services.settingsService.runCliCommand("set wifi.enabled 0") + let canonical = harness.manager.radioWiFiState(for: harness.deviceB.radioID) + await harness.bluetooth.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + let gate = IdentityRecoveryFixture.Gate() + harness.manager.testIdentityAfterCommit = { await gate.wait() } + let importing = harness.track(Task { + try await services.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + }) + do { + try await waitUntil("accepted canonical store result should hold before evidence transfer") { gate.arrived } + #expect(!canonical.rebootPending) + importing.cancel() + gate.open() + _ = await importing.result + } catch { + gate.open() + _ = await importing.result + harness.manager.testIdentityAfterCommit = nil + throw error + } + harness.manager.testIdentityAfterCommit = nil + await harness.manager.metadataCommitTask?.value + let fresh = try await harness.manager.persistenceStore.fetchDevice(id: harness.deviceA.id) + #expect(fresh?.radioID == harness.deviceB.radioID) + #expect(canonical.rebootPending) + #expect(canonical.stableRevision() == nil) + let cancelledOwnerWasNotPublished = harness.manager.connectedDevice == nil && harness.manager.services == nil + #expect(cancelledOwnerWasNotPublished) + _ = try await harness.manager.connect(to: harness.deviceA.id, forceReconnect: true) + #expect(harness.manager.connectedDevice?.radioID == harness.deviceB.radioID) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityConsumerTests.swift b/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityConsumerTests.swift new file mode 100644 index 0000000000..687148fed0 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityConsumerTests.swift @@ -0,0 +1,164 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Canonical identity partition consumers") +@MainActor +struct CanonicalIdentityConsumerTests { + @Test + func `actual channel room discovery and cleanup handlers use the canonical partition`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + harness.manager.testNotificationSystemOperations = .init( + setBadgeCount: { _ in }, deliveredRequests: { [] }, removeDeliveredNotifications: { _ in } + ) + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let source = try #require(harness.manager.services) + let store = harness.manager.persistenceStore + let roomKey = Data(repeating: 0xD4, count: ProtocolLimits.publicKeySize) + let roomA = RemoteNodeSessionDTO.testSession(radioID: harness.deviceA.radioID, publicKey: roomKey, name: "A room") + let roomB = RemoteNodeSessionDTO.testSession(radioID: harness.deviceB.radioID, publicKey: roomKey, name: "B room") + try await store.saveRemoteNodeSessionDTO(roomA) + try await store.saveRemoteNodeSessionDTO(roomB) + let contactA = ContactDTO.testContact(radioID: harness.deviceA.radioID, publicKey: roomKey, name: "A room", typeRawValue: ContactType.room.rawValue) + let contactB = ContactDTO.testContact(radioID: harness.deviceB.radioID, publicKey: roomKey, name: "B room", typeRawValue: ContactType.room.rawValue) + try await store.saveContact(contactA) + try await store.saveContact(contactB) + let pendingA = try await source.messageService.createPendingMessage(text: "Preserve A history", to: contactA) + _ = try await source.messageService.createPendingMessage(text: "Delete B history", to: contactB) + let advertKey = Data(repeating: 0xD6, count: ProtocolLimits.publicKeySize) + let advertA = ContactDTO.testContact(radioID: harness.deviceA.radioID, publicKey: advertKey) + let advertB = ContactDTO.testContact(radioID: harness.deviceB.radioID, publicKey: advertKey) + try await store.saveContact(advertA) + try await store.saveContact(advertB) + _ = try await source.messageService.createPendingMessage(text: "Preserve A advert history", to: advertA) + _ = try await source.messageService.createPendingMessage(text: "Delete B advert history", to: advertB) + await harness.bluetooth.setResponsePackets(for: .getContacts, packets: [ + Data([ResponseCode.contactStart.rawValue, 2, 0, 0, 0]), + Data([ResponseCode.contact.rawValue]) + contactData(key: roomKey, name: "B room", type: .room), + Data([ResponseCode.contact.rawValue]) + contactData(key: advertKey, name: "B advertised", type: .chat), + Data([ResponseCode.contactEnd.rawValue, 1, 0, 0, 0]) + ]) + await harness.bluetooth.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + try await source.nodeConfigService.importConfig( + MeshCoreNodeConfig( + privateKey: CanonicalIdentityFixture.privateKeyHex, + channels: [.init(name: "Canonical", secret: String(repeating: "CD", count: 16))] + ), sections: ConfigSections(nodeIdentity: true, channels: true), radioID: harness.deviceA.radioID + ) + let live = try #require(harness.manager.services) + var channel = Data([ResponseCode.channelMessageReceived.rawValue, 0, 0, MeshCore.TextType.plainText.rawValue]) + channel.append(withUnsafeBytes(of: UInt32(1_700_000_100).littleEndian) { Data($0) }) + channel.append(Data("Remote: Canonical channel incoming".utf8)) + await harness.bluetooth.inject(channel) + var room = Data([ResponseCode.contactMessageReceived.rawValue]) + roomKey.prefix(6) + room.append(contentsOf: [0, MeshCore.TextType.signed.rawValue]) + room.append(withUnsafeBytes(of: UInt32(1_700_000_101).littleEndian) { Data($0) }) + room.append(contentsOf: [0xE1, 0xE2, 0xE3, 0xE4]) + room.append(Data("Author: Canonical room incoming".utf8)) + await harness.bluetooth.inject(room) + let discoveredKey = Data(repeating: 0xD5, count: ProtocolLimits.publicKeySize) + await harness.bluetooth.inject(newAdvertisement(key: discoveredKey)) + try await waitUntil("canonical channel message should persist") { + await (try? store.fetchMessages(radioID: harness.deviceB.radioID, channelIndex: 0).contains { $0.text == "Canonical channel incoming" }) == true + } + try await waitUntil("canonical room should receive its signed message") { + await (try? store.fetchRoomMessages(sessionID: roomB.id).contains { $0.text.contains("Canonical room incoming") }) == true + } + try await waitUntil("canonical discovered node should persist") { + await (try? store.fetchDiscoveredNodes(radioID: harness.deviceB.radioID).contains { $0.publicKey == discoveredKey }) == true + } + #expect(try await store.fetchMessages(radioID: harness.deviceA.radioID, channelIndex: 0).isEmpty) + #expect(try await store.fetchRoomMessages(sessionID: roomA.id).isEmpty) + #expect(try await store.fetchDiscoveredNodes(radioID: harness.deviceA.radioID).contains { $0.publicKey == discoveredKey } == false) + await harness.bluetooth.inject(Data([ResponseCode.contactDeleted.rawValue]) + advertKey) + try await waitUntil("canonical advert deletion should delete B contact and history") { + let contact = try? await store.fetchContact(id: advertB.id) + let messages = try? await store.fetchMessages(contactID: advertB.id) + return contact == nil && messages?.isEmpty == true + } + #expect(try await store.fetchContact(id: advertA.id) != nil) + #expect(try await store.fetchMessages(contactID: advertA.id).count == 1) + try await live.contactService.removeContact(radioID: harness.deviceB.radioID, publicKey: roomKey) + #expect(try await store.fetchMessages(contactID: contactB.id).isEmpty) + #expect(try await store.fetchContact(id: contactA.id)?.radioID == harness.deviceA.radioID) + #expect(try await store.fetchRemoteNodeSession(id: roomA.id)?.radioID == harness.deviceA.radioID) + #expect(try await store.fetchRemoteNodeSession(id: roomB.id) == nil) + #expect(try await store.fetchMessage(id: pendingA.id)?.radioID == harness.deviceA.radioID) + #expect(try await live.settingsService.getTime().timeIntervalSince1970 > 0) + } + } + + @Test + func `parked canonical send hydrates on reconnect while old unsent data stays excluded`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let source = try #require(harness.manager.services) + let oldMessage = try await source.messageService.createPendingChannelMessage( + text: "A-unsent", channelIndex: 0, radioID: harness.deviceA.radioID + ) + let oldEnvelope = envelope(oldMessage) + _ = try await harness.manager.persistenceStore.insertPendingSendAssigningSequence( + PendingSendDTO(envelope: oldEnvelope, radioID: harness.deviceA.radioID) + ) + await harness.bluetooth.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + await harness.bluetooth.setChannel(index: 0, name: "Canonical", secret: Data(repeating: 0xCD, count: 16)) + try await source.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + let canonical = try #require(harness.manager.services) + let channel = try #require(try await canonical.channelService.getChannel(radioID: harness.deviceB.radioID, index: 0)) + try #require(channel.secret == Data(repeating: 0xCD, count: 16)) + #expect(await harness.bluetooth.channelMatches(index: 0, secret: channel.secret)) + let message = try await canonical.messageService.createPendingChannelMessage( + text: "B-parked", channelIndex: 0, radioID: harness.deviceB.radioID + ) + let failedSendsBefore = await harness.bluetooth.failedSendCount + await harness.bluetooth.setSendError(MeshCoreError.notConnected, for: .sendChannelMessage) + try await canonical.chatSendQueueService.enqueueChannel(envelope(message)) + try await waitUntil("canonical send should fail transiently and park before reconnect") { + let rows = await (try? harness.manager.persistenceStore.fetchPendingSends(radioID: harness.deviceB.radioID)) ?? [] + let row = try? await harness.manager.persistenceStore.fetchMessage(id: message.id) + let failedSends = await harness.bluetooth.failedSendCount + let parkedDrains = await canonical.chatSendQueueService.parkedDrainCountForTesting + return failedSends > failedSendsBefore && parkedDrains > 0 && row?.status == .pending && + rows.contains { $0.messageID == message.id && ($0.attemptCount ?? 0) > 0 } + } + await harness.bluetooth.setSendError(nil, for: .sendChannelMessage) + _ = try await harness.manager.connect(to: harness.deviceA.id, forceReconnect: true) + try await waitUntil("fresh canonical queue should replay and remove its pending row") { + let row = try? await harness.manager.persistenceStore.fetchMessage(id: message.id) + let pending = await (try? harness.manager.persistenceStore.fetchPendingSends(radioID: harness.deviceB.radioID)) ?? [] + return row?.status == .sent && !pending.contains { $0.messageID == message.id } + } + #expect(try await harness.manager.persistenceStore.fetchPendingSends(radioID: harness.deviceA.radioID).contains { $0.messageID == oldMessage.id }) + let sent = await harness.bluetooth.sentData.filter { $0.first == CommandCode.sendChannelMessage.rawValue } + #expect(sent.contains { $0.range(of: Data("B-parked".utf8)) != nil }) + #expect(sent.contains { $0.range(of: Data("A-unsent".utf8)) != nil } == false) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } + + private func envelope(_ message: MessageDTO) -> ChannelMessageEnvelope { + ChannelMessageEnvelope(messageID: message.id, channelIndex: 0, isResend: false, + messageText: message.text, messageTimestamp: message.timestamp, localNodeName: "Canonical radio") + } + + private func newAdvertisement(key: Data) -> Data { + Data([ResponseCode.newAdvertisement.rawValue]) + contactData(key: key, name: "Canonical discovered", type: .chat) + } + + private func contactData(key: Data, name: String, type: ContactType) -> Data { + let nameBytes = Data(name.utf8) + var packet = key + packet.append(contentsOf: [type.rawValue, 0, 0xFF]) + packet.append(Data(repeating: 0, count: 64)) + packet.append(nameBytes) + packet.append(Data(repeating: 0, count: 32 - nameBytes.count)) + packet.append(Data(repeating: 0, count: 16)) + return packet + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityContractTests.swift b/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityContractTests.swift new file mode 100644 index 0000000000..0e51baafbf --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityContractTests.swift @@ -0,0 +1,124 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Canonical identity contracts") +@MainActor +struct CanonicalIdentityContractTests { + @Test(arguments: [false, true], [false, true]) + func `config import adopts canonical WiFi ownership before later mutation and reconnect`( + sourceWasPending: Bool, canonicalWasPending: Bool + ) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let services = try #require(harness.manager.services) + let settings = services.settingsService + let oldContext = settings.radioWiFiContextID + let stateA = settings.radioWiFiState + let stateB = harness.manager.radioWiFiState(for: harness.deviceB.radioID) + if canonicalWasPending { + let mutation = try #require(stateB.beginMutation(expectedRevision: nil)) + stateB.settle(mutation, outcome: .accepted) + } + if sourceWasPending { _ = try await settings.runCliCommand("set wifi.enabled 0") } + let observedAt = ContinuousClock.now + let before = RadioWiFiResetObservation(uptimeSeconds: 1000, startedAt: observedAt, completedAt: observedAt) + let sourceCandidate = stateA.prepareExpectedReboot(contextID: oldContext, observation: before) + let canonicalContext = UUID() + let canonicalCandidate = stateB.prepareExpectedReboot(contextID: canonicalContext, observation: before) + if let sourceCandidate { + stateA.completeRebootSubmission(id: sourceCandidate, succeeded: true) + stateA.noteLinkEnded(contextID: oldContext) + } + if let canonicalCandidate { + stateB.completeRebootSubmission(id: canonicalCandidate, succeeded: true) + stateB.noteLinkEnded(contextID: canonicalContext) + } + let revisionB = stateB.revision + await harness.bluetooth.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + let config = MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex) + try await services.nodeConfigService.importConfig( + config, sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + + #expect(harness.manager.connectedDevice?.radioID == harness.deviceB.radioID) + let canonicalSettings = try #require(harness.manager.services?.settingsService) + #expect(canonicalSettings !== settings) + #expect(canonicalSettings.radioWiFiState === stateB) + #expect(canonicalSettings.radioWiFiContextID != oldContext) + #expect(settings.radioWiFiContextID == oldContext) + #expect(settings.radioWiFiState === stateA) + #expect(stateB.revision > revisionB) + #expect(stateB.rebootPending == (sourceWasPending || canonicalWasPending)) + #expect(stateA.expectedRebootID == nil) + #expect(stateB.expectedRebootID == nil) + let after = RadioWiFiResetObservation(uptimeSeconds: 1, startedAt: .now, completedAt: .now) + if let sourceCandidate { + #expect(!stateA.clearExpectedReboot(id: sourceCandidate, contextID: UUID(), readRevision: stateA.revision, observation: after)) + } + if let canonicalCandidate { + #expect(!stateB.clearExpectedReboot(id: canonicalCandidate, contextID: canonicalSettings.radioWiFiContextID, readRevision: stateB.revision, observation: after)) + } + #expect(stateB.stableRevision() != nil) + let framesBeforeOldCommand = await harness.bluetooth.sentData.count + await #expect { + try await settings.runCliCommand("set wifi.enabled 1") + } throws: { $0 is CancellationError } + #expect(await harness.bluetooth.sentData.count == framesBeforeOldCommand) + _ = try await canonicalSettings.runCliCommand("set wifi.enabled 1") + #expect(stateB.rebootPending) + let afterWrite = stateB.revision + _ = try await harness.manager.connect(to: harness.deviceA.id, forceReconnect: true) + #expect(harness.manager.services?.settingsService.radioWiFiState === stateB) + #expect(stateB.rebootPending) + #expect(stateB.revision == afterWrite) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } + + @Test + func `config import continuation and a new queued send use canonical partition`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let services = try #require(harness.manager.services) + await harness.bluetooth.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + let contactKey = Data(repeating: 0xC1, count: ProtocolLimits.publicKeySize) + let config = MeshCoreNodeConfig( + privateKey: CanonicalIdentityFixture.privateKeyHex, + channels: [.init(name: "Canonical", secret: String(repeating: "CD", count: 16))], + contacts: [.init( + type: 1, name: "Canonical contact", publicKey: contactKey.hexString, + flags: 0, latitude: "0", longitude: "0", lastAdvert: 0, lastModified: 0 + )] + ) + try await services.nodeConfigService.importConfig( + config, sections: ConfigSections(nodeIdentity: true, channels: true, contacts: true), + radioID: harness.deviceA.radioID + ) + #expect(try await harness.manager.persistenceStore.fetchContacts(radioID: harness.deviceB.radioID) + .contains { $0.publicKey == contactKey }) + #expect(try await harness.manager.persistenceStore.fetchChannels(radioID: harness.deviceB.radioID) + .contains { $0.name == "Canonical" }) + let live = try #require(harness.manager.services) + let pending = try await live.messageService.createPendingChannelMessage( + text: "Canonical queue", channelIndex: 0, radioID: harness.deviceB.radioID + ) + await harness.bluetooth.holdNextSubmission() + try await live.chatSendQueueService.enqueueChannel(ChannelMessageEnvelope( + messageID: pending.id, channelIndex: 0, isResend: false, + messageText: pending.text, messageTimestamp: pending.timestamp, localNodeName: "Canonical radio" + )) + try await waitUntil("new canonical send should reach its physical gate") { + await harness.bluetooth.submissionIsHeld + } + let rowsB = try await harness.manager.persistenceStore.fetchPendingSends(radioID: harness.deviceB.radioID) + let rowsA = try await harness.manager.persistenceStore.fetchPendingSends(radioID: harness.deviceA.radioID) + #expect(rowsB.contains { $0.messageID == pending.id }) + #expect(!rowsA.contains { $0.messageID == pending.id }) + await harness.bluetooth.releaseSubmission() + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityDurabilityTests.swift b/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityDurabilityTests.swift new file mode 100644 index 0000000000..2e5b3f3902 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityDurabilityTests.swift @@ -0,0 +1,181 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Canonical identity durability") +@MainActor +struct CanonicalIdentityDurabilityTests { + @Test(arguments: [false, true]) + func `failed canonical save cannot leave staged partition or ghost deletion for a later save`( + pendingRxLog: Bool + ) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let source = try #require(harness.manager.services) + let stateA = source.settingsService.radioWiFiState + let stateB = harness.manager.radioWiFiState(for: harness.deviceB.radioID) + let entry = RxLogEntryDTO( + radioID: harness.deviceA.radioID, + from: ParsedRxLogData( + snr: 10, rssi: -65, rawPayload: Data([0x15]), routeType: .flood, + payloadType: .groupText, payloadVersion: 0, payloadTypeBits: 5, transportCode: nil, + pathLength: 0, pathNodes: [], packetPayload: Data([0xAB]) + ) + ) + if pendingRxLog { + harness.manager.testIdentityBeforeCommit = { + do { try await harness.manager.persistenceStore.saveRxLogEntry(entry) } catch { Issue.record(error) } + } + } + _ = try await source.settingsService.runCliCommand("set wifi.enabled 0") + await harness.bluetooth.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + await harness.manager.persistenceStore.setIdentityReconciliationFaultInjection { throw Failure.save } + await #expect(throws: (any Error).self) { + try await source.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + } + await harness.manager.persistenceStore.setIdentityReconciliationFaultInjection(nil) + harness.manager.testIdentityBeforeCommit = nil + #expect(harness.manager.services == nil) + #expect(stateA.rebootPending) + #expect(!stateB.rebootPending) + #expect(stateA.stableRevision() == nil) + if pendingRxLog { + #expect(await harness.manager.persistenceStore.unsavedRxLogInsertCount == 0) + #expect(try await harness.manager.persistenceStore.fetchRxLogEntries(radioID: harness.deviceA.radioID) + .contains { $0.id == entry.id }) + } + let a = try #require(try await harness.manager.persistenceStore.fetchDevice(id: harness.deviceA.id)) + #expect(a.radioID == harness.deviceA.radioID) + #expect(a.publicKey == harness.deviceA.publicKey) + #expect(try await harness.manager.persistenceStore.fetchDevice(radioID: harness.deviceB.radioID)?.radioID == harness.deviceB.radioID) + _ = try await source.messageService.createPendingChannelMessage( + text: "Later unrelated commit", channelIndex: 0, radioID: harness.deviceA.radioID + ) + #expect(try await harness.manager.persistenceStore.fetchDevice(id: harness.deviceA.id)?.radioID == harness.deviceA.radioID) + #expect(try await harness.manager.persistenceStore.fetchDevice(radioID: harness.deviceB.radioID) != nil) + #expect(harness.manager.pendingIdentityReconciliations[harness.deviceA.id]?.publicKey == CanonicalIdentityFixture.publicKey) + await harness.wifi.setDeviceID(harness.deviceB.id) + await harness.wifi.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceB.id) + _ = try await harness.manager.connectViaWiFi(host: "radio.local", port: 4242) + #expect(harness.manager.connectedDevice?.id == harness.deviceA.id) + #expect(harness.manager.connectedDevice?.radioID == harness.deviceB.radioID) + #expect(stateB.rebootPending) + #expect(stateB.stableRevision() != nil) + #expect(harness.manager.pendingIdentityReconciliations[harness.deviceA.id] == nil) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + if pendingRxLog { + #expect(try await harness.manager.persistenceStore.fetchRxLogEntries(radioID: harness.deviceA.radioID) + .contains { $0.id == entry.id }) + } + } + } + + @Test(arguments: [false, true], [false, true]) + func `accepted canonical effects finish after supersession without borrowing its identity`( + holdAfterCommit: Bool, sameRadio: Bool + ) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let source = try #require(harness.manager.services) + _ = try await source.settingsService.runCliCommand("set wifi.enabled 0") + let gate = Gate() + if holdAfterCommit { + harness.manager.testIdentityAfterCommit = { await gate.wait() } + } else { + harness.manager.testIdentityBeforeCommit = { await gate.wait() } + } + await harness.bluetooth.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + let importing = harness.track(Task { + try await source.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + }) + var successor: Task? + do { + try await waitUntil("accepted identity should reach its real store boundary") { gate.arrived } + let key = sameRadio ? CanonicalIdentityFixture.publicKey : Data(repeating: 0xC6, count: ProtocolLimits.publicKeySize) + await harness.wifi.setDeviceID(harness.deviceB.id) + await harness.wifi.setPublicKey(key, for: harness.deviceB.id) + let oldRequest = harness.manager.desiredRequest?.id + successor = harness.track(Task { try await harness.manager.connectViaWiFi(host: "radio.local", port: 4242) }) + try await waitUntil("successor request should supersede the captured importer") { + harness.manager.desiredRequest?.id != oldRequest + } + gate.open() + _ = await importing.result + _ = try await successor?.value + #expect(harness.manager.connectedDevice?.publicKey == key) + #expect((harness.manager.connectedDevice?.radioID == harness.deviceB.radioID) == sameRadio) + let canonicalResultWasAccepted = holdAfterCommit || sameRadio + #expect(harness.manager.radioWiFiState(for: harness.deviceB.radioID).rebootPending == canonicalResultWasAccepted) + #expect(harness.manager.services?.settingsService.radioWiFiState.rebootPending == sameRadio) + #expect(try await harness.manager.persistenceStore.fetchDevice(id: harness.deviceA.id)?.radioID + == (canonicalResultWasAccepted ? harness.deviceB.radioID : harness.deviceA.radioID)) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } catch { + gate.open() + _ = await importing.result + _ = await successor?.result + harness.manager.testIdentityBeforeCommit = nil + harness.manager.testIdentityAfterCommit = nil + throw error + } + harness.manager.testIdentityBeforeCommit = nil + harness.manager.testIdentityAfterCommit = nil + } + } + + @Test + func `identity import with no ghost preserves the current partition and child rows`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + await harness.bluetooth.setChannel(index: 0, name: "Current channel", secret: Data(repeating: 0xA1, count: 16)) + try await harness.connectBluetooth() + let source = try #require(harness.manager.services) + let history = try await source.messageService.createPendingChannelMessage( + text: "Retain current partition history", channelIndex: 0, radioID: harness.deviceA.radioID + ) + _ = try await source.settingsService.runCliCommand("set wifi.enabled 0") + let state = source.settingsService.radioWiFiState + await harness.bluetooth.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + try await source.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + #expect(harness.manager.connectedDevice?.radioID == harness.deviceA.radioID) + #expect(harness.manager.connectedDevice?.publicKey == CanonicalIdentityFixture.publicKey) + #expect(harness.manager.services?.settingsService.radioWiFiState === state) + #expect(state.rebootPending) + #expect(try await harness.manager.persistenceStore.fetchMessage(id: history.id)?.radioID == harness.deviceA.radioID) + #expect(try await harness.manager.persistenceStore.fetchDevice(id: harness.deviceB.id) != nil) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } + + private enum Failure: Error { case save } + + @MainActor + private final class Gate { + var arrived = false + private var opened = false + private var continuation: CheckedContinuation? + + func wait() async { + arrived = true + guard !opened else { return } + await withCheckedContinuation { continuation = $0 } + } + + func open() { + opened = true + continuation?.resume() + continuation = nil + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityEnqueueDrainTests.swift b/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityEnqueueDrainTests.swift new file mode 100644 index 0000000000..c48a917bfb --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityEnqueueDrainTests.swift @@ -0,0 +1,68 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Canonical identity enqueue drain") +@MainActor +struct CanonicalIdentityEnqueueDrainTests { + @Test + func `shutdown joins an enqueue already parked in actual persistence`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await harness.connectBluetooth() + let services = try #require(harness.manager.services) + let queue = services.chatSendQueueService + let pending = try await services.messageService.createPendingChannelMessage( + text: "Admitted before handoff", channelIndex: 0, radioID: harness.deviceA.radioID + ) + let gate = Gate() + await harness.manager.persistenceStore.setPendingSendInsertHandler { await gate.wait() } + let enqueuing = harness.track(Task { + try await queue.enqueueChannel(ChannelMessageEnvelope( + messageID: pending.id, channelIndex: 0, isResend: false, messageText: pending.text, + messageTimestamp: pending.timestamp, localNodeName: "Old radio" + )) + }) + var stopped = false + var stopping: Task? + do { + try await waitUntil("actual PendingSend insert should remain held") { await gate.arrived } + stopping = harness.track(Task { await queue.shutdown(); stopped = true }) + try await Task.sleep(for: .milliseconds(30)) + #expect(!stopped) + await gate.open() + _ = await enqueuing.result + await stopping?.value + #expect(stopped) + #expect(try await harness.manager.persistenceStore.fetchPendingSends(radioID: harness.deviceA.radioID) + .contains { $0.messageID == pending.id }) + #expect(await harness.bluetooth.sentData.contains { $0.first == CommandCode.sendChannelMessage.rawValue } == false) + } catch { + await gate.open() + _ = await enqueuing.result + await stopping?.value + await harness.manager.persistenceStore.setPendingSendInsertHandler(nil) + throw error + } + await harness.manager.persistenceStore.setPendingSendInsertHandler(nil) + } + } + + private actor Gate { + private(set) var arrived = false + private var opened = false + private var continuation: CheckedContinuation? + + func wait() async { + arrived = true + guard !opened else { return } + await withCheckedContinuation { continuation = $0 } + } + + func open() { + opened = true + continuation?.resume() + continuation = nil + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityProvenanceTests.swift b/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityProvenanceTests.swift new file mode 100644 index 0000000000..d3c2bb4f77 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityProvenanceTests.swift @@ -0,0 +1,157 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Canonical identity provenance") +@MainActor +struct CanonicalIdentityProvenanceTests { + @Test + func `accepted key without SelfInfo cannot merge a later foreign identity`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let old = try #require(harness.manager.services) + let stateA = old.settingsService.radioWiFiState + _ = try await old.settingsService.runCliCommand("set wifi.enabled 0") + await harness.bluetooth.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + await harness.bluetooth.holdReplies(for: .importPrivateKey) + let importing = harness.track(Task { + try await old.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + }) + try await waitUntil("private key should reach its held acknowledgement") { + await harness.bluetooth.sentData.contains { $0.first == CommandCode.importPrivateKey.rawValue } + } + await harness.bluetooth.setSendError(MeshTransportError.notConnected) + await harness.bluetooth.releaseReplies(for: .importPrivateKey) + await #expect(throws: (any Error).self) { try await importing.value } + let unresolved = try #require(harness.manager.pendingIdentityReconciliations[harness.deviceA.id]) + #expect(unresolved.publicKey == nil) + #expect(stateA.rebootPending) + #expect(stateA.stableRevision() == nil) + + let foreignKey = Data(repeating: 0xC3, count: ProtocolLimits.publicKeySize) + await harness.bluetooth.setSendError(nil) + await harness.bluetooth.setPublicKey(foreignKey, for: harness.deviceA.id) + await #expect(throws: ConnectionRequestFailure.self) { + _ = try await harness.manager.connect(to: harness.deviceA.id, forceReconnect: true) + } + #expect(harness.manager.services == nil) + #expect(harness.manager.connectedDevice == nil) + let unchangedA = try #require(try await harness.manager.persistenceStore.fetchDevice(id: harness.deviceA.id)) + #expect(unchangedA.publicKey == harness.deviceA.publicKey) + #expect(unchangedA.radioID == harness.deviceA.radioID) + #expect(try await harness.manager.persistenceStore.fetchDevice(radioID: harness.deviceB.radioID)?.radioID == harness.deviceB.radioID) + + await harness.wifi.setDeviceID(harness.deviceB.id) + await harness.wifi.setPublicKey(foreignKey, for: harness.deviceB.id) + _ = try await harness.manager.connectViaWiFi(host: "radio.local", port: 4242) + let foreign = try #require(harness.manager.connectedDevice) + #expect(foreign.publicKey == foreignKey) + #expect(foreign.radioID != harness.deviceA.radioID) + #expect(foreign.radioID != harness.deviceB.radioID) + #expect(harness.manager.services?.settingsService.radioWiFiState.rebootPending == false) + #expect(stateA.rebootPending) + #expect(harness.manager.pendingIdentityReconciliations[harness.deviceA.id]?.publicKey == nil) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } + + @Test + func `explicit rejected key does not create a pending identity merge`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await harness.connectBluetooth() + let old = try #require(harness.manager.services) + await harness.bluetooth.rejectNext(.importPrivateKey) + await #expect(throws: (any Error).self) { + try await old.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + } + #expect(harness.manager.pendingIdentityReconciliations[harness.deviceA.id] == nil) + _ = try await harness.manager.connect(to: harness.deviceA.id, forceReconnect: true) + #expect(harness.manager.connectedDevice?.publicKey == harness.deviceA.publicKey) + #expect(harness.manager.connectedDevice?.radioID == harness.deviceA.radioID) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } + + @Test + func `old public config reads and writes close before the private key acknowledgement`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let source = try #require(harness.manager.installedLink) + let old = source.services.nodeConfigService + await harness.bluetooth.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + await harness.bluetooth.holdReplies(for: .importPrivateKey) + let importing = harness.track(Task { + try await old.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + }) + try await waitUntil("private key should reach its held acknowledgement") { + await harness.bluetooth.sentData.contains { $0.first == CommandCode.importPrivateKey.rawValue } + } + let before = await harness.bluetooth.sentData.count + let config = MeshCoreNodeConfig(channels: [.init(name: "Stale", secret: String(repeating: "AB", count: 16))]) + await #expect(throws: CancellationError.self) { _ = try await old.exportConfig(sections: ConfigSections(channels: true)) } + await #expect(throws: CancellationError.self) { _ = try await old.previewImport(config, sections: ConfigSections(channels: true)) } + await #expect(throws: CancellationError.self) { + try await old.importConfig(config, sections: ConfigSections(channels: true), radioID: harness.deviceA.radioID) + } + await #expect(throws: CancellationError.self) { try await source.resource.session.reboot() } + #expect(await harness.bluetooth.sentData.count == before) + await harness.bluetooth.releaseReplies(for: .importPrivateKey) + try await importing.value + let fresh = try #require(harness.manager.services?.nodeConfigService) + await #expect(throws: CancellationError.self) { _ = try await old.exportConfig(sections: ConfigSections(channels: true)) } + try await fresh.importConfig(config, sections: ConfigSections(channels: true), radioID: harness.deviceB.radioID) + #expect(try await harness.manager.persistenceStore.fetchChannels(radioID: harness.deviceB.radioID).contains { $0.name == "Stale" }) + #expect(try await harness.manager.persistenceStore.fetchChannels(radioID: harness.deviceA.radioID).contains { $0.name == "Stale" } == false) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } + + @Test + func `a public export already reading the old session cannot issue its next command after handoff`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let source = try #require(harness.manager.installedLink) + var capabilities = Data([ResponseCode.deviceInfo.rawValue, 14, 1, 2]) + capabilities.append(Data(repeating: 0, count: 76)) + await harness.bluetooth.setResponsePackets(for: .deviceQuery, packets: [capabilities]) + await harness.bluetooth.holdReplies(for: .getChannel) + let readsBefore = await harness.bluetooth.sentData.filter { $0.first == CommandCode.getChannel.rawValue }.count + let exporting = harness.track(Task { + try await source.services.nodeConfigService.exportConfig(sections: ConfigSections(channels: true)) + }) + try await waitUntil("the old export should hold its first real channel reply") { + await harness.bluetooth.sentData.filter { $0.first == CommandCode.getChannel.rawValue }.count > readsBefore + } + await harness.bluetooth.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + let importing = harness.track(Task { + try await harness.manager.importIdentity( + CanonicalIdentityFixture.privateKey, + expectedServices: source.services, deviceID: harness.deviceA.id + ) + }) + try await waitUntil("handoff should close old service admission before the held read settles") { + await source.services.settingsService.radioWiFiOperationsRetired + } + await harness.bluetooth.releaseReplies(for: .getChannel) + await #expect(throws: CancellationError.self) { _ = try await exporting.value } + _ = try await importing.value + let frames = await harness.bluetooth.sentData + let keyIndex = try #require(frames.firstIndex { $0.first == CommandCode.importPrivateKey.rawValue }) + #expect(frames[..? + do { + try await waitUntil("actual queue attempt persistence should be held") { await gate.arrived } + let heldRows = try await store.fetchPendingSends(radioID: harness.deviceA.radioID) + #expect(heldRows.first { $0.messageID == pending.id }?.attemptCount == 0) + await harness.bluetooth.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + importing = harness.track(Task { + try await source.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + }) + try await waitUntil("identity import should close old queue admission") { queue.isRetiredForTesting } + try await Task.sleep(for: .milliseconds(30)) + #expect(await harness.bluetooth.sentData.contains { $0.first == CommandCode.importPrivateKey.rawValue } == false) + #expect(await gate.finished == false) + await gate.open() + try await importing?.value + await store.setPendingSendAttemptHandler(nil) + await queue.awaitDrainCompletion() + #expect(await gate.finished) + let rowsA = try await store.fetchPendingSends(radioID: harness.deviceA.radioID) + #expect(rowsA.first { $0.messageID == pending.id }?.attemptCount == 1) + let current = try #require(harness.manager.services) + #expect(harness.manager.connectedDevice?.radioID == harness.deviceB.radioID) + #expect(try await current.settingsService.getTime().timeIntervalSince1970 > 0) + let fresh = try await current.messageService.createPendingChannelMessage( + text: "Canonical queue is live", channelIndex: 0, radioID: harness.deviceB.radioID + ) + try await current.chatSendQueueService.enqueueChannel(envelope(fresh)) + try await waitUntil("fresh B queue should finish its actual send") { + let message = try? await store.fetchMessage(id: fresh.id) + let rows = await (try? store.fetchPendingSends(radioID: harness.deviceB.radioID)) ?? [] + return message?.status == .sent && !rows.contains { $0.messageID == fresh.id } + } + let frames = await harness.bluetooth.sentData + #expect(frames.contains { $0.range(of: Data(pending.text.utf8)) != nil } == false) + #expect(frames.contains { $0.range(of: Data(fresh.text.utf8)) != nil }) + } catch { + await gate.open() + await store.setPendingSendAttemptHandler(nil) + _ = await importing?.result + await queue.awaitDrainCompletion() + throw error + } + } + } + + private func envelope(_ message: MessageDTO) -> ChannelMessageEnvelope { + ChannelMessageEnvelope( + messageID: message.id, channelIndex: 0, isResend: false, messageText: message.text, + messageTimestamp: message.timestamp, localNodeName: "Queue drain radio" + ) + } + + private actor Gate { + private(set) var arrived = false + private(set) var finished = false + private var opened = false + private var continuation: CheckedContinuation? + + func wait() async { + arrived = true + if !opened { await withCheckedContinuation { continuation = $0 } } + finished = true + } + + func open() { + opened = true + continuation?.resume() + continuation = nil + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityReceiptAmbiguityTests.swift b/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityReceiptAmbiguityTests.swift new file mode 100644 index 0000000000..29f36f0e01 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/CanonicalIdentityReceiptAmbiguityTests.swift @@ -0,0 +1,57 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Canonical identity receipt ambiguity") +@MainActor +struct CanonicalIdentityReceiptAmbiguityTests { + @Test + func `two accepted failed imports of the same key do not choose an arbitrary WiFi source row`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + let keyD = Data(repeating: 0xD7, count: ProtocolLimits.publicKeySize) + let radioD = DeviceDTO.testDevice(radioID: UUID(), publicKey: keyD, firmwareVersion: 14).copy { + $0.connectionMethods = [.bluetooth(peripheralUUID: $0.id, displayName: nil)] + } + try await harness.manager.persistenceStore.saveDevice(radioD) + await harness.bluetooth.setPublicKey(keyD, for: radioD.id) + await harness.manager.persistenceStore.setIdentityReconciliationFaultInjection { throw Failure.save } + for device in [harness.deviceA, radioD] { + _ = try await harness.manager.connect(to: device.id, forceReconnect: true) + let services = try #require(harness.manager.services) + _ = try await services.settingsService.runCliCommand("set wifi.enabled 0") + await harness.bluetooth.setPublicKey(CanonicalIdentityFixture.publicKey, for: device.id) + await #expect(throws: (any Error).self) { + try await services.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: device.radioID + ) + } + #expect(harness.manager.pendingIdentityReconciliations[device.id]?.publicKey == CanonicalIdentityFixture.publicKey) + } + await harness.manager.persistenceStore.setIdentityReconciliationFaultInjection(nil) + #expect(harness.manager.pendingIdentityReconciliations.count == 2) + await harness.wifi.setDeviceID(harness.deviceB.id) + await harness.wifi.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceB.id) + await #expect(throws: ConnectionRequestFailure.self) { + _ = try await harness.manager.connectViaWiFi(host: "radio.local", port: 4242) + } + #expect(harness.manager.services == nil) + #expect(try await harness.manager.persistenceStore.fetchDevice(id: harness.deviceA.id)?.radioID == harness.deviceA.radioID) + #expect(try await harness.manager.persistenceStore.fetchDevice(id: radioD.id)?.radioID == radioD.radioID) + #expect(try await harness.manager.persistenceStore.fetchDevice(radioID: harness.deviceB.radioID)?.isActive == false) + #expect(harness.manager.pendingIdentityReconciliations.count == 2) + #expect(!harness.manager.radioWiFiState(for: harness.deviceB.radioID).rebootPending) + + _ = try await harness.manager.connect(to: harness.deviceA.id, forceReconnect: true) + #expect(harness.manager.connectedDevice?.id == harness.deviceA.id) + #expect(harness.manager.connectedDevice?.radioID == harness.deviceB.radioID) + #expect(harness.manager.pendingIdentityReconciliations[harness.deviceA.id] == nil) + #expect(harness.manager.pendingIdentityReconciliations[radioD.id]?.publicKey == CanonicalIdentityFixture.publicKey) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } + + private enum Failure: Error { case save } +} diff --git a/MC1Services/Tests/MC1ServicesTests/CanonicalIdentitySettlementTests.swift b/MC1Services/Tests/MC1ServicesTests/CanonicalIdentitySettlementTests.swift new file mode 100644 index 0000000000..c93a2c45d2 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/CanonicalIdentitySettlementTests.swift @@ -0,0 +1,98 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Canonical identity captured settlement") +@MainActor +struct CanonicalIdentitySettlementTests { + @Test(arguments: [false, true], Outcome.allCases) + func `actual held mutation settles its captured sink before canonical admission opens`( + canonicalSink: Bool, outcome: Outcome + ) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let source = try #require(harness.manager.services) + let sourceContext = source.settingsService.radioWiFiContextID + let canonical = harness.manager.radioWiFiState(for: harness.deviceB.radioID) + let otherWire = ConnectionTestRadioTransport() + let otherSession = MeshCoreSession(transport: otherWire) + try await otherSession.start() + let otherSettings = SettingsService(session: otherSession, radioWiFiState: canonical) + let settings = canonicalSink ? otherSettings : source.settingsService + let wire = canonicalSink ? otherWire : harness.bluetooth + let captured = settings.radioWiFiBinding + let command = "set wifi.enabled 0" + await wire.setCLIResponse(command, response: outcome.reply) + await wire.holdReplies(for: .runCliCommand) + let mutating = harness.track(Task { try await settings.runCliCommand(command) }) + var importing: Task? + var imported = false + do { + try await waitUntil("actual WiFi mutation should hold its firmware reply") { + await wire.cliCommands.contains(command) + } + mutating.cancel() + if canonicalSink { + _ = harness.track(Task { await otherSettings.retireRadioWiFiOperations() }) + } + await harness.bluetooth.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + importing = harness.track(Task { + try await source.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + imported = true + }) + if canonicalSink { + try await waitUntil("canonical transfer should reach the accepted identity observation") { + harness.manager.pendingIdentityReconciliations[harness.deviceA.id]?.publicKey == CanonicalIdentityFixture.publicKey + } + try await Task.sleep(for: .milliseconds(30)) + #expect(!imported) + #expect(canonical.stableRevision() == nil) + } + await wire.releaseReplies(for: .runCliCommand) + _ = try await mutating.value + try await importing?.value + #expect(captured.state.rebootPending == outcome.pending) + #expect(canonical.rebootPending == outcome.pending) + let canonicalSettings = try #require(harness.manager.services?.settingsService) + #expect(canonicalSettings !== source.settingsService) + #expect(canonicalSettings.radioWiFiBinding.contextID != sourceContext) + #expect(canonicalSettings.radioWiFiState === canonical) + #expect(source.settingsService.radioWiFiBinding.contextID == sourceContext) + if !canonicalSink { #expect(source.settingsService.radioWiFiState === captured.state) } + #expect(canonical.stableRevision() != nil) + #expect(try await canonicalSettings.getTime().timeIntervalSince1970 > 0) + } catch { + await wire.releaseReplies(for: .runCliCommand) + _ = await mutating.result + _ = await importing?.result + await otherSettings.retireRadioWiFiOperations() + await otherSession.stop() + await otherSession.waitForQuiescence() + throw error + } + await otherSettings.retireRadioWiFiOperations() + await otherSession.stop() + await otherSession.waitForQuiescence() + } + } + + enum Outcome: CaseIterable, Sendable { + case accepted, rejected, uncertain + var pending: Bool { + self != .rejected + } + + var reply: String { + switch self { + case .accepted: "OK" + case .rejected: "Error: invalid value" + case .uncertain: "ambiguous reply" + } + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/CanonicalWiFiCertificateTests.swift b/MC1Services/Tests/MC1ServicesTests/CanonicalWiFiCertificateTests.swift new file mode 100644 index 0000000000..4758c1a3ef --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/CanonicalWiFiCertificateTests.swift @@ -0,0 +1,65 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Canonical WiFi certificates") +@MainActor +struct CanonicalWiFiCertificateTests { + @Test + func `equal revision counters cannot preserve old probe or credential authority`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let services = try #require(harness.manager.services) + let settings = services.settingsService + await harness.bluetooth.setCLIResponse("get wifi.ssid", response: "> synthetic-network") + await harness.bluetooth.setCLIResponse("get wifi.pwd", response: "> synthetic-password") + _ = try await settings.runCliCommand("set wifi.enabled 0") + let stateB = harness.manager.radioWiFiState(for: harness.deviceB.radioID) + let rejected = try #require(stateB.beginMutation(expectedRevision: nil)) + stateB.settle(rejected, outcome: .rejected) + #expect(stateB.revision == settings.radioWiFiState.revision) + guard case let .supported(probe) = try await settings.probeRadioWiFiSettings() else { + Issue.record("Expected supported WiFi fixture") + return + } + let editorID = UUID() + let baseline = try #require(try await settings.readRadioWiFiCredentials(editorID: editorID)) + await harness.bluetooth.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + try await services.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + let canonicalSettings = try #require(harness.manager.services?.settingsService) + #expect(canonicalSettings !== settings) + #expect(await settings.readRadioWiFiObservation(probe: probe) == nil) + #expect(await canonicalSettings.readRadioWiFiObservation(probe: probe) == nil) + let commandsBefore = await harness.bluetooth.cliCommands.count + for target in [settings, canonicalSettings] { + var rejectedOldCertificate = false + do { + _ = try await target.saveRadioWiFiCredentials( + ssid: "fresh-network", password: "fresh-password", baseline: baseline, + editorID: editorID, ownerIsCurrent: { harness.manager.services?.settingsService === target } + ) + } catch is CancellationError { + rejectedOldCertificate = true + } + #expect(rejectedOldCertificate) + } + #expect(await harness.bluetooth.cliCommands.count == commandsBefore) + let freshEditor = UUID() + let fresh = try #require(try await canonicalSettings.readRadioWiFiCredentials(editorID: freshEditor)) + #expect(fresh.radioID == harness.deviceB.radioID) + let receipt = try await canonicalSettings.saveRadioWiFiCredentials( + ssid: "fresh-network", password: "fresh-password", baseline: fresh, + editorID: freshEditor, ownerIsCurrent: { harness.manager.services?.settingsService === canonicalSettings } + ) + #expect(receipt.ssidAccepted && receipt.passwordAccepted) + #expect(!receipt.uncertain) + #expect(stateB.rebootPending) + #expect(try await canonicalSettings.getTime() > .distantPast) + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ChannelFloodScopeResolverTests.swift b/MC1Services/Tests/MC1ServicesTests/ChannelFloodScopeResolverTests.swift deleted file mode 100644 index e890d70318..0000000000 --- a/MC1Services/Tests/MC1ServicesTests/ChannelFloodScopeResolverTests.swift +++ /dev/null @@ -1,85 +0,0 @@ -import Foundation -@testable import MC1Services -import MeshCore -import Testing - -@Suite("ChannelFloodScopeResolver") -struct ChannelFloodScopeResolverTests { - @Test - func `.inherit with device default set resolves to .scope(.region(default))`() { - let resolved = ChannelFloodScopeResolver.resolve( - channelFloodScope: .inherit, - deviceDefaultFloodScopeName: "Germany", - supportsUnscopedFloodSend: true - ) - #expect(resolved == .scope(.region("Germany"))) - } - - @Test - func `.inherit with no device default resolves to .scope(.disabled)`() { - let resolved = ChannelFloodScopeResolver.resolve( - channelFloodScope: .inherit, - deviceDefaultFloodScopeName: nil, - supportsUnscopedFloodSend: true - ) - #expect(resolved == .scope(.disabled)) - } - - @Test - func `.inherit with empty-string default treats it as no default`() { - let resolved = ChannelFloodScopeResolver.resolve( - channelFloodScope: .inherit, - deviceDefaultFloodScopeName: "", - supportsUnscopedFloodSend: true - ) - #expect(resolved == .scope(.disabled)) - } - - @Test - func `.allRegions on firmware v12+ resolves to .unscoped (true override)`() { - let withDefault = ChannelFloodScopeResolver.resolve( - channelFloodScope: .allRegions, - deviceDefaultFloodScopeName: "Germany", - supportsUnscopedFloodSend: true - ) - let withoutDefault = ChannelFloodScopeResolver.resolve( - channelFloodScope: .allRegions, - deviceDefaultFloodScopeName: nil, - supportsUnscopedFloodSend: true - ) - #expect(withDefault == .unscoped) - #expect(withoutDefault == .unscoped) - } - - @Test - func `.allRegions on older firmware falls back to .scope(.disabled)`() { - let withDefault = ChannelFloodScopeResolver.resolve( - channelFloodScope: .allRegions, - deviceDefaultFloodScopeName: "Germany", - supportsUnscopedFloodSend: false - ) - let withoutDefault = ChannelFloodScopeResolver.resolve( - channelFloodScope: .allRegions, - deviceDefaultFloodScopeName: nil, - supportsUnscopedFloodSend: false - ) - #expect(withDefault == .scope(.disabled)) - #expect(withoutDefault == .scope(.disabled)) - } - - @Test - func `.region(name) resolves to that region regardless of default or capability`() { - let withDefault = ChannelFloodScopeResolver.resolve( - channelFloodScope: .region("France"), - deviceDefaultFloodScopeName: "Germany", - supportsUnscopedFloodSend: true - ) - let withoutCapability = ChannelFloodScopeResolver.resolve( - channelFloodScope: .region("France"), - deviceDefaultFloodScopeName: nil, - supportsUnscopedFloodSend: false - ) - #expect(withDefault == .scope(.region("France"))) - #expect(withoutCapability == .scope(.region("France"))) - } -} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectRadioIDResolutionTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectRadioIDResolutionTests.swift index f085ee8752..c60b52a5e7 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectRadioIDResolutionTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectRadioIDResolutionTests.swift @@ -1,155 +1,118 @@ import Foundation @testable import MC1Services import MeshCore -import MeshCoreTestSupport -import SwiftData import Testing -/// Reconnecting the same radio over a fresh CoreBluetooth handle must not -/// re-partition its data. `buildServicesAndSaveDevice` resolves the radioID by -/// missing on `fetchDevice(id:)` (the volatile BLE UUID changed) and falling -/// back to `fetchDevice(publicKey:)`, so every per-radio row persisted under the -/// first connection stays reachable. Losing that fallback would mint a fresh -/// radioID and orphan the radio's `PendingSend` rows. +/// Connection entry points must preserve the radio partition across volatile handle changes. @Suite("Connect-path radioID resolution") @MainActor struct ConnectRadioIDResolutionTests { private static let radioPublicKey = Data(repeating: 0xC3, count: 32) - private static let testCapabilities = DeviceCapabilities( - firmwareVersion: 9, - maxContacts: 100, - maxChannels: 8, - blePin: 0, - firmwareBuild: "01 Jan 2025", - model: "T-Deck", - version: "v1.13.0" - ) - - private static func makeSelfInfo(publicKey: Data = radioPublicKey) -> SelfInfo { - SelfInfo( - advertisementType: 0, - txPower: 20, - maxTxPower: 20, - publicKey: publicKey, - latitude: 0, - longitude: 0, - multiAcks: 2, - advertisementLocationPolicy: 0, - telemetryModeEnvironment: 0, - telemetryModeLocation: 0, - telemetryModeBase: 2, - manualAddContacts: false, - radioFrequency: 915.0, - radioBandwidth: 250.0, - radioSpreadingFactor: 10, - radioCodingRate: 5, - name: "TestNode" - ) - } - - /// A never-connected session so the up-front `getAutoAddConfig` roundtrip - /// fails fast with `.notConnected`; the ceremony swallows it and proceeds. - private func makeOfflineSession() -> MeshCoreSession { - MeshCoreSession( - transport: SimulatorMockTransport(), - configuration: SessionConfiguration(defaultTimeout: 0.5, clientIdentifier: "RadioIDResolutionTest") - ) + private func withManager( + publicKey: Data = ConnectRadioIDResolutionTests.radioPublicKey, + _ operation: @MainActor (ConnectionManager, ConnectionTestRadioTransport) async throws -> Void + ) async throws { + let environment = try ConnectionManagerRadioTestHarness(publicKey: publicKey) + do { try await operation(environment.manager, environment.ble) } catch { + await environment.close() + throw error + } + await environment.close() } @Test func `Reconnect with a changed BLE id but same publicKey resolves the original radioID and keeps its PendingSends reachable`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - - // First connect: fresh pairing mints a radioID for this publicKey. - let firstBLEID = UUID() - let firstConnect = try await manager.buildServicesAndSaveDevice( - deviceID: firstBLEID, - session: makeOfflineSession(), - selfInfo: Self.makeSelfInfo(), - capabilities: Self.testCapabilities - ) - let originalRadioID = firstConnect.radioID - - // The second connect hydrates the chat send queue, whose DM drain - // terminally deletes any envelope missing its Contact row ("contact - // deleted") or its Message row (sendFailed). A complete fixture — the - // same Contact + Message + PendingSend triple a real enqueue leaves on - // disk — makes the offline session's failure transient instead, so the - // drain parks and the row deterministically survives to the assertion - // below. - let contactID = UUID() - let contact = ContactDTO( - id: contactID, - radioID: originalRadioID, - publicKey: Data((0.. UUID { - let connected = try await manager.buildServicesAndSaveDevice( - deviceID: deviceID, - session: makeOfflineSession(), - selfInfo: Self.makeSelfInfo(publicKey: publicKey), - capabilities: Self.testCapabilities, - connectionMethods: methods - ) - return connected.radioID + let connected = try await saveConnection(manager: manager, deviceID: deviceID, methods: methods) + #expect(connected.device.publicKey == publicKey) + return connected.device.radioID + } + + private func saveConnection( + manager: ConnectionManager, deviceID: UUID, methods: [ConnectionMethod] + ) async throws -> ConnectionSnapshot { + var result: ConnectionResult? + for method in methods.isEmpty ? [wifiMethod] : methods { + switch method { + case let .bluetooth(peripheralUUID, _): + result = try await manager.connect(to: peripheralUUID, forceFullSync: true, forceReconnect: true) + case let .wifi(host, port, _): + result = try await manager.connectViaWiFi(host: host, port: port, forceFullSync: true) + } + } + guard case let .operational(snapshot) = result else { + throw ConnectionError.notConnected + } + #expect(snapshot.device.id == deviceID) + return snapshot } @Test func `wifi save keeps a bluetooth row id and radioID`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let publicKey = Data(repeating: 0x11, count: 32) - let peripheralID = UUID() - let radioID = try await save( - manager: manager, - deviceID: peripheralID, - publicKey: publicKey, - methods: [.bluetooth(peripheralUUID: peripheralID, displayName: nil)] - ) - - let wifiID = await manager.wifiDeviceID(publicKey: publicKey) - #expect(wifiID == peripheralID) - let savedRadioID = try await save( - manager: manager, - deviceID: wifiID, - publicKey: publicKey, - methods: [wifiMethod] - ) - - let rows = try await manager.persistenceStore.fetchDevices() - #expect(rows.map(\.id) == [peripheralID]) - #expect(savedRadioID == radioID) - #expect(rows.first?.radioID == radioID) - #expect(rows.first?.connectionMethods == [ - .bluetooth(peripheralUUID: peripheralID, displayName: nil), - wifiMethod - ]) - #expect(try await manager.persistenceStore.fetchDevice(id: DeviceIdentity.deriveUUID(from: publicKey)) == nil) + try await withManager(publicKey: Data(repeating: 0x11, count: 32)) { manager, _ in + let publicKey = Data(repeating: 0x11, count: 32) + let peripheralID = UUID() + let radioID = try await save( + manager: manager, + deviceID: peripheralID, + publicKey: publicKey, + methods: [.bluetooth(peripheralUUID: peripheralID, displayName: nil)] + ) + + let wifiID = await manager.wifiDeviceID(publicKey: publicKey) + #expect(wifiID == peripheralID) + let savedRadioID = try await save( + manager: manager, + deviceID: wifiID, + publicKey: publicKey, + methods: [wifiMethod] + ) + + let rows = try await manager.persistenceStore.fetchDevices() + #expect(rows.map(\.id) == [peripheralID]) + #expect(savedRadioID == radioID) + #expect(rows.first?.radioID == radioID) + #expect(rows.first?.connectionMethods == [ + .bluetooth(peripheralUUID: peripheralID, displayName: nil), + wifiMethod + ]) + #expect(try await manager.persistenceStore.fetchDevice(id: DeviceIdentity.deriveUUID(from: publicKey)) == nil) + } } @Test func `bluetooth save then wifi reconnect save keeps one row at the peripheral id`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let publicKey = Data(repeating: 0x22, count: 32) - let peripheralID = UUID() - _ = try await save( - manager: manager, - deviceID: peripheralID, - publicKey: publicKey, - methods: [.bluetooth(peripheralUUID: peripheralID, displayName: nil)] - ) - - let wifiID = await manager.wifiDeviceID(publicKey: publicKey) - _ = try await save(manager: manager, deviceID: wifiID, publicKey: publicKey, methods: []) - - let rows = try await manager.persistenceStore.fetchDevices() - #expect(rows.map(\.id) == [peripheralID]) - #expect(try await manager.persistenceStore.fetchDevice(id: peripheralID) != nil) + try await withManager(publicKey: Data(repeating: 0x22, count: 32)) { manager, _ in + let publicKey = Data(repeating: 0x22, count: 32) + let peripheralID = UUID() + _ = try await save( + manager: manager, + deviceID: peripheralID, + publicKey: publicKey, + methods: [.bluetooth(peripheralUUID: peripheralID, displayName: nil)] + ) + + let wifiID = await manager.wifiDeviceID(publicKey: publicKey) + _ = try await save(manager: manager, deviceID: wifiID, publicKey: publicKey, methods: []) + + let rows = try await manager.persistenceStore.fetchDevices() + #expect(rows.map(\.id) == [peripheralID]) + #expect(try await manager.persistenceStore.fetchDevice(id: peripheralID) != nil) + } } @Test func `wifi reconnect save then bluetooth save keeps one row at the peripheral id`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let publicKey = Data(repeating: 0x33, count: 32) - let derivedID = await manager.wifiDeviceID(publicKey: publicKey) - #expect(derivedID == DeviceIdentity.deriveUUID(from: publicKey)) - let radioID = try await save(manager: manager, deviceID: derivedID, publicKey: publicKey, methods: []) - - let peripheralID = UUID() - let savedRadioID = try await save( - manager: manager, - deviceID: peripheralID, - publicKey: publicKey, - methods: [.bluetooth(peripheralUUID: peripheralID, displayName: nil)] - ) - - let rows = try await manager.persistenceStore.fetchDevices() - #expect(rows.map(\.id) == [peripheralID]) - #expect(savedRadioID == radioID) + try await withManager(publicKey: Data(repeating: 0x33, count: 32)) { manager, _ in + let publicKey = Data(repeating: 0x33, count: 32) + let derivedID = await manager.wifiDeviceID(publicKey: publicKey) + #expect(derivedID == DeviceIdentity.deriveUUID(from: publicKey)) + let radioID = try await save(manager: manager, deviceID: derivedID, publicKey: publicKey, methods: []) + + let peripheralID = UUID() + let savedRadioID = try await save( + manager: manager, + deviceID: peripheralID, + publicKey: publicKey, + methods: [.bluetooth(peripheralUUID: peripheralID, displayName: nil)] + ) + + let rows = try await manager.persistenceStore.fetchDevices() + #expect(rows.map(\.id) == [peripheralID]) + #expect(savedRadioID == radioID) + } } @Test func `wifi save with no row uses the derived id`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let publicKey = Data(repeating: 0x44, count: 32) - let derivedID = DeviceIdentity.deriveUUID(from: publicKey) - #expect(await manager.wifiDeviceID(publicKey: publicKey) == derivedID) + try await withManager(publicKey: Data(repeating: 0x44, count: 32)) { manager, _ in + let publicKey = Data(repeating: 0x44, count: 32) + let derivedID = DeviceIdentity.deriveUUID(from: publicKey) + #expect(await manager.wifiDeviceID(publicKey: publicKey) == derivedID) - _ = try await save(manager: manager, deviceID: derivedID, publicKey: publicKey, methods: [wifiMethod]) + _ = try await save(manager: manager, deviceID: derivedID, publicKey: publicKey, methods: [wifiMethod]) - let rows = try await manager.persistenceStore.fetchDevices() - #expect(rows.map(\.id) == [derivedID]) + let rows = try await manager.persistenceStore.fetchDevices() + #expect(rows.map(\.id) == [derivedID]) + } } @Test func `wifi save keeps a wifi-only row id`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let publicKey = Data(repeating: 0x55, count: 32) - let derivedID = DeviceIdentity.deriveUUID(from: publicKey) - let radioID = try await save( - manager: manager, - deviceID: derivedID, - publicKey: publicKey, - methods: [wifiMethod] - ) - - let wifiID = await manager.wifiDeviceID(publicKey: publicKey) - #expect(wifiID == derivedID) - let savedRadioID = try await save( - manager: manager, - deviceID: wifiID, - publicKey: publicKey, - methods: [wifiMethod] - ) - - let rows = try await manager.persistenceStore.fetchDevices() - #expect(rows.map(\.id) == [derivedID]) - #expect(savedRadioID == radioID) + try await withManager(publicKey: Data(repeating: 0x55, count: 32)) { manager, _ in + let publicKey = Data(repeating: 0x55, count: 32) + let derivedID = DeviceIdentity.deriveUUID(from: publicKey) + let radioID = try await save( + manager: manager, + deviceID: derivedID, + publicKey: publicKey, + methods: [wifiMethod] + ) + + let wifiID = await manager.wifiDeviceID(publicKey: publicKey) + #expect(wifiID == derivedID) + let savedRadioID = try await save( + manager: manager, + deviceID: wifiID, + publicKey: publicKey, + methods: [wifiMethod] + ) + + let rows = try await manager.persistenceStore.fetchDevices() + #expect(rows.map(\.id) == [derivedID]) + #expect(savedRadioID == radioID) + } } @Test func `wifi save after bluetooth removal keeps the peripheral id`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let publicKey = Data(repeating: 0x66, count: 32) - let peripheralID = UUID() - let radioID = try await save( - manager: manager, - deviceID: peripheralID, - publicKey: publicKey, - methods: [ - .bluetooth(peripheralUUID: peripheralID, displayName: nil), - wifiMethod - ] - ) - let stripped = try await manager.persistenceStore.removeBluetoothMethod(peripheralID: peripheralID) - #expect(stripped?.id == peripheralID) - - let wifiID = await manager.wifiDeviceID(publicKey: publicKey) - #expect(wifiID == peripheralID) - let savedRadioID = try await save( - manager: manager, - deviceID: wifiID, - publicKey: publicKey, - methods: [wifiMethod] - ) - - let rows = try await manager.persistenceStore.fetchDevices() - #expect(rows.map(\.id) == [peripheralID]) - #expect(savedRadioID == radioID) - #expect(try await manager.persistenceStore.fetchDevice(id: DeviceIdentity.deriveUUID(from: publicKey)) == nil) + try await withManager(publicKey: Data(repeating: 0x66, count: 32)) { manager, _ in + let publicKey = Data(repeating: 0x66, count: 32) + let peripheralID = UUID() + let radioID = try await save( + manager: manager, + deviceID: peripheralID, + publicKey: publicKey, + methods: [ + .bluetooth(peripheralUUID: peripheralID, displayName: nil), + wifiMethod + ] + ) + let stripped = try await manager.persistenceStore.removeBluetoothMethod(peripheralID: peripheralID) + #expect(stripped?.id == peripheralID) + + let wifiID = await manager.wifiDeviceID(publicKey: publicKey) + #expect(wifiID == peripheralID) + let savedRadioID = try await save( + manager: manager, + deviceID: wifiID, + publicKey: publicKey, + methods: [wifiMethod] + ) + + let rows = try await manager.persistenceStore.fetchDevices() + #expect(rows.map(\.id) == [peripheralID]) + #expect(savedRadioID == radioID) + #expect(try await manager.persistenceStore.fetchDevice(id: DeviceIdentity.deriveUUID(from: publicKey)) == nil) + } } @Test func `wifi save re-keys a legacy derived row that still has bluetooth`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let publicKey = Data(repeating: 0x77, count: 32) - let peripheralID = UUID() - let derivedID = UUID() - #expect(derivedID != peripheralID) - let legacy = DeviceDTO.testDevice(id: derivedID, publicKey: publicKey).copy { - $0.connectionMethods = [ - .bluetooth(peripheralUUID: peripheralID, displayName: nil), - wifiMethod - ] + try await withManager(publicKey: Data(repeating: 0x77, count: 32)) { manager, _ in + let publicKey = Data(repeating: 0x77, count: 32) + let peripheralID = UUID() + let derivedID = UUID() + #expect(derivedID != peripheralID) + let legacy = DeviceDTO.testDevice(id: derivedID, publicKey: publicKey).copy { + $0.connectionMethods = [ + .bluetooth(peripheralUUID: peripheralID, displayName: nil), + wifiMethod + ] + } + try await manager.persistenceStore.saveDevice(legacy) + + let wifiID = await manager.wifiDeviceID(publicKey: publicKey) + #expect(wifiID == peripheralID) + let savedRadioID = try await save( + manager: manager, + deviceID: wifiID, + publicKey: publicKey, + methods: [wifiMethod] + ) + + let rows = try await manager.persistenceStore.fetchDevices() + #expect(rows.map(\.id) == [peripheralID]) + #expect(savedRadioID == legacy.radioID) + #expect(try await manager.persistenceStore.fetchDevice(id: derivedID) == nil) } - try await manager.persistenceStore.saveDevice(legacy) - - let wifiID = await manager.wifiDeviceID(publicKey: publicKey) - #expect(wifiID == peripheralID) - let savedRadioID = try await save( - manager: manager, - deviceID: wifiID, - publicKey: publicKey, - methods: [wifiMethod] - ) - - let rows = try await manager.persistenceStore.fetchDevices() - #expect(rows.map(\.id) == [peripheralID]) - #expect(savedRadioID == legacy.radioID) - #expect(try await manager.persistenceStore.fetchDevice(id: derivedID) == nil) } @Test func `wifi save keeps a backup shadow id`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let publicKey = Data(repeating: 0x88, count: 32) - let shadowID = UUID() - let shadow = DeviceDTO.testDevice(id: shadowID, publicKey: publicKey).copy { - $0.connectionMethods = [wifiMethod] + try await withManager(publicKey: Data(repeating: 0x88, count: 32)) { manager, _ in + let publicKey = Data(repeating: 0x88, count: 32) + let shadowID = UUID() + let shadow = DeviceDTO.testDevice(id: shadowID, publicKey: publicKey).copy { + $0.connectionMethods = [wifiMethod] + } + try await manager.persistenceStore.saveDevice(shadow) + + let wifiID = await manager.wifiDeviceID(publicKey: publicKey) + #expect(wifiID == shadowID) + let savedRadioID = try await save( + manager: manager, + deviceID: wifiID, + publicKey: publicKey, + methods: [wifiMethod] + ) + + let rows = try await manager.persistenceStore.fetchDevices() + #expect(rows.map(\.id) == [shadowID]) + #expect(savedRadioID == shadow.radioID) } - try await manager.persistenceStore.saveDevice(shadow) - - let wifiID = await manager.wifiDeviceID(publicKey: publicKey) - #expect(wifiID == shadowID) - let savedRadioID = try await save( - manager: manager, - deviceID: wifiID, - publicKey: publicKey, - methods: [wifiMethod] - ) - - let rows = try await manager.persistenceStore.fetchDevices() - #expect(rows.map(\.id) == [shadowID]) - #expect(savedRadioID == shadow.radioID) } @Test func `wifi save keeps a ghost id`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let publicKey = Data(repeating: 0x99, count: 32) - let ghostID = UUID() - let ghost = DeviceDTO.testDevice(id: ghostID, publicKey: publicKey, isActive: false) - try await manager.persistenceStore.saveDevice(ghost) - - let wifiID = await manager.wifiDeviceID(publicKey: publicKey) - #expect(wifiID == ghostID) - let savedRadioID = try await save( - manager: manager, - deviceID: wifiID, - publicKey: publicKey, - methods: [wifiMethod] - ) - - let rows = try await manager.persistenceStore.fetchDevices() - #expect(rows.map(\.id) == [ghostID]) - #expect(savedRadioID == ghost.radioID) + try await withManager(publicKey: Data(repeating: 0x99, count: 32)) { manager, _ in + let publicKey = Data(repeating: 0x99, count: 32) + let ghostID = UUID() + let ghost = DeviceDTO.testDevice(id: ghostID, publicKey: publicKey, isActive: false) + try await manager.persistenceStore.saveDevice(ghost) + + let wifiID = await manager.wifiDeviceID(publicKey: publicKey) + #expect(wifiID == ghostID) + let savedRadioID = try await save( + manager: manager, + deviceID: wifiID, + publicKey: publicKey, + methods: [wifiMethod] + ) + + let rows = try await manager.persistenceStore.fetchDevices() + #expect(rows.map(\.id) == [ghostID]) + #expect(savedRadioID == ghost.radioID) + } } @Test func `bluetooth save after a wifi-only row re-keys to the peripheral`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let publicKey = Data(repeating: 0xAA, count: 32) - let derivedID = DeviceIdentity.deriveUUID(from: publicKey) - let radioID = try await save( - manager: manager, - deviceID: derivedID, - publicKey: publicKey, - methods: [wifiMethod] - ) - - let peripheralID = UUID() - let savedRadioID = try await save( - manager: manager, - deviceID: peripheralID, - publicKey: publicKey, - methods: [.bluetooth(peripheralUUID: peripheralID, displayName: nil)] - ) - - let rows = try await manager.persistenceStore.fetchDevices() - #expect(rows.count == 1) - #expect(rows.first?.id == peripheralID) - #expect(savedRadioID == radioID) - #expect(rows.first?.connectionMethods == [ - wifiMethod, - .bluetooth(peripheralUUID: peripheralID, displayName: nil) - ]) + try await withManager(publicKey: Data(repeating: 0xAA, count: 32)) { manager, _ in + let publicKey = Data(repeating: 0xAA, count: 32) + let derivedID = DeviceIdentity.deriveUUID(from: publicKey) + let radioID = try await save( + manager: manager, + deviceID: derivedID, + publicKey: publicKey, + methods: [wifiMethod] + ) + + let peripheralID = UUID() + let savedRadioID = try await save( + manager: manager, + deviceID: peripheralID, + publicKey: publicKey, + methods: [.bluetooth(peripheralUUID: peripheralID, displayName: nil)] + ) + + let rows = try await manager.persistenceStore.fetchDevices() + #expect(rows.count == 1) + #expect(rows.first?.id == peripheralID) + #expect(savedRadioID == radioID) + #expect(rows.first?.connectionMethods == [ + wifiMethod, + .bluetooth(peripheralUUID: peripheralID, displayName: nil) + ]) + } } @Test func `wifiDeviceID prefers a bluetooth row over a newer ghost with the same key`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let publicKey = Data(repeating: 0xBB, count: 32) - let peripheralID = UUID() - let ghost = DeviceDTO.testDevice( - id: UUID(), - publicKey: publicKey, - lastConnected: Date(), - isActive: false - ) - let bluetooth = DeviceDTO.testDevice( - id: peripheralID, - publicKey: publicKey, - lastConnected: Date().addingTimeInterval(-3600), - isActive: false - ).copy { - $0.connectionMethods = [.bluetooth(peripheralUUID: peripheralID, displayName: nil)] + try await withManager(publicKey: Data(repeating: 0xBB, count: 32)) { manager, _ in + let publicKey = Data(repeating: 0xBB, count: 32) + let peripheralID = UUID() + let ghost = DeviceDTO.testDevice( + id: UUID(), + publicKey: publicKey, + lastConnected: Date(), + isActive: false + ) + let bluetooth = DeviceDTO.testDevice( + id: peripheralID, + publicKey: publicKey, + lastConnected: Date().addingTimeInterval(-3600), + isActive: false + ).copy { + $0.connectionMethods = [.bluetooth(peripheralUUID: peripheralID, displayName: nil)] + } + try await manager.persistenceStore.saveDevice(ghost) + try await manager.persistenceStore.saveDevice(bluetooth) + + #expect(await manager.wifiDeviceID(publicKey: publicKey) == peripheralID) } - try await manager.persistenceStore.saveDevice(ghost) - try await manager.persistenceStore.saveDevice(bluetooth) - - #expect(await manager.wifiDeviceID(publicKey: publicKey) == peripheralID) } } diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionActivityTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionActivityTests.swift new file mode 100644 index 0000000000..863f2d296e --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionActivityTests.swift @@ -0,0 +1,331 @@ +import Foundation +@testable import MC1Services +import MeshCore +import MeshCoreTestSupport +import Observation +import Testing + +@Suite("Connection activity and recovery controls") +@MainActor +struct ConnectionActivityTests { + enum StopPoint: CaseIterable { + case recovering, presentationExpired, watchdogWaiting + } + + @Test(.timeLimit(.minutes(1))) + func `initial connection remains cancellable when the same request becomes ready`() async throws { + try await Fixture.withFixture { fixture in + await fixture.ble.holdConnect() + let connecting = Task { try await fixture.connect() } + fixture.connections.append(connecting) + try await waitUntil("the production transport connect must be held") { await fixture.ble.connectIsHeld } + let activity = try #require(fixture.manager.connectionActivity) + #expect(activity.phase == .connecting) + #expect(activity.requestID == fixture.manager.connectionRequestID) + + await fixture.ble.releaseConnect() + _ = try await connecting.value + let link = try #require(fixture.manager.installedLink) + #expect(link.requestID == activity.requestID) + #expect(fixture.manager.connectionActivity?.phase == .ready) + #expect(fixture.manager.connectionActivity?.targetName == link.device.nodeName) + let receipt = await fixture.manager.disconnect(requestID: activity.requestID) + #expect(receipt != nil) + #expect(fixture.manager.connectionActivity == nil) + #expect(!link.resource.binding.isActive) + #expect(fixture.manager.connectionIntent.isUserDisconnected) + } + } + + @Test(.timeLimit(.minutes(1))) + func `production BLE recovery remains visible after its actual presentation timeout`() async throws { + try await Fixture.withFixture { fixture in + _ = try await fixture.connect() + let device = try #require(fixture.manager.connectedDevice) + let request = try #require(fixture.manager.desiredRequest) + try await fixture.startRecovery() + let cycle = try #require(fixture.manager.reconnectionCoordinator.currentCycle) + #expect(fixture.manager.connectionActivity?.phase == .reconnecting) + #expect(fixture.manager.connectionActivity?.requestID == request.id) + #expect(fixture.manager.connectionActivity?.targetName == device.nodeName) + #expect(fixture.manager.connectedDevice == nil) + + try await fixture.expirePresentation() + #expect(fixture.manager.connectionActivity?.phase == .waitingToReconnect) + #expect(fixture.manager.connectionActivity?.requestID == request.id) + #expect(fixture.manager.connectionActivity?.targetName == device.nodeName) + #expect(fixture.manager.desiredRequest.map(ObjectIdentifier.init) == ObjectIdentifier(request)) + #expect(fixture.manager.reconnectionCoordinator.currentCycle == cycle) + #expect(fixture.manager.connectionIntent.wantsConnection) + #expect(fixture.manager.currentConnection == nil) + #expect(fixture.clock.sleeperCount == 0) + #expect(fixture.events.values.suffix(2) == [.connecting, .disconnected]) + #expect(await fixture.ble.connectCount == 1) + #expect(await fixture.ble.disconnectCount == 0) + } + } + + @Test(.timeLimit(.minutes(1)), arguments: StopPoint.allCases) + func `stop ends recovery intent and late callbacks cannot revive it`(point: StopPoint) async throws { + try await Fixture.withFixture { fixture in + _ = try await fixture.connect() + let oldLink = try #require(fixture.manager.installedLink) + let origin = try await fixture.startRecovery() + if point == .presentationExpired { try await fixture.expirePresentation() } + if point == .watchdogWaiting { + await fixture.manager.handleBLELifecycleEvent(.disconnected(origin, error: nil)) + try await waitUntil("production loss must arm its watchdog") { + fixture.manager.isReconnectionWatchdogRunning && fixture.clock.sleeperCount == 1 + } + #expect(fixture.manager.connectionActivity?.phase == .waitingToReconnect) + } + let activity = try #require(fixture.manager.connectionActivity) + try await fixture.drainCurrentState() + let previousEvents = fixture.events.values + let changes = ValueTracker() + withObservationTracking { + _ = fixture.manager.connectionActivity + } onChange: { + changes.record(true) + } + let disconnects = await fixture.ble.disconnectCount + let receipt = try #require(await fixture.manager.disconnect(requestID: activity.requestID)) + #expect(fixture.manager.isCurrent(receipt)) + #expect(fixture.manager.connectionActivity == nil) + #expect(fixture.manager.connectionIntent.isUserDisconnected) + #expect(ConnectionIntent.restored(from: fixture.defaults).isUserDisconnected) + #expect(fixture.manager.reconnectionCoordinator.currentCycle == nil) + #expect(!fixture.manager.isReconnectionWatchdogRunning) + #expect(fixture.manager.currentConnection == nil) + #expect(fixture.manager.services == nil) + #expect(fixture.manager.session == nil) + #expect(!oldLink.resource.binding.isActive) + #expect(changes.values == [true]) + #expect(await fixture.ble.disconnectCount == disconnects + 1) + #expect(try await fixture.manager.persistenceStore.fetchActiveDevice() == nil) + #expect(try await fixture.manager.persistenceStore.fetchDevice(id: oldLink.device.id)?.radioID == oldLink.device.radioID) + + let connects = await fixture.ble.connectCount + let commands = await fixture.ble.sentData + let closed = await fixture.ble.disconnectCount + await fixture.manager.handleBLELifecycleEvent(.reconnected(origin)) + await fixture.manager.handleBLELifecycleEvent(.disconnected(origin, error: .authenticationFailed)) + await fixture.manager.handleBLELifecycleEvent(.autoReconnecting(origin, errorInfo: "late loss")) + await fixture.manager.appDidBecomeActive() + fixture.clock.advance(by: .seconds(120)) + await fixture.finishEvents() + #expect(fixture.events.values == previousEvents + [.disconnected]) + #expect(fixture.manager.isCurrent(receipt)) + #expect(fixture.manager.connectionActivity == nil) + #expect(fixture.manager.connectionIntent.isUserDisconnected) + #expect(fixture.manager.reconnectionCoordinator.currentCycle == nil) + #expect(!fixture.manager.isReconnectionWatchdogRunning) + #expect(fixture.clock.sleeperCount == 0) + #expect(await fixture.ble.connectCount == connects) + #expect(await fixture.ble.sentData == commands) + #expect(await fixture.ble.disconnectCount == closed) + } + } + + @Test(.timeLimit(.minutes(1)), arguments: [false, true]) + func `stale stop leaves a successor request and all its resources untouched`(sameRadio: Bool) async throws { + try await Fixture.withFixture { fixture in + _ = try await fixture.connect() + try await fixture.startRecovery() + let oldRequestID = try #require(fixture.manager.connectionRequestID) + try await fixture.expirePresentation() + let nextID = sameRadio ? fixture.deviceID : UUID() + if !sameRadio { await fixture.ble.setPublicKey(Data(repeating: 2, count: ProtocolLimits.publicKeySize), for: nextID) } + await fixture.stateMachine.setStubbedIsAutoReconnecting(false) + _ = try await fixture.manager.connect(to: nextID, forceFullSync: true, forceReconnect: true) + let request = try #require(fixture.manager.desiredRequest) + let link = try #require(fixture.manager.installedLink) + #expect(request.id != oldRequestID) + #expect(link.device.id == nextID) + try await fixture.drainCurrentState() + let states = fixture.events.values + let commands = await fixture.ble.sentData + let connects = await fixture.ble.connectCount + let disconnects = await fixture.ble.disconnectCount + let metadata = try #require(try await fixture.manager.persistenceStore.fetchActiveDevice()) + let activity = try #require(fixture.manager.connectionActivity) + + let receipt = await fixture.manager.disconnect(requestID: oldRequestID) + #expect(receipt == nil) + #expect(fixture.manager.desiredRequest.map(ObjectIdentifier.init) == ObjectIdentifier(request)) + #expect(fixture.manager.installedLink.map(ObjectIdentifier.init) == ObjectIdentifier(link)) + #expect(fixture.manager.session.map(ObjectIdentifier.init) == ObjectIdentifier(link.resource.session)) + #expect(fixture.manager.services.map(ObjectIdentifier.init) == ObjectIdentifier(link.services)) + #expect(link.resource.binding.isActive) + #expect(fixture.manager.connectionIntent.wantsConnection) + #expect(!ConnectionIntent.restored(from: fixture.defaults).isUserDisconnected) + #expect(fixture.manager.connectionActivity?.requestID == activity.requestID) + #expect(fixture.manager.connectionActivity?.phase == .ready) + #expect(try await fixture.manager.persistenceStore.fetchActiveDevice()?.id == metadata.id) + #expect(await fixture.ble.sentData == commands) + #expect(await fixture.ble.connectCount == connects) + #expect(await fixture.ble.disconnectCount == disconnects) + await fixture.finishEvents() + #expect(fixture.events.values == states) + _ = try await link.resource.session.getTime() + } + } + + @Test(.timeLimit(.minutes(1))) + func `a recovery stop still applies after the same request becomes ready`() async throws { + try await Fixture.withFixture { fixture in + _ = try await fixture.connect() + try await fixture.startRecovery() + let activity = try #require(fixture.manager.connectionActivity) + await fixture.stateMachine.setStubbedIsAutoReconnecting(false) + await fixture.ble.simulateReconnected() + try await waitUntil("the real coordinator must rebuild and publish ready") { + fixture.manager.connectionState == .ready && fixture.manager.reconnectionCoordinator.currentCycle == nil + } + let link = try #require(fixture.manager.installedLink) + #expect(link.requestID == activity.requestID) + let receipt = await fixture.manager.disconnect(requestID: activity.requestID) + #expect(receipt != nil) + #expect(!link.resource.binding.isActive) + #expect(fixture.manager.connectionActivity == nil) + #expect(fixture.manager.currentConnection == nil) + #expect(fixture.manager.connectionIntent.isUserDisconnected) + } + } + + @Test(.timeLimit(.minutes(1))) + func `WiFi loss projects recovery for its original explicit request`() async throws { + try await Fixture.withFixture { fixture in + _ = try await fixture.manager.connectViaWiFi(host: "radio.test", port: 5123, forceFullSync: true) + let request = try #require(fixture.manager.desiredRequest) + #expect(request.origin == .explicit) + #expect(!request.handedOff) + let gate = BLEReconnectionTestHarness.Gate() + fixture.gates.append(gate) + var notified = false + fixture.manager.onAutoReconnectStarted = { _ in + notified = true + await gate.wait() + } + let loss = Task { + await fixture.manager.handleWiFiDisconnection(error: MeshTransportError.notConnected, remoteLossAt: nil, source: fixture.wifi) + } + fixture.losses.append(loss) + try await waitUntil("the production WiFi loss callback must remain held") { notified } + #expect(fixture.manager.connectionActivity?.requestID == request.id) + #expect(fixture.manager.connectionActivity?.phase == .reconnecting) + #expect(fixture.manager.desiredRequest.map(ObjectIdentifier.init) == ObjectIdentifier(request)) + #expect(!request.handedOff) + #expect(fixture.manager.connectedDevice == nil) + let receipt = await fixture.manager.disconnect(requestID: request.id) + #expect(receipt != nil) + gate.open() + await loss.value + #expect(fixture.manager.connectionActivity == nil) + #expect(fixture.manager.wifiReconnectTask == nil) + } + } + + @MainActor + private final class Fixture { + let clock = TestClock() + let stateMachine = MockBLEStateMachine() + let ble = ConnectionTestRadioTransport() + let wifi = ConnectionTestRadioTransport() + let deviceID = UUID() + let defaults: UserDefaults + let manager: ConnectionManager + let events = ValueTracker() + var connections: [Task] = [] + var losses: [Task] = [] + var gates: [BLEReconnectionTestHarness.Gate] = [] + private let suite = "test.connection-activity.\(UUID())" + private var observer: Task? + + init() throws { + defaults = try #require(UserDefaults(suiteName: suite)) + let pairing = MockAccessorySetupKitService() + pairing.isSessionActive = false + let wifi = wifi + manager = try ConnectionManager( + modelContainer: PersistenceStore.createContainer(inMemory: true), defaults: defaults, + stateMachine: stateMachine, transport: ble, + pairing: AccessorySetupPairingService(accessorySetupKit: pairing), + reconnectionClock: clock, makeWiFiTransport: { wifi } + ) + let stream = manager.connectionStateEvents.subscribe() + observer = Task { [events] in for await state in stream { + events.record(state) + } } + } + + static func withFixture(_ body: @MainActor (Fixture) async throws -> Void) async throws { + let fixture = try Fixture() + do { + await fixture.manager.wireTransportHandlers() + try await body(fixture) + } catch { await fixture.close(); throw error } + await fixture.close() + } + + func connect() async throws -> ConnectionResult { + try await manager.connect(to: deviceID, forceFullSync: true, forceReconnect: true) + } + + @discardableResult + func startRecovery() async throws -> BLELifecycleOrigin { + await stateMachine.setStubbedIsAutoReconnecting(true) + await ble.simulateAutoReconnecting(deviceID: deviceID) + try await waitUntil("the transport event must begin real recovery and park its timeout") { + self.manager.connectionState == .connecting + && self.manager.reconnectionCoordinator.currentCycle != nil && self.clock.sleeperCount == 1 + } + try await drainCurrentState() + return try #require(await ble.lifecycleOrigin) + } + + func expirePresentation() async throws { + for interval in 0..<4 { + try await waitUntil("the current presentation timeout must be sleeping") { self.clock.sleeperCount == 1 } + clock.advance(by: .seconds(15)) + if interval < 3 { + try await waitUntil("OS auto recovery must rearm before the next interval") { self.clock.sleeperCount == 1 } + } + } + try await waitUntil("the real coordinator must publish its expired presentation") { + self.manager.connectionState == .disconnected + } + try await drainCurrentState() + } + + func drainCurrentState() async throws { + try await waitUntil("state events must reach the current production publication") { + self.events.values.last == self.manager.connectionState + } + } + + func finishEvents() async { + manager.connectionStateEvents.finish() + await observer?.value + } + + func close() async { + gates.forEach { $0.open() } + await ble.releaseAllGates() + await wifi.releaseAllGates() + for connection in connections { + connection.cancel(); _ = await connection.result + } + for loss in losses { + await loss.value + } + manager.onAutoReconnectStarted = nil + _ = await manager.disconnect() + await manager.retirementTask?.value + await manager.metadataCommitTask?.value + await finishEvents() + #expect(clock.sleeperCount == 0) + UserDefaults().removePersistentDomain(forName: suite) + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionDeviceUpdateProvenanceTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionDeviceUpdateProvenanceTests.swift new file mode 100644 index 0000000000..962d9a8047 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionDeviceUpdateProvenanceTests.swift @@ -0,0 +1,251 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Connection Device update provenance") +@MainActor +struct ConnectionDeviceUpdateProvenanceTests { + @Test(arguments: MetadataPeer.allCases) + func `accepted peers merge unrelated fresh metadata`(peer: MetadataPeer) async throws { + let env = try ConnectionManagerRadioTestHarness() + let gate = BLEReconnectionTestHarness.Gate() + var predecessor: Task? + var bodyError: (any Error)? + do { + _ = try await env.connect(.bluetooth) + guard let source = env.manager.connectedDevice else { + throw NSError(domain: "ConnectionDeviceUpdateProvenance", code: 1) + } + let seeded = source.copy { + $0.preRepeatFrequency = 900_000 + $0.preRepeatBandwidth = 62500 + $0.preRepeatSpreadingFactor = 12 + $0.preRepeatCodingRate = 8 + } + try await env.manager.persistenceStore.saveDevice(seeded) + env.manager.updateDevice(with: seeded) + predecessor = env.manager.enqueueMetadata { store in + await gate.wait() + try await store.addDeviceKnownRegion(radioID: source.radioID, region: Self.freshRegion) + } + peer.apply(to: env.manager, source: seeded) + let peerWasPublished = env.manager.connectedDevice.map { peer.matches($0, source: seeded) } == true + try #require(peerWasPublished) + gate.open() + try await predecessor?.value + await env.manager.metadataCommitTask?.value + let saved = try await env.manager.persistenceStore.fetchDevice(id: source.id) + let acceptedPeerWasSaved = saved.map { peer.matches($0, source: seeded) } == true + let unrelatedFreshFieldSurvives = saved?.knownRegions == [Self.freshRegion] + let originalTupleSurvives = saved?.id == source.id && saved?.publicKey == source.publicKey + && saved?.radioID == source.radioID + #expect(acceptedPeerWasSaved) + #expect(unrelatedFreshFieldSurvives) + #expect(originalTupleSurvives) + let laterTime = try await env.manager.services?.settingsService.getTime() + #expect(laterTime != nil) + } catch { + bodyError = error + } + gate.open() + _ = await predecessor?.result + await env.close() + if let bodyError { throw bodyError } + } + + @Test(arguments: [IdentityChange.publicKey, .radioID, .remintedDeviceID, .removed]) + func `accepted transform cannot cross changed or missing identity`(change: IdentityChange) async throws { + let env = try ConnectionManagerRadioTestHarness() + let gate = BLEReconnectionTestHarness.Gate() + let newRadioID = UUID() + let newDeviceID = UUID() + var predecessor: Task? + var bodyError: (any Error)? + do { + _ = try await env.connect(.bluetooth) + guard let source = env.manager.connectedDevice else { + throw NSError(domain: "ConnectionDeviceUpdateProvenance", code: 1) + } + let admittedPredecessor: Task = env.manager.enqueueMetadata { store in + await gate.wait() + guard let fresh = try await store.fetchDevice(id: source.id) else { return nil } + if change == .removed { + try await store.deleteDevice(id: source.id) + return nil + } + let changed = fresh.copy { + $0.knownRegions = [Self.freshRegion] + switch change { + case .publicKey: $0.publicKey = Self.replacementPublicKey + case .radioID: $0.radioID = newRadioID + case .remintedDeviceID: $0.id = newDeviceID + case .removed: break + } + } + if change == .remintedDeviceID { try await store.deleteDevice(id: source.id) } + try await store.saveDevice(changed) + try await store.addDeviceKnownRegion(radioID: changed.radioID, region: Self.freshRegion) + let committed = try await store.fetchDevice(id: changed.id) + let intendedFixtureWasCommitted = committed == changed + try #require(intendedFixtureWasCommitted) + return changed + } + predecessor = admittedPredecessor + env.manager.updateDefaultFloodScopeName(Self.acceptedScope) + let updateWasAccepted = env.manager.connectedDevice?.defaultFloodScopeName == Self.acceptedScope + try #require(updateWasAccepted) + gate.open() + let predecessorResult = try await admittedPredecessor.value + await env.manager.metadataCommitTask?.value + let storedID = change == .remintedDeviceID ? newDeviceID : source.id + let saved = try await env.manager.persistenceStore.fetchDevice(id: storedID) + let changedIdentityAndFieldsRemainUntouched = saved == predecessorResult + let oldHandle = try await env.manager.persistenceStore.fetchDevice(id: source.id) + let oldHandleWasNotRecreated = change != .remintedDeviceID || oldHandle == nil + #expect(changedIdentityAndFieldsRemainUntouched) + #expect(oldHandleWasNotRecreated) + let laterTime = try await env.manager.services?.settingsService.getTime() + #expect(laterTime != nil) + } catch { + bodyError = error + } + gate.open() + _ = await predecessor?.result + await env.close() + if let bodyError { throw bodyError } + } + + @Test + func `settings refresh cannot restore a replaced public key`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let gate = BLEReconnectionTestHarness.Gate() + var predecessor: Task? + do { + _ = try await env.connect(.bluetooth) + let source = try #require(env.manager.connectedDevice) + let services = try #require(env.manager.services) + predecessor = env.manager.enqueueMetadata { store in + await gate.wait() + let current = try #require(try await store.fetchDevice(id: source.id)) + try await store.saveDevice(current.copy { $0.publicKey = Self.replacementPublicKey }) + } + let release = Task { @MainActor in + await Task.yield() + gate.open() + } + await env.manager.applyDeviceObservation(MetadataPeer.info(from: source), from: services) + await release.value + try await predecessor?.value + let stored = try #require(try await env.manager.persistenceStore.fetchDevice(id: source.id)) + #expect(stored.publicKey == Self.replacementPublicKey) + #expect(stored.nodeName == source.nodeName) + #expect(env.manager.connectedDevice == source) + } catch { + gate.open() + _ = await predecessor?.result + await env.close() + throw error + } + await env.close() + } + + @Test + func `persisted DTO callback only publishes the installed identity`() async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + _ = try await env.connect(.bluetooth) + guard let source = env.manager.connectedDevice else { + throw NSError(domain: "ConnectionDeviceUpdateProvenance", code: 1) + } + let wrongKey = source.copy { + $0.publicKey = Self.replacementPublicKey + $0.nodeName = "Rejected key" + } + let wrongRadioID = source.copy { + $0.radioID = UUID() + $0.nodeName = "Rejected Radio ID" + } + let wrongDeviceID = source.copy { + $0.id = UUID() + $0.nodeName = "Rejected Device ID" + } + env.manager.updateDevice(with: wrongKey) + env.manager.updateDevice(with: wrongRadioID) + env.manager.updateDevice(with: wrongDeviceID) + let mismatchedCallbacksWereRejected = env.manager.connectedDevice == source + #expect(mismatchedCallbacksWereRejected) + let persisted = source.copy { + $0.ocvPreset = "custom" + $0.customOCVArrayString = "4100,3900" + } + try await env.manager.persistenceStore.saveDevice(persisted) + env.manager.updateDevice(with: persisted) + let matchingCallbackWasPublished = env.manager.connectedDevice == persisted + #expect(matchingCallbackWasPublished) + await env.manager.metadataCommitTask?.value + let saved = try await env.manager.persistenceStore.fetchDevice(id: source.id) + let persistedFieldsRemainUntouched = saved == persisted + #expect(persistedFieldsRemainUntouched) + let laterTime = try await env.manager.services?.settingsService.getTime() + #expect(laterTime != nil) + } catch { + await env.close() + throw error + } + await env.close() + } + + enum MetadataPeer: CaseIterable, Sendable { + case selfInfo, autoAddConfig, clientRepeat, pathHashMode, defaultFloodScope, savePreRepeat, clearPreRepeat + + @MainActor + func apply(to manager: ConnectionManager, source: DeviceDTO) { + switch self { + case .selfInfo: + manager.updateDevice(from: Self.info(from: source), appliedRadioPresetID: nil) + case .autoAddConfig: manager.updateAutoAddConfig(AutoAddConfig(bitmask: 7, maxHops: 5)) + case .clientRepeat: manager.updateClientRepeat(true) + case .pathHashMode: manager.updatePathHashMode(2) + case .defaultFloodScope: manager.updateDefaultFloodScopeName(ConnectionDeviceUpdateProvenanceTests.acceptedScope) + case .savePreRepeat: manager.savePreRepeatSettings() + case .clearPreRepeat: manager.clearPreRepeatSettings() + } + } + + @MainActor + func matches(_ device: DeviceDTO, source: DeviceDTO) -> Bool { + switch self { + case .selfInfo: device.nodeName == "Accepted Settings name" && device.telemetryModeBase == 1 + case .autoAddConfig: device.autoAddConfig == 7 && device.autoAddMaxHops == 5 + case .clientRepeat: device.clientRepeat + case .pathHashMode: device.pathHashMode == 2 + case .defaultFloodScope: device.defaultFloodScopeName == ConnectionDeviceUpdateProvenanceTests.acceptedScope + case .savePreRepeat: + device.preRepeatFrequency == source.frequency && device.preRepeatBandwidth == source.bandwidth + && device.preRepeatSpreadingFactor == source.spreadingFactor && device.preRepeatCodingRate == source.codingRate + case .clearPreRepeat: + device.preRepeatFrequency == nil && device.preRepeatBandwidth == nil + && device.preRepeatSpreadingFactor == nil && device.preRepeatCodingRate == nil + } + } + + static func info(from device: DeviceDTO) -> MeshCore.SelfInfo { + MeshCore.SelfInfo( + advertisementType: 1, txPower: device.txPower, maxTxPower: device.maxTxPower, + publicKey: device.publicKey, latitude: device.latitude, longitude: device.longitude, + multiAcks: device.multiAcks, advertisementLocationPolicy: device.advertLocationPolicy, + telemetryModeEnvironment: device.telemetryModeEnv, telemetryModeLocation: device.telemetryModeLoc, + telemetryModeBase: 1, manualAddContacts: device.manualAddContacts, + radioFrequency: Double(device.frequency) / 1000, radioBandwidth: Double(device.bandwidth) / 1000, + radioSpreadingFactor: device.spreadingFactor, radioCodingRate: device.codingRate, name: "Accepted Settings name" + ) + } + } + + enum IdentityChange: Sendable { case publicKey, radioID, remintedDeviceID, removed } + + private static let acceptedScope = "Accepted scope" + private static let freshRegion = "Fresh local region" + private static let replacementPublicKey = Data(repeating: 0xB9, count: ProtocolLimits.publicKeySize) +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionLifecycleDiagnosticsTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionLifecycleDiagnosticsTests.swift new file mode 100644 index 0000000000..eb2a7e11ae --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionLifecycleDiagnosticsTests.swift @@ -0,0 +1,261 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Connection lifecycle diagnostics", .serialized, .timeLimit(.minutes(1))) +@MainActor +struct ConnectionLifecycleDiagnosticsTests { + @Test + func `production publication and retirement keep their captured owners in persistent records`() async throws { + let run = try Harness() + do { + let link = try await run.connect() + let request = try #require(run.env.manager.desiredRequest) + let attempt = try #require(request.attempt) + let origin = try #require(request.physicalOrigin) + let fields = capturedFields(request: request, attempt: attempt, link: link, origin: origin) + #expect(try await link.resource.session.getBattery().level == 3700) + run.reclaimLogs() + + _ = await run.env.manager.disconnect(reason: .userInitiated) + + let records = try await run.records(until: ["event=retired,"]) + let terminalRequestID = try #require(run.env.manager.connectionRequestID) + #expect(records.contains { record in + record.contains("event=disconnectAdmitted,") && record.contains("request=\(terminalRequestID)") + && record.contains("currentLink=\(link.generation)") + && record.contains("currentBinding=\(ObjectIdentifier(link.resource.binding))") + && record.contains("reason=\(DisconnectReason.userInitiated.rawValue)") + }) + #expect(records.contains { $0.contains("event=admitted,") && $0.contains("request=\(request.id)") }) + #expect(records.contains { $0.contains("event=attemptStarted,") && $0.contains("attempt=\(ObjectIdentifier(attempt))") }) + for event in ["published", "dispose", "retired"] { + #expect(records.contains { record in + record.contains("event=\(event),") && fields.allSatisfy { record.contains($0) } + }, "The \(event) record must retain the exact request, Link, binding, session and physical origin") + } + #expect(records.contains { record in + record.contains("event=state,") && record.contains("state=ready") && fields.allSatisfy { record.contains($0) } + }) + #expect(records.contains { $0.contains("event=state,") && $0.contains("state=disconnected") && $0.contains("link=none") }) + #expect(run.env.manager.currentConnection == nil) + #expect(await run.env.ble.disconnectCount == 1) + expectAllowedFields(records) + } catch { await run.close(); throw error } + await run.close() + } + + @Test + func `stale admission and publication explain the rejected owner and same-radio successor`() async throws { + let run = try Harness() + do { + let first = try await run.connect() + let oldRequest = try #require(run.env.manager.desiredRequest) + let oldAttempt = try #require(oldRequest.attempt) + let next = try await run.connect() + let currentRequest = try #require(run.env.manager.desiredRequest) + let connects = await run.env.ble.connectCount + let disconnects = await run.env.ble.disconnectCount + #expect(next.device.id == first.device.id) + #expect(next.generation != first.generation) + run.reclaimLogs() + + #expect(throws: CancellationError.self) { try run.env.manager.requireAttemptOwnership(oldRequest, oldAttempt) } + #expect(throws: CancellationError.self) { try run.env.manager.publish(first, repeatRanges: []) } + + let records = try await run.records(until: ["event=admissionRejected,", "event=publicationRejected,"]) + let expected = [ + "request=\(oldRequest.id)", "currentRequest=\(currentRequest.id)", + "currentLink=\(next.generation)", "currentBinding=\(ObjectIdentifier(next.resource.binding))" + ] + for (event, reason) in [("admissionRejected", "supersededRequest"), ("publicationRejected", "requestOrBinding")] { + #expect(records.contains { record in + record.contains("event=\(event),") && record.contains("reason=\(reason)") + && expected.allSatisfy { record.contains($0) } + }) + } + #expect(records.contains { $0.contains("event=publicationRejected,") && $0.contains("link=\(first.generation)") }) + #expect(run.env.manager.installedLink === next) + #expect(run.env.manager.connectionState == .ready) + #expect(try await next.resource.session.getBattery().level == 3700) + #expect(await run.env.ble.connectCount == connects) + #expect(await run.env.ble.disconnectCount == disconnects) + expectAllowedFields(records) + } catch { await run.close(); throw error } + await run.close() + } + + @Test(arguments: [CollectionPreference.absent, .storedFalse, .storedTrue]) + private func `lifecycle records survive the collection preference and restore it`(preference: CollectionPreference) async throws { + let process = CollectionPreference.capture() + defer { CollectionPreference.restore(process) } + preference.install() + let previousBuffer = DebugLogBuffer.shared + let run = try Harness() + do { + _ = try await run.connect() + let records = try await run.records(until: ["event=published,"]) + #expect(records.contains { $0.contains("event=published,") }) + } catch { + await run.close() + throw error + } + await run.close() + #expect(DebugLogBuffer.shared === previousBuffer) + preference.assertRestored() + } + + @Test(arguments: [CollectionPreference.absent, .storedFalse, .storedTrue]) + private func `lifecycle records restore the collection preference after the test body throws`( + preference: CollectionPreference + ) async throws { + let process = CollectionPreference.capture() + defer { CollectionPreference.restore(process) } + preference.install() + let previousBuffer = DebugLogBuffer.shared + let run = try Harness() + do { + _ = try await run.connect() + let records = try await run.records(until: ["event=published,"]) + #expect(records.contains { $0.contains("event=published,") }) + throw BodyFailure() + } catch is BodyFailure { + await run.close() + } catch { + await run.close() + throw error + } + #expect(DebugLogBuffer.shared === previousBuffer) + preference.assertRestored() + } + + private struct BodyFailure: Error {} + + private enum CollectionPreference: Sendable, CustomStringConvertible { + case absent + case storedFalse + case storedTrue + + private static var key: String { + AppStorageKey.collectDebugLogs.rawValue + } + + var description: String { + switch self { + case .absent: "absent" + case .storedFalse: "false" + case .storedTrue: "true" + } + } + + func install() { + switch self { + case .absent: UserDefaults.standard.removeObject(forKey: Self.key) + case .storedFalse: UserDefaults.standard.set(false, forKey: Self.key) + case .storedTrue: UserDefaults.standard.set(true, forKey: Self.key) + } + } + + static func capture() -> Any? { + UserDefaults.standard.object(forKey: key) + } + + static func restore(_ value: Any?) { + if let value { + UserDefaults.standard.set(value, forKey: key) + } else { + UserDefaults.standard.removeObject(forKey: key) + } + } + + func assertRestored() { + switch self { + case .absent: + #expect(UserDefaults.standard.object(forKey: Self.key) == nil) + case .storedFalse: + #expect(UserDefaults.standard.object(forKey: Self.key) != nil) + #expect(UserDefaults.standard.bool(forKey: Self.key) == false) + case .storedTrue: + #expect(UserDefaults.standard.bool(forKey: Self.key)) + } + } + } + + private func capturedFields( + request: ConnectionRequest, attempt: ConnectionAttempt, link: ConnectionLink, origin: BLELifecycleOrigin + ) -> [String] { + ["request=\(request.id)", "attempt=\(ObjectIdentifier(attempt))", "link=\(link.generation)", + "binding=\(ObjectIdentifier(link.resource.binding))", "session=\(ObjectIdentifier(link.resource.session))", + "device=\(link.device.id.uuidString.prefix(8))", "physicalGeneration=\(origin.generation)"] + } + + private func expectAllowedFields(_ records: [String]) { + for record in records { + for forbidden in ["payload=", "password=", "pin=", "secret=", "publicKey=", "host=", "ssid="] { + #expect(!record.localizedCaseInsensitiveContains(forbidden)) + } + } + } + + @MainActor + private final class Harness { + let env: ConnectionManagerRadioTestHarness + private let previousBuffer = DebugLogBuffer.shared + private let capturedPreference: Any? + private let bootstrap: DebugLogBuffer + private var ownedBuffers: [DebugLogBuffer] + private static let settleTimeout: Duration = .seconds(2) + private static let pollInterval: Duration = .milliseconds(10) + private static let logLimit = 2000 + + init() throws { + env = try ConnectionManagerRadioTestHarness() + capturedPreference = CollectionPreference.capture() + DebugLogBuffer.enableCollection() + bootstrap = DebugLogBuffer(dataStore: env.manager.persistenceStore) + ownedBuffers = [bootstrap] + DebugLogBuffer.shared = bootstrap + } + + func connect() async throws -> ConnectionLink { + reclaimLogs() + await env.manager.wireTransportHandlers() + _ = try await env.connect(.bluetooth) + let link = try #require(env.manager.installedLink) + ownedBuffers.append(link.services.debugLogBuffer) + #expect(env.manager.connectionState == .ready) + return link + } + + func reclaimLogs() { + DebugLogBuffer.shared = bootstrap + } + + func records(until markers: [String]) async throws -> [String] { + let deadline = ContinuousClock.now + Self.settleTimeout + var messages: [String] = [] + repeat { + for buffer in ownedBuffers { + await buffer.flush() + } + messages = try await env.manager.persistenceStore.fetchDebugLogEntries(since: .distantPast, limit: Self.logLimit) + .map(\.message).filter { $0.contains("[ConnectionLifecycle]") } + if markers.allSatisfy({ marker in messages.contains { $0.contains(marker) } }) { break } + try await Task.sleep(for: Self.pollInterval) + } while ContinuousClock.now < deadline + return messages + } + + func close() async { + await env.close() + for buffer in ownedBuffers { + await buffer.shutdown() + } + if let current = DebugLogBuffer.shared, ownedBuffers.contains(where: { $0 === current }) { + DebugLogBuffer.shared = previousBuffer + } + CollectionPreference.restore(capturedPreference) + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerACKRecoveryTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerACKRecoveryTests.swift new file mode 100644 index 0000000000..00f3e706b3 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerACKRecoveryTests.swift @@ -0,0 +1,65 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("ConnectionManager ACK recovery", .serialized) +@MainActor +struct ConnectionManagerACKRecoveryTests { + @Test + func `ACK buffered during app start resolves the restored owner before any retransmission`() async throws { + let previousLogBuffer = DebugLogBuffer.shared + defer { DebugLogBuffer.shared = previousLogBuffer } + let env = try ConnectionManagerRadioTestHarness() + env.manager.testNotificationSystemOperations = .init( + setBadgeCount: { _ in }, deliveredRequests: { [] }, removeDeliveredNotifications: { _ in } + ) + let radioID = UUID() + try await env.manager.persistenceStore.saveDevice(.testDevice( + id: env.deviceID, radioID: radioID, publicKey: env.ble.publicKey + )) + let contact = ContactDTO.testContact(radioID: radioID) + try await env.manager.persistenceStore.saveContact(contact) + await env.ble.setContact(contact.toContactFrame().toMeshContact()) + let message = MessageDTO.testDirectMessage(radioID: radioID, contactID: contact.id) + try await env.manager.persistenceStore.saveMessage(message) + let code = Data([0xDE, 0xAD, 0xBE, 0xEF]) + let sentAt = Date().addingTimeInterval(-1) + let row = PendingSendDTO( + envelope: DirectMessageEnvelope(messageID: message.id, contactID: contact.id), radioID: radioID, + ackCodes: [code], ackSentAt: sentAt, ackDeadline: sentAt.addingTimeInterval(60) + ) + #expect(try await env.manager.persistenceStore.savePendingAcknowledgement(row, replacingPendingSendID: nil)) + var ack = Data([ResponseCode.ack.rawValue]) + ack.append(code) + ack.append(contentsOf: [123, 0, 0, 0]) + await env.ble.setResponsePackets(for: .appStart, packets: [ack, selfInfoPacket(publicKey: env.ble.publicKey)]) + do { + _ = try await env.connect(.bluetooth) + let deadline = ContinuousClock.now.advanced(by: .seconds(5)) + while try await env.manager.persistenceStore.fetchMessage(id: message.id)?.status != .delivered { + try #require(ContinuousClock.now < deadline, "The pre-start ACK must reach the restored owner") + try await Task.sleep(for: .milliseconds(1)) + } + #expect(try await env.manager.persistenceStore.fetchMessage(id: message.id)?.roundTripTime == 123) + #expect(try await env.manager.persistenceStore.fetchPendingSends(radioID: radioID).isEmpty) + #expect(await env.ble.sentData.allSatisfy { $0.first != CommandCode.sendMessage.rawValue }) + } catch { + await env.close() + throw error + } + await env.close() + } + + private func selfInfoPacket(publicKey: Data) -> Data { + var reply = Data([ResponseCode.selfInfo.rawValue, 1, 22, 22]) + reply.append(publicKey) + reply.append(Data(repeating: 0, count: 12)) + for value: UInt32 in [915_000, 125_000] { + reply.append(withUnsafeBytes(of: value.littleEndian) { Data($0) }) + } + reply.append(contentsOf: [7, 5]) + reply.append(contentsOf: "Test Radio".utf8) + return reply + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAdmissionPortTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAdmissionPortTests.swift new file mode 100644 index 0000000000..4da99502fc --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAdmissionPortTests.swift @@ -0,0 +1,102 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Explicit admission during retirement") +@MainActor +struct ConnectionManagerAdmissionPortTests { + enum Entry: CaseIterable { + case connect + case bluetooth + case wifi + case simulator + } + + @Test(.timeLimit(.minutes(1)), arguments: Entry.allCases) + func `an older explicit entry waiting for retirement cannot replace a newer choice`(entry: Entry) async throws { + let env = try ConnectionManagerRadioTestHarness() + let retirement = Gate() + var older: Task? + var newer: Task? + do { + _ = try await env.connect(.bluetooth) + let initial = try #require(env.manager.currentConnection) + env.manager.testConnectionTeardownHandler = { await retirement.wait() } + older = Task { + switch entry { + case .connect: + try await env.manager.connect(to: env.deviceID, forceFullSync: true, forceReconnect: true) + case .bluetooth: + try await env.manager.connectViaBluetooth(peripheralID: env.deviceID, forceFullSync: true) + case .wifi: + try await env.manager.connectViaWiFi(host: "older.test", port: 5123, forceFullSync: true) + case .simulator: + try await env.manager.simulatorConnect() + } + } + try await waitUntil("the older choice must claim retirement before the newer choice arrives") { retirement.isWaiting } + let oldRequest = try #require(env.manager.desiredRequest) + #expect(oldRequest.id != initial.requestID) + let nextID = UUID() + newer = Task { try await env.manager.connect(to: nextID, forceFullSync: true, forceReconnect: true) } + try await waitUntil("the newer choice must be admitted while predecessor retirement is held") { + env.manager.desiredRequest?.target == .bluetooth(nextID) + } + let nextRequestID = env.manager.connectionRequestID + #expect(env.manager.currentConnection == nil) + #expect(env.manager.connectionIntent.wantsConnection) + #expect(await env.ble.connectCount == 1) + #expect(await env.wifi.connectCount == 0) + retirement.open() + let oldResult = try await #require(older).value + #expect(!env.manager.isCurrent(oldResult)) + let result = try await #require(newer).value + #expect(env.manager.isCurrent(result)) + #expect(env.manager.connectionRequestID == nextRequestID) + #expect(env.manager.connectedDevice?.id == nextID) + #expect(env.manager.lastConnectedDeviceID == nextID) + #expect(env.manager.connectionState == .ready) + #expect(env.manager.connectionTeardownCount == 0) + #expect(await env.ble.connectCount == 2) + #expect(await env.wifi.connectCount == 0) + let current = try #require(env.manager.currentConnection) + #expect(try await current.services.session.getTime().timeIntervalSince1970 > 0) + } catch { + retirement.open() + older?.cancel() + newer?.cancel() + env.manager.testConnectionTeardownHandler = nil + await env.ble.releaseAllGates() + await env.wifi.releaseAllGates() + _ = await older?.result + _ = await newer?.result + await env.close() + throw error + } + env.manager.testConnectionTeardownHandler = nil + await env.close() + } + + @MainActor + private final class Gate { + private var continuations: [CheckedContinuation] = [] + private var isOpen = false + var isWaiting: Bool { + !continuations.isEmpty + } + + func wait() async { + guard !isOpen else { return } + await withCheckedContinuation { continuations.append($0) } + } + + func open() { + isOpen = true + let waiting = continuations + continuations.removeAll() + for continuation in waiting { + continuation.resume() + } + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAdoptionRaceTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAdoptionRaceTests.swift index 4902a97ece..2f8de4f604 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAdoptionRaceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAdoptionRaceTests.swift @@ -1,3 +1,4 @@ +@preconcurrency import CoreBluetooth import Foundation @testable import MC1Services import Testing @@ -10,67 +11,100 @@ struct ConnectionManagerAdoptionRaceTests { let env = try ConnectionManager.createForPairingTesting() defer { env.cleanup() } let deviceID = UUID() + env.accessorySetupKit.isSessionActive = false env.manager.testLastConnectedDeviceID = deviceID - env.manager.setTestState(connectionState: .disconnected, connectionIntent: .wantsConnection()) await env.stateMachine.setStubbedIsDeviceConnectedToSystem(true) + await env.transport.setConnectError(BLEError.bluetoothUnavailable) - let started = await env.manager.startAdoptingLastSystemConnectedPeripheralIfAvailable( - deviceID: deviceID, context: "test" - ) + await #expect(throws: ConnectionRequestFailure.self) { + try await env.manager.connect(to: deviceID, forceReconnect: true) + } - #expect(!started) #expect(env.manager.connectionState == .disconnected) - #expect(env.manager.reconnectionCoordinator.reconnectingDeviceID == nil) + #expect(env.manager.reconnectionCoordinator.currentCycle == nil) #expect(await env.stateMachine.startAdoptingSystemConnectedPeripheralCalls == [deviceID]) + #expect(await env.transport.connectInvocations.map(\.deviceID) == [deviceID]) + _ = await env.manager.disconnect(reason: .userInitiated) } @Test - func `user disconnect during adoption entry prevents fallback or adoption`() async throws { - let env = try ConnectionManager.createForPairingTesting() - defer { env.cleanup() } - let manager = env.manager - let deviceID = UUID() - manager.testLastConnectedDeviceID = deviceID - manager.setTestState(connectionState: .disconnected, connectionIntent: .wantsConnection()) - await env.stateMachine.setStubbedIsDeviceConnectedToSystem(true) - manager.onAutoReconnectStarted = { - manager.reconnectionCoordinator.clearReconnectingDevice() - manager.setTestState(connectionState: .disconnected, connectionIntent: .userDisconnected) - } + func `user disconnect during adoption entry prevents fallback or completion`() async throws { + let harness = try await BLEAdoptionTestHarness.make() + let manager = harness.manager + let deviceID = harness.ble.peripheral.identifier + let adopting = Task { try await manager.connect(to: deviceID) } + var disconnecting: Task? + do { + try await harness.awaitCondition { await harness.transport.originReadIsHeld } + let oldRequestID = manager.connectionRequestID + let disconnect = Task { await manager.disconnect(reason: .userInitiated) } + disconnecting = disconnect + try await harness.awaitCondition { manager.connectionRequestID != oldRequestID } + await harness.transport.releaseOrigin() + let result = try await adopting.value + if case .superseded = result {} else { Issue.record("The disconnect must supersede adoption") } + let receipt = await disconnect.value - let handled = await manager.startAdoptingLastSystemConnectedPeripheralIfAvailable( - deviceID: deviceID, context: "test" - ) - - #expect(handled) - #expect(manager.connectionState == .disconnected) - #expect(manager.connectionIntent == .userDisconnected) - #expect(await env.stateMachine.startAdoptingSystemConnectedPeripheralCalls.isEmpty) + #expect(manager.isCurrent(receipt)) + #expect(manager.connectionState == .disconnected) + #expect(manager.connectionIntent.isUserDisconnected) + #expect(manager.reconnectionCoordinator.currentCycle == nil) + #expect(harness.ble.native.connectCount == 0) + #expect(await harness.firmware.sentData.isEmpty) + } catch { + await harness.transport.releaseOrigin() + adopting.cancel() + _ = await adopting.result + _ = await disconnecting?.value + await harness.close() + throw error + } + await harness.close() } @Test - func `adoption entry preserves a newer reconnect for a different device`() async throws { - let env = try ConnectionManager.createForPairingTesting() - defer { env.cleanup() } - let manager = env.manager - let deviceID = UUID() + func `adoption entry preserves an admitted reconnect for a different device`() async throws { + let harness = try await BLEAdoptionTestHarness.make() + let manager = harness.manager + let deviceID = harness.ble.peripheral.identifier let replacementID = UUID() - manager.testLastConnectedDeviceID = deviceID - manager.setTestState(connectionState: .disconnected, connectionIntent: .wantsConnection()) - await env.stateMachine.setStubbedIsDeviceConnectedToSystem(true) - manager.onAutoReconnectStarted = { - manager.onAutoReconnectStarted = nil - await manager.reconnectionCoordinator.handleEnteringAutoReconnect(deviceID: replacementID) - } - - let handled = await manager.startAdoptingLastSystemConnectedPeripheralIfAvailable( - deviceID: deviceID, context: "test" - ) + let adopting = Task { try await manager.connect(to: deviceID) } + var replacing: Task? + do { + try await harness.awaitCondition { await harness.transport.originReadIsHeld } + let next = Task { + try await manager.requestConnection( + targets: [.bluetooth(replacementID)], origin: .explicit, forceFullSync: false, forceReconnect: true, + operation: { request in + let origin = BLELifecycleOrigin(deviceID: replacementID, generation: 1, eventTime: CFAbsoluteTimeGetCurrent()) + await manager.enterBLERecovery(request, origin: origin) + return .handoff(requestID: request.id) + } + ) + } + replacing = next + let replacement = try await next.value + let cycle = try #require(manager.reconnectionCoordinator.currentCycle) + await harness.transport.releaseOrigin() + let oldResult = try await adopting.value - #expect(handled) - #expect(manager.reconnectionCoordinator.reconnectingDeviceID == replacementID) - #expect(manager.connectionState == .connecting) - #expect(await env.stateMachine.startAdoptingSystemConnectedPeripheralCalls.isEmpty) - manager.reconnectionCoordinator.cancelTimeout() + if case .superseded = oldResult {} else { Issue.record("The newer request must supersede adoption") } + #expect(manager.isCurrent(replacement)) + #expect(manager.desiredRequest?.target == .bluetooth(replacementID)) + #expect(manager.reconnectionCoordinator.currentCycle == cycle) + #expect(cycle.deviceID == replacementID) + #expect(manager.connectionState == .connecting) + #expect(harness.ble.native.connectCount == 0) + #expect(await harness.firmware.sentData.isEmpty) + } catch { + await harness.transport.releaseOrigin() + adopting.cancel() + replacing?.cancel() + _ = await adopting.result + _ = await replacing?.result + await harness.close() + throw error + } + await harness.close() } } diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAuthFailureRoutingTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAuthFailureRoutingTests.swift index 47b6956975..75673b92e1 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAuthFailureRoutingTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAuthFailureRoutingTests.swift @@ -16,16 +16,17 @@ struct ConnectionManagerAuthFailureRoutingTests { func `connection loss with authenticationFailed fires the callback once per episode`() async throws { let env = try ConnectionManager.createForPairingTesting() defer { env.cleanup() } + env.manager.setTestState(connectionIntent: .wantsConnection()) let deviceID = UUID() var surfaced: [UUID] = [] env.manager.onAuthenticationFailure = { surfaced.append($0) } - await env.manager.handleConnectionLoss(deviceID: deviceID, error: BLEError.authenticationFailed) + await env.manager.acceptSeededBLELoss(deviceID: deviceID, error: BLEError.authenticationFailed) #expect(surfaced == [deviceID]) // Watchdog retries keep failing the same way while the bond stays invalid; // the latch must keep those repeats from re-presenting the recovery alert. - await env.manager.handleConnectionLoss(deviceID: deviceID, error: BLEError.authenticationFailed) + await env.manager.acceptSeededBLELoss(deviceID: deviceID, error: BLEError.authenticationFailed) #expect(surfaced == [deviceID]) } @@ -33,10 +34,11 @@ struct ConnectionManagerAuthFailureRoutingTests { func `connection loss with a non-auth error does not fire the callback`() async throws { let env = try ConnectionManager.createForPairingTesting() defer { env.cleanup() } + env.manager.setTestState(connectionIntent: .wantsConnection()) var surfaced: [UUID] = [] env.manager.onAuthenticationFailure = { surfaced.append($0) } - await env.manager.handleConnectionLoss( + await env.manager.acceptSeededBLELoss( deviceID: UUID(), error: BLEError.connectionFailed("link supervision timeout") ) @@ -48,10 +50,11 @@ struct ConnectionManagerAuthFailureRoutingTests { func `connection loss with no error does not fire the callback`() async throws { let env = try ConnectionManager.createForPairingTesting() defer { env.cleanup() } + env.manager.setTestState(connectionIntent: .wantsConnection()) var surfaced: [UUID] = [] env.manager.onAuthenticationFailure = { surfaced.append($0) } - await env.manager.handleConnectionLoss(deviceID: UUID(), error: nil) + await env.manager.acceptSeededBLELoss(deviceID: UUID(), error: nil) #expect(surfaced.isEmpty) } @@ -60,13 +63,15 @@ struct ConnectionManagerAuthFailureRoutingTests { func `explicit disconnect clears the latch so a new failure episode re-alerts`() async throws { let env = try ConnectionManager.createForPairingTesting() defer { env.cleanup() } + env.manager.setTestState(connectionIntent: .wantsConnection()) let deviceID = UUID() var surfaced: [UUID] = [] env.manager.onAuthenticationFailure = { surfaced.append($0) } - await env.manager.handleConnectionLoss(deviceID: deviceID, error: BLEError.authenticationFailed) + await env.manager.acceptSeededBLELoss(deviceID: deviceID, error: BLEError.authenticationFailed) await env.manager.disconnect(reason: .userInitiated) - await env.manager.handleConnectionLoss(deviceID: deviceID, error: BLEError.authenticationFailed) + env.manager.setTestState(connectionIntent: .wantsConnection()) + await env.manager.acceptSeededBLELoss(deviceID: deviceID, error: BLEError.authenticationFailed) #expect(surfaced == [deviceID, deviceID]) } @@ -75,11 +80,12 @@ struct ConnectionManagerAuthFailureRoutingTests { func `ready promotion clears the latch so a new failure episode re-alerts`() async throws { let env = try ConnectionManager.createForPairingTesting() defer { env.cleanup() } + env.manager.setTestState(connectionIntent: .wantsConnection()) let deviceID = UUID() var surfaced: [UUID] = [] env.manager.onAuthenticationFailure = { surfaced.append($0) } - await env.manager.handleConnectionLoss(deviceID: deviceID, error: BLEError.authenticationFailed) + await env.manager.acceptSeededBLELoss(deviceID: deviceID, error: BLEError.authenticationFailed) #expect(surfaced == [deviceID]) // A successful re-pair reconnects and promotes to .ready; install the @@ -90,17 +96,16 @@ struct ConnectionManagerAuthFailureRoutingTests { connectionState: .connected, services: services, session: session, - connectedDevice: DeviceDTO.testDevice(), + connectedDevice: DeviceDTO.testDevice(id: deviceID), connectionIntent: .wantsConnection() ) - let promoted = await env.manager.promoteToReady( - syncResult: FullSyncResult(contacts: .clean, channels: .clean, messages: .clean), - expectedServices: services, - transportType: .bluetooth + let link = try #require(env.manager.installedLink) + let promoted = await env.manager.completeSync( + link, syncResult: FullSyncResult(contacts: .clean, channels: .clean, messages: .clean) ) #expect(promoted) - await env.manager.handleConnectionLoss(deviceID: deviceID, error: BLEError.authenticationFailed) + await env.manager.acceptSeededBLELoss(deviceID: deviceID, error: BLEError.authenticationFailed) #expect(surfaced == [deviceID, deviceID]) } @@ -108,17 +113,18 @@ struct ConnectionManagerAuthFailureRoutingTests { func `clearing the surfaced-auth latch lets the same device re-alert`() async throws { let env = try ConnectionManager.createForPairingTesting() defer { env.cleanup() } + env.manager.setTestState(connectionIntent: .wantsConnection()) let deviceID = UUID() var surfaced: [UUID] = [] env.manager.onAuthenticationFailure = { surfaced.append($0) } - await env.manager.handleConnectionLoss(deviceID: deviceID, error: BLEError.authenticationFailed) + await env.manager.acceptSeededBLELoss(deviceID: deviceID, error: BLEError.authenticationFailed) #expect(surfaced == [deviceID]) // The foreground path clears the latch so a still-invalid bond re-surfaces // fresh from the foreground reconnect attempt. env.manager.clearSurfacedAuthenticationFailure() - await env.manager.handleConnectionLoss(deviceID: deviceID, error: BLEError.authenticationFailed) + await env.manager.acceptSeededBLELoss(deviceID: deviceID, error: BLEError.authenticationFailed) #expect(surfaced == [deviceID, deviceID]) } @@ -128,35 +134,65 @@ struct ConnectionManagerAuthFailureRoutingTests { func `opportunistic reconnect surfaces authenticationFailed thrown by connect`() async throws { let env = try ConnectionManager.createForPairingTesting() defer { env.cleanup() } + env.manager.setTestState(connectionIntent: .wantsConnection()) let deviceID = UUID() + env.manager.testLastConnectedDeviceID = deviceID var surfaced: [UUID] = [] env.manager.onAuthenticationFailure = { surfaced.append($0) } - // No system pairing registry (the macOS shape), so connect(to:) reaches the - // transport instead of failing the registry check; the transport then fails - // auth the way a radio with an invalidated bond does. This also proves - // connect(to:) rethrows the raw BLEError.authenticationFailed the pattern - // match in attemptOpportunisticReconnect requires. + // An eligible saved target reaches the transport before session startup. env.accessorySetupKit.isSessionActive = false await env.transport.setConnectError(BLEError.authenticationFailed) await env.manager.attemptOpportunisticReconnect(deviceID: deviceID, reason: "test") + let dialedIDs = await env.transport.connectInvocations.map(\.deviceID) + #expect(dialedIDs == [deviceID]) + #expect(env.manager.desiredRequest?.target == .bluetooth(deviceID)) + #expect(env.manager.connectionState == .disconnected) + #expect(env.manager.session == nil) #expect(surfaced == [deviceID]) + _ = await env.manager.disconnect(reason: .userInitiated) } @Test func `opportunistic reconnect stays silent for non-auth connect failures`() async throws { let env = try ConnectionManager.createForPairingTesting() defer { env.cleanup() } + env.manager.setTestState(connectionIntent: .wantsConnection()) + let deviceID = UUID() + env.manager.testLastConnectedDeviceID = deviceID var surfaced: [UUID] = [] env.manager.onAuthenticationFailure = { surfaced.append($0) } - // Default mock registry has no paired accessories, so connect(to:) throws - // ConnectionError.deviceNotFound - a failure that must not trigger the - // pairing-failure recovery alert. + env.accessorySetupKit.isSessionActive = false + await env.transport.setConnectError(BLEError.bluetoothUnavailable) + await env.manager.attemptOpportunisticReconnect(deviceID: deviceID, reason: "test") + + let dialedIDs = await env.transport.connectInvocations.map(\.deviceID) + #expect(dialedIDs == [deviceID]) + #expect(env.manager.connectionState == .disconnected) + #expect(env.manager.session == nil) + #expect(surfaced.isEmpty) + _ = await env.manager.disconnect(reason: .userInitiated) + } + + @Test + func `opportunistic reconnect without an authoritative target does not dial or surface auth`() async throws { + let env = try ConnectionManager.createForPairingTesting() + defer { env.cleanup() } + env.manager.setTestState(connectionIntent: .wantsConnection()) + var surfaced: [UUID] = [] + env.manager.onAuthenticationFailure = { surfaced.append($0) } + env.accessorySetupKit.isSessionActive = false + await env.transport.setConnectError(BLEError.authenticationFailed) + + #expect(env.manager.connectionRequestID == nil) + #expect(env.manager.lastConnectedDeviceID == nil) await env.manager.attemptOpportunisticReconnect(deviceID: UUID(), reason: "test") + #expect(await env.transport.connectInvocations.isEmpty) + #expect(env.manager.connectionRequestID == nil) #expect(surfaced.isEmpty) } @@ -166,14 +202,13 @@ struct ConnectionManagerAuthFailureRoutingTests { func `launch auto-reconnect throwing authenticationFailed surfaces recovery without the watchdog`() async throws { let env = try ConnectionManager.createForPairingTesting() defer { env.cleanup() } + env.manager.setTestState(connectionIntent: .wantsConnection()) let deviceID = UUID() var surfaced: [UUID] = [] env.manager.onAuthenticationFailure = { surfaced.append($0) } - // Model a launch-time auto-reconnect to the last radio whose bond was - // invalidated: no system pairing registry (the macOS shape) so connect(to:) - // reaches the transport, which fails auth. The failure arrives as a thrown - // error on the setup path, never firing onDisconnection. + // Without a system pairing registry, launch-time recovery reaches a transport + // that throws authentication failure before it can emit a lifecycle event. env.manager.testLastConnectedDeviceID = deviceID env.accessorySetupKit.isSessionActive = false await env.transport.setConnectError(BLEError.authenticationFailed) diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAutoReconnectEntryTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAutoReconnectEntryTests.swift index 2a652014c6..dc711011ec 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAutoReconnectEntryTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAutoReconnectEntryTests.swift @@ -25,7 +25,7 @@ struct ConnectionManagerAutoReconnectEntryTests { ) try await waitUntil("auto-reconnect handler should be installed") { - await env.stateMachine.hasAutoReconnectingHandler + await env.transport.hasLifecycleHandler } try await simulateEntry(env, deviceID: deviceID) @@ -36,7 +36,7 @@ struct ConnectionManagerAutoReconnectEntryTests { // The manual claim is released so the retry loop bails without // disconnecting the transport (which would cancel the OS pending connect). - #expect(env.manager.connectingDeviceID == nil) + #expect(env.manager.reconnectionCoordinator.currentCycle?.requestID == env.manager.desiredRequest?.id) #expect(env.manager.connectionState == .connecting) #expect(await env.transport.disconnectInvocations == 0) } @@ -47,6 +47,8 @@ struct ConnectionManagerAutoReconnectEntryTests { defer { env.cleanup() } let manualDeviceID = UUID() let droppedDeviceID = UUID() + let counter = FireCounter() + env.manager.onAutoReconnectStarted = { _ in counter.count += 1 } env.manager.setTestState( connectionState: .connecting, @@ -56,13 +58,14 @@ struct ConnectionManagerAutoReconnectEntryTests { ) try await waitUntil("auto-reconnect handler should be installed") { - await env.stateMachine.hasAutoReconnectingHandler + await env.transport.hasLifecycleHandler } try await simulateEntry(env, deviceID: droppedDeviceID) #expect(env.manager.reconnectionCoordinator.reconnectingDeviceID == nil) - #expect(env.manager.connectingDeviceID == manualDeviceID) + #expect(counter.count == 0) + #expect(env.manager.activeConnectionAttemptDeviceID == manualDeviceID) #expect(env.manager.connectionState == .connecting) } @@ -73,7 +76,7 @@ struct ConnectionManagerAutoReconnectEntryTests { let deviceID = UUID() let counter = FireCounter() - env.manager.onAutoReconnectStarted = { counter.count += 1 } + env.manager.onAutoReconnectStarted = { _ in counter.count += 1 } env.manager.setTestState( connectionState: .connecting, @@ -81,9 +84,10 @@ struct ConnectionManagerAutoReconnectEntryTests { connectionIntent: .wantsConnection(), connectingDeviceID: UUID?.none ) + _ = env.manager.seedBLERecoveryRequest(deviceID: deviceID) try await waitUntil("auto-reconnect handler should be installed") { - await env.stateMachine.hasAutoReconnectingHandler + await env.transport.hasLifecycleHandler } try await simulateEntry(env, deviceID: deviceID) @@ -101,7 +105,7 @@ struct ConnectionManagerAutoReconnectEntryTests { let deviceID = UUID() let counter = FireCounter() - env.manager.onAutoReconnectStarted = { counter.count += 1 } + env.manager.onAutoReconnectStarted = { _ in counter.count += 1 } env.manager.setTestState( connectionState: .connecting, @@ -111,7 +115,7 @@ struct ConnectionManagerAutoReconnectEntryTests { ) try await waitUntil("auto-reconnect handler should be installed") { - await env.stateMachine.hasAutoReconnectingHandler + await env.transport.hasLifecycleHandler } try await simulateEntry(env, deviceID: deviceID) @@ -119,33 +123,6 @@ struct ConnectionManagerAutoReconnectEntryTests { #expect(counter.count == 0) } - @Test - func `manual-connect stand-down for a different device does not notify the loss`() async throws { - let env = try ConnectionManager.createForPairingTesting() - defer { env.cleanup() } - let manualDeviceID = UUID() - let droppedDeviceID = UUID() - - let counter = FireCounter() - env.manager.onAutoReconnectStarted = { counter.count += 1 } - - env.manager.setTestState( - connectionState: .connecting, - currentTransportType: .bluetooth, - connectionIntent: .wantsConnection(), - connectingDeviceID: manualDeviceID - ) - - try await waitUntil("auto-reconnect handler should be installed") { - await env.stateMachine.hasAutoReconnectingHandler - } - - try await simulateEntry(env, deviceID: droppedDeviceID) - - #expect(env.manager.reconnectionCoordinator.reconnectingDeviceID == nil) - #expect(counter.count == 0) - } - @Test func `connection loss after adoption clears the claim and arms the watchdog`() async throws { // Interleaving (a) of the stranded-claim finding: Bluetooth drops during the @@ -164,7 +141,7 @@ struct ConnectionManagerAutoReconnectEntryTests { ) try await waitUntil("auto-reconnect handler should be installed") { - await env.stateMachine.hasAutoReconnectingHandler + await env.transport.hasLifecycleHandler } try await simulateEntry(env, deviceID: deviceID) @@ -172,7 +149,7 @@ struct ConnectionManagerAutoReconnectEntryTests { env.manager.reconnectionCoordinator.reconnectingDeviceID == deviceID } - await env.manager.handleConnectionLoss(deviceID: deviceID, error: nil) + await env.manager.acceptSeededBLELoss(deviceID: deviceID, error: nil) #expect(env.manager.reconnectionCoordinator.reconnectingDeviceID == nil) #expect(env.manager.connectionState == .disconnected) @@ -180,11 +157,14 @@ struct ConnectionManagerAutoReconnectEntryTests { } private func simulateEntry(_ env: PairingTestEnvironment, deviceID: UUID) async throws { - let completions = env.manager.testAutoReconnectEntryCompletions - await env.stateMachine.simulateAutoReconnecting(deviceID: deviceID) - try await waitUntil("auto-reconnect entry should finish") { - env.manager.testAutoReconnectEntryCompletions == completions + 1 + var handled = false + env.manager.testBLELifecycleEventHandled = { event in + guard case let .autoReconnecting(origin, _) = event, origin.deviceID == deviceID else { return } + handled = true } + defer { env.manager.testBLELifecycleEventHandled = nil } + await env.transport.simulateAutoReconnecting(deviceID: deviceID) + try await waitUntil("auto-reconnect entry should finish") { handled } } } diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAutonomousPortTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAutonomousPortTests.swift new file mode 100644 index 0000000000..cf0c709a9f --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAutonomousPortTests.swift @@ -0,0 +1,107 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("Autonomous connection result ownership") +@MainActor +struct ConnectionManagerAutonomousPortTests { + enum Entry { + case foreground + case savedWiFi + } + + enum Outcome { + case success + case failure + case cancellation + } + + struct HandshakeSample: Sendable { + var entry: Entry + var outcome: Outcome + } + + /// Foreground covers each way the old handshake ends. Saved WiFi is the entry that starts on the other transport. + nonisolated static let handshakeSamples: [HandshakeSample] = [ + HandshakeSample(entry: .foreground, outcome: .success), + HandshakeSample(entry: .foreground, outcome: .failure), + HandshakeSample(entry: .foreground, outcome: .cancellation), + HandshakeSample(entry: .savedWiFi, outcome: .success), + ] + + @Test(.timeLimit(.minutes(1)), arguments: handshakeSamples) + func `superseded autonomous handshake cannot resume fallback or replace the admitted choice`(_ sample: HandshakeSample) async throws { + let entry = sample.entry + let outcome = sample.outcome + let env = try ConnectionManagerRadioTestHarness() + let bluetooth = ConnectionMethod.bluetooth(peripheralUUID: env.deviceID, displayName: nil) + let wifi = ConnectionMethod.wifi(host: "saved.test", port: 5123, displayName: nil) + let saved = DeviceDTO.testDevice(id: env.deviceID, isActive: false).copy { + $0.connectionMethods = entry == .savedWiFi ? [bluetooth, wifi] : [wifi, bluetooth] + } + try await env.manager.persistenceStore.saveDevice(saved) + env.manager.testLastConnectedDeviceID = saved.id + env.manager.setTestState(connectionIntent: .wantsConnection()) + await env.manager.wireTransportHandlers() + let oldTransport = entry == .savedWiFi ? env.wifi : env.ble + let nextTransport = entry == .savedWiFi ? env.ble : env.wifi + let nextType: TransportType = entry == .savedWiFi ? .bluetooth : .wifi + await oldTransport.holdReplies(for: .appStart) + if outcome == .failure { await oldTransport.rejectNext(.appStart) } + var synced: [UUID] = [] + var authFailures: [UUID] = [] + env.manager.onDeviceSynced = { snapshot, _ in synced.append(snapshot.generation) } + env.manager.onAuthenticationFailure = { authFailures.append($0) } + let recovery = Task { + switch entry { + case .foreground: await env.manager.checkBLEConnectionHealth() + case .savedWiFi: await env.manager.checkWiFiConnectionHealth() + } + } + var replacement: Task? + do { + try await waitUntil("the autonomous entry must reach a real held handshake result") { + await oldTransport.heldReplyCount(for: .appStart) == 1 + } + let request = try #require(env.manager.desiredRequest) + let resource = try #require(request.attempt?.resource) + replacement = Task { try await env.connect(nextType) } + try await waitUntil("the explicit choice must supersede the autonomous request") { + env.manager.connectionRequestID != request.id + } + let nextRequestID = env.manager.connectionRequestID + #expect(!resource.binding.isActive) + #expect(env.manager.currentConnection == nil) + #expect(await nextTransport.connectCount == 0) + if outcome == .cancellation { recovery.cancel() } + await oldTransport.releaseReplies(for: .appStart) + await recovery.value + let result = try await #require(replacement).value + #expect(env.manager.isCurrent(result)) + let current = try #require(env.manager.currentConnection) + #expect(env.manager.connectionRequestID == nextRequestID) + #expect(current.transportType == nextType) + #expect(current.device.radioID == saved.radioID) + #expect(env.manager.connectionState == .ready) + #expect(env.manager.connectionIntent.wantsConnection) + #expect(!env.manager.isReconnectionWatchdogRunning) + #expect(synced == [current.generation]) + #expect(authFailures.isEmpty) + #expect(await oldTransport.connectCount == 1) + #expect(await nextTransport.connectCount == 1) + #expect(await resource.session.subscriberCountForTest == 0) + #expect(try await current.services.session.getTime().timeIntervalSince1970 > 0) + } catch { + recovery.cancel() + replacement?.cancel() + await env.ble.releaseAllGates() + await env.wifi.releaseAllGates() + await recovery.value + _ = await replacement?.result + await env.close() + throw error + } + await env.close() + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAvailabilityRecoveryTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAvailabilityRecoveryTests.swift new file mode 100644 index 0000000000..92b0994b68 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerAvailabilityRecoveryTests.swift @@ -0,0 +1,138 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Bluetooth availability and launch recovery") +@MainActor +struct ConnectionManagerAvailabilityRecoveryTests { + @Test(arguments: [BLEError.bluetoothPoweredOff, .bluetoothUnavailable, .bluetoothUnauthorized], [false, true]) + func `availability recovery within cooldown installs a working session`(error: BLEError, dualTransport: Bool) async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + await env.manager.wireTransportHandlers() + let saved = savedDevice(env, wifiLast: dualTransport ? false : nil) + try await env.manager.persistenceStore.saveDevice(saved) + await env.wifi.setConnectError(WiFiTransportError.notConnected) + await env.ble.setConnectError(error) + await env.manager.reconnectLastUsedTransport(device: saved, lastDeviceID: saved.id) + try #require(env.manager.connectionState == .disconnected) + #expect(await env.ble.connectCount == 1) + #expect(await env.wifi.connectCount == (dualTransport ? 1 : 0)) + #expect(env.manager.isReconnectionWatchdogRunning) + #expect(env.manager.shouldAllowConnection(force: false), "Bluetooth availability must not consume the retry cooldown") + + let failedRequestID = env.manager.connectionRequestID + await env.ble.setConnectError(nil) + let handled = env.manager.testBluetoothPoweredOnHandlerRuns + await env.stateMachine.simulateBluetoothPoweredOn() + try await waitUntil("installed power-on callback must finish its recovery request") { + env.manager.testBluetoothPoweredOnHandlerRuns == handled + 1 + } + + #expect(env.manager.connectionRequestID != failedRequestID) + #expect(await env.ble.connectCount == 2) + #expect(env.manager.connectionState == .ready) + #expect(env.manager.connectedDevice?.radioID == saved.radioID) + let session = try #require(env.manager.session) + #expect(try await session.getTime().timeIntervalSince1970 > 0) + } catch { await env.close(); throw error } + await env.close() + } + + @Test + func `failed owned power-on recovery keeps a watchdog that can exchange frames`() async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + await env.manager.wireTransportHandlers() + let saved = savedDevice(env, wifiLast: nil) + try await env.manager.persistenceStore.saveDevice(saved) + await env.ble.setConnectError(BLEError.deviceNotFound) + await env.manager.reconnectLastUsedTransport(device: saved, lastDeviceID: saved.id) + try #require(env.manager.isReconnectionWatchdogRunning) + env.manager.stopReconnectionWatchdog() + env.manager.setCircuitBreakerOpenForTesting(since: .distantPast) + env.manager.testWatchdogInitialDelay = .milliseconds(1) + + let failedLaunchRequestID = env.manager.connectionRequestID + var failedPowerOnRequestID: UUID? + env.manager.onConnectionLost = { receipt in + env.manager.onConnectionLost = nil + failedPowerOnRequestID = receipt.requestID + #expect(env.manager.connectionRequestID == receipt.requestID) + #expect(receipt.requestID != failedLaunchRequestID) + #expect(await env.ble.connectCount == 2) + #expect(env.manager.connectionState == .disconnected) + #expect(!env.manager.isReconnectionWatchdogRunning) + await env.ble.setConnectError(nil) + env.manager.setCircuitBreakerOpenForTesting(since: .distantPast) + } + let handled = env.manager.testBluetoothPoweredOnHandlerRuns + await env.stateMachine.simulateBluetoothPoweredOn() + try await waitUntil(timeout: .seconds(3), "owned power-on failure must re-arm a watchdog that establishes a usable session") { + env.manager.connectionState == .ready + } + + let exhaustedRequestID = try #require(failedPowerOnRequestID) + #expect(env.manager.testBluetoothPoweredOnHandlerRuns == handled + 1) + #expect(env.manager.connectionRequestID != exhaustedRequestID) + #expect(await env.ble.connectCount == 3) + #expect(env.manager.connectedDevice?.radioID == saved.radioID) + let session = try #require(env.manager.session) + #expect(try await session.getTime().timeIntervalSince1970 > 0) + } catch { await env.close(); throw error } + await env.close() + } + + @Test(arguments: [false, true]) + func `exhausted dual-transport launch retains Bluetooth watchdog recovery`(wifiLast: Bool) async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + let saved = savedDevice(env, wifiLast: wifiLast) + try await env.manager.persistenceStore.saveDevice(saved) + await env.ble.setConnectError(BLEError.deviceNotFound) + await env.wifi.setConnectError(WiFiTransportError.notConnected) + env.manager.testWatchdogInitialDelay = .milliseconds(1) + var failedRequestID: UUID? + env.manager.onConnectionLost = { receipt in + env.manager.onConnectionLost = nil + failedRequestID = receipt.requestID + let bluetooth = ConnectionRequest.Target.bluetooth(env.deviceID) + let wifi = ConnectionRequest.Target.wifi(host: "radio.test", port: 5123) + #expect(env.manager.desiredRequest?.id == receipt.requestID) + #expect(env.manager.desiredRequest?.targets == (wifiLast ? [wifi, bluetooth] : [bluetooth, wifi])) + #expect(env.manager.desiredRequest?.target == bluetooth, "An exhausted launch must retain the Bluetooth target its watchdog can retry") + #expect(await env.ble.connectCount == 1) + #expect(await env.wifi.connectCount == 1) + #expect(env.manager.connectionState == .disconnected) + await env.ble.setConnectError(nil) + env.manager.setCircuitBreakerOpenForTesting(since: .distantPast) + } + await env.manager.reconnectLastUsedTransport(device: saved, lastDeviceID: saved.id) + try await waitUntil(timeout: .seconds(3), "launch watchdog must recover Bluetooth after both transports fail") { + env.manager.connectionState == .ready + } + + let exhaustedRequestID = try #require(failedRequestID) + #expect(await env.ble.connectCount == 2) + #expect(await env.wifi.connectCount == 1) + #expect(env.manager.connectionRequestID != exhaustedRequestID) + #expect(env.manager.currentTransportType == .bluetooth) + #expect(env.manager.connectedDevice?.radioID == saved.radioID) + let session = try #require(env.manager.session) + #expect(try await session.getTime().timeIntervalSince1970 > 0) + } catch { await env.close(); throw error } + await env.close() + } + + private func savedDevice(_ env: ConnectionManagerRadioTestHarness, wifiLast: Bool?) -> DeviceDTO { + let bluetooth = ConnectionMethod.bluetooth(peripheralUUID: env.deviceID, displayName: nil) + let wifi = ConnectionMethod.wifi(host: "radio.test", port: 5123, displayName: nil) + return DeviceDTO.testDevice(id: env.deviceID, publicKey: env.ble.publicKey, isActive: false).copy { + if let wifiLast { + $0.connectionMethods = wifiLast ? [bluetooth, wifi] : [wifi, bluetooth] + } else { + $0.connectionMethods = [bluetooth] + } + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerBLEAttemptOwnershipTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerBLEAttemptOwnershipTests.swift new file mode 100644 index 0000000000..c303b609fb --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerBLEAttemptOwnershipTests.swift @@ -0,0 +1,295 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import os +import Testing + +@Suite("BLE attempt retirement ownership") +@MainActor +struct ConnectionManagerBLEAttemptOwnershipTests { + @Test(.timeLimit(.minutes(1))) + func `replacement joins a failed unpublished candidate until its actual send settles`() async throws { + let env = try ConnectionManagerRadioTestHarness() + await env.ble.holdNextSendCompletion() + let first = Task { try await env.connect(.bluetooth) } + var replacement: Task? + do { + try await waitUntil("candidate appStart should remain physically in flight") { await env.ble.sendCompletionIsHeld } + let request = try #require(env.manager.desiredRequest) + let attempt = try #require(request.attempt) + let oldSession = try #require(attempt.resource?.session) + var cleanupEntered = false + env.manager.testCandidateRetirementHandler = { binding in + if binding === attempt.binding { cleanupEntered = true } + } + first.cancel() + try await waitUntil("cancelled setup should enter captured candidate retirement") { cleanupEntered } + #expect(request.attempt === attempt) + #expect(!attempt.binding.isActive) + #expect(env.manager.currentConnection == nil) + let target = UUID() + let next = Task { try await env.manager.connect(to: target, forceReconnect: true) } + replacement = next + try await waitUntil("replacement should be admitted behind actual candidate drain") { + env.manager.desiredRequest?.target.deviceID == target + } + #expect(await env.ble.connectCount == 1) + #expect(await env.ble.sendCompletionIsHeld) + await env.ble.releaseSendCompletion() + _ = await first.result + guard case let .operational(current) = try await next.value else { throw ConnectionError.notConnected } + #expect(current.device.id == target) + #expect(env.manager.isCurrent(current)) + #expect(await oldSession.subscriberCountForTest == 0) + _ = try await current.services.session.getTime() + } catch { + first.cancel() + replacement?.cancel() + env.manager.testCandidateRetirementHandler = nil + await env.ble.releaseAllGates() + await env.close() + _ = await first.result + _ = await replacement?.result + throw error + } + env.manager.testCandidateRetirementHandler = nil + await env.close() + } + + @Test(.timeLimit(.minutes(1))) + func `late cleanup from an old rebuild cannot retire the next attempt in the same request`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let metadata = Gate() + let cleanup = Gate() + let deliveries = OSAllocatedUnfairLock<[Task]>(initialState: []) + do { + _ = try await env.connect(.bluetooth) + let requestID = env.manager.connectionRequestID + await env.ble.setLifecycleHandler { [weak manager = env.manager] event in + let worker = Task { @MainActor in + guard let manager else { return } + await manager.handleBLELifecycleEvent(event) + } + deliveries.withLock { $0.append(worker) } + } + var selections = 0 + env.manager.testConnectionSelectionHandler = { _ in + selections += 1 + if selections == 1 { await metadata.wait() } + } + + await env.ble.simulateAutoReconnecting(deviceID: env.deviceID) + let firstLoss = try #require(deliveries.withLock { $0.last }) + await firstLoss.value + await env.ble.simulateReconnected() + let firstCompletion = try #require(deliveries.withLock { $0.last }) + try await waitUntil("first rebuild should hold accepted metadata") { metadata.isWaiting } + let oldAttempt = try #require(env.manager.desiredRequest?.attempt) + env.manager.testCandidateRetirementHandler = { binding in + if binding === oldAttempt.binding { await cleanup.wait() } + } + + await env.ble.simulateAutoReconnecting(deviceID: env.deviceID) + let secondLoss = try #require(deliveries.withLock { $0.last }) + await secondLoss.value + await env.ble.simulateReconnected() + let secondCompletion = try #require(deliveries.withLock { $0.last }) + #expect(await env.ble.sentData.filter { $0.first == CommandCode.appStart.rawValue }.count == 2) + metadata.open() + + try await waitUntil("old cleanup should park while the next attempt installs") { cleanup.isWaiting } + try await waitUntil("second cycle should complete the real handshake and sync") { env.manager.connectionState == .ready } + let current = try #require(env.manager.currentConnection) + let currentBinding = try #require(env.manager.installedLink?.resource.binding) + #expect(env.manager.connectionRequestID == requestID) + #expect(currentBinding !== oldAttempt.binding) + #expect(currentBinding.isActive) + cleanup.open() + await firstCompletion.value + await secondCompletion.value + #expect(env.manager.isCurrent(current)) + #expect(currentBinding.isActive) + #expect(await env.ble.connectCount == 1) + _ = try await current.services.session.getTime() + } catch { + metadata.open() + cleanup.open() + env.manager.testConnectionSelectionHandler = nil + env.manager.testCandidateRetirementHandler = nil + await env.close() + for worker in deliveries.withLock({ $0 }) { + await worker.value + } + throw error + } + env.manager.testConnectionSelectionHandler = nil + env.manager.testCandidateRetirementHandler = nil + await env.close() + for worker in deliveries.withLock({ $0 }) { + await worker.value + } + } + + @Test(.timeLimit(.minutes(1))) + func `caller cancelled before publication lets the same request recover`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let selection = Gate() + let deliveries = OSAllocatedUnfairLock<[Task]>(initialState: []) + var connecting: Task? + do { + try await installLifecycleDeliveries(env, deliveries: deliveries) + env.manager.testConnectionSelectionHandler = { _ in await selection.wait() } + connecting = Task { try await env.connect(.bluetooth) } + try await waitUntil("selection should hold the unpublished attempt") { selection.isWaiting } + let requestID = try #require(env.manager.connectionRequestID) + #expect(env.manager.desiredRequest?.committedGeneration == nil) + let appStartsAtCancel = await env.ble.sentData.filter { $0.first == CommandCode.appStart.rawValue }.count + connecting?.cancel() + try await waitUntil("caller cancellation should reach the admission worker") { + env.manager.desiredRequest?.worker?.isCancelled == true + } + selection.open() + let outcome = try await #require(connecting).value + if case .cancelled = outcome {} else { Issue.record("Cancelled caller returned another outcome") } + #expect(env.manager.connectionRequestID == requestID) + #expect(env.manager.connectionIntent.wantsConnection) + #expect(env.manager.desiredRequest?.committedGeneration == nil) + + await env.ble.simulateAutoReconnecting(deviceID: env.deviceID) + try await #require(deliveries.withLock { $0.last }).value + await env.ble.simulateReconnected() + try await #require(deliveries.withLock { $0.last }).value + try await waitUntil("same request recovery should publish") { env.manager.connectionState == .ready } + #expect(env.manager.connectionRequestID == requestID) + #expect(env.manager.services != nil) + #expect(await env.ble.sentData.filter { $0.first == CommandCode.appStart.rawValue }.count > appStartsAtCancel) + #expect(try await env.manager.session?.getTime() != nil) + } catch { + selection.open() + connecting?.cancel() + env.manager.testConnectionSelectionHandler = nil + await env.close() + _ = await connecting?.result + for worker in deliveries.withLock({ $0 }) { + await worker.value + } + throw error + } + env.manager.testConnectionSelectionHandler = nil + await env.close() + for worker in deliveries.withLock({ $0 }) { + await worker.value + } + } + + @Test(.timeLimit(.minutes(1))) + func `caller cancellation after the next attempt is installed keeps that binding`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let admissionSelection = Gate() + let recoverySelection = Gate() + let cancelHop = Gate() + let deliveries = OSAllocatedUnfairLock<[Task]>(initialState: []) + var connecting: Task? + var selections = 0 + do { + try await installLifecycleDeliveries(env, deliveries: deliveries) + env.manager.testConnectionSelectionHandler = { _ in + selections += 1 + if selections == 1 { await admissionSelection.wait() } + if selections == 2 { await recoverySelection.wait() } + } + env.manager.testAdmissionCancellationHandler = { await cancelHop.wait() } + connecting = Task { try await env.connect(.bluetooth) } + try await waitUntil("admission should hold before publication") { admissionSelection.isWaiting } + let requestID = try #require(env.manager.connectionRequestID) + connecting?.cancel() + try await waitUntil("cancel hop should pause before it revokes") { cancelHop.isWaiting } + let admissionBinding = try #require(env.manager.desiredRequest?.admissionBinding) + admissionSelection.open() + let outcome = try await #require(connecting).value + if case .cancelled = outcome {} else { Issue.record("Cancelled caller returned another outcome") } + #expect(env.manager.desiredRequest?.committedGeneration == nil) + let appStartsBeforeRecovery = await env.ble.sentData.filter { $0.first == CommandCode.appStart.rawValue }.count + + await env.ble.simulateAutoReconnecting(deviceID: env.deviceID) + try await #require(deliveries.withLock { $0.last }).value + await env.ble.simulateReconnected() + let completion = try #require(deliveries.withLock { $0.last }) + try await waitUntil("recovery should install the next attempt before publication") { recoverySelection.isWaiting } + let recoveryBinding = try #require(env.manager.desiredRequest?.binding) + #expect(recoveryBinding !== admissionBinding) + #expect(recoveryBinding.isActive) + #expect(env.manager.desiredRequest?.committedGeneration == nil) + cancelHop.open() + try await waitUntil("cancel hop should revoke the admission binding") { + env.manager.testAdmissionCancellationFinished + } + #expect(recoveryBinding.isActive) + #expect(env.manager.connectionRequestID == requestID) + recoverySelection.open() + await completion.value + try await waitUntil("same request should reach ready with the recovery binding") { + env.manager.connectionState == .ready + } + #expect(env.manager.connectionRequestID == requestID) + #expect(recoveryBinding.isActive) + #expect(env.manager.services != nil) + #expect(await env.ble.sentData.filter { $0.first == CommandCode.appStart.rawValue }.count > appStartsBeforeRecovery) + #expect(try await env.manager.session?.getTime() != nil) + } catch { + admissionSelection.open() + recoverySelection.open() + cancelHop.open() + connecting?.cancel() + env.manager.testConnectionSelectionHandler = nil + env.manager.testAdmissionCancellationHandler = nil + await env.close() + _ = await connecting?.result + for worker in deliveries.withLock({ $0 }) { + await worker.value + } + throw error + } + env.manager.testConnectionSelectionHandler = nil + env.manager.testAdmissionCancellationHandler = nil + await env.close() + for worker in deliveries.withLock({ $0 }) { + await worker.value + } + } + + private func installLifecycleDeliveries( + _ env: ConnectionManagerRadioTestHarness, + deliveries: OSAllocatedUnfairLock<[Task]> + ) async throws { + try await waitUntil("default lifecycle handler should be installed") { await env.ble.hasLifecycleHandler } + await env.ble.setLifecycleHandler { [weak manager = env.manager] event in + let worker = Task { @MainActor in + guard let manager else { return } + await manager.handleBLELifecycleEvent(event) + } + deliveries.withLock { $0.append(worker) } + } + } + + @MainActor + private final class Gate { + private var continuation: CheckedContinuation? + private var isOpen = false + var isWaiting: Bool { + continuation != nil + } + + func wait() async { + guard !isOpen else { return } + await withCheckedContinuation { continuation = $0 } + } + + func open() { + isOpen = true + let waiting = continuation + continuation = nil + waiting?.resume() + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerBLEHealthTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerBLEHealthTests.swift index b19d9a0687..da16940d59 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerBLEHealthTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerBLEHealthTests.swift @@ -2,9 +2,6 @@ import Foundation @testable import MC1Services import Testing -/// Tests for ConnectionManager.checkBLEConnectionHealth() - stale connection state detection. -/// Verifies the fix from commit b2ab8f17 that detects when connectionState is stale after -/// iOS terminates BLE connection while app is suspended. @Suite("ConnectionManager BLE Health Check Tests") @MainActor struct ConnectionManagerBLEHealthTests { @@ -50,7 +47,7 @@ struct ConnectionManagerBLEHealthTests { manager.setTestState( connectionState: .ready, currentTransportType: .bluetooth, - connectionIntent: .none + connectionIntent: ConnectionIntent.none ) manager.testLastConnectedDeviceID = UUID() @@ -82,13 +79,9 @@ struct ConnectionManagerBLEHealthTests { let (manager, mock) = try ConnectionManager.createForTesting() let deviceID = UUID() let (session, services, device) = try await makeServices(deviceID: deviceID, startEventMonitoring: true) - let tracker = SessionRebuildTracker() await mock.setStubbedIsConnected(true) await mock.setStubbedConnectedDeviceID(deviceID) - manager.rebuildSessionForHealthCheckOverride = { deviceID in - await tracker.record(deviceID) - } manager.setTestState( connectionState: .ready, @@ -105,7 +98,7 @@ struct ConnectionManagerBLEHealthTests { #expect(manager.connectionState == .ready) #expect(services.isEventMonitoringActive) #expect(await services.messagePollingService.isAutoFetching) - #expect(await tracker.recordedCalls().isEmpty) + #expect(manager.session === session) } @Test @@ -178,6 +171,7 @@ struct ConnectionManagerBLEHealthTests { await mock.setStubbedIsConnected(false) await mock.setStubbedIsAutoReconnecting(false) + _ = manager.seedBLERecoveryRequest(deviceID: deviceID) manager.setTestState( connectionState: .disconnected, currentTransportType: .bluetooth, @@ -189,37 +183,28 @@ struct ConnectionManagerBLEHealthTests { await manager.checkBLEConnectionHealth() #expect(manager.connectionState == .disconnected) - #expect(manager.sessionRebuildDeviceID == deviceID) + #expect(manager.reconnectionCoordinator.reconnectingDeviceID == deviceID) } // MARK: - Connected Transport App-Stack Reconciliation Tests @Test func `BLE connected with missing session and services rebuilds app stack`() async throws { - let (manager, mock) = try ConnectionManager.createForTesting() - let deviceID = UUID() - let tracker = SessionRebuildTracker() - - await mock.setStubbedIsConnected(true) - await mock.setStubbedConnectedDeviceID(deviceID) - await mock.setStubbedIsAutoReconnecting(false) - manager.rebuildSessionForHealthCheckOverride = { deviceID in - await tracker.record(deviceID) - } - - manager.setTestState( - connectionState: .disconnected, - services: nil, - session: nil, - connectedDevice: nil, - currentTransportType: .bluetooth, - connectionIntent: .wantsConnection() - ) - manager.testLastConnectedDeviceID = deviceID - - await manager.checkBLEConnectionHealth() - - #expect(await tracker.recordedCalls() == [deviceID]) + let harness = try ConnectionManagerRadioTestHarness() + do { + await harness.ble.primePhysicalLink(deviceID: harness.deviceID) + await harness.stateMachine.setStubbedIsConnected(true) + await harness.stateMachine.setStubbedConnectedDeviceID(harness.deviceID) + harness.manager.testLastConnectedDeviceID = harness.deviceID + harness.manager.setTestState(connectionIntent: .wantsConnection()) + await harness.manager.checkBLEConnectionHealth() + #expect(harness.manager.connectionState == .ready) + #expect(harness.manager.connectedDevice?.id == harness.deviceID) + #expect(await harness.ble.connectCount == 0) + #expect(await harness.ble.sentData.contains { $0.first == CommandCode.appStart.rawValue }) + _ = try await harness.manager.session?.getTime() + await harness.close() + } catch { await harness.close(); throw error } } @Test @@ -255,14 +240,10 @@ struct ConnectionManagerBLEHealthTests { let (manager, mock) = try ConnectionManager.createForTesting() let deviceID = UUID() let (session, services, device) = try await makeServices(deviceID: deviceID, startEventMonitoring: true) - let tracker = SessionRebuildTracker() await mock.setStubbedIsConnected(true) await mock.setStubbedConnectedDeviceID(deviceID) await mock.setStubbedIsAutoReconnecting(false) - manager.rebuildSessionForHealthCheckOverride = { deviceID in - await tracker.record(deviceID) - } manager.setTestState( connectionState: .ready, services: services, @@ -275,7 +256,7 @@ struct ConnectionManagerBLEHealthTests { await manager.checkBLEConnectionHealth() - #expect(await tracker.recordedCalls().isEmpty) + #expect(manager.session === session) #expect(services.isEventMonitoringActive) #expect(await services.messagePollingService.isAutoFetching) } @@ -284,14 +265,11 @@ struct ConnectionManagerBLEHealthTests { func `BLE connected skips duplicate recovery while session rebuild is active`() async throws { let (manager, mock) = try ConnectionManager.createForTesting() let deviceID = UUID() - let tracker = SessionRebuildTracker() await mock.setStubbedIsConnected(true) await mock.setStubbedConnectedDeviceID(deviceID) await mock.setStubbedIsAutoReconnecting(false) - manager.rebuildSessionForHealthCheckOverride = { deviceID in - await tracker.record(deviceID) - } + _ = manager.seedBLERecoveryRequest(deviceID: deviceID) manager.setTestState( connectionState: .disconnected, services: nil, @@ -305,8 +283,8 @@ struct ConnectionManagerBLEHealthTests { await manager.checkBLEConnectionHealth() - #expect(await tracker.recordedCalls().isEmpty) - #expect(manager.sessionRebuildDeviceID == deviceID) + #expect(manager.session == nil) + #expect(manager.reconnectionCoordinator.reconnectingDeviceID == deviceID) } @Test @@ -356,6 +334,7 @@ struct ConnectionManagerBLEHealthTests { func `detects stale state when connectionState is .ready but BLE disconnected`() async throws { let (manager, mock) = try ConnectionManager.createForTesting() let deviceID = UUID() + _ = manager.seedBLERecoveryRequest(deviceID: deviceID) // BLE is actually disconnected await mock.setStubbedIsConnected(false) @@ -380,6 +359,7 @@ struct ConnectionManagerBLEHealthTests { func `detects stale state when connectionState is .connected but BLE disconnected`() async throws { let (manager, mock) = try ConnectionManager.createForTesting() let deviceID = UUID() + _ = manager.seedBLERecoveryRequest(deviceID: deviceID) // BLE is actually disconnected await mock.setStubbedIsConnected(false) @@ -404,6 +384,7 @@ struct ConnectionManagerBLEHealthTests { func `detects stale state when connectionState is .syncing but BLE disconnected`() async throws { let (manager, mock) = try ConnectionManager.createForTesting() let deviceID = UUID() + _ = manager.seedBLERecoveryRequest(deviceID: deviceID) await mock.setStubbedIsConnected(false) await mock.setStubbedIsAutoReconnecting(false) @@ -455,6 +436,7 @@ struct ConnectionManagerBLEHealthTests { func `calls onConnectionLost when stale state detected`() async throws { let (manager, mock) = try ConnectionManager.createForTesting() let deviceID = UUID() + _ = manager.seedBLERecoveryRequest(deviceID: deviceID) await mock.setStubbedIsConnected(false) await mock.setStubbedIsAutoReconnecting(false) @@ -468,7 +450,7 @@ struct ConnectionManagerBLEHealthTests { manager.testLastConnectedDeviceID = deviceID let tracker = ConnectionLostTracker() - manager.onConnectionLost = { + manager.onConnectionLost = { _ in await tracker.markConnectionLost() } @@ -581,7 +563,7 @@ struct ConnectionManagerBLEHealthTests { manager.setTestState( connectionState: .disconnected, currentTransportType: .bluetooth, - connectionIntent: .none + connectionIntent: ConnectionIntent.none ) await manager.appDidBecomeActive() @@ -615,15 +597,3 @@ private actor ConnectionLostTracker { connectionLostCalled = true } } - -private actor SessionRebuildTracker { - private var calls: [UUID] = [] - - func record(_ deviceID: UUID) { - calls.append(deviceID) - } - - func recordedCalls() -> [UUID] { - calls - } -} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerCapabilityPortTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerCapabilityPortTests.swift new file mode 100644 index 0000000000..24a01cdbf8 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerCapabilityPortTests.swift @@ -0,0 +1,69 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("Capability result retirement ownership") +@MainActor +struct ConnectionManagerCapabilityPortTests { + @Test(.timeLimit(.minutes(1))) + func `late capabilities drain before the same-radio successor sets its platform and pacing`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let saved = DeviceDTO.testDevice(id: env.deviceID) + try await env.manager.persistenceStore.saveDevice(saved) + await env.ble.setResponsePackets(for: .deviceQuery, packets: [capabilities(model: "T1000-E")]) + await env.ble.holdReplies(for: .deviceQuery) + let old = Task { try await env.connect(.bluetooth) } + var replacement: Task? + do { + try await waitUntil("the old capability reply must be held after the actual query") { + await env.ble.heldReplyCount(for: .deviceQuery) == 1 + } + let request = try #require(env.manager.desiredRequest) + let resource = try #require(request.attempt?.resource) + await env.ble.setResponsePackets(for: .deviceQuery, packets: [capabilities(model: "Heltec V3")]) + replacement = Task { try await env.connect(.bluetooth) } + try await waitUntil("the same-radio successor must revoke the old attempt") { + env.manager.connectionRequestID != request.id + } + #expect(!resource.binding.isActive) + #expect(env.manager.currentConnection == nil) + #expect(env.manager.detectedPlatform == .unknown) + #expect(await env.ble.connectCount == 1) + await env.ble.releaseReplies(for: .deviceQuery) + _ = await old.result + let result = try await #require(replacement).value + #expect(env.manager.isCurrent(result)) + let current = try #require(env.manager.currentConnection) + #expect(current.device.id == env.deviceID) + #expect(current.device.radioID == saved.radioID) + #expect(current.device.manufacturerName == "Heltec V3") + #expect(env.manager.detectedPlatform == .esp32) + #expect(await env.stateMachine.writePacingDelay == DevicePlatform.esp32.recommendedWritePacing) + #expect(await env.ble.connectCount == 2) + #expect(await resource.session.subscriberCountForTest == 0) + #expect(try await current.services.session.getTime().timeIntervalSince1970 > 0) + } catch { + old.cancel() + replacement?.cancel() + await env.ble.releaseAllGates() + _ = await old.result + _ = await replacement?.result + await env.close() + throw error + } + await env.close() + } + + private func capabilities(model: String) -> Data { + let modelOffset = 20 + var packet = Data(repeating: 0, count: 80) + packet[0] = ResponseCode.deviceInfo.rawValue + packet[1] = 14 + packet[2] = 1 + packet[3] = 1 + let bytes = Data(model.utf8.prefix(40)) + packet.replaceSubrange(modelOffset..<(modelOffset + bytes.count), with: bytes) + return packet + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerCircuitBreakerTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerCircuitBreakerTests.swift index 9567eaf93d..f56f5d14de 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerCircuitBreakerTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerCircuitBreakerTests.swift @@ -87,8 +87,12 @@ struct ConnectionManagerCircuitBreakerTests { let (manager, _) = try ConnectionManager.createForTesting() manager.recordConnectionFailure() - await #expect(throws: BLEError.self) { + try await #expect { try await manager.connect(to: UUID()) + } throws: { error in + guard let failure = error as? ConnectionRequestFailure, + manager.isCurrent(failure), case BLEError.connectionFailed = failure.underlying else { return false } + return true } } } diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerDisconnectDiagnosticsTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerDisconnectDiagnosticsTests.swift index d8ac42b35f..5887fb50f6 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerDisconnectDiagnosticsTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerDisconnectDiagnosticsTests.swift @@ -13,7 +13,9 @@ struct ConnectionManagerDisconnectDiagnosticsTests { @Test func `auto-reconnect entry persists disconnect diagnostic with error info`() async throws { - let (manager, mock) = try ConnectionManager.createForTesting(defaults: defaults) + let env = try ConnectionManager.createForPairingTesting(defaults: defaults) + defer { env.cleanup() } + let manager = env.manager let deviceID = UUID() manager.setTestState( connectionState: .ready, @@ -21,24 +23,20 @@ struct ConnectionManagerDisconnectDiagnosticsTests { connectionIntent: .wantsConnection() ) - // Wait for ConnectionManager init to wire auto-reconnect handler. + _ = manager.seedBLERecoveryRequest(deviceID: deviceID) try await waitUntil("auto-reconnect handler should be installed") { - await mock.hasAutoReconnectingHandler + await env.transport.hasLifecycleHandler } - await mock.simulateAutoReconnecting( + await env.transport.simulateAutoReconnecting( deviceID: deviceID, errorInfo: "domain=CBErrorDomain, code=15, desc=Failed to encrypt" ) - // Wait for both the .connecting state transition and the diagnostic write — - // the handler claims the cycle (sync) before running the state-machine - // queries that feed the diagnostic, so observing only the state can race - // ahead of the persistDisconnectDiagnostic call. try await waitUntil("connectionState should transition to .connecting and diagnostic should be persisted") { manager.connectionState == .connecting && (manager.lastDisconnectDiagnostic ?? "") - .localizedStandardContains("source=bleStateMachine.autoReconnectingHandler") + .localizedStandardContains("source=ble.autoReconnecting") } let diagnostic = manager.lastDisconnectDiagnostic ?? "" @@ -48,7 +46,9 @@ struct ConnectionManagerDisconnectDiagnosticsTests { @Test func `auto-reconnect entry skips the claim but tears down the stale OLD session during pairing`() async throws { - let (manager, mock) = try ConnectionManager.createForTesting(defaults: defaults) + let env = try ConnectionManager.createForPairingTesting(defaults: defaults) + defer { env.cleanup() } + let manager = env.manager let oldDeviceID = UUID() manager.setTestState( @@ -59,28 +59,23 @@ struct ConnectionManagerDisconnectDiagnosticsTests { isPairingInProgress: true ) + _ = manager.seedBLERecoveryRequest(deviceID: oldDeviceID) try await waitUntil("auto-reconnect handler should be installed") { - await mock.hasAutoReconnectingHandler + await env.transport.hasLifecycleHandler } - await mock.simulateAutoReconnecting(deviceID: oldDeviceID) + await env.transport.simulateAutoReconnecting(deviceID: oldDeviceID) - // Wait for the gate's teardown path to run. handleConnectionLoss transitions - // state to .disconnected and clears connectedDevice; observing both confirms - // teardown completed without claiming a reconnect cycle. try await waitUntil("suppression branch should tear down OLD session") { manager.connectionState == .disconnected && manager.connectedDevice == nil } - #expect(manager.activeReconnectDeviceID == nil, "Claim must remain unset so pairing's connect(to:) is not preempted") + #expect(manager.reconnectionCoordinator.reconnectingDeviceID == nil, "Claim must remain unset so pairing's connect(to:) is not preempted") #expect(manager.connectionState == .disconnected, "OLD session is dead — UI must not stay on .ready") #expect(manager.connectedDevice == nil, "Stale connectedDevice must be cleared so message sends fail loudly instead of silently") - // The suppression gate runs before the diagnostic preamble, so - // `handleConnectionLoss`'s diagnostic is the only writer for this branch - // and is the observable proof the suppression branch took the loss path. let diagnostic = manager.lastDisconnectDiagnostic ?? "" - #expect(diagnostic.localizedStandardContains("source=handleConnectionLoss")) + #expect(diagnostic.localizedStandardContains("source=ble.autoReconnecting")) } @Test @@ -103,7 +98,7 @@ struct ConnectionManagerDisconnectDiagnosticsTests { let diagnostic = manager.lastDisconnectDiagnostic ?? "" #expect( - diagnostic.localizedStandardContains("source=checkBLEConnectionHealth.otherAppConnected") + diagnostic.localizedStandardContains("source=ble.otherAppConnected") ) #expect(manager.connectionIntent.wantsConnection) #expect(manager.isReconnectionWatchdogRunning) @@ -136,7 +131,7 @@ struct ConnectionManagerDisconnectDiagnosticsTests { let diagnostic = manager.lastDisconnectDiagnostic ?? "" #expect( - diagnostic.localizedStandardContains("source=checkBLEConnectionHealth.adoptSystemConnectedPeripheral") + diagnostic.localizedStandardContains("source=ble.adoptSystemConnectedPeripheral") ) #expect(manager.connectionState == .connecting) #expect(manager.connectionIntent.wantsConnection) @@ -156,7 +151,7 @@ struct ConnectionManagerDisconnectDiagnosticsTests { manager.setTestState( connectionState: .disconnected, currentTransportType: .bluetooth, - connectionIntent: .none + connectionIntent: ConnectionIntent.none ) manager.testLastConnectedDeviceID = deviceID @@ -166,7 +161,7 @@ struct ConnectionManagerDisconnectDiagnosticsTests { #expect(calls == [deviceID]) let diagnostic = manager.lastDisconnectDiagnostic ?? "" - #expect(diagnostic.localizedStandardContains("source=connect(to:).adoptSystemConnectedPeripheral")) + #expect(diagnostic.localizedStandardContains("source=ble.adoptSystemConnectedPeripheral")) #expect(manager.connectionState == .connecting) #expect(manager.connectionIntent.wantsConnection) } diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerFullSyncConsumptionTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerFullSyncConsumptionTests.swift new file mode 100644 index 0000000000..2ae9f1ba0e --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerFullSyncConsumptionTests.swift @@ -0,0 +1,181 @@ +import Foundation +@testable import MC1Services +import MeshCore +import MeshCoreTestSupport +import Testing + +@Suite("Connection full sync consumption") +@MainActor +struct ConnectionManagerFullSyncConsumptionTests { + private static let watermark: UInt32 = 2000 + + @Test(.timeLimit(.minutes(1)), arguments: [TransportType.bluetooth, .wifi]) + func `same request recovery uses incremental sync after its forced first sync`(type: TransportType) async throws { + let env = try ConnectionManagerRadioTestHarness() + let transport = type == .bluetooth ? env.ble : env.wifi + do { + let saved = try await configure(env, transport: transport) + env.manager.lastCleanChannelSync = (saved.radioID, Date()) + _ = try await env.connect(type) + let first = try #require(env.manager.currentConnection) + #expect(await contactReads(transport) == [PacketBuilder.getContacts()], + "The admitted override must force the first contact exchange") + let initialChannels = await transport.sentData.filter { $0.first == CommandCode.getChannel.rawValue } + #expect(initialChannels.count == 1, "A forced sync must bypass a recent clean channel stamp") + #expect(env.manager.currentChannelSyncConfig(for: first.device.radioID, transportType: type).channelSyncSkipWindow > .zero) + + try await recover(env, type: type, previousGeneration: first.generation) + + let recovered = try #require(env.manager.currentConnection) + #expect(recovered.requestID == first.requestID) + #expect(recovered.device.radioID == first.device.radioID) + #expect(await contactReads(transport) == [PacketBuilder.getContacts(), incrementalRequest()], + "Recovery must use the saved watermark after the request's forced sync has begun") + let recoveredChannels = await transport.sentData.filter { $0.first == CommandCode.getChannel.rawValue } + #expect(recoveredChannels == initialChannels, "Recovery must honor the recent clean channel stamp") + #expect(try await recovered.services.session.getTime().timeIntervalSince1970 > 0) + } catch { await env.close(); throw error } + await env.close() + } + + enum InterruptedSetup { + case handshakeFailure + case retiredReadyCallback + } + + struct InterruptedSample: Sendable { + var type: TransportType + var interruption: InterruptedSetup + } + + /// Handshake retries differ by transport. Retirement during readiness uses the same callback on either transport. + nonisolated static let interruptedSamples: [InterruptedSample] = [ + InterruptedSample(type: .bluetooth, interruption: .handshakeFailure), + InterruptedSample(type: .wifi, interruption: .handshakeFailure), + InterruptedSample(type: .bluetooth, interruption: .retiredReadyCallback), + ] + + @Test(.timeLimit(.minutes(1)), arguments: interruptedSamples) + func `setup interrupted before sync preserves its forced exchange`(_ sample: InterruptedSample) async throws { + let type = sample.type + let interruption = sample.interruption + let sessionClock = interruption == .handshakeFailure ? TestClock() : nil + let env = try ConnectionManagerRadioTestHarness(sessionClock: sessionClock) + let transport = type == .bluetooth ? env.ble : env.wifi + var retirement: ConnectionRetirement? + do { + _ = try await configure(env, transport: transport) + if interruption == .handshakeFailure { + let attempts = type == .bluetooth + ? (env.manager.hasSystemPairingRegistry ? ConnectionManager.defaultConnectAttempts : ConnectionManager.unverifiedConnectAttempts) + : 1 + await transport.rejectNext(.appStart, count: attempts) + } else { + env.manager.onConnectionReady = { _ in + retirement = env.manager.beginOwnedRetirement( + previousRequest: env.manager.desiredRequest, phase: .connecting, closePhysical: true, retainMembership: true + ) + } + } + let first: Result + do { + first = try await .success(env.resultAdvancingClock { try await env.connect(type) }) + } catch { + first = .failure(error) + } + if interruption == .handshakeFailure { + if case .success = first { Issue.record("The rejected handshake must fail before sync") } + } else { + if case .failure = first { Issue.record("Retirement during readiness must return its handoff") } + try #require(retirement != nil) + } + // The replacement session uses the production clock so the pipeline grace sleep can finish. + env.manager.sessionClockForTesting = nil + await retirement?.value + let request = try #require(env.manager.desiredRequest) + #expect(await contactReads(transport).isEmpty, "Neither interrupted setup may enter contact sync") + env.manager.onConnectionReady = nil + + let next = try await env.manager.establishAttempt(request, preservePhysicalBLE: false) + + #expect(env.manager.isCurrent(next)) + #expect(env.manager.currentConnection?.requestID == request.id) + #expect(env.manager.connectionState == .ready) + #expect(await contactReads(transport) == [PacketBuilder.getContacts()], + "The first sync that actually starts must still force the complete contact exchange") + let session = try #require(env.manager.session) + #expect(try await session.getTime().timeIntervalSince1970 > 0) + } catch { await env.close(); throw error } + await env.close() + } + + @Test(.timeLimit(.minutes(1)), arguments: [TransportType.bluetooth, .wifi]) + func `first sync retries retain their captured full sync override`(type: TransportType) async throws { + let env = try ConnectionManagerRadioTestHarness() + let transport = type == .bluetooth ? env.ble : env.wifi + do { + _ = try await configure(env, transport: transport) + await transport.rejectNext(.getContacts) + _ = try await env.connect(type) + let first = try #require(env.manager.currentConnection) + let retry = try #require(env.manager.resyncTask) + await retry.value + + #expect(env.manager.connectionState == .ready) + #expect(await contactReads(transport) == [PacketBuilder.getContacts(), PacketBuilder.getContacts()], + "A failed first exchange must retry in full even after the request override is consumed") + try await recover(env, type: type, previousGeneration: first.generation) + + let recovered = try #require(env.manager.currentConnection) + #expect(recovered.requestID == first.requestID) + #expect(await contactReads(transport) == [PacketBuilder.getContacts(), PacketBuilder.getContacts(), incrementalRequest()], + "A later Link record must resume incremental sync after the forced retry finishes") + #expect(try await recovered.services.session.getTime().timeIntervalSince1970 > 0) + } catch { await env.close(); throw error } + await env.close() + } + + private func configure(_ env: ConnectionManagerRadioTestHarness, transport: ConnectionTestRadioTransport) async throws -> DeviceDTO { + await env.manager.wireTransportHandlers() + let saved = DeviceDTO.testDevice(id: env.deviceID, publicKey: env.ble.publicKey, lastContactSync: Self.watermark) + try await env.manager.persistenceStore.saveDevice(saved) + await transport.setResponsePackets(for: .getContacts, packets: contactResponses()) + let model = Data("T-Deck".utf8) + let capabilities = Data([ResponseCode.deviceInfo.rawValue, 14, 50, 1]) + + Data(repeating: 0, count: 16) + model + Data(repeating: 0, count: 40 - model.count + 20) + await transport.setResponsePackets(for: .deviceQuery, packets: [capabilities]) + return saved + } + + private func recover( + _ env: ConnectionManagerRadioTestHarness, type: TransportType, previousGeneration: UUID + ) async throws { + if type == .bluetooth { + await env.ble.simulateAutoReconnecting(deviceID: env.deviceID) + try await waitUntil("Bluetooth loss should retire the first Link record") { env.manager.currentConnection == nil } + await env.manager.retirementTask?.value + await env.ble.simulateReconnected() + } else { + await env.wifi.simulateRemoteLoss() + } + try await waitUntil("same request recovery must finish a fresh setup") { + env.manager.currentConnection?.generation != previousGeneration && env.manager.connectionState == .ready + } + } + + private func contactReads(_ transport: ConnectionTestRadioTransport) async -> [Data] { + await transport.sentData.filter { $0.first == CommandCode.getContacts.rawValue } + } + + private func incrementalRequest() -> Data { + PacketBuilder.getContacts(since: Date(timeIntervalSince1970: TimeInterval(Self.watermark - 1))) + } + + private func contactResponses() -> [Data] { + let watermark = Self.watermark.littleEndian + return [ + Data([ResponseCode.contactStart.rawValue, 0, 0, 0, 0]), + Data([ResponseCode.contactEnd.rawValue]) + withUnsafeBytes(of: watermark) { Data($0) } + ] + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerLateCompletionTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerLateCompletionTests.swift new file mode 100644 index 0000000000..4811cf2ec3 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerLateCompletionTests.swift @@ -0,0 +1,154 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Connection late completions") +@MainActor +struct ConnectionManagerLateCompletionTests { + @Test(arguments: [false, true]) + func `accepted selection settles before replacement or terminal metadata`(disconnect: Bool) async throws { + let env = try ConnectionManagerRadioTestHarness() + let gate = BLEReconnectionTestHarness.Gate() + var acceptedRequest: UUID? + env.manager.testConnectionSelectionHandler = { requestID in + guard acceptedRequest == nil else { return } + acceptedRequest = requestID + await gate.wait() + } + let first = Task { try await env.connect(.bluetooth) } + var next: Task? + var terminal: Task? + do { + try await waitUntil("first connection must reach accepted selection") { acceptedRequest != nil } + if disconnect { + terminal = Task { await env.manager.disconnect() } + } else { + next = Task { try await env.connect(.wifi) } + } + try await waitUntil("successor must be admitted before old metadata finishes") { + env.manager.connectionRequestID != acceptedRequest + } + #expect(await env.wifi.connectCount == 0) + #expect(env.manager.currentConnection == nil) + gate.open() + #expect(try await !env.manager.isCurrent(first.value)) + if let terminal { + _ = await terminal.value + #expect(env.manager.currentConnection == nil) + #expect(try await env.manager.persistenceStore.fetchActiveDevice() == nil) + #expect(env.manager.lastConnectedDeviceID == nil) + } + if let next { + #expect(try await env.manager.isCurrent(next.value)) + let current = try #require(env.manager.currentConnection) + let saved = try #require(try await env.manager.persistenceStore.fetchActiveDevice()) + #expect(saved.id == current.device.id) + #expect(saved.radioID == current.device.radioID) + #expect(saved.lastUsedConnectionMethod?.isWiFi == true) + #expect(env.manager.lastConnectedDeviceID == current.device.id) + } + } catch { + gate.open() + first.cancel() + next?.cancel() + _ = await first.result + _ = await next?.result + _ = await terminal?.value + await env.close() + throw error + } + env.manager.testConnectionSelectionHandler = nil + await env.close() + } + + @Test + func `an accepted Device update merges fresh metadata before the successor dials`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let gate = BLEReconnectionTestHarness.Gate() + var successor: Task? + do { + _ = try await env.connect(.bluetooth) + let old = try #require(env.manager.currentConnection) + let blocker = env.manager.enqueueMetadata { _ in await gate.wait() } + env.manager.updateDefaultFloodScopeName("accepted scope") + try await env.manager.persistenceStore.addDeviceKnownRegion(radioID: old.device.radioID, region: "local region") + successor = Task { try await env.connect(.wifi) } + try await waitUntil("successor must replace the old request") { + env.manager.connectionRequestID != old.requestID + } + #expect(await env.wifi.connectCount == 0) + gate.open() + _ = await blocker.result + #expect(try await env.manager.isCurrent(#require(successor).value)) + let saved = try #require(try await env.manager.persistenceStore.fetchActiveDevice()) + #expect(saved.defaultFloodScopeName == "accepted scope") + #expect(saved.knownRegions == ["local region"]) + #expect(saved.lastUsedConnectionMethod?.isWiFi == true) + } catch { + gate.open() + successor?.cancel() + _ = await successor?.result + await env.close() + throw error + } + await env.close() + } + + @Test + func `replacement between old clock read and reply sends no old followup`() async throws { + let env = try ConnectionManagerRadioTestHarness(sameRadio: false) + await env.ble.setRadioTime(Date(timeIntervalSince1970: 1000)) + await env.ble.holdReplies(for: .getTime) + let first = Task { try await env.connect(.bluetooth) } + var successor: Task? + do { + try await waitUntil("first connection must reach its clock tail") { await env.ble.timeReads == 1 } + let requestID = env.manager.connectionRequestID + successor = Task { try await env.connect(.wifi) } + try await waitUntil("successor must retire the old clock owner") { env.manager.connectionRequestID != requestID } + #expect(await env.wifi.connectCount == 0) + await env.ble.releaseReplies(for: .getTime) + _ = try await first.value + #expect(try await env.manager.isCurrent(#require(successor).value)) + #expect(await env.ble.timeWrites == 0) + let noObsoleteTimezoneWrite = await !env.ble.cliCommands.contains { + ConnectionTestRadioTransport.splitCLICommand($0).command == "get tz.offset" + } + #expect(noObsoleteTimezoneWrite) + #expect(await env.wifi.timeReads == 1) + #expect(try await env.manager.session?.getTime() != nil) + } catch { + await env.ble.releaseAllGates() + first.cancel() + successor?.cancel() + _ = await first.result + _ = await successor?.result + await env.close() + throw error + } + await env.close() + } + + @Test(arguments: [false, true]) + func `retired clean sync callbacks cannot stamp replacement freshness`(sameRadio: Bool) async throws { + let env = try ConnectionManagerRadioTestHarness(sameRadio: sameRadio) + do { + _ = try await env.connect(.bluetooth) + let old = try #require(env.manager.currentConnection) + let clean = await old.services.syncCoordinator.onCleanChannelSync + let attempted = await old.services.syncCoordinator.onChannelSyncAttempted + _ = try await env.connect(.wifi) + let beforeClean = env.manager.lastCleanChannelSync + let beforeAttempt = env.manager.lastAttemptedChannelSync + await clean?(old.device.radioID) + await attempted?(old.device.radioID) + #expect(env.manager.lastCleanChannelSync?.radioID == beforeClean?.radioID) + #expect(env.manager.lastCleanChannelSync?.completedAt == beforeClean?.completedAt) + #expect(env.manager.lastAttemptedChannelSync?.radioID == beforeAttempt?.radioID) + #expect(env.manager.lastAttemptedChannelSync?.attemptedAt == beforeAttempt?.attemptedAt) + #expect(try await env.manager.session?.getTime() != nil) + } catch { await env.close(); throw error } + await env.close() + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerLaunchPreflightPortTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerLaunchPreflightPortTests.swift new file mode 100644 index 0000000000..57d41b0228 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerLaunchPreflightPortTests.swift @@ -0,0 +1,143 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("Launch activation preflight ownership") +@MainActor +struct ConnectionManagerLaunchPreflightPortTests { + enum Outcome: CaseIterable { + case success + case failure + case cancellation + } + + enum Choice: CaseIterable { + case sameRadio + case differentRadio + case disconnect + } + + @Test(.timeLimit(.minutes(1)), arguments: Outcome.allCases, Choice.allCases) + func `held launch activation result cannot dispatch after a newer explicit choice`(outcome: Outcome, choice: Choice) async throws { + let suite = "test.launch.preflight.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suite)) + let pairing = Pairing(outcome: outcome) + let ble = ConnectionTestRadioTransport() + let stateMachine = MockBLEStateMachine() + let manager = try ConnectionManager( + modelContainer: PersistenceStore.createContainer(inMemory: true), defaults: defaults, + stateMachine: stateMachine, transport: ble, pairing: pairing + ) + let saved = DeviceDTO.testDevice().copy { + $0.connectionMethods = [.bluetooth(peripheralUUID: $0.id, displayName: nil)] + } + try await manager.persistenceStore.saveDevice(saved) + manager.testLastConnectedDeviceID = saved.id + manager.setTestState(connectionIntent: .wantsConnection()) + let activation = Task { await manager.activate() } + do { + try await waitUntil("launch must suspend in its actual pairing activation preflight") { pairing.isWaiting } + let current: ConnectionSnapshot? + switch choice { + case .sameRadio, .differentRadio: + let target = choice == .sameRadio ? saved.id : UUID() + if choice == .differentRadio { await ble.setPublicKey(Data(repeating: 2, count: 32), for: target) } + let result = try await manager.connect(to: target, forceFullSync: true, forceReconnect: true) + #expect(manager.isCurrent(result)) + current = try #require(manager.currentConnection) + #expect((current?.device.radioID == saved.radioID) == (choice == .sameRadio)) + case .disconnect: + _ = await manager.disconnect(reason: .userInitiated) + current = nil + } + let expectedRequest = manager.connectionRequestID + let expectedState = manager.connectionState + let expectedIntent = manager.connectionIntent + let connects = await ble.connectCount + let closes = await ble.disconnectCount + if outcome == .cancellation { activation.cancel() } + pairing.release() + await activation.value + #expect(manager.connectionRequestID == expectedRequest) + #expect(manager.connectionState == expectedState) + #expect(manager.connectionIntent == expectedIntent) + #expect(await ble.connectCount == connects) + #expect(await ble.disconnectCount == closes) + #expect(!manager.isReconnectionWatchdogRunning) + if let current { + #expect(manager.isCurrent(current)) + #expect(try await current.services.session.getTime().timeIntervalSince1970 > 0) + } else { + #expect(manager.currentConnection == nil) + #expect(manager.connectionIntent.isUserDisconnected) + #expect(await ble.sentData.isEmpty) + } + } catch { + pairing.release() + activation.cancel() + await activation.value + await ble.releaseAllGates() + _ = await manager.disconnect(reason: .userInitiated) + await manager.retirementTask?.value + await manager.metadataCommitTask?.value + UserDefaults().removePersistentDomain(forName: suite) + throw error + } + _ = await manager.disconnect(reason: .userInitiated) + await manager.retirementTask?.value + await manager.metadataCommitTask?.value + UserDefaults().removePersistentDomain(forName: suite) + } + + @MainActor + private final class Pairing: DevicePairingService { + enum Failure: Error { case unavailable } + weak var delegate: (any DevicePairingDelegate)? + let isSessionActive = false + let registeredDeviceCount = 0 + let hasSystemPairingRegistry = false + let supportsSystemRename = false + private let outcome: Outcome + private var continuation: CheckedContinuation? + private var isOpen = false + var isWaiting: Bool { + continuation != nil + } + + init(outcome: Outcome) { + self.outcome = outcome + } + + func activate() async throws { + if !isOpen { await withCheckedContinuation { continuation = $0 } } + switch outcome { + case .success: return + case .failure: throw Failure.unavailable + case .cancellation: throw CancellationError() + } + } + + func release() { + isOpen = true + continuation?.resume() + continuation = nil + } + + func discoverDevice() async throws -> UUID { + throw CancellationError() + } + + func isDeviceConnectable(_ id: UUID) -> Bool { + true + } + + func registeredDeviceInfos() -> [(id: UUID, name: String)] { + [] + } + + func removeDevice(_ id: UUID) async throws {} + func renameDevice(_ id: UUID) async throws {} + func clearStaleRegistrations() async {} + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerLaunchTransportTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerLaunchTransportTests.swift index 226be0692e..62d6459513 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerLaunchTransportTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerLaunchTransportTests.swift @@ -1,165 +1,98 @@ import Foundation @testable import MC1Services -import MeshCore import Testing -/// Launch reconnect on a simulator build returns before this path. These tests call -/// `reconnectLastUsedTransport`, which `activate()` uses on device. @Suite("Launch last-used transport") @MainActor struct ConnectionManagerLaunchTransportTests { - private func makeEnvironment() throws -> PairingTestEnvironment { - let env = try ConnectionManager.createForPairingTesting() - env.accessorySetupKit.isSessionActive = false - return env - } - @Test - func `bluetooth then wifi falls back to wifi when bluetooth throws and skips the watchdog`() async throws { - let env = try makeEnvironment() - defer { env.cleanup() } - let peripheralID = UUID() - let device = DeviceDTO.testDevice().copy { - $0.connectionMethods = [ - .wifi(host: "10.0.0.8", port: 5000, displayName: nil), - .bluetooth(peripheralUUID: peripheralID, displayName: nil) - ] - } + func `bluetooth then wifi falls back only within the admitted launch request`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let device = savedDevice(env, wifiLast: false) try await env.manager.persistenceStore.saveDevice(device) env.manager.testLastConnectedDeviceID = device.id - env.manager.testWiFiConnectHandler = { _, _ in } - await env.transport.setConnectError(BLEError.connectionFailed("down")) - + await env.ble.setConnectError(BLEError.authenticationFailed) await env.manager.reconnectLastUsedTransport(device: device, lastDeviceID: device.id) - - #expect(env.manager.testWiFiConnectAttempts.count == 1) - #expect(env.manager.testWiFiConnectAttempts.first?.host == "10.0.0.8") - #expect(env.manager.isReconnectionWatchdogRunning == false) - env.manager.stopReconnectionWatchdog() + #expect(await env.wifi.connectCount == 1) + #expect(env.manager.currentTransportType == .wifi) + #expect(!env.manager.isReconnectionWatchdogRunning) + await env.close() } @Test - func `wifi then bluetooth dials the peripheral when wifi throws`() async throws { - let env = try makeEnvironment() - defer { env.cleanup() } - let peripheralID = UUID() - let device = DeviceDTO.testDevice().copy { - $0.connectionMethods = [ - .bluetooth(peripheralUUID: peripheralID, displayName: nil), - .wifi(host: "10.0.0.8", port: 5000, displayName: nil) - ] - } - env.manager.testWiFiConnectHandler = { _, _ in throw BLEError.connectionFailed("wifi") } - await env.transport.setConnectError(BLEError.connectionFailed("down")) - + func `wifi then bluetooth dials the recorded peripheral after owned wifi failure`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let device = savedDevice(env, wifiLast: true) + try await env.manager.persistenceStore.saveDevice(device) + await env.wifi.setConnectError(BLEError.connectionFailed("unreachable")) await env.manager.reconnectLastUsedTransport(device: device, lastDeviceID: device.id) - - let dialed = await env.transport.connectInvocations.compactMap(\.deviceID) - #expect(dialed.isEmpty == false) - #expect(dialed.allSatisfy { $0 == peripheralID }) - #expect(dialed.contains(device.id) == false) - env.manager.stopReconnectionWatchdog() + #expect(await env.ble.connectCount == 1) + #expect(env.manager.currentTransportType == .bluetooth) + #expect(env.manager.connectedDevice?.id == env.deviceID) + await env.close() } @Test - func `wifi only does not dial bluetooth or start the watchdog`() async throws { - let env = try makeEnvironment() - defer { env.cleanup() } - let device = DeviceDTO.testDevice().copy { - $0.connectionMethods = [.wifi(host: "10.0.0.8", port: 5000, displayName: nil)] - } - env.manager.testWiFiConnectHandler = { _, _ in throw BLEError.connectionFailed("wifi") } - + func `wifi only failure never dials bluetooth or starts its watchdog`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let device = DeviceDTO.testDevice().copy { $0.connectionMethods = [.wifi(host: "radio.test", port: 5123, displayName: nil)] } + await env.wifi.setConnectError(BLEError.connectionFailed("unreachable")) await env.manager.reconnectLastUsedTransport(device: device, lastDeviceID: device.id) - - let dialed = await env.transport.connectInvocations - #expect(dialed.isEmpty) - #expect(env.manager.isReconnectionWatchdogRunning == false) + #expect(await env.ble.connectCount == 0) + #expect(!env.manager.isReconnectionWatchdogRunning) + await env.close() } @Test - func `no methods dials the device id`() async throws { - let env = try makeEnvironment() - defer { env.cleanup() } - let device = DeviceDTO.testDevice() - await env.transport.setConnectError(BLEError.connectionFailed("down")) - + func `a row with no methods dials its Device ID`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let device = DeviceDTO.testDevice(id: env.deviceID) await env.manager.reconnectLastUsedTransport(device: device, lastDeviceID: device.id) - - let dialed = await env.transport.connectInvocations.compactMap(\.deviceID) - #expect(dialed.isEmpty == false) - #expect(dialed.allSatisfy { $0 == device.id }) - env.manager.stopReconnectionWatchdog() + #expect(await env.ble.connectCount == 1) + #expect(env.manager.connectedDevice?.id == device.id) + await env.close() } @Test - func `foreground health check reconnects wifi only when it was last used`() async throws { - let env = try makeEnvironment() - defer { env.cleanup() } - let wifiLast = DeviceDTO.testDevice().copy { - $0.connectionMethods = [ - .bluetooth(peripheralUUID: UUID(), displayName: nil), - .wifi(host: "10.0.0.9", port: 5000, displayName: nil) - ] - } - try await env.manager.persistenceStore.saveDevice(wifiLast) - env.manager.testLastConnectedDeviceID = wifiLast.id - env.manager.setTestState(connectionState: .disconnected, connectionIntent: .wantsConnection()) - env.manager.testWiFiConnectHandler = { _, _ in } - - await env.manager.checkWiFiConnectionHealth() - #expect(env.manager.testWiFiConnectAttempts.count == 1) - - let bluetoothLast = wifiLast.copy { - $0.connectionMethods = [ - .wifi(host: "10.0.0.9", port: 5000, displayName: nil), - .bluetooth(peripheralUUID: UUID(), displayName: nil) - ] - } - try await env.manager.persistenceStore.saveDevice(bluetoothLast) - env.manager.testWiFiConnectAttempts = [] + func `foreground wifi recovery follows the saved last method`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let device = savedDevice(env, wifiLast: true) + try await env.manager.persistenceStore.saveDevice(device) + env.manager.testLastConnectedDeviceID = device.id + env.manager.setTestState(connectionIntent: .wantsConnection()) await env.manager.checkWiFiConnectionHealth() - #expect(env.manager.testWiFiConnectAttempts.isEmpty) + #expect(await env.wifi.connectCount == 1) + #expect(env.manager.connectionState == .ready) + await env.close() } @Test - func `bluetooth connect prep keeps the intent to connect`() async throws { - let env = try makeEnvironment() - defer { env.cleanup() } - env.manager.setTestState( - connectionState: .connected, - currentTransportType: .some(.wifi), - connectionIntent: .wantsConnection() - ) - env.manager.wifiTransport = WiFiTransport() - - await env.manager.disconnect(reason: .bluetoothConnectPrep) - - #expect(env.manager.connectionIntent.wantsConnection) - #expect(env.manager.connectionState == .disconnected) - #expect(env.manager.wifiTransport == nil) + func `switching to bluetooth closes the captured wifi socket before dialing`() async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + _ = try await env.connect(.wifi) + await env.ble.holdConnect() + let switchTask = Task { try await env.connect(.bluetooth) } + do { + try await waitUntil("BLE should reach its real dial") { await env.ble.connectIsHeld } + #expect(await env.wifi.isConnected == false) + #expect(env.manager.services == nil) + await env.ble.releaseConnect() + let result = try await switchTask.value + #expect(env.manager.isCurrent(result)) + } catch { + await env.ble.releaseAllGates() + switchTask.cancel() + _ = await switchTask.result + throw error + } + } catch { await env.close(); throw error } + await env.close() } - @Test - func `connect via bluetooth drops wifi before dialing the peripheral`() async throws { - let env = try makeEnvironment() - defer { env.cleanup() } - let peripheralID = UUID() - env.manager.setTestState( - connectionState: .connected, - currentTransportType: .some(.wifi), - connectionIntent: .wantsConnection() - ) - env.manager.wifiTransport = WiFiTransport() - await env.transport.setConnectError(BLEError.connectionFailed("down")) - - await #expect(throws: BLEError.self) { - try await env.manager.connectViaBluetooth(peripheralID: peripheralID) - } - - let dialed = await env.transport.connectInvocations.compactMap(\.deviceID) - #expect(env.manager.wifiTransport == nil) - #expect(dialed.first == peripheralID) - #expect(env.manager.connectionIntent.wantsConnection) + private func savedDevice(_ env: ConnectionManagerRadioTestHarness, wifiLast: Bool) -> DeviceDTO { + let bluetooth = ConnectionMethod.bluetooth(peripheralUUID: env.deviceID, displayName: nil) + let wifi = ConnectionMethod.wifi(host: "radio.test", port: 5123, displayName: nil) + return DeviceDTO.testDevice(id: env.deviceID).copy { $0.connectionMethods = wifiLast ? [bluetooth, wifi] : [wifi, bluetooth] } } } diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerMembershipTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerMembershipTests.swift new file mode 100644 index 0000000000..d1c1c1eefc --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerMembershipTests.swift @@ -0,0 +1,207 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("ConnectionManager membership handoff") +@MainActor +struct ConnectionManagerMembershipTests { + @Test + func `same-radio WiFi handoff restores only connected source memberships after readiness`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + let activeA = try await harness.addMembership(radioID: harness.deviceA.radioID, connected: true) + let manualA = try await harness.addMembership(radioID: harness.deviceA.radioID, connected: false) + let activeB = try await harness.addMembership(radioID: harness.deviceB.radioID, connected: true) + let channelSecret = Data(repeating: 0xC1, count: 16) + await harness.bluetooth.setChannel(index: 0, name: "Queue", secret: channelSecret) + await harness.wifi.setChannel(index: 0, name: "Queue", secret: channelSecret) + try await harness.connectBluetooth() + #expect(await loginDestinations(harness.bluetooth).isEmpty) + #expect(await loginDestinations(harness.wifi).isEmpty) + await harness.wifi.holdLoginResults() + let handoff = harness.track(Task { + try await harness.manager.connectViaWiFi(host: "radio.local", port: 4242) + }) + try await waitUntil("room login result should remain held after readiness") { + await harness.wifi.heldLoginResultCount == 1 + } + let current = try #require(harness.manager.currentConnection) + #expect(current.device.radioID == harness.deviceA.radioID) + #expect(harness.manager.connectionState == .ready) + #expect(harness.manager.wifiHeartbeatTask != nil) + #expect(harness.manager.membershipBatch?.sessionIDs == [activeA.id]) + #expect(try await !harness.isConnected(activeA)) + #expect(try await !harness.isConnected(manualA)) + #expect(try await harness.isConnected(activeB)) + + let message = try await current.services.messageService.createPendingChannelMessage( + text: "queue remains usable", channelIndex: 0, radioID: current.device.radioID + ) + try await current.services.chatSendQueueService.enqueueChannel(ChannelMessageEnvelope( + messageID: message.id, channelIndex: 0, isResend: false, + messageText: message.text, messageTimestamp: message.timestamp, localNodeName: nil + )) + try await waitUntil("channel queue should finish while room login remains held") { + await (try? harness.manager.persistenceStore.fetchMessage(id: message.id))?.status == .sent + } + #expect(await harness.wifi.heldLoginResultCount == 1) + #expect(await loginDestinations(harness.wifi) == [activeA.publicKey]) + await harness.wifi.releaseLoginResults() + _ = try await handoff.value + + #expect(try await harness.isConnected(activeA)) + #expect(try await !harness.isConnected(manualA)) + #expect(try await harness.isConnected(activeB)) + #expect(harness.manager.membershipBatch?.sessionIDs.isEmpty == true) + } + } + + @Test + func `foreign WiFi identity discards source restoration without touching the other partition`() async throws { + try await ConnectionRadioHandoffHarness.withHarness(wifiIsSameRadio: false) { harness in + let activeA = try await harness.addMembership(radioID: harness.deviceA.radioID, connected: true) + let activeB = try await harness.addMembership(radioID: harness.deviceB.radioID, connected: true) + try await harness.connectBluetooth() + + _ = try await harness.manager.connectViaWiFi(host: "radio.local", port: 4242) + + #expect(harness.manager.connectedDevice?.radioID == harness.deviceB.radioID) + #expect(harness.manager.membershipBatch == nil) + #expect(await loginDestinations(harness.wifi).isEmpty) + #expect(try await !harness.isConnected(activeA)) + #expect(try await harness.isConnected(activeB)) + } + } + + @Test + func `a second BLE loss retains the new batch while the previous room login retires`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + let activeA = try await harness.addMembership(radioID: harness.deviceA.radioID, connected: true) + try await harness.connectBluetooth() + try await waitUntil("BLE lifecycle source should be installed") { await harness.bluetooth.hasLifecycleHandler } + await harness.bluetooth.holdLoginResults() + await harness.bluetooth.simulateAutoReconnecting(deviceID: harness.deviceA.id) + try await waitUntil("first BLE loss should capture its membership batch") { + harness.manager.currentConnection == nil && harness.manager.connectionTeardownCount == 0 + } + await harness.bluetooth.simulateReconnected() + try await waitUntil("first BLE rebuild should hold its room login") { + await harness.bluetooth.heldLoginResultCount == 1 + } + let firstBatch = try #require(harness.manager.membershipBatch) + let firstServices = try #require(harness.manager.services) + let addedDuringRestore = try await harness.addMembership(radioID: harness.deviceA.radioID, connected: true) + + await harness.bluetooth.simulateAutoReconnecting(deviceID: harness.deviceA.id) + try await waitUntil("second BLE loss should retire the previous room login") { + harness.manager.currentConnection == nil && harness.manager.connectionTeardownCount == 0 + && harness.manager.membershipBatch?.id != firstBatch.id + } + #expect(await firstServices.remoteNodeService.pendingLoginCount == 0) + await harness.bluetooth.releaseLoginResults() + await harness.bluetooth.holdLoginResults() + let loginCountBeforeRebuild = await loginDestinations(harness.bluetooth).count + await harness.bluetooth.simulateReconnected() + try await waitUntil("the first login in the new BLE batch should be held") { + await harness.bluetooth.heldLoginResultCount == 1 + } + + #expect(harness.manager.connectionState == .ready) + #expect(harness.manager.membershipBatch?.sessionIDs == [activeA.id, addedDuringRestore.id]) + #expect(await loginDestinations(harness.bluetooth).count == loginCountBeforeRebuild + 1) + #expect(try await !harness.isConnected(activeA)) + #expect(try await !harness.isConnected(addedDuringRestore)) + await harness.bluetooth.releaseLoginResults() + try await waitUntil("new batch should restore both memberships") { + let firstConnected = await (try? harness.isConnected(activeA)) == true + let addedConnected = await (try? harness.isConnected(addedDuringRestore)) == true + return firstConnected && addedConnected + } + try await waitUntil("only the completed batch should be consumed") { + harness.manager.membershipBatch?.sessionIDs.isEmpty == true + } + let newDestinations = await loginDestinations(harness.bluetooth).dropFirst(loginCountBeforeRebuild) + #expect(newDestinations.count == 2) + #expect(Set(newDestinations) == [activeA.publicKey, addedDuringRestore.publicKey]) + } + } + + @Test + func `explicit disconnect cancels a held restore and the next manual connection stays manual`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + let activeA = try await harness.addMembership(radioID: harness.deviceA.radioID, connected: true) + try await harness.connectBluetooth() + await harness.wifi.holdLoginResults() + let handoff = harness.track(Task { + try await harness.manager.connectViaWiFi(host: "radio.local", port: 4242) + }) + try await waitUntil("WiFi restore should hold its room login") { + await harness.wifi.heldLoginResultCount == 1 + } + + _ = await harness.manager.disconnect(reason: .userInitiated) + await harness.wifi.releaseLoginResults() + _ = await handoff.result + #expect(harness.manager.membershipBatch == nil) + #expect(try await !harness.isConnected(activeA)) + try await harness.connectBluetooth() + + #expect(await loginDestinations(harness.bluetooth).isEmpty) + #expect(harness.manager.membershipBatch == nil) + #expect(try await !harness.isConnected(activeA)) + } + } + + @Test + func `flood scope recovery replaces a fenced session during a post-ready BLE rebuild`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + _ = try await harness.addMembership(radioID: harness.deviceA.radioID, connected: true) + let secret = Data(repeating: 0x5A, count: 16) + let channel = ChannelDTO.testChannel( + radioID: harness.deviceA.radioID, index: 0, secret: secret, floodScope: .region("Selected") + ) + try await harness.manager.persistenceStore.saveChannel(channel) + await harness.bluetooth.setChannel(index: channel.index, name: channel.name, secret: secret) + try await harness.connectBluetooth() + await harness.bluetooth.holdLoginResults() + await harness.bluetooth.simulateAutoReconnecting(deviceID: harness.deviceA.id) + try await waitUntil("BLE loss should drop the installed link") { harness.manager.currentConnection == nil } + await harness.bluetooth.simulateReconnected() + try await waitUntil("rebuild should be ready with its room login held") { + guard let cycle = harness.manager.reconnectionCoordinator.currentCycle else { return false } + let loginHeld = await harness.bluetooth.heldLoginResultCount == 1 + return harness.manager.connectionState == .ready + && harness.manager.reconnectionCoordinator.isRebuilding(cycle) + && loginHeld + } + let fenced = try #require(harness.manager.installedLink) + await harness.bluetooth.enqueueResponsePackets( + for: .setFloodScope, packets: [Data([ResponseCode.ok.rawValue])] + ) + await harness.bluetooth.enqueueResponsePackets( + for: .setFloodScope, packets: [Data([ResponseCode.error.rawValue, 1])] + ) + + _ = try await fenced.services.messageService.sendChannelMessage( + text: "kept", channelIndex: channel.index, radioID: channel.radioID + ) + try await waitUntil("forced recovery should publish a successor") { + harness.manager.installedLink?.resource !== fenced.resource && harness.manager.connectionState == .ready + } + let successor = try #require(harness.manager.installedLink) + await harness.bluetooth.releaseLoginResults() + try await waitUntil("the released login must leave the successor in place") { + harness.manager.installedLink === successor && harness.manager.connectionState == .ready + } + _ = try await successor.services.session.getTime() + #expect(harness.manager.installedLink === successor) + #expect(await harness.bluetooth.sentData.filter { $0.first == CommandCode.sendChannelMessage.rawValue }.count == 1) + } + } + + private func loginDestinations(_ radio: ConnectionTestRadioTransport) async -> [Data] { + await radio.sentData.filter { $0.first == CommandCode.sendLogin.rawValue }.map { + Data($0.dropFirst().prefix(ProtocolLimits.publicKeySize)) + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerOwnershipRegressionTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerOwnershipRegressionTests.swift new file mode 100644 index 0000000000..43dba82ce7 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerOwnershipRegressionTests.swift @@ -0,0 +1,98 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Connection ownership regressions") +@MainActor +struct ConnectionManagerOwnershipRegressionTests { + @Test(.timeLimit(.minutes(1))) + func `explicit disconnect supersedes launch fallback while BLE is dialing`() async throws { + let container = try PersistenceStore.createContainer(inMemory: true) + let transport = ConnectionTestRadioTransport() + await transport.holdConnect() + await transport.setConnectError(BLEError.connectionFailed("held launch failed")) + let wifi = ConnectionTestRadioTransport() + let suite = "test.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suite)) + defer { UserDefaults().removePersistentDomain(forName: suite) } + let pairing = MockAccessorySetupKitService() + pairing.isSessionActive = false + let manager = ConnectionManager( + modelContainer: container, + defaults: defaults, + stateMachine: MockBLEStateMachine(), + transport: transport, + pairing: AccessorySetupPairingService(accessorySetupKit: pairing), + makeWiFiTransport: { wifi } + ) + let device = DeviceDTO.testDevice().copy { + $0.connectionMethods = [ + .wifi(host: "10.0.0.8", port: 5000, displayName: nil), + .bluetooth(peripheralUUID: $0.id, displayName: nil) + ] + } + try await manager.persistenceStore.saveDevice(device) + manager.testLastConnectedDeviceID = device.id + + let launch = Task { await manager.reconnectLastUsedTransport(device: device, lastDeviceID: device.id) } + do { + try await waitUntil("launch should reach the physical BLE dial") { await transport.connectIsHeld } + let disconnect = Task { await manager.disconnect(reason: .userInitiated) } + try await waitUntil("disconnect should revoke launch publication") { manager.connectionState == .disconnected } + await transport.releaseConnect() + _ = await disconnect.value + await launch.value + + #expect(await wifi.connectCount == 0, "A superseded launch must not start its fallback") + #expect(manager.connectionIntent.isUserDisconnected) + #expect(manager.connectionState == .disconnected) + #expect(!manager.isReconnectionWatchdogRunning) + } catch { + await transport.releaseConnect() + launch.cancel() + await launch.value + throw error + } + manager.stopReconnectionWatchdog() + } + + @Test(.timeLimit(.minutes(1))) + func `successful BLE resync runs the timezone step through the production retry path`() async throws { + let transport = ConnectionTestRadioTransport() + let session = MeshCoreSession(transport: transport) + try await session.start() + let services = try await ServiceContainer.forTesting(session: session) + let (manager, _) = try ConnectionManager.createForTesting() + let device = DeviceDTO.testDevice(firmwareVersion: 14) + try await services.dataStore.saveDevice(device) + manager.setTestState( + connectionState: .syncing, + services: services, + session: session, + connectedDevice: device, + currentTransportType: .bluetooth, + connectionIntent: .wantsConnection() + ) + await services.syncCoordinator.setPerformResyncOverride { _, _ in + FullSyncResult(contacts: .clean, channels: .clean, messages: .clean) + } + var completed = false + manager.onDeviceSynced = { _, _ in completed = true } + manager.startResyncLoop(radioID: device.radioID, services: services) + do { + try await waitUntil(timeout: .seconds(10), "production resync should complete") { completed } + let commands = await transport.cliCommands.map { ConnectionTestRadioTransport.splitCLICommand($0).command } + #expect(commands.contains("get tz.offset"), "BLE recovery must run the same timezone work as initial success") + #expect(manager.connectionState == .ready) + } catch { + manager.cancelResyncLoop() + await session.stop() + await services.tearDown() + throw error + } + manager.cancelResyncLoop() + await session.stop() + await services.tearDown() + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPairingTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPairingTests.swift index 76d310f268..6d20ee362f 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPairingTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPairingTests.swift @@ -1,6 +1,9 @@ +#if canImport(UIKit) + import AccessorySetupKit +#endif import Foundation @testable import MC1Services -import MeshCore +@testable import MeshCore import os import Testing @@ -358,6 +361,197 @@ struct ConnectionManagerPairingTests { try await manager.deleteDevice(id: UUID()) } + @Test + func `radio erase records before pairing and resumes after local failure`() async throws { + enum InjectedFailure: Error { case save } + + let environment = try ConnectionManager.createForPairingTesting() + defer { environment.cleanup() } + let manager = environment.manager + let pairing = environment.accessorySetupKit + let store = manager.persistenceStore + let radio = DeviceDTO.testDevice() + try await store.saveDevice(radio) + pairing.setPairedAccessories([ASAccessory(bluetoothIdentifier: radio.id, displayName: radio.nodeName)]) + let link = ReceiveScope.Lifetime() + let captured = try #require(await store.captureReceiveScope(radioID: radio.radioID, link: link)) + + await store.setRadioEraseFaults(begin: { throw InjectedFailure.save }, complete: nil) + await #expect(throws: InjectedFailure.save) { try await manager.startRadioErase(radio) } + #expect(pairing.removeAccessoryCallCount == 0) + #expect(captured.isCurrent) + #expect(try await store.fetchDevice(id: radio.id) != nil) + + await store.setRadioEraseFaults(begin: nil, complete: nil) + pairing.removeAccessoryError = DevicePairingError.cancelled + await #expect(throws: DevicePairingError.cancelled) { try await manager.startRadioErase(radio) } + #expect(pairing.accessory(for: radio.id) != nil) + #expect(try await store.fetchDevice(id: radio.id) != nil) + #expect(!captured.isCurrent) + #expect(try await store.fetchPendingRadioErases().isEmpty) + #expect(try await store.captureReceiveScope(radioID: radio.radioID, link: link)?.isCurrent == true) + + pairing.removeAccessoryError = nil + await store.setRadioEraseFaults(begin: nil, complete: { throw InjectedFailure.save }) + await #expect(throws: InjectedFailure.save) { try await manager.startRadioErase(radio) } + #expect(pairing.accessory(for: radio.id) == nil) + #expect(manager.radioCleanup[radio.radioID]?.state == .failed) + let target = try #require(await store.fetchPendingRadioErases().first) + + manager.retryRadioErase(target) + _ = await manager.radioEraseTasks[radio.radioID]?.result + #expect(manager.radioCleanup[radio.radioID]?.state == .failed) + #expect(try await store.fetchPendingRadioErases().count == 1) + + await store.setRadioEraseFaults(begin: nil, complete: nil) + manager.retryRadioErase(target) + _ = await manager.radioEraseTasks[radio.radioID]?.result + #expect(manager.radioCleanup[radio.radioID]?.state == .completed) + #expect(pairing.removeAccessoryCallCount == 2) + #expect(try await store.fetchPendingRadioErases().isEmpty) + #expect(try await store.fetchDevice(id: radio.id) == nil) + } + + @Test(arguments: [false, true]) + func `factory reset retry only repeats local cleanup`(cancelPairingRemoval: Bool) async throws { + enum InjectedFailure: Error { case save } + + let environment = try ConnectionManager.createForPairingTesting() + defer { environment.cleanup() } + let manager = environment.manager + let store = manager.persistenceStore + let radio = DeviceDTO.testDevice() + try await store.saveDevice(radio) + let transport = MockTransport() + let session = MeshCoreSession(transport: transport) + try await startEraseTestSession(session, transport: transport, radio: radio) + let services = ServiceContainer(session: session, dataStore: store, radioID: radio.radioID) + manager.setTestState( + connectionState: .connected, services: .some(services), session: .some(session), connectedDevice: .some(radio) + ) + + if cancelPairingRemoval { + environment.accessorySetupKit.setPairedAccessories([ + ASAccessory(bluetoothIdentifier: radio.id, displayName: radio.nodeName) + ]) + environment.accessorySetupKit.removeAccessoryError = DevicePairingError.cancelled + } else { + await store.setRadioEraseFaults(begin: nil, complete: { throw InjectedFailure.save }) + } + await transport.holdNextSend() + let context = try #require(manager.captureCurrentRemoval()) + let reset = Task { try await manager.factoryResetAndEraseRadio(context) } + try await waitUntil("factory reset reaches transport") { await transport.sendIsWaiting } + #expect(try await store.fetchPendingRadioErases().first?.radioID == radio.radioID) + #expect(await Array(transport.sentData.dropFirst()) == [PacketBuilder.factoryReset()]) + await transport.failHeldSend() + await transport.releaseHeldSend() + if cancelPairingRemoval { + await #expect(throws: DevicePairingError.cancelled) { try await reset.value } + #expect(manager.radioCleanup[radio.radioID]?.state == .failed) + #expect(try await store.fetchDevice(id: radio.id) != nil) + } else { + await #expect(throws: InjectedFailure.save) { try await reset.value } + } + let target = try #require(await store.fetchPendingRadioErases().first) + + environment.accessorySetupKit.removeAccessoryError = nil + await store.setRadioEraseFaults(begin: nil, complete: nil) + manager.retryRadioErase(target) + _ = await manager.radioEraseTasks[radio.radioID]?.result + #expect(manager.radioCleanup[radio.radioID]?.state == .completed) + #expect(await Array(transport.sentData.dropFirst()) == [PacketBuilder.factoryReset()]) + } + + @Test + func `cancelled erase settles in flight message and restarts queued delivery`() async throws { + let environment = try ConnectionManager.createForPairingTesting() + defer { environment.cleanup() } + let manager = environment.manager + let pairing = environment.accessorySetupKit + let store = manager.persistenceStore + let radio = DeviceDTO.testDevice() + try await store.saveDevice(radio) + pairing.setPairedAccessories([ASAccessory(bluetoothIdentifier: radio.id, displayName: radio.nodeName)]) + let (gate, answerPrompt) = AsyncStream.makeStream() + defer { answerPrompt.finish() } + pairing.removeAccessoryGate = gate + pairing.removeAccessoryError = DevicePairingError.cancelled + + let transport = MockTransport() + let session = MeshCoreSession(transport: transport) + try await startEraseTestSession(session, transport: transport, radio: radio) + let services = ServiceContainer(session: session, dataStore: store, radioID: radio.radioID) + manager.setTestState( + connectionState: .connected, services: .some(services), session: .some(session), connectedDevice: .some(radio) + ) + let poller = services.messagePollingService + await services.syncCoordinator.wireMessageHandlers(dependencies: services.syncDependencies, radioID: radio.radioID) + await poller.startAutoFetch(radioID: radio.radioID) + try await waitUntil("poller and automatic fetch are subscribed") { await session.subscriberCountForTest >= 2 } + + let getMessage = PacketBuilder.getMessage() + let timestamp = UInt32(Date().timeIntervalSince1970) + await transport.simulateReceive(Data([ResponseCode.messagesWaiting.rawValue])) + try await waitUntil("first queue read reaches transport") { await transport.sentData.last == getMessage } + let erase = Task { try await manager.startRadioErase(radio) } + try await waitUntil("erase suspends new queue reads") { await session.isMessageFetchingSuspended } + #expect(pairing.removeAccessoryCallCount == 0) + #expect(try await !store.isRadioErasePending(radio.radioID)) + + await transport.simulateReceive(eraseTestChannelFrame("before prompt", timestamp: timestamp)) + try await waitUntil("pairing removal reaches confirmation") { + await MainActor.run { pairing.removeAccessoryCallCount == 1 } + } + #expect(try await store.fetchMessages(radioID: radio.radioID, channelIndex: 0).map(\.text) == ["before prompt"]) + #expect(try await store.isRadioErasePending(radio.radioID)) + await transport.simulateReceive(Data([ResponseCode.messagesWaiting.rawValue])) + try await waitUntil("message waiting was observed during pairing confirmation") { + await session.processedMessagesWaitingCountForTest == 2 + } + #expect(await transport.sentData.filter { $0 == getMessage }.count == 1) + + answerPrompt.yield() + await #expect(throws: DevicePairingError.cancelled) { try await erase.value } + #expect(try await !store.isRadioErasePending(radio.radioID)) + try await waitUntil("cancellation restarts the radio queue drain") { + await transport.sentData.filter { $0 == getMessage }.count == 2 + } + await transport.simulateReceive(eraseTestChannelFrame("during prompt", timestamp: timestamp + 1)) + try await waitUntil("radio queue is checked after the resumed delivery") { + await transport.sentData.filter { $0 == getMessage }.count == 3 + } + await transport.simulateReceive(Data([ResponseCode.noMoreMessages.rawValue])) + try await waitUntil("both channel arrivals are stored once") { + let messages = try? await store.fetchMessages(radioID: radio.radioID, channelIndex: 0) + return messages?.map(\.text).sorted() == ["before prompt", "during prompt"] + } + await poller.stopAutoFetch() + await session.stop() + } + + private func startEraseTestSession(_ session: MeshCoreSession, transport: MockTransport, radio: DeviceDTO) async throws { + let start = Task { try await session.start() } + try await waitUntil("app start reaches transport") { await !transport.sentData.isEmpty } + var selfInfo = Data([ResponseCode.selfInfo.rawValue, ContactType.chat.rawValue, 22, 22]) + selfInfo.append(radio.publicKey) + selfInfo.append(Data(repeating: 0, count: 12)) + for value in [radio.frequency, radio.bandwidth] { + selfInfo.append(withUnsafeBytes(of: value.littleEndian) { Data($0) }) + } + selfInfo.append(contentsOf: [radio.spreadingFactor, radio.codingRate]) + selfInfo.append(contentsOf: radio.nodeName.utf8) + await transport.simulateReceive(selfInfo) + try await start.value + } + + private func eraseTestChannelFrame(_ body: String, timestamp: UInt32) -> Data { + var frame = Data([ResponseCode.channelMessageReceivedV3.rawValue, 32, 0, 0, 0, 0, 0]) + frame.append(withUnsafeBytes(of: timestamp.littleEndian) { Data($0) }) + frame.append(contentsOf: "Peer: \(body)".utf8) + return frame + } + // MARK: - Forget/Resume Signal @Test @@ -399,11 +593,14 @@ struct ConnectionManagerPairingTests { defer { UserDefaults().removePersistentDomain(forName: suiteName) } let (manager, _) = try ConnectionManager.createForTesting(defaults: defaults) - let deviceID = UUID() - manager.persistConnection(deviceID: deviceID, radioID: UUID(), deviceName: "Radio") - #expect(manager.lastConnectedDeviceID == deviceID) + let device = DeviceDTO.testDevice() + try await manager.persistenceStore.saveDevice(device) + manager.setTestState(connectedDevice: .some(device)) + manager.persistConnection(deviceID: device.id, radioID: device.radioID, deviceName: device.nodeName) + #expect(manager.lastConnectedDeviceID == device.id) - await manager.forgetDevice(id: deviceID) + let context = try #require(manager.captureCurrentRemoval()) + _ = try await manager.forgetDevice(context, deleteData: true) // The auto-reconnect / onboarding-resume signal must not survive forgetting its own radio. #expect(manager.lastConnectedDeviceID == nil) @@ -419,7 +616,9 @@ struct ConnectionManagerPairingTests { let lastConnected = UUID() manager.persistConnection(deviceID: lastConnected, radioID: UUID(), deviceName: "Radio") - await manager.forgetDevice(id: UUID()) + let device = DeviceDTO.testDevice() + try await manager.persistenceStore.saveDevice(device) + try await manager.startRadioErase(device) #expect(manager.lastConnectedDeviceID == lastConnected) } diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPlatformRemovalTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPlatformRemovalTests.swift new file mode 100644 index 0000000000..2ff0cb5538 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPlatformRemovalTests.swift @@ -0,0 +1,135 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Platform Bluetooth association removal") +@MainActor +struct ConnectionManagerPlatformRemovalTests { + @Test(arguments: [false, true], [false, true]) + func `failed pairing removes Bluetooth while preserving radio data`(hasSystemRegistry: Bool, hasWiFi: Bool) async throws { + let env = try PlatformRemovalTestHarness(hasSystemRegistry: hasSystemRegistry) + do { + let saved = try await env.saveDevice(hasWiFi: hasWiFi) + let history = MessageDTO(from: Message(radioID: saved.radioID, channelIndex: 0, text: "Saved history")) + let pending = PendingSendDTO( + id: UUID(), radioID: saved.radioID, messageID: history.id, kind: .channel, + contactID: nil, channelIndex: 0, isResend: false, messageText: history.text, + messageTimestamp: history.timestamp, localNodeName: nil, sequence: 1, enqueuedAt: Date() + ) + try await env.manager.persistenceStore.saveMessage(history) + try await env.manager.persistenceStore.upsertPendingSend(pending) + let failedRequestID = try await env.failConnection() + await env.seedBondVerification() + let receipt = try await env.requireRemoved(env.manager.removeFailedPairing(deviceID: saved.id)) + + #expect(receipt.requestID != failedRequestID) + #expect(env.manager.currentConnection == nil) + #expect(env.manager.connectionState == .disconnected) + #expect(!env.manager.connectionIntent.wantsConnection) + let stored = try #require(await env.manager.persistenceStore.fetchDevice(radioID: saved.radioID)) + #expect(stored.publicKey == saved.publicKey) + #expect(stored.radioID == saved.radioID) + #expect(!stored.isActive) + if hasWiFi { + #expect(stored.id == saved.id) + #expect(stored.connectionMethods == [PlatformRemovalTestHarness.wifi]) + #expect(stored.lastUsedConnectionMethod == PlatformRemovalTestHarness.wifi) + #expect(env.manager.lastConnectedDeviceID == saved.id) + #expect(env.manager.lastConnectedRadioID == saved.radioID) + #expect(env.manager.lastConnectedDeviceName == saved.nodeName) + } else { + #expect(stored.id != saved.id) + #expect(stored.connectionMethods.isEmpty) + #expect(try await env.manager.persistenceStore.fetchDevice(id: saved.id) == nil) + #expect(env.manager.lastConnectedDeviceID == nil) + #expect(env.manager.lastConnectedRadioID == nil) + #expect(env.manager.lastConnectedDeviceName == nil) + } + #expect(try await env.manager.persistenceStore.fetchMessage(id: history.id)?.radioID == saved.radioID) + #expect(try await env.manager.persistenceStore.fetchPendingSends(radioID: saved.radioID) == [pending]) + #expect(await env.stateMachine.recordedBondVerifications[saved.id] == nil) + #expect(LastConnectionStore(defaults: env.defaults).bondVerificationDate(for: saved.id) == nil) + #expect(await env.radio.connectCount == 1) + } catch { await env.close(); throw error } + await env.close() + } + + @Test(arguments: [false, true]) + func `association readded before cleanup remains saved`(hasWiFi: Bool) async throws { + let env = try PlatformRemovalTestHarness(hasSystemRegistry: true) + let gate = PlatformRemovalTestHarness.Gate() + var removing: Task? + do { + let saved = try await env.saveDevice(hasWiFi: hasWiFi) + env.registerAccessory() + let failedRequestID = try await env.failConnection() + let predecessor = env.manager.enqueueMetadata { _ in await gate.wait() } + try await waitUntil("metadata predecessor must be held") { gate.entered } + let removal = Task { try await env.manager.removeFailedPairing(deviceID: saved.id) } + removing = removal + try await waitUntil("system removal must finish before local metadata cleanup") { + env.ask.removeAccessoryCallCount == 1 && env.manager.desiredRequest?.target == .disconnected + } + #expect(env.ask.accessory(for: saved.id) == nil) + env.registerAccessory() + gate.open() + _ = try await predecessor.value + let receipt = try await env.requireRemoved(removal.value) + #expect(receipt.requestID != failedRequestID) + let retained = try #require(await env.manager.persistenceStore.fetchDevice(id: saved.id)) + #expect(retained.radioID == saved.radioID) + #expect(retained.publicKey == saved.publicKey) + #expect(retained.connectionMethods == saved.connectionMethods) + #expect(env.ask.accessory(for: saved.id) != nil) + #expect(env.manager.currentConnection == nil) + #expect(!env.manager.connectionIntent.wantsConnection) + } catch { + gate.open() + _ = await removing?.result + await env.close() + throw error + } + await env.close() + } + + @Test + func `stale no registry removal preserves a newer same handle connection`() async throws { + let env = try PlatformRemovalTestHarness(hasSystemRegistry: false) + do { + await env.manager.wireTransportHandlers() + _ = try await env.manager.connect(to: env.deviceID, forceFullSync: true, forceReconnect: true) + let context = try #require(env.manager.captureCurrentRemoval()) + let oldRequestID = env.manager.connectionRequestID + let result = try await env.manager.connect(to: env.deviceID, forceFullSync: true, forceReconnect: true) + let successor = try #require(env.manager.currentConnection) + let link = try #require(env.manager.installedLink) + let before = try #require(await env.manager.persistenceStore.fetchDevice(id: env.deviceID)) + #expect(successor.requestID != oldRequestID) + let removal = try await env.manager.startRemoval( + context, policy: .bluetoothAssociation(pairingFailed: false), + reason: .forgetDevice, sourceIsCurrent: false + ).value + guard case .superseded = removal else { + Issue.record("A stale removal must leave the successor in control") + throw ConnectionError.notConnected + } + #expect(env.manager.isCurrent(result)) + #expect(env.manager.installedLink === link) + #expect(link.resource.binding.isActive) + #expect(env.manager.currentConnection?.generation == successor.generation) + #expect(env.manager.connectionIntent.wantsConnection) + #expect(env.manager.lastConnectedDeviceID == successor.device.id) + #expect(env.manager.lastConnectedRadioID == successor.device.radioID) + let retained = try #require(await env.manager.persistenceStore.fetchDevice(id: env.deviceID)) + #expect(retained.radioID == before.radioID) + #expect(retained.publicKey == before.publicKey) + #expect(retained.connectionMethods == before.connectionMethods) + #expect(retained.isActive) + #expect(await env.stateMachine.recordedBondVerifications[env.deviceID] != nil) + #expect(LastConnectionStore(defaults: env.defaults).bondVerificationDate(for: env.deviceID) != nil) + #expect(await env.radio.connectCount == 2) + #expect(try await successor.services.session.getTime().timeIntervalSince1970 > 0) + } catch { await env.close(); throw error } + await env.close() + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPowerOffTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPowerOffTests.swift index abf9983c6b..61f7dce4e6 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPowerOffTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPowerOffTests.swift @@ -1,6 +1,8 @@ import Foundation @testable import MC1Services @testable import MeshCore +import MeshCoreTestSupport +import os import Testing @Suite("ConnectionManager power off") @@ -8,245 +10,285 @@ import Testing struct ConnectionManagerPowerOffTests { @Test func `silence disconnects only the owned link`() async throws { - let harness = try await Harness.make() - try await harness.powerOff() - #expect(harness.manager.connectionIntent.isUserDisconnected) - #expect(harness.manager.connectionState == .disconnected) + try await withPowerOffHarness(clock: TestClock()) { harness in + try await harness.powerOff() + #expect(harness.manager.connectionIntent.isUserDisconnected) + #expect(harness.manager.connectionState == .disconnected) + } } @Test func `a CLI reply leaves the owned link connected`() async throws { - let harness = try await Harness.make() - await harness.transport.holdNextSend() - let task = Task { try await harness.manager.powerOffCurrentLink() } - try await waitUntil("poweroff write should park") { await harness.transport.sendIsWaiting } - await harness.transport.simulateReceive(Data([ResponseCode.cliReply.rawValue])) - await harness.transport.releaseHeldSend() - - await #expect(throws: SettingsServiceError.self) { try await task.value } - #expect(harness.manager.connectionIntent.wantsConnection) - #expect(harness.manager.connectionState == .ready) + try await withPowerOffHarness { harness in + await harness.transport.holdNextSend() + let task = Task { try await harness.manager.powerOffCurrentLink() } + try await waitUntil("poweroff write should park") { await harness.transport.sendIsWaiting } + await harness.transport.simulateReceive(Data([ResponseCode.cliReply.rawValue])) + await harness.transport.releaseHeldSend() + + await #expect(throws: SettingsServiceError.self) { try await task.value } + #expect(harness.manager.connectionIntent.wantsConnection) + #expect(harness.manager.connectionState == .ready) + } } @Test func `send failure without link loss is not shutdown`() async throws { - let harness = try await Harness.make() - await harness.transport.holdNextSend() - let task = Task { try await harness.manager.powerOffCurrentLink() } - try await waitUntil("poweroff write should park") { await harness.transport.sendIsWaiting } - let early = CFAbsoluteTimeGetCurrent() - 5 - harness.manager.notePowerOffRemoteLoss(deviceID: harness.device.id, eventTime: early) - await harness.transport.failHeldSend() - await harness.transport.releaseHeldSend() - - await #expect(throws: SettingsServiceError.self) { try await task.value } - #expect(harness.manager.connectionIntent.wantsConnection) + try await withPowerOffHarness { harness in + await harness.transport.holdNextSend() + let task = Task { try await harness.manager.powerOffCurrentLink() } + try await waitUntil("poweroff write should park") { await harness.transport.sendIsWaiting } + let early = CFAbsoluteTimeGetCurrent() - 5 + harness.manager.notePowerOffRemoteLoss(deviceID: harness.device.id, eventTime: early) + await harness.transport.failHeldSend() + await harness.transport.releaseHeldSend() + + await #expect(throws: SettingsServiceError.self) { try await task.value } + #expect(harness.manager.connectionIntent.wantsConnection) + } } @Test func `remote loss after submission counts as shutdown when the write fails`() async throws { - let harness = try await Harness.make() - harness.manager.setTestState(currentTransportType: .wifi) - await harness.transport.holdNextSend() - let task = Task { try await harness.manager.powerOffCurrentLink() } - try await waitUntil("poweroff write should park") { await harness.transport.sendIsWaiting } - - await harness.manager.handleWiFiDisconnection( - error: WiFiTransportError.notConnected, - remoteLossAt: CFAbsoluteTimeGetCurrent() - ) - #expect(harness.manager.wifiReconnectTask == nil) - await harness.transport.failHeldSend() - await harness.transport.releaseHeldSend() - - _ = try await task.value - #expect(harness.manager.connectionIntent.isUserDisconnected) - #expect(harness.manager.wifiReconnectTask == nil) + try await withPowerOffHarness(wifi: true) { harness in + let socket = try #require(harness.wifi) + await harness.transport.holdNextSend() + let task = Task { try await harness.manager.powerOffCurrentLink() } + try await waitUntil("poweroff write should park") { await harness.transport.sendIsWaiting } + + let loss = Task { + await harness.manager.handleWiFiDisconnection( + error: WiFiTransportError.notConnected, + remoteLossAt: CFAbsoluteTimeGetCurrent(), source: socket + ) + } + do { + try await waitUntil("socket loss must detach before its captured exchange drains") { + harness.manager.currentConnection == nil + } + #expect(harness.manager.wifiReconnectTask == nil) + await harness.transport.failHeldSend() + await harness.transport.releaseHeldSend() + await loss.value + _ = try await task.value + #expect(harness.manager.connectionIntent.isUserDisconnected) + #expect(harness.manager.wifiReconnectTask == nil) + } catch { + await harness.transport.releaseHeldSend() + _ = await loss.result + _ = await task.result + _ = await harness.manager.disconnect() + throw error + } + } } @Test func `heartbeat failure does not tear down or prove shutdown`() async throws { - let harness = try await Harness.make() - await harness.transport.holdNextSend() - let task = Task { try await harness.manager.powerOffCurrentLink() } - try await waitUntil("poweroff write should park") { await harness.transport.sendIsWaiting } - - await harness.manager.handleWiFiDisconnection( - error: MeshCoreError.timeout, - remoteLossAt: nil, - isHeartbeat: true - ) - #expect(harness.manager.connectionState == .ready) - #expect(harness.manager.session != nil) - - await harness.transport.simulateReceive(Data([ResponseCode.cliReply.rawValue])) - await harness.transport.releaseHeldSend() - await #expect(throws: SettingsServiceError.self) { try await task.value } - #expect(harness.manager.connectionIntent.wantsConnection) + try await withPowerOffHarness { harness in + await harness.transport.holdNextSend() + let task = Task { try await harness.manager.powerOffCurrentLink() } + try await waitUntil("poweroff write should park") { await harness.transport.sendIsWaiting } + + await harness.manager.handleWiFiDisconnection( + error: MeshCoreError.timeout, + remoteLossAt: nil, + isHeartbeat: true + ) + #expect(harness.manager.connectionState == .ready) + #expect(harness.manager.session != nil) + + await harness.transport.simulateReceive(Data([ResponseCode.cliReply.rawValue])) + await harness.transport.releaseHeldSend() + await #expect(throws: SettingsServiceError.self) { try await task.value } + #expect(harness.manager.connectionIntent.wantsConnection) + } } @Test func `generic link loss without remote-loss evidence does not count as shutdown`() async throws { - let harness = try await Harness.make() - await harness.transport.holdNextSend() - let task = Task { try await harness.manager.powerOffCurrentLink() } - try await waitUntil("poweroff write should park") { await harness.transport.sendIsWaiting } - - await harness.manager.handleConnectionLoss(deviceID: harness.device.id, error: nil) - #expect(harness.manager.reconnectionWatchdogTask == nil) - await harness.transport.failHeldSend() - await harness.transport.releaseHeldSend() - - await #expect(throws: Error.self) { try await task.value } - #expect(!harness.manager.connectionIntent.isUserDisconnected) - harness.manager.stopReconnectionWatchdog() + try await withPowerOffHarness { harness in + await harness.transport.holdNextSend() + let task = Task { try await harness.manager.powerOffCurrentLink() } + try await waitUntil("poweroff write should park") { await harness.transport.sendIsWaiting } + + let origin = BLELifecycleOrigin(deviceID: harness.device.id, generation: 1, eventTime: CFAbsoluteTimeGetCurrent()) + let loss = Task { await harness.manager.handleBLELifecycleEvent(.disconnected(origin, error: nil)) } + try await waitUntil("loss should detach publication before draining the held command") { harness.manager.connectionState == .disconnected } + #expect(harness.manager.reconnectionWatchdogTask == nil) + await harness.transport.failHeldSend() + await harness.transport.releaseHeldSend() + await loss.value + + await #expect(throws: Error.self) { try await task.value } + #expect(!harness.manager.connectionIntent.isUserDisconnected) + harness.manager.stopReconnectionWatchdog() + } } @Test func `early auto-reconnect and the watchdog stay suppressed during the attempt`() async throws { - let harness = try await Harness.make() - await harness.transport.holdNextSend() - let task = Task { try await harness.manager.powerOffCurrentLink() } - try await waitUntil("poweroff write should park") { await harness.transport.sendIsWaiting } - - #expect(harness.manager.powerOffSuppressesReconnect(for: harness.device.id)) - harness.manager.startReconnectionWatchdog() - #expect(harness.manager.reconnectionWatchdogTask == nil) - - await harness.transport.simulateReceive(Data([ResponseCode.cliReply.rawValue])) - await harness.transport.releaseHeldSend() - await #expect(throws: SettingsServiceError.self) { try await task.value } - #expect(harness.manager.powerOffSuppressesReconnect(for: harness.device.id) == false) + try await withPowerOffHarness { harness in + await harness.transport.holdNextSend() + let task = Task { try await harness.manager.powerOffCurrentLink() } + try await waitUntil("poweroff write should park") { await harness.transport.sendIsWaiting } + + #expect(harness.manager.powerOffSuppressesReconnect(for: harness.device.id)) + harness.manager.startReconnectionWatchdog() + #expect(harness.manager.reconnectionWatchdogTask == nil) + + await harness.transport.simulateReceive(Data([ResponseCode.cliReply.rawValue])) + await harness.transport.releaseHeldSend() + await #expect(throws: SettingsServiceError.self) { try await task.value } + #expect(harness.manager.powerOffSuppressesReconnect(for: harness.device.id) == false) + } } @Test func `a second power-off waits instead of sending twice`() async throws { - let harness = try await Harness.make() - await harness.transport.holdNextSend() - let first = Task { try await harness.manager.powerOffCurrentLink() } - let second = Task { try await harness.manager.powerOffCurrentLink() } - try await waitUntil("poweroff write should park") { await harness.transport.sendIsWaiting } - await harness.transport.simulateReceive(Data([ResponseCode.cliReply.rawValue])) - await harness.transport.releaseHeldSend() - - await #expect(throws: SettingsServiceError.self) { try await first.value } - await #expect(throws: SettingsServiceError.self) { try await second.value } - let powerOffs = await harness.transport.sentData.filter { - Data($0.dropFirst()) == Data(PacketBuilder.powerOffCommand.utf8) + try await withPowerOffHarness { harness in + await harness.transport.holdNextSend() + let first = Task { try await harness.manager.powerOffCurrentLink() } + let second = Task { try await harness.manager.powerOffCurrentLink() } + try await waitUntil("poweroff write should park") { await harness.transport.sendIsWaiting } + await harness.transport.simulateReceive(Data([ResponseCode.cliReply.rawValue])) + await harness.transport.releaseHeldSend() + + await #expect(throws: SettingsServiceError.self) { try await first.value } + await #expect(throws: SettingsServiceError.self) { try await second.value } + let powerOffs = await harness.transport.sentData.filter { + Data($0.dropFirst()) == Data(PacketBuilder.powerOffCommand.utf8) + } + #expect(powerOffs.count == 1) } - #expect(powerOffs.count == 1) } @Test func `a replacement session is left connected when the old attempt finishes`() async throws { - let harness = try await Harness.make() - await harness.transport.holdNextSend() - let task = Task { try await harness.manager.powerOffCurrentLink() } - try await waitUntil("poweroff write should park") { await harness.transport.sendIsWaiting } - - let replacement = MeshCoreSession(transport: MockTransport()) - let replacementDevice = DeviceDTO.testDevice() - let replacementServices = try await ServiceContainer.forTesting(session: replacement) - harness.manager.setTestState( - connectionState: .ready, - services: replacementServices, - session: replacement, - connectedDevice: replacementDevice, - connectionIntent: .wantsConnection() - ) - await harness.transport.failHeldSend() - await harness.transport.releaseHeldSend() - - await #expect(throws: PowerOffSuperseded.self) { try await task.value } - #expect(harness.manager.session === replacement) - #expect(harness.manager.connectedDevice?.id == replacementDevice.id) - #expect(harness.manager.connectionIntent.wantsConnection) - #expect(harness.manager.connectionState == .ready) + try await withPowerOffHarness { harness in + await harness.transport.holdNextSend() + let task = Task { try await harness.manager.powerOffCurrentLink() } + try await waitUntil("poweroff write should park") { await harness.transport.sendIsWaiting } + + let replacement = MeshCoreSession(transport: MockTransport()) + let replacementDevice = DeviceDTO.testDevice() + let replacementServices = try await ServiceContainer.forTesting(session: replacement) + harness.manager.setTestState( + connectionState: .ready, + services: replacementServices, + session: replacement, + connectedDevice: replacementDevice, + connectionIntent: .wantsConnection() + ) + await harness.transport.failHeldSend() + await harness.transport.releaseHeldSend() + + await #expect(throws: PowerOffSuperseded.self) { try await task.value } + #expect(harness.manager.session === replacement) + #expect(harness.manager.connectedDevice?.id == replacementDevice.id) + #expect(harness.manager.connectionIntent.wantsConnection) + #expect(harness.manager.connectionState == .ready) + } } @Test func `cancelling before submission sends nothing`() async throws { - let harness = try await Harness.make() - await harness.transport.holdNextSend() - let blocker = Task { try await harness.session.runCliCommand("board") } - try await waitUntil("blocker write should park") { await harness.transport.sendIsWaiting } - - let powerOff = Task { try await harness.manager.powerOffCurrentLink() } - try await Task.sleep(for: .milliseconds(20)) - powerOff.cancel() - await harness.transport.releaseHeldSend() - await harness.transport.simulateReceive(Data([ResponseCode.cliReply.rawValue])) - _ = try? await blocker.value - - let outcome = await powerOff.result - guard case .failure = outcome else { - Issue.record("expected the queued power-off to fail") - return - } - let powerOffs = await harness.transport.sentData.filter { - Data($0.dropFirst()) == Data(PacketBuilder.powerOffCommand.utf8) + try await withPowerOffHarness { harness in + await harness.transport.holdNextSend() + let blocker = Task { try await harness.session.runCliCommand("board") } + try await waitUntil("blocker write should park") { await harness.transport.sendIsWaiting } + + let powerOff = Task { try await harness.manager.powerOffCurrentLink() } + try await Task.sleep(for: .milliseconds(20)) + powerOff.cancel() + await harness.transport.releaseHeldSend() + await harness.transport.simulateReceive(Data([ResponseCode.cliReply.rawValue])) + _ = try? await blocker.value + + let outcome = await powerOff.result + guard case .failure = outcome else { + Issue.record("expected the queued power-off to fail") + return + } + let powerOffs = await harness.transport.sentData.filter { + Data($0.dropFirst()) == Data(PacketBuilder.powerOffCommand.utf8) + } + #expect(powerOffs.isEmpty) + #expect(harness.manager.connectionIntent.wantsConnection) } - #expect(powerOffs.isEmpty) - #expect(harness.manager.connectionIntent.wantsConnection) } @Test func `settled cleanup survives nil publication and dies on a replacement session`() async throws { - let harness = try await Harness.make() - - let token = try await harness.manager.powerOffCurrentLink() - #expect(harness.manager.powerOffOwnsCleanup(token)) - harness.manager.setTestState(session: MeshCoreSession?.none) - #expect(harness.manager.powerOffOwnsCleanup(token)) - await harness.manager.disconnect(reason: .powerOff) - #expect(harness.manager.powerOffOwnsCleanup(token)) - - installReplacement(on: harness.manager, radioID: UUID()) - #expect(harness.manager.powerOffOwnsCleanup(token) == false) + try await withPowerOffHarness(clock: TestClock()) { harness in + let token = try await harness.awaitPowerOff() + #expect(harness.manager.powerOffOwnsCleanup(token)) + harness.manager.setTestState(session: MeshCoreSession?.none) + #expect(harness.manager.powerOffOwnsCleanup(token)) + await harness.manager.disconnect(reason: .powerOff) + #expect(harness.manager.powerOffOwnsCleanup(token)) + + installReplacement(on: harness.manager, radioID: UUID()) + #expect(harness.manager.powerOffOwnsCleanup(token) == false) + } } @Test func `explicit disconnect revokes a settled cleanup token`() async throws { - let harness = try await Harness.make() - let token = try await harness.manager.powerOffCurrentLink() - #expect(harness.manager.powerOffOwnsCleanup(token)) + try await withPowerOffHarness(clock: TestClock()) { harness in + let token = try await harness.awaitPowerOff() + #expect(harness.manager.powerOffOwnsCleanup(token)) - await harness.manager.disconnect() + await harness.manager.disconnect() - #expect(harness.manager.powerOffOwnsCleanup(token) == false) + #expect(harness.manager.powerOffOwnsCleanup(token) == false) + } } @Test func `a replacement revokes the shared cleanup token for every waiting caller`() async throws { - let harness = try await Harness.make() - let first = Task { try await harness.manager.powerOffCurrentLink() } - let second = Task { try await harness.manager.powerOffCurrentLink() } - - let firstToken = try await first.value - let secondToken = try await second.value - #expect(firstToken == secondToken) - #expect(harness.manager.powerOffOwnsCleanup(firstToken)) - - installReplacement(on: harness.manager, radioID: UUID()) - #expect(harness.manager.powerOffOwnsCleanup(firstToken) == false) - #expect(harness.manager.powerOffOwnsCleanup(secondToken) == false) + let clock = TestClock() + try await withPowerOffHarness(clock: clock) { harness in + let finished = OSAllocatedUnfairLock(initialState: 0) + let first = Task { + defer { finished.withLock { $0 += 1 } } + return try await harness.manager.powerOffCurrentLink() + } + let second = Task { + defer { finished.withLock { $0 += 1 } } + return try await harness.manager.powerOffCurrentLink() + } + try await waitUntilClockAdvances(clock, timeout: .seconds(5), "power-off silence should elapse") { + finished.withLock { $0 == 2 } + } + + let firstToken = try await first.value + let secondToken = try await second.value + #expect(firstToken == secondToken) + #expect(harness.manager.powerOffOwnsCleanup(firstToken)) + + installReplacement(on: harness.manager, radioID: UUID()) + #expect(harness.manager.powerOffOwnsCleanup(firstToken) == false) + #expect(harness.manager.powerOffOwnsCleanup(secondToken) == false) + } } @Test func `a replacement before settlement revokes the shared cleanup token`() async throws { - let harness = try await Harness.make() - await harness.transport.holdNextSend() - let first = Task { try await harness.manager.powerOffCurrentLink() } - let second = Task { try await harness.manager.powerOffCurrentLink() } - try await waitUntil("poweroff write should park") { await harness.transport.sendIsWaiting } - - installReplacement(on: harness.manager, radioID: harness.device.radioID) - await harness.transport.failHeldSend() - await harness.transport.releaseHeldSend() - - await #expect(throws: PowerOffSuperseded.self) { try await first.value } - await #expect(throws: PowerOffSuperseded.self) { try await second.value } - #expect(harness.manager.powerOffCleanupToken == nil) + try await withPowerOffHarness { harness in + await harness.transport.holdNextSend() + let first = Task { try await harness.manager.powerOffCurrentLink() } + let second = Task { try await harness.manager.powerOffCurrentLink() } + try await waitUntil("poweroff write should park") { await harness.transport.sendIsWaiting } + + installReplacement(on: harness.manager, radioID: harness.device.radioID) + await harness.transport.failHeldSend() + await harness.transport.releaseHeldSend() + + await #expect(throws: PowerOffSuperseded.self) { try await first.value } + await #expect(throws: PowerOffSuperseded.self) { try await second.value } + #expect(harness.manager.powerOffCleanupToken == nil) + } } } @@ -256,13 +298,22 @@ private struct Harness { let session: MeshCoreSession let transport: MockTransport let device: DeviceDTO - - static func make() async throws -> Harness { - let (manager, _) = try ConnectionManager.createForTesting() + let wifi: PowerOffSocket? + let services: ServiceContainer + let clock: TestClock? + let suiteName: String + + static func make(wifi: Bool = false, clock: TestClock? = nil) async throws -> Harness { + let suiteName = "test.poweroff.\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + let (manager, _) = try ConnectionManager.createForTesting(defaults: defaults) let transport = MockTransport() + let socket = wifi ? PowerOffSocket(transport: transport) : nil + let physical: any MeshTransport = if let socket { socket } else { transport } let session = MeshCoreSession( - transport: transport, - configuration: SessionConfiguration(defaultTimeout: 10, clientIdentifier: "MCTst") + transport: physical, + configuration: SessionConfiguration(defaultTimeout: 10, clientIdentifier: "MCTst"), + clock: clock ) let device = DeviceDTO.testDevice(firmwareVersion: 14) let services = try await ServiceContainer.forTesting(session: session, radioID: device.radioID) @@ -271,14 +322,45 @@ private struct Harness { services: services, session: session, connectedDevice: device, + currentTransportType: wifi ? .wifi : .bluetooth, + wifiTransport: socket, connectionIntent: .wantsConnection() ) try await start(session, transport: transport) - return Harness(manager: manager, session: session, transport: transport, device: device) + return Harness( + manager: manager, session: session, transport: transport, device: device, wifi: socket, + services: services, clock: clock, suiteName: suiteName + ) + } + + func close() async { + await transport.releaseHeldSend() + _ = await manager.disconnect() + await session.stop(disconnectTransport: false, drainExchanges: true) + await session.waitForQuiescence() + await services.tearDown() + await transport.disconnect() + UserDefaults().removePersistentDomain(forName: suiteName) + #expect(await session.subscriberCountForTest == 0) } func powerOff() async throws { - _ = try await manager.powerOffCurrentLink() + _ = try await awaitPowerOff() + } + + func awaitPowerOff() async throws -> UUID { + guard let clock else { return try await manager.powerOffCurrentLink() } + let slot = OSAllocatedUnfairLock?>(initialState: nil) + let task = Task { @MainActor in + let outcome: Result + do { outcome = try await .success(manager.powerOffCurrentLink()) } catch { outcome = .failure(error) } + slot.withLock { $0 = outcome } + } + try await waitUntilClockAdvances(clock, timeout: .seconds(5), "power-off silence should elapse") { + slot.withLock { $0 != nil } + } + task.cancel() + return try slot.withLock { try $0!.get() } } private static func start(_ session: MeshCoreSession, transport: MockTransport) async throws { @@ -308,6 +390,17 @@ private struct Harness { } } +@MainActor +private func withPowerOffHarness( + wifi: Bool = false, + clock: TestClock? = nil, + _ operation: @MainActor (Harness) async throws -> Void +) async throws { + let harness = try await Harness.make(wifi: wifi, clock: clock) + do { try await operation(harness) } catch { await harness.close(); throw error } + await harness.close() +} + @MainActor private func installReplacement(on manager: ConnectionManager, radioID: UUID) { let replacement = MeshCoreSession(transport: MockTransport()) @@ -319,3 +412,37 @@ private func installReplacement(on manager: ConnectionManager, radioID: UUID) { connectionIntent: .wantsConnection() ) } + +private actor PowerOffSocket: WiFiMeshTransport { + let transport: MockTransport + var connectionInfo: (host: String, port: UInt16)? { + ("radio.test", 5123) + } + + var receivedData: AsyncStream { + get async { await transport.receivedData } + } + + var isConnected: Bool { + get async { await transport.isConnected } + } + + init(transport: MockTransport) { + self.transport = transport + } + + func connect() async throws { + try await transport.connect() + } + + func disconnect() async { + await transport.disconnect() + } + + func send(_ data: Data) async throws { + try await transport.send(data) + } + + func setConnectionInfo(host: String, port: UInt16) {} + func setDisconnectionHandler(_ handler: @escaping @Sendable (Error?, CFAbsoluteTime) -> Void) {} +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPreparedQueuePortTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPreparedQueuePortTests.swift new file mode 100644 index 0000000000..c17570398e --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPreparedQueuePortTests.swift @@ -0,0 +1,98 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("Prepared queue retirement ownership") +@MainActor +struct ConnectionManagerPreparedQueuePortTests { + @Test(.timeLimit(.minutes(1))) + func `unpublished candidate cannot advance persisted sends when its successor becomes ready`() async throws { + let env = try ConnectionManagerRadioTestHarness(sameRadio: false) + let selection = Gate() + let radioID = UUID() + let device = DeviceDTO.testDevice(id: env.deviceID, radioID: radioID, publicKey: env.ble.publicKey) + try await env.manager.persistenceStore.saveDevice(device) + let contact = ContactDTO.testContact(radioID: radioID) + try await env.manager.persistenceStore.saveContact(contact) + let message = MessageDTO(from: Message( + radioID: radioID, contactID: contact.id, text: "pending before replacement", timestamp: 1_700_000_000 + )) + try await env.manager.persistenceStore.saveMessage(message) + try await env.manager.persistenceStore.upsertPendingSend(PendingSendDTO( + envelope: DirectMessageEnvelope(messageID: message.id, contactID: contact.id), radioID: radioID + )) + let original = try #require(try await env.manager.persistenceStore.fetchPendingSendsForMessage(messageID: message.id).first) + var firstSelection = true + env.manager.testConnectionSelectionHandler = { _ in + if firstSelection { + firstSelection = false + await selection.wait() + } + } + let first = Task { try await env.connect(.bluetooth) } + var replacement: Task? + do { + try await waitUntil("old preparation must reach metadata selection before publication") { selection.isWaiting } + let request = try #require(env.manager.desiredRequest) + let attempt = try #require(request.attempt) + let prepared = try #require(attempt.preparedServices) + #expect(env.manager.currentConnection == nil) + replacement = Task { try await env.connect(.wifi) } + try await waitUntil("replacement must synchronously revoke its predecessor") { + env.manager.connectionRequestID != request.id + } + #expect(!attempt.binding.isActive) + #expect(await env.wifi.connectCount == 0) + let held = try #require(try await env.manager.persistenceStore.fetchPendingSendsForMessage(messageID: message.id).first) + #expect(held.attemptCount == original.attemptCount) + selection.open() + _ = await first.result + let result = try await #require(replacement).value + #expect(env.manager.isCurrent(result)) + let current = try #require(env.manager.currentConnection) + #expect(env.manager.connectionState == .ready) + #expect(current.device.radioID != radioID) + #expect(!prepared.isAcceptingRuntimeWork) + #expect(prepared.chatSendQueueService.isRetiredForTesting) + let after = try #require(try await env.manager.persistenceStore.fetchPendingSendsForMessage(messageID: message.id).first) + #expect(after.attemptCount == original.attemptCount) + #expect(await env.ble.sentData.allSatisfy { $0.first != CommandCode.sendMessage.rawValue }) + #expect(try await current.services.session.getTime().timeIntervalSince1970 > 0) + #expect(await prepared.session.subscriberCountForTest == 0) + } catch { + selection.open() + first.cancel() + replacement?.cancel() + env.manager.testConnectionSelectionHandler = nil + await env.ble.releaseAllGates() + await env.wifi.releaseAllGates() + _ = await first.result + _ = await replacement?.result + await env.close() + throw error + } + env.manager.testConnectionSelectionHandler = nil + await env.close() + } + + @MainActor + private final class Gate { + private var continuation: CheckedContinuation? + private var isOpen = false + var isWaiting: Bool { + continuation != nil + } + + func wait() async { + guard !isOpen else { return } + await withCheckedContinuation { continuation = $0 } + } + + func open() { + isOpen = true + continuation?.resume() + continuation = nil + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPromotionTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPromotionTests.swift index c95f98b310..49d6254f5e 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPromotionTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPromotionTests.swift @@ -1,363 +1,150 @@ import Foundation @testable import MC1Services -import MeshCoreTestSupport +import MeshCore import Testing -@Suite("ConnectionManager Promotion Tests") +@Suite("Owned connection completion") @MainActor struct ConnectionManagerPromotionTests { - private func usableSyncResult( - channels: SyncPhaseStatus = .clean, - messages: SyncPhaseStatus = .clean - ) -> FullSyncResult { - FullSyncResult(contacts: .clean, channels: channels, messages: messages) - } - - private func unusableSyncResult() -> FullSyncResult { - FullSyncResult(contacts: .failed("sync failed"), channels: .skipped, messages: .skipped) - } - - private func makeTestServices() async throws -> ServiceContainer { - let transport = SimulatorMockTransport() - let session = MeshCoreSession(transport: transport) - return try await ServiceContainer.forTesting(session: session) - } - - /// Sets up manager state for promotion tests. Sets session and connectedDevice - /// so the .ready invariant can pass when promotion succeeds. - private func setupForPromotion( - manager: ConnectionManager, - services: ServiceContainer, - connectionState: DeviceConnectionState = .connected, - connectionIntent: ConnectionIntent = .wantsConnection(), - firmwareVersion: UInt8 = 9 - ) { - let mockTransport = SimulatorMockTransport() - let session = MeshCoreSession(transport: mockTransport) - manager.setTestState( - connectionState: connectionState, - services: services, - session: session, - connectedDevice: DeviceDTO.testDevice(firmwareVersion: firmwareVersion), - connectionIntent: connectionIntent - ) - } - - // MARK: - Suppression: services replaced - - @Test - func `promoteToReady suppressed when services replaced during sync`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let originalServices = try await makeTestServices() - let replacementServices = try await makeTestServices() - - setupForPromotion(manager: manager, services: originalServices) - - // Simulate: disconnect + new connection replaced services - manager.setTestState(services: replacementServices) - - let promoted = await manager.promoteToReady( - syncResult: usableSyncResult(), - expectedServices: originalServices, - transportType: .bluetooth - ) - - #expect(!promoted) - #expect(manager.connectionState == .connected) - } - - // MARK: - Suppression: services nil (disconnected) - - @Test - func `promoteToReady suppressed when services nil (disconnected)`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let originalServices = try await makeTestServices() - - manager.setTestState( - connectionState: .disconnected, - services: .some(nil), - connectionIntent: .wantsConnection() - ) - - let promoted = await manager.promoteToReady( - syncResult: usableSyncResult(), - expectedServices: originalServices, - transportType: .bluetooth - ) - - #expect(!promoted) - #expect(manager.connectionState == .disconnected) - } - - // MARK: - Sync failure sets .syncing (resync loop continues from there) - - @Test - func `promoteToReady sets .syncing when sync failed`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let services = try await makeTestServices() - - setupForPromotion(manager: manager, services: services) - - let promoted = await manager.promoteToReady( - syncResult: unusableSyncResult(), - expectedServices: services, - transportType: .bluetooth - ) - - #expect(promoted) - #expect(manager.connectionState == .syncing) - } - - // MARK: - Sync failure skips onDeviceSynced - - @Test - func `promoteToReady skips onDeviceSynced when sync failed`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let services = try await makeTestServices() - var onDeviceSyncedCalled = false - var becameUsable = false - - setupForPromotion(manager: manager, services: services) - manager.onConnectionBecameUsable = { becameUsable = true } - manager.onDeviceSynced = { _ in onDeviceSyncedCalled = true } - - let promoted = await manager.promoteToReady( - syncResult: unusableSyncResult(), - expectedServices: services, - transportType: .bluetooth - ) - - #expect(promoted, "Should still promote to .syncing for resync loop") - #expect(!onDeviceSyncedCalled, "onDeviceSynced should be skipped on sync failure") - #expect(!becameUsable) - } - - // MARK: - Sync success sets .ready and fires onDeviceSynced - - @Test - func `promoteToReady sets .ready when sync succeeded`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let services = try await makeTestServices() - - setupForPromotion(manager: manager, services: services) - - let promoted = await manager.promoteToReady( - syncResult: usableSyncResult(), - expectedServices: services, - transportType: .bluetooth - ) - - #expect(promoted) - #expect(manager.connectionState == .ready) - } - - @Test - func `promoteToReady calls onDeviceSynced when sync succeeded`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let services = try await makeTestServices() - var onDeviceSyncedCalled = false - - setupForPromotion(manager: manager, services: services) - manager.onDeviceSynced = { _ in onDeviceSyncedCalled = true } - - await manager.promoteToReady( - syncResult: usableSyncResult(), - expectedServices: services, - transportType: .bluetooth - ) - - #expect(onDeviceSyncedCalled) - } - - @Test - func `promoteToReady does NOT call onDeviceSynced when sync failed`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let services = try await makeTestServices() - var onDeviceSyncedCalled = false - - setupForPromotion(manager: manager, services: services) - manager.onDeviceSynced = { _ in onDeviceSyncedCalled = true } - - await manager.promoteToReady( - syncResult: unusableSyncResult(), - expectedServices: services, - transportType: .bluetooth - ) - - #expect(!onDeviceSyncedCalled) - } - - // MARK: - Happy path - - @Test - func `promoteToReady sets .ready and fires onDeviceSynced on successful sync`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let services = try await makeTestServices() - var onDeviceSyncedCalled = false - var becameUsableCount = 0 - - setupForPromotion(manager: manager, services: services) - manager.onConnectionBecameUsable = { [weak manager] in - #expect(manager?.connectionState == .ready) - #expect(!onDeviceSyncedCalled) - becameUsableCount += 1 + @Test(arguments: [TransportType.bluetooth, .wifi]) + func `production connection publishes readiness before its best effort clock tail`(type: TransportType) async throws { + let env = try ConnectionManagerRadioTestHarness() + let radio = type == .bluetooth ? env.ble : env.wifi + await radio.holdReplies(for: .getTime) + var readyEdges = 0 + var synced = 0 + env.manager.onConnectionBecameUsable = { snapshot in + #expect(env.manager.isCurrent(snapshot)) + #expect(synced == 0) + readyEdges += 1 } - manager.onDeviceSynced = { hasCleanRecipientData in + env.manager.onDeviceSynced = { snapshot, hasCleanRecipientData in + #expect(env.manager.isCurrent(snapshot)) #expect(hasCleanRecipientData) - #expect(becameUsableCount == 1) - onDeviceSyncedCalled = true + synced += 1 + } + let connect = Task { try await env.connect(type) } + do { + try await waitUntil("the production sync should make the connection usable") { env.manager.connectionState == .ready } + #expect(readyEdges == 1) + #expect(synced == 0) + await radio.releaseReplies(for: .getTime) + let result = try await connect.value + #expect(env.manager.isCurrent(result)) + #expect(synced == 1) + #expect(await radio.timeReads == 1) + #expect(await radio.cliCommands.filter { ConnectionTestRadioTransport.splitCLICommand($0).command == "get tz.offset" }.count == 1) + } catch { + await radio.releaseAllGates() + connect.cancel() + _ = await connect.result + await env.close() + throw error + } + await env.close() + } + + @Test(arguments: [TransportType.bluetooth, .wifi]) + func `failed initial contacts recover through the same production completion once`(type: TransportType) async throws { + let env = try ConnectionManagerRadioTestHarness() + let radio = type == .bluetooth ? env.ble : env.wifi + await radio.rejectNext(.getContacts) + var synced = 0 + var readyEdges = 0 + env.manager.onDeviceSynced = { _, _ in synced += 1 } + env.manager.onConnectionBecameUsable = { _ in readyEdges += 1 } + do { + _ = try await env.connect(type) + #expect(env.manager.connectionState == .syncing) + if type == .bluetooth { #expect(await radio.timeReads == 0) } + if type == .wifi { #expect(await radio.timeReads == 1) } + try await waitUntil(timeout: .seconds(12), "production resync should recover contacts") { synced == 1 } + #expect(env.manager.connectionState == .ready) + #expect(readyEdges == 1) + #expect(await radio.timeReads == 1) + #expect(await radio.cliCommands.filter { ConnectionTestRadioTransport.splitCLICommand($0).command == "get tz.offset" }.count == 1) + } catch { await env.close(); throw error } + await env.close() + } + + enum CompletionOutcome: CaseIterable { + case partialChannels + case failedMessages + case missingResult + + var syncResult: FullSyncResult? { + switch self { + case .partialChannels: FullSyncResult(contacts: .clean, channels: .partial, messages: .clean) + case .failedMessages: FullSyncResult(contacts: .clean, channels: .clean, messages: .failed("catch-up")) + case .missingResult: nil + } } - let promoted = await manager.promoteToReady( - syncResult: usableSyncResult(), - expectedServices: services, - transportType: .bluetooth - ) - - #expect(promoted) - #expect(manager.connectionState == .ready) - #expect(manager.currentTransportType == .bluetooth) - #expect(onDeviceSyncedCalled, "onDeviceSynced should fire on successful sync") - #expect(becameUsableCount == 1) - manager.setTestState(connectionState: .ready) - #expect(becameUsableCount == 1) - } - - // MARK: - Suppression: user disconnected - - @Test - func `promoteToReady suppressed when user disconnected during sync`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let services = try await makeTestServices() - - setupForPromotion(manager: manager, services: services, connectionIntent: .userDisconnected) - - let promoted = await manager.promoteToReady( - syncResult: usableSyncResult(), - expectedServices: services, - transportType: .bluetooth - ) - - #expect(!promoted) - #expect(manager.connectionState == .connected) - } - - // MARK: - Additional guard suppresses promotion - - @Test - func `promoteToReady suppressed when additionalGuard returns false`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let services = try await makeTestServices() - - setupForPromotion(manager: manager, services: services) - - let promoted = await manager.promoteToReady( - syncResult: usableSyncResult(), - expectedServices: services, - transportType: .bluetooth, - additionalGuard: { false } - ) - - #expect(!promoted) - #expect(manager.connectionState == .connected) - } - - @Test - func `promoteToReady completes for a radio CLI device when timezone sync fails`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let services = try await makeTestServices() - setupForPromotion(manager: manager, services: services, firmwareVersion: 14) - - let promoted = await manager.promoteToReady( - syncResult: usableSyncResult(), - expectedServices: services, - transportType: .bluetooth - ) - - #expect(promoted) - #expect(manager.connectionState == .ready) - } - - @Test - func `disconnect for power off leaves user disconnected`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let services = try await makeTestServices() - setupForPromotion( - manager: manager, - services: services, - connectionState: .ready, - connectionIntent: .wantsConnection() - ) - - await manager.disconnect(reason: .powerOff) - - #expect(manager.connectionIntent.isUserDisconnected) - #expect(manager.connectionState == .disconnected) - } - - @Test - func `promoteToReady passes false when channels are partial`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let services = try await makeTestServices() - var eligibility: Bool? - setupForPromotion(manager: manager, services: services) - manager.onDeviceSynced = { eligibility = $0 } - - let promoted = await manager.promoteToReady( - syncResult: usableSyncResult(channels: .partial), - expectedServices: services, - transportType: .bluetooth - ) - - #expect(promoted) - #expect(manager.connectionState == .ready) - #expect(eligibility == false) + var expectedEligibility: Bool? { + switch self { + case .partialChannels: false + case .failedMessages: true + case .missingResult: nil + } + } } - @Test - func `promoteToReady passes true when channels are clean and messages failed`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let services = try await makeTestServices() + @Test(arguments: CompletionOutcome.allCases) + func `owned completion forwards recipient eligibility from its sync result`(outcome: CompletionOutcome) async throws { + let env = try ConnectionManagerRadioTestHarness() + await env.ble.rejectNext(.getContacts) var eligibility: Bool? - setupForPromotion(manager: manager, services: services) - manager.onDeviceSynced = { eligibility = $0 } - - let promoted = await manager.promoteToReady( - syncResult: usableSyncResult(messages: .failed("catch-up")), - expectedServices: services, - transportType: .bluetooth - ) - - #expect(promoted) - #expect(manager.connectionState == .ready) - #expect(eligibility == true) + env.manager.onDeviceSynced = { snapshot, hasCleanRecipientData in + #expect(env.manager.isCurrent(snapshot)) + eligibility = hasCleanRecipientData + } + do { + _ = try await env.connect(.bluetooth) + #expect(env.manager.connectionState == .syncing) + #expect(eligibility == nil) + env.manager.cancelResyncLoop() + let link = try #require(env.manager.installedLink) + let completed = await env.manager.completeSync(link, syncResult: outcome.syncResult) + #expect(completed) + #expect(env.manager.connectionState == (outcome.syncResult == nil ? .syncing : .ready)) + #expect(eligibility == outcome.expectedEligibility) + } catch { await env.close(); throw error } + await env.close() + } + + @Test(arguments: [TransportType.bluetooth, .wifi]) + func `same radio transport handoff preserves partition and replaces the Link generation`(first: TransportType) async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + _ = try await env.connect(first) + let before = try #require(env.manager.currentConnection) + _ = try await env.connect(first == .bluetooth ? .wifi : .bluetooth) + let after = try #require(env.manager.currentConnection) + #expect(after.device.radioID == before.device.radioID) + #expect(after.generation != before.generation) + #expect(!env.manager.isCurrent(before)) + let active = try await env.manager.persistenceStore.fetchActiveDevice() + #expect(active?.id == after.device.id) + #expect(active?.lastUsedConnectionMethod?.isWiFi == (after.transportType == .wifi)) + } catch { await env.close(); throw error } + await env.close() } @Test - func `promoteToReady skips onDeviceSynced for a nil sync result`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - let services = try await makeTestServices() - var onDeviceSyncedCalled = false - setupForPromotion(manager: manager, services: services) - manager.onDeviceSynced = { _ in onDeviceSyncedCalled = true } - - let promoted = await manager.promoteToReady( - syncResult: nil, - expectedServices: services, - transportType: .bluetooth - ) - - #expect(promoted) - #expect(manager.connectionState == .syncing) - #expect(!onDeviceSyncedCalled) + func `a loss receipt cannot become current again after a newer stack retires`() async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + _ = try await env.connect(.bluetooth) + let request = try #require(env.manager.desiredRequest) + let old = env.manager.beginOwnedRetirement(previousRequest: request, phase: .connecting, closePhysical: true, retainMembership: true) + await old.value + #expect(env.manager.isCurrent(old.receipt)) + _ = try await env.manager.establishAttempt(request, preservePhysicalBLE: false) + let newer = env.manager.beginOwnedRetirement(previousRequest: request, phase: .disconnected, closePhysical: true, retainMembership: true) + await newer.value + #expect(env.manager.isCurrent(newer.receipt)) + #expect(!env.manager.isCurrent(old.receipt)) + } catch { await env.close(); throw error } + await env.close() } - - // MARK: - Post-time-sync re-validation (not unit-testable) - - // promoteToReady re-checks connectionIntent, services identity, and additionalGuard - // after syncDeviceTimeIfNeeded() returns. These guards are structurally identical to - // the pre-await guards tested above. Exercising them requires mutating state during - // the syncDeviceTimeIfNeeded() suspension point, which needs concurrency interleaving - // that unit tests cannot reliably control. Covering this path requires integration - // tests with a real (or delay-injected) session where state can change mid-await. } diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerRadioWiFiDrainTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerRadioWiFiDrainTests.swift new file mode 100644 index 0000000000..b28493f62d --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerRadioWiFiDrainTests.swift @@ -0,0 +1,53 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("ConnectionManager WiFi mutation drain") +@MainActor +struct ConnectionManagerRadioWiFiDrainTests { + @Test + func `replacement radio waits for a submitted Tools write and retains only its source evidence`() async throws { + try await ConnectionRadioHandoffHarness.withHarness(wifiIsSameRadio: false) { harness in + try await harness.connectBluetooth() + let original = try #require(harness.manager.currentConnection) + let stateA = original.services.settingsService.radioWiFiState + let stateB = harness.manager.radioWiFiState(for: harness.deviceB.radioID) + let stream = await original.services.settingsService.events() + let consumer = harness.track(Task { for await _ in stream {} }) + await harness.bluetooth.holdNextSendCompletion() + let write = harness.track(Task { + try await original.services.settingsService.runCliCommand("set wifi.pwd synthetic-terminal") + }) + try await waitUntil("Tools setter should reach actual physical completion gate") { + await harness.bluetooth.sendCompletionIsHeld + } + #expect(await harness.bluetooth.cliCommands.contains("set wifi.pwd synthetic-terminal")) + write.cancel() + consumer.cancel() + await consumer.value + let replacement = harness.track(Task { + try await harness.manager.connectViaWiFi(host: "radio.local", port: 4242) + }) + try await waitUntil("replacement should retire the old publication") { + harness.manager.currentConnection == nil && harness.manager.connectionTeardownCount > 0 + } + #expect(await harness.wifi.connectCount == 0) + #expect(!stateB.rebootPending) + + await harness.bluetooth.releaseSendCompletion() + _ = await write.result + _ = try await replacement.value + + #expect(harness.manager.connectedDevice?.radioID == harness.deviceB.radioID) + #expect(harness.manager.connectionState == .ready) + #expect(stateA.rebootPending) + #expect(stateA.stableRevision() != nil) + #expect(!stateB.rebootPending) + #expect(harness.manager.services?.settingsService.radioWiFiState === stateB) + try await harness.connectBluetooth() + #expect(harness.manager.services?.settingsService.radioWiFiState === stateA) + #expect(stateA.rebootPending) + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerRebuildResultPortTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerRebuildResultPortTests.swift new file mode 100644 index 0000000000..ed23a9e10d --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerRebuildResultPortTests.swift @@ -0,0 +1,150 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import os +import Testing + +@Suite("Manager rebuild result ownership") +@MainActor +struct ConnectionManagerRebuildResultPortTests { + private static let secondRebuildArrivalTimeout: Duration = .seconds(15) + + enum Outcome: CaseIterable { + case success + case failure + case cancellation + } + + @Test(.timeLimit(.minutes(1)), arguments: Outcome.allCases) + func `obsolete second rebuild cannot invoke manager exhaustion against a same-radio successor`(outcome: Outcome) async throws { + let env = try ConnectionManagerRadioTestHarness() + let deliveries = OSAllocatedUnfairLock<[Task]>(initialState: []) + var exhausted: [UUID] = [] + var replacement: Task? + do { + _ = try await env.connect(.bluetooth) + let initial = try #require(env.manager.currentConnection) + await captureDeliveries(env, into: deliveries) + env.manager.reconnectionCoordinator.onExhausted = { [weak manager = env.manager] cycle in + exhausted.append(cycle.id) + await manager?.finishBLERecoveryFailure(cycle) + } + await env.ble.rejectNext(.appStart) + await env.ble.holdReplies(for: .deviceQuery) + if outcome == .failure { await env.ble.rejectNext(.deviceQuery) } + await env.ble.simulateAutoReconnecting(deviceID: env.deviceID) + let loss = try #require(deliveries.withLock { $0.last }) + await loss.value + let cycle = try #require(env.manager.reconnectionCoordinator.currentCycle) + await env.ble.simulateReconnected() + let completion = try #require(deliveries.withLock { $0.last }) + try await waitUntil(timeout: Self.secondRebuildArrivalTimeout, "the failed first rebuild must reach its held second capability result") { + await env.ble.heldReplyCount(for: .deviceQuery) == 1 + } + #expect(await env.ble.sentData.filter { $0.first == CommandCode.appStart.rawValue }.count == 3) + let oldResource = try #require(env.manager.desiredRequest?.attempt?.resource) + replacement = Task { try await env.connect(.wifi) } + try await waitUntil("the manual successor must replace the rebuilding request") { + env.manager.connectionRequestID != cycle.requestID + } + #expect(env.manager.currentConnection == nil) + #expect(!oldResource.binding.isActive) + #expect(await env.wifi.connectCount == 0) + if outcome == .cancellation { completion.cancel() } + await env.ble.releaseReplies(for: .deviceQuery) + let result = try await #require(replacement).value + let current = try #require(env.manager.currentConnection) + let closes = await env.ble.disconnectCount + await completion.value + #expect(env.manager.isCurrent(result)) + #expect(env.manager.isCurrent(current)) + #expect(current.device.radioID == initial.device.radioID) + #expect(current.generation != initial.generation) + #expect(exhausted.isEmpty) + #expect(env.manager.consecutiveRebuildFailures == 0) + #expect(env.manager.reconnectionCoordinator.currentCycle == nil) + #expect(env.manager.connectionState == .ready) + #expect(!env.manager.isReconnectionWatchdogRunning) + #expect(await env.ble.disconnectCount == closes) + #expect(await oldResource.session.subscriberCountForTest == 0) + #expect(try await current.services.session.getTime().timeIntervalSince1970 > 0) + } catch { + replacement?.cancel() + await releaseAndClose(env, deliveries: deliveries) + _ = await replacement?.result + throw error + } + await releaseAndClose(env, deliveries: deliveries) + } + + @Test(.timeLimit(.minutes(1))) + func `current retry exhaustion invokes manager cleanup and permits the next working connection`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let deliveries = OSAllocatedUnfairLock<[Task]>(initialState: []) + var exhausted: [UUID] = [] + do { + _ = try await env.connect(.bluetooth) + let initial = try #require(env.manager.currentConnection) + await captureDeliveries(env, into: deliveries) + env.manager.reconnectionCoordinator.onExhausted = { [weak manager = env.manager] cycle in + exhausted.append(cycle.id) + await manager?.finishBLERecoveryFailure(cycle) + } + await env.ble.rejectNext(.appStart, count: 2) + await env.ble.simulateAutoReconnecting(deviceID: env.deviceID) + let loss = try #require(deliveries.withLock { $0.last }) + await loss.value + let cycle = try #require(env.manager.reconnectionCoordinator.currentCycle) + await env.ble.simulateReconnected() + let completion = try #require(deliveries.withLock { $0.last }) + await completion.value + #expect(exhausted == [cycle.id]) + #expect(env.manager.consecutiveRebuildFailures == 1) + #expect(env.manager.reconnectionCoordinator.currentCycle == nil) + #expect(env.manager.currentConnection == nil) + #expect(env.manager.connectionState == .disconnected) + #expect(env.manager.isReconnectionWatchdogRunning) + #expect(await env.ble.isConnected == false) + #expect(await initial.services.session.subscriberCountForTest == 0) + let next = try await env.connect(.wifi) + #expect(env.manager.isCurrent(next)) + let current = try #require(env.manager.currentConnection) + #expect(current.device.radioID == initial.device.radioID) + #expect(env.manager.connectionState == .ready) + #expect(try await current.services.session.getTime().timeIntervalSince1970 > 0) + } catch { + await releaseAndClose(env, deliveries: deliveries) + throw error + } + await releaseAndClose(env, deliveries: deliveries) + } + + private func captureDeliveries( + _ env: ConnectionManagerRadioTestHarness, + into deliveries: OSAllocatedUnfairLock<[Task]> + ) async { + await env.ble.setLifecycleHandler { [weak manager = env.manager] event in + let worker = Task { @MainActor in + guard let manager else { return } + await manager.handleBLELifecycleEvent(event) + } + deliveries.withLock { $0.append(worker) } + } + } + + private func releaseAndClose( + _ env: ConnectionManagerRadioTestHarness, + deliveries: OSAllocatedUnfairLock<[Task]> + ) async { + for task in deliveries.withLock({ $0 }) { + task.cancel() + } + await env.ble.releaseAllGates() + await env.wifi.releaseAllGates() + await env.close() + for task in deliveries.withLock({ $0 }) { + await task.value + } + env.manager.reconnectionCoordinator.onExhausted = nil + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerReconnectAbandonmentTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerReconnectAbandonmentTests.swift index b8cadf1856..4fe50d02c5 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerReconnectAbandonmentTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerReconnectAbandonmentTests.swift @@ -9,7 +9,7 @@ import Testing @Suite("ConnectionManager Reconnect Abandonment Tests") @MainActor struct ConnectionManagerReconnectAbandonmentTests { - // MARK: - handleReconnectionFailure + // MARK: - Recovery failure policy @Test func `reconnection failure preserves a live link and keeps the watchdog armed`() async throws { @@ -26,13 +26,13 @@ struct ConnectionManagerReconnectAbandonmentTests { connectionIntent: .wantsConnection() ) - await env.manager.handleReconnectionFailure() + await env.manager.finishSeededBLERecovery() #expect(await env.transport.disconnectInvocations == 0) #expect(env.manager.connectionState == .disconnected) #expect(env.manager.isReconnectionWatchdogRunning) #expect(env.manager.consecutiveRebuildFailures == 1) - #expect(env.manager.activeReconnectDeviceID == nil) + #expect(env.manager.reconnectionCoordinator.reconnectingDeviceID == nil) } @Test @@ -47,7 +47,7 @@ struct ConnectionManagerReconnectAbandonmentTests { connectionIntent: .wantsConnection() ) - await env.manager.handleReconnectionFailure() + await env.manager.finishSeededBLERecovery() #expect(await env.transport.disconnectInvocations == 1) #expect(env.manager.connectionState == .disconnected) @@ -68,7 +68,7 @@ struct ConnectionManagerReconnectAbandonmentTests { connectionIntent: .userDisconnected ) - await env.manager.handleReconnectionFailure() + await env.manager.finishSeededBLERecovery() #expect(await env.transport.disconnectInvocations == 1) #expect(!env.manager.isReconnectionWatchdogRunning) @@ -95,11 +95,11 @@ struct ConnectionManagerReconnectAbandonmentTests { let budget = ConnectionManager.maxRebuildFailuresPreservingLink for _ in 0.. armedGeneration) @@ -248,7 +181,7 @@ struct ConnectionManagerReconnectAbandonmentTests { connectionIntent: .userDisconnected ) - await env.manager.handleReconnectionFailure() + await env.manager.finishSeededBLERecovery() #expect(env.manager.consecutiveRebuildFailures == 0) } @@ -267,7 +200,7 @@ struct ConnectionManagerReconnectAbandonmentTests { let budget = ConnectionManager.maxRebuildFailuresPreservingLink for _ in 0...budget { - await env.manager.handleReconnectionFailure() + await env.manager.finishSeededBLERecovery() } #expect(await env.transport.disconnectInvocations == 1) @@ -276,7 +209,7 @@ struct ConnectionManagerReconnectAbandonmentTests { #expect(env.manager.consecutiveRebuildFailures == 0) // Further failure still preserves. - await env.manager.handleReconnectionFailure() + await env.manager.finishSeededBLERecovery() #expect(await env.transport.disconnectInvocations == 1) } @@ -297,14 +230,14 @@ struct ConnectionManagerReconnectAbandonmentTests { #expect(env.manager.isReconnectionWatchdogRunning) env.manager.setTestState(connectionState: .connecting) - await env.manager.handleReconnectionFailure() + await env.manager.finishSeededBLERecovery() // Preserve must not cancel+restart (generation would advance via stop). #expect(env.manager.reconnectionWatchdogGeneration == firstGeneration) #expect(env.manager.isReconnectionWatchdogRunning) } - // MARK: - notifyConnectionLost + // MARK: - Source loss policy @Test func `connection-lost notification while wanting connection arms the watchdog`() async throws { @@ -316,7 +249,7 @@ struct ConnectionManagerReconnectAbandonmentTests { connectionIntent: .wantsConnection() ) - await manager.notifyConnectionLost() + await manager.acceptSeededBLELoss() #expect(manager.isReconnectionWatchdogRunning) } @@ -331,7 +264,7 @@ struct ConnectionManagerReconnectAbandonmentTests { connectionIntent: .userDisconnected ) - await manager.notifyConnectionLost() + await manager.acceptSeededBLELoss() #expect(!manager.isReconnectionWatchdogRunning) } @@ -346,7 +279,11 @@ struct ConnectionManagerReconnectAbandonmentTests { connectionIntent: .wantsConnection() ) - await manager.notifyConnectionLost() + manager.desiredRequest = ConnectionRequest( + targets: [.wifi(host: "radio.test", port: 5123)], origin: .recovery, + forceFullSync: false, forceReconnect: false, continuing: nil + ) + await manager.acceptSeededBLELoss() #expect(!manager.isReconnectionWatchdogRunning) } @@ -361,7 +298,13 @@ struct ConnectionManagerReconnectAbandonmentTests { let env = try ConnectionManager.createForPairingTesting() defer { env.cleanup() } let deviceID = UUID() + env.accessorySetupKit.setPairedAccessories([ASAccessory(bluetoothIdentifier: deviceID, displayName: "Radio")]) + try await env.accessorySetupKit.activateSession() + await env.transport.setConnectError(BLEError.deviceNotFound) + let request = env.manager.seedBLERecoveryRequest(deviceID: deviceID) + request.handedOff = true + _ = env.manager.reconnectionCoordinator.begin(deviceID: deviceID, requestID: request.id) env.manager.reconnectionCoordinator.restartTimeout(deviceID: deviceID) env.manager.setTestState( connectionState: .disconnected, @@ -369,14 +312,14 @@ struct ConnectionManagerReconnectAbandonmentTests { connectionIntent: .wantsConnection() ) - // The mock pairing registry has no paired accessories, so the fresh attempt - // fails fast with the real "device not found" error instead of hanging - proof - // the call reached a genuine connect attempt rather than deferring. - await #expect(throws: ConnectionError.self) { + // The valid paired target reaches the transport, which rejects the fresh dial. + // This distinguishes a new attempt from joining the abandoned OS cycle. + await #expect(throws: ConnectionRequestFailure.self) { try await env.manager.connect(to: deviceID, forceReconnect: true) } - #expect(await env.transport.disconnectInvocations == 1) + #expect(await env.transport.connectInvocations.count == 1) + #expect(await env.transport.disconnectInvocations == 2) #expect(env.manager.reconnectionCoordinator.reconnectingDeviceID == nil) #expect(env.manager.connectionState == .disconnected) } @@ -388,7 +331,13 @@ struct ConnectionManagerReconnectAbandonmentTests { let env = try ConnectionManager.createForPairingTesting() defer { env.cleanup() } let deviceID = UUID() + env.accessorySetupKit.setPairedAccessories([ASAccessory(bluetoothIdentifier: deviceID, displayName: "Radio")]) + try await env.accessorySetupKit.activateSession() + await env.transport.setConnectError(BLEError.deviceNotFound) + let request = env.manager.seedBLERecoveryRequest(deviceID: deviceID) + request.handedOff = true + _ = env.manager.reconnectionCoordinator.begin(deviceID: deviceID, requestID: request.id) env.manager.reconnectionCoordinator.restartTimeout(deviceID: deviceID) env.manager.setTestState( connectionState: .connecting, @@ -410,7 +359,13 @@ struct ConnectionManagerReconnectAbandonmentTests { let env = try ConnectionManager.createForPairingTesting() defer { env.cleanup() } let deviceID = UUID() + env.accessorySetupKit.setPairedAccessories([ASAccessory(bluetoothIdentifier: deviceID, displayName: "Radio")]) + try await env.accessorySetupKit.activateSession() + await env.transport.setConnectError(BLEError.deviceNotFound) + let request = env.manager.seedBLERecoveryRequest(deviceID: deviceID) + request.handedOff = true + _ = env.manager.reconnectionCoordinator.begin(deviceID: deviceID, requestID: request.id) env.manager.reconnectionCoordinator.restartTimeout(deviceID: deviceID) env.manager.setTestState( connectionState: .disconnected, @@ -426,26 +381,33 @@ struct ConnectionManagerReconnectAbandonmentTests { } @Test - func `forceReconnect connect while a session rebuild is in flight for the device defers instead of breaking glass`() async throws { - // A live session rebuild is progress, not a stuck wait: tearing down the - // transport under it would destroy a reconnect that is about to succeed. - let env = try ConnectionManager.createForPairingTesting() - defer { env.cleanup() } - let deviceID = UUID() - - env.manager.reconnectionCoordinator.restartTimeout(deviceID: deviceID) - env.manager.setTestState( - connectionState: .disconnected, - currentTransportType: .bluetooth, - connectionIntent: .wantsConnection(), - sessionRebuildDeviceID: deviceID - ) - - try await env.manager.connect(to: deviceID, forceReconnect: true) - - #expect(await env.transport.disconnectInvocations == 0) - #expect(env.manager.reconnectionCoordinator.reconnectingDeviceID == deviceID) - #expect(env.manager.connectionState == .disconnected) + func `forceReconnect during an actual rebuild joins the cycle even after UI abandonment`() async throws { + let harness = try ConnectionManagerRadioTestHarness() + do { + _ = try await harness.connect(.bluetooth) + await harness.ble.holdReplies(for: .appStart) + await harness.ble.simulateAutoReconnecting(deviceID: harness.deviceID) + try await waitUntil("loss should claim recovery") { harness.manager.reconnectionCoordinator.reconnectingDeviceID == harness.deviceID } + await harness.ble.simulateReconnected() + try await waitUntil("a real rebuild should hold the handshake") { + guard let cycle = harness.manager.reconnectionCoordinator.currentCycle else { return false } + return harness.manager.reconnectionCoordinator.isRebuilding(cycle) + } + harness.manager.setTestState(connectionState: .disconnected) + let owner = harness.manager.connectionRequestID + let result = try await harness.manager.connect(to: harness.deviceID, forceReconnect: true) + guard case let .handoff(requestID) = result else { + Issue.record("forced connect should join the live rebuild") + await harness.close() + return + } + #expect(requestID == owner) + #expect(await harness.ble.connectCount == 1) + await harness.ble.releaseReplies(for: .appStart) + try await waitUntil("the joined rebuild should become ready") { harness.manager.connectionState == .ready } + _ = try await harness.manager.session?.getTime() + await harness.close() + } catch { await harness.close(); throw error } } @Test @@ -456,7 +418,12 @@ struct ConnectionManagerReconnectAbandonmentTests { let env = try ConnectionManager.createForPairingTesting() defer { env.cleanup() } let deviceID = UUID() + env.accessorySetupKit.setPairedAccessories([ASAccessory(bluetoothIdentifier: deviceID, displayName: "Radio")]) + try await env.accessorySetupKit.activateSession() + await env.transport.setConnectError(BLEError.deviceNotFound) + let request = env.manager.seedBLERecoveryRequest(deviceID: deviceID) + request.handedOff = true await env.stateMachine.setStubbedIsAutoReconnecting(true) await env.stateMachine.setStubbedConnectedDeviceID(deviceID) env.manager.setTestState( @@ -465,11 +432,12 @@ struct ConnectionManagerReconnectAbandonmentTests { connectionIntent: .wantsConnection() ) - await #expect(throws: ConnectionError.self) { + await #expect(throws: ConnectionRequestFailure.self) { try await env.manager.connect(to: deviceID, forceReconnect: true) } - #expect(await env.transport.disconnectInvocations == 1) + #expect(await env.transport.connectInvocations.count == 1) + #expect(await env.transport.disconnectInvocations == 2) #expect(env.manager.connectionState == .disconnected) } @@ -477,72 +445,49 @@ struct ConnectionManagerReconnectAbandonmentTests { @Test func `overlapping health checks on a connected missing stack rebuild once`() async throws { - let env = try ConnectionManager.createForPairingTesting() - defer { env.cleanup() } - let deviceID = UUID() - - await env.stateMachine.setStubbedIsConnected(true) - env.manager.testLastConnectedDeviceID = deviceID - env.manager.setTestState( - connectionState: .disconnected, - services: .some(nil), - session: .some(nil), - connectedDevice: .some(nil), - currentTransportType: .bluetooth, - connectionIntent: .wantsConnection() - ) - - var rebuildCount = 0 - env.manager.rebuildSessionForHealthCheckOverride = { _ in - rebuildCount += 1 - try await Task.sleep(for: .milliseconds(50)) - throw ConnectionError.initializationFailed("test rebuild fail") - } - - async let first: Void = env.manager.checkBLEConnectionHealth() - async let second: Void = env.manager.checkBLEConnectionHealth() - _ = await (first, second) - - #expect(rebuildCount == 1) - // Failure path preserves the link under budget. - #expect(await env.transport.disconnectInvocations == 0) + let harness = try ConnectionManagerRadioTestHarness() + do { + await harness.ble.primePhysicalLink(deviceID: harness.deviceID) + await harness.ble.holdReplies(for: .appStart) + await harness.stateMachine.setStubbedIsConnected(true) + await harness.stateMachine.setStubbedConnectedDeviceID(harness.deviceID) + harness.manager.testLastConnectedDeviceID = harness.deviceID + harness.manager.setTestState(connectionIntent: .wantsConnection()) + let first = Task { await harness.manager.checkBLEConnectionHealth() } + let second = Task { await harness.manager.checkBLEConnectionHealth() } + try await waitUntil("exactly one rebuild should submit the held handshake") { + await harness.ble.sentData.filter { $0.first == CommandCode.appStart.rawValue }.count == 1 + } + await harness.ble.releaseReplies(for: .appStart) + await first.value + await second.value + #expect(harness.manager.connectionState == .ready) + #expect(await harness.ble.sentData.filter { $0.first == CommandCode.appStart.rawValue }.count == 1) + #expect(await harness.ble.connectCount == 0) + _ = try await harness.manager.session?.getTime() + await harness.close() + } catch { await harness.close(); throw error } } @Test - func `coordinator cycle claim blocks health rebuild during retry gap`() async throws { - let env = try ConnectionManager.createForPairingTesting() - defer { env.cleanup() } - let deviceID = UUID() - - await env.stateMachine.setStubbedIsConnected(true) - env.manager.testLastConnectedDeviceID = deviceID - env.manager.setTestState( - connectionState: .disconnected, - services: .some(nil), - session: .some(nil), - connectedDevice: .some(nil), - currentTransportType: .bluetooth, - connectionIntent: .wantsConnection() - ) - - // Claim via the real entry path so reconnectingDeviceID is set the same way - // handleReconnectionComplete keeps it across first-fail → sleep. - await env.manager.reconnectionCoordinator.handleEnteringAutoReconnect(deviceID: deviceID) - #expect(env.manager.reconnectionCoordinator.reconnectingDeviceID == deviceID) - - // After entry, state is .connecting; health path for connected transport needs - // BLE connected + missing stack. Keep the claim and flip UI to disconnected - // while SM stays connected so health would rebuild if unclaimed. - env.manager.setTestState(connectionState: .disconnected) - - var rebuildCount = 0 - env.manager.rebuildSessionForHealthCheckOverride = { _ in - rebuildCount += 1 - } - - await env.manager.checkBLEConnectionHealth() - - #expect(env.manager.activeReconnectDeviceID == deviceID) - #expect(rebuildCount == 0) + func `coordinator cycle blocks health rebuild until the OS reconnect completes`() async throws { + let harness = try ConnectionManagerRadioTestHarness() + do { + _ = try await harness.connect(.bluetooth) + await harness.ble.simulateAutoReconnecting(deviceID: harness.deviceID) + try await waitUntil("source loss should retain its cycle") { + harness.manager.reconnectionCoordinator.reconnectingDeviceID == harness.deviceID && harness.manager.connectionTeardownCount == 0 + } + harness.manager.setTestState(connectionState: .disconnected) + await harness.stateMachine.setStubbedIsConnected(true) + await harness.stateMachine.setStubbedConnectedDeviceID(harness.deviceID) + await harness.manager.checkBLEConnectionHealth() + #expect(harness.manager.reconnectionCoordinator.reconnectingDeviceID == harness.deviceID) + #expect(await harness.ble.sentData.filter { $0.first == CommandCode.appStart.rawValue }.count == 1) + await harness.ble.simulateReconnected() + try await waitUntil("the retained cycle should still rebuild") { harness.manager.connectionState == .ready } + _ = try await harness.manager.session?.getTime() + await harness.close() + } catch { await harness.close(); throw error } } } diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerReconnectWindowTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerReconnectWindowTests.swift new file mode 100644 index 0000000000..b44f2db5b9 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerReconnectWindowTests.swift @@ -0,0 +1,312 @@ +import Foundation +@testable import MC1Services +import MeshCoreTestSupport +import Testing + +@Suite("ConnectionManager reconnect presentation window") +@MainActor +struct ConnectionManagerReconnectWindowTests { + enum NextAction: CaseIterable { + case restart + case sameRadioCycle + case differentRadio + case disconnect + } + + @Test(.timeLimit(.minutes(1)), arguments: [false, true]) + func `same-radio handoff refreshes the whole presentation window`(forceReconnect: Bool) async throws { + try await withFixture { fixture in + let cycle = try #require(fixture.coordinator.currentCycle) + let receipt = try #require(fixture.manager.currentLossReceipt) + for _ in 0..<3 { + try await fixture.advanceRearmingInterval() + } + fixture.clock.advance(by: .seconds(10)) + + let result = try await fixture.manager.connect( + to: fixture.deviceID, forceFullSync: true, forceReconnect: forceReconnect + ) + guard case let .handoff(requestID) = result else { + Issue.record("The connect must join the existing recovery request") + return + } + #expect(requestID == fixture.request.id) + try await waitUntil("the refreshed timeout must park") { fixture.clock.sleeperCount == 1 } + fixture.clock.advance(by: .seconds(5)) + try await waitUntil("the old deadline must be handled or remain superseded") { + fixture.clock.sleeperCount == 1 || !fixture.losses.isEmpty + } + try await waitUntil("state events must reach the current publication") { + fixture.events.values.last == fixture.manager.connectionState + } + #expect(fixture.manager.connectionState == .connecting) + #expect(fixture.losses.isEmpty) + #expect(fixture.events.values == [.connecting]) + try #require(fixture.clock.sleeperCount == 1) + #expect(fixture.manager.desiredRequest === fixture.request) + #expect(fixture.coordinator.currentCycle == cycle) + #expect(fixture.manager.currentLossReceipt?.id == receipt.id) + #expect(fixture.manager.currentConnection == nil) + #expect(fixture.manager.services == nil) + #expect(fixture.manager.session == nil) + #expect(await fixture.env.transport.connectInvocations.isEmpty) + #expect(await fixture.env.transport.disconnectInvocations == 0) + + try await fixture.advanceRearmingInterval(by: .seconds(10)) + for _ in 0..<2 { + try await fixture.advanceRearmingInterval() + } + fixture.clock.advance(by: .seconds(15)) + try await waitUntil("the refreshed window must eventually expire") { fixture.losses.count == 1 } + try await waitUntil("expiry must publish its state event") { fixture.events.values.count == 2 } + #expect(fixture.events.values == [.connecting, .disconnected]) + #expect(fixture.losses.map(\.id) == [receipt.id]) + #expect(fixture.manager.connectionState == .disconnected) + #expect(fixture.manager.desiredRequest === fixture.request) + #expect(fixture.coordinator.currentCycle == cycle) + #expect(fixture.manager.connectionIntent.wantsConnection) + #expect(fixture.clock.sleeperCount == 0) + #expect(await fixture.env.stateMachine.isAutoReconnecting) + #expect(await fixture.env.transport.connectInvocations.isEmpty) + #expect(await fixture.env.transport.disconnectInvocations == 0) + + let abandoned = try await fixture.manager.connect(to: fixture.deviceID) + #expect(fixture.manager.isCurrent(abandoned)) + #expect(fixture.manager.connectionState == .disconnected) + #expect(fixture.manager.desiredRequest === fixture.request) + #expect(fixture.coordinator.currentCycle == cycle) + // Probe the elapsed window without beginning or restarting the recovery cycle. + fixture.manager.setTestState(connectionState: .connecting) + fixture.coordinator.armTimeout(cycle) + try await waitUntil("the elapsed-window probe must park") { fixture.clock.sleeperCount == 1 } + fixture.clock.advance(by: .seconds(15)) + try await waitUntil("the probe must expire or rearm") { + fixture.losses.count == 2 || fixture.clock.sleeperCount == 1 + } + try await waitUntil("the probe's state event must be recorded") { + fixture.events.values.last == fixture.manager.connectionState + } + #expect(fixture.losses.map(\.id) == [receipt.id, receipt.id]) + #expect(fixture.events.values == [.connecting, .disconnected, .connecting, .disconnected]) + #expect(fixture.clock.sleeperCount == 0) + } + } + + @Test(.timeLimit(.minutes(1)), arguments: [false, true]) + func `same-radio handoff leaves an active rebuild without a presentation timer`(forceReconnect: Bool) async throws { + try await withFixture { fixture in + let cycle = try #require(fixture.coordinator.currentCycle) + let gate = fixture.gate() + var rebuilding = false + fixture.coordinator.onRebuild = { _ in + rebuilding = true + await gate.wait() + try Task.checkCancellation() + } + fixture.tasks.append(Task { + await fixture.manager.handleBLELifecycleEvent(.reconnected(fixture.origin)) + }) + try await waitUntil("the real coordinator must enter its rebuild") { rebuilding } + #expect(fixture.coordinator.isRebuilding(cycle)) + #expect(fixture.clock.sleeperCount == 0) + + let result = try await fixture.manager.connect(to: fixture.deviceID, forceReconnect: forceReconnect) + guard case let .handoff(requestID) = result else { + Issue.record("The connect must join the existing recovery request") + return + } + #expect(requestID == fixture.request.id) + fixture.clock.advance(by: .seconds(120)) + #expect(fixture.clock.sleeperCount == 0) + #expect(fixture.coordinator.isRebuilding(cycle)) + #expect(fixture.coordinator.currentCycle == cycle) + #expect(fixture.manager.desiredRequest === fixture.request) + #expect(fixture.manager.connectionState == .connecting) + #expect(fixture.events.values == [.connecting]) + #expect(fixture.losses.isEmpty) + #expect(await fixture.env.transport.connectInvocations.isEmpty) + #expect(await fixture.env.transport.disconnectInvocations == 0) + } + } + + @Test(.timeLimit(.minutes(1)), arguments: [false, true], NextAction.allCases) + func `a suspended timeout query cannot affect a restarted or replaced owner`(oldResult: Bool, action: NextAction) async throws { + try await withFixture { fixture in + let oldCycle = try #require(fixture.coordinator.currentCycle) + let gate = fixture.gate() + let originalQuery = fixture.coordinator.isAutoReconnecting + fixture.coordinator.isAutoReconnecting = { + fixture.activeQueries += 1 + defer { fixture.activeQueries -= 1 } + await gate.wait() + return oldResult + } + fixture.clock.advance(by: .seconds(15)) + try await waitUntil("the old timeout must suspend in its transport query") { fixture.activeQueries == 1 } + + let expectedEventCount: Int + switch action { + case .restart: + _ = try await fixture.manager.connect(to: fixture.deviceID, forceReconnect: true) + expectedEventCount = 1 + case .sameRadioCycle: + let nextOrigin = BLELifecycleOrigin(deviceID: fixture.deviceID, generation: 2, eventTime: fixture.request.admittedAt) + await fixture.manager.enterBLERecovery(fixture.request, origin: nextOrigin) + expectedEventCount = 2 + case .differentRadio: + let nextID = UUID() + fixture.env.accessorySetupKit.setPairedAccessories([ + ASAccessory(bluetoothIdentifier: nextID, displayName: "Next") + ]) + _ = try await fixture.manager.requestConnection( + targets: [.bluetooth(nextID)], origin: .explicit, forceFullSync: false, forceReconnect: true, + operation: { request in + let origin = BLELifecycleOrigin(deviceID: nextID, generation: 2, eventTime: request.admittedAt) + await fixture.manager.enterBLERecovery(request, origin: origin) + return .handoff(requestID: request.id) + } + ) + expectedEventCount = 3 + case .disconnect: + await fixture.manager.disconnect() + expectedEventCount = 2 + } + if action != .disconnect { + try await waitUntil("the current timeout must park") { fixture.clock.sleeperCount == 1 } + } + try await waitUntil("the action's state events must be recorded") { fixture.events.values.count == expectedEventCount } + let request = try #require(fixture.manager.desiredRequest) + let currentCycle = fixture.coordinator.currentCycle + let receipt = try #require(fixture.manager.currentLossReceipt) + let events = fixture.events.values + let losses = fixture.losses.map(\.id) + let disconnects = await fixture.env.transport.disconnectInvocations + #expect((currentCycle == oldCycle) == (action == .restart)) + fixture.coordinator.isAutoReconnecting = originalQuery + gate.open() + try await waitUntil("the old transport query must settle") { fixture.activeQueries == 0 } + + if action == .disconnect { + fixture.clock.advance(by: .seconds(120)) + #expect(fixture.clock.sleeperCount == 0) + #expect(fixture.manager.connectionState == .disconnected) + #expect(fixture.manager.connectionIntent.isUserDisconnected) + } else { + for _ in 0..<3 { + try await fixture.advanceRearmingInterval() + } + fixture.clock.advance(by: .seconds(15)) + try await waitUntil("only the current window may publish loss") { fixture.losses.count > losses.count } + try await waitUntil("the current expiry event must be recorded") { fixture.events.values.count > events.count } + #expect(fixture.manager.connectionState == .disconnected) + #expect(fixture.events.values == events + [.disconnected]) + #expect(fixture.losses.map(\.id) == losses + [receipt.id]) + } + if action == .disconnect { + #expect(fixture.events.values == events) + #expect(fixture.losses.map(\.id) == losses) + } + #expect(fixture.manager.desiredRequest === request) + #expect(fixture.coordinator.currentCycle == currentCycle) + #expect(fixture.manager.currentLossReceipt?.id == receipt.id) + #expect(fixture.manager.currentConnection == nil) + #expect(fixture.manager.services == nil) + #expect(fixture.manager.session == nil) + #expect(await fixture.env.transport.connectInvocations.isEmpty) + #expect(await fixture.env.transport.disconnectInvocations == disconnects) + } + } + + private func withFixture(_ body: @MainActor (Fixture) async throws -> Void) async throws { + let fixture = try Fixture() + do { + try await fixture.start() + try await body(fixture) + } catch { + await fixture.close() + throw error + } + await fixture.close() + } + + @MainActor + private final class Fixture { + let clock: TestClock + let env: PairingTestEnvironment + let deviceID: UUID + let request: ConnectionRequest + let events = ValueTracker() + var losses: [ConnectionLossReceipt] = [] + var tasks: [Task] = [] + var activeQueries = 0 + private var gates: [BLEReconnectionTestHarness.Gate] = [] + private var observer: Task? + + var manager: ConnectionManager { + env.manager + } + + var coordinator: BLEReconnectionCoordinator { + manager.reconnectionCoordinator + } + + var origin: BLELifecycleOrigin { + BLELifecycleOrigin(deviceID: deviceID, generation: 1, eventTime: request.admittedAt) + } + + init() throws { + let clock = TestClock() + self.clock = clock + let env = try ConnectionManager.createForPairingTesting(reconnectionClock: clock) + self.env = env + let deviceID = UUID() + self.deviceID = deviceID + request = env.manager.seedBLERecoveryRequest(deviceID: deviceID) + } + + func start() async throws { + await manager.wireTransportHandlers() + await env.stateMachine.setStubbedIsAutoReconnecting(true) + manager.setTestState(connectionIntent: .wantsConnection()) + let stream = manager.connectionStateEvents.subscribe() + observer = Task { [events] in for await state in stream { + events.record(state) + } } + manager.onConnectionLost = { [weak self] receipt in self?.losses.append(receipt) } + await manager.enterBLERecovery(request, origin: origin) + try await waitUntil("the recovery timeout must park") { self.clock.sleeperCount == 1 } + try await waitUntil("recovery must publish connecting") { self.events.values == [.connecting] } + } + + func advanceRearmingInterval(by duration: Duration = .seconds(15)) async throws { + try await waitUntil("the current timeout must be sleeping") { self.clock.sleeperCount == 1 } + clock.advance(by: duration) + try await waitUntil("active OS recovery must rearm") { self.clock.sleeperCount == 1 } + } + + func gate() -> BLEReconnectionTestHarness.Gate { + let gate = BLEReconnectionTestHarness.Gate() + gates.append(gate) + return gate + } + + func close() async { + manager.onConnectionLost = nil + coordinator.clear() + manager.wireReconnectPolicy() + gates.forEach { $0.open() } + tasks.forEach { $0.cancel() } + for task in tasks { + await task.value + } + await manager.disconnect() + manager.connectionStateEvents.finish() + await observer?.value + do { + try await waitUntil("released transport queries must settle") { self.activeQueries == 0 } + } catch { Issue.record(error) } + #expect(clock.sleeperCount == 0) + env.cleanup() + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerRecoveryOwnershipTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerRecoveryOwnershipTests.swift new file mode 100644 index 0000000000..8af029a84c --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerRecoveryOwnershipTests.swift @@ -0,0 +1,303 @@ +import Foundation +@testable import MC1Services +import MeshCore +import MeshCoreTestSupport +import Testing + +@Suite("Connection recovery ownership") +@MainActor +struct ConnectionManagerRecoveryOwnershipTests { + @Test(arguments: [false, true]) + func `queued wi fi recovery cannot join successor retirement`(disconnect: Bool) async throws { + let env = try ConnectionManagerRadioTestHarness() + let entry = BLEReconnectionTestHarness.Gate() + var entered = false + var completed = false + _ = try await env.connect(.wifi) + let requestID = env.manager.connectionRequestID + env.manager.testWiFiRecoveryEntryHandler = { entered = true; await entry.wait() } + await env.wifi.simulateRemoteLoss() + try await waitUntil("socket loss must queue its actual recovery worker") { entered } + let recovery = try #require(env.manager.wifiReconnectTask) + let replacement = Task { + if disconnect { + _ = await env.manager.disconnect(reason: .userInitiated) + } else { + _ = try? await env.connect(.bluetooth) + } + completed = true + } + try await waitUntil("the explicit action must supersede queued recovery") { + env.manager.connectionRequestID != requestID + } + entry.open() + do { + try await waitUntil("actual successor retirement must join cancelled recovery and finish") { completed } + } catch { + // A dependency cycle cannot join its own tasks; a failed assertion leaves + // those tasks for the isolated test process to dispose. + Issue.record("Successor retirement did not finish after the queued recovery was cancelled") + return + } + await replacement.value + await recovery.value + #expect(env.manager.connectionTeardownCount == 0) + #expect(await env.wifi.connectCount == 1, "obsolete recovery must never dial") + if disconnect { _ = try await env.connect(.bluetooth) } + #expect(try await env.manager.session?.getTime() != nil) + #expect(await env.ble.sentData.contains { $0.first == CommandCode.appStart.rawValue }) + env.manager.testWiFiRecoveryEntryHandler = nil + await env.close() + } + + @Test(arguments: [false, true]) + func `foreground cannot replace admitted BLE target`(holdHandshake: Bool) async throws { + let env = try ConnectionManagerRadioTestHarness() + var exchange: Task? + var replacement: Task? + var foreground: Task? + var foregroundFinished = false + do { + _ = try await env.connect(.bluetooth) + let previousID = env.deviceID + let nextID = UUID() + let saved = try #require(env.manager.connectedDevice) + try await env.manager.persistenceStore.saveDevice(saved.copy { $0.id = nextID; $0.isActive = false }) + if holdHandshake { + await env.ble.holdReplies(for: .appStart) + } else { + await env.ble.holdReplies(for: .getTime) + let session = try #require(env.manager.session) + exchange = Task { try await session.getTime() } + try await waitUntil("A must submit the exchange being drained") { await env.ble.timeReads >= 2 } + } + let previousRequest = env.manager.connectionRequestID + replacement = Task { try await env.manager.connect(to: nextID, forceFullSync: true, forceReconnect: true) } + try await waitUntil("B must be admitted") { env.manager.connectionRequestID != previousRequest } + let nextRequest = env.manager.connectionRequestID + if holdHandshake { + try await waitUntil("B must physically connect and submit appStart") { + await env.ble.sentData.filter { $0.first == CommandCode.appStart.rawValue }.count == 2 + } + } else { + #expect(env.manager.connectionTeardownCount > 0) + } + #expect(env.manager.lastConnectedDeviceID == previousID) + await env.stateMachine.setStubbedIsConnected(true) + await env.stateMachine.setStubbedConnectedDeviceID(holdHandshake ? nextID : previousID) + foreground = Task { await env.manager.appDidBecomeActive(); foregroundFinished = true } + try await waitUntil("foreground must enter the real lifecycle callback") { + await env.stateMachine.appDidBecomeActiveCallCount == 1 + } + try await waitUntil("foreground must finish or expose its incorrect retirement/admission") { + foregroundFinished || env.manager.connectionRequestID != nextRequest || env.manager.connectionState == .disconnected + } + #expect(env.manager.connectionRequestID == nextRequest, "foreground must preserve admitted B") + #expect(env.manager.connectionState != .disconnected, "foreground must not retire B's actual handshake") + await env.ble.releaseAllGates() + _ = await exchange?.result + let result = try await #require(replacement).value + await foreground?.value + #expect(env.manager.isCurrent(result), "B's actual connection request must finish current") + #expect(env.manager.connectedDevice?.id == nextID) + #expect(env.manager.lastConnectedDeviceID == nextID) + #expect(try await env.manager.persistenceStore.fetchActiveDevice()?.id == nextID) + #expect(try await env.manager.session?.getTime() != nil) + } catch { + await env.ble.releaseAllGates() + replacement?.cancel() + _ = await exchange?.result + _ = await replacement?.result + await foreground?.value + await env.close() + throw error + } + await env.close() + } + + @Test + func `same request BLE recovery returns owned handoff during clock tail`() async throws { + let env = try ConnectionManagerRadioTestHarness() + await env.ble.holdReplies(for: .getTime) + let connect = Task { try await env.connect(.bluetooth) } + do { + try await waitUntil("published Link must be in its actual clock query") { await env.ble.timeReads == 1 } + let old = try #require(env.manager.currentConnection) + await env.ble.simulateAutoReconnecting(deviceID: env.deviceID) + try await waitUntil("owned BLE loss must retire the published Link") { env.manager.currentConnection == nil } + await env.ble.releaseReplies(for: .getTime) + let result = try await connect.value + if case let .handoff(requestID) = result { + #expect(requestID == old.requestID) + } else { + Issue.record("same request Link loss must return an owned handoff") + } + #expect(env.manager.isCurrent(result)) + await env.ble.simulateReconnected() + try await waitUntil("same request OS rebuild must finish") { + env.manager.connectionState == .ready && env.manager.currentConnection?.generation != old.generation + } + #expect(env.manager.connectionRequestID == old.requestID) + #expect(try await env.manager.session?.getTime() != nil) + } catch { + await env.ble.releaseAllGates() + connect.cancel() + _ = await connect.result + await env.close() + throw error + } + await env.close() + } + + @Test + func `old setup result uses already installed same request successor`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let resultGate = BLEReconnectionTestHarness.Gate() + var heldGeneration: UUID? + env.manager.testPostSetupResultHandler = { generation in + guard heldGeneration == nil else { return } + heldGeneration = generation + await resultGate.wait() + } + await env.ble.holdReplies(for: .getTime) + let connect = Task { try await env.connect(.bluetooth) } + do { + try await waitUntil("old setup must reach its actual clock query") { await env.ble.timeReads == 1 } + let old = try #require(env.manager.currentConnection) + await env.ble.simulateAutoReconnecting(deviceID: env.deviceID) + try await waitUntil("physical loss must retire the old Link") { env.manager.currentConnection == nil } + await env.ble.releaseReplies(for: .getTime) + try await waitUntil("the old request result must remain held after setup finishes") { heldGeneration == old.generation } + try await waitUntil("old Link retirement must join actual setup independently of its caller") { + env.manager.connectionTeardownCount == 0 + } + await env.ble.simulateReconnected() + try await waitUntil("same-request successor must install before old result resumes") { + env.manager.connectionState == .ready && env.manager.currentConnection?.generation != old.generation + } + let successor = try #require(env.manager.currentConnection) + resultGate.open() + let result = try await connect.value + if case let .operational(snapshot) = result { + #expect(snapshot.generation == successor.generation) + #expect(snapshot.requestID == old.requestID) + } else { Issue.record("an owned request must return its already installed successor") } + #expect(env.manager.isCurrent(result)) + #expect(try await env.manager.session?.getTime() != nil) + } catch { + resultGate.open() + await env.ble.releaseAllGates() + connect.cancel() + _ = await connect.result + await env.close() + throw error + } + env.manager.testPostSetupResultHandler = nil + await env.close() + } + + @Test + func `retirement joins pending listener repair without restarting old polling`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let repairGate = BLEReconnectionTestHarness.Gate() + var repairStarted = false + var foreground: Task? + var replacement: Task? + do { + _ = try await env.connect(.bluetooth) + let old = try #require(env.manager.currentConnection) + await old.services.messagePollingService.stopAutoFetch() + let oldWireHistory = await env.ble.sentData + env.manager.testMessageListenerRepairHandler = { generation in + guard generation == old.generation else { return } + repairStarted = true + await repairGate.wait() + } + await env.stateMachine.setStubbedIsConnected(true) + await env.stateMachine.setStubbedConnectedDeviceID(env.deviceID) + foreground = Task { await env.manager.appDidBecomeActive() } + try await waitUntil("foreground must enter actual missing-fetch repair") { repairStarted } + replacement = Task { try await env.connect(.wifi) } + try await waitUntil("replacement must retire the source Link") { env.manager.connectionRequestID != old.requestID } + #expect(await env.wifi.connectCount == 0, "physical successor must wait for admitted old repair") + repairGate.open() + await foreground?.value + let result = try await #require(replacement).value + #expect(env.manager.isCurrent(result)) + #expect(await !old.services.messagePollingService.isAutoFetching) + #expect(await env.ble.sentData == oldWireHistory, "retired repair must submit no old polling commands") + #expect(try await env.manager.session?.getTime() != nil) + } catch { + repairGate.open() + await env.ble.releaseAllGates() + await env.wifi.releaseAllGates() + replacement?.cancel() + await foreground?.value + _ = await replacement?.result + await env.close() + throw error + } + env.manager.testMessageListenerRepairHandler = nil + await env.close() + } + + @Test(.timeLimit(.minutes(1)), arguments: [false, true]) + func `initial contacts timeout resync restores later message receipt`(foreground: Bool) async throws { + let sessionClock = TestClock() + let resyncClock = TestClock() + let env = try ConnectionManagerRadioTestHarness(clock: resyncClock, sessionClock: sessionClock) + await env.ble.setChannel(index: 0, name: "Dispatch", secret: Data(repeating: 1, count: 16)) + await env.ble.enqueueResponsePackets(for: .getContacts, packets: []) + let connect = Task { try await env.connect(.bluetooth) } + do { + try await waitUntil("initial contact request must run after monitoring starts") { + await env.ble.sentData.contains { $0.first == CommandCode.getContacts.rawValue } + } + let initial = try #require(env.manager.currentConnection) + let initialLink = try #require(env.manager.installedLink) + #expect(initial.services.isEventMonitoringActive) + #expect(await !initial.services.messagePollingService.isAutoFetching) + try await waitUntilClockAdvances(sessionClock, "real contacts timeout must schedule resync") { + env.manager.resyncTask != nil + } + _ = try await connect.value + try await waitUntilClockAdvances(resyncClock, "actual full resync must become usable") { + env.manager.connectionState == .ready + } + if foreground { + await env.stateMachine.setStubbedIsConnected(true) + await env.stateMachine.setStubbedConnectedDeviceID(env.deviceID) + await env.manager.appDidBecomeActive() + } + let readsBefore = await env.ble.sentData.filter { $0.first == CommandCode.getMessage.rawValue }.count + var packet = Data([ResponseCode.channelMessageReceived.rawValue, 0, 0, 0]) + packet.append(withUnsafeBytes(of: UInt32(1_792_310_400).littleEndian) { Data($0) }) + packet.append(Data("Dispatch: after resync".utf8)) + await env.ble.enqueueResponsePackets(for: .getMessage, packets: [packet]) + await env.ble.inject(Data([ResponseCode.messagesWaiting.rawValue])) + try await waitUntil("later messagesWaiting must issue getMessage after resync") { + await env.ble.sentData.filter { $0.first == CommandCode.getMessage.rawValue }.count > readsBefore + } + try await waitUntil("fetched post-resync message must be persisted") { + await (try? env.manager.persistenceStore.fetchMessages(radioID: initial.device.radioID, channelIndex: 0))? + .contains { $0.text.contains("after resync") } == true + } + #expect(env.manager.currentConnection?.generation == initial.generation) + #expect(await initial.services.messagePollingService.isAutoFetching) + env.manager.sessionClockForTesting = nil + _ = try await env.connect(.wifi) + await env.manager.completeSync( + initialLink, syncResult: FullSyncResult(contacts: .clean, channels: .clean, messages: .clean) + ) + #expect(await !initial.services.messagePollingService.isAutoFetching) + #expect(try await env.manager.session?.getTime() != nil) + } catch { + await env.ble.releaseAllGates() + connect.cancel() + _ = await connect.result + await env.close() + throw error + } + await env.close() + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerRestorationHandoffTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerRestorationHandoffTests.swift new file mode 100644 index 0000000000..cca8eeb7e1 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerRestorationHandoffTests.swift @@ -0,0 +1,104 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("ConnectionManager Restoration Handoff") +@MainActor +struct ConnectionManagerRestorationHandoffTests { + @Test + func `restoration that claims the link during adoption is handed off without disconnecting`() async throws { + let env = try ConnectionManager.createForPairingTesting() + defer { env.cleanup() } + let deviceID = UUID() + env.accessorySetupKit.isSessionActive = false + env.manager.testLastConnectedDeviceID = deviceID + await env.stateMachine.setStubbedIsDeviceConnectedToSystem(true) + await env.stateMachine.claimRestorationOnNextAdoption() + await env.transport.primePhysicalLink(deviceID: deviceID, generation: 1, recovering: true) + try await waitUntil("lifecycle handler should be installed") { await env.transport.hasLifecycleHandler } + + let result = try await env.manager.requestConnection( + targets: [.bluetooth(deviceID)], origin: .launch, forceFullSync: false, forceReconnect: false + ) + + guard case .handoff = result else { + Issue.record("Launch must hand the restored link to recovery") + return + } + #expect(env.manager.connectionState == .connecting) + #expect(env.manager.reconnectionCoordinator.currentCycle?.deviceID == deviceID) + #expect(env.manager.desiredRequest?.physicalOrigin?.generation == 1) + #expect(!env.manager.isReconnectionWatchdogRunning) + #expect(await env.stateMachine.startAdoptingSystemConnectedPeripheralCalls == [deviceID]) + #expect(await env.transport.connectInvocations.isEmpty) + #expect(await env.transport.disconnectInvocations == 0) + _ = await env.manager.disconnect(reason: .userInitiated) + } + + @Test + func `a connect rejected while restoration owns the link keeps the peripheral`() async throws { + let env = try ConnectionManager.createForPairingTesting() + defer { env.cleanup() } + let deviceID = UUID() + env.accessorySetupKit.isSessionActive = false + env.manager.testLastConnectedDeviceID = deviceID + let stateMachine = env.stateMachine + let transport = env.transport + await transport.setConnectError(BLEError.connectionFailed("Already in operation: restoringState")) + await transport.setBeforeConnect { + await stateMachine.setStubbedIsAutoReconnecting(true) + await stateMachine.setStubbedIsConnected(false) + await stateMachine.setStubbedConnectedDeviceID(deviceID) + await stateMachine.setStubbedPhase(.restoringState) + await transport.primePhysicalLink(deviceID: deviceID, generation: 1, recovering: true) + } + try await waitUntil("lifecycle handler should be installed") { await env.transport.hasLifecycleHandler } + + let result = try await env.manager.requestConnection( + targets: [.bluetooth(deviceID)], origin: .launch, forceFullSync: false, forceReconnect: false + ) + + guard case .handoff = result else { + Issue.record("A rejected dial must hand off once restoration owns the peripheral") + return + } + #expect(await env.transport.connectInvocations.map(\.deviceID) == [deviceID]) + #expect(await env.transport.disconnectInvocations == 0) + #expect(env.manager.reconnectionCoordinator.currentCycle?.deviceID == deviceID) + #expect(env.manager.desiredRequest?.handedOff == true) + #expect(!env.manager.isReconnectionWatchdogRunning) + await env.transport.setBeforeConnect(nil) + _ = await env.manager.disconnect(reason: .userInitiated) + } + + @Test + func `a rejected dial whose restored phase ends before handoff closes the peripheral`() async throws { + let env = try ConnectionManager.createForPairingTesting() + defer { env.cleanup() } + let deviceID = UUID() + env.accessorySetupKit.isSessionActive = false + env.manager.testLastConnectedDeviceID = deviceID + let stateMachine = env.stateMachine + let transport = env.transport + await transport.setConnectError(BLEError.connectionFailed("Already in operation: restoringState")) + await transport.setBeforeConnect { + await stateMachine.setStubbedIsAutoReconnecting(true) + await stateMachine.setStubbedIsConnected(false) + await stateMachine.setStubbedConnectedDeviceID(deviceID) + await stateMachine.setStubbedPhase(.restoringState) + await stateMachine.releaseOwnershipAfterNextConnectedDeviceIDRead() + await transport.primePhysicalLink(deviceID: deviceID, generation: 1, recovering: true) + } + try await waitUntil("lifecycle handler should be installed") { await env.transport.hasLifecycleHandler } + + await #expect(throws: ConnectionRequestFailure.self) { + try await env.manager.requestConnection( + targets: [.bluetooth(deviceID)], origin: .launch, forceFullSync: false, forceReconnect: false + ) + } + + #expect(await env.transport.disconnectInvocations > 0) + #expect(env.manager.connectionState == .disconnected) + await env.transport.setBeforeConnect(nil) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerResyncLoopTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerResyncLoopTests.swift index fcf7d6fc72..b8af67f609 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerResyncLoopTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerResyncLoopTests.swift @@ -12,14 +12,18 @@ struct ConnectionManagerResyncLoopTests { private func makeResyncTestHarness(deviceID: UUID) async throws -> ( manager: ConnectionManager, services: ServiceContainer, - session: MeshCoreSession + session: MeshCoreSession, + clock: TestClock ) { - let (manager, _) = try ConnectionManager.createForTesting() + let clock = TestClock() + let (manager, _) = try ConnectionManager.createForTesting(reconnectionClock: clock) let transport = SimulatorMockTransport() - // Don't connect transport — commands fail immediately with .notConnected + // The session never starts, so a command returns before it waits. + // This clock stays separate from the reconnection clock. let session = MeshCoreSession( transport: transport, - configuration: SessionConfiguration(defaultTimeout: 0.5, clientIdentifier: "ResyncTest") + configuration: SessionConfiguration(clientIdentifier: "ResyncTest"), + clock: TestClock() ) let services = try await ServiceContainer.forTesting(session: session) @@ -37,7 +41,16 @@ struct ConnectionManagerResyncLoopTests { connectionIntent: .wantsConnection() ) - return (manager, services, session) + return (manager, services, session, clock) + } + + private func waitUntilResync( + _ clock: TestClock, + timeout: Duration = .seconds(2), + _ message: String, + _ condition: @escaping @MainActor () async throws -> Bool + ) async throws { + try await waitUntilClockAdvances(clock, timeout: timeout, message, condition) } // MARK: - Cancellation @@ -45,7 +58,7 @@ struct ConnectionManagerResyncLoopTests { @Test func `Cancelling resync loop closes the activity bracket with succeeded=false`() async throws { let deviceID = UUID() - let (manager, services, _) = try await makeResyncTestHarness(deviceID: deviceID) + let (manager, services, _, clock) = try await makeResyncTestHarness(deviceID: deviceID) let startedTracker = CallTracker() let succeededValues = ValueTracker() @@ -59,7 +72,7 @@ struct ConnectionManagerResyncLoopTests { manager.startResyncLoop(radioID: deviceID, services: services) // Wait for the outer bracket to open - try await waitUntil("beginResyncActivity should fire") { + try await waitUntilResync(clock, "beginResyncActivity should fire") { startedTracker.wasCalled } @@ -67,7 +80,7 @@ struct ConnectionManagerResyncLoopTests { manager.cancelResyncLoop() // Wait for the catch-all to close the bracket - try await waitUntil("endResyncActivity should fire after cancellation") { + try await waitUntilResync(clock, "endResyncActivity should fire after cancellation") { !succeededValues.values.isEmpty } @@ -81,7 +94,7 @@ struct ConnectionManagerResyncLoopTests { @Test func `Resync loop exits and closes bracket when connectionIntent changes`() async throws { let deviceID = UUID() - let (manager, services, _) = try await makeResyncTestHarness(deviceID: deviceID) + let (manager, services, _, clock) = try await makeResyncTestHarness(deviceID: deviceID) let startedTracker = CallTracker() let succeededValues = ValueTracker() @@ -95,17 +108,16 @@ struct ConnectionManagerResyncLoopTests { manager.startResyncLoop(radioID: deviceID, services: services) // Wait for the outer bracket to open - try await waitUntil("beginResyncActivity should fire") { + try await waitUntilResync(clock, "beginResyncActivity should fire") { startedTracker.wasCalled } - // Change intent while the loop is sleeping between retries. - // The MainActor is free during Task.sleep, so this runs immediately. + // Change intent while the loop is parked on the test clock, before the next attempt. manager.setTestState(connectionIntent: .userDisconnected) // The guard at the top of the while loop will fail after the sleep, // causing a break → catch-all fires endResyncActivity(succeeded: false). - try await waitUntil(timeout: .seconds(5), "endResyncActivity should fire after guard exit") { + try await waitUntilResync(clock, timeout: .seconds(5), "endResyncActivity should fire after guard exit") { !succeededValues.values.isEmpty } @@ -120,10 +132,10 @@ struct ConnectionManagerResyncLoopTests { ) func `Max resync attempts triggers disconnect and onResyncFailed`() async throws { let deviceID = UUID() - let (manager, services, _) = try await makeResyncTestHarness(deviceID: deviceID) + let (manager, services, _, clock) = try await makeResyncTestHarness(deviceID: deviceID) let resyncFailedTracker = CallTracker() - manager.onResyncFailed = { + manager.onResyncFailed = { _ in resyncFailedTracker.markCalled() } @@ -138,7 +150,7 @@ struct ConnectionManagerResyncLoopTests { manager.startResyncLoop(radioID: deviceID, services: services) // Wait for max attempts to be exhausted (3 attempts × 2s intervals) - try await waitUntil(timeout: .seconds(15), "onResyncFailed should fire after max attempts") { + try await waitUntilResync(clock, timeout: .seconds(15), "onResyncFailed should fire after max attempts") { resyncFailedTracker.wasCalled } @@ -159,7 +171,7 @@ struct ConnectionManagerResyncLoopTests { ) func `Each resync attempt opens and closes an inner bracket`() async throws { let deviceID = UUID() - let (manager, services, _) = try await makeResyncTestHarness(deviceID: deviceID) + let (manager, services, _, clock) = try await makeResyncTestHarness(deviceID: deviceID) let startCount = CallTracker() let endCount = CallTracker() @@ -171,12 +183,12 @@ struct ConnectionManagerResyncLoopTests { ) let resyncFailedTracker = CallTracker() - manager.onResyncFailed = { resyncFailedTracker.markCalled() } + manager.onResyncFailed = { _ in resyncFailedTracker.markCalled() } manager.startResyncLoop(radioID: deviceID, services: services) // Wait for loop to exhaust - try await waitUntil(timeout: .seconds(15), "resync loop should exhaust") { + try await waitUntilResync(clock, timeout: .seconds(15), "resync loop should exhaust") { resyncFailedTracker.wasCalled } @@ -193,7 +205,7 @@ struct ConnectionManagerResyncLoopTests { ) func `Resync success promotes .syncing → .ready`() async throws { let deviceID = UUID() - let (manager, services, _) = try await makeResyncTestHarness(deviceID: deviceID) + let (manager, services, _, clock) = try await makeResyncTestHarness(deviceID: deviceID) // Override performResync to succeed await services.syncCoordinator.setPerformResyncOverride { _, _ in @@ -209,8 +221,8 @@ struct ConnectionManagerResyncLoopTests { manager.startResyncLoop(radioID: deviceID, services: services) - try await waitUntil(timeout: .seconds(10), "endResyncActivity should fire with success") { - succeededValues.values.contains(true) + try await waitUntilResync(clock, timeout: .seconds(10), "successful resync completion should promote readiness") { + succeededValues.values.contains(true) && manager.connectionState == .ready } #expect(manager.connectionState == .ready) @@ -221,7 +233,7 @@ struct ConnectionManagerResyncLoopTests { ) func `Resync success calls onDeviceSynced`() async throws { let deviceID = UUID() - let (manager, services, _) = try await makeResyncTestHarness(deviceID: deviceID) + let (manager, services, _, clock) = try await makeResyncTestHarness(deviceID: deviceID) // Override performResync to succeed await services.syncCoordinator.setPerformResyncOverride { _, _ in @@ -229,7 +241,7 @@ struct ConnectionManagerResyncLoopTests { } let onDeviceSyncedTracker = CallTracker() - manager.onDeviceSynced = { _ in onDeviceSyncedTracker.markCalled() } + manager.onDeviceSynced = { _, _ in onDeviceSyncedTracker.markCalled() } let succeededValues = ValueTracker() await services.syncCoordinator.setSyncActivityCallbacks( @@ -240,7 +252,7 @@ struct ConnectionManagerResyncLoopTests { manager.startResyncLoop(radioID: deviceID, services: services) - try await waitUntil(timeout: .seconds(10), "onDeviceSynced should fire after resync success") { + try await waitUntilResync(clock, timeout: .seconds(10), "onDeviceSynced should fire after resync success") { onDeviceSyncedTracker.wasCalled } @@ -260,15 +272,15 @@ struct ConnectionManagerResyncLoopTests { for (result, expected) in [(partial, false), (cleanDespiteMessages, true)] { let deviceID = UUID() - let (manager, services, _) = try await makeResyncTestHarness(deviceID: deviceID) + let (manager, services, _, clock) = try await makeResyncTestHarness(deviceID: deviceID) let delivered = result await services.syncCoordinator.setPerformResyncOverride { _, _ in delivered } var eligibility: [Bool] = [] - manager.onDeviceSynced = { eligibility.append($0) } + manager.onDeviceSynced = { _, hasCleanRecipientData in eligibility.append(hasCleanRecipientData) } manager.startResyncLoop(radioID: deviceID, services: services) - try await waitUntil(timeout: .seconds(10), "onDeviceSynced should fire with the result flag") { + try await waitUntilResync(clock, timeout: .seconds(10), "onDeviceSynced should fire with the result flag") { eligibility.count == 1 } @@ -283,17 +295,17 @@ struct ConnectionManagerResyncLoopTests { ) func `A thrown resync stays ineligible and retries`() async throws { let deviceID = UUID() - let (manager, services, _) = try await makeResyncTestHarness(deviceID: deviceID) + let (manager, services, _, clock) = try await makeResyncTestHarness(deviceID: deviceID) let attempts = CallTracker() await services.syncCoordinator.setPerformResyncOverride { _, _ in attempts.markCalled() return nil } var published = false - manager.onDeviceSynced = { _ in published = true } + manager.onDeviceSynced = { _, _ in published = true } manager.startResyncLoop(radioID: deviceID, services: services) - try await waitUntil(timeout: .seconds(8), "a thrown resync should be retried") { + try await waitUntilResync(clock, timeout: .seconds(8), "a thrown resync should be retried") { attempts.callCount >= 2 } @@ -309,7 +321,7 @@ struct ConnectionManagerResyncLoopTests { ) func `Disconnect during .syncing transitions to .disconnected and closes bracket`() async throws { let deviceID = UUID() - let (manager, services, _) = try await makeResyncTestHarness(deviceID: deviceID) + let (manager, services, _, clock) = try await makeResyncTestHarness(deviceID: deviceID) let startedTracker = CallTracker() let succeededValues = ValueTracker() @@ -323,7 +335,7 @@ struct ConnectionManagerResyncLoopTests { manager.startResyncLoop(radioID: deviceID, services: services) // Wait for the outer bracket to open - try await waitUntil("beginResyncActivity should fire") { + try await waitUntilResync(clock, "beginResyncActivity should fire") { startedTracker.wasCalled } @@ -331,7 +343,7 @@ struct ConnectionManagerResyncLoopTests { await manager.disconnect(reason: .userInitiated) // Wait for bracket to close - try await waitUntil("endResyncActivity should fire after disconnect") { + try await waitUntilResync(clock, "endResyncActivity should fire after disconnect") { !succeededValues.values.isEmpty } @@ -346,7 +358,7 @@ struct ConnectionManagerResyncLoopTests { ) func `Superseded resync loop cannot disconnect a healthy successor connection`() async throws { let deviceID = UUID() - let (manager, staleServices, _) = try await makeResyncTestHarness(deviceID: deviceID) + let (manager, staleServices, _, clock) = try await makeResyncTestHarness(deviceID: deviceID) // Count resync attempts against the cycle-N container. A loop orphaned by a // later reconnect must never drive resync against the replaced container. @@ -357,7 +369,7 @@ struct ConnectionManagerResyncLoopTests { } let onResyncFailedTracker = CallTracker() - manager.onResyncFailed = { onResyncFailedTracker.markCalled() } + manager.onResyncFailed = { _ in onResyncFailedTracker.markCalled() } // Install the resync loop bound to the cycle-N container. manager.startResyncLoop(radioID: deviceID, services: staleServices) @@ -367,7 +379,8 @@ struct ConnectionManagerResyncLoopTests { // reconnect that superseded the loop's container. let successorSession = MeshCoreSession( transport: SimulatorMockTransport(), - configuration: SessionConfiguration(defaultTimeout: 0.5, clientIdentifier: "SuccessorResyncTest") + configuration: SessionConfiguration(clientIdentifier: "SuccessorResyncTest"), + clock: TestClock() ) let successorServices = try await ServiceContainer.forTesting(session: successorSession) manager.setTestState( @@ -381,7 +394,7 @@ struct ConnectionManagerResyncLoopTests { // branch that would disconnect. The timeout is generous enough that with // the fence absent the loop would exhaust and tear the successor down, // making the assertions below fail rather than hang. - try await waitUntil(timeout: .seconds(12), "orphaned resync loop should stop") { + try await waitUntilResync(clock, timeout: .seconds(12), "orphaned resync loop should stop") { manager.resyncTask == nil } @@ -396,7 +409,7 @@ struct ConnectionManagerResyncLoopTests { ) func `Cancelling the resync loop stops further resync attempts`() async throws { let deviceID = UUID() - let (manager, services, _) = try await makeResyncTestHarness(deviceID: deviceID) + let (manager, services, _, clock) = try await makeResyncTestHarness(deviceID: deviceID) let resyncCalls = CallTracker() await services.syncCoordinator.setPerformResyncOverride { _, _ in @@ -406,20 +419,17 @@ struct ConnectionManagerResyncLoopTests { manager.startResyncLoop(radioID: deviceID, services: services) - try await waitUntil(timeout: .seconds(6), "first resync attempt should run") { + try await waitUntilResync(clock, timeout: .seconds(6), "first resync attempt should run") { resyncCalls.wasCalled } manager.cancelResyncLoop() + try await waitUntilResync(clock, "cancellation should clear the stored resync task") { + manager.resyncTask == nil + } let countAtCancel = resyncCalls.callCount + if clock.sleeperCount > 0 { clock.advanceToNextSleep() } #expect(manager.resyncTask == nil, "Cancellation must clear the stored resync task") - - // A full interval beyond cancellation proves the loop made no further attempts. - try await Task.sleep(for: Self.postCancelObservationWindow) #expect(resyncCalls.callCount == countAtCancel, "Cancelled loop must not perform further resync attempts") } - - /// Waited after cancelling a loop to confirm no further attempt fires; longer - /// than one `resyncInterval` so a still-running loop would have woken. - private static let postCancelObservationWindow: Duration = .seconds(3) } diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerSessionTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerSessionTests.swift index 6def0b560a..659e4b4465 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerSessionTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerSessionTests.swift @@ -5,76 +5,18 @@ import Testing @Suite("ConnectionManager Session Tests") @MainActor struct ConnectionManagerSessionTests { - // MARK: - setConnectionState Tests - - @Test - func `setConnectionState updates to connected`() throws { - let (manager, _) = try ConnectionManager.createForTesting() - manager.setTestState(connectionIntent: .wantsConnection()) - - manager.setConnectionState(.connected) - - #expect(manager.connectionState == .connected) - } - - @Test - func `setConnectionState updates to disconnected`() throws { - let (manager, _) = try ConnectionManager.createForTesting() - manager.setTestState(connectionState: .connected, connectionIntent: .wantsConnection()) - - manager.setConnectionState(.disconnected) - - #expect(manager.connectionState == .disconnected) - } - - // MARK: - setConnectedDevice Tests - - @Test - func `setConnectedDevice sets device`() throws { - let (manager, _) = try ConnectionManager.createForTesting() - let device = DeviceDTO.testDevice(nodeName: "TestDevice") - - manager.setConnectedDevice(device) - - #expect(manager.connectedDevice?.nodeName == "TestDevice") - } - - @Test - func `setConnectedDevice sets nil`() throws { - let (manager, _) = try ConnectionManager.createForTesting() - let device = DeviceDTO.testDevice() - manager.setConnectedDevice(device) - #expect(manager.connectedDevice != nil) - - manager.setConnectedDevice(nil) - - #expect(manager.connectedDevice == nil) - } - - // MARK: - isTransportAutoReconnecting Tests - - @Test - func `isTransportAutoReconnecting delegates to stateMachine`() async throws { - let (manager, mock) = try ConnectionManager.createForTesting() - - await mock.setStubbedIsAutoReconnecting(false) - var result = await manager.isTransportAutoReconnecting() - #expect(!result) - - await mock.setStubbedIsAutoReconnecting(true) - result = await manager.isTransportAutoReconnecting() - #expect(result) - } + // MARK: - Request and cycle projections @Test func `activeConnectionAttemptDeviceID prefers session rebuild device`() throws { let (manager, _) = try ConnectionManager.createForTesting() let deviceID = UUID() - manager.setTestState(sessionRebuildDeviceID: deviceID) + let request = manager.seedBLERecoveryRequest(deviceID: deviceID) + _ = manager.reconnectionCoordinator.begin(deviceID: deviceID, requestID: request.id) #expect(manager.activeConnectionAttemptDeviceID == deviceID) - #expect(manager.activeReconnectDeviceID == deviceID) + #expect(manager.reconnectionCoordinator.reconnectingDeviceID == deviceID) } @Test @@ -83,6 +25,7 @@ struct ConnectionManagerSessionTests { let deviceID = UUID() manager.testLastConnectedDeviceID = deviceID + _ = manager.seedBLERecoveryRequest(deviceID: deviceID) manager.setTestState( connectionState: .disconnected, currentTransportType: .bluetooth, @@ -93,15 +36,14 @@ struct ConnectionManagerSessionTests { try await manager.connect(to: deviceID) #expect(manager.connectionState == .disconnected) - #expect(manager.sessionRebuildDeviceID == deviceID) + #expect(manager.reconnectionCoordinator.reconnectingDeviceID == deviceID) #expect(manager.connectionIntent == .wantsConnection()) - #expect(manager.reconnectionCoordinator.reconnectingDeviceID == nil) } - // MARK: - handleReconnectionFailure Tests + // MARK: - Recovery failure policy @Test - func `handleReconnectionFailure clears state and sets disconnected`() async throws { + func `owned recovery failure clears state and notifies connection loss`() async throws { let (manager, _) = try ConnectionManager.createForTesting() manager.updateDevice(with: DeviceDTO.testDevice()) manager.setTestState( @@ -109,87 +51,70 @@ struct ConnectionManagerSessionTests { connectionIntent: ConnectionIntent.none ) - await manager.handleReconnectionFailure() + var lossCount = 0 + manager.onConnectionLost = { _ in lossCount += 1 } + await manager.finishSeededBLERecovery() + #expect(lossCount == 1) #expect(manager.connectionState == .disconnected) #expect(manager.connectedDevice == nil) #expect(manager.allowedRepeatFreqRanges.isEmpty) } - // MARK: - WiFi Health Check Early Returns - - @Test - func `checkWiFiConnectionHealth returns early when reconnect in progress`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - manager.setTestState( - connectionState: .ready, - currentTransportType: .wifi, - connectionIntent: .wantsConnection() - ) - - manager.wifiReconnectTask = Task {} - - await manager.checkWiFiConnectionHealth() - - #expect(manager.connectionState == .ready) - - manager.wifiReconnectTask?.cancel() - manager.wifiReconnectTask = nil - } - - @Test - func `checkWiFiConnectionHealth returns early when disconnected without intent`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - manager.setTestState( - connectionState: .disconnected, - currentTransportType: nil, - connectionIntent: ConnectionIntent.none - ) - - await manager.checkWiFiConnectionHealth() - - #expect(manager.connectionState == .disconnected) - } - - @Test - func `checkWiFiConnectionHealth returns early when transport is bluetooth`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - manager.setTestState( - connectionState: .ready, - currentTransportType: .bluetooth, - connectionIntent: .wantsConnection() - ) - - await manager.checkWiFiConnectionHealth() - - #expect(manager.connectionState == .ready) + @Test(.timeLimit(.minutes(1)), arguments: HealthCheckExclusion.allCases) + func `WiFi health checks preserve an excluded request without dialing`(_ exclusion: HealthCheckExclusion) async throws { + let env = try ConnectionManagerRadioTestHarness() + var releaseRecovery: CheckedContinuation? + do { + switch exclusion { + case .recoveryInProgress: + await env.wifi.setConnectError(MeshTransportError.notConnected) + await #expect(throws: ConnectionRequestFailure.self) { _ = try await env.connect(.wifi) } + var recoveryEntered = false + env.manager.testWiFiRecoveryEntryHandler = { + await withCheckedContinuation { + releaseRecovery = $0 + recoveryEntered = true + } + } + env.manager.startWiFiReconnection() + try await waitUntil("the recovery worker should enter before the health check") { recoveryEntered } + #expect(env.manager.wifiReconnectTask != nil) + case .withoutIntent: + _ = try await env.connect(.wifi) + _ = await env.manager.disconnect(reason: .userInitiated) + #expect(!env.manager.connectionIntent.wantsConnection) + case .bluetoothRequest: + _ = try await env.connect(.wifi) + await env.ble.setConnectError(BLEError.deviceNotFound) + await #expect(throws: ConnectionRequestFailure.self) { _ = try await env.connect(.bluetooth) } + #expect(env.manager.desiredRequest?.target == .bluetooth(env.deviceID)) + } + #expect(env.manager.connectionState == .disconnected) + let requestID = env.manager.connectionRequestID + let recoverySlot = env.manager.wifiRecoverySlotID + let wifiDials = await env.wifi.connectCount + let bleDials = await env.ble.connectCount + await env.manager.checkWiFiConnectionHealth() + #expect(env.manager.connectionRequestID == requestID) + #expect(env.manager.wifiRecoverySlotID == recoverySlot) + #expect(await env.wifi.connectCount == wifiDials) + #expect(await env.ble.connectCount == bleDials) + #expect(env.manager.connectionState == .disconnected) + } catch { + releaseRecovery?.resume() + env.manager.testWiFiRecoveryEntryHandler = nil + await env.close() + throw error + } + releaseRecovery?.resume() + env.manager.testWiFiRecoveryEntryHandler = nil + await env.close() } - @Test - func `handleReconnectionFailure notifies onConnectionLost so UI can react`() async throws { - let (manager, _) = try ConnectionManager.createForTesting() - manager.updateDevice(with: DeviceDTO.testDevice()) - manager.setTestState( - connectionState: .connected, - connectionIntent: ConnectionIntent.none - ) - - let tracker = ReconnectionFailureLostTracker() - manager.onConnectionLost = { await tracker.markConnectionLost() } - - await manager.handleReconnectionFailure() - - let wasCalled = await tracker.connectionLostCalled - #expect(wasCalled, "onConnectionLost must fire so AppState can update the Live Activity to disconnected") - } -} - -// MARK: - Test Helpers - -private actor ReconnectionFailureLostTracker { - var connectionLostCalled = false - - func markConnectionLost() { - connectionLostCalled = true + enum HealthCheckExclusion: CaseIterable, Sendable { + case recoveryInProgress + case withoutIntent + case bluetoothRequest } } diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerSiblingEntryRegressionTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerSiblingEntryRegressionTests.swift new file mode 100644 index 0000000000..e564590e40 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerSiblingEntryRegressionTests.swift @@ -0,0 +1,231 @@ +#if canImport(UIKit) + import AccessorySetupKit +#endif +import Foundation +@testable import MC1Services +import MeshCore +import MeshCoreTestSupport +import Testing + +@Suite("Connection manager sibling entry regressions") +@MainActor +struct ConnectionManagerSiblingEntryRegressionTests { + @Test + func `foreground retries admitted bluetooth despite saved wifi last`() async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + let seed = DeviceDTO.testDevice(id: env.deviceID, publicKey: env.ble.publicKey, isActive: false).copy { + $0.connectionMethods = [ + .bluetooth(peripheralUUID: env.deviceID, displayName: nil), + .wifi(host: "radio.test", port: 5123, displayName: nil) + ] + } + try await env.manager.persistenceStore.saveDevice(seed) + _ = try await env.connect(.wifi) + await env.ble.setConnectError(BLEError.bluetoothUnavailable) + _ = try? await env.connect(.bluetooth) + let failedRequest = env.manager.connectionRequestID + #expect(env.manager.desiredRequest?.target == .bluetooth(env.deviceID)) + #expect(try await env.manager.persistenceStore.fetchDevice(id: env.deviceID)?.lastUsedConnectionMethod?.isWiFi == true) + #expect(env.manager.connectionState == .disconnected) + let attempts = await env.ble.connectCount + await env.ble.setConnectError(nil) + env.manager.setCircuitBreakerOpenForTesting(since: .distantPast) + #expect(env.manager.shouldAllowConnection(force: false)) + await env.manager.appDidBecomeActive() + let connectCount = await env.ble.connectCount + #expect(connectCount == attempts + 1, "foreground must honor the admitted Bluetooth target over saved method order") + #expect(env.manager.connectionRequestID != failedRequest) + #expect(env.manager.currentTransportType == .bluetooth) + #expect(env.manager.connectionState == .ready) + let probed = try await env.manager.session?.getTime() != nil + #expect(probed) + } catch { await env.close(); throw error } + await env.close() + } + + @Test(arguments: [false, true]) + func `opportunistic entries retry admitted failed bluetooth target instead of last selection`(activate: Bool) async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + _ = try await env.connect(.bluetooth) + let savedA = try #require(env.manager.connectedDevice) + let idB = UUID() + let keyB = Data(repeating: 2, count: ProtocolLimits.publicKeySize) + await env.ble.setPublicKey(keyB, for: idB) + try await env.manager.persistenceStore.saveDevice(savedA.copy { + $0.id = idB + $0.radioID = UUID() + $0.publicKey = keyB + $0.isActive = false + $0.connectionMethods = [.bluetooth(peripheralUUID: idB, displayName: nil)] + }) + env.pairing.setPairedAccessories([ + ASAccessory(bluetoothIdentifier: savedA.id, displayName: "A"), ASAccessory(bluetoothIdentifier: idB, displayName: "B") + ]) + await env.ble.setConnectError(BLEError.bluetoothUnavailable) + _ = try? await env.manager.connect(to: idB, forceFullSync: true, forceReconnect: true) + #expect(env.manager.desiredRequest?.target == .bluetooth(idB)) + #expect(env.manager.lastConnectedDeviceID == savedA.id) + #expect(env.manager.connectionState == .disconnected) + await env.ble.setConnectError(nil) + env.manager.setCircuitBreakerOpenForTesting(since: .distantPast) + #expect(env.manager.shouldAllowConnection(force: false)) + if activate { + await env.manager.activate() + } else { + let handled = env.manager.testBluetoothPoweredOnHandlerRuns + await env.stateMachine.simulateBluetoothPoweredOn() + try await waitUntil("installed power-on callback must complete its production request") { + env.manager.testBluetoothPoweredOnHandlerRuns == handled + 1 + } + } + let dialedIDs = await env.ble.sessionDeviceIDs + let target = env.manager.desiredRequest?.target + #expect(target == .bluetooth(idB), "opportunistic entry must preserve admitted B") + #expect(dialedIDs == [savedA.id, idB, idB], "opportunistic entry may retry only admitted B") + #expect(env.manager.connectedDevice?.id == idB) + #expect(env.manager.lastConnectedDeviceID == idB) + #expect(try await env.manager.persistenceStore.fetchActiveDevice()?.id == idB) + let probed = try await env.manager.session?.getTime() != nil + #expect(probed) + } catch { await env.close(); throw error } + await env.close() + } + + @Test(arguments: [false, true]) + func `power on stands down for wifi and explicit terminal requests`(disconnect: Bool) async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + _ = try await env.connect(.bluetooth) + if disconnect { + _ = await env.manager.disconnect(reason: .userInitiated) + } else { + await env.wifi.setConnectError(WiFiTransportError.connectionTimeout) + _ = try? await env.connect(.wifi) + } + let attempts = await env.ble.sessionDeviceIDs + let requestID = env.manager.connectionRequestID + let handled = env.manager.testBluetoothPoweredOnHandlerRuns + await env.stateMachine.simulateBluetoothPoweredOn() + try await waitUntil("installed power-on callback must settle") { + env.manager.testBluetoothPoweredOnHandlerRuns == handled + 1 + } + let dialedIDs = await env.ble.sessionDeviceIDs + #expect(dialedIDs == attempts) + #expect(env.manager.connectionRequestID == requestID) + let published = env.manager.currentConnection != nil + #expect(!published) + } catch { await env.close(); throw error } + await env.close() + } + + @Test(arguments: [false, true]) + func `accessory removal revokes unpublished preparation before final metadata`(keepsWifi: Bool) async throws { + let env = try ConnectionManagerRadioTestHarness() + let radioID = UUID() + let seed = DeviceDTO.testDevice(id: env.deviceID, radioID: radioID, publicKey: env.ble.publicKey, isActive: false).copy { + $0.connectionMethods = [.bluetooth(peripheralUUID: env.deviceID, displayName: nil)] + if keepsWifi { $0.connectionMethods.append(.wifi(host: "radio.test", port: 5123, displayName: nil)) } + } + try await env.manager.persistenceStore.saveDevice(seed) + env.pairing.setPairedAccessories([ASAccessory(bluetoothIdentifier: env.deviceID, displayName: "Radio")]) + await env.ble.holdReplies(for: .getAutoAddConfig) + let connect = Task { try await env.connect(.bluetooth) } + do { + try await waitUntil("actual unpublished preparation must await getAutoAddConfig") { + await env.ble.sentData.contains { $0.first == CommandCode.getAutoAddConfig.rawValue } + } + #expect(env.manager.currentConnection == nil) + env.pairing.simulateAccessoryRemoved(env.deviceID) + let removalMetadata = env.manager.metadataCommitTask + await env.ble.releaseReplies(for: .getAutoAddConfig) + _ = await connect.result + await removalMetadata?.value + await env.manager.retirementTask?.value + await env.manager.metadataCommitTask?.value + let saved = try #require(try await env.manager.persistenceStore.fetchDevice(publicKey: seed.publicKey)) + #expect(saved.radioID == radioID) + #expect(saved.bluetoothPeripheralID == nil, "late registration must not restore removed Bluetooth") + #expect((saved.wifiConnectionMethod != nil) == keepsWifi) + #expect(!saved.isActive) + let activeID = try await env.manager.persistenceStore.fetchActiveDevice()?.id + let published = env.manager.currentConnection != nil + #expect(activeID == nil) + #expect(!published, "removed unpublished target must never publish") + #expect(env.manager.lastConnectedDeviceID == nil) + #expect(env.manager.desiredRequest?.target == .disconnected) + } catch { + await env.ble.releaseAllGates() + connect.cancel() + _ = await connect.result + await env.close() + throw error + } + await env.close() + } + + @Test + func `accessory removal keeps installed wifi and its radio partition`() async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + let seed = DeviceDTO.testDevice(id: env.deviceID, radioID: UUID(), publicKey: env.ble.publicKey, isActive: false).copy { + $0.connectionMethods = [.bluetooth(peripheralUUID: env.deviceID, displayName: nil), .wifi(host: "radio.test", port: 5123, displayName: nil)] + } + try await env.manager.persistenceStore.saveDevice(seed) + env.pairing.setPairedAccessories([ASAccessory(bluetoothIdentifier: env.deviceID, displayName: "Radio")]) + _ = try await env.connect(.wifi) + let old = try #require(env.manager.currentConnection) + env.pairing.simulateAccessoryRemoved(env.deviceID) + await env.manager.metadataCommitTask?.value + let saved = try #require(try await env.manager.persistenceStore.fetchDevice(publicKey: seed.publicKey)) + #expect(saved.radioID == seed.radioID) + #expect(saved.bluetoothPeripheralID == nil) + #expect(saved.wifiConnectionMethod != nil) + #expect(saved.isActive) + #expect(env.manager.currentConnection?.generation == old.generation) + #expect(env.manager.currentTransportType == .wifi) + let probed = try await env.manager.session?.getTime() != nil + #expect(probed) + } catch { await env.close(); throw error } + await env.close() + } + + @Test(arguments: [TransportType.bluetooth, .wifi], [false, true]) + func `foreground recovers after actual resync exhaustion`(type: TransportType, explicitDisconnect: Bool) async throws { + let clock = TestClock() + let env = try ConnectionManagerRadioTestHarness(clock: clock) + let radio = type == .bluetooth ? env.ble : env.wifi + do { + await radio.rejectNext(.getContacts, count: 4) + _ = try await env.connect(type) + let first = try #require(env.manager.currentConnection) + try await waitUntilClockAdvances(clock, timeout: .seconds(2), "actual initial failure and three resync failures must retire the Link") { + env.manager.connectionState == .disconnected && env.manager.connectionRequestID != first.requestID + } + await env.manager.retirementTask?.value + await env.manager.metadataCommitTask?.value + #expect(env.manager.connectionIntent.wantsConnection) + #expect(await radio.sentData.filter { $0.first == CommandCode.getContacts.rawValue }.count == 4) + let attempts = await radio.connectCount + if explicitDisconnect { _ = await env.manager.disconnect(reason: .userInitiated) } + await env.manager.checkWiFiConnectionHealth() + await env.manager.appDidBecomeActive() + if explicitDisconnect { + #expect(await radio.connectCount == attempts) + #expect(env.manager.currentConnection == nil) + #expect(env.manager.connectionIntent.isUserDisconnected) + } else { + let connectCount = await radio.connectCount + let handshakeCount = await radio.sentData.filter { $0.first == CommandCode.appStart.rawValue }.count + #expect(connectCount == attempts + 1, "foreground must recover the retained admitted target") + #expect(handshakeCount == 2) + #expect(env.manager.connectionState == .ready) + #expect(env.manager.currentConnection?.device.radioID == first.device.radioID) + let probed = try await env.manager.session?.getTime() != nil + #expect(probed, "recovered production session must exchange frames") + } + } catch { await env.close(); throw error } + await env.close() + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerSystemAdoptionTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerSystemAdoptionTests.swift new file mode 100644 index 0000000000..f781627080 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerSystemAdoptionTests.swift @@ -0,0 +1,83 @@ +@preconcurrency import CoreBluetooth +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("System adoption source capture boundary") +@MainActor +struct ConnectionManagerSystemAdoptionTests { + @Test(arguments: [false, true], [false, true]) + func `actual completed adoption reconciles after its origin read resumes`(newerCycleWhileHeld: Bool, restoring: Bool) async throws { + let harness = try await BLEAdoptionTestHarness.make() + let manager = harness.manager + let deviceID = harness.ble.peripheral.identifier + var connection: Task? + do { + if restoring { + await harness.ble.machine.handleRestoredPeripheral(harness.ble.peripheral) + try await harness.awaitCondition { + harness.handledEvents.contains { if case .autoReconnecting = $0 { return true }; return false } + } + } + let connecting = Task { try await manager.connect(to: deviceID, forceFullSync: true, forceReconnect: false) } + connection = connecting + try await harness.awaitCondition { await harness.transport.originReadIsHeld } + #expect(await harness.ble.machine.currentPhase.name == "autoReconnecting") + #expect(manager.desiredRequest?.physicalOrigin == nil) + let originalOrigin = try #require(await harness.transport.capturedOrigin) + await harness.completeAdoptionDiscovery() + try await harness.awaitCondition { + harness.handledEvents.contains { event in + if case .reconnected = event { return event.origin.generation == originalOrigin.generation } + return false + } + } + #expect(await harness.ble.machine.isConnected) + #expect(manager.session == nil) + #expect(await harness.firmware.sentData.isEmpty) + + if newerCycleWhileHeld { + harness.ble.native.peripheralState = .disconnected + await harness.ble.machine.handleDidDisconnect( + harness.ble.peripheral, timestamp: CFAbsoluteTimeGetCurrent(), isReconnecting: true, error: nil + ) + try await harness.awaitCondition { + manager.desiredRequest?.physicalOrigin?.generation == originalOrigin.generation + 1 + } + let newerCycle = manager.reconnectionCoordinator.currentCycle + await harness.transport.releaseOrigin() + _ = try await connecting.value + let acceptedGeneration = manager.desiredRequest?.physicalOrigin?.generation + let expectedGeneration = originalOrigin.generation + 1 + #expect(acceptedGeneration == expectedGeneration, + "An older adoption origin read cannot replace the accepted newer generation") + #expect(manager.reconnectionCoordinator.currentCycle == newerCycle) + await manager.handleBLELifecycleEvent(.reconnected(originalOrigin)) + #expect(manager.session == nil) + harness.ble.native.peripheralState = .connected + await harness.ble.machine.handleDidConnect(harness.ble.peripheral) + await harness.completeAdoptionDiscovery() + } else { + await harness.transport.releaseOrigin() + } + let outcome = try await connecting.value + #expect(manager.isCurrent(outcome)) + let automaticallyReady = await harness.observedBeforeDeadline { manager.connectionState == .ready && manager.session != nil } + #expect(automaticallyReady, "The current source cycle must automatically rebuild a session after origin capture") + guard automaticallyReady else { throw BLESetupRetirementHarness.WaitError.expired } + let session = try #require(manager.session) + _ = try await session.getTime() + #expect(await harness.firmware.timeReads > 0) + #expect(harness.ble.native.connectCount == 0) + #expect(manager.connectedDevice?.id == deviceID) + } catch { + await harness.transport.releaseOrigin() + _ = await connection?.result + await harness.close() + throw error + } + await harness.close() + #expect(await !harness.ble.machine.isRSSIKeepaliveActive) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerTeardownTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerTeardownTests.swift index b7de891fd5..e3eead6f1e 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerTeardownTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerTeardownTests.swift @@ -1,490 +1,351 @@ import Foundation @testable import MC1Services -@testable import MeshCore +import MeshCore import Testing @Suite("ConnectionManager teardown ownership") @MainActor struct ConnectionManagerTeardownTests { @Test(arguments: [false, true]) - func `stale sync schedulers leave the current recovery tasks intact`(channelRetry: Bool) async throws { - let harness = try await TeardownHarness.make() - let staleServices = try await ServiceContainer.forTesting( - session: MeshCoreSession(transport: MockTransport()), radioID: harness.device.radioID - ) - let resyncGate = TeardownGate() - let channelGate = TeardownGate() - let resync = Task { await resyncGate.wait() } - let channel = Task { await channelGate.wait() } - harness.manager.resyncTask = resync - harness.manager.resyncAttemptCount = 2 - harness.manager.channelRetryTask = channel - - if channelRetry { - harness.manager.scheduleChannelOnlyRetry(radioID: harness.device.radioID, services: staleServices, indices: [0]) - } else { - harness.manager.startResyncLoop(radioID: harness.device.radioID, services: staleServices) + func `stale sync schedulers leave current recovery workers intact`(channelRetry: Bool) async throws { + try await withHarness { harness in + let current = try #require(harness.manager.currentConnection) + let stale = try await ServiceContainer.forTesting( + session: MeshCoreSession(transport: MockTransport()), radioID: current.device.radioID + ) + let resyncGate = harness.gate() + let channelGate = harness.gate() + let resync = harness.track(Task { await resyncGate.wait() }) + let channel = harness.track(Task { await channelGate.wait() }) + harness.manager.resyncTask = resync + harness.manager.resyncAttemptCount = 2 + harness.manager.channelRetryTask = channel + if channelRetry { + harness.manager.scheduleChannelOnlyRetry(radioID: current.device.radioID, services: stale, indices: [0]) + } else { + harness.manager.startResyncLoop(radioID: current.device.radioID, services: stale) + } + #expect(!resync.isCancelled && !channel.isCancelled) + #expect(harness.manager.resyncAttemptCount == 2) + resyncGate.open() + channelGate.open() + await stale.tearDown() } - - #expect(resync.isCancelled == false) - #expect(channel.isCancelled == false) - #expect(harness.manager.resyncAttemptCount == 2) - harness.manager.resyncTask?.cancel() - harness.manager.channelRetryTask?.cancel() - resyncGate.release() - channelGate.release() - await resync.value - await channel.value - await staleServices.tearDown() - await harness.finish(replacement: nil) } @Test(arguments: [false, true]) - func `a connection resumed after power-off cannot disconnect its shared replacement`( - duringSync: Bool - ) async throws { - let harness = try await TeardownHarness.make() - await harness.manager.disconnect() - let ready = TeardownGate() - harness.manager.onConnectionReady = { - if duringSync, let services = harness.manager.services { - await services.syncCoordinator.setSyncActivityCallbacks( - onStarted: { await ready.wait() }, onEnded: { _ in }, onPhaseChanged: { _ in } - ) - } else { - await ready.wait() + func `retirement joins old wiring and sync before a replacement can dial`(duringSync: Bool) async throws { + try await withHarness { harness in + _ = await harness.manager.disconnect() + let ready = harness.gate() + harness.manager.onConnectionReady = { snapshot in + if duringSync { + await snapshot.services.syncCoordinator.setSyncActivityCallbacks( + onStarted: { await ready.wait() }, onEnded: { _ in }, onPhaseChanged: { _ in } + ) + } else { + await ready.wait() + } } - } - await harness.transport.setAnswerSetup(true) - let firstID = UUID() - let first = Task { try await harness.manager.connectViaBluetooth(peripheralID: firstID) } - var replacement: Task? - let recoveryGate = TeardownGate() - var replacementRecovery: Task? - do { - try await waitUntil("first connection should park before sync") { ready.isWaiting } - #expect(harness.manager.connectedDevice?.id == firstID) - try await harness.manager.powerOffCurrentLink() - await harness.transport.setAnswerSetup(false) - let replacementID = firstID - replacement = Task { - try await harness.manager.connect(to: replacementID, forceFullSync: true, forceReconnect: true) + let firstID = UUID() + let first = harness.track(Task { try await harness.manager.connectViaBluetooth(peripheralID: firstID) }) + try await waitUntil("old setup should enter its gate") { ready.isWaiting } + let firstRequest = harness.manager.connectionRequestID + let baseline = await harness.radio.connectCount + let retiring = harness.track(Task { await harness.manager.disconnect(reason: .powerOff) }) + try await waitUntil("old publication should retire") { harness.manager.currentConnection == nil } + let replacementID = UUID() + let replacement = harness.track(Task { try await harness.manager.connect(to: replacementID, forceReconnect: true) }) + try await waitUntil("replacement should be admitted") { + harness.manager.connectionRequestID != firstRequest && harness.manager.desiredRequest?.target.deviceID == replacementID } - try await waitUntil("replacement should send app start") { await harness.transport.appStartCount == 3 } - let currentSession = try #require(harness.manager.session) - let recovery = Task { await recoveryGate.wait() } - replacementRecovery = recovery - harness.manager.resyncTask = recovery - harness.manager.resyncAttemptCount = 2 - ready.release() - _ = await first.result - #expect(await harness.transport.isConnected) - #expect(harness.manager.session === currentSession) - #expect(harness.manager.connectingDeviceID == replacementID) - #expect(harness.manager.connectionIntent == .wantsConnection(forceFullSync: true)) - #expect(recovery.isCancelled == false) - #expect(harness.manager.resyncAttemptCount == 2) - recoveryGate.release() - await recovery.value - await harness.finish(replacement: replacement) - } catch { - ready.release() - recoveryGate.release() + #expect(await harness.radio.connectCount == baseline) + ready.open() _ = await first.result - await replacementRecovery?.value - await harness.finish(replacement: replacement) - throw error + _ = await retiring.value + let outcome = try await replacement.value + if case .operational = outcome {} else { Issue.record("Replacement did not become operational") } + #expect(harness.manager.connectedDevice?.id == replacementID) + #expect(harness.manager.connectionState == .ready) + #expect(await harness.radio.isConnected) + _ = try await harness.manager.currentConnection?.services.session.getTime() } } @Test - func `opportunistic BLE rebuild stands down during teardown`() async throws { - let harness = try await TeardownHarness.make() - let gate = TeardownGate() - harness.manager.testConnectionTeardownHandler = { await gate.wait() } - harness.manager.testLastConnectedDeviceID = harness.device.id - await harness.stateMachine.setStubbedIsConnected(true) - await harness.stateMachine.setStubbedConnectedDeviceID(harness.device.id) - var rebuilt = false - harness.manager.rebuildSessionForHealthCheckOverride = { _ in rebuilt = true } - let disconnect = Task { await harness.manager.disconnect(reason: .resyncFailed) } - do { - try await waitUntil("transient disconnect should park in teardown") { gate.isWaiting } - await harness.manager.checkBLEConnectionHealth() - #expect(rebuilt == false) - await #expect(throws: CancellationError.self) { - try await harness.manager.rebuildSession(deviceID: harness.device.id) + func `opportunistic health and an old rebuild cannot cross a terminal cleanup barrier`() async throws { + try await withHarness { harness in + let request = try #require(harness.manager.desiredRequest) + let oldCycle = harness.manager.reconnectionCoordinator.begin(deviceID: harness.deviceID, requestID: request.id) + let gate = harness.gate() + harness.manager.testConnectionTeardownHandler = { await gate.wait() } + let closing = harness.track(Task { await harness.manager.disconnect(reason: .resyncFailed) }) + try await waitUntil("cleanup should park") { gate.isWaiting } + let baseline = await harness.radio.connectCount + var healthFinished = false + let health = harness.track(Task { + await harness.manager.checkBLEConnectionHealth() + healthFinished = true + }) + try await waitUntil("health should return or join the physical retirement barrier") { + healthFinished || harness.manager.desiredRequest?.target.deviceID == harness.deviceID } - #expect(harness.manager.connectionState == .disconnected) - #expect(harness.manager.session == nil) - gate.release() - await disconnect.value - await harness.finish(replacement: nil) - } catch { - gate.release() - await disconnect.value - await harness.finish(replacement: nil) - throw error + await #expect(throws: CancellationError.self) { try await harness.manager.rebuildBLEStack(oldCycle) } + #expect(await harness.radio.connectCount == baseline) + #expect(harness.manager.currentConnection == nil) + gate.open() + _ = await closing.value + await health.value } } @Test - func `cancelling a replacement parked behind teardown never connects`() async throws { - let harness = try await TeardownHarness.make() - let gate = TeardownGate() - harness.manager.testConnectionTeardownHandler = { await gate.wait() } - let powerOff = Task { try await harness.manager.powerOffCurrentLink() } - var replacement: Task? - do { - try await waitUntil("power-off should park in teardown") { gate.isWaiting } - let baseline = await harness.transport.connectCount - let attempt = Task { try await harness.manager.connectViaBluetooth(peripheralID: UUID()) } - replacement = attempt - try await waitUntil("replacement should wait for teardown") { - harness.manager.testConnectionTeardownWaiterCount == 1 + func `cancelling a replacement behind retirement never submits a physical connect`() async throws { + try await withHarness { harness in + let gate = harness.gate() + var losses: [ConnectionLossReceipt] = [] + harness.manager.onConnectionLost = { losses.append($0) } + harness.manager.testConnectionTeardownHandler = { await gate.wait() } + let closing = harness.track(Task { await harness.manager.disconnect() }) + try await waitUntil("cleanup should park") { gate.isWaiting } + let baseline = await harness.radio.connectCount + let target = UUID() + let replacement = harness.track(Task { try await harness.manager.connectViaBluetooth(peripheralID: target) }) + try await waitUntil("replacement should be admitted") { harness.manager.desiredRequest?.target.deviceID == target } + let admitted = harness.manager.connectionRequestID + let admittedIntent = harness.manager.connectionIntent + replacement.cancel() + try await waitUntil("caller cancellation should cancel the admitted worker") { + harness.manager.desiredRequest?.worker?.isCancelled == true } - attempt.cancel() - gate.release() - _ = await powerOff.result - await #expect(throws: CancellationError.self) { try await attempt.value } - #expect(await harness.transport.connectCount == baseline) - #expect(harness.manager.testConnectionTeardownWaiterCount == 0) + gate.open() + _ = await closing.value + let outcome = try await replacement.value + if case .cancelled = outcome {} else { Issue.record("Cancelled caller returned another outcome") } + #expect(await harness.radio.connectCount == baseline) #expect(harness.manager.connectionTeardownCount == 0) - await harness.finish(replacement: replacement) - } catch { - gate.release() - _ = await powerOff.result - await harness.finish(replacement: replacement) - throw error + #expect(harness.manager.currentConnection == nil) + #expect(harness.manager.connectionState == .disconnected) + #expect(harness.manager.desiredRequest?.attempt == nil) + #expect(harness.manager.desiredRequest?.target.deviceID == target) + #expect(harness.manager.connectionIntent == admittedIntent) + #expect(harness.manager.connectionIntent == .wantsConnection(forceFullSync: false)) + #expect(losses.map(\.requestID) == [admitted]) + harness.manager.testConnectionTeardownHandler = nil + await harness.manager.checkBLEConnectionHealth() + await harness.manager.checkWiFiConnectionHealth() + #expect(harness.manager.connectionState != .connecting) + if harness.manager.connectionState == .ready { + #expect(try await harness.manager.session?.getTime() != nil) + } } } @Test(arguments: [false, true]) - func `duplicate disconnects drain before a manual test override runs`(wifi: Bool) async throws { - let harness = try await TeardownHarness.make() - let gate = TeardownGate() - harness.manager.testConnectionTeardownHandler = { await gate.wait() } - let powerOff = Task { try await harness.manager.powerOffCurrentLink() } - var replacement: Task? - do { - try await waitUntil("power-off should park in teardown") { gate.isWaiting } - await harness.manager.disconnect() - #expect(harness.manager.connectionTeardownCount == 1) - var attempted = false - harness.manager.testBluetoothConnectHandler = { _ in attempted = true } - harness.manager.testWiFiConnectHandler = { _, _ in attempted = true } - let attempt = Task { - if wifi { - try await harness.manager.connectViaWiFi(host: "radio.local", port: 4242) - } else { - try await harness.manager.connectViaBluetooth(peripheralID: UUID()) - } + func `overlapping retirement callers join the old close before replacement setup`(wifi: Bool) async throws { + try await withHarness { harness in + let gate = harness.gate() + harness.manager.testConnectionTeardownHandler = { await gate.wait() } + let first = harness.track(Task { await harness.manager.disconnect() }) + try await waitUntil("first retirement should park") { gate.isWaiting } + let firstTerminal = harness.manager.connectionRequestID + let second = harness.track(Task { await harness.manager.disconnect() }) + try await waitUntil("second terminal request should be admitted") { + harness.manager.connectionRequestID != firstTerminal } - replacement = attempt - try await waitUntil("manual entry should wait for all teardown") { - harness.manager.testConnectionTeardownWaiterCount == 1 || attempted + let baseline = await harness.radio.connectCount + let replacement = harness.track(Task { + if wifi { return try await harness.manager.connectViaWiFi(host: "radio.local", port: 4242) } + return try await harness.manager.connectViaBluetooth(peripheralID: UUID()) + }) + try await waitUntil("replacement request should replace terminal request") { + harness.manager.desiredRequest?.target != .disconnected } - #expect(attempted == false) - gate.release() - _ = await powerOff.result - try await attempt.value - #expect(attempted) + #expect(await harness.radio.connectCount == baseline) + gate.open() + _ = await first.value + _ = await second.value + _ = try await replacement.value + #expect(harness.manager.connectionState == .ready) #expect(harness.manager.connectionTeardownCount == 0) - #expect(harness.manager.testConnectionTeardownWaiterCount == 0) - await harness.finish(replacement: replacement) - } catch { - gate.release() - _ = await powerOff.result - await harness.finish(replacement: replacement) - throw error + #expect(await harness.radio.disconnectCount == 1) } } @Test - func `power-off finishes shared transport teardown before a replacement connects`() async throws { - let harness = try await TeardownHarness.make() - let gate = TeardownGate() - harness.manager.testConnectionTeardownHandler = { await gate.wait() } - let powerOff = Task { try await harness.manager.powerOffCurrentLink() } - var replacement: Task? - do { - try await waitUntil("power-off should park in teardown") { gate.isWaiting } - let target = harness.device.id - let baseline = await harness.transport.connectCount - replacement = Task { try await harness.manager.connectViaBluetooth(peripheralID: target) } - try await waitUntil("replacement should reach teardown or transport") { - let connectCount = await harness.transport.connectCount - return harness.manager.testConnectionTeardownWaiterCount > 0 || connectCount > baseline - } - #expect(await harness.transport.connectCount == baseline) - - gate.release() - _ = await powerOff.result - try await harness.waitForReplacementHandshake() - #expect(await harness.transport.isConnected) - #expect(await harness.transport.lastConnectFollowsLastDisconnect) - #expect(harness.manager.connectionIntent.wantsConnection) - #expect(harness.manager.session != nil) - await harness.finish(replacement: replacement) - } catch { - gate.release() + func `power off retirement finishes before an admitted Bluetooth replacement dials`() async throws { + try await withHarness { harness in + let gate = harness.gate() + harness.manager.testConnectionTeardownHandler = { await gate.wait() } + let powerOff = harness.track(Task { try await harness.manager.powerOffCurrentLink() }) + try await waitUntil("power off cleanup should park") { gate.isWaiting } + let baseline = await harness.radio.connectCount + let replacement = harness.track(Task { try await harness.manager.connectViaBluetooth(peripheralID: UUID()) }) + try await waitUntil("replacement should be admitted") { harness.manager.connectionIntent.wantsConnection } + #expect(await harness.radio.connectCount == baseline) + gate.open() _ = await powerOff.result - await harness.finish(replacement: replacement) - throw error + _ = try await replacement.value + #expect(harness.manager.connectionState == .ready) + #expect(await harness.radio.isConnected) } } @Test - func `an admitted replacement revokes settled cleanup before session publication`() async throws { - let harness = try await TeardownHarness.make() - let token = try await harness.manager.powerOffCurrentLink() - #expect(harness.manager.powerOffOwnsCleanup(token)) - await harness.transport.holdConnect() - let replacement = Task { try await harness.manager.connect(to: UUID(), forceReconnect: true) } - do { - try await waitUntil("replacement connect should park") { await harness.transport.connectIsWaiting } + func `an admitted replacement revokes settled power off cleanup before session publication`() async throws { + try await withHarness { harness in + let token = try await harness.manager.powerOffCurrentLink() + #expect(harness.manager.powerOffOwnsCleanup(token)) + await harness.radio.holdConnect() + let replacement = harness.track(Task { try await harness.manager.connect(to: UUID(), forceReconnect: true) }) + try await waitUntil("replacement connect should park") { await harness.radio.connectIsHeld } #expect(harness.manager.session == nil) - #expect(harness.manager.powerOffOwnsCleanup(token) == false) - await harness.transport.releaseConnect() - try await harness.waitForReplacementHandshake() - #expect(await harness.transport.isConnected) - await harness.finish(replacement: replacement) - } catch { - await harness.transport.releaseConnect() - await harness.finish(replacement: replacement) - throw error + #expect(!harness.manager.powerOffOwnsCleanup(token)) + await harness.radio.releaseConnect() + _ = try await replacement.value + #expect(harness.manager.connectionState == .ready) } } @Test - func `an admitted switch invalidates an unsettled power-off before transport connect`() async throws { - let harness = try await TeardownHarness.make() - await harness.transport.inner.holdNextSend() - let powerOff = Task { try await harness.manager.powerOffCurrentLink() } - var replacement: Task? - do { - try await waitUntil("power-off send should park") { await harness.transport.inner.sendIsWaiting } - await harness.transport.holdConnect() - replacement = Task { try await harness.manager.switchDevice(to: UUID()) } - try await waitUntil("replacement switch should park") { await harness.transport.connectIsWaiting } - await harness.transport.inner.releaseHeldSend() + func `admitting a replacement revokes unsettled power off and drains its actual send first`() async throws { + try await withHarness { harness in + await harness.radio.holdNextSendCompletion() + let powerOff = harness.track(Task { try await harness.manager.powerOffCurrentLink() }) + try await waitUntil("power off send completion should park") { await harness.radio.sendCompletionIsHeld } + let previous = harness.manager.connectionRequestID + let baseline = await harness.radio.connectCount + let replacement = harness.track(Task { try await harness.manager.connect(to: UUID(), forceReconnect: true) }) + try await waitUntil("replacement should be admitted") { harness.manager.connectionRequestID != previous } + #expect(await harness.radio.connectCount == baseline) + await harness.radio.releaseSendCompletion() await #expect(throws: PowerOffSuperseded.self) { try await powerOff.value } + _ = try await replacement.value + #expect(harness.manager.connectionState == .ready) #expect(harness.manager.connectionIntent.wantsConnection) - await harness.transport.releaseConnect() - await harness.finish(replacement: replacement) - } catch { - await harness.transport.inner.releaseHeldSend() - await harness.transport.releaseConnect() - _ = await powerOff.result - await harness.finish(replacement: replacement) - throw error } } @Test - func `socket loss teardown finishes before a manual Bluetooth replacement`() async throws { - let harness = try await TeardownHarness.make() - let gate = TeardownGate() - harness.manager.setTestState(currentTransportType: .wifi) - harness.manager.testConnectionTeardownHandler = { await gate.wait() } - harness.manager.testWiFiMaxReconnectDuration = .seconds(-1) - let loss = Task { - await harness.manager.handleWiFiDisconnection(error: WiFiTransportError.notConnected, remoteLossAt: nil) - } - var replacement: Task? - do { - try await waitUntil("socket loss should park in teardown") { gate.isWaiting } - let baseline = await harness.transport.connectCount - replacement = Task { try await harness.manager.connectViaBluetooth(peripheralID: UUID()) } - try await waitUntil("replacement should reach teardown or transport") { - let connectCount = await harness.transport.connectCount - return harness.manager.testConnectionTeardownWaiterCount > 0 || connectCount > baseline - } - #expect(await harness.transport.connectCount == baseline) - harness.manager.testConnectionTeardownHandler = nil - gate.release() + func `socket loss retirement finishes before a manual Bluetooth replacement`() async throws { + try await withHarness(wifi: true) { harness in + let gate = harness.gate() + harness.manager.testConnectionTeardownHandler = { await gate.wait() } + let socket = try #require(harness.manager.installedLink?.resource.wifi) + let loss = harness.track(Task { + await harness.manager.handleWiFiDisconnection(error: WiFiTransportError.notConnected, remoteLossAt: nil, source: socket) + }) + try await waitUntil("socket retirement should park") { gate.isWaiting } + let baseline = await harness.radio.connectCount + let replacement = harness.track(Task { try await harness.manager.connectViaBluetooth(peripheralID: UUID()) }) + try await waitUntil("Bluetooth replacement should be admitted") { harness.manager.desiredRequest?.target.transportType == .bluetooth } + #expect(await harness.radio.connectCount == baseline) + gate.open() await loss.value - try await harness.waitForReplacementHandshake() - #expect(await harness.transport.isConnected) - #expect(harness.manager.connectionState == .connected) + _ = try await replacement.value + #expect(harness.manager.connectionState == .ready) #expect(harness.manager.wifiReconnectTask == nil) - await harness.finish(replacement: replacement) - } catch { - harness.manager.testConnectionTeardownHandler = nil - gate.release() - await loss.value - await harness.finish(replacement: replacement) - throw error } } -} -extension ConnectionManagerTeardownTests { + private func withHarness(wifi: Bool = false, _ body: (Harness) async throws -> Void) async throws { + let harness = try await Harness.make(wifi: wifi) + do { try await body(harness) } catch { await harness.finish(); throw error } + await harness.finish() + } + @MainActor - private struct TeardownHarness { + private final class Harness { let manager: ConnectionManager - let transport: SharedTeardownTransport - let device: DeviceDTO - let stateMachine: MockBLEStateMachine + let radio: ConnectionTestRadioTransport + let deviceID: UUID let suiteName: String + private var gates: [Gate] = [] + private var cancellations: [() -> Void] = [] + private var joins: [() async -> Void] = [] + + private init(manager: ConnectionManager, radio: ConnectionTestRadioTransport, deviceID: UUID, suiteName: String) { + self.manager = manager + self.radio = radio + self.deviceID = deviceID + self.suiteName = suiteName + } - static func make() async throws -> TeardownHarness { - let suiteName = "test.teardown.\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: suiteName)) + static func make(wifi: Bool) async throws -> Harness { + let suite = "test.teardown.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suite)) let container = try PersistenceStore.createContainer(inMemory: true) - let transport = SharedTeardownTransport() + let radio = ConnectionTestRadioTransport() let stateMachine = MockBLEStateMachine() + let pairing = MockAccessorySetupKitService() + pairing.isSessionActive = false let manager = ConnectionManager( - modelContainer: container, defaults: defaults, - stateMachine: stateMachine, transport: transport - ) - let session = MeshCoreSession(transport: transport) - let device = DeviceDTO.testDevice(firmwareVersion: 14) - let services = try await ServiceContainer.forTesting(session: session, radioID: device.radioID) - manager.setTestState( - connectionState: .ready, services: services, session: session, - connectedDevice: device, currentTransportType: .bluetooth, connectionIntent: .wantsConnection() - ) - let start = Task { try await session.start() } - try await waitUntil("session should send app start") { await transport.appStartCount == 1 } - await transport.inner.simulateReceive(selfInfoPacket()) - try await start.value - return TeardownHarness( - manager: manager, transport: transport, device: device, stateMachine: stateMachine, suiteName: suiteName + modelContainer: container, defaults: defaults, stateMachine: stateMachine, transport: radio, + pairing: AccessorySetupPairingService(accessorySetupKit: pairing), makeWiFiTransport: { radio } ) + let deviceID = UUID() + let harness = Harness(manager: manager, radio: radio, deviceID: deviceID, suiteName: suite) + do { + if wifi { + _ = try await manager.connectViaWiFi(host: "radio.local", port: 4242) + } else { + _ = try await manager.connect(to: deviceID, forceReconnect: true) + } + #expect(manager.connectionState == .ready) + return harness + } catch { + await harness.finish() + throw error + } } - func waitForReplacementHandshake() async throws { - try await waitUntil("replacement should send app start") { await transport.appStartCount == 2 } + func gate() -> Gate { + let gate = Gate(); gates.append(gate); return gate } - func finish(replacement: Task?) async { - manager.testConnectionTeardownHandler = nil - await transport.releaseConnect() - await transport.inner.releaseHeldSend() - replacement?.cancel() - await manager.disconnect() - _ = await replacement?.result - UserDefaults().removePersistentDomain(forName: suiteName) + func track(_ task: Task) -> Task { + cancellations.append { task.cancel() } + joins.append { _ = await task.result } + return task } - nonisolated static func selfInfoPacket() -> Data { - var packet = Data([ResponseCode.selfInfo.rawValue, 1, 22, 22]) - packet.append(Data(repeating: 0x01, count: 32)) - packet.append(Data(repeating: 0, count: 12)) - for value: UInt32 in [915_000, 125_000] { - packet.append(withUnsafeBytes(of: value.littleEndian) { Data($0) }) + func finish() async { + manager.testConnectionTeardownHandler = nil + for gate in gates { + gate.open() } - packet.append(contentsOf: [7, 5]) - return packet + await radio.releaseAllGates() + for cancel in cancellations { + cancel() + } + _ = await manager.disconnect() + for join in joins { + await join() + } + UserDefaults().removePersistentDomain(forName: suiteName) } } @MainActor - private final class TeardownGate { - private var continuation: CheckedContinuation? + private final class Gate { + private var waiters: [CheckedContinuation] = [] private var isOpen = false - private(set) var isWaiting = false + var isWaiting: Bool { + !waiters.isEmpty + } func wait() async { - guard !isOpen, !isWaiting else { return } - isWaiting = true - await withCheckedContinuation { continuation = $0 } - isWaiting = false + guard !isOpen else { return } + await withCheckedContinuation { waiters.append($0) } } - func release() { + func open() { isOpen = true - let pending = continuation - continuation = nil - pending?.resume() - } - } - - private actor SharedTeardownTransport: iOSMeshTransport { - let inner = MockTransport() - private var events: [String] = [] - private var shouldHoldConnect = false - private var connectContinuation: CheckedContinuation? - private var answerSetup = false - private(set) var connectIsWaiting = false - private(set) var connectCount = 0 - - var isConnected: Bool { - get async { await inner.isConnected } - } - - var receivedData: AsyncStream { - get async { await inner.receivedData } - } - - var appStartCount: Int { - get async { await inner.sentData.filter { $0.first == CommandCode.appStart.rawValue }.count } - } - - var lastConnectFollowsLastDisconnect: Bool { - guard let connect = events.lastIndex(of: "connect"), let disconnect = events.lastIndex(of: "disconnect") else { return false } - return connect > disconnect - } - - func connect() async throws { - connectCount += 1 - if shouldHoldConnect { - connectIsWaiting = true - await withCheckedContinuation { connectContinuation = $0 } - connectIsWaiting = false - } - events.append("connect") - try await inner.connect() - } - - func disconnect() async { - events.append("disconnect") - await inner.disconnect() - } - - func send(_ data: Data) async throws { - try await inner.send(data) - guard answerSetup else { return } - switch data.first { - case CommandCode.appStart.rawValue: - await inner.simulateReceive(TeardownHarness.selfInfoPacket()) - case CommandCode.deviceQuery.rawValue: - var response = Data([ResponseCode.deviceInfo.rawValue, 14, 1, 1]) - response.append(Data(repeating: 0, count: 76)) - await inner.simulateReceive(response) - case CommandCode.getAutoAddConfig.rawValue: - await inner.simulateReceive(Data([ResponseCode.autoAddConfig.rawValue, 0])) - case CommandCode.runCliCommand.rawValue: - break - default: - await inner.simulateReceive(Data([ResponseCode.error.rawValue, 1])) + let pending = waiters + waiters.removeAll() + for waiter in pending { + waiter.resume() } } - - func setDeviceID(_ id: UUID) {} - func switchDevice(to deviceID: UUID) async throws { - await disconnect() - try await connect() - } - - func setDisconnectionHandler(_ handler: @escaping @Sendable (UUID, Error?) -> Void) {} - func setReconnectionHandler(_ handler: @escaping @Sendable (UUID) -> Void) {} - func refreshDataStream() {} - - func holdConnect() { - shouldHoldConnect = true - } - - func setAnswerSetup(_ answer: Bool) { - answerSetup = answer - } - - func releaseConnect() { - shouldHoldConnect = false - let pending = connectContinuation - connectContinuation = nil - pending?.resume() - } } } diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWatchdogDeferralTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWatchdogDeferralTests.swift new file mode 100644 index 0000000000..98a9f4fb47 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWatchdogDeferralTests.swift @@ -0,0 +1,156 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Bluetooth watchdog pairing deferral", .timeLimit(.minutes(1))) +@MainActor +struct ConnectionManagerWatchdogDeferralTests { + @Test(arguments: [false, true]) + func `cancelled discovery retains a later usable retry`(cancelTask: Bool) async throws { + try await withWatchdogFixture { fixture in + let request = try #require(fixture.manager.desiredRequest) + let oldLink = try #require(fixture.manager.installedLink) + try await fixture.openDiscovery() + let watchdog = try await fixture.loseConnection() + let generation = fixture.manager.reconnectionWatchdogGeneration + #expect(fixture.manager.desiredRequest === request) + #expect(fixture.manager.installedLink == nil) + #expect(!oldLink.resource.binding.isActive) + try await fixture.expectStates([.disconnected]) + + fixture.clock.advance(by: WatchdogDeferralFixture.initialDelay) + try await waitUntil(timeout: WatchdogDeferralFixture.observationTimeout, "the held picker tick must settle") { + fixture.clock.sleeperCount == 1 || !fixture.manager.isReconnectionWatchdogRunning + } + #expect(fixture.pairing.isPresenting) + #expect(fixture.manager.isPairingInProgress) + #expect(fixture.manager.connectionIntent.wantsConnection) + #expect(fixture.manager.connectionState == .disconnected) + #expect(fixture.manager.desiredRequest === request) + #expect(await fixture.radio.connectCount == 1) + try #require(fixture.clock.sleeperCount == 1, "Temporary picker deferral must schedule the next retry") + #expect(fixture.manager.reconnectionWatchdogGeneration == generation) + try await fixture.expectStates([.disconnected]) + + try await fixture.cancelDiscovery(cancelTask: cancelTask) + #expect(!fixture.pairing.isPresenting) + #expect(!fixture.manager.isPairingInProgress) + #expect(fixture.manager.desiredRequest === request) + #expect(fixture.manager.isReconnectionWatchdogRunning) + fixture.clock.advance(by: WatchdogDeferralFixture.initialDelay) + #expect(await fixture.radio.connectCount == 1) + #expect(fixture.clock.sleeperCount == 1) + fixture.clock.advance(by: WatchdogDeferralFixture.initialDelay) + try await fixture.requireReady() + await watchdog.value + + let current = try #require(fixture.manager.installedLink) + #expect(current !== oldLink) + #expect(current.resource !== oldLink.resource) + #expect(current.requestID != request.id) + #expect(current.target == .bluetooth(fixture.deviceID)) + #expect(current.device.radioID == oldLink.device.radioID) + #expect(await fixture.radio.connectCount == 2) + #expect(fixture.clock.sleeperCount == 0) + fixture.clock.advance(by: WatchdogDeferralFixture.laterTime) + #expect(fixture.manager.installedLink === current) + #expect(await fixture.radio.connectCount == 2) + #expect(try await current.services.session.getTime().timeIntervalSince1970 > 0) + await fixture.finishAndExpectStates([.disconnected, .connecting, .connecting, .connected, .syncing, .ready]) + } + } + + @Test + func `a pending health handshake owns one physical attempt`() async throws { + try await withWatchdogFixture { fixture in + let oldLink = try #require(fixture.manager.installedLink) + let watchdog = try await fixture.loseConnection() + await fixture.radio.holdReplies(for: .appStart) + fixture.clock.advance(by: WatchdogDeferralFixture.initialDelay) + try await waitUntil(timeout: WatchdogDeferralFixture.observationTimeout, "health recovery must reach the held handshake") { + await fixture.radio.heldReplyCount(for: .appStart) == 1 + } + let request = try #require(fixture.manager.desiredRequest) + let attempt = try #require(request.attempt) + let resource = try #require(attempt.resource) + #expect(request.id != oldLink.requestID) + #expect(resource !== oldLink.resource) + #expect(resource.binding.isActive) + #expect(await fixture.radio.connectCount == 2) + #expect(fixture.clock.sleeperCount == 0) + try await fixture.expectStates([.disconnected, .connecting, .connecting, .connected]) + + fixture.clock.advance(by: WatchdogDeferralFixture.laterTime) + #expect(fixture.manager.desiredRequest === request) + #expect(request.attempt === attempt) + #expect(attempt.resource === resource) + #expect(await fixture.radio.heldReplyCount(for: .appStart) == 1) + #expect(await fixture.radio.connectCount == 2) + await fixture.radio.releaseReplies(for: .appStart) + try await fixture.requireReady() + await watchdog.value + + let current = try #require(fixture.manager.installedLink) + #expect(current.requestID == request.id) + #expect(current.resource === resource) + #expect(current.resource.binding.isActive) + #expect(await fixture.radio.connectCount == 2) + #expect(try await current.services.session.getTime().timeIntervalSince1970 > 0) + await fixture.finishAndExpectStates([.disconnected, .connecting, .connecting, .connected, .syncing, .ready]) + } + } + + @Test(arguments: [false, true]) + func `a sleeping old timer cannot alter a successor`(sameRadio: Bool) async throws { + try await withWatchdogFixture { fixture in + let oldRequest = try #require(fixture.manager.desiredRequest) + let watchdog = try await fixture.loseConnection() + let targetID = sameRadio ? fixture.deviceID : UUID() + await fixture.radio.setPublicKey(Data(repeating: sameRadio ? 1 : 2, count: 32), for: targetID) + let result = try await fixture.manager.connect(to: targetID, forceFullSync: true, forceReconnect: true) + await watchdog.value + let current = try #require(fixture.manager.installedLink) + let physicalOrigin = await fixture.radio.lifecycleOrigin + let disconnectCount = await fixture.radio.disconnectCount + #expect(current.requestID != oldRequest.id) + #expect(fixture.manager.isCurrent(result)) + #expect(current.target == .bluetooth(targetID)) + #expect(current.resource.binding.isActive) + #expect(fixture.clock.sleeperCount == 0) + + fixture.clock.advance(by: WatchdogDeferralFixture.laterTime) + #expect(fixture.manager.installedLink === current) + #expect(fixture.manager.connectionRequestID == current.requestID) + #expect(fixture.manager.connectionState == .ready) + #expect(current.resource.binding.isActive) + #expect(await fixture.radio.lifecycleOrigin == physicalOrigin) + #expect(await fixture.radio.connectCount == 2) + #expect(await fixture.radio.disconnectCount == disconnectCount) + #expect(try await current.services.session.getTime().timeIntervalSince1970 > 0) + await fixture.finishAndExpectStates([.disconnected, .connecting, .connecting, .connected, .syncing, .ready]) + } + } + + @Test + func `explicit disconnect revokes a sleeping retry`() async throws { + try await withWatchdogFixture { fixture in + let watchdog = try await fixture.loseConnection() + let receipt = await fixture.manager.disconnect() + await watchdog.value + let requestID = fixture.manager.connectionRequestID + let disconnectCount = await fixture.radio.disconnectCount + fixture.clock.advance(by: WatchdogDeferralFixture.laterTime) + + #expect(fixture.manager.isCurrent(receipt)) + #expect(fixture.manager.connectionRequestID == requestID) + #expect(!fixture.manager.connectionIntent.wantsConnection) + #expect(fixture.manager.connectionState == .disconnected) + #expect(fixture.manager.installedLink == nil) + #expect(!fixture.manager.isReconnectionWatchdogRunning) + #expect(fixture.clock.sleeperCount == 0) + #expect(await fixture.radio.connectCount == 1) + #expect(await fixture.radio.disconnectCount == disconnectCount) + await fixture.finishAndExpectStates([.disconnected, .disconnected]) + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiEstablishmentControlTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiEstablishmentControlTests.swift new file mode 100644 index 0000000000..314afe94f7 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiEstablishmentControlTests.swift @@ -0,0 +1,147 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("WiFi pre-publication loss authority controls") +@MainActor +struct ConnectionManagerWiFiEstablishmentControlTests { + @Test(arguments: [false, true]) + func `actual caller cancellation retains cancellation after TCP EOF`(launch: Bool) async throws { + try await ConnectionWiFiEstablishmentHarness.withHarness { harness in + harness.holdFirstSelection() + let connecting = harness.track(Task { + if launch { + await harness.manager.reconnectLastUsedTransport(device: harness.saved, lastDeviceID: harness.saved.id) + return nil + } + return try await harness.manager.connectViaWiFi(host: harness.host, port: harness.port) + }) + let candidate = try await harness.selectedCandidate() + let worker = try #require(candidate.request.worker) + try await harness.endReceive(candidate.attempt) + connecting.cancel() + try await waitUntil("caller cancellation must cancel the actual request worker before selection resumes") { + candidate.request.worker?.isCancelled == true + } + harness.releaseSelection() + _ = await connecting.result + let outcome = await worker.result + if case .success(.cancelled) = outcome {} else { Issue.record("An actually cancelled request must retain cancellation") } + #expect(harness.manager.desiredRequest === candidate.request) + #expect(harness.manager.currentConnection == nil) + #expect(await harness.bluetooth.connectCount == 0) + #expect(!harness.manager.isReconnectionWatchdogRunning) + try await harness.proveLaterIO() + } + } + + @Test(arguments: [false, true]) + func `explicit disconnect and matching removal stay terminal after TCP EOF`(removal: Bool) async throws { + try await ConnectionWiFiEstablishmentHarness.withHarness { harness in + harness.holdFirstSelection() + let launch = harness.track(Task { + await harness.manager.reconnectLastUsedTransport(device: harness.saved, lastDeviceID: harness.saved.id) + }) + let candidate = try await harness.selectedCandidate() + let worker = try #require(candidate.request.worker) + try await harness.endReceive(candidate.attempt) + let terminal = harness.track(Task { + if removal { try await harness.manager.deleteDevice(id: harness.saved.id) } else { _ = await harness.manager.disconnect(reason: .userInitiated) } + }) + try await waitUntil("terminal action must revoke this request before selection resumes") { + harness.manager.desiredRequest !== candidate.request + } + harness.releaseSelection() + await launch.value + try await terminal.value + let outcome = await worker.result + if case .success(.superseded) = outcome {} else { Issue.record("A terminal action must supersede the old request") } + #expect(!harness.manager.connectionIntent.wantsConnection) + #expect(harness.manager.currentConnection == nil) + #expect(await harness.bluetooth.connectCount == 0) + #expect(!harness.manager.isReconnectionWatchdogRunning) + if removal { + let ghost = try #require(try await harness.manager.persistenceStore.fetchDevice(publicKey: harness.saved.publicKey)) + #expect(ghost.radioID == harness.saved.radioID) + #expect(ghost.connectionMethods.isEmpty) + } + try await harness.proveLaterIO() + } + } + + @Test(arguments: [false, true]) + func `a new same-radio or different-radio request supersedes the lost WiFi candidate`(sameRadio: Bool) async throws { + try await ConnectionWiFiEstablishmentHarness.withHarness { harness in + harness.holdFirstSelection() + let connecting = harness.track(Task { + try await harness.manager.connectViaWiFi(host: harness.host, port: harness.port) + }) + let candidate = try await harness.selectedCandidate() + try await harness.endReceive(candidate.attempt) + let target = sameRadio ? harness.saved.id : UUID() + if !sameRadio { + await harness.bluetooth.setPublicKey(Data(repeating: 0xB1, count: ProtocolLimits.publicKeySize), for: target) + } + let replacement = harness.track(Task { try await harness.manager.connect(to: target, forceReconnect: true) }) + try await waitUntil("replacement must acquire user authority before old selection resumes") { + harness.manager.desiredRequest !== candidate.request + } + #expect(await harness.bluetooth.connectCount == 0) + harness.releaseSelection() + let oldOutcome = try await connecting.value + if case .superseded = oldOutcome {} else { Issue.record("A replaced request must retain supersession") } + let current = try await replacement.value + #expect(harness.manager.isCurrent(current)) + #expect(harness.manager.connectedDevice?.id == target) + #expect(harness.manager.desiredRequest?.binding?.isActive == true) + #expect(await harness.bluetooth.isConnected) + let session = try #require(harness.manager.session) + #expect(try await session.getTime().timeIntervalSince1970 > 0) + try await harness.proveLaterIO() + } + } + + @Test + func `pre-publication Bluetooth OS handoff does not advance the launch WiFi fallback`() async throws { + try await ConnectionWiFiEstablishmentHarness.withHarness(wifiLast: false) { harness in + await harness.manager.wireTransportHandlers() + harness.holdFirstSelection() + let launch = harness.track(Task { + await harness.manager.reconnectLastUsedTransport(device: harness.saved, lastDeviceID: harness.saved.id) + }) + let candidate = try await harness.selectedCandidate() + let worker = try #require(candidate.request.worker) + var lossHandled = false + var rebuildHandled = false + harness.manager.testBLELifecycleEventHandled = { event in + switch event { + case .autoReconnecting: lossHandled = true + case .reconnected: rebuildHandled = true + default: break + } + } + await harness.bluetooth.simulateAutoReconnecting(deviceID: harness.saved.id) + try await waitUntil("production BLE lifecycle handling must finish retirement of the unpublished candidate") { lossHandled } + try #require(candidate.request.handedOff) + try #require(!candidate.attempt.binding.isActive) + harness.releaseSelection() + await launch.value + let outcome = await worker.result + if case let .success(.handoff(requestID)) = outcome { #expect(requestID == candidate.request.id) } else { Issue.record("An OS-owned recovery must retain handoff") } + #expect(candidate.request.targetIndex == 0) + #expect(await harness.peer?.acceptedCount == 0) + #expect(!harness.manager.isReconnectionWatchdogRunning) + await harness.bluetooth.simulateReconnected() + try await waitUntil("the same request's OS rebuild must finish and become ready") { + rebuildHandled && harness.manager.connectionState == .ready + } + #expect(harness.manager.connectionRequestID == candidate.request.id) + #expect(harness.manager.desiredRequest?.binding?.isActive == true) + #expect(await harness.bluetooth.connectCount == 1) + let session = try #require(harness.manager.session) + #expect(try await session.getTime().timeIntervalSince1970 > 0) + try await harness.proveLaterIO() + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiEstablishmentLossTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiEstablishmentLossTests.swift new file mode 100644 index 0000000000..4fd2a159ae --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiEstablishmentLossTests.swift @@ -0,0 +1,112 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("WiFi pre-publication loss outcomes") +@MainActor +struct ConnectionManagerWiFiEstablishmentLossTests { + @Test + func `actual TCP EOF during launch selection advances to the saved Bluetooth target`() async throws { + try await ConnectionWiFiEstablishmentHarness.withHarness { harness in + harness.holdFirstSelection() + let launch = harness.track(Task { + await harness.manager.reconnectLastUsedTransport(device: harness.saved, lastDeviceID: harness.saved.id) + }) + let candidate = try await harness.selectedCandidate() + try #require(candidate.request.targets == [ + .wifi(host: harness.host, port: harness.port), .bluetooth(harness.saved.id) + ]) + try await harness.endReceive(candidate.attempt) + try #require(harness.manager.desiredRequest === candidate.request) + harness.releaseSelection() + await launch.value + + #expect(await harness.bluetooth.connectCount == 1) + #expect(harness.manager.currentTransportType == .bluetooth) + #expect(harness.manager.connectedDevice?.radioID == harness.saved.radioID) + #expect(harness.manager.connectionState == .ready) + #expect(!harness.manager.isReconnectionWatchdogRunning) + #expect(harness.manager.session != nil) + if let session = harness.manager.session { #expect(try await session.getTime().timeIntervalSince1970 > 0) } + try await harness.proveLaterIO() + } + } + + @Test + func `actual TCP EOF during explicit WiFi selection throws a current request failure`() async throws { + try await ConnectionWiFiEstablishmentHarness.withHarness { harness in + harness.holdFirstSelection() + let connecting = harness.track(Task { + try await harness.manager.connectViaWiFi(host: harness.host, port: harness.port) + }) + let candidate = try await harness.selectedCandidate() + try await harness.endReceive(candidate.attempt) + try #require(harness.manager.desiredRequest === candidate.request) + harness.releaseSelection() + await assertConnectionLoss(connecting.result, requestID: candidate.request.id, manager: harness.manager) + #expect(await harness.bluetooth.connectCount == 0) + #expect(!harness.manager.isReconnectionWatchdogRunning) + try await harness.proveLaterIO() + } + } + + @Test(arguments: [false, true]) + func `modeled receive errors follow launch fallback and explicit failure paths`(launch: Bool) async throws { + try await ConnectionWiFiEstablishmentHarness.withHarness(realSocket: false) { harness in + harness.holdFirstSelection() + let connecting = harness.track(Task { + if launch { + await harness.manager.reconnectLastUsedTransport(device: harness.saved, lastDeviceID: harness.saved.id) + return nil + } + return try await harness.manager.connectViaWiFi(host: harness.host, port: harness.port) + }) + let candidate = try await harness.selectedCandidate() + try await harness.endReceive(candidate.attempt, error: WiFiTransportError.connectionFailed("Modeled receive failure")) + harness.releaseSelection() + let outcome = await connecting.result + if launch { + #expect(await harness.bluetooth.connectCount == 1) + #expect(harness.manager.currentTransportType == .bluetooth) + #expect(harness.manager.connectionState == .ready) + } else { + assertConnectionLoss(outcome, requestID: candidate.request.id, manager: harness.manager) + #expect(await harness.bluetooth.connectCount == 0) + } + try await harness.proveLaterIO() + } + } + + @Test + func `ordinary failure of both launch targets still arms the Bluetooth watchdog`() async throws { + try await ConnectionWiFiEstablishmentHarness.withHarness(realSocket: false) { harness in + await harness.modeledWiFi.setConnectError(WiFiTransportError.notConnected) + await harness.bluetooth.setConnectError(BLEError.authenticationFailed) + await harness.manager.reconnectLastUsedTransport(device: harness.saved, lastDeviceID: harness.saved.id) + #expect(await harness.modeledWiFi.connectCount == 1) + #expect(await harness.bluetooth.connectCount == 1) + #expect(harness.manager.currentConnection == nil) + #expect(harness.manager.isReconnectionWatchdogRunning) + await harness.modeledWiFi.setConnectError(nil) + await harness.bluetooth.setConnectError(nil) + try await harness.proveLaterIO() + } + } + + private func assertConnectionLoss( + _ result: Result, requestID: UUID, manager: ConnectionManager + ) { + guard case let .failure(error) = result, let failure = error as? ConnectionRequestFailure else { + Issue.record("An owned receive loss must throw ConnectionRequestFailure, including explicit caller feedback") + return + } + #expect(failure.requestID == requestID) + #expect(manager.isCurrent(failure)) + #expect(!(failure.underlying is CancellationError)) + let connectionLoss = if case ConnectionError.notConnected = failure.underlying { true } else if case WiFiTransportError.notConnected = failure.underlying { true } else { false } + #expect(connectionLoss) + #expect(manager.currentConnection == nil) + #expect(manager.connectionIntent.wantsConnection) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiGiveUpTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiGiveUpTests.swift index 94a106641c..4a0345035c 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiGiveUpTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiGiveUpTests.swift @@ -2,54 +2,46 @@ import Foundation @testable import MC1Services import Testing -/// A WiFi give-up has to drop `wifiTransport`. `disconnect()` closes that socket -/// whenever it is set, including after a later Bluetooth session. -@Suite("WiFi give-up releases the transport") +@Suite("WiFi give-up releases the captured transport") @MainActor struct ConnectionManagerWiFiGiveUpTests { - private func armWiFiSession(_ manager: ConnectionManager) { - manager.testWiFiMaxReconnectDuration = .seconds(-1) - manager.setTestState( - connectionState: .ready, - currentTransportType: .wifi, - connectionIntent: .wantsConnection() - ) - manager.wifiTransport = WiFiTransport() - } - @Test - func `reconnect timeout clears the wifi transport`() async throws { - let env = try ConnectionManager.createForPairingTesting() - defer { env.cleanup() } - armWiFiSession(env.manager) - - await env.manager.checkWiFiConnectionHealth() - - try await waitUntil("WiFi reconnect timeout should release the transport") { - env.manager.wifiTransport == nil && env.manager.wifiReconnectTask == nil - } - #expect(env.manager.currentTransportType == nil) - #expect(env.manager.connectionState == .disconnected) + func `owned reconnect timeout closes the socket and a subsequent connection is usable`() async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + _ = try await env.connect(.wifi) + env.manager.testWiFiMaxReconnectDuration = .seconds(-1) + await env.wifi.simulateRemoteLoss() + try await waitUntil("bounded recovery should retire the socket") { + env.manager.connectionState == .disconnected && env.manager.wifiReconnectTask == nil + } + #expect(env.manager.wifiTransport == nil) + #expect(env.manager.currentTransportType == nil) + #expect(await env.wifi.isConnected == false) + _ = try await env.connect(.bluetooth) + #expect(env.manager.connectionState == .ready) + #expect(env.manager.currentTransportType == .bluetooth) + } catch { await env.close(); throw error } + await env.close() } @Test - func `reconnect cooldown clears the wifi transport`() async throws { - let env = try ConnectionManager.createForPairingTesting() - defer { env.cleanup() } - env.manager.testWiFiReconnectCooldown = 10000 - armWiFiSession(env.manager) - - await env.manager.checkWiFiConnectionHealth() - try await waitUntil("first WiFi reconnect should finish") { - env.manager.wifiTransport == nil && env.manager.wifiReconnectTask == nil - } - - armWiFiSession(env.manager) - await env.manager.checkWiFiConnectionHealth() - - try await waitUntil("cooldown suppression should release the transport") { - env.manager.wifiTransport == nil && env.manager.currentTransportType == nil - } - #expect(env.manager.connectionState == .disconnected) + func `cooldown after a second socket loss also releases its own socket`() async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + env.manager.testWiFiReconnectCooldown = 10000 + env.manager.testWiFiMaxReconnectDuration = .seconds(-1) + _ = try await env.connect(.wifi) + await env.wifi.simulateRemoteLoss() + try await waitUntil("first recovery should give up") { env.manager.connectionState == .disconnected } + _ = try await env.connect(.wifi) + await env.wifi.simulateRemoteLoss() + try await waitUntil("cooldown should finish retirement") { + env.manager.connectionState == .disconnected && env.manager.connectionTeardownCount == 0 + } + #expect(env.manager.wifiTransport == nil) + #expect(await env.wifi.isConnected == false) + } catch { await env.close(); throw error } + await env.close() } } diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiHeartbeatTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiHeartbeatTests.swift index 14716cce78..8fa5799c33 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiHeartbeatTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiHeartbeatTests.swift @@ -2,6 +2,7 @@ import Foundation @testable import MC1Services @testable import MeshCore import MeshCoreTestSupport +import os import Testing @Suite("ConnectionManager WiFi heartbeat") @@ -13,12 +14,21 @@ struct ConnectionManagerWiFiHeartbeatTests { await harness.gate.armIsConnected() let powerOff = Task { try await harness.manager.powerOffCurrentLink() } try await waitUntil("power-off should park before submission") { await harness.gate.isConnectedIsWaiting } - harness.manager.testBluetoothConnectHandler = { _ in } - try await harness.manager.connectViaBluetooth(peripheralID: UUID()) + let deviceID = UUID() + let replacement = Task { try await harness.manager.connectViaBluetooth(peripheralID: deviceID) } + try await waitUntil("replacement should be admitted before old submission") { + harness.manager.desiredRequest?.target == .bluetooth(deviceID) + } + #expect(await harness.ble.connectCount == 0) await harness.gate.releaseIsConnected() await #expect(throws: PowerOffSuperseded.self) { try await powerOff.value } + guard case .operational = try await replacement.value else { + Issue.record("replacement should become operational") + return + } #expect(await harness.powerOffFrameCount() == 0) - #expect(harness.manager.session === harness.session) + #expect(harness.manager.session !== harness.session) + _ = try await harness.manager.session?.getTime() } } @@ -26,8 +36,6 @@ struct ConnectionManagerWiFiHeartbeatTests { func `a stale socket callback leaves the replacement session and power-off evidence alone`() async throws { try await Harness.make().run { harness in let oldSocket = WiFiTransport() - let currentSocket = WiFiTransport() - harness.manager.wifiTransport = currentSocket await harness.inner.holdNextSend() let powerOff = Task { try await harness.manager.powerOffCurrentLink() } try await waitUntil("power-off send should park") { await harness.inner.sendIsWaiting } @@ -86,6 +94,7 @@ struct ConnectionManagerWiFiHeartbeatTests { try await waitUntil("handler should resume released WiFi recovery") { harness.manager.connectionState == .disconnected && harness.manager.currentTransportType == nil + && harness.manager.connectionTeardownCount == 0 } #expect(await harness.powerOffFrameCount() == 0) #expect(harness.manager.connectionTeardownCount == 0) @@ -95,7 +104,8 @@ struct ConnectionManagerWiFiHeartbeatTests { @Test func `socket loss before power-off submission resumes recovery`() async throws { try await Harness.make().run { harness in - harness.manager.testWiFiMaxReconnectDuration = .seconds(30) + harness.manager.testWiFiMaxReconnectDuration = .milliseconds(50) + await harness.gate.armFailingConnect() try await harness.parkHeartbeat() try await harness.fireProbe() await harness.gate.armIsConnected() @@ -106,26 +116,33 @@ struct ConnectionManagerWiFiHeartbeatTests { } await harness.inner.disconnect() - await harness.manager.handleWiFiDisconnection( - error: WiFiTransportError.notConnected, - remoteLossAt: CFAbsoluteTimeGetCurrent() - ) - #expect(harness.manager.connectionState == .connecting) + let loss = Task { + await harness.manager.handleWiFiDisconnection( + error: WiFiTransportError.notConnected, + remoteLossAt: CFAbsoluteTimeGetCurrent(), + source: harness.gate + ) + } + try await waitUntil("socket loss should start retirement") { + harness.manager.connectionState == .connecting && harness.manager.connectionTeardownCount > 0 + } #expect(harness.manager.wifiReconnectTask == nil) await harness.gate.releaseIsConnected() await #expect(throws: Error.self) { try await powerOff.value } + await loss.value try await waitUntil("released recovery should enter the real WiFi retry loop") { - harness.manager.wifiReconnectAttempt > 0 + await harness.gate.connectIsWaiting } #expect(harness.manager.connectionIntent.wantsConnection) #expect(harness.manager.connectionState == .connecting) #expect(harness.manager.wifiReconnectTask != nil) - harness.manager.testWiFiMaxReconnectDuration = .seconds(-1) + await harness.gate.releaseConnect() try await waitUntil("failed power-off should release deferred WiFi recovery") { harness.manager.connectionState == .disconnected && harness.manager.currentTransportType == nil + && harness.manager.connectionTeardownCount == 0 } #expect(await harness.powerOffFrameCount() == 0) } @@ -188,7 +205,7 @@ struct ConnectionManagerWiFiHeartbeatTests { func `successful power-off stops the heartbeat without reconnecting`() async throws { try await Harness.make().run { harness in try await harness.parkHeartbeat() - try await harness.manager.powerOffCurrentLink() + try await harness.elapsePowerOff() #expect(harness.manager.connectionIntent.isUserDisconnected) #expect(harness.manager.connectionState == .disconnected) @@ -202,14 +219,21 @@ struct ConnectionManagerWiFiHeartbeatTests { try await Harness.make().run { harness in try await harness.parkHeartbeat() await harness.inner.holdNextSend() - let powerOff = Task { try await harness.manager.powerOffCurrentLink() } + let powerOffFinished = OSAllocatedUnfairLock(initialState: false) + let powerOff = Task { + defer { powerOffFinished.withLock { $0 = true } } + return try await harness.manager.powerOffCurrentLink() + } try await waitUntil("power-off write should park") { await harness.inner.sendIsWaiting } - await harness.manager.handleWiFiDisconnection( - error: WiFiTransportError.notConnected, - remoteLossAt: CFAbsoluteTimeGetCurrent(), - isHeartbeat: false - ) + let loss = Task { + await harness.manager.handleWiFiDisconnection( + error: WiFiTransportError.notConnected, + remoteLossAt: CFAbsoluteTimeGetCurrent(), + isHeartbeat: false, + source: harness.gate + ) + } try await waitUntil("socket loss should stop the heartbeat") { harness.heartbeatClock.sleeperCount == 0 } @@ -217,7 +241,12 @@ struct ConnectionManagerWiFiHeartbeatTests { await harness.inner.failHeldSend() await harness.inner.releaseHeldSend() + try await waitUntil(timeout: .seconds(5), "failed power-off grace should elapse") { + advancePowerOffWindowIfParked(harness.requestClock) + return powerOffFinished.withLock { $0 } + } _ = try await powerOff.value + await loss.value #expect(harness.manager.connectionIntent.isUserDisconnected) #expect(harness.manager.wifiReconnectTask == nil) } @@ -325,15 +354,18 @@ extension ConnectionManagerWiFiHeartbeatTests { @MainActor private final class SocketLossTeardownGate { private var continuation: CheckedContinuation? + private var isOpen = false private(set) var isWaiting = false func wait() async { + guard !isOpen else { return } isWaiting = true await withCheckedContinuation { continuation = $0 } isWaiting = false } func release() { + isOpen = true let pending = continuation continuation = nil pending?.resume() @@ -344,6 +376,8 @@ extension ConnectionManagerWiFiHeartbeatTests { @MainActor private struct Harness { let manager: ConnectionManager + let ble: ConnectionTestRadioTransport + let suite: String let session: MeshCoreSession let inner: MockTransport let gate: ProbeTransport @@ -352,9 +386,18 @@ private struct Harness { let requestTimeout: Duration = .seconds(10) static func make() async throws -> Harness { - let (manager, _) = try ConnectionManager.createForTesting() + let suite = "test.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suite)) + let ble = ConnectionTestRadioTransport() let inner = MockTransport() let gate = ProbeTransport(inner: inner) + let pairing = MockAccessorySetupKitService() + pairing.isSessionActive = false + let manager = try ConnectionManager( + modelContainer: PersistenceStore.createContainer(inMemory: true), + defaults: defaults, stateMachine: MockBLEStateMachine(), transport: ble, + pairing: AccessorySetupPairingService(accessorySetupKit: pairing), makeWiFiTransport: { gate } + ) let requestClock = TestClock() let session = MeshCoreSession( transport: gate, @@ -372,6 +415,7 @@ private struct Harness { session: session, connectedDevice: device, currentTransportType: .wifi, + wifiTransport: gate, connectionIntent: .wantsConnection() ) try await start(session, transport: inner) @@ -379,6 +423,8 @@ private struct Harness { manager.startWiFiHeartbeat() return Harness( manager: manager, + ble: ble, + suite: suite, session: session, inner: inner, gate: gate, @@ -401,10 +447,27 @@ private struct Harness { try await waitUntil("heartbeat should park") { heartbeatClock.sleeperCount == 1 } } + /// Advances only the power-off silence window on `requestClock`. A probe timeout on that clock stays parked. + func elapsePowerOff() async throws { + let slot = OSAllocatedUnfairLock?>(initialState: nil) + let task = Task { @MainActor in + let outcome: Result + do { outcome = try await .success(manager.powerOffCurrentLink()) } catch { outcome = .failure(error) } + slot.withLock { $0 = outcome } + } + try await waitUntil(timeout: .seconds(5), "power-off silence should elapse") { + advancePowerOffWindowIfParked(requestClock) + return slot.withLock { $0 != nil } + } + task.cancel() + _ = try slot.withLock { try $0!.get() } + } + func fireProbe() async throws { let baseline = await getTimeCount() heartbeatClock.advance(by: ConnectionManager.wifiHeartbeatInterval) try await waitUntil("heartbeat should send getTime") { await getTimeCount() == baseline + 1 } + try await waitUntil("probe timeout should be registered") { requestClock.sleeperCount == 1 } } /// Completes the in-flight getTime so the loop is parked before the next interval. @@ -431,6 +494,8 @@ private struct Harness { func finish() async { await gate.releaseIsConnected() + await gate.releaseConnect() + await ble.releaseAllGates() await inner.releaseHeldSend() manager.resyncTask?.cancel() manager.channelRetryTask?.cancel() @@ -441,6 +506,7 @@ private struct Harness { requestClock.advance(by: .seconds(60)) await manager.disconnect() await session.stop() + UserDefaults().removePersistentDomain(forName: suite) let drained = await (try? waitUntil("heartbeat clocks should drain") { heartbeatClock.sleeperCount == 0 && requestClock.sleeperCount == 0 }) != nil @@ -491,11 +557,23 @@ private func parkedTask() -> Task { } } -private actor ProbeTransport: MeshTransport { +private actor ProbeTransport: WiFiMeshTransport { private let inner: MockTransport private var parkNextIsConnected = false private var continuation: CheckedContinuation? private(set) var isConnectedIsWaiting = false + private var shouldHoldConnect = false + private var heldConnect: CheckedContinuation? + private(set) var connectIsWaiting = false + private var failConnect = false + + var connectionInfo: (host: String, port: UInt16)? = ("radio.test", 5123) + + func setConnectionInfo(host: String, port: UInt16) { + connectionInfo = (host, port) + } + + func setDisconnectionHandler(_ handler: @escaping @Sendable (Error?, CFAbsoluteTime) -> Void) {} init(inner: MockTransport) { self.inner = inner @@ -514,9 +592,30 @@ private actor ProbeTransport: MeshTransport { } func connect() async throws { + if shouldHoldConnect { + shouldHoldConnect = false + await withCheckedContinuation { + heldConnect = $0 + connectIsWaiting = true + } + } + if failConnect { throw WiFiTransportError.notConnected } try await inner.connect() } + func armFailingConnect() { + shouldHoldConnect = true + failConnect = true + } + + func releaseConnect() { + shouldHoldConnect = false + connectIsWaiting = false + let held = heldConnect + heldConnect = nil + held?.resume() + } + func disconnect() async { await inner.disconnect() } diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiLossOwnershipTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiLossOwnershipTests.swift new file mode 100644 index 0000000000..3a765c911e --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiLossOwnershipTests.swift @@ -0,0 +1,238 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Synchronization +import Testing + +@Suite("ConnectionManager WiFi loss ownership") +@MainActor +struct ConnectionManagerWiFiLossOwnershipTests { + @Test + func `an old loss notification cannot suppress a replacement socket loss`() async throws { + try await Harness.withHarness { harness in + _ = try await harness.manager.connectViaWiFi(host: "first.local", port: 4242) + let first = try #require(harness.manager.currentConnection) + let notification = harness.gate() + let replacementNotification = harness.gate() + var firstNotificationStarted = false + var replacementNotificationStarted = false + var firstNotificationReturned = false + harness.manager.onAutoReconnectStarted = { receipt in + if receipt.requestID == first.requestID { + firstNotificationStarted = true + await notification.wait() + firstNotificationReturned = true + } else { + replacementNotificationStarted = true + await replacementNotification.wait() + } + } + await harness.first.simulateRemoteLoss() + try await waitUntil("old loss notification should remain held") { firstNotificationStarted } + _ = try await harness.manager.connectViaWiFi(host: "second.local", port: 4242) + let second = try #require(harness.manager.currentConnection) + #expect(second.device.radioID != first.device.radioID) + + await harness.second.simulateRemoteLoss() + try await waitUntil("replacement loss must be admitted while the old notification remains held") { + replacementNotificationStarted + } + notification.open() + try await waitUntil("old notification should return independently") { firstNotificationReturned } + #expect(harness.manager.isHandlingWiFiDisconnection) + replacementNotification.open() + try await waitUntil("replacement loss must remain able to recover") { + harness.manager.currentConnection?.generation != second.generation + && harness.manager.connectionState == .ready + } + + #expect(harness.manager.connectedDevice?.radioID == second.device.radioID) + #expect(await harness.third.connectCount == 1) + } + } + + @Test + func `a delayed loss callback cannot start recovery for a newer loss in the same request`() async throws { + try await Harness.withHarness { harness in + _ = try await harness.manager.connectViaWiFi(host: "first.local", port: 4242) + let requestID = harness.manager.connectionRequestID + let setup = harness.gate() + let olderNotification = harness.gate() + let newerNotification = harness.gate() + var setupStarted = false + var notificationCount = 0 + harness.manager.onConnectionReady = { _ in + if harness.factory.createdCount == 2 { + setupStarted = true + await setup.wait() + } + } + harness.manager.onAutoReconnectStarted = { _ in + notificationCount += 1 + switch notificationCount { + case 2: await olderNotification.wait() + case 3: await newerNotification.wait() + default: break + } + } + await harness.first.simulateRemoteLoss() + try await waitUntil("recovery should enter the second socket setup") { setupStarted } + await harness.second.disconnect() + let olderLoss = harness.handleLoss(source: harness.second) + try await waitUntil("second socket loss callback should remain held") { notificationCount == 2 } + setup.open() + try await waitUntil("existing retry worker should publish the third socket") { + harness.factory.createdCount == 3 && harness.manager.connectionState == .ready + && harness.manager.wifiReconnectTask == nil + } + #expect(harness.manager.connectionRequestID == requestID) + await harness.third.disconnect() + let newerLoss = harness.handleLoss(source: harness.third) + try await waitUntil("newer loss callback should own the same request") { notificationCount == 3 } + + olderNotification.open() + await olderLoss.value + + #expect(harness.manager.isHandlingWiFiDisconnection) + #expect(harness.manager.wifiReconnectTask == nil) + #expect(harness.factory.createdCount == 3) + newerNotification.open() + await newerLoss.value + try await waitUntil("only the newer loss should restart recovery") { + harness.manager.connectionState == .ready && harness.factory.createdCount == 4 + } + } + } + + @Test + func `a recovery retry waits for retirement of the socket lost during setup`() async throws { + try await Harness.withHarness { harness in + _ = try await harness.manager.connectViaWiFi(host: "first.local", port: 4242) + let setup = harness.gate() + var setupStarted = false + harness.manager.onConnectionReady = { snapshot in + if snapshot.device.publicKey == harness.second.publicKey { + setupStarted = true + await setup.wait() + } + } + await harness.second.holdDisconnect() + await harness.third.holdConnect() + await harness.first.simulateRemoteLoss() + try await waitUntil("first recovery should publish and enter its setup callback") { setupStarted } + #expect(harness.factory.createdCount == 2) + await harness.second.simulateRemoteLoss() + try await waitUntil("lost recovery socket should remain in physical close") { await harness.second.disconnectIsHeld } + setup.open() + try await waitUntil("existing recovery worker should advance to its next attempt") { + harness.manager.wifiReconnectAttempt == 2 + } + + #expect(harness.factory.createdCount == 2) + #expect(await harness.third.connectCount == 0) + #expect(harness.manager.currentConnection == nil) + await harness.second.releaseDisconnect() + try await waitUntil("settled retirement should release the next physical connect") { + await harness.third.connectIsHeld + } + await harness.third.releaseConnect() + try await waitUntil("the later retry should remain able to become ready") { + harness.manager.connectionState == .ready && harness.manager.currentConnection != nil + } + #expect(harness.manager.connectedDevice?.publicKey == harness.third.publicKey) + #expect(harness.manager.connectionTeardownCount == 0) + } + } + + @MainActor + private final class Harness { + let manager: ConnectionManager + let factory = SocketSequence() + private let suite: String + private var gates: [BLEReconnectionTestHarness.Gate] = [] + private var lossWorkers: [Task] = [] + var first: ConnectionTestRadioTransport { + factory.sockets[0] + } + + var second: ConnectionTestRadioTransport { + factory.sockets[1] + } + + var third: ConnectionTestRadioTransport { + factory.sockets[2] + } + + init() throws { + suite = "test.wifi-loss-ownership.\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suite)) + let container = try PersistenceStore.createContainer(inMemory: true) + let pairing = MockAccessorySetupKitService() + pairing.isSessionActive = false + let factory = factory + manager = ConnectionManager( + modelContainer: container, defaults: defaults, stateMachine: MockBLEStateMachine(), + transport: ConnectionTestRadioTransport(), + pairing: AccessorySetupPairingService(accessorySetupKit: pairing), + makeWiFiTransport: { factory.make() } + ) + manager.testWiFiReconnectCooldown = 0 + } + + func gate() -> BLEReconnectionTestHarness.Gate { + let gate = BLEReconnectionTestHarness.Gate() + gates.append(gate) + return gate + } + + func handleLoss(source: ConnectionTestRadioTransport) -> Task { + let worker = Task { + await manager.handleWiFiDisconnection(error: WiFiTransportError.notConnected, remoteLossAt: nil, source: source) + } + lossWorkers.append(worker) + return worker + } + + func close() async { + for gate in gates { + gate.open() + } + for socket in factory.sockets { + await socket.releaseAllGates() + } + _ = await manager.disconnect(reason: .userInitiated) + for worker in lossWorkers { + await worker.value + } + await manager.retirementTask?.value + await manager.metadataCommitTask?.value + UserDefaults().removePersistentDomain(forName: suite) + } + + static func withHarness(_ body: (Harness) async throws -> Void) async throws { + let harness = try Harness() + do { try await body(harness) } catch { await harness.close(); throw error } + await harness.close() + } + } + + private final class SocketSequence: Sendable { + nonisolated let sockets = [ + ConnectionTestRadioTransport(publicKey: Data(repeating: 0xA1, count: ProtocolLimits.publicKeySize)), + ConnectionTestRadioTransport(publicKey: Data(repeating: 0xB1, count: ProtocolLimits.publicKeySize)), + ConnectionTestRadioTransport(publicKey: Data(repeating: 0xB1, count: ProtocolLimits.publicKeySize)) + ] + private let count = Mutex(0) + nonisolated var createdCount: Int { + count.withLock { $0 } + } + + nonisolated func make() -> any WiFiMeshTransport { + count.withLock { count in + let socket = sockets[min(count, sockets.count - 1)] + count += 1 + return socket + } + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionNativeTCPPortTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionNativeTCPPortTests.swift new file mode 100644 index 0000000000..9ef2d71ec3 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionNativeTCPPortTests.swift @@ -0,0 +1,103 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("Native BLE to TCP ownership integration") +@MainActor +struct ConnectionNativeTCPPortTests { + @Test(.timeLimit(.minutes(1)), arguments: [false, true]) + func `TCP successor waits for native candidate retirement and survives late BLE loss`(sameRadio: Bool) async throws { + let run = try await NativeConnectionPortHarness() + let peer = try await ConnectionLoopbackRadioPeer.make(publicKey: Data(repeating: sameRadio ? 1 : 2, count: 32)) + let gate = Gate() + var firstSelection = true + run.manager.testConnectionSelectionHandler = { _ in + guard firstSelection else { return } + firstSelection = false + await gate.wait() + } + let first = Task { try await run.manager.connectViaBluetooth(peripheralID: run.native.deviceID) } + var replacement: Task? + do { + try await waitUntil("native candidate must reach metadata selection before publication") { gate.arrived } + let oldRequest = try #require(run.manager.desiredRequest) + let attempt = try #require(oldRequest.attempt) + let resource = try #require(attempt.resource) + let prepared = try #require(attempt.preparedServices) + let capturedOrigin = try #require(oldRequest.physicalOrigin) + let port = try #require(await peer.port) + #expect(run.manager.installedLink == nil) + replacement = Task { try await run.manager.connectViaWiFi(host: "127.0.0.1", port: port) } + try await waitUntil("TCP admission must revoke the old candidate immediately") { + run.manager.connectionRequestID != oldRequest.id + } + #expect(!attempt.binding.isActive) + #expect(run.manager.installedLink == nil) + #expect(await peer.acceptedCount == 0) + gate.open() + let oldResult = try await first.value + #expect(!run.manager.isCurrent(oldResult)) + let result = try await #require(replacement).value + #expect(run.manager.isCurrent(result)) + let current = try #require(run.manager.installedLink) + run.remember(current) + #expect(run.manager.connectionState == .ready) + #expect(current.target.transportType == .wifi) + #expect(current.resource !== resource) + #expect(current.resource.binding.isActive) + #expect(current.services !== prepared) + #expect(current.device.publicKey == Data(repeating: sameRadio ? 1 : 2, count: 32)) + #expect((current.device.id == run.native.deviceID) == sameRadio) + #expect((current.device.radioID == prepared.chatSendQueueService.radioID) == sameRadio) + #expect(current.device.radioID == current.services.chatSendQueueService.radioID) + #expect(!prepared.isAcceptingRuntimeWork) + #expect(await resource.session.subscriberCountForTest == 0) + #expect(await run.machine.currentAppSessionLiveDeviceID == nil) + #expect(await peer.acceptedCount == 1) + let closes = run.native.cancellationCount + #expect(closes == 1) + let requestID = run.manager.connectionRequestID + await run.manager.handleBLELifecycleEvent(.disconnected(capturedOrigin, error: .authenticationFailed)) + #expect(run.manager.connectionRequestID == requestID) + #expect(run.manager.installedLink === current) + #expect(current.resource.binding.isActive) + #expect(run.native.cancellationCount == closes) + #expect(try await current.resource.session.getBattery().level == 3700) + #expect(try await current.resource.session.getTime().timeIntervalSince1970 > 0) + #expect(await peer.acceptedCount == 1) + } catch { + gate.open() + first.cancel() + replacement?.cancel() + _ = await first.result + _ = await replacement?.result + await run.close() + await peer.close() + throw error + } + run.manager.testConnectionSelectionHandler = nil + await run.close() + await peer.close() + #expect(await peer.stopped) + } + + @MainActor + private final class Gate { + private var continuation: CheckedContinuation? + private var isOpen = false + private(set) var arrived = false + + func wait() async { + arrived = true + guard !isOpen else { return } + await withCheckedContinuation { continuation = $0 } + } + + func open() { + isOpen = true + continuation?.resume() + continuation = nil + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionRegistrationRekeyTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionRegistrationRekeyTests.swift new file mode 100644 index 0000000000..e8582f2402 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionRegistrationRekeyTests.swift @@ -0,0 +1,154 @@ +#if canImport(UIKit) + import AccessorySetupKit +#endif +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Authenticated registration rekey boundary") +@MainActor +struct ConnectionRegistrationRekeyTests { + @Test + func `superseded authenticated rekey reconnects through its durable saved Bluetooth target`() async throws { + let env = try ConnectionManagerRadioTestHarness(publicKey: Data(repeating: 0xD5, count: 32)) + let manager = env.manager + let oldID = UUID() + let newID = UUID() + let wifi = ConnectionMethod.wifi(host: "saved.radio", port: 5123, displayName: "Saved WiFi") + let lastConnected = Date(timeIntervalSince1970: 1_700_000_000) + let saved = DeviceDTO.testDevice(id: oldID, publicKey: env.ble.publicKey, lastConnected: lastConnected, isActive: false).copy { + $0.connectionMethods = [wifi, .bluetooth(peripheralUUID: oldID, displayName: "Field Bluetooth")] + } + var connecting: Task? + var superseding: Task? + do { + try await manager.persistenceStore.saveDevice(saved) + let pending = try await seedPendingSend(store: manager.persistenceStore, radioID: saved.radioID, radio: env.ble) + env.pairing.isSessionActive = true + env.pairing.setPairedAccessories([ASAccessory(bluetoothIdentifier: newID, displayName: "New pairing")]) + var capabilities = Data([ResponseCode.deviceInfo.rawValue, 14, 1, 1]) + capabilities.append(Data(repeating: 0, count: 76)) + capabilities.append(1) + await env.ble.setResponsePackets(for: .deviceQuery, packets: [capabilities]) + await env.ble.setResponsePackets(for: .getRepeatFreq, packets: [Data([ResponseCode.allowedRepeatFreq.rawValue])]) + await env.ble.holdReplies(for: .getRepeatFreq) + let attempt = Task { try await manager.connect(to: newID, forceFullSync: true, forceReconnect: true) } + connecting = attempt + try await waitUntil { + await env.ble.sentData.contains { $0.first == CommandCode.getRepeatFreq.rawValue } + } + #expect(try await manager.persistenceStore.fetchDevice(id: newID)?.radioID == saved.radioID) + #expect(manager.installedLink == nil) + let disconnecting = Task { await manager.disconnect(reason: .userInitiated) } + superseding = disconnecting + try await waitUntil { manager.desiredRequest?.target == .disconnected } + await env.ble.releaseReplies(for: .getRepeatFreq) + let outcome = try await attempt.value + if case .superseded = outcome {} else { Issue.record("Rekey attempt must lose publication to the admitted disconnect") } + _ = await disconnecting.value + await manager.metadataCommitTask?.value + + let registered = try #require(try await manager.persistenceStore.fetchDevice(id: newID)) + #expect(try await manager.persistenceStore.fetchDevice(id: oldID) == nil) + #expect(registered.radioID == saved.radioID) + #expect(registered.connectionMethods == [wifi, .bluetooth(peripheralUUID: newID, displayName: "Field Bluetooth")], + "Durable authenticated registration must rekey the existing Bluetooth method in place before selection") + #expect(registered.savedDeviceConnectTarget == .bluetooth(peripheralID: newID)) + #expect(registered.lastConnected == lastConnected) + #expect(!registered.isActive) + #expect(try await manager.persistenceStore.fetchPendingSends(radioID: registered.radioID).contains { $0.id == pending.id }) + #expect(await manager.wifiDeviceID(publicKey: registered.publicKey) == newID) + + let reconnected: ConnectionResult = switch registered.savedDeviceConnectTarget { + case let .bluetooth(peripheralID): + try await manager.connect(to: peripheralID, forceFullSync: true, forceReconnect: true) + case let .wifi(host, port): + try await manager.connectViaWiFi(host: host, port: port, forceFullSync: true) + } + let snapshot: ConnectionSnapshot + if case let .operational(current) = reconnected { snapshot = current } else { throw ConnectionError.notConnected } + #expect(snapshot.device.id == newID) + #expect(snapshot.device.radioID == saved.radioID) + _ = try await snapshot.services.session.getTime() + #expect(try await manager.persistenceStore.fetchPendingSends(radioID: snapshot.device.radioID).contains { $0.id == pending.id }) + #expect(snapshot.device.wifiConnectionMethod == wifi) + } catch { + await env.ble.releaseAllGates() + _ = await connecting?.result + _ = await superseding?.value + await env.close() + throw error + } + await env.close() + } + + @Test(arguments: [false, true]) + func `registration does not invent or infer Bluetooth methods from a WiFi observation`(existingBluetooth: Bool) async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + let oldID = UUID() + let newID = UUID() + let wifi = ConnectionMethod.wifi(host: "saved.radio", port: 5123, displayName: "WiFi") + let methods: [ConnectionMethod] = existingBluetooth + ? [.bluetooth(peripheralUUID: oldID, displayName: "Bluetooth"), wifi] : [wifi] + let saved = DeviceDTO.testDevice(id: oldID, isActive: false).copy { $0.connectionMethods = methods } + try await env.manager.persistenceStore.saveDevice(saved) + let observed = saved.copy { $0.id = newID } + let registered = try await env.manager.persistenceStore.registerConnectionDevice(observed, bluetoothPeripheralID: nil) + #expect(registered.connectionMethods == methods) + #expect(registered.radioID == saved.radioID) + #expect(!registered.isActive) + #expect(registered.lastConnected == saved.lastConnected) + let roundTrip = try JSONDecoder().decode(DeviceDTO.self, from: JSONEncoder().encode(registered)) + #expect(roundTrip.connectionMethods == methods) + #expect(roundTrip.radioID == saved.radioID) + } catch { await env.close(); throw error } + await env.close() + } + + @Test(arguments: [false, true]) + func `authenticated Bluetooth registration does not create a method before selection`(hasWiFi: Bool) async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + let oldID = UUID() + let newID = UUID() + let methods: [ConnectionMethod] = hasWiFi ? [.wifi(host: "saved.radio", port: 5123, displayName: "WiFi")] : [] + let saved = DeviceDTO.testDevice(id: oldID, isActive: false).copy { $0.connectionMethods = methods } + try await env.manager.persistenceStore.saveDevice(saved) + let observed = saved.copy { $0.id = newID } + let registered = try await env.manager.persistenceStore.registerConnectionDevice(observed, bluetoothPeripheralID: newID) + #expect(registered.connectionMethods == methods) + #expect(registered.radioID == saved.radioID) + #expect(!registered.isActive) + #expect(registered.lastConnected == saved.lastConnected) + } catch { await env.close(); throw error } + await env.close() + } + + private func seedPendingSend(store: PersistenceStore, radioID: UUID, radio: ConnectionTestRadioTransport) async throws -> PendingSendDTO { + let contact = ContactDTO.testContact(radioID: radioID) + try await store.saveContact(contact) + let message = MessageDTO(from: Message(radioID: radioID, contactID: contact.id, text: "Queued before re-pair", timestamp: 1_700_000_000)) + try await store.saveMessage(message) + let pending = PendingSendDTO( + id: UUID(), radioID: radioID, messageID: message.id, kind: .dm, contactID: contact.id, + channelIndex: nil, isResend: false, messageText: message.text, messageTimestamp: message.timestamp, + localNodeName: "Field radio", sequence: 1, enqueuedAt: Date() + ) + try await store.upsertPendingSend(pending) + var packet = Data([ResponseCode.contact.rawValue]) + packet.append(contact.publicKey) + packet.append(contentsOf: [ContactType.chat.rawValue, 0, 0xFF]) + packet.append(Data(repeating: 0, count: 64)) + let name = Data(contact.name.utf8.prefix(31)) + packet.append(name) + packet.append(Data(repeating: 0, count: 32 - name.count)) + packet.append(Data(repeating: 0, count: 16)) + await radio.setResponsePackets(for: .getContacts, packets: [ + Data([ResponseCode.contactStart.rawValue, 1, 0, 0, 0]), packet, + Data([ResponseCode.contactEnd.rawValue, 1, 0, 0, 0]) + ]) + return pending + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalConfirmationTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalConfirmationTests.swift new file mode 100644 index 0000000000..0b1a1501c3 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalConfirmationTests.swift @@ -0,0 +1,245 @@ +#if canImport(UIKit) + import AccessorySetupKit +#endif +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Removal confirmation identity boundaries") +@MainActor +struct ConnectionRemovalConfirmationTests { + @Test + func `reset cleanup persists across declined system removal`() async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + _ = try await env.connect(.bluetooth) + let device = try #require(env.manager.connectedDevice) + let context = try #require(env.manager.captureCurrentRemoval()) + env.pairing.isSessionActive = true + env.pairing.setPairedAccessories([ASAccessory(bluetoothIdentifier: device.id, displayName: "Reset radio")]) + env.pairing.removeAccessoryError = DevicePairingError.cancelled + await #expect(throws: DevicePairingError.cancelled) { try await env.manager.factoryResetAndEraseRadio(context) } + let target = try #require(try await env.manager.persistenceStore.fetchPendingRadioErases().first) + #expect(target.radioID == device.radioID) + #expect(try await env.manager.persistenceStore.fetchDevice(id: device.id) != nil) + env.pairing.removeAccessoryError = nil + env.manager.retryRadioErase(target) + _ = try await env.manager.radioEraseTasks[device.radioID]?.value + #expect(try await env.manager.persistenceStore.fetchPendingRadioErases().isEmpty) + #expect(try await env.manager.persistenceStore.fetchDevice(id: device.id) == nil) + let disconnected = env.manager.currentConnection == nil + #expect(disconnected) + } catch { await env.close(); throw error } + await env.close() + } + + @Test(arguments: [false, true]) + func `confirmation uses identity acquired while system sheet is open`(declined: Bool) async throws { + let env = try ConnectionManagerRadioTestHarness() + let saved = DeviceDTO.testDevice(publicKey: env.wifi.publicKey, isActive: false).copy { + $0.connectionMethods = [.wifi(host: "radio.test", port: 5123, displayName: nil)] + } + let gate = Gate() + var connecting: Task? + var removing: Task? + do { + try await env.manager.persistenceStore.saveDevice(saved) + env.pairing.isSessionActive = true + env.pairing.setPairedAccessories([ASAccessory(bluetoothIdentifier: saved.id, displayName: "Radio")]) + env.pairing.beforeRemovalResult = { await gate.wait() } + if declined { env.pairing.removeAccessoryError = DevicePairingError.cancelled } + await env.wifi.holdReplies(for: .appStart) + let connect = Task { try await env.connect(.wifi) } + connecting = connect + try await waitUntil { await env.wifi.sentData.contains { $0.first == CommandCode.appStart.rawValue } } + let removal = Task { try await env.manager.deleteDevice(id: saved.id) } + removing = removal + try await waitUntil { gate.entered } + await env.wifi.releaseAllGates() + let result = try await connect.value + #expect(env.manager.isCurrent(result)) + #expect(try await env.manager.session?.getTime() != nil) + gate.release() + if declined { + await #expect(throws: DevicePairingError.self) { try await removal.value } + #expect(env.manager.isCurrent(result)) + #expect(try await env.manager.persistenceStore.fetchDevice(id: saved.id)?.isActive == true) + #expect(env.manager.connectionIntent.wantsConnection) + } else { + try await removal.value + let disconnected = env.manager.currentConnection == nil + #expect(disconnected) + #expect(try await env.manager.persistenceStore.fetchDevice(id: saved.id) == nil) + #expect(!env.manager.connectionIntent.wantsConnection) + } + } catch { + gate.release() + await env.wifi.releaseAllGates() + _ = await connecting?.result + _ = await removing?.result + await env.close() + throw error + } + await env.close() + } + + @Test(arguments: [false, true]) + func `confirmation resolves the fresh rekeyed row`(declined: Bool) async throws { + let env = try ConnectionManagerRadioTestHarness() + let saved = DeviceDTO.testDevice(publicKey: env.ble.publicKey, isActive: false).copy { + $0.connectionMethods = [.bluetooth(peripheralUUID: $0.id, displayName: nil), + .wifi(host: "radio.test", port: 5123, displayName: nil)] + } + let gate = Gate() + var connecting: Task? + var removing: Task? + do { + try await env.manager.persistenceStore.saveDevice(saved) + env.pairing.isSessionActive = true + env.pairing.setPairedAccessories([ + ASAccessory(bluetoothIdentifier: saved.id, displayName: "Previous association"), + ASAccessory(bluetoothIdentifier: env.deviceID, displayName: "Current association") + ]) + env.pairing.beforeRemovalResult = { await gate.wait() } + if declined { env.pairing.removeAccessoryError = DevicePairingError.cancelled } + await env.ble.holdReplies(for: .getAutoAddConfig) + let connect = Task { try await env.connect(.bluetooth) } + connecting = connect + try await waitUntil { await env.ble.sentData.contains { $0.first == CommandCode.getAutoAddConfig.rawValue } } + let removal = Task { try await env.manager.deleteDevice(id: saved.id) } + removing = removal + try await waitUntil { gate.entered } + await env.ble.releaseAllGates() + let result = try await connect.value + #expect(env.manager.isCurrent(result)) + let rekeyed = try #require(try await env.manager.persistenceStore.fetchDevice(id: env.deviceID)) + #expect(rekeyed.radioID == saved.radioID) + #expect(try await env.manager.persistenceStore.fetchDevice(id: saved.id) == nil) + gate.release() + if declined { + await #expect(throws: DevicePairingError.self) { try await removal.value } + #expect(env.manager.isCurrent(result)) + #expect(try await env.manager.persistenceStore.fetchDevice(id: env.deviceID)?.isActive == true) + let observedTime = try await #require(env.manager.session).getTime() + #expect(observedTime.timeIntervalSince1970 > 0) + } else { + try await removal.value + let disconnected = env.manager.currentConnection == nil + #expect(disconnected) + #expect(!env.manager.connectionIntent.wantsConnection) + let ghost = try #require(try await env.manager.persistenceStore.fetchDevice(publicKey: saved.publicKey)) + #expect(ghost.radioID == saved.radioID) + #expect(ghost.connectionMethods.isEmpty) + #expect(!ghost.isActive) + #expect(try await env.manager.isCurrent(env.connect(.bluetooth))) + let observedTime = try await #require(env.manager.session).getTime() + #expect(observedTime.timeIntervalSince1970 > 0) + } + } catch { + gate.release() + await env.ble.releaseAllGates() + _ = await connecting?.result + _ = await removing?.result + await env.close() + throw error + } + await env.close() + } + + @Test(arguments: [false, true]) + func `accepted old system removal preserves new request`(sameRadio: Bool) async throws { + let env = try ConnectionManagerRadioTestHarness(sameRadio: false) + let gate = Gate() + var removing: Task? + do { + _ = try await env.connect(.wifi) + let first = try #require(env.manager.currentConnection) + env.pairing.isSessionActive = true + env.pairing.setPairedAccessories([ + ASAccessory(bluetoothIdentifier: first.device.id, displayName: "First"), + ASAccessory(bluetoothIdentifier: env.deviceID, displayName: "Next") + ]) + env.pairing.beforeRemovalResult = { await gate.wait() } + let removal = Task { try await env.manager.deleteDevice(id: first.device.id) } + removing = removal + try await waitUntil { gate.entered } + let next = try await env.connect(sameRadio ? .wifi : .bluetooth) + let successor = try #require(env.manager.currentConnection) + #expect(successor.requestID != first.requestID) + gate.release() + try await removal.value + #expect(env.manager.isCurrent(next)) + #expect(try await env.manager.persistenceStore.fetchDevice(id: successor.device.id)?.radioID == successor.device.radioID) + let observedTime = try await successor.services.session.getTime() + #expect(observedTime.timeIntervalSince1970 > 0) + } catch { + gate.release() + _ = await removing?.result + await env.close() + throw error + } + await env.close() + } + + @Test(arguments: [TransportType.bluetooth, .wifi]) + func `native association removal during preparation preserves only surviving wi fi`(transport: TransportType) async throws { + let env = try ConnectionManagerRadioTestHarness() + let saved = DeviceDTO.testDevice(id: env.deviceID, publicKey: env.ble.publicKey, isActive: false).copy { + $0.connectionMethods = [ + .bluetooth(peripheralUUID: env.deviceID, displayName: nil), + .wifi(host: "radio.test", port: 5123, displayName: nil) + ] + } + let radio = transport == .bluetooth ? env.ble : env.wifi + var connecting: Task? + do { + try await env.manager.persistenceStore.saveDevice(saved) + env.pairing.isSessionActive = true + env.pairing.setPairedAccessories([ASAccessory(bluetoothIdentifier: env.deviceID, displayName: "Radio")]) + await radio.holdReplies(for: .getAutoAddConfig) + let connect = Task { try await env.connect(transport) } + connecting = connect + try await waitUntil { await radio.sentData.contains { $0.first == CommandCode.getAutoAddConfig.rawValue } } + env.pairing.simulateAccessoryRemoved(env.deviceID) + await env.manager.metadataCommitTask?.value + await radio.releaseAllGates() + let result = await connect.result + if transport == .wifi { + #expect(try env.manager.isCurrent(result.get())) + #expect(try await env.manager.session?.getTime() != nil) + } else { + let disconnected = env.manager.currentConnection == nil + #expect(disconnected) + } + let kept = try #require(try await env.manager.persistenceStore.fetchDevice(id: saved.id)) + #expect(kept.radioID == saved.radioID) + let onlyWiFiRemains = kept.connectionMethods.allSatisfy(\.isWiFi) + #expect(onlyWiFiRemains) + } catch { + await radio.releaseAllGates() + _ = await connecting?.result + await env.close() + throw error + } + await env.close() + } + + @MainActor + private final class Gate { + private(set) var entered = false + private var released = false + private var continuation: CheckedContinuation? + func wait() async { + entered = true + guard !released else { return } + await withCheckedContinuation { continuation = $0 } + } + + func release() { + released = true + continuation?.resume() + continuation = nil + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalDrainTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalDrainTests.swift new file mode 100644 index 0000000000..8479158952 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalDrainTests.swift @@ -0,0 +1,453 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("Destructive removal drains admitted writers") +@MainActor +struct ConnectionRemovalDrainTests { + private static let sentinel = "admitted-forget-dm" + /// Long enough for an unfenced delete to finish, short enough to stay a gate observation. + private static let deletionObservation: Duration = .seconds(1) + + @Test + func `destructive forget waits for an admitted direct message`() async throws { + let fixture = try await Fixture.make() + var removal: Task? + do { + try await fixture.admitSentinel() + let context = try #require(fixture.env.manager.captureCurrentRemoval()) + var finished = false + removal = Task { + let result = try await fixture.env.manager.forgetDevice(context, deleteData: true) + finished = true + return result + } + try await waitUntil("forget must suspend new reads while the admitted save is held") { + await fixture.env.manager.session?.isMessageFetchingSuspended == true + } + #expect(try await !fixture.env.manager.persistenceStore.isRadioErasePending(fixture.radioID)) + #expect(try await fixture.env.manager.persistenceStore.fetchDevice(radioID: fixture.radioID) != nil) + #expect(!finished) + let messageID = try #require(fixture.gate.messageID) + fixture.gate.release() + let outcome = try await #require(removal).value + if case .removed = outcome {} else { Issue.record("Destructive forget of the live Link must publish removal") } + try await fixture.expectPartitionAbsent(messageID: messageID) + try await fixture.expectUnrelatedDataRemains() + await fixture.finish() + } catch { + await fixture.stop(removal) + throw error + } + } + + @Test + func `admitted successor cannot pass the reserved destructive removal`() async throws { + let fixture = try await Fixture.make(sameRadio: false) + let retirement = Gate() + fixture.armRetirement(retirement) + var removal: Task? + var successor: Task? + do { + try await fixture.admitSentinel() + fixture.gate.release() + let context = try #require(fixture.env.manager.captureCurrentRemoval()) + let removedRadioID = fixture.radioID + removal = Task { try await fixture.env.manager.forgetDevice(context, deleteData: true) } + try await waitUntil("forget must capture retirement before the successor is admitted") { + retirement.entered + } + #expect(try await fixture.env.manager.persistenceStore.isRadioErasePending(removedRadioID)) + let dialsBefore = await fixture.env.wifi.connectCount + successor = Task { try await fixture.env.connect(.wifi) } + try await waitUntil("successor must be admitted behind the reserved removal") { + fixture.env.manager.connectionIntent.wantsConnection && fixture.env.manager.currentConnection == nil + } + try await fixture.observeDeletionStillPending() + #expect(await fixture.env.wifi.connectCount == dialsBefore) + #expect(fixture.env.manager.currentConnection == nil) + let messageID = try #require(fixture.gate.messageID) + retirement.release() + _ = try await removal?.value + let connected = try await #require(successor).value + #expect(fixture.env.manager.isCurrent(connected)) + #expect(try await fixture.env.manager.session?.getTime() != nil) + #expect(try await fixture.env.manager.persistenceStore.fetchDevice(radioID: removedRadioID) == nil) + #expect(try await fixture.env.manager.persistenceStore.fetchMessage(id: messageID) == nil) + let contacts = try await fixture.env.manager.persistenceStore.fetchContacts(radioID: removedRadioID) + #expect(contacts.isEmpty) + try await fixture.expectUnrelatedDataRemains() + await fixture.finish() + } catch { + retirement.release() + await fixture.stop(removal, successor) + throw error + } + } + + @Test + func `accepted confirmation after supersession still drains the captured retirement`() async throws { + let fixture = try await Fixture.make(sameRadio: false) + let confirmation = Gate() + let retirement = Gate() + fixture.armRetirement(retirement) + var removal: Task? + var successor: Task? + do { + try await fixture.admitSentinel() + fixture.gate.release() + let device = try #require(fixture.env.manager.connectedDevice) + fixture.armConfirmation(confirmation, accessoryID: device.id) + let context = try #require(fixture.env.manager.captureCurrentRemoval()) + removal = Task { try await fixture.env.manager.forgetDevice(context, deleteData: true) } + try await waitUntil("system confirmation must be waiting") { confirmation.entered } + let previousRequest = fixture.env.manager.connectionRequestID + successor = Task { try await fixture.env.connect(.wifi) } + try await waitUntil("successor must park on retirement") { + let dials = await fixture.env.wifi.connectCount + return fixture.env.manager.connectionRequestID != previousRequest && retirement.entered + && dials == 0 + } + let successorRequest = fixture.env.manager.connectionRequestID + let lossesBefore = fixture.losses.count + confirmation.release() + try await waitUntil("accepted confirmation must reserve removal without retiring the successor") { + fixture.env.pairing.accessory(for: device.id) == nil && fixture.env.manager.connectionRequestID == successorRequest + } + try await fixture.observeDeletionStillPending() + #expect(fixture.env.manager.connectionRequestID == successorRequest) + #expect(fixture.env.manager.connectionIntent.wantsConnection) + #expect(fixture.losses.count == lossesBefore) + #expect(await fixture.env.wifi.connectCount == 0) + let messageID = try #require(fixture.gate.messageID) + retirement.release() + let outcome = try await #require(removal).value + if case .superseded = outcome {} else { Issue.record("A detached confirmation must not publish removal into the successor") } + let connected = try await #require(successor).value + #expect(fixture.env.manager.isCurrent(connected)) + #expect(fixture.losses.count == lossesBefore) + #expect(try await fixture.env.manager.session?.getTime() != nil) + try await fixture.expectPartitionAbsent(messageID: messageID) + await fixture.finish() + } catch { + confirmation.release() + retirement.release() + await fixture.stop(removal, successor) + throw error + } + } + + @Test + func `new pairing during a held destructive removal keeps the fresh association`() async throws { + let fixture = try await Fixture.make(sameRadio: false) + let confirmation = Gate() + let retirement = Gate() + fixture.armRetirement(retirement) + var removal: Task? + var successor: Task? + do { + try await fixture.admitSentinel() + fixture.gate.release() + let device = try #require(fixture.env.manager.connectedDevice) + fixture.armConfirmation(confirmation, accessoryID: device.id) + let context = try #require(fixture.env.manager.captureCurrentRemoval()) + removal = Task { try await fixture.env.manager.forgetDevice(context, deleteData: true) } + try await waitUntil("system confirmation must be waiting") { confirmation.entered } + successor = Task { try await fixture.env.connect(.wifi) } + try await waitUntil("successor must supersede the removal source") { + fixture.env.manager.connectionRequestID != context.requestID && retirement.entered + } + confirmation.release() + try await waitUntil("accepted confirmation must queue removal while retirement is held") { + fixture.env.pairing.accessory(for: device.id) == nil && fixture.gate.messageID != nil + } + try await fixture.observeDeletionStillPending() + fixture.env.pairing.setPairedAccessories([ + ASAccessory(bluetoothIdentifier: device.id, displayName: "Renewed association") + ]) + #expect(fixture.env.manager.pairing.isDeviceConnectable(device.id)) + retirement.release() + _ = try await removal?.value + _ = try await successor?.value + let preserved = try #require(try await fixture.env.manager.persistenceStore.fetchDevice(id: device.id)) + #expect(preserved.radioID == device.radioID) + #expect(try await !fixture.env.manager.persistenceStore.isRadioErasePending(device.radioID)) + #expect(try await fixture.env.manager.session?.getTime() != nil) + await fixture.finish() + } catch { + confirmation.release() + retirement.release() + await fixture.stop(removal, successor) + throw error + } + } + + @Test + func `drained retirement still deletes and a missing source stays absent`() async throws { + let fixture = try await Fixture.make(connect: false) + do { + let saved = DeviceDTO.testDevice(publicKey: Data(repeating: 0x51, count: 32), isActive: false) + try await fixture.env.manager.persistenceStore.saveDevice(saved) + #expect(fixture.env.manager.installedLink == nil) + #expect(fixture.env.manager.retirementTask == nil) + let context = try await fixture.env.manager.captureRemoval(id: saved.id) + let removed = try await fixture.env.manager.forgetDevice(context, deleteData: true) + if case .superseded = removed {} else { Issue.record("Removal without a Link has no loss to publish") } + #expect(try await fixture.env.manager.persistenceStore.fetchDevice(id: saved.id) == nil) + + let missing = DeviceDTO.testDevice(publicKey: Data(repeating: 0x52, count: 32), isActive: false) + try await fixture.env.manager.persistenceStore.saveDevice(missing) + let stale = try await fixture.env.manager.captureRemoval(id: missing.id) + try await fixture.env.manager.persistenceStore.deleteDevice(id: missing.id) + _ = try await fixture.env.manager.forgetDevice(stale, deleteData: true) + #expect(try await fixture.env.manager.persistenceStore.fetchDevice(id: missing.id) == nil) + #expect(try await fixture.env.manager.persistenceStore.fetchDevice(radioID: missing.radioID) == nil) + await fixture.finish() + } catch { + await fixture.finish() + throw error + } + } + + @Test + func `ghost demotion does not wait for the admitted writer`() async throws { + let fixture = try await Fixture.make() + var removal: Task? + do { + try await fixture.admitSentinel() + let device = try #require(fixture.env.manager.connectedDevice) + let context = try #require(fixture.env.manager.captureCurrentRemoval()) + var finished = false + removal = Task { + let result = try await fixture.env.manager.forgetDevice(context, deleteData: false) + finished = true + return result + } + try await waitUntil("ghost demotion must finish while the admitted save is still held") { + await (try? fixture.env.manager.persistenceStore.fetchDevice(id: device.id)) == nil + } + #expect(!finished) + let ghost = try #require(try await fixture.env.manager.persistenceStore.fetchDevice(radioID: device.radioID)) + #expect(ghost.id != device.id) + #expect(!ghost.isActive) + #expect(ghost.connectionMethods.isEmpty) + fixture.gate.release() + _ = await removal?.result + await fixture.finish() + } catch { + await fixture.stop(removal) + throw error + } + } + + @MainActor + private final class Fixture { + let env: ConnectionManagerRadioTestHarness + let gate = SaveGate() + let radioID: UUID + let unrelatedDeviceID: UUID + let unrelatedContactID: UUID + let unrelatedMessageID: UUID + private(set) var losses: [ConnectionLossReceipt] = [] + private let coordinator: SyncCoordinator? + + private init( + env: ConnectionManagerRadioTestHarness, + radioID: UUID, + unrelatedDeviceID: UUID, + unrelatedContactID: UUID, + unrelatedMessageID: UUID, + coordinator: SyncCoordinator? + ) { + self.env = env + self.radioID = radioID + self.unrelatedDeviceID = unrelatedDeviceID + self.unrelatedContactID = unrelatedContactID + self.unrelatedMessageID = unrelatedMessageID + self.coordinator = coordinator + } + + static func make(sameRadio: Bool = true, connect: Bool = true) async throws -> Fixture { + let env = try ConnectionManagerRadioTestHarness(sameRadio: sameRadio) + let unrelatedDeviceID = UUID() + let unrelatedContactID = UUID() + let unrelatedMessageID = UUID() + let unrelatedRadioID = UUID() + do { + let store = env.manager.persistenceStore + try await store.saveDevice(DeviceDTO.testDevice(id: unrelatedDeviceID, radioID: unrelatedRadioID, publicKey: Data(repeating: 0x44, count: 32), isActive: false)) + try await store.saveContact(ContactDTO.testContact(id: unrelatedContactID, radioID: unrelatedRadioID, publicKey: Data(repeating: 0x45, count: 32))) + try await store.saveMessage(Self.storedMessage(id: unrelatedMessageID, radioID: unrelatedRadioID, contactID: unrelatedContactID)) + var radioID = UUID() + var coordinator: SyncCoordinator? + if connect { + _ = try await env.connect(.bluetooth) + let device = try #require(env.manager.connectedDevice) + radioID = device.radioID + let contact = ContactDTO.testContact( + radioID: radioID, publicKey: Data(repeating: 0xAB, count: 32), name: "Dispatch" + ) + try await store.saveContact(contact) + let sync = try #require(env.manager.services).syncCoordinator + coordinator = sync + await sync.setTestBeforeMessageSave { message in + await SaveGate.sharedHold(message) + } + } + let fixture = Fixture( + env: env, radioID: radioID, unrelatedDeviceID: unrelatedDeviceID, + unrelatedContactID: unrelatedContactID, unrelatedMessageID: unrelatedMessageID, coordinator: coordinator + ) + SaveGate.current = fixture.gate + fixture.env.manager.onConnectionLost = { receipt in + fixture.losses.append(receipt) + } + return fixture + } catch { + await env.close() + throw error + } + } + + func admitSentinel() async throws { + let contacts = try await env.manager.persistenceStore.fetchContacts(radioID: radioID) + let contact = try #require(contacts.first { $0.name == "Dispatch" }) + await env.ble.inject(Self.directPacket(prefix: contact.publicKey, text: ConnectionRemovalDrainTests.sentinel)) + try await waitUntil("the admitted direct message must reach the real save hook") { self.gate.messageID != nil } + } + + func observeDeletionStillPending() async throws { + let probe = Probe() + _ = env.manager.enqueueMetadata { _ in + probe.started = true + } + let deadline = ContinuousClock.now + ConnectionRemovalDrainTests.deletionObservation + while ContinuousClock.now < deadline, !probe.started { + try await Task.sleep(for: .milliseconds(20)) + } + #expect(!probe.started) + #expect(try await env.manager.persistenceStore.fetchDevice(radioID: radioID) != nil) + } + + func armConfirmation(_ confirmation: Gate, accessoryID: UUID) { + env.pairing.isSessionActive = true + env.pairing.setPairedAccessories([ASAccessory(bluetoothIdentifier: accessoryID, displayName: "Radio")]) + env.pairing.beforeRemovalResult = { await confirmation.wait() } + } + + func armRetirement(_ retirement: Gate) { + env.manager.testConnectionTeardownHandler = { await retirement.wait() } + } + + func expectPartitionAbsent(messageID: UUID) async throws { + #expect(try await env.manager.persistenceStore.fetchMessage(id: messageID) == nil) + #expect(try await env.manager.persistenceStore.fetchDevice(radioID: radioID) == nil) + let contacts = try await env.manager.persistenceStore.fetchContacts(radioID: radioID) + #expect(contacts.isEmpty) + } + + func expectUnrelatedDataRemains() async throws { + #expect(try await env.manager.persistenceStore.fetchDevice(id: unrelatedDeviceID) != nil) + #expect(try await env.manager.persistenceStore.fetchContact(id: unrelatedContactID) != nil) + #expect(try await env.manager.persistenceStore.fetchMessage(id: unrelatedMessageID) != nil) + } + + func stop(_ first: Task?, _ second: Task? = nil) async { + gate.release() + _ = await first?.result + _ = await second?.result + await finish() + } + + func finish() async { + gate.release() + env.manager.testConnectionTeardownHandler = nil + if let coordinator { + await coordinator.setTestBeforeMessageSave(nil) + } + SaveGate.current = nil + await env.close() + } + + private static func directPacket(prefix: Data, text: String) -> Data { + var packet = Data([ResponseCode.contactMessageReceived.rawValue]) + packet.append(prefix.prefix(6)) + packet.append(0) + packet.append(MeshCore.TextType.plainText.rawValue) + let timestamp = UInt32(Date().timeIntervalSince1970) + packet.append(withUnsafeBytes(of: timestamp.littleEndian) { Data($0) }) + packet.append(contentsOf: text.utf8) + return packet + } + + private static func storedMessage(id: UUID, radioID: UUID, contactID: UUID) -> MessageDTO { + let now = Date() + return MessageDTO( + id: id, radioID: radioID, contactID: contactID, channelIndex: nil, text: "unrelated", + timestamp: UInt32(now.timeIntervalSince1970), createdAt: now, direction: .incoming, status: .delivered, + textType: .plain, ackCode: nil, pathLength: 0, snr: nil, senderKeyPrefix: nil, senderNodeName: nil, + isRead: true, replyToID: nil, roundTripTime: nil, heardRepeats: 0, retryAttempt: 0, maxRetryAttempts: 0 + ) + } + } + + /// Parked across monitor cancellation so the admitted save cannot be skipped. + @MainActor + private final class SaveGate { + static var current: SaveGate? + private(set) var messageID: UUID? + private var isOpen = false + private var waiters: [CheckedContinuation] = [] + + static func sharedHold(_ message: MessageDTO) async { + await current?.hold(message) + } + + func hold(_ message: MessageDTO) async { + guard message.text == ConnectionRemovalDrainTests.sentinel else { return } + messageID = message.id + guard !isOpen else { return } + await withCheckedContinuation { continuation in + if isOpen { + continuation.resume() + } else { + waiters.append(continuation) + } + } + } + + func release() { + isOpen = true + let pending = waiters + waiters.removeAll() + for waiter in pending { + waiter.resume() + } + } + } + + @MainActor + private final class Probe { + var started = false + } + + @MainActor + private final class Gate { + private(set) var entered = false + private var released = false + private var continuation: CheckedContinuation? + + func wait() async { + entered = true + guard !released else { return } + await withCheckedContinuation { continuation = $0 } + } + + func release() { + released = true + continuation?.resume() + continuation = nil + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalRecoveryTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalRecoveryTests.swift new file mode 100644 index 0000000000..8138a827cb --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalRecoveryTests.swift @@ -0,0 +1,94 @@ +import Foundation +@testable import MC1Services +import MeshCore +import MeshCoreTestSupport +import os +import Testing + +@Suite("Removal authority through automatic recovery") +@MainActor +struct ConnectionRemovalRecoveryTests { + @Test(arguments: [false, true], [false, true]) + func `failed unidentified handshake preserves removal`( + internalDisconnect: Bool, unrelatedEndpoint: Bool + ) async throws { + let clock = TestClock() + let env = try ConnectionManagerRadioTestHarness(sessionClock: clock) + let removedKey = unrelatedEndpoint ? Data(repeating: 0xA8, count: 32) : env.wifi.publicKey + let saved = DeviceDTO.testDevice(publicKey: removedKey, isActive: false).copy { + $0.connectionMethods = [.wifi(host: "radio.test", port: 5123, displayName: nil)] + } + var connecting: Task? + do { + try await env.manager.persistenceStore.saveDevice(saved) + await env.wifi.holdReplies(for: .appStart) + let handshakeFinished = OSAllocatedUnfairLock(initialState: false) + let initial = Task { @MainActor in + defer { handshakeFinished.withLock { $0 = true } } + return try await env.connect(.wifi) + } + connecting = initial + try await waitUntil { + await env.wifi.sentData.contains { $0.first == CommandCode.appStart.rawValue } + } + #expect(env.manager.desiredRequest?.attempt?.identity.publicKey == nil) + try await env.manager.deleteDevice(id: saved.id) + let firstRequest = try #require(env.manager.desiredRequest) + #expect(!firstRequest.removedIdentities.isEmpty) + let deleted = try #require(await env.manager.persistenceStore.fetchDevice(publicKey: removedKey)) + #expect(deleted.connectionMethods.isEmpty) + + await env.wifi.simulateRemoteLoss() + try await advanceParkedMatchedSessionClock(clock, observation: { + await sessionClockObservation(radio: env.wifi, session: env.manager.session) + }) { + handshakeFinished.withLock { $0 } + } + env.manager.sessionClockForTesting = nil + let initialResult = await initial.result + if case .success(.operational) = initialResult { + Issue.record("The initial handshake must fail without acquiring identity") + } + await env.wifi.releaseAllGates() + #expect(env.manager.currentConnection == nil) + #expect(env.manager.connectionState == .disconnected) + #expect(env.manager.connectionIntent.wantsConnection) + #expect(env.manager.desiredRequest === firstRequest) + if internalDisconnect { + _ = await env.manager.disconnect(reason: .resyncFailed) + #expect(env.manager.connectionIntent.wantsConnection) + } + + await env.manager.checkWiFiConnectionHealth() + await env.manager.retirementTask?.value + await env.manager.metadataCommitTask?.value + let remaining = try #require(await env.manager.persistenceStore.fetchDevice(publicKey: removedKey)) + #expect(remaining.radioID == saved.radioID) + #expect(remaining.connectionMethods.isEmpty) + #expect(!remaining.isActive) + if unrelatedEndpoint { + #expect(env.manager.connectionState == .ready) + #expect(env.manager.connectedDevice?.publicKey == env.wifi.publicKey) + #expect(env.manager.connectedDevice?.radioID != saved.radioID) + #expect(env.manager.lastConnectedRadioID != saved.radioID) + } else { + #expect(env.manager.currentConnection == nil) + #expect(!env.manager.connectionIntent.wantsConnection) + #expect(env.manager.lastConnectedDeviceID == nil) + #expect(env.manager.lastConnectedRadioID == nil) + let explicit = try await env.connect(.wifi) + #expect(env.manager.isCurrent(explicit)) + #expect(env.manager.connectedDevice?.radioID == saved.radioID) + } + let session = try #require(env.manager.session) + let time = try await session.getTime() + #expect(time.timeIntervalSince1970 > 0) + } catch { + await env.wifi.releaseAllGates() + _ = await connecting?.result + await env.close() + throw error + } + await env.close() + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalTests.swift new file mode 100644 index 0000000000..2c08edad06 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalTests.swift @@ -0,0 +1,221 @@ +#if canImport(UIKit) + import AccessorySetupKit +#endif +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Acquired identity removal contracts") +@MainActor +struct ConnectionRemovalTests { + enum Boundary { + case unidentified, authenticated, registered, published + } + + enum ConnectionPath { + case initialWiFi, initialDual, recoveringWiFi, recoveringDual + + var recovering: Bool { + self == .recoveringWiFi || self == .recoveringDual + } + + var dualMethod: Bool { + self == .initialDual || self == .recoveringDual + } + } + + struct RemovalSample: Sendable { + var boundary: Boundary + var path: ConnectionPath + } + + /// Each removal boundary, plus one recovering start and one device that also has Bluetooth. + nonisolated static let removalSamples: [RemovalSample] = [ + RemovalSample(boundary: .unidentified, path: .initialWiFi), + RemovalSample(boundary: .authenticated, path: .initialWiFi), + RemovalSample(boundary: .registered, path: .initialWiFi), + RemovalSample(boundary: .published, path: .initialWiFi), + RemovalSample(boundary: .unidentified, path: .recoveringWiFi), + RemovalSample(boundary: .unidentified, path: .initialDual), + ] + + @Test(arguments: removalSamples) + func `removal cannot restore an in flight wi fi device`(_ sample: RemovalSample) async throws { + let boundary = sample.boundary + let path = sample.path + let dualMethod = path.dualMethod + let recovering = path.recovering + let env = try ConnectionManagerRadioTestHarness() + let saved = DeviceDTO.testDevice(publicKey: env.wifi.publicKey, isActive: false).copy { + $0.connectionMethods = [.wifi(host: "radio.test", port: 5123, displayName: nil)] + if dualMethod { $0.connectionMethods.append(.bluetooth(peripheralUUID: $0.id, displayName: nil)) } + } + let selection = Gate() + var connecting: Task? + var deleting: Task? + var removalFinished = false + do { + try await env.manager.persistenceStore.saveDevice(saved) + env.pairing.isSessionActive = true + env.pairing.setPairedAccessories([ASAccessory(bluetoothIdentifier: saved.id, displayName: "Saved")]) + let previousGeneration: UUID? + if recovering { + _ = try await env.connect(.wifi) + previousGeneration = env.manager.currentConnection?.generation + env.manager.testWiFiReconnectCooldown = 0 + } else { + previousGeneration = nil + } + let command: CommandCode = boundary == .unidentified ? .appStart : .getAutoAddConfig + if boundary == .registered { + env.manager.testConnectionSelectionHandler = { _ in await selection.wait() } + } else if boundary != .published { + await env.wifi.holdReplies(for: command) + } + let task = Task { + if recovering { + await env.wifi.simulateRemoteLoss() + try await waitUntil { + env.manager.desiredRequest?.target == .disconnected + || (env.manager.currentConnection?.generation != previousGeneration && env.manager.connectionState == .ready) + } + guard let current = env.manager.currentConnection else { return ConnectionResult.superseded } + return ConnectionResult.operational(current) + } + return try await env.connect(.wifi) + } + connecting = task + if boundary == .registered { + try await waitUntil { selection.entered } + } else if boundary == .published { + #expect(try await env.manager.isCurrent(task.value)) + } else { + let initialCount = recovering ? 1 : 0 + try await waitUntil { + await env.wifi.sentData.filter { $0.first == command.rawValue }.count > initialCount + } + } + let removal = Task { + try await env.manager.deleteDevice(id: saved.id) + removalFinished = true + } + deleting = removal + try await waitUntil { + removalFinished || env.manager.desiredRequest?.target == .disconnected + } + selection.release() + await env.wifi.releaseAllGates() + _ = await task.result + try await removal.value + await env.manager.metadataCommitTask?.value + let hasConnection = env.manager.currentConnection != nil + #expect(!hasConnection) + #expect(!env.manager.connectionIntent.wantsConnection) + #expect(try await env.manager.persistenceStore.fetchDevice(id: saved.id) == nil) + let ghost = try #require(try await env.manager.persistenceStore.fetchDevice(publicKey: saved.publicKey)) + #expect(ghost.radioID == saved.radioID) + #expect(ghost.connectionMethods.isEmpty) + #expect(!ghost.isActive) + env.manager.testConnectionSelectionHandler = nil + let fresh = try await env.connect(.wifi) + #expect(env.manager.isCurrent(fresh), "A fresh explicit request is new connection authority") + #expect(env.manager.connectedDevice?.radioID == saved.radioID) + #expect(try await env.manager.session?.getTime() != nil) + } catch { + selection.release() + await env.wifi.releaseAllGates() + _ = await connecting?.result + _ = await deleting?.result + await env.close() + throw error + } + await env.close() + } + + @Test + func `unidentified removal exclusion survives launch fallback`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let saved = DeviceDTO.testDevice(id: env.deviceID, publicKey: env.wifi.publicKey, isActive: false).copy { + $0.connectionMethods = [.bluetooth(peripheralUUID: $0.id, displayName: nil), + .wifi(host: "radio.test", port: 5123, displayName: nil)] + } + var launch: Task? + do { + try await env.manager.persistenceStore.saveDevice(saved) + await env.wifi.setConnectError(BLEError.connectionFailed("Unavailable endpoint")) + await env.wifi.holdConnect() + let worker = Task { await env.manager.reconnectLastUsedTransport(device: saved, lastDeviceID: saved.id) } + launch = worker + try await waitUntil { await env.wifi.connectIsHeld } + try await env.manager.deleteDevice(id: saved.id) + await env.wifi.releaseConnect() + await worker.value + await env.manager.retirementTask?.value + await env.manager.metadataCommitTask?.value + #expect(await env.ble.connectCount == 0) + let hasConnection = env.manager.currentConnection != nil + #expect(!hasConnection) + #expect(!env.manager.connectionIntent.wantsConnection) + let ghost = try #require(try await env.manager.persistenceStore.fetchDevice(publicKey: saved.publicKey)) + #expect(ghost.radioID == saved.radioID) + #expect(ghost.connectionMethods.isEmpty) + #expect(try await env.manager.isCurrent(env.connect(.bluetooth))) + let observedTime = try await #require(env.manager.session).getTime() + #expect(observedTime.timeIntervalSince1970 > 0) + } catch { + await env.wifi.releaseAllGates() + await launch?.value + await env.close() + throw error + } + await env.close() + } + + @Test + func `unidentified endpoint may belong to an unrelated radio`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let other = DeviceDTO.testDevice(publicKey: Data(repeating: 0xA8, count: 32), isActive: false).copy { + $0.connectionMethods = [.wifi(host: "radio.test", port: 5123, displayName: nil)] + } + var connecting: Task? + do { + try await env.manager.persistenceStore.saveDevice(other) + await env.wifi.holdReplies(for: .appStart) + let task = Task { try await env.connect(.wifi) } + connecting = task + try await waitUntil { await env.wifi.sentData.contains { $0.first == CommandCode.appStart.rawValue } } + try await env.manager.deleteDevice(id: other.id) + await env.wifi.releaseAllGates() + #expect(try await env.manager.isCurrent(task.value)) + #expect(env.manager.connectedDevice?.publicKey == env.wifi.publicKey) + #expect(env.manager.connectedDevice?.radioID != other.radioID) + #expect(try await env.manager.session?.getTime() != nil) + } catch { + await env.wifi.releaseAllGates() + _ = await connecting?.result + await env.close() + throw error + } + await env.close() + } + + @MainActor + private final class Gate { + private(set) var entered = false + private var continuation: CheckedContinuation? + private var released = false + + func wait() async { + entered = true + guard !released else { return } + await withCheckedContinuation { continuation = $0 } + } + + func release() { + released = true + continuation?.resume() + continuation = nil + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionRequestCancellationTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionRequestCancellationTests.swift new file mode 100644 index 0000000000..6ac5121609 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionRequestCancellationTests.swift @@ -0,0 +1,244 @@ +import Foundation +@testable import MC1Services +import os +import Testing + +@Suite("Connection request cancellation") +@MainActor +struct ConnectionRequestCancellationTests { + @Test + func `a caller cancelled before admission creates no request`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let gate = IdentityRecoveryFixture.Gate() + do { + _ = try await env.connect(.bluetooth) + let requestID = env.manager.connectionRequestID + let state = env.manager.connectionState + let intent = env.manager.connectionIntent + let generation = env.manager.currentConnection?.generation + let dials = await env.ble.connectCount + let teardowns = env.manager.connectionTeardownCount + let task = Task { () throws -> ConnectionResult in + await gate.wait() + return try await env.manager.connect(to: UUID(), forceReconnect: true) + } + task.cancel() + gate.open() + await #expect(throws: CancellationError.self) { try await task.value } + #expect(env.manager.connectionRequestID == requestID) + #expect(env.manager.connectionState == state) + #expect(env.manager.connectionIntent == intent) + #expect(env.manager.currentConnection?.generation == generation) + #expect(await env.ble.connectCount == dials) + #expect(env.manager.connectionTeardownCount == teardowns) + } catch { + gate.open() + await env.close() + throw error + } + await env.close() + } + + @Test + func `cancellation while metadata is held never starts the attempt`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let gate = IdentityRecoveryFixture.Gate() + let entered = OSAllocatedUnfairLock(initialState: false) + var connecting: Task? + do { + _ = try await env.connect(.bluetooth) + let held = env.manager.enqueueMetadata { _ in await gate.wait() } + try await waitUntil("metadata predecessor should be held") { gate.arrived } + let target = UUID() + connecting = Task { + try await env.manager.requestConnection( + targets: [.bluetooth(target)], origin: .explicit, forceFullSync: true, forceReconnect: true, + operation: { _ in + entered.withLock { $0 = true } + return .superseded + } + ) + } + try await waitUntil("replacement should be admitted behind the held metadata") { + env.manager.desiredRequest?.target.deviceID == target && env.manager.connectionTeardownCount == 0 + } + let dials = await env.ble.connectCount + let disconnects = await env.ble.disconnectCount + connecting?.cancel() + try await waitUntil("cancellation should reach the admitted worker") { + env.manager.desiredRequest?.worker?.isCancelled == true + } + #expect(entered.withLock { $0 } == false) + gate.open() + let outcome = try await connecting?.value + if case .cancelled = outcome {} else { Issue.record("Held metadata cancellation returned another outcome") } + #expect(entered.withLock { $0 } == false) + #expect(env.manager.connectionState == .disconnected) + #expect(env.manager.currentConnection == nil) + #expect(env.manager.desiredRequest?.attempt == nil) + #expect(env.manager.desiredRequest?.target.deviceID == target) + #expect(env.manager.connectionIntent == .wantsConnection(forceFullSync: true)) + #expect(await env.ble.connectCount == dials) + #expect(await env.ble.disconnectCount == disconnects) + #expect(env.manager.connectionTeardownCount == 0) + _ = try await held.value + } catch { + gate.open() + _ = await connecting?.result + await env.close() + throw error + } + await env.close() + } + + @Test + func `a cancelled request cannot publish into the choice that replaced it`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let gate = IdentityRecoveryFixture.Gate() + var first: Task? + var second: Task? + do { + _ = try await env.connect(.bluetooth) + var losses: [UUID] = [] + env.manager.onConnectionLost = { losses.append($0.requestID) } + env.manager.testConnectionTeardownHandler = { await gate.wait() } + let targetA = UUID() + first = Task { try await env.manager.connect(to: targetA, forceFullSync: true, forceReconnect: true) } + try await waitUntil("first replacement should park in retirement") { + gate.arrived && env.manager.desiredRequest?.target.deviceID == targetA + } + let dials = await env.ble.connectCount + first?.cancel() + try await waitUntil("first worker should be cancelled while it is still current") { + env.manager.desiredRequest?.worker?.isCancelled == true + && env.manager.desiredRequest?.target.deviceID == targetA + } + let targetB = UUID() + second = Task { try await env.manager.connect(to: targetB, forceFullSync: false, forceReconnect: true) } + try await waitUntil("successor should own the request") { + env.manager.desiredRequest?.target.deviceID == targetB + } + let successorRequest = try #require(env.manager.connectionRequestID) + let successorIntent = env.manager.connectionIntent + let lossesAtSuccessor = losses + gate.open() + env.manager.testConnectionTeardownHandler = nil + _ = try await first?.value + #expect(env.manager.connectionRequestID == successorRequest) + #expect(env.manager.connectionIntent == successorIntent) + #expect(env.manager.desiredRequest?.target.deviceID == targetB) + #expect(losses == lossesAtSuccessor) + #expect(!losses.contains(successorRequest)) + let outcome = try await second?.value + if case .operational = outcome {} else { Issue.record("Successor did not become operational") } + #expect(env.manager.connectedDevice?.id == targetB) + #expect(env.manager.currentConnection?.generation != nil) + #expect(await env.ble.connectCount == dials + 1) + #expect(try await env.manager.session?.getTime() != nil) + } catch { + gate.open() + env.manager.testConnectionTeardownHandler = nil + _ = await first?.result + _ = await second?.result + await env.close() + throw error + } + await env.close() + } + + @Test + func `cancelling the current successor leaves the superseded worker silent`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let gate = IdentityRecoveryFixture.Gate() + var first: Task? + var second: Task? + do { + _ = try await env.connect(.bluetooth) + var losses: [UUID] = [] + env.manager.onConnectionLost = { losses.append($0.requestID) } + env.manager.testConnectionTeardownHandler = { await gate.wait() } + let targetA = UUID() + first = Task { try await env.manager.connect(to: targetA, forceFullSync: false, forceReconnect: true) } + try await waitUntil("first replacement should park in retirement") { + gate.arrived && env.manager.desiredRequest?.target.deviceID == targetA + } + let dials = await env.ble.connectCount + let targetB = UUID() + second = Task { try await env.manager.connect(to: targetB, forceFullSync: true, forceReconnect: true) } + try await waitUntil("successor should own the request before cancellation") { + env.manager.desiredRequest?.target.deviceID == targetB + } + let admitted = try #require(env.manager.connectionRequestID) + second?.cancel() + try await waitUntil("successor cancellation should reach its worker") { + env.manager.desiredRequest?.id == admitted && env.manager.desiredRequest?.worker?.isCancelled == true + } + gate.open() + env.manager.testConnectionTeardownHandler = nil + let firstOutcome = try await first?.value + let secondOutcome = try await second?.value + if case .superseded = firstOutcome {} else { Issue.record("Superseded worker returned another outcome") } + if case .cancelled = secondOutcome {} else { Issue.record("Cancelled successor returned another outcome") } + #expect(env.manager.connectionState == .disconnected) + #expect(env.manager.currentConnection == nil) + #expect(env.manager.desiredRequest?.attempt == nil) + #expect(env.manager.desiredRequest?.target.deviceID == targetB) + #expect(env.manager.connectionIntent == .wantsConnection(forceFullSync: true)) + #expect(env.manager.connectionTeardownCount == 0) + #expect(losses == [admitted]) + #expect(await env.ble.connectCount == dials) + } catch { + gate.open() + env.manager.testConnectionTeardownHandler = nil + _ = await first?.result + _ = await second?.result + await env.close() + throw error + } + await env.close() + } + + @Test + func `cancellation after link commitment leaves the link usable`() async throws { + let env = try ConnectionManagerRadioTestHarness() + let gate = IdentityRecoveryFixture.Gate() + var connecting: Task? + do { + var held = false + env.manager.testPostSetupResultHandler = { _ in + guard !held else { return } + held = true + await gate.wait() + } + connecting = Task { try await env.connect(.bluetooth) } + try await waitUntil("setup should reach the committed link") { gate.arrived } + let generation = try #require(env.manager.currentConnection?.generation) + let dials = await env.ble.connectCount + let disconnects = await env.ble.disconnectCount + connecting?.cancel() + try await Task.sleep(for: Self.cancelDeliveryWindow) + #expect(env.manager.desiredRequest?.committedGeneration == generation) + #expect(env.manager.desiredRequest?.worker?.isCancelled != true) + #expect(env.manager.currentConnection?.generation == generation) + gate.open() + env.manager.testPostSetupResultHandler = nil + let outcome = try await connecting?.value + if case .cancelled = outcome {} else { Issue.record("Caller cancellation changed the committed result surface") } + #expect(env.manager.currentConnection?.generation == generation) + #expect(env.manager.connectionState == .ready) + #expect(env.manager.connectionTeardownCount == 0) + #expect(await env.ble.connectCount == dials) + #expect(await env.ble.disconnectCount == disconnects) + #expect(try await env.manager.session?.getTime() != nil) + } catch { + gate.open() + env.manager.testPostSetupResultHandler = nil + _ = await connecting?.result + await env.close() + throw error + } + await env.close() + } + + private static let cancelDeliveryWindow: Duration = .milliseconds(50) +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionResourceRetirementTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionResourceRetirementTests.swift new file mode 100644 index 0000000000..0068a78c05 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionResourceRetirementTests.swift @@ -0,0 +1,101 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("Connection resource retirement") +@MainActor +struct ConnectionResourceRetirementTests { + @Test + func `retirement closes its captured socket before joining a blocked physical send`() async throws { + let socket = DisconnectReleasedSocket() + let binding = SessionTransportBinding() + let session = MeshCoreSession(transport: SessionBoundTransport(transport: socket, binding: binding)) + let resource = ConnectionResource(binding: binding, transport: socket, session: session, wifi: socket, ble: nil) + do { + try await session.start(disconnectTransportOnFailure: false) + await socket.holdNextSend() + let waiter = Task { try await session.getTime() } + try await waitUntil("physical send should remain active") { await socket.isSendHeld } + waiter.cancel() + await #expect(throws: CancellationError.self) { try await waiter.value } + #expect(await socket.isSendHeld) + #expect(await socket.disconnectCount == 0) + + let retirement = Task { await resource.retire(closePhysical: true) } + try await waitUntil("captured socket close should release the actual send") { + let closes = await socket.disconnectCount + let held = await socket.isSendHeld + return closes == 1 && !held + } + await retirement.value + #expect(!binding.isActive) + #expect(await session.subscriberCountForTest == 0) + + let successorBinding = SessionTransportBinding() + let successor = MeshCoreSession(transport: SessionBoundTransport(transport: socket, binding: successorBinding)) + try await successor.start(disconnectTransportOnFailure: false) + _ = try await successor.getTime() + successorBinding.revoke() + await successor.stop(disconnectTransport: false, drainExchanges: true) + await socket.disconnect() + await successorBinding.waitForQuiescence() + await successor.waitForQuiescence() + } catch { + binding.revoke() + await socket.disconnect() + await session.stop(disconnectTransport: false) + await binding.waitForQuiescence() + await session.waitForQuiescence() + throw error + } + } + + private actor DisconnectReleasedSocket: WiFiMeshTransport { + private let radio = ConnectionTestRadioTransport() + private var holdSend = false + private var heldSend: CheckedContinuation? + private(set) var disconnectCount = 0 + var isSendHeld: Bool { + heldSend != nil + } + + var connectionInfo: (host: String, port: UInt16)? { + ("radio.test", 5123) + } + + var isConnected: Bool { + get async { await radio.isConnected } + } + + var receivedData: AsyncStream { + get async { await radio.receivedData } + } + + func setConnectionInfo(host: String, port: UInt16) {} + func setDisconnectionHandler(_ handler: @escaping @Sendable (Error?, CFAbsoluteTime) -> Void) {} + func connect() async throws { + try await radio.connect() + } + + func holdNextSend() { + holdSend = true + } + + func send(_ data: Data) async throws { + try await radio.send(data) + if holdSend { + holdSend = false + await withCheckedContinuation { heldSend = $0 } + } + } + + func disconnect() async { + disconnectCount += 1 + let held = heldSend + heldSend = nil + held?.resume() + await radio.disconnect() + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionResyncFinalizationTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionResyncFinalizationTests.swift new file mode 100644 index 0000000000..1d35106b49 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionResyncFinalizationTests.swift @@ -0,0 +1,226 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import MeshCoreTestSupport +import Testing + +@Suite("Resync terminal finalization ownership") +@MainActor +struct ConnectionResyncFinalizationTests { + private static let initialEvents: [DeviceConnectionState] = [.connecting, .connecting, .connected, .syncing, .syncing] + private static let successorEvents: [DeviceConnectionState] = [.connecting, .connecting, .connected, .syncing, .ready] + + enum NextAction: CaseIterable { + case sameRadio + case differentRadio + case disconnect + } + + @Test(.timeLimit(.minutes(1)), arguments: [false, true], NextAction.allCases) + func `terminal resync result cannot cross a connection change during its activity callback`(succeeds: Bool, action: NextAction) async throws { + let clock = TestClock() + let env = try ConnectionManagerRadioTestHarness(sameRadio: action != .differentRadio, clock: clock) + let events = ValueTracker() + let stream = env.manager.connectionStateEvents.subscribe() + let observer = Task { for await state in stream { + events.record(state) + } } + let ended = Gate() + let expectedAttempts = succeeds ? 1 : ConnectionManager.maxResyncAttempts + let activity = Activity() + var failureGenerations: [UUID] = [] + var syncedGenerations: [UUID] = [] + var resync: Task? + var replacement: Task? + var terminal: Task? + env.manager.onDeviceSynced = { snapshot, _ in syncedGenerations.append(snapshot.generation) } + env.manager.onResyncFailed = { snapshot in failureGenerations.append(snapshot.generation) } + env.manager.onConnectionReady = { snapshot in + await snapshot.services.syncCoordinator.setPerformResyncOverride { _, _ in + await activity.attempted() + return succeeds ? FullSyncResult(contacts: .clean, channels: .clean, messages: .clean) : nil + } + await snapshot.services.syncCoordinator.setSyncActivityCallbacks( + onStarted: {}, + onEnded: { succeeded in + if await activity.didEnd(succeeded: succeeded, expectedAttempts: expectedAttempts, expectedSuccess: succeeds) { + await ended.wait() + } + }, + onPhaseChanged: { _ in } + ) + } + await env.ble.rejectNext(.getContacts) + do { + _ = try await env.connect(.bluetooth) + let old = try #require(env.manager.currentConnection) + #expect(env.manager.connectionState == .syncing) + try await waitUntilClockAdvances(clock, timeout: .seconds(10), "terminal resync should hold its activity-end callback") { ended.isWaiting } + let oldResync = try #require(env.manager.resyncTask) + resync = oldResync + switch action { + case .sameRadio, .differentRadio: + await env.wifi.holdReplies(for: .appStart) + replacement = Task { try await env.connect(.wifi) } + case .disconnect: + terminal = Task { await env.manager.disconnect(reason: .userInitiated) } + } + try await waitUntilClockAdvances(clock, "the new request must retire the old resync owner") { + env.manager.connectionRequestID != old.requestID + } + #expect(env.manager.currentConnection == nil) + #expect(await env.wifi.connectCount == 0) + #expect(failureGenerations.isEmpty) + ended.open() + await oldResync.value + #expect(activity.terminalEnds == 1) + #expect(failureGenerations.isEmpty) + switch action { + case .sameRadio, .differentRadio: + try await waitUntilClockAdvances(clock, "successor handshake must wait until old resync drains") { + await env.wifi.heldReplyCount(for: .appStart) == 1 + } + #expect(env.manager.currentConnection == nil) + #expect(syncedGenerations.isEmpty) + await env.wifi.releaseReplies(for: .appStart) + let result = try await #require(replacement).value + #expect(env.manager.isCurrent(result)) + let current = try #require(env.manager.currentConnection) + #expect(env.manager.connectionState == .ready) + #expect(current.generation != old.generation) + #expect((current.device.radioID == old.device.radioID) == (action == .sameRadio)) + #expect(syncedGenerations == [current.generation]) + #expect(env.manager.resyncAttemptCount == 0) + #expect(try await current.services.session.getTime().timeIntervalSince1970 > 0) + case .disconnect: + let receipt = try await #require(terminal).value + #expect(env.manager.isCurrent(receipt)) + #expect(env.manager.connectionState == .disconnected) + #expect(env.manager.connectionIntent.isUserDisconnected) + #expect(syncedGenerations.isEmpty) + } + #expect(await old.services.session.subscriberCountForTest == 0) + env.manager.connectionStateEvents.finish() + await observer.value + let expectedEvents = Self.initialEvents + (action == .disconnect ? [.disconnected] : Self.successorEvents) + #expect(events.values == expectedEvents) + } catch { + ended.open() + replacement?.cancel() + await env.ble.releaseAllGates() + await env.wifi.releaseAllGates() + await resync?.value + _ = await replacement?.result + _ = await terminal?.value + observer.cancel() + env.manager.connectionStateEvents.finish() + await observer.value + await env.close() + throw error + } + await env.close() + } + + @Test(.timeLimit(.minutes(1)), arguments: [false, true]) + func `cancelling terminal resync keeps its current stack`(succeeds: Bool) async throws { + let clock = TestClock() + let env = try ConnectionManagerRadioTestHarness(clock: clock) + let events = ValueTracker() + let stream = env.manager.connectionStateEvents.subscribe() + let observer = Task { for await state in stream { + events.record(state) + } } + let ended = Gate() + let expectedAttempts = succeeds ? 1 : ConnectionManager.maxResyncAttempts + let activity = Activity() + var synced = 0 + var failed = 0 + var resync: Task? + env.manager.onDeviceSynced = { _, _ in synced += 1 } + env.manager.onResyncFailed = { _ in failed += 1 } + env.manager.onConnectionReady = { snapshot in + await snapshot.services.syncCoordinator.setPerformResyncOverride { _, _ in + await activity.attempted() + return succeeds ? FullSyncResult(contacts: .clean, channels: .clean, messages: .clean) : nil + } + await snapshot.services.syncCoordinator.setSyncActivityCallbacks( + onStarted: {}, + onEnded: { succeeded in + if await activity.didEnd(succeeded: succeeded, expectedAttempts: expectedAttempts, expectedSuccess: succeeds) { + await ended.wait() + } + }, + onPhaseChanged: { _ in } + ) + } + await env.ble.rejectNext(.getContacts) + do { + _ = try await env.connect(.bluetooth) + let current = try #require(env.manager.currentConnection) + try await waitUntilClockAdvances(clock, timeout: .seconds(10), "terminal resync must reach its held activity callback") { ended.isWaiting } + let oldResync = try #require(env.manager.resyncTask) + resync = oldResync + env.manager.cancelResyncLoop() + ended.open() + await oldResync.value + #expect(activity.terminalEnds == 1) + #expect(synced == 0) + #expect(failed == 0) + #expect(env.manager.isCurrent(current)) + #expect(env.manager.connectionState == .syncing) + #expect(env.manager.connectionIntent.wantsConnection) + #expect(env.manager.resyncAttemptCount == 0) + #expect(current.services.isAcceptingRuntimeWork) + #expect(try await current.services.session.getTime().timeIntervalSince1970 > 0) + env.manager.connectionStateEvents.finish() + await observer.value + #expect(events.values == Self.initialEvents) + } catch { + ended.open() + env.manager.cancelResyncLoop() + await resync?.value + observer.cancel() + env.manager.connectionStateEvents.finish() + await observer.value + await env.close() + throw error + } + await env.close() + } + + @MainActor + private final class Activity { + private var attempts = 0 + private(set) var terminalEnds = 0 + + func attempted() { + attempts += 1 + } + + func didEnd(succeeded: Bool, expectedAttempts: Int, expectedSuccess: Bool) -> Bool { + guard attempts == expectedAttempts, succeeded == expectedSuccess else { return false } + terminalEnds += 1 + return true + } + } + + @MainActor + private final class Gate { + private var continuation: CheckedContinuation? + private var isOpen = false + var isWaiting: Bool { + continuation != nil + } + + func wait() async { + guard !isOpen else { return } + await withCheckedContinuation { continuation = $0 } + } + + func open() { + isOpen = true + continuation?.resume() + continuation = nil + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ContactShareUtilitiesTests.swift b/MC1Services/Tests/MC1ServicesTests/ContactShareUtilitiesTests.swift index 4252089696..86d7de29d3 100644 --- a/MC1Services/Tests/MC1ServicesTests/ContactShareUtilitiesTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ContactShareUtilitiesTests.swift @@ -10,7 +10,7 @@ struct ContactShareUtilitiesTests { // MARK: - Round-trip @Test( - arguments: [ContactType.chat, .repeater, .room] + arguments: [ContactType.chat, .repeater, .room, .sensor] ) func `formatShare then parseShare round-trips for every contact type`(type: ContactType) throws { let publicKey = try #require(Data(hexString: Self.validHex)) @@ -64,7 +64,7 @@ struct ContactShareUtilitiesTests { // MARK: - Adversarial type bounds (regression for the trap) @Test( - arguments: ["256", "300", "99999999999999999999", "0", "4"] + arguments: ["256", "300", "99999999999999999999", "0", "127"] ) func `parseShare rejects out-of-range and overflowing type values without trapping`(typeDigits: String) { let token = "<\(Self.validHex):\(typeDigits):x>" diff --git a/MC1Services/Tests/MC1ServicesTests/DeviceWriterTests.swift b/MC1Services/Tests/MC1ServicesTests/DeviceWriterTests.swift new file mode 100644 index 0000000000..8ec8028add --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/DeviceWriterTests.swift @@ -0,0 +1,120 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Device field writer contracts") +@MainActor +struct DeviceWriterTests { + @Test(arguments: [false, true]) + func `ocv edit cannot restore removed identity or undo canonicalization`(remove: Bool) async throws { + let env = try ConnectionManagerRadioTestHarness() + let current = DeviceDTO.testDevice(publicKey: env.ble.publicKey) + let canonical = DeviceDTO.testDevice(publicKey: Data(repeating: 0xB9, count: 32), isActive: false).copy { + $0.connectionMethods = [] + } + let gate = Gate() + let sink = CallbackSink() + let store = HeldOCVStore(store: env.manager.persistenceStore, gate: gate) + let service = DeviceService(dataStore: store) + var writing: Task? + do { + try await env.manager.persistenceStore.saveDevice(current) + try await env.manager.persistenceStore.saveDevice(canonical) + await service.setDeviceUpdateCallback { await sink.record($0) } + let write = Task { + try await service.updateOCVSettings(deviceID: current.id, preset: "custom", customArray: "4100,3900") + } + writing = write + try await waitUntil { gate.entered } + if remove { + try await env.manager.deleteDevice(id: current.id) + } else { + #expect(try await env.manager.persistenceStore.reconcileGhostIdentity( + currentDeviceID: current.id, newPublicKey: canonical.publicKey + ) == canonical.radioID) + } + gate.release() + let result = await write.result + if remove { + #expect(try await env.manager.persistenceStore.fetchDevice(id: current.id) == nil) + let ghost = try #require(try await env.manager.persistenceStore.fetchDevice(publicKey: current.publicKey)) + #expect(ghost.radioID == current.radioID) + #expect(ghost.connectionMethods.isEmpty) + #expect(await sink.value == nil, "A removed row cannot authorize a captured DTO callback") + } else { + try result.get() + let saved = try #require(try await env.manager.persistenceStore.fetchDevice(id: current.id)) + #expect(saved.radioID == canonical.radioID) + #expect(saved.publicKey == canonical.publicKey) + #expect(saved.ocvPreset == "custom") + #expect(saved.customOCVArrayString == "4100,3900") + #expect(await sink.value?.radioID == canonical.radioID) + #expect(await sink.value?.publicKey == canonical.publicKey) + } + } catch { + gate.release() + _ = await writing?.result + await env.close() + throw error + } + await env.close() + } + + @MainActor + private final class Gate { + private(set) var entered = false + private var continuation: CheckedContinuation? + private var released = false + + func wait() async { + entered = true + guard !released else { return } + await withCheckedContinuation { continuation = $0 } + } + + func release() { + released = true + continuation?.resume() + continuation = nil + } + } + + private actor CallbackSink { + private(set) var value: DeviceDTO? + func record(_ value: DeviceDTO) { + self.value = value + } + } + + private actor HeldOCVStore: DevicePersisting { + let store: PersistenceStore + let gate: Gate + + init(store: PersistenceStore, gate: Gate) { + self.store = store + self.gate = gate + } + + func fetchDevice(id: UUID) async throws -> DeviceDTO? { + try await store.fetchDevice(id: id) + } + + func fetchDevice(radioID: UUID) async throws -> DeviceDTO? { + try await store.fetchDevice(radioID: radioID) + } + + func updateDeviceLastContactSync(radioID: UUID, timestamp: UInt32) async throws { + try await store.updateDeviceLastContactSync(radioID: radioID, timestamp: timestamp) + } + + func saveDevice(_ dto: DeviceDTO) async throws { + await gate.wait() + try await store.saveDevice(dto) + } + + func updateDeviceOCVSettings(id: UUID, preset: String, customArray: String?) async throws -> DeviceDTO? { + await gate.wait() + return try await store.updateDeviceOCVSettings(id: id, preset: preset, customArray: customArray) + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ExplicitIdentityRecoveryTests.swift b/MC1Services/Tests/MC1ServicesTests/ExplicitIdentityRecoveryTests.swift new file mode 100644 index 0000000000..a2d7ce6d03 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ExplicitIdentityRecoveryTests.swift @@ -0,0 +1,112 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Explicit identity recovery") +@MainActor +struct ExplicitIdentityRecoveryTests { + @Test + func `repeated uncertainty and rejected retry preserve the earlier receipt until a deliberate success`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let original = try await IdentityRecoveryFixture.interrupt(harness) + await harness.bluetooth.holdReplies(for: .importPrivateKey) + let retrying = harness.track(Task { + try await harness.manager.retryIdentityImport(confirmation: original, privateKey: CanonicalIdentityFixture.privateKey) + }) + try await waitUntil("deliberate retry should write exactly one private key") { + await IdentityRecoveryFixture.keyWriteCount(harness) == 2 + } + await harness.bluetooth.setSendError(MeshTransportError.notConnected) + await harness.bluetooth.releaseReplies(for: .importPrivateKey) + _ = await retrying.result + await harness.bluetooth.setSendError(nil) + let repeated = try #require(harness.manager.prepareIdentityImportRecovery(receiptID: original.receiptID)) + #expect(repeated.originalRadioID == original.originalRadioID) + #expect(repeated.capturedConnectionMethod == original.capturedConnectionMethod) + await harness.bluetooth.rejectNext(.importPrivateKey) + await #expect(throws: (any Error).self) { + _ = try await harness.manager.retryIdentityImport(confirmation: repeated, privateKey: CanonicalIdentityFixture.privateKey) + } + let rejected = try #require(harness.manager.prepareIdentityImportRecovery(receiptID: original.receiptID)) + #expect(rejected.receiptID == original.receiptID) + #expect(try await harness.manager.persistenceStore.fetchDevice(id: harness.deviceA.id)?.radioID == harness.deviceA.radioID) + _ = try await harness.manager.retryIdentityImport(confirmation: rejected, privateKey: CanonicalIdentityFixture.privateKey) + #expect(harness.manager.connectedDevice?.radioID == harness.deviceB.radioID) + #expect(harness.manager.identityImportRecoveries.isEmpty) + let writes = await IdentityRecoveryFixture.keyWriteCount(harness) + #expect(writes == 4) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } + + @Test + func `unchanged original source consumes uncertainty without resending identity`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await harness.connectBluetooth() + _ = try await IdentityRecoveryFixture.interrupt(harness) + await harness.bluetooth.setPublicKey(harness.deviceA.publicKey, for: harness.deviceA.id) + _ = try await harness.manager.connect(to: harness.deviceA.id, forceReconnect: true) + #expect(harness.manager.connectedDevice?.radioID == harness.deviceA.radioID) + #expect(harness.manager.connectedDevice?.publicKey == harness.deviceA.publicKey) + #expect(harness.manager.identityImportRecoveries.isEmpty) + let writes = await IdentityRecoveryFixture.keyWriteCount(harness) + #expect(writes == 1) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } + + @Test + func `a stale confirmation and invalid input cannot submit or replace an unresolved receipt`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await harness.connectBluetooth() + let original = try await IdentityRecoveryFixture.interrupt(harness) + await #expect(throws: CancellationError.self) { + _ = try await harness.manager.retryIdentityImport(confirmation: original, privateKey: Data()) + } + await harness.wifi.setDeviceID(harness.deviceB.id) + await harness.wifi.setPublicKey(harness.deviceB.publicKey, for: harness.deviceB.id) + _ = try await harness.manager.connectViaWiFi(host: "other.local", port: 4242) + let successorID = harness.manager.connectionRequestID + let before = await harness.bluetooth.connectCount + await #expect(throws: CancellationError.self) { + _ = try await harness.manager.retryIdentityImport(confirmation: original, privateKey: CanonicalIdentityFixture.privateKey) + } + #expect(harness.manager.connectionRequestID == successorID) + #expect(harness.manager.connectedDevice?.radioID == harness.deviceB.radioID) + let after = await harness.bluetooth.connectCount + let writes = await IdentityRecoveryFixture.keyWriteCount(harness) + #expect(after == before) + #expect(writes == 1) + #expect(harness.manager.prepareIdentityImportRecovery(receiptID: original.receiptID) != nil) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } + + @Test + func `source uncertainty terminates a launch request before its otherwise usable fallback`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await harness.connectBluetooth() + _ = try await IdentityRecoveryFixture.interrupt(harness) + let before = await harness.wifi.connectCount + await #expect(throws: ConnectionRequestFailure.self) { + _ = try await harness.manager.requestConnection( + targets: [.bluetooth(harness.deviceA.id), .wifi(host: "fallback.local", port: 4242)], + origin: .launch, forceFullSync: false, forceReconnect: true + ) + } + let after = await harness.wifi.connectCount + #expect(after == before) + #expect(harness.manager.desiredRequest?.target == .disconnected) + #expect(!harness.manager.connectionIntent.wantsConnection) + await harness.manager.checkBLEConnectionHealth() + await harness.manager.checkWiFiConnectionHealth() + #expect(await harness.wifi.connectCount == after) + let recovery = try #require(harness.manager.identityImportRecoveries.first) + _ = try await harness.manager.retryIdentityImport(confirmation: recovery, privateKey: CanonicalIdentityFixture.privateKey) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/FloodScopeConnectionTests.swift b/MC1Services/Tests/MC1ServicesTests/FloodScopeConnectionTests.swift new file mode 100644 index 0000000000..288d9ceade --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/FloodScopeConnectionTests.swift @@ -0,0 +1,280 @@ +import Foundation +@testable import MC1Services +import MeshCore +import MeshCoreTestSupport +import os +import Testing + +@Suite("Flood scope connection baseline") +@MainActor +struct FloodScopeConnectionTests { + @Test(arguments: [TransportType.bluetooth, TransportType.wifi]) + func `services stay unavailable until the baseline reset is acknowledged`(type: TransportType) async throws { + let harness = try ConnectionManagerRadioTestHarness() + let radio = radio(type, harness) + do { + await radio.holdReplies(for: .setFloodScope) + let connect = Task { try await harness.connect(type) } + try await waitUntil("baseline reset should be held") { + await radio.heldReplyCount(for: .setFloodScope) == 1 + } + #expect(harness.manager.services == nil) + #expect(harness.manager.connectionState != .ready) + let heldFrames = await radio.sentData + #expect(heldFrames.contains { Self.contactCommand($0) } == false) + await radio.releaseReplies(for: .setFloodScope) + _ = try await connect.value + #expect(harness.manager.connectionState == .ready) + let scopeFrames = await radio.sentData.filter { $0.first == CommandCode.setFloodScope.rawValue } + #expect(scopeFrames == [PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey())]) + await harness.close() + } catch { + await harness.close() + throw error + } + } + + @Test + func `firmware before scope support omits the baseline reset`() async throws { + let harness = try ConnectionManagerRadioTestHarness(firmwareVersion: 7) + do { + _ = try await harness.connect(.bluetooth) + #expect(harness.manager.connectionState == .ready) + #expect(await harness.ble.sentData.contains { $0.first == CommandCode.setFloodScope.rawValue } == false) + await harness.close() + } catch { + await harness.close() + throw error + } + } + + @Test(arguments: [TransportType.bluetooth, TransportType.wifi]) + func `baseline reset rejection fails the candidate`(type: TransportType) async throws { + let harness = try ConnectionManagerRadioTestHarness() + let radio = radio(type, harness) + await radio.rejectNext(.setFloodScope, count: ConnectionManager.defaultConnectAttempts) + do { + _ = try await harness.connect(type) + Issue.record("Baseline reset rejection left the candidate connected") + } catch { + #expect(harness.manager.services == nil) + } + #expect(harness.manager.connectionState != .ready) + await harness.close() + } + + @Test + func `baseline reset timeout fails the candidate`() async throws { + let clock = TestClock() + let harness = try ConnectionManagerRadioTestHarness(sessionClock: clock) + await harness.ble.holdReplies(for: .setFloodScope) + do { + _ = try await harness.resultAdvancingClock { try await harness.connect(.bluetooth) } + Issue.record("Baseline reset timeout left the candidate connected") + } catch { + #expect(harness.manager.services == nil) + } + await harness.close() + } + + @Test + func `revoking the attempt drops a late baseline acknowledgement`() async throws { + let harness = try ConnectionManagerRadioTestHarness() + do { + await harness.ble.holdReplies(for: .setFloodScope) + let connect = Task { try await harness.connect(.bluetooth) } + try await waitUntil("baseline reset should be held") { + await harness.ble.heldReplyCount(for: .setFloodScope) == 1 + } + _ = await harness.manager.disconnect(reason: .userInitiated) + await harness.ble.releaseReplies(for: .setFloodScope) + _ = await connect.result + #expect(harness.manager.services == nil) + #expect(harness.manager.connectionState == .disconnected) + await harness.close() + } catch { + await harness.close() + throw error + } + } + + @Test + func `a stale recovery callback cannot reconnect after disconnect or replacement`() async throws { + let harness = try ConnectionManagerRadioTestHarness() + do { + _ = try await harness.connect(.bluetooth) + let original = try #require(harness.manager.installedLink) + _ = await harness.manager.disconnect(reason: .userInitiated) + await harness.manager.recoverFloodScope( + resource: original.resource, requestID: original.requestID + ) + #expect(harness.manager.connectionState == .disconnected) + #expect(await harness.ble.connectCount == 1) + + _ = try await harness.connect(.bluetooth) + let replaced = try #require(harness.manager.installedLink) + _ = try await harness.connect(.bluetooth) + let successor = try #require(harness.manager.installedLink) + #expect(successor.resource !== replaced.resource) + await harness.manager.recoverFloodScope( + resource: replaced.resource, requestID: replaced.requestID + ) + #expect(harness.manager.installedLink === successor) + #expect(await harness.ble.connectCount == 3) + await harness.close() + } catch { + await harness.close() + throw error + } + } + + @Test(arguments: [false, true]) + func `scope recovery replaces the link only when Power Off leaves the radio on`(radioStaysOn: Bool) async throws { + let harness = try ConnectionManagerRadioTestHarness() + do { + _ = try await harness.connect(.bluetooth) + let link = try #require(harness.manager.installedLink) + let session = link.resource.session + let recovery = OSAllocatedUnfairLock(initialState: (started: false, task: Task?.none)) + await session.setFloodScopeRecoveryHandler { [weak manager = harness.manager, weak link] in + let task = Task { @MainActor in + guard let manager, let link else { return } + recovery.withLock { $0.started = true } + await manager.recoverFloodScope( + resource: link.resource, requestID: link.requestID + ) + } + recovery.withLock { $0.task = task } + } + + await harness.ble.enqueueResponsePackets(for: .setFloodScope, packets: [Data([ResponseCode.ok.rawValue])]) + await harness.ble.enqueueResponsePackets(for: .setFloodScope, packets: [Data([ResponseCode.error.rawValue, 1])]) + await harness.ble.holdSubmissions(for: .sendChannelMessage) + let send = Task { + try await session.sendChannelMessage( + channel: 0, text: "accepted", timestamp: Date(), floodScope: .scope(.region("Selected")) + ) + } + try await waitUntil("the channel write should park after scope is applied") { + await harness.ble.submissionIsHeld(for: .sendChannelMessage) + } + await harness.ble.holdReplies(for: .setFloodScope) + await harness.ble.releaseSubmissions(for: .sendChannelMessage) + try await waitUntil("the cleanup rejection should be held") { + await harness.ble.heldReplyCount(for: .setFloodScope) == 1 + } + + if radioStaysOn { + await harness.ble.enqueueResponsePackets( + for: .runCliCommand, packets: [Data([ResponseCode.cliReply.rawValue]) + Data("still on".utf8)] + ) + } + await harness.ble.holdSubmissions(for: .runCliCommand) + let powerOff = Task { try await harness.manager.powerOffCurrentLink() } + try await waitUntil("Power Off should own reconnect") { harness.manager.powerOffBlocksReconnect } + await harness.ble.releaseReplies(for: .setFloodScope) + try await send.value + try await waitUntil("scope recovery should start while Power Off is held") { + guard recovery.withLock({ $0.started }) else { return false } + return await harness.ble.submissionIsHeld(for: .runCliCommand) + } + #expect(harness.manager.installedLink === link) + #expect(await harness.ble.connectCount == 1) + + let recoveryTask = try #require(recovery.withLock { $0.task }) + await harness.ble.releaseSubmissions(for: .runCliCommand) + if radioStaysOn { + let error = await #expect(throws: SettingsServiceError.self) { try await powerOff.value } + switch error { + case .powerOffUnsupported?: break + default: Issue.record("Expected an unsupported Power Off reply") + } + await recoveryTask.value + #expect(await harness.ble.connectCount == 2) + #expect(harness.manager.installedLink !== link) + let successor = try #require(harness.manager.session) + let baseline = PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey()) + #expect(await harness.ble.sentData.filter { $0 == baseline }.count == 3) + _ = try await successor.getTime() + } else { + let token = try await powerOff.value + await recoveryTask.value + #expect(harness.manager.powerOffOwnsCleanup(token)) + #expect(harness.manager.connectionState == .disconnected) + #expect(await harness.ble.connectCount == 1) + } + await harness.close() + } catch { + await harness.close() + throw error + } + } + + @Test(arguments: QueueRecoveryCase.allCases) + func `accepted channel queue sends survive cleanup failure`(recovery: QueueRecoveryCase) async throws { + let harness = try ConnectionManagerRadioTestHarness() + do { + _ = try await harness.connect(.bluetooth) + let radioID = try #require(harness.manager.connectedDevice?.radioID) + let secret = Data(repeating: 0x5A, count: 16) + let channel = ChannelDTO.testChannel( + radioID: radioID, index: 0, secret: secret, floodScope: .region("Selected") + ) + try await harness.manager.persistenceStore.saveChannel(channel) + await harness.ble.setChannel(index: channel.index, name: channel.name, secret: secret) + let services = try #require(harness.manager.services) + let message = try await services.messageService.createPendingChannelMessage( + text: "queued", channelIndex: channel.index, radioID: radioID + ) + if recovery == .failedReplacement { + await harness.ble.setConnectError(BLEError.deviceNotFound) + } + await harness.ble.enqueueResponsePackets(for: .setFloodScope, packets: [Data([ResponseCode.ok.rawValue])]) + await harness.ble.enqueueResponsePackets( + for: .setFloodScope, packets: [Data([ResponseCode.error.rawValue, 1])] + ) + try await services.chatSendQueueService.enqueueChannel(ChannelMessageEnvelope( + messageID: message.id, channelIndex: channel.index, isResend: recovery == .resend, + messageText: message.text, messageTimestamp: message.timestamp, localNodeName: nil + )) + try await waitUntil("the accepted send should commit and leave no pending row") { + let stored = try await harness.manager.persistenceStore.fetchMessage(id: message.id) + let pending = try await harness.manager.persistenceStore.fetchPendingSends(radioID: radioID) + return stored?.status == .sent && pending.isEmpty + } + try await waitUntil("recovery should settle the fenced session") { + if recovery == .failedReplacement { return harness.manager.connectionState == .disconnected } + return harness.manager.connectionState == .ready && harness.manager.services !== services + } + if recovery != .failedReplacement { + let successor = try #require(harness.manager.session) + _ = try await successor.getTime() + } + let channelSends = await harness.ble.sentData.filter { $0.first == CommandCode.sendChannelMessage.rawValue } + #expect(channelSends.count == 1) + #expect(channelSends.first?.dropFirst(2).first == channel.index) + await harness.close() + } catch { + await harness.close() + throw error + } + } + + enum QueueRecoveryCase: CaseIterable { + case initialSend + case resend + case failedReplacement + } + + private func radio(_ type: TransportType, _ harness: ConnectionManagerRadioTestHarness) -> ConnectionTestRadioTransport { + type == .bluetooth ? harness.ble : harness.wifi + } + + private static func contactCommand(_ frame: Data) -> Bool { + guard let code = frame.first else { return false } + return code == CommandCode.sendChannelMessage.rawValue + || code == CommandCode.sendMessage.rawValue + || code == CommandCode.sendLogin.rawValue + || code == CommandCode.getSelfTelemetry.rawValue + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/AppBackupEnvelope+Testing.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/AppBackupEnvelope+Testing.swift index 1d8197303e..961adaffd0 100644 --- a/MC1Services/Tests/MC1ServicesTests/Helpers/AppBackupEnvelope+Testing.swift +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/AppBackupEnvelope+Testing.swift @@ -6,6 +6,7 @@ extension AppBackupEnvelope { /// Every DTO array and userDefaults payload defaults to empty, so call sites /// only pass what the specific test needs. static func test( + version: Int = AppBackupEnvelope.currentVersion, exportDate: Date = Date(timeIntervalSince1970: 1_700_000_000), appVersion: String = "test", appBuild: String = "1", @@ -24,6 +25,7 @@ extension AppBackupEnvelope { userDefaults: BackupUserDefaults? = nil ) -> AppBackupEnvelope { var envelope = AppBackupEnvelope( + version: version, exportDate: exportDate, appVersion: appVersion, appBuild: appBuild, diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/BLEAdoptionOriginTransport.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/BLEAdoptionOriginTransport.swift new file mode 100644 index 0000000000..71c57185ce --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/BLEAdoptionOriginTransport.swift @@ -0,0 +1,106 @@ +import Foundation +@testable import MC1Services +import MeshCore + +actor BLEAdoptionOriginTransport: iOSMeshTransport { + let base: iOSBLETransport + private var holdFirstOrigin = true + private var originWaiter: CheckedContinuation? + private(set) var capturedOrigin: BLELifecycleOrigin? + + init(base: iOSBLETransport) { + self.base = base + } + + var originReadIsHeld: Bool { + originWaiter != nil + } + + func releaseOrigin() { + originWaiter?.resume(); originWaiter = nil + } + + var lifecycleOrigin: BLELifecycleOrigin? { + get async { + let origin = await base.lifecycleOrigin + if holdFirstOrigin { + holdFirstOrigin = false + capturedOrigin = origin + await withCheckedContinuation { originWaiter = $0 } + } + return origin + } + } + + var isConnected: Bool { + get async { await base.isConnected } + } + + var receivedData: AsyncStream { + get async { await base.receivedData } + } + + var supportsWriteWithoutResponse: Bool { + get async { await base.supportsWriteWithoutResponse } + } + + func makeSessionTransport(deviceID: UUID, binding: SessionTransportBinding) async -> SessionBoundTransport { + await base.makeSessionTransport(deviceID: deviceID, binding: binding) + } + + func connect() async throws { + try await base.connect() + } + + func connect(sessionBinding: SessionTransportBinding) async throws { + try await base.connect(sessionBinding: sessionBinding) + } + + func disconnect() async { + await base.disconnect() + } + + func disconnect(sessionBinding: SessionTransportBinding) async { + await base.disconnect(sessionBinding: sessionBinding) + } + + func cancelPendingEstablishment(sessionBinding: SessionTransportBinding) async { + await base.cancelPendingEstablishment(sessionBinding: sessionBinding) + } + + func cancelUnsubmittedWrites(sessionBinding: SessionTransportBinding) async { + await base.cancelUnsubmittedWrites(sessionBinding: sessionBinding) + } + + func send(_ data: Data) async throws { + try await base.send(data) + } + + func send(_ data: Data, sessionBinding: SessionTransportBinding) async throws { + try await base.send(data, sessionBinding: sessionBinding) + } + + func sendWithoutResponse(_ data: Data) async throws { + try await base.sendWithoutResponse(data) + } + + func sendWithoutResponse(_ data: Data, sessionBinding: SessionTransportBinding) async throws { + try await base.sendWithoutResponse(data, sessionBinding: sessionBinding) + } + + func receivedData(sessionBinding: SessionTransportBinding) async -> AsyncStream { + await base.receivedData(sessionBinding: sessionBinding) + } + + func refreshDataStream() async { + await base.refreshDataStream() + } + + func refreshDataStream(sessionBinding: SessionTransportBinding) async { + await base.refreshDataStream(sessionBinding: sessionBinding) + } + + func setLifecycleHandler(_ handler: @escaping @Sendable (BLELifecycleEvent) -> Void) async { + await base.setLifecycleHandler(handler) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/BLEAdoptionTestHarness.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/BLEAdoptionTestHarness.swift new file mode 100644 index 0000000000..d41691f7c6 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/BLEAdoptionTestHarness.swift @@ -0,0 +1,109 @@ +@preconcurrency import CoreBluetooth +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@MainActor +final class BLEAdoptionTestHarness { + let ble: BLESetupRetirementHarness + let transport: BLEAdoptionOriginTransport + let manager: ConnectionManager + let firmware: ConnectionTestRadioTransport + private let suite: String + private let writes: AsyncStream.Continuation + private let writeWorker: Task + private let replyWorker: Task + private(set) var handledEvents: [BLELifecycleEvent] = [] + + private init( + ble: BLESetupRetirementHarness, transport: BLEAdoptionOriginTransport, manager: ConnectionManager, + firmware: ConnectionTestRadioTransport, suite: String, writes: AsyncStream.Continuation, + writeWorker: Task, replyWorker: Task + ) { + self.ble = ble + self.transport = transport + self.manager = manager + self.firmware = firmware + self.suite = suite + self.writes = writes + self.writeWorker = writeWorker + self.replyWorker = replyWorker + manager.testBLELifecycleEventHandled = { [weak self] in self?.handledEvents.append($0) } + } + + static func make() async throws -> BLEAdoptionTestHarness { + let ble = await BLESetupRetirementHarness.make() + ble.native.peripheralState = .connected + ble.native.systemConnected = true + let transport = BLEAdoptionOriginTransport(base: ble.adapter) + let firmware = ConnectionTestRadioTransport() + try await firmware.connect() + let suite = "test.adoption.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suite)) + let pairing = MockAccessorySetupKitService() + pairing.isSessionActive = false + let manager = try ConnectionManager( + modelContainer: PersistenceStore.createContainer(inMemory: true), defaults: defaults, + stateMachine: ble.machine, transport: transport, pairing: AccessorySetupPairingService(accessorySetupKit: pairing) + ) + let saved = DeviceDTO.testDevice(id: ble.peripheral.identifier, publicKey: firmware.publicKey, isActive: false).copy { + $0.connectionMethods = [.bluetooth(peripheralUUID: ble.peripheral.identifier, displayName: nil)] + } + try await manager.persistenceStore.saveDevice(saved) + manager.persistConnection(deviceID: saved.id, radioID: saved.radioID, deviceName: saved.nodeName) + await manager.wireTransportHandlers() + let (physicalWrites, continuation) = AsyncStream.makeStream(of: Data.self) + ble.native.setWriteHandler { continuation.yield($0) } + let writeWorker = Task { + for await data in physicalWrites { + try? await firmware.send(data) + await ble.completeWrite() + } + } + let replies = await firmware.receivedData + let replyWorker = Task { + for await reply in replies { + await ble.inject(reply) + } + } + return BLEAdoptionTestHarness( + ble: ble, transport: transport, manager: manager, firmware: firmware, suite: suite, + writes: continuation, writeWorker: writeWorker, replyWorker: replyWorker + ) + } + + func completeAdoptionDiscovery() async { + await ble.machine.handleDidDiscoverServices(ble.peripheral, error: nil) + await ble.machine.handleDidDiscoverCharacteristics(ble.peripheral, service: ble.native.service, error: nil) + await ble.machine.handleDidUpdateNotificationState(ble.peripheral, characteristic: ble.native.rx, error: nil) + } + + func awaitCondition(_ predicate: @escaping @MainActor () async -> Bool) async throws { + guard await observedBeforeDeadline(predicate) else { throw BLESetupRetirementHarness.WaitError.expired } + } + + func observedBeforeDeadline(_ predicate: @escaping @MainActor () async -> Bool) async -> Bool { + do { + try await waitUntil { await predicate() } + return true + } catch { + return false + } + } + + func close() async { + await transport.releaseOrigin() + _ = await manager.disconnect(reason: .userInitiated) + await manager.retirementTask?.value + await manager.metadataCommitTask?.value + manager.testBLELifecycleEventHandled = nil + ble.native.setWriteHandler(nil) + writes.finish() + await writeWorker.value + await firmware.disconnect() + await replyWorker.value + await ble.machine.shutdown() + UserDefaults().removePersistentDomain(forName: suite) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/BLEReconnectionTestHarness.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/BLEReconnectionTestHarness.swift new file mode 100644 index 0000000000..124329e222 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/BLEReconnectionTestHarness.swift @@ -0,0 +1,125 @@ +import Foundation +@testable import MC1Services +import MeshCoreTestSupport +import Testing + +@MainActor +final class BLEReconnectionTestHarness { + @MainActor + final class Gate { + private var continuations: [CheckedContinuation] = [] + private var isOpen = false + + func wait() async { + guard !isOpen else { return } + await withCheckedContinuation { continuations.append($0) } + } + + func open() { + isOpen = true + let waiting = continuations + continuations.removeAll() + waiting.forEach { $0.resume() } + } + } + + enum RebuildError: Error { + case failed + } + + let clock = TestClock() + let coordinator: BLEReconnectionCoordinator + var rebuilds: [BLEReconnectionCoordinator.Cycle] = [] + var exhausted: [BLEReconnectionCoordinator.Cycle] = [] + var timeouts: [BLEReconnectionCoordinator.Cycle] = [] + var remainingFailures = 0 + var autoReconnecting = false + var onRebuild: (@MainActor (BLEReconnectionCoordinator.Cycle) async -> Void)? + var onExhausted: (@MainActor (BLEReconnectionCoordinator.Cycle) async -> Void)? + var onAutoReconnectQuery: (@MainActor () async -> Void)? + private var tasks: [Task] = [] + private var gateReleases: [() -> Void] = [] + private var activeTransportQueries = 0 + + init(uiTimeout: TimeInterval, maxUIWindow: TimeInterval) { + coordinator = BLEReconnectionCoordinator( + uiTimeoutDuration: uiTimeout, + maxConnectingUIWindow: maxUIWindow, + clock: clock + ) + coordinator.onRebuild = { [weak self] cycle in + guard let self else { throw CancellationError() } + rebuilds.append(cycle) + await onRebuild?(cycle) + if remainingFailures > 0 { + remainingFailures -= 1 + throw RebuildError.failed + } + } + coordinator.onExhausted = { [weak self] cycle in + guard let self else { return } + exhausted.append(cycle) + await onExhausted?(cycle) + } + coordinator.onTimeout = { [weak self] cycle in + self?.timeouts.append(cycle) + } + coordinator.isAutoReconnecting = { [weak self] in + guard let self else { return false } + activeTransportQueries += 1 + defer { activeTransportQueries -= 1 } + await onAutoReconnectQuery?() + return autoReconnecting + } + } + + func begin(deviceID: UUID = UUID(), requestID: UUID = UUID()) -> BLEReconnectionCoordinator.Cycle { + coordinator.begin(deviceID: deviceID, requestID: requestID) + } + + func complete(_ cycle: BLEReconnectionCoordinator.Cycle) -> Task { + let task = Task { await coordinator.complete(cycle) } + tasks.append(task) + return task + } + + func gate() -> Gate { + let gate = Gate() + gateReleases.append { gate.open() } + return gate + } + + func cleanup() async { + coordinator.clear() + gateReleases.forEach { $0() } + tasks.forEach { $0.cancel() } + for task in tasks { + await task.value + } + do { + try await waitUntil("cancelled transport queries should settle") { self.activeTransportQueries == 0 } + } catch { + Issue.record(error) + } + onRebuild = nil + onExhausted = nil + onAutoReconnectQuery = nil + #expect(clock.sleeperCount == 0) + } +} + +@MainActor +func withReconnectionHarness( + uiTimeout: TimeInterval = 10, + maxUIWindow: TimeInterval = 60, + _ body: @MainActor (BLEReconnectionTestHarness) async throws -> Void +) async rethrows { + let harness = BLEReconnectionTestHarness(uiTimeout: uiTimeout, maxUIWindow: maxUIWindow) + do { + try await body(harness) + } catch { + await harness.cleanup() + throw error + } + await harness.cleanup() +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/BLESetupRetirementHarness.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/BLESetupRetirementHarness.swift new file mode 100644 index 0000000000..d782b5f148 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/BLESetupRetirementHarness.swift @@ -0,0 +1,115 @@ +@preconcurrency import CoreBluetooth +import Foundation +@testable import MC1Services +@testable import MeshCore + +@MainActor +struct BLESetupRetirementHarness { + enum WaitError: Error { case expired } + let machine: BLEStateMachine + let adapter: iOSBLETransport + let native: BLETransportHarness + var peripheral: CBPeripheral { + native.peripheral + } + + var central: CBCentralManager { + native.central + } + + static func make() async -> Self { + let native = BLETransportHarness(supportsWriteWithoutResponse: true) + native.isReadyToWrite = true + let machine = BLEStateMachine(centralManager: native.central) + return Self(machine: machine, adapter: iOSBLETransport(stateMachine: machine), native: native) + } + + func connect(binding: SessionTransportBinding) async throws -> SessionBoundTransport { + let view = await adapter.makeSessionTransport(deviceID: peripheral.identifier, binding: binding) + let connecting = Task { try await view.connect() } + do { + try await awaitCondition { await machine.currentPhase.name == "connecting" } + await finishDiscovery() + try await connecting.value + return view + } catch { + await machine.shutdown() + _ = await connecting.result + throw error + } + } + + func beginDiscovery() async { + native.peripheralState = .connected + await machine.handleDidConnect(peripheral) + } + + func finishDiscovery() async { + await beginDiscovery() + await machine.handleDidDiscoverServices(peripheral, error: nil) + await machine.handleDidDiscoverCharacteristics(peripheral, service: native.service, error: nil) + await machine.handleDidUpdateNotificationState(peripheral, characteristic: native.rx, error: nil) + } + + func start(_ session: MeshCoreSession) async throws { + let starting = Task { try await session.start(disconnectTransportOnFailure: false) } + do { + try await awaitCondition { await machine.setupWriteIsPending } + await completeWrite() + var packet = Data([ResponseCode.selfInfo.rawValue, 1, 22, 22]) + packet.append(Data(repeating: 1, count: 32)) + packet.append(Data(repeating: 0, count: 12)) + for value: UInt32 in [915_000, 125_000] { + packet.append(withUnsafeBytes(of: value.littleEndian) { Data($0) }) + } + packet.append(contentsOf: [7, 5]) + packet.append(contentsOf: "Retirement Radio".utf8) + await inject(packet) + try await starting.value + } catch { + await machine.shutdown() + await session.stop(disconnectTransport: false) + _ = await starting.result + throw error + } + } + + func completeWrite() async { + await machine.completeSetupWrite() + } + + func inject(_ data: Data) async { + await machine.injectSetupData(data) + } + + func awaitCondition(_ predicate: @escaping @Sendable () async -> Bool) async throws { + guard await observedBeforeDeadline(predicate) else { throw WaitError.expired } + } + + func observedBeforeDeadline(_ predicate: @escaping @Sendable () async -> Bool) async -> Bool { + do { + try await waitUntil { await predicate() } + return true + } catch { + return false + } + } +} + +private extension BLEStateMachine { + func completeSetupWrite() { + guard case let .connected(peripheral, tx, _, _) = phase else { return } + handleDidWriteValue(peripheral, characteristic: tx, error: nil, writeSequence: pendingWriteSequence) + } + + func injectSetupData(_ data: Data) { + guard case let .connected(_, _, _, continuation) = phase else { return } + continuation.yield(data) + } +} + +extension BLEStateMachine { + var setupWriteIsPending: Bool { + pendingWriteContinuation != nil + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/CanonicalIdentityFixture.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/CanonicalIdentityFixture.swift new file mode 100644 index 0000000000..a9eb2644b3 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/CanonicalIdentityFixture.swift @@ -0,0 +1,32 @@ +import Foundation +@testable import MC1Services +import MeshCore + +@MainActor +enum CanonicalIdentityFixture { + static let privateKey = Data([ + 0x70, 0x65, 0xE1, 0x8F, 0xD9, 0xFA, 0xBB, 0x70, + 0xC1, 0xED, 0x90, 0xDC, 0xA1, 0x99, 0x07, 0xDE, + 0x69, 0x8C, 0x88, 0xB7, 0x09, 0xEA, 0x14, 0x6E, + 0xAF, 0xD9, 0x3D, 0x9B, 0x83, 0x0C, 0x7B, 0x60, + 0xC4, 0x68, 0x11, 0x93, 0xC7, 0x9B, 0xBC, 0x39, + 0x94, 0x5B, 0xA8, 0x06, 0x41, 0x04, 0xBB, 0x61, + 0x8F, 0x8F, 0xD7, 0xA8, 0x4A, 0x0A, 0xF6, 0xF5, + 0x70, 0x33, 0xD6, 0xE8, 0xDD, 0xCD, 0x64, 0x71 + ]) + static var privateKeyHex: String { + privateKey.hexString + } + + static let publicKey = Data([ + 0x1E, 0xC7, 0x71, 0x75, 0xB0, 0x91, 0x8E, 0xD2, + 0x06, 0xF9, 0xAE, 0x04, 0xEC, 0x13, 0x6D, 0x6D, + 0x5D, 0x43, 0x15, 0xBB, 0x26, 0x30, 0x54, 0x27, + 0xF6, 0x45, 0xB4, 0x92, 0xE9, 0x35, 0x0C, 0x10 + ]) + + static func prepareGhost(in harness: ConnectionRadioHandoffHarness) async throws { + try await harness.manager.persistenceStore.saveDevice(harness.deviceB.copy { $0.publicKey = publicKey }) + try await harness.manager.persistenceStore.demoteDeviceToGhost(id: harness.deviceB.id) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/ChannelScopeTestTransport.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/ChannelScopeTestTransport.swift index 061dbf4a14..349a485970 100644 --- a/MC1Services/Tests/MC1ServicesTests/Helpers/ChannelScopeTestTransport.swift +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/ChannelScopeTestTransport.swift @@ -3,19 +3,28 @@ import Foundation import MeshCore actor ChannelScopeTestTransport: MeshTransport { + enum ChannelCommandOutcome: Sendable { + case failWrite + case accept + } + let receivedData: AsyncStream private let continuation: AsyncStream.Continuation private let scopeError: UInt8? + private let channelOutcome: ChannelCommandOutcome private let beforePoolRetry: (@Sendable () async throws -> Void)? private(set) var isConnected = false private(set) var scopePackets: [Data] = [] private(set) var scopesAtChannelSend: [Data] = [] + private(set) var sentFrames: [Data] = [] init( scopeError: UInt8? = nil, + channelOutcome: ChannelCommandOutcome = .failWrite, beforePoolRetry: (@Sendable () async throws -> Void)? = nil ) { self.scopeError = scopeError + self.channelOutcome = channelOutcome self.beforePoolRetry = beforePoolRetry (receivedData, continuation) = AsyncStream.makeStream(of: Data.self) } @@ -30,6 +39,7 @@ actor ChannelScopeTestTransport: MeshTransport { } func send(_ data: Data) async throws { + sentFrames.append(data) switch data.first { case CommandCode.appStart.rawValue: continuation.yield(selfInfoPacket()) @@ -47,8 +57,15 @@ actor ChannelScopeTestTransport: MeshTransport { continuation.yield(Data([ResponseCode.error.rawValue, FirmwareDeviceErrorCode.channelMessageNotFound])) return } - // Stop before post-send bookkeeping reaches the OS notification center. - throw MeshTransportError.sendFailed("Test transport send failure") + switch channelOutcome { + case .failWrite: + // Stop before post-send bookkeeping reaches the OS notification center. + throw MeshTransportError.sendFailed("Test transport send failure") + case .accept: + continuation.yield(Data([ResponseCode.ok.rawValue])) + } + case CommandCode.sendMessage.rawValue: + continuation.yield(Data([ResponseCode.messageSent.rawValue, 0, 1, 2, 3, 4, 0x88, 0x13, 0, 0])) default: throw MeshTransportError.sendFailed("Unexpected test command") } diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionLoopbackRadioPeer.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionLoopbackRadioPeer.swift new file mode 100644 index 0000000000..0c370c9064 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionLoopbackRadioPeer.swift @@ -0,0 +1,175 @@ +import Foundation +import MeshCore +import Network +import Testing + +/// A framed TCP endpoint backed by the same stateful responder as the manager's BLE fixture. +actor ConnectionLoopbackRadioPeer { + private enum Event: Sendable { + case listener(NWListener.State) + case accepted(NWConnection) + } + + private enum Limits { + static let receiveSize = 65536 + static let lengthLowOffset = 1 + static let lengthHighOffset = 2 + static let byteShift = 8 + } + + let radio: ConnectionTestRadioTransport + private let listener: NWListener + private let events: AsyncStream + private let continuation: AsyncStream.Continuation + private var listenerWorker: Task? + private var receiveWorkers: [Task] = [] + private var connections: [NWConnection] = [] + private var closing = false + private(set) var ready = false + private(set) var listenerEnded = false + private(set) var receiveEndedCount = 0 + private(set) var failure: NWError? + private(set) var finishedWriteCount = 0 + + var port: UInt16? { + listener.port?.rawValue + } + + var acceptedCount: Int { + connections.count + } + + var stopped: Bool { + listenerEnded && receiveEndedCount == receiveWorkers.count + } + + private init(listener: NWListener, radio: ConnectionTestRadioTransport) { + self.listener = listener + self.radio = radio + (events, continuation) = AsyncStream.makeStream(of: Event.self) + } + + @MainActor + static func make(publicKey: Data) async throws -> ConnectionLoopbackRadioPeer { + let peer = try ConnectionLoopbackRadioPeer( + listener: NWListener(using: .tcp), radio: ConnectionTestRadioTransport(publicKey: publicKey) + ) + await peer.start() + do { + try await waitUntil("localhost listener must become ready") { + let ready = await peer.ready + let failed = await peer.failure != nil + return ready || failed + } + if let failure = await peer.failure { throw failure } + return peer + } catch { + await peer.close() + throw error + } + } + + private func start() { + let continuation = continuation + listener.stateUpdateHandler = { continuation.yield(.listener($0)) } + listener.newConnectionHandler = { continuation.yield(.accepted($0)) } + listenerWorker = Task { + for await event in events { + handle(event) + } + } + listener.start(queue: DispatchQueue(label: "test.connection-loopback-radio")) + } + + private func handle(_ event: Event) { + switch event { + case let .listener(state): + switch state { + case .ready: ready = true + case let .failed(error): failure = error + case .cancelled: + listenerEnded = true + continuation.finish() + default: break + } + case let .accepted(connection): + guard !closing else { connection.cancel(); return } + connections.append(connection) + connection.start(queue: DispatchQueue(label: "test.connection-loopback-client")) + receiveWorkers.append(Task { await serve(connection) }) + } + } + + private func serve(_ connection: NWConnection) async { + defer { receiveEndedCount += 1 } + var buffer = Data() + do { + while !closing { + let (content, complete) = try await Self.receive(connection) + if let content { buffer.append(content) } + while buffer.count >= WiFiFrameCodec.headerSize { + let start = buffer.startIndex + guard buffer[start] == WiFiFrameCodec.outboundDelimiter else { + Issue.record("Client submitted an invalid WiFi frame delimiter") + return + } + let length = Int(buffer[start + Limits.lengthLowOffset]) + | (Int(buffer[start + Limits.lengthHighOffset]) << Limits.byteShift) + let size = WiFiFrameCodec.headerSize + length + guard buffer.count >= size else { break } + let payload = Data(buffer[(start + WiFiFrameCodec.headerSize)..<(start + size)]) + buffer.removeFirst(size) + for reply in await radio.receiveFramedCommand(payload) { + var frame = WiFiFrameCodec.encode(reply) + frame[frame.startIndex] = WiFiFrameCodec.inboundDelimiter + try await Self.send(frame, on: connection) + } + } + if complete { return } + } + } catch { + if !closing, finishedWriteCount == 0 { Issue.record("Loopback radio receive failed: \(error)") } + } + } + + func finishAcceptedConnection() async throws { + let connection = try #require(connections.last) + finishedWriteCount += 1 + do { try await Self.send(nil, on: connection, final: true) } catch { finishedWriteCount -= 1; throw error } + } + + func close() async { + closing = true + listener.cancel() + for connection in connections { + connection.cancel() + } + for worker in receiveWorkers { + await worker.value + } + await listenerWorker?.value + listener.stateUpdateHandler = nil + listener.newConnectionHandler = nil + } + + func prepareToClose() { + closing = true + } + + private nonisolated static func receive(_ connection: NWConnection) async throws -> (Data?, Bool) { + try await withCheckedThrowingContinuation { continuation in + connection.receive(minimumIncompleteLength: 1, maximumLength: Limits.receiveSize) { content, _, complete, error in + if let error { continuation.resume(throwing: error) } else { continuation.resume(returning: (content, complete)) } + } + } + } + + private nonisolated static func send(_ content: Data?, on connection: NWConnection, final: Bool = false) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + connection.send(content: content, contentContext: final ? .finalMessage : .defaultMessage, isComplete: true, + completion: .contentProcessed { error in + if let error { continuation.resume(throwing: error) } else { continuation.resume() } + }) + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManager+BLERecoveryTesting.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManager+BLERecoveryTesting.swift new file mode 100644 index 0000000000..a2ed3973fc --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManager+BLERecoveryTesting.swift @@ -0,0 +1,35 @@ +import Foundation +@testable import MC1Services + +@MainActor +extension ConnectionManager { + @discardableResult + func seedBLERecoveryRequest(deviceID: UUID = UUID()) -> ConnectionRequest { + if let desiredRequest, desiredRequest.target != .disconnected { return desiredRequest } + let request = ConnectionRequest( + targets: [.bluetooth(deviceID)], origin: .recovery, + forceFullSync: false, forceReconnect: false, continuing: desiredRequest + ) + desiredRequest = request + return request + } + + func finishSeededBLERecovery() async { + let request = seedBLERecoveryRequest() + guard let deviceID = request.target.deviceID else { return } + request.handedOff = true + let cycle = reconnectionCoordinator.currentCycle + ?? reconnectionCoordinator.begin(deviceID: deviceID, requestID: request.id) + await finishBLERecoveryFailure(cycle) + if reconnectionCoordinator.isCurrent(cycle) { reconnectionCoordinator.clear() } + } + + func acceptSeededBLELoss(deviceID: UUID? = nil, error: BLEError? = nil) async { + let request = seedBLERecoveryRequest(deviceID: deviceID ?? connectedDevice?.id ?? UUID()) + let origin = BLELifecycleOrigin( + deviceID: deviceID ?? request.target.deviceID ?? UUID(), + generation: request.physicalOrigin?.generation ?? 1, eventTime: CFAbsoluteTimeGetCurrent() + ) + await handleBLELifecycleEvent(.disconnected(origin, error: error)) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManager+Testing.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManager+Testing.swift index aac6b97d14..94bd1848be 100644 --- a/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManager+Testing.swift +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManager+Testing.swift @@ -4,14 +4,17 @@ import SwiftData extension ConnectionManager { static func createForTesting( - defaults: UserDefaults? = nil + defaults: UserDefaults? = nil, + reconnectionClock: (any Clock)? = nil ) throws -> (ConnectionManager, MockBLEStateMachine) { let container = try PersistenceStore.createContainer(inMemory: true) let mock = MockBLEStateMachine() let manager = if let defaults { - ConnectionManager(modelContainer: container, defaults: defaults, stateMachine: mock) + ConnectionManager( + modelContainer: container, defaults: defaults, stateMachine: mock, reconnectionClock: reconnectionClock + ) } else { - ConnectionManager(modelContainer: container, stateMachine: mock) + ConnectionManager(modelContainer: container, stateMachine: mock, reconnectionClock: reconnectionClock) } return (manager, mock) } @@ -20,7 +23,8 @@ extension ConnectionManager { static func createForPairingTesting( defaults: UserDefaults? = nil, transport: MockMeshTransport? = nil, - accessorySetupKit: MockAccessorySetupKitService? = nil + accessorySetupKit: MockAccessorySetupKitService? = nil, + reconnectionClock: (any Clock)? = nil ) throws -> PairingTestEnvironment { let container = try PersistenceStore.createContainer(inMemory: true) let stateMachine = MockBLEStateMachine() @@ -47,7 +51,8 @@ extension ConnectionManager { defaults: resolvedDefaults, stateMachine: stateMachine, transport: mockTransport, - pairing: AccessorySetupPairingService(accessorySetupKit: mockASK) + pairing: AccessorySetupPairingService(accessorySetupKit: mockASK), + reconnectionClock: reconnectionClock ) // Cleanup closure: tests `defer { env.cleanup() }` to remove the persistent diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManagerRadioTestHarness.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManagerRadioTestHarness.swift new file mode 100644 index 0000000000..16669cc109 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManagerRadioTestHarness.swift @@ -0,0 +1,76 @@ +import Foundation +@testable import MC1Services +import MeshCoreTestSupport +import os +import Testing + +@MainActor +final class ConnectionManagerRadioTestHarness { + let manager: ConnectionManager + let ble: ConnectionTestRadioTransport + let wifi: ConnectionTestRadioTransport + let stateMachine = MockBLEStateMachine() + let pairing = MockAccessorySetupKitService() + let deviceID = UUID() + /// Resync and reconnect delays. Command timeouts stay on `sessionClock`. + let clock: TestClock? + let sessionClock: TestClock? + private let suite = "test.\(UUID().uuidString)" + + init( + sameRadio: Bool = true, + publicKey: Data = Data(repeating: 1, count: 32), + clock: TestClock? = nil, + sessionClock: TestClock? = nil, + firmwareVersion: UInt8 = 14 + ) throws { + self.clock = clock + self.sessionClock = sessionClock + let store = try PersistenceStore.createContainer(inMemory: true) + ble = ConnectionTestRadioTransport(publicKey: publicKey, firmwareVersion: firmwareVersion) + let wifi = ConnectionTestRadioTransport( + publicKey: sameRadio ? publicKey : Data(repeating: 2, count: 32), firmwareVersion: firmwareVersion + ) + self.wifi = wifi + pairing.isSessionActive = false + let defaults = try #require(UserDefaults(suiteName: suite)) + manager = ConnectionManager( + modelContainer: store, defaults: defaults, stateMachine: stateMachine, transport: ble, + pairing: AccessorySetupPairingService(accessorySetupKit: pairing), + reconnectionClock: clock, makeWiFiTransport: { wifi } + ) + manager.sessionClockForTesting = sessionClock + } + + /// Runs work whose command timeouts park on `sessionClock` and lets each parked timeout elapse. + func resultAdvancingClock( + _ work: @escaping @MainActor @Sendable () async throws -> T + ) async throws -> T { + guard let sessionClock else { return try await work() } + let slot = OSAllocatedUnfairLock?>(initialState: nil) + let task = Task { @MainActor in + let outcome: Result + do { outcome = try await .success(work()) } catch { outcome = .failure(error) } + slot.withLock { $0 = outcome } + } + try await waitUntilClockAdvances(sessionClock, timeout: .seconds(15), "clocked connection work should finish") { + slot.withLock { $0 != nil } + } + task.cancel() + return try slot.withLock { try $0!.get() } + } + + func connect(_ type: TransportType) async throws -> ConnectionResult { + if type == .bluetooth { return try await manager.connect(to: deviceID, forceFullSync: true, forceReconnect: true) } + return try await manager.connectViaWiFi(host: "radio.test", port: 5123, forceFullSync: true) + } + + func close() async { + await ble.releaseAllGates() + await wifi.releaseAllGates() + _ = await manager.disconnect(reason: .userInitiated) + await manager.retirementTask?.value + await manager.metadataCommitTask?.value + UserDefaults().removePersistentDomain(forName: suite) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionRadioHandoffHarness.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionRadioHandoffHarness.swift new file mode 100644 index 0000000000..9bfc0273e2 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionRadioHandoffHarness.swift @@ -0,0 +1,128 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@MainActor +final class ConnectionRadioHandoffHarness { + let manager: ConnectionManager + let bluetooth: ConnectionTestRadioTransport + let wifi: ConnectionTestRadioTransport + let pairing: MockAccessorySetupKitService + let stateMachine: MockBLEStateMachine + let deviceA: DeviceDTO + let deviceB: DeviceDTO + private let suiteName: String + private var joins: [() async -> Void] = [] + private var cancellations: [() -> Void] = [] + private var nodeKeys: [Data] = [] + + private init( + manager: ConnectionManager, bluetooth: ConnectionTestRadioTransport, wifi: ConnectionTestRadioTransport, + pairing: MockAccessorySetupKitService, stateMachine: MockBLEStateMachine, + deviceA: DeviceDTO, deviceB: DeviceDTO, suiteName: String + ) { + self.manager = manager + self.bluetooth = bluetooth + self.wifi = wifi + self.pairing = pairing + self.stateMachine = stateMachine + self.deviceA = deviceA + self.deviceB = deviceB + self.suiteName = suiteName + } + + static func make(wifiIsSameRadio: Bool = true, maxChannels: UInt8 = 1) async throws -> ConnectionRadioHandoffHarness { + let suite = "test.radio-handoff.\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suite)) + let container = try PersistenceStore.createContainer(inMemory: true) + let keyA = Data(repeating: 0xA1, count: ProtocolLimits.publicKeySize) + let keyB = Data(repeating: 0xB1, count: ProtocolLimits.publicKeySize) + let bluetooth = ConnectionTestRadioTransport(publicKey: keyA, maxChannels: maxChannels) + let wifi = ConnectionTestRadioTransport(publicKey: wifiIsSameRadio ? keyA : keyB, maxChannels: maxChannels) + let pairing = MockAccessorySetupKitService() + pairing.isSessionActive = false + let stateMachine = MockBLEStateMachine() + let manager = ConnectionManager( + modelContainer: container, defaults: defaults, stateMachine: stateMachine, transport: bluetooth, + pairing: AccessorySetupPairingService(accessorySetupKit: pairing), makeWiFiTransport: { wifi } + ) + let deviceA = DeviceDTO.testDevice(radioID: UUID(), publicKey: keyA, firmwareVersion: 14).copy { + $0.connectionMethods = [.bluetooth(peripheralUUID: $0.id, displayName: nil)] + } + let deviceB = DeviceDTO.testDevice(radioID: UUID(), publicKey: keyB, firmwareVersion: 14, isActive: false).copy { + $0.connectionMethods = [.wifi(host: "radio.local", port: 4242, displayName: nil)] + } + try await manager.persistenceStore.saveDevice(deviceA) + try await manager.persistenceStore.saveDevice(deviceB) + return ConnectionRadioHandoffHarness( + manager: manager, bluetooth: bluetooth, wifi: wifi, pairing: pairing, stateMachine: stateMachine, + deviceA: deviceA, deviceB: deviceB, suiteName: suite + ) + } + + func connectBluetooth() async throws { + _ = try await manager.connect(to: deviceA.id, forceReconnect: true) + #expect(manager.connectionState == .ready) + #expect(manager.connectedDevice?.radioID == deviceA.radioID) + } + + func addMembership(radioID: UUID, connected: Bool) async throws -> RemoteNodeSessionDTO { + let key = Data(UUID().uuidString.utf8.prefix(ProtocolLimits.publicKeySize)) + nodeKeys.append(key) + // Keep the fixture password within the firmware limit so login reaches the radio. + try await KeychainService.shared.storePassword("handoff", forNodeKey: key) + let membership = RemoteNodeSessionDTO.testSession( + radioID: radioID, publicKey: key, isConnected: connected, permissionLevel: .readWrite + ) + let contact = ContactDTO.testContact(radioID: radioID, publicKey: key, typeRawValue: ContactType.room.rawValue) + try await manager.persistenceStore.saveContact(contact) + let frame = contact.toContactFrame().toMeshContact() + for peer in [bluetooth, wifi] { + let matchesA = radioID == deviceA.radioID && peer.publicKey == deviceA.publicKey + let matchesB = radioID == deviceB.radioID && peer.publicKey == deviceB.publicKey + if matchesA || matchesB { await peer.setContact(frame) } + } + try await manager.persistenceStore.saveRemoteNodeSessionDTO(membership) + return membership + } + + func isConnected(_ membership: RemoteNodeSessionDTO) async throws -> Bool { + try #require(try await manager.persistenceStore.fetchRemoteNodeSession(id: membership.id)).isConnected + } + + func track(_ task: Task) -> Task { + cancellations.append { task.cancel() } + joins.append { _ = await task.result } + return task + } + + func finish() async { + await bluetooth.releaseAllGates() + await wifi.releaseAllGates() + for cancel in cancellations { + cancel() + } + _ = await manager.disconnect(reason: .userInitiated) + for join in joins { + await join() + } + for key in nodeKeys { + try? await KeychainService.shared.deletePassword(forNodeKey: key) + } + UserDefaults().removePersistentDomain(forName: suiteName) + #expect(manager.services == nil) + #expect(await bluetooth.isConnected == false) + #expect(await wifi.isConnected == false) + } + + static func withHarness( + wifiIsSameRadio: Bool = true, + maxChannels: UInt8 = 1, + _ body: (ConnectionRadioHandoffHarness) async throws -> Void + ) async throws { + let harness = try await make(wifiIsSameRadio: wifiIsSameRadio, maxChannels: maxChannels) + do { try await body(harness) } catch { await harness.finish(); throw error } + await harness.finish() + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionTestRadioTransport.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionTestRadioTransport.swift new file mode 100644 index 0000000000..5364e647e0 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionTestRadioTransport.swift @@ -0,0 +1,663 @@ +import Foundation +@testable import MC1Services +import MeshCore + +/// Drives production session framing and connection ownership with a bounded radio model. +actor ConnectionTestRadioTransport: iOSMeshTransport, WiFiMeshTransport { + private enum Gate: Hashable { case connect, submission, completion, disconnect, commandSubmission(UInt8) } + private var heldGates: Set = [] + private var waiters: [Gate: [CheckedContinuation]] = [:] + private var heldReplyCodes: Set = [] + private var heldReplies: [UInt8: [Data]] = [:] + private var rejection: [UInt8: (remaining: Int, code: UInt8)] = [:] + private var cliResponses: [String: String] = [:] + private var cliResponder: (@Sendable (String) -> String?)? + private var heldCLICommands: Set = [] + private var heldCLIReplies: [String: [Data]] = [:] + private var responsePackets: [UInt8: [Data]] = [:] + private var responseSequences: [UInt8: [[Data]]] = [:] + private var channels: [UInt8: (name: String, secret: Data)] = [:] + private var contacts: [Data: Data] = [:] + private var devicePublicKeys: [UUID: Data] = [:] + private var identityImportPublicKey: Data? + private var importedPublicKey: Data? + private var selfInfoName = "Test Radio" + private var selfInfoTxPower: UInt8 = 22 + private var selfInfoCoordinates = Data(repeating: 0, count: 8) + private var selfInfoOtherParams = Data(repeating: 0, count: 4) + private var selfInfoRadio = Data(PacketBuilder.setRadio( + frequency: 915, bandwidth: 125, spreadingFactor: 7, codingRate: 5 + ).dropFirst()) + private var holdsLoginResults = false + private var heldLoginResults: [Data] = [] + private var stream: AsyncStream + private var continuation: AsyncStream.Continuation + private var streamNeedsRenewal = false + private var deviceID: UUID? + private var generation: UInt64 = 0 + private var originTime = CFAbsoluteTimeGetCurrent() + private var binding: SessionTransportBinding? + private var lifecycleHandler: (@Sendable (BLELifecycleEvent) -> Void)? + private var socketDisconnectionHandler: (@Sendable (Error?, CFAbsoluteTime) -> Void)? + private var connectError: (any Error)? + private var sendError: (any Error)? + private var commandSendErrors: [UInt8: any Error] = [:] + private var postSubmissionSendErrors: [UInt8: any Error] = [:] + private var recovering = false + let publicKey: Data + let firmwareVersion: UInt8 + let maxChannels: UInt8 + private(set) var connectionInfo: (host: String, port: UInt16)? + private(set) var isConnected = false + private(set) var connectCount = 0 + private(set) var disconnectCount = 0 + private(set) var sentData: [Data] = [] + private var lastYieldedByCommand: [UInt8: Data] = [:] + private(set) var yieldedChannelInfoCount = 0 + private(set) var failedSendCount = 0 + private(set) var sessionDeviceIDs: [UUID] = [] + private(set) var cliCommands: [String] = [] + private(set) var timeReads = 0 + private(set) var timeWrites = 0 + private(set) var channelWriteIndices: [UInt8] = [] + private(set) var unconfiguredChannelSendCount = 0 + var radioTime = Date() + + init(publicKey: Data = Data(repeating: 1, count: 32), firmwareVersion: UInt8 = 14, maxChannels: UInt8 = 1) { + self.publicKey = publicKey + self.firmwareVersion = firmwareVersion + self.maxChannels = maxChannels + (stream, continuation) = AsyncStream.makeStream(of: Data.self) + } + + var receivedData: AsyncStream { + stream + } + + var supportsPipelinedReads: Bool { + true + } + + var connectIsHeld: Bool { + waiters[.connect]?.isEmpty == false + } + + var submissionIsHeld: Bool { + waiters[.submission]?.isEmpty == false + } + + var sendCompletionIsHeld: Bool { + waiters[.completion]?.isEmpty == false + } + + var disconnectIsHeld: Bool { + waiters[.disconnect]?.isEmpty == false + } + + var hasLifecycleHandler: Bool { + lifecycleHandler != nil + } + + var heldLoginResultCount: Int { + heldLoginResults.count + } + + var lifecycleOrigin: BLELifecycleOrigin? { + guard let deviceID, isConnected || recovering else { return nil } + return BLELifecycleOrigin(deviceID: deviceID, generation: generation, eventTime: originTime) + } + + func primePhysicalLink(deviceID: UUID, generation: UInt64 = 1, recovering: Bool = false) { + self.deviceID = deviceID + self.generation = generation + originTime = CFAbsoluteTimeGetCurrent() + self.recovering = recovering + isConnected = !recovering + } + + func releaseAllGates() { + for gate in heldGates { + release(gate) + } + let replies = heldReplies.values.flatMap(\.self) + heldReplies.removeAll() + heldReplyCodes.removeAll() + for reply in replies { + continuation.yield(reply) + } + let cliReplies = heldCLIReplies.values.flatMap(\.self) + heldCLICommands.removeAll() + heldCLIReplies.removeAll() + for reply in cliReplies { + continuation.yield(reply) + } + releaseLoginResults() + } + + func setDeviceID(_ id: UUID) { + deviceID = id + } + + func setPublicKey(_ key: Data, for deviceID: UUID) { + devicePublicKeys[deviceID] = key + } + + func setIdentityImportPublicKey(_ key: Data) { + identityImportPublicKey = key + } + + func setConnectionInfo(host: String, port: UInt16) { + connectionInfo = (host, port) + } + + func setConnectError(_ error: (any Error)?) { + connectError = error + } + + func setSendError(_ error: (any Error)?) { + sendError = error + } + + func setSendError(_ error: (any Error)?, for command: CommandCode) { + commandSendErrors[command.rawValue] = error + } + + func failNextSendAfterSubmission(_ command: CommandCode, error: any Error) { + postSubmissionSendErrors[command.rawValue] = error + } + + func setCLIResponse(_ command: String, response: String) { + cliResponses[command] = response + } + + func setCLIResponder(_ responder: @escaping @Sendable (String) -> String?) { + cliResponder = responder + } + + func holdCLIReplies(for command: String) { + heldCLICommands.insert(command) + } + + func heldCLIReplyCount(for command: String) -> Int { + heldCLIReplies[command]?.count ?? 0 + } + + func releaseCLIReplies(for command: String) { + heldCLICommands.remove(command) + for reply in heldCLIReplies.removeValue(forKey: command) ?? [] { + continuation.yield(reply) + } + } + + static func splitCLICommand(_ command: String) -> (prefix: String, command: String) { + let bytes = Array(command.utf8.prefix(while: { $0 != 0 }).drop(while: { $0 == 0x20 })) + guard bytes.count > 4, bytes[2] == 0x7C else { + return ("", String(decoding: bytes, as: UTF8.self)) + } + return (String(decoding: bytes.prefix(3), as: UTF8.self), String(decoding: bytes.dropFirst(3), as: UTF8.self)) + } + + func setChannel(index: UInt8, name: String, secret: Data) { + channels[index] = (name, secret) + } + + func setContact(_ contact: MeshContact) { + _ = responses(to: PacketBuilder.updateContact(contact)) + } + + func channelMatches(index: UInt8, secret: Data) -> Bool { + channels[index]?.secret == secret + } + + func isChannelConfigured(index: UInt8) -> Bool { + guard let channel = channels[index] else { return false } + return !channel.name.isEmpty || channel.secret.contains { $0 != 0 } + } + + func setResponsePackets(for command: CommandCode, packets: [Data]) { + responsePackets[command.rawValue] = packets + } + + func enqueueResponsePackets(for command: CommandCode, packets: [Data]) { + responseSequences[command.rawValue, default: []].append(packets) + } + + /// The last command's delivered reply. A held or missing reply is `nil` so a test can tell it from a frame that can still match. + func latestCommandExchange() -> (sent: Bool, response: Data?) { + guard let code = sentData.last?.first else { return (false, nil) } + return (true, lastYieldedByCommand[code]) + } + + func setRadioTime(_ date: Date) { + radioTime = date + } + + func setTelemetryModeBase(_ mode: UInt8) { + let mask = OtherParamsIntent.telemetryModeMask + selfInfoOtherParams[2] = (selfInfoOtherParams[2] & ~mask) | (mode & mask) + } + + func rejectNext(_ command: CommandCode, count: Int = 1, code: UInt8 = 1) { + rejection[command.rawValue] = (count, code) + } + + func holdConnect() { + heldGates.insert(.connect) + } + + func releaseConnect() { + release(.connect) + } + + func holdDisconnect() { + heldGates.insert(.disconnect) + } + + func releaseDisconnect() { + release(.disconnect) + } + + func holdNextSubmission() { + heldGates.insert(.submission) + } + + func releaseSubmission() { + release(.submission) + } + + func holdNextSendCompletion() { + heldGates.insert(.completion) + } + + func releaseSendCompletion() { + release(.completion) + } + + func holdReplies(for command: CommandCode) { + heldReplyCodes.insert(command.rawValue) + } + + func heldReplyCount(for command: CommandCode) -> Int { + heldReplies[command.rawValue]?.count ?? 0 + } + + func holdSubmissions(for command: CommandCode) { + heldGates.insert(.commandSubmission(command.rawValue)) + } + + func submissionIsHeld(for command: CommandCode) -> Bool { + waiters[.commandSubmission(command.rawValue)]?.isEmpty == false + } + + func releaseSubmissions(for command: CommandCode) { + release(.commandSubmission(command.rawValue)) + } + + func holdLoginResults() { + holdsLoginResults = true + } + + func releaseLoginResults() { + holdsLoginResults = false + let results = heldLoginResults + heldLoginResults.removeAll() + for result in results { + continuation.yield(result) + } + } + + func releaseReplies(for command: CommandCode) { + heldReplyCodes.remove(command.rawValue) + for reply in heldReplies.removeValue(forKey: command.rawValue) ?? [] { + continuation.yield(reply) + } + } + + func makeSessionTransport(deviceID: UUID, binding: SessionTransportBinding) -> SessionBoundTransport { + try? binding.performIfActive { + if self.binding !== binding { self.binding?.revoke() } + self.deviceID = deviceID + self.sessionDeviceIDs.append(deviceID) + self.binding = binding + } + return SessionBoundTransport(transport: self, binding: binding) + } + + func connect() async throws { + try await performConnect(binding: nil) + } + + func connect(sessionBinding: SessionTransportBinding) async throws { + try sessionBinding.performIfActive { + if binding !== sessionBinding { binding?.revoke(); binding = sessionBinding } + } + try await performConnect(binding: sessionBinding) + } + + private func performConnect(binding: SessionTransportBinding?) async throws { + try binding?.checkActive() + if isConnected { return } + connectCount += 1 + await wait(.connect) + try binding?.checkActive() + if let connectError { throw connectError } + if streamNeedsRenewal { refreshDataStream() } + let submit = { + self.isConnected = true + self.recovering = false + self.generation += 1 + self.originTime = CFAbsoluteTimeGetCurrent() + } + if let binding { try binding.performIfActive(submit) } else { submit() } + } + + func disconnect() async { + disconnectCount += 1 + await wait(.disconnect) + isConnected = false + recovering = false + continuation.finish() + streamNeedsRenewal = true + } + + func disconnect(sessionBinding: SessionTransportBinding) async { + guard binding === sessionBinding else { return } + await disconnect() + } + + func cancelPendingEstablishment(sessionBinding: SessionTransportBinding) { + guard binding === sessionBinding, !isConnected else { return } + release(.connect) + } + + func cancelUnsubmittedWrites(sessionBinding: SessionTransportBinding) {} + func refreshDataStream() { + continuation.finish() + (stream, continuation) = AsyncStream.makeStream(of: Data.self) + streamNeedsRenewal = false + } + + func refreshDataStream(sessionBinding: SessionTransportBinding) { + guard binding === sessionBinding, sessionBinding.isActive else { return } + refreshDataStream() + } + + func receivedData(sessionBinding: SessionTransportBinding) -> AsyncStream { + guard binding === sessionBinding, sessionBinding.isActive else { return AsyncStream { $0.finish() } } + return stream + } + + func send(_ data: Data) async throws { + try await performSend(data, binding: nil) + } + + func send(_ data: Data, sessionBinding: SessionTransportBinding) async throws { + try await performSend(data, binding: sessionBinding) + } + + func sendWithoutResponse(_ data: Data, sessionBinding: SessionTransportBinding) async throws { + try await performSend(data, binding: sessionBinding) + } + + private func performSend(_ data: Data, binding: SessionTransportBinding?) async throws { + if let code = data.first { await wait(.commandSubmission(code)) } + await wait(.submission) + try binding?.checkActive() + guard isConnected else { throw MeshTransportError.notConnected } + if let error = data.first.flatMap({ commandSendErrors[$0] }) { + failedSendCount += 1 + throw error + } + if let sendError { + failedSendCount += 1 + throw sendError + } + let submit = { + let responses = self.receiveFramedCommand(data) + guard let code = data.first else { return } + var delivered: Data? + for response in responses { + if self.holdsLoginResults, response.first == ResponseCode.loginSuccess.rawValue { + self.heldLoginResults.append(response) + } else if code == CommandCode.runCliCommand.rawValue, + self.heldCLICommands.contains(Self.splitCLICommand(String(decoding: data.dropFirst(), as: UTF8.self)).command) { + let command = Self.splitCLICommand(String(decoding: data.dropFirst(), as: UTF8.self)).command + self.heldCLIReplies[command, default: []].append(response) + } else if self.heldReplyCodes.contains(code) { + self.heldReplies[code, default: []].append(response) + } else { + delivered = response + if code == CommandCode.getChannel.rawValue, response.first == ResponseCode.channelInfo.rawValue { + self.yieldedChannelInfoCount += 1 + } + self.continuation.yield(response) + } + } + if let delivered { + self.lastYieldedByCommand[code] = delivered + } else if !self.heldReplyCodes.contains(code) { + self.lastYieldedByCommand.removeValue(forKey: code) + } + } + if let binding { try binding.performIfActive(submit) } else { submit() } + let postSubmissionError = data.first.flatMap { postSubmissionSendErrors.removeValue(forKey: $0) } + await wait(.completion) + if let postSubmissionError { + failedSendCount += 1 + throw postSubmissionError + } + } + + func setLifecycleHandler(_ handler: @escaping @Sendable (BLELifecycleEvent) -> Void) { + lifecycleHandler = handler + } + + func setDisconnectionHandler(_ handler: @escaping @Sendable (Error?, CFAbsoluteTime) -> Void) { + socketDisconnectionHandler = handler + } + + func simulateAutoReconnecting(deviceID: UUID) { + self.deviceID = deviceID + binding?.revoke() + isConnected = false + recovering = true + generation += 1 + originTime = CFAbsoluteTimeGetCurrent() + continuation.finish() + lifecycleHandler?(.autoReconnecting(lifecycleOrigin!, errorInfo: "radio link lost")) + } + + func simulateReconnected() { + guard let deviceID else { return } + isConnected = true + recovering = false + refreshDataStream() + let origin = BLELifecycleOrigin(deviceID: deviceID, generation: generation, eventTime: CFAbsoluteTimeGetCurrent()) + lifecycleHandler?(.reconnected(origin)) + } + + func simulateRemoteLoss(error: BLEError? = nil) { + let timestamp = CFAbsoluteTimeGetCurrent() + binding?.revoke() + if let deviceID { + let origin = BLELifecycleOrigin(deviceID: deviceID, generation: generation, eventTime: timestamp) + lifecycleHandler?(.remoteLinkLost(origin)) + lifecycleHandler?(.disconnected(origin, error: error)) + } + isConnected = false + continuation.finish() + streamNeedsRenewal = true + socketDisconnectionHandler?(error, timestamp) + } + + func simulateSocketReceiveLoss(error: (any Error)? = MeshTransportError.notConnected) { + isConnected = false + continuation.finish() + streamNeedsRenewal = true + socketDisconnectionHandler?(error, CFAbsoluteTimeGetCurrent()) + } + + func inject(_ packet: Data) { + continuation.yield(packet) + } + + func receiveFramedCommand(_ data: Data) -> [Data] { + sentData.append(data) + return responses(to: data) + } + + private func wait(_ gate: Gate) async { + guard heldGates.contains(gate) else { return } + await withCheckedContinuation { waiters[gate, default: []].append($0) } + } + + private func release(_ gate: Gate) { + heldGates.remove(gate) + let pending = waiters.removeValue(forKey: gate) ?? [] + for continuation in pending { + continuation.resume() + } + } + + private func responses(to data: Data) -> [Data] { + guard let rawCode = data.first, let code = CommandCode(rawValue: rawCode) else { return [] } + if responseSequences[rawCode]?.isEmpty == false { + return responseSequences[rawCode]!.removeFirst() + } + if let reject = rejection[rawCode], reject.remaining > 0 { + rejection[rawCode] = (reject.remaining - 1, reject.code) + return [Data([ResponseCode.error.rawValue, reject.code])] + } + if let packets = responsePackets[rawCode] { return packets } + if let response = configurationResponse(to: code, data: data) { return [response] } + switch code { + case .deviceQuery: + var reply = Data([ResponseCode.deviceInfo.rawValue, firmwareVersion, 1, maxChannels]) + reply.append(Data(repeating: 0, count: 76)) + return [reply] + case .getContacts: + let count = UInt32(contacts.count).littleEndian + let start = Data([ResponseCode.contactStart.rawValue]) + withUnsafeBytes(of: count) { Data($0) } + let rows = contacts.sorted { $0.key.lexicographicallyPrecedes($1.key) }.map { + Data([ResponseCode.contact.rawValue]) + $0.value + } + return [start] + rows + [Data([ResponseCode.contactEnd.rawValue, 1, 0, 0, 0])] + case .getContactByKey: + let key = Data(data.dropFirst().prefix(ProtocolLimits.publicKeySize)) + guard let contact = contacts[key] else { + return [Data([ResponseCode.error.rawValue, ProtocolError.notFound.rawValue])] + } + return [Data([ResponseCode.contact.rawValue]) + contact] + case .updateContact: + guard data.count >= 144 else { return [Data([ResponseCode.error.rawValue, 1])] } + let key = Data(data.dropFirst().prefix(32)) + contacts[key] = Data(data.dropFirst().prefix(143)) + Data([1, 0, 0, 0]) + return [Data([ResponseCode.ok.rawValue])] + case .getChannel: + let index = data.count > 1 ? data[1] : 0 + let channel = channels[index] + let name = Data((channel?.name ?? "").utf8.prefix(32)) + let secret = Data((channel?.secret ?? Data()).prefix(16)) + return [Data([ResponseCode.channelInfo.rawValue, index]) + + name + Data(repeating: 0, count: 32 - name.count) + + secret + Data(repeating: 0, count: 16 - secret.count)] + case .setChannel: + guard data.count >= 50, data[1] < maxChannels else { + return [Data([ResponseCode.error.rawValue, 1])] + } + let index = data[1] + let name = String(decoding: data.dropFirst(2).prefix(32).prefix { $0 != 0 }, as: UTF8.self) + channels[index] = (name, Data(data.dropFirst(34).prefix(16))) + channelWriteIndices.append(index) + return [Data([ResponseCode.ok.rawValue])] + case .sendChannelMessage: + if data.count > 2, !isChannelConfigured(index: data[2]) { unconfiguredChannelSendCount += 1 } + return [Data([ResponseCode.ok.rawValue])] + case .getMessage: return [Data([ResponseCode.noMoreMessages.rawValue])] + case .getAutoAddConfig: return [Data([ResponseCode.autoAddConfig.rawValue, 0])] + case .getBattery: return [Data([ResponseCode.battery.rawValue, 0x74, 0x0E])] + case .exportPrivateKey: return [Data([ResponseCode.disabled.rawValue])] + case .getTime: + timeReads += 1 + var reply = Data([ResponseCode.currentTime.rawValue]) + reply.append(withUnsafeBytes(of: UInt32(max(0, radioTime.timeIntervalSince1970)).littleEndian) { Data($0) }) + return [reply] + case .setTime: + timeWrites += 1 + if data.count >= 5 { + let seconds = data.dropFirst().prefix(4).enumerated().reduce(UInt32(0)) { value, element in + value | (UInt32(element.element) << (8 * element.offset)) + } + radioTime = Date(timeIntervalSince1970: TimeInterval(seconds)) + } + return [Data([ResponseCode.ok.rawValue])] + case .runCliCommand: + let command = String(decoding: data.dropFirst(), as: UTF8.self) + cliCommands.append(command) + let parsed = Self.splitCLICommand(command) + if parsed.command == PacketBuilder.powerOffCommand, cliResponses[command] == nil { return [] } + let firmwareCommand = String(decoding: command.utf8.prefix(while: { $0 != 0 }), as: UTF8.self) + if let text = cliResponder?(firmwareCommand) { + return [Data([ResponseCode.cliReply.rawValue]) + Data(text.utf8)] + } + let body = cliResponses[command] ?? cliResponses[parsed.command] + ?? (parsed.command.hasPrefix("get ") ? "> 0" : "OK") + let text = parsed.prefix.isEmpty || body.hasPrefix(parsed.prefix) ? body : parsed.prefix + body + return [Data([ResponseCode.cliReply.rawValue]) + Data(text.utf8)] + case .sendLogin: + let publicKey = Data(data.dropFirst().prefix(ProtocolLimits.publicKeySize)) + guard publicKey.count == ProtocolLimits.publicKeySize, contacts[publicKey] != nil else { + return [Data([ResponseCode.error.rawValue, ProtocolError.notFound.rawValue])] + } + let destination = Data(publicKey.prefix(6)) + return [ + Data([ResponseCode.messageSent.rawValue, 0, 1, 2, 3, 4, 0x88, 0x13, 0, 0]), + Data([ResponseCode.loginSuccess.rawValue, 0]) + destination + ] + default: return [Data([ResponseCode.ok.rawValue])] + } + } + + private func configurationResponse(to code: CommandCode, data: Data) -> Data? { + switch code { + case .importPrivateKey: + if let identityImportPublicKey { + importedPublicKey = identityImportPublicKey + if let deviceID { devicePublicKeys[deviceID] = identityImportPublicKey } + } + return Data([ResponseCode.ok.rawValue]) + case .setName: + selfInfoName = String(decoding: data.dropFirst().prefix { $0 != 0 }, as: UTF8.self) + return Data([ResponseCode.ok.rawValue]) + case .setCoordinates: + if data.count >= 9 { selfInfoCoordinates = Data(data.dropFirst().prefix(8)) } + return Data([ResponseCode.ok.rawValue]) + case .setOtherParams: + if data.count >= 4 { + if data.count >= 5 { selfInfoOtherParams[0] = data[4] } + selfInfoOtherParams[1] = data[3] + selfInfoOtherParams[2] = data[2] + selfInfoOtherParams[3] = data[1] + } + return Data([ResponseCode.ok.rawValue]) + case .setRadio: + if data.count >= 11 { selfInfoRadio = Data(data.dropFirst().prefix(10)) } + return Data([ResponseCode.ok.rawValue]) + case .setTxPower: + if data.count >= 2 { selfInfoTxPower = data[1] } + return Data([ResponseCode.ok.rawValue]) + case .appStart: return selfInfoPacket() + default: return nil + } + } + + private func selfInfoPacket() -> Data { + var reply = Data([ResponseCode.selfInfo.rawValue, 1, selfInfoTxPower, 22]) + reply.append(deviceID.flatMap { devicePublicKeys[$0] } ?? importedPublicKey ?? publicKey) + reply.append(selfInfoCoordinates) + reply.append(selfInfoOtherParams) + reply.append(selfInfoRadio) + reply.append(contentsOf: selfInfoName.utf8) + return reply + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionWiFiEstablishmentHarness.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionWiFiEstablishmentHarness.swift new file mode 100644 index 0000000000..d6afad8110 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionWiFiEstablishmentHarness.swift @@ -0,0 +1,194 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +@MainActor +final class ConnectionWiFiEstablishmentHarness { + let manager: ConnectionManager + let bluetooth: ConnectionTestRadioTransport + let modeledWiFi: ConnectionTestRadioTransport + let peer: ConnectionLoopbackRadioPeer? + let saved: DeviceDTO + private let suite: String + private let selection = Gate() + private var cancellations: [() -> Void] = [] + private var joins: [() async -> Void] = [] + private var candidates: [ConnectionResource] = [] + private(set) var selectedRequestID: UUID? + + var host: String { + "127.0.0.1" + } + + var port: UInt16 { + guard case let .wifi(_, port, _) = saved.wifiConnectionMethod else { preconditionFailure("Missing test endpoint") } + return port + } + + private init( + manager: ConnectionManager, bluetooth: ConnectionTestRadioTransport, modeledWiFi: ConnectionTestRadioTransport, + peer: ConnectionLoopbackRadioPeer?, saved: DeviceDTO, suite: String + ) { + self.manager = manager + self.bluetooth = bluetooth + self.modeledWiFi = modeledWiFi + self.peer = peer + self.saved = saved + self.suite = suite + } + + static func make(realSocket: Bool, wifiLast: Bool = true) async throws -> ConnectionWiFiEstablishmentHarness { + let suite = "test.wifi-establishment.\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suite)) + let container = try PersistenceStore.createContainer(inMemory: true) + let publicKey = Data(repeating: 0xA1, count: ProtocolLimits.publicKeySize) + let bluetooth = ConnectionTestRadioTransport(publicKey: publicKey) + let modeledWiFi = ConnectionTestRadioTransport(publicKey: publicKey) + let peer = realSocket ? try await ConnectionLoopbackRadioPeer.make(publicKey: publicKey) : nil + do { + let port: UInt16 = if let peer { try #require(await peer.port) } else { 4242 } + let pairing = MockAccessorySetupKitService() + pairing.isSessionActive = false + let makeSocket: @Sendable () -> any WiFiMeshTransport = if realSocket { { WiFiTransport() } } else { { modeledWiFi } } + let manager = ConnectionManager( + modelContainer: container, defaults: defaults, stateMachine: MockBLEStateMachine(), transport: bluetooth, + pairing: AccessorySetupPairingService(accessorySetupKit: pairing), makeWiFiTransport: makeSocket + ) + let device = DeviceDTO.testDevice(publicKey: publicKey, isActive: false).copy { + let ble = ConnectionMethod.bluetooth(peripheralUUID: $0.id, displayName: nil) + let wifi = ConnectionMethod.wifi(host: "127.0.0.1", port: port, displayName: nil) + $0.connectionMethods = wifiLast ? [ble, wifi] : [wifi, ble] + } + try await manager.persistenceStore.saveDevice(device) + return ConnectionWiFiEstablishmentHarness( + manager: manager, bluetooth: bluetooth, modeledWiFi: modeledWiFi, peer: peer, saved: device, suite: suite + ) + } catch { + await peer?.close() + UserDefaults().removePersistentDomain(forName: suite) + throw error + } + } + + func holdFirstSelection() { + manager.testConnectionSelectionHandler = { [self] requestID in + guard selectedRequestID == nil else { return } + selectedRequestID = requestID + await selection.wait() + } + } + + func selectedCandidate() async throws -> (request: ConnectionRequest, attempt: ConnectionAttempt) { + try await waitUntil("actual session preparation must reach final selection") { self.selection.arrived } + let request = try #require(manager.desiredRequest) + let attempt = try #require(request.attempt) + let resource = try #require(attempt.resource) + candidates.append(resource) + try #require(attempt.preparedServices != nil) + try #require(request.id == selectedRequestID) + try #require(attempt.binding.isActive) + try #require(manager.currentConnection == nil) + let responder = if attempt.target.transportType == .bluetooth { bluetooth } else { peer?.radio ?? modeledWiFi } + let frames = await responder.sentData + try #require(frames.contains { $0.first == CommandCode.appStart.rawValue }) + try #require(frames.contains { $0.first == CommandCode.deviceQuery.rawValue }) + try #require(frames.contains { $0.first == CommandCode.getAutoAddConfig.rawValue }) + return (request, attempt) + } + + func endReceive(_ candidate: ConnectionAttempt, error: (any Error)? = MeshTransportError.notConnected) async throws { + let socket = try #require(candidate.resource?.wifi) + if let peer { + try #require(await peer.acceptedCount == 1) + try await peer.finishAcceptedConnection() + try #require(await peer.finishedWriteCount == 1) + } else { + await modeledWiFi.simulateSocketReceiveLoss(error: error) + } + try await waitUntil("physical receive termination must disconnect the candidate and invoke captured manager revocation") { + let disconnected = await !socket.isConnected + return disconnected && !candidate.binding.isActive + } + if let peer { + try await waitUntil("the closed client socket must also end the peer receive worker") { await peer.receiveEndedCount == 1 } + } + try #require(manager.currentConnection == nil) + try #require(manager.desiredRequest?.attempt === candidate) + try #require(manager.desiredRequest?.worker?.isCancelled == false) + } + + func releaseSelection() { + selection.open() + manager.testConnectionSelectionHandler = nil + } + + func proveLaterIO() async throws { + releaseSelection() + let result = try await manager.connectViaWiFi(host: host, port: port) + #expect(manager.isCurrent(result)) + #expect(manager.connectionState == .ready) + let session = try #require(manager.session) + #expect(try await session.getTime().timeIntervalSince1970 > 0) + } + + func track(_ task: Task) -> Task { + cancellations.append { task.cancel() } + joins.append { _ = await task.result } + return task + } + + func close() async { + releaseSelection() + manager.testBLELifecycleEventHandled = nil + await bluetooth.releaseAllGates() + await modeledWiFi.releaseAllGates() + for cancel in cancellations { + cancel() + } + await peer?.prepareToClose() + _ = await manager.disconnect(reason: .userInitiated) + for join in joins { + await join() + } + await manager.retirementTask?.value + await manager.metadataCommitTask?.value + for resource in candidates { + await resource.session.waitForQuiescence() + #expect(await resource.session.subscriberCountForTest == 0) + } + await peer?.close() + if let peer { #expect(await peer.stopped) } + #expect(manager.currentConnection == nil) + #expect(manager.connectionTeardownCount == 0) + UserDefaults().removePersistentDomain(forName: suite) + } + + static func withHarness( + realSocket: Bool = true, wifiLast: Bool = true, + _ body: (ConnectionWiFiEstablishmentHarness) async throws -> Void + ) async throws { + let harness = try await make(realSocket: realSocket, wifiLast: wifiLast) + do { try await body(harness) } catch { await harness.close(); throw error } + await harness.close() + } + + @MainActor + private final class Gate { + private var continuation: CheckedContinuation? + private var openState = false + private(set) var arrived = false + + func wait() async { + arrived = true + guard !openState else { return } + await withCheckedContinuation { continuation = $0 } + } + + func open() { + openState = true + continuation?.resume() + continuation = nil + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/GatedContactService.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/GatedContactService.swift new file mode 100644 index 0000000000..ead0cbe4e6 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/GatedContactService.swift @@ -0,0 +1,32 @@ +import Foundation +@testable import MC1Services + +/// Holds a contact sync open while a test exercises another sync path. +actor GatedContactService: ContactServiceProtocol { + private var hasStarted = false + private var startWaiters: [CheckedContinuation] = [] + private var gate: CheckedContinuation? + private var isReleased = false + + func waitForSyncStart() async { + if hasStarted { return } + await withCheckedContinuation { startWaiters.append($0) } + } + + func release() { + isReleased = true + gate?.resume() + gate = nil + } + + func syncContacts(radioID _: UUID, since _: Date?) async throws -> ContactSyncResult { + hasStarted = true + while !startWaiters.isEmpty { + startWaiters.removeFirst().resume() + } + if !isReleased { + await withCheckedContinuation { gate = $0 } + } + return ContactSyncResult(contactsReceived: 0, lastSyncTimestamp: 0, isIncremental: true) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/HydratedChannelSendHarness.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/HydratedChannelSendHarness.swift new file mode 100644 index 0000000000..2e51313340 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/HydratedChannelSendHarness.swift @@ -0,0 +1,76 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +@MainActor +final class HydratedChannelSendHarness { + static let secretA = Data(repeating: 0xAA, count: 16) + static let secretB = Data(repeating: 0xBB, count: 16) + let store: PersistenceStore + let radio: ConnectionTestRadioTransport + let session: MeshCoreSession + let channelService: ChannelService + let queue: ChatSendQueueService + let message: MessageDTO + let radioID: UUID + + private init( + store: PersistenceStore, radio: ConnectionTestRadioTransport, session: MeshCoreSession, + channelService: ChannelService, queue: ChatSendQueueService, message: MessageDTO, radioID: UUID + ) { + self.store = store + self.radio = radio + self.session = session + self.channelService = channelService + self.queue = queue + self.message = message + self.radioID = radioID + } + + static func make() async throws -> HydratedChannelSendHarness { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radio = ConnectionTestRadioTransport() + let session = MeshCoreSession( + transport: radio, configuration: SessionConfiguration(defaultTimeout: 2) + ) + try await session.start() + let saved = DeviceDTO.testDevice(publicKey: radio.publicKey) + try await store.saveDevice(saved) + let message = try await seed(store: store, radioID: saved.radioID) + await radio.setChannel(index: 0, name: "Original", secret: secretA) + let channelService = ChannelService(session: session, dataStore: store, rxLogService: nil) + let queue = ChatSendQueueService( + radioID: saved.radioID, dataStore: store, + messageService: MessageService(session: session, dataStore: store, contactService: nil), + channelService: channelService, + reactionService: ReactionService() + ) + return HydratedChannelSendHarness( + store: store, radio: radio, session: session, channelService: channelService, + queue: queue, message: message, radioID: saved.radioID + ) + } + + static func seed(store: PersistenceStore, radioID: UUID) async throws -> MessageDTO { + try await store.saveChannel(ChannelDTO.testChannel(radioID: radioID, secret: secretA)) + let message = MessageDTO.testChannelMessage(radioID: radioID, text: "Only for channel A", status: .pending) + try await store.saveMessage(message) + let envelope = ChannelMessageEnvelope( + messageID: message.id, channelIndex: 0, isResend: false, + messageText: message.text, messageTimestamp: message.timestamp, localNodeName: nil + ) + _ = try await store.insertPendingSendAssigningSequence(PendingSendDTO(envelope: envelope, radioID: radioID)) + return message + } + + var sendFrames: [Data] { + get async { await radio.sentData.filter { $0.first == CommandCode.sendChannelMessage.rawValue } } + } + + func close() async { + await radio.releaseAllGates() + await queue.shutdown() + await session.stop() + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/IdentityRecoveryFixture.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/IdentityRecoveryFixture.swift new file mode 100644 index 0000000000..d1560cec61 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/IdentityRecoveryFixture.swift @@ -0,0 +1,59 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@MainActor +enum IdentityRecoveryFixture { + static func interrupt(_ harness: ConnectionRadioHandoffHarness) async throws -> IdentityImportRecovery { + let source = try #require(harness.manager.services) + let radio = harness.manager.currentTransportType == .wifi ? harness.wifi : harness.bluetooth + await radio.holdReplies(for: .importPrivateKey) + let importing = harness.track(Task { + try await source.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + }) + try await waitUntil("initial private-key submission should reach its held response") { + await radio.sentData.contains { $0.first == CommandCode.importPrivateKey.rawValue } + } + await radio.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + await radio.setSendError(MeshTransportError.notConnected) + await radio.releaseReplies(for: .importPrivateKey) + _ = await importing.result + await radio.setSendError(nil) + return try #require(harness.manager.identityImportRecoveries.first) + } + + static func keyWriteCount(_ harness: ConnectionRadioHandoffHarness) async -> Int { + let bluetooth = await harness.bluetooth.sentData.filter { $0.first == CommandCode.importPrivateKey.rawValue }.count + let wifi = await harness.wifi.sentData.filter { $0.first == CommandCode.importPrivateKey.rawValue }.count + return bluetooth + wifi + } + + static func connectCount(_ harness: ConnectionRadioHandoffHarness) async -> Int { + let bluetooth = await harness.bluetooth.connectCount + let wifi = await harness.wifi.connectCount + return bluetooth + wifi + } + + @MainActor + final class Gate { + var arrived = false + private var opened = false + private var continuation: CheckedContinuation? + + func wait() async { + arrived = true + guard !opened else { return } + await withCheckedContinuation { continuation = $0 } + } + + func open() { + opened = true + continuation?.resume() + continuation = nil + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/NativeConnectionPortHarness.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/NativeConnectionPortHarness.swift new file mode 100644 index 0000000000..1235437b59 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/NativeConnectionPortHarness.swift @@ -0,0 +1,51 @@ +import Foundation +@testable import MC1Services +import Testing + +@MainActor +final class NativeConnectionPortHarness { + let native = BLETransportHarness() + let machine: BLEStateMachine + let adapter: iOSBLETransport + let manager: ConnectionManager + private let suite = "test.native-connection-port.\(UUID())" + private let previousLogs = DebugLogBuffer.shared + private let bootstrap: DebugLogBuffer + private var buffers: [DebugLogBuffer] + + init() async throws { + let defaults = try #require(UserDefaults(suiteName: suite)) + machine = BLEStateMachine(centralManager: native.central) + adapter = iOSBLETransport(stateMachine: machine) + manager = try ConnectionManager( + modelContainer: PersistenceStore.createContainer(inMemory: true), defaults: defaults, + stateMachine: machine, transport: adapter + ) + bootstrap = DebugLogBuffer(dataStore: manager.persistenceStore) + buffers = [bootstrap] + DebugLogBuffer.shared = bootstrap + let bridge = await machine.delegateHandler + native.enableAutomaticCallbacks(bridge, onWrite: BLETransportHarness.emptyRadioFrames) + await manager.wireTransportHandlers() + } + + func remember(_ link: ConnectionLink) { + buffers.append(link.services.debugLogBuffer) + } + + func close() async { + manager.testConnectionSelectionHandler = nil + manager.onConnectionReady = nil + _ = await manager.disconnect(reason: .userInitiated) + await manager.retirementTask?.value + await manager.metadataCommitTask?.value + await machine.shutdown() + for buffer in buffers { + await buffer.shutdown() + } + if let current = DebugLogBuffer.shared, buffers.contains(where: { $0 === current }) { + DebugLogBuffer.shared = previousLogs + } + UserDefaults().removePersistentDomain(forName: suite) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/NodeStatusSnapshotDTO+Testing.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/NodeStatusSnapshotDTO+Testing.swift index ff3e4c7b65..d14aafc8e5 100644 --- a/MC1Services/Tests/MC1ServicesTests/Helpers/NodeStatusSnapshotDTO+Testing.swift +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/NodeStatusSnapshotDTO+Testing.swift @@ -12,6 +12,7 @@ extension NodeStatusSnapshotDTO { id: UUID = UUID(), timestamp: Date = Date(), nodePublicKey: Data = Data(repeating: 0xDD, count: 32), + selfRadioID: UUID? = nil, batteryMillivolts: UInt16? = 3800, lastSNR: Double? = 9.0, lastRSSI: Int16? = -85, @@ -37,6 +38,7 @@ extension NodeStatusSnapshotDTO { id: id, timestamp: timestamp, nodePublicKey: nodePublicKey, + selfRadioID: selfRadioID, batteryMillivolts: batteryMillivolts, lastSNR: lastSNR, lastRSSI: lastRSSI, diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/PlatformRemovalTestHarness.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/PlatformRemovalTestHarness.swift new file mode 100644 index 0000000000..cc743f6b2f --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/PlatformRemovalTestHarness.swift @@ -0,0 +1,103 @@ +#if canImport(UIKit) + import AccessorySetupKit +#endif +import Foundation +@testable import MC1Services +import Testing + +@MainActor +final class PlatformRemovalTestHarness { + @MainActor + final class Gate { + private(set) var entered = false + private var continuation: CheckedContinuation? + private var isOpen = false + + func wait() async { + entered = true + guard !isOpen else { return } + await withCheckedContinuation { continuation = $0 } + } + + func open() { + isOpen = true + continuation?.resume() + continuation = nil + } + } + + static let publicKey = Data(repeating: 0x73, count: 32) + static let wifi = ConnectionMethod.wifi(host: "radio.test", port: 5123, displayName: nil) + let deviceID = UUID() + let radioID = UUID() + let manager: ConnectionManager + let stateMachine = MockBLEStateMachine() + let radio = ConnectionTestRadioTransport(publicKey: PlatformRemovalTestHarness.publicKey) + let ask = MockAccessorySetupKitService() + let defaults: UserDefaults + private let suiteName = "test.platform-removal.\(UUID().uuidString)" + + init(hasSystemRegistry: Bool) throws { + defaults = try #require(UserDefaults(suiteName: suiteName)) + let container = try PersistenceStore.createContainer(inMemory: true) + ask.isSessionActive = false + let pairing: any DevicePairingService = hasSystemRegistry + ? AccessorySetupPairingService(accessorySetupKit: ask) : BluetoothScanPairingService() + manager = ConnectionManager( + modelContainer: container, defaults: defaults, stateMachine: stateMachine, + transport: radio, pairing: pairing + ) + } + + func saveDevice(hasWiFi: Bool) async throws -> DeviceDTO { + let saved = DeviceDTO.testDevice(id: deviceID, radioID: radioID, publicKey: Self.publicKey, isActive: false).copy { + let bluetooth = ConnectionMethod.bluetooth(peripheralUUID: $0.id, displayName: nil) + $0.connectionMethods = hasWiFi ? [bluetooth, Self.wifi] : [bluetooth] + } + try await manager.persistenceStore.saveDevice(saved) + manager.persistConnection(deviceID: saved.id, radioID: saved.radioID, deviceName: saved.nodeName) + return saved + } + + func failConnection() async throws -> UUID { + await manager.wireTransportHandlers() + await radio.setConnectError(BLEError.authenticationFailed) + do { + _ = try await manager.connect(to: deviceID, forceReconnect: true) + Issue.record("The saved Bluetooth association must fail authentication") + throw ConnectionError.notConnected + } catch let failure as ConnectionRequestFailure { + #expect(manager.isCurrent(failure)) + guard case BLEError.authenticationFailed = failure.underlying else { throw failure } + #expect(await radio.connectCount == 1) + #expect(manager.connectionState == .disconnected) + return failure.requestID + } + } + + func seedBondVerification() async { + await stateMachine.recordBondVerification(deviceID: deviceID, at: Date()) + LastConnectionStore(defaults: defaults).persistBondVerification(deviceID: deviceID) + } + + func registerAccessory() { + ask.setPairedAccessories([ASAccessory(bluetoothIdentifier: deviceID, displayName: "Saved radio")]) + } + + func requireRemoved(_ result: ConnectionRemovalResult) throws -> ConnectionLossReceipt { + guard case let .removed(receipt) = result else { + Issue.record("Removal of the current failed request must complete") + throw ConnectionError.notConnected + } + #expect(manager.isCurrent(receipt)) + return receipt + } + + func close() async { + await radio.releaseAllGates() + _ = await manager.disconnect() + await manager.retirementTask?.value + await manager.metadataCommitTask?.value + defaults.removePersistentDomain(forName: suiteName) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/RadioWiFiFirmware.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/RadioWiFiFirmware.swift new file mode 100644 index 0000000000..a9ea89e680 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/RadioWiFiFirmware.swift @@ -0,0 +1,78 @@ +import Foundation + +/// Models saved WiFi overrides separately from build defaults and the boot-time association. +struct RadioWiFiFirmware: Sendable { + var savedSSID = "" + var savedPassword = "" + var enabled = true + let defaultSSID: String + let defaultPassword: String + private var associatedSSID = "" + private var associatedPassword = "" + + init(defaultSSID: String = "", defaultPassword: String = "") { + self.defaultSSID = defaultSSID + self.defaultPassword = defaultPassword + boot() + } + + mutating func boot() { + associatedSSID = enabled ? reportedSSID : "" + associatedPassword = savedSSID.isEmpty ? defaultPassword : savedPassword + } + + func bootUses(ssid: String, password: String) -> Bool { + associatedSSID == ssid && associatedPassword == password + } + + static func reflectedReply(_ reply: String, to command: String) -> String { + let bytes = Array(command.utf8.drop(while: { $0 == 0x20 })) + let prefix = bytes.count > 4 && bytes[2] == 0x7C ? String(decoding: bytes.prefix(3), as: UTF8.self) : "" + return prefix + reply + } + + mutating func reply(to command: String) -> String? { + var bytes = Array(command.utf8.drop(while: { $0 == 0x20 })) + if bytes.count > 4, bytes[2] == 0x7C { bytes.removeFirst(3) } + let effective = String(decoding: bytes, as: UTF8.self) + return Self.reflectedReply(replyToEffectiveCommand(effective) ?? "Unknown command", to: command) + } + + private mutating func replyToEffectiveCommand(_ command: String) -> String? { + switch command { + case "get wifi.enabled": + return enabled ? "> 1" : "> 0" + case "get wifi.ssid": + return reportedSSID.isEmpty ? "> (not set)" : "> \(reportedSSID)" + case "get wifi.pwd": + return "> \(savedPassword)" + case "get wifi.status": + return associatedSSID.isEmpty ? "> disconnected" : "> connected" + case "get wifi.ip": + return associatedSSID.isEmpty ? "> (not connected)" : "> 10.0.0.8" + case "set wifi.clear": + savedSSID = "" + savedPassword = "" + return "> wifi config cleared (reboot to apply)" + default: + break + } + if command.hasPrefix("set wifi.ssid ") { + savedSSID = String(command.dropFirst("set wifi.ssid ".count)) + return "> wifi.ssid updated (reboot to apply)" + } + if command.hasPrefix("set wifi.pwd ") { + savedPassword = String(command.dropFirst("set wifi.pwd ".count)) + return "> wifi.pwd updated (reboot to apply)" + } + if command.hasPrefix("set wifi.enabled ") { + enabled = command.dropFirst("set wifi.enabled ".count) != "0" + return "> wifi.enabled updated (reboot to apply)" + } + return nil + } + + private var reportedSSID: String { + savedSSID.isEmpty ? defaultSSID : savedSSID + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/RetirementBLEManagerHarness.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/RetirementBLEManagerHarness.swift new file mode 100644 index 0000000000..2c6e75527f --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/RetirementBLEManagerHarness.swift @@ -0,0 +1,140 @@ +@preconcurrency import CoreBluetooth +import Foundation +@testable import MC1Services +@testable import MeshCore +import Synchronization +import Testing + +@MainActor +final class RetirementBLEManagerHarness { + let ble: BLESetupRetirementHarness + let wire: ConnectionTestRadioTransport + let wifi = ConnectionTestRadioTransport(publicKey: Data(repeating: 0xB2, count: 32)) + let manager: ConnectionManager + private let bridge: Bridge + private let suite: String + + private init(ble: BLESetupRetirementHarness, maxChannels: UInt8) throws { + self.ble = ble + wire = ConnectionTestRadioTransport(maxChannels: maxChannels) + suite = "test.manager-ble-retirement.\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suite)) + let store = try PersistenceStore.createContainer(inMemory: true) + let pairing = MockAccessorySetupKitService() + pairing.isSessionActive = false + let wifi = wifi + manager = ConnectionManager( + modelContainer: store, defaults: defaults, stateMachine: ble.machine, + transport: ble.adapter, pairing: AccessorySetupPairingService(accessorySetupKit: pairing), + makeWiFiTransport: { wifi } + ) + manager.otherAppWaitStrategyOverride = { _ in false } + bridge = Bridge(wire: wire, complete: { await ble.completeWrite() }, inject: { await ble.inject($0) }) + } + + static func make(maxChannels: UInt8 = 1) async throws -> RetirementBLEManagerHarness { + let fixture = try await RetirementBLEManagerHarness(ble: BLESetupRetirementHarness.make(), maxChannels: maxChannels) + await fixture.wire.setDeviceID(fixture.ble.peripheral.identifier) + try await fixture.bridge.start() + fixture.installWriteHandler(backpressureAfterChannelIndex: nil) + return fixture + } + + func installWriteHandler(backpressureAfterChannelIndex: UInt8?) { + let bridge = bridge + let native = ble.native + let submit: @Sendable (Data) -> Void = { data in + if data.first == CommandCode.importPrivateKey.rawValue { + native.isReadyToWrite = true + } + bridge.submit(data) + } + native.setWriteHandler { data in + if let backpressureAfterChannelIndex, + data.first == CommandCode.getChannel.rawValue, data.dropFirst().first == backpressureAfterChannelIndex { + native.isReadyToWrite = false + native.setWriteHandler(submit) + } + submit(data) + } + } + + func connect() async throws { + let machine = ble.machine + let connect = Task { + try await manager.connect(to: ble.peripheral.identifier, forceFullSync: true, forceReconnect: true) + } + do { + try await ble.awaitCondition { await machine.currentPhase.name == "connecting" } + await ble.finishDiscovery() + _ = try await connect.value + } catch { + await ble.machine.shutdown() + _ = await connect.result + throw error + } + } + + func close() async { + await wire.releaseAllGates() + await wifi.releaseAllGates() + ble.native.isReadyToWrite = true + _ = await manager.disconnect(reason: .userInitiated) + await manager.retirementTask?.value + await manager.metadataCommitTask?.value + ble.native.setWriteHandler(nil) + await ble.machine.shutdown() + await bridge.stop() + defaultsCleanup() + } + + private func defaultsCleanup() { + UserDefaults().removePersistentDomain(forName: suite) + } + + private final class Bridge: Sendable { + private let wire: ConnectionTestRadioTransport + private let complete: @Sendable () async -> Void + private let inject: @Sendable (Data) async -> Void + private let workers = Mutex<[Task]>([]) + private let receive = Mutex?>(nil) + + init(wire: ConnectionTestRadioTransport, complete: @escaping @Sendable () async -> Void, + inject: @escaping @Sendable (Data) async -> Void) { + self.wire = wire + self.complete = complete + self.inject = inject + } + + func start() async throws { + try await wire.connect() + let stream = await wire.receivedData + let task = Task { [inject] in + for await packet in stream { + await inject(packet) + } + } + receive.withLock { $0 = task } + } + + func submit(_ data: Data) { + let task = Task { [wire, complete] in + await complete() + try? await wire.send(data) + } + workers.withLock { $0.append(task) } + } + + func stop() async { + await wire.releaseAllGates() + let active = workers.withLock { value in defer { value.removeAll() }; return value } + for worker in active { + await worker.value + } + await wire.disconnect() + let task = receive.withLock { value in defer { value = nil }; return value } + task?.cancel() + await task?.value + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/TestPolling.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/TestPolling.swift index 68e37d91e7..c783f199a2 100644 --- a/MC1Services/Tests/MC1ServicesTests/Helpers/TestPolling.swift +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/TestPolling.swift @@ -1,4 +1,7 @@ import Foundation +@testable import MeshCore +import MeshCoreTestSupport +import os /// Polls a condition at short intervals until it returns `true` or a timeout expires. /// Replaces fixed `Task.sleep` calls in tests where we wait for an asynchronous state change. @@ -12,16 +15,123 @@ func waitUntil( timeout: Duration = .seconds(10), pollingInterval: Duration = .milliseconds(10), _ message: String = "waitUntil timed out", - condition: @escaping @MainActor () async -> Bool + condition: @escaping @MainActor () async throws -> Bool ) async throws { let deadline = ContinuousClock.now + timeout while ContinuousClock.now < deadline { - if await condition() { return } + if try await condition() { return } try await Task.sleep(for: pollingInterval) } - if await condition() { return } + if try await condition() { return } struct WaitTimeoutError: Error, CustomStringConvertible { let description: String } throw WaitTimeoutError(description: message) } + +struct SessionClockObservation: Sendable { + var channelInfosDispatched: Int + var channelInfosYielded: Int + var sentACommand: Bool + var latestResponse: Data? +} + +func sessionClockObservation( + radio: ConnectionTestRadioTransport, + session: MeshCoreSession? +) async -> SessionClockObservation { + let exchange = await radio.latestCommandExchange() + return await SessionClockObservation( + channelInfosDispatched: session?.dispatchedChannelInfoCountForTest ?? 0, + channelInfosYielded: radio.yieldedChannelInfoCount, + sentACommand: exchange.sent, + latestResponse: exchange.response + ) +} + +/// Polls like `waitUntil`, and lets each production timeout elapse on `clock` as soon as it parks. +func waitUntilClockAdvances( + _ clock: TestClock, + timeout: Duration = .seconds(5), + _ message: String = "waitUntil timed out", + _ condition: @escaping @MainActor () async throws -> Bool +) async throws { + try await waitUntil(timeout: timeout, message) { + if clock.sleeperCount > 0 { clock.advanceToNextSleep() } + return try await condition() + } +} + +/// Lets a parked production timeout elapse when its reply can no longer succeed. +/// The channel pipeline's idle sleep waits until every yielded channelInfo has been dispatched. +func advanceParkedMatchedSessionClock( + _ clock: TestClock, + timeout: Duration = .seconds(30), + _ message: String = "clocked session work should finish", + observation: @escaping @MainActor () async -> SessionClockObservation, + until finished: @escaping @MainActor () async -> Bool +) async throws { + try await waitUntil(timeout: timeout, message) { + await advanceElapsedSessionTimeout(clock, observation: observation()) + return await finished() + } +} + +func resultAdvancingMatchedSessionClock( + _ clock: TestClock, + timeout: Duration = .seconds(30), + observation: @escaping @MainActor () async -> SessionClockObservation, + _ work: @escaping @MainActor @Sendable () async throws -> T +) async throws -> T { + let slot = OSAllocatedUnfairLock?>(initialState: nil) + let task = Task { @MainActor in + let outcome: Result + do { outcome = try await .success(work()) } catch { outcome = .failure(error) } + slot.withLock { $0 = outcome } + } + try await advanceParkedMatchedSessionClock(clock, timeout: timeout, observation: observation) { + slot.withLock { $0 != nil } + } + task.cancel() + return try slot.withLock { try $0!.get() } +} + +private func advanceElapsedSessionTimeout(_ clock: TestClock, observation: SessionClockObservation) { + guard clock.sleeperCount > 0, let parked = clock.nextSleepDuration else { return } + let configuration = SessionConfiguration.default + let grace = Duration.seconds(configuration.channelPipelinePostDrainGrace) + if parked <= grace + .milliseconds(20) { + clock.advanceToNextSleep() + return + } + if durationsAreClose(parked, .seconds(configuration.channelPipelineIdleTimeout)) + || durationsAreClose(parked, .seconds(configuration.channelPipelineHardTimeout)) { + if observation.channelInfosDispatched >= observation.channelInfosYielded { + clock.advanceToNextSleep() + } + return + } + if durationsAreClose(parked, .seconds(configuration.contactStreamInactivityTimeout)) + || durationsAreClose(parked, .seconds(configuration.contactStreamHardTimeout)) { + return + } + let unmatched = observation.sentACommand + && (observation.latestResponse == nil || observation.latestResponse?.first == ResponseCode.error.rawValue) + if unmatched { + clock.advanceToNextSleep() + } +} + +func advancePowerOffWindowIfParked(_ clock: TestClock) { + guard clock.sleeperCount > 0, let parked = clock.nextSleepDuration else { return } + let grace = Duration.seconds(MeshCoreSession.powerOffBufferedReplyGrace) + let window = Duration.seconds(MeshCoreSession.powerOffReplyWindow) + if parked <= grace + .milliseconds(20) || durationsAreClose(parked, window) { + clock.advanceToNextSleep() + } +} + +private func durationsAreClose(_ parked: Duration, _ target: Duration, tolerance: Duration = .milliseconds(50)) -> Bool { + let delta = parked > target ? parked - target : target - parked + return delta <= tolerance +} diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/WatchdogDeferralFixture.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/WatchdogDeferralFixture.swift new file mode 100644 index 0000000000..e6ba7e2df8 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/WatchdogDeferralFixture.swift @@ -0,0 +1,140 @@ +import Foundation +@testable import MC1Services +import MeshCoreTestSupport +import Testing + +@MainActor +final class WatchdogDeferralFixture { + static let initialDelay: Duration = .seconds(30) + static let laterTime: Duration = .seconds(600) + static let observationTimeout: Duration = .seconds(3) + + let clock = TestClock() + let pairing = BluetoothScanPairingService() + let radio = ConnectionTestRadioTransport() + let deviceID = UUID() + let manager: ConnectionManager + private let defaults: UserDefaults + private let suite = "test.watchdog-deferral.\(UUID().uuidString)" + private var discovery: Task? + private var watchdogs: [Task] = [] + private var lifecycleEvents: [BLELifecycleEvent] = [] + private var states: [DeviceConnectionState] = [] + private var stateObserver: Task? + + init() throws { + defaults = try #require(UserDefaults(suiteName: suite)) + manager = try ConnectionManager( + modelContainer: PersistenceStore.createContainer(inMemory: true), defaults: defaults, + stateMachine: MockBLEStateMachine(), transport: radio, pairing: pairing, reconnectionClock: clock + ) + manager.testBLELifecycleEventHandled = { [weak self] event in self?.lifecycleEvents.append(event) } + } + + func connect() async throws { + await manager.wireTransportHandlers() + let result = try await manager.connect(to: deviceID, forceFullSync: true, forceReconnect: true) + try #require(manager.isCurrent(result)) + try #require(manager.connectionState == .ready) + #expect(await radio.connectCount == 1) + let stream = manager.connectionStateEvents.subscribe() + stateObserver = Task { [weak self] in + for await state in stream { + self?.states.append(state) + } + } + } + + func openDiscovery() async throws { + discovery = Task { try await self.manager.pairNewDevice() } + try await waitUntil(timeout: Self.observationTimeout, "the real picker must await a choice") { + self.pairing.isPresenting + } + try #require(manager.isPairingInProgress) + } + + func cancelDiscovery(cancelTask: Bool) async throws { + let task = try #require(discovery) + if cancelTask { task.cancel() } else { pairing.cancel() } + do { + _ = try await task.value + Issue.record("Cancelled discovery must throw the platform cancellation") + } catch DevicePairingError.cancelled {} + discovery = nil + } + + func loseConnection() async throws -> Task { + let origin = try #require(await radio.lifecycleOrigin) + await radio.simulateRemoteLoss() + try await waitUntil(timeout: Self.observationTimeout, "real link loss must arm and park recovery") { + self.manager.connectionState == .disconnected && self.manager.connectionTeardownCount == 0 + && self.manager.isReconnectionWatchdogRunning && self.clock.sleeperCount == 1 + } + let watchdog = try #require(manager.reconnectionWatchdogTask) + watchdogs.append(watchdog) + #expect(lifecycleEvents.contains { event in + guard case .remoteLinkLost = event else { return false } + return event.origin.deviceID == origin.deviceID && event.origin.generation == origin.generation + }) + #expect(lifecycleEvents.contains { event in + guard case .disconnected = event else { return false } + return event.origin.deviceID == origin.deviceID && event.origin.generation == origin.generation + }) + return watchdog + } + + func requireReady() async throws { + try await waitUntil(timeout: Self.observationTimeout, "a later retry must install a usable session") { + self.manager.connectionState == .ready + } + try #require(manager.installedLink?.resource.binding.isActive == true) + } + + func expectStates(_ expected: [DeviceConnectionState]) async throws { + try await waitUntil(timeout: Self.observationTimeout, "state publications must be observed") { + self.states.count >= expected.count + } + #expect(states == expected) + } + + func finishAndExpectStates(_ expected: [DeviceConnectionState]) async { + manager.connectionStateEvents.finish() + await stateObserver?.value + #expect(states == expected) + } + + func close() async { + pairing.cancel() + discovery?.cancel() + _ = await discovery?.result + discovery = nil + if let watchdog = manager.reconnectionWatchdogTask { watchdogs.append(watchdog) } + await radio.releaseAllGates() + let worker = manager.desiredRequest?.worker + await manager.disconnect() + _ = await worker?.result + for watchdog in watchdogs { + await watchdog.value + } + await manager.retirementTask?.value + await manager.metadataCommitTask?.value + manager.connectionStateEvents.finish() + await stateObserver?.value + manager.testBLELifecycleEventHandled = nil + defaults.removePersistentDomain(forName: suite) + #expect(clock.sleeperCount == 0) + } +} + +@MainActor +func withWatchdogFixture(_ body: @MainActor (WatchdogDeferralFixture) async throws -> Void) async throws { + let fixture = try WatchdogDeferralFixture() + do { + try await fixture.connect() + try await body(fixture) + } catch { + await fixture.close() + throw error + } + await fixture.close() +} diff --git a/MC1Services/Tests/MC1ServicesTests/IdentityImportPrivateRuntimeTests.swift b/MC1Services/Tests/MC1ServicesTests/IdentityImportPrivateRuntimeTests.swift new file mode 100644 index 0000000000..556afcb48b --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/IdentityImportPrivateRuntimeTests.swift @@ -0,0 +1,211 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Identity import private runtime ownership") +@MainActor +struct IdentityImportPrivateRuntimeTests { + @Test(arguments: [false, true]) + func `actual WiFi receive loss revokes a private candidate before publication`(atSelection: Bool) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + _ = try await harness.manager.connectViaWiFi(host: "radio.local", port: 4242) + let sourceServices = harness.manager.services + let source = try #require(sourceServices) + await harness.wifi.setIdentityImportPublicKey(CanonicalIdentityFixture.publicKey) + let selection = IdentityRecoveryFixture.Gate() + defer { + selection.open() + harness.manager.testConnectionSelectionHandler = nil + } + if atSelection { + harness.manager.testConnectionSelectionHandler = { _ in await selection.wait() } + } else { + await harness.wifi.holdSubmissions(for: .setChannel) + } + let canonicalRadioID = harness.deviceB.radioID + var publishedCanonical = false + harness.manager.onConnectionReady = { snapshot in + if snapshot.device.radioID == canonicalRadioID { publishedCanonical = true } + } + let importing = harness.track(Task { + try await source.nodeConfigService.importConfig( + MeshCoreNodeConfig( + privateKey: CanonicalIdentityFixture.privateKeyHex, + channels: [.init(name: "Selected tail", secret: String(repeating: "CD", count: 16))] + ), sections: ConfigSections(nodeIdentity: true, channels: true), radioID: harness.deviceA.radioID + ) + }) + try await waitUntil("canonical WiFi preparation should reach its private boundary") { + if atSelection { return selection.arrived } + return await harness.wifi.submissionIsHeld(for: .setChannel) + } + let candidateAttempt = harness.manager.desiredRequest?.attempt + let candidate = try #require(candidateAttempt) + let unpublishedBeforeLoss = harness.manager.currentConnection == nil + let activeBeforeLoss = candidate.binding.isActive + #expect(unpublishedBeforeLoss) + #expect(harness.manager.identityRebuildUnpublished) + #expect(activeBeforeLoss) + + await harness.wifi.simulateSocketReceiveLoss() + + let revokedByCallback = !candidate.binding.isActive + let unpublishedAfterLoss = harness.manager.currentConnection == nil + #expect(revokedByCallback) + #expect(unpublishedAfterLoss) + selection.open() + await harness.wifi.releaseSubmissions(for: .setChannel) + let result = await importing.result + let failed = if case .failure = result { true } else { false } + let stillUnpublished = harness.manager.currentConnection == nil + let disconnected = await !harness.wifi.isConnected + let candidateRetired = candidate.preparedServices?.isAcceptingRuntimeWork == false + let frames = await harness.wifi.sentData + let keyIndex = frames.firstIndex { $0.first == CommandCode.importPrivateKey.rawValue } + let index = try #require(keyIndex) + let ordinaryWorkSuppressed = !frames.suffix(from: index).contains { + $0.first == CommandCode.getChannel.rawValue || $0.first == CommandCode.getMessage.rawValue || + $0.first == CommandCode.sendChannelMessage.rawValue + } + let actualTailApplied = await harness.wifi.channelWriteIndices == (atSelection ? [0] : []) + #expect(failed) + #expect(stillUnpublished) + #expect(!harness.manager.identityRebuildUnpublished) + #expect(disconnected) + #expect(candidateRetired) + #expect(!publishedCanonical) + #expect(ordinaryWorkSuppressed) + #expect(actualTailApplied) + + harness.manager.testConnectionSelectionHandler = nil + _ = try await harness.manager.connectViaWiFi(host: "radio.local", port: 4242) + let replacementReady = harness.manager.connectionState == .ready + let laterIOWorks = try await harness.manager.services?.settingsService.getTime() != nil + #expect(replacementReady) + #expect(laterIOWorks) + } + } + + @Test(arguments: [false, true]) + func `late imported setup completion cannot disconnect the next BLE attempt in the same request`( + explicitRecovery: Bool + ) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await harness.connectBluetooth() + await harness.manager.wireTransportHandlers() + let sourceServices = harness.manager.services + let source = try #require(sourceServices) + let recovery: IdentityImportRecovery? = if explicitRecovery { try await IdentityRecoveryFixture.interrupt(harness) } else { nil } + await harness.bluetooth.setIdentityImportPublicKey(CanonicalIdentityFixture.publicKey) + let setup = IdentityRecoveryFixture.Gate() + var completionHeld = false + var lossHandled = false + defer { + setup.open() + harness.manager.testBLELifecycleEventHandled = nil + harness.manager.testPostSetupResultHandler = nil + } + harness.manager.testPostSetupResultHandler = { _ in + guard !completionHeld else { return } + completionHeld = true + await setup.wait() + } + harness.manager.testBLELifecycleEventHandled = { event in + if case .autoReconnecting = event { lossHandled = true } + } + let importing = harness.track(Task { + if let recovery { + _ = try await harness.manager.retryIdentityImport(confirmation: recovery, privateKey: CanonicalIdentityFixture.privateKey) + } else { + try await source.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + } + }) + try await waitUntil("the imported Link should finish setup before its caller continuation") { setup.arrived } + let requestID = harness.manager.connectionRequestID + let importedGeneration = harness.manager.currentConnection?.generation + let oldAttempt = harness.manager.desiredRequest?.attempt + let old = try #require(oldAttempt) + await harness.bluetooth.simulateAutoReconnecting(deviceID: harness.deviceA.id) + try await waitUntil("native BLE loss should finish captured retirement") { lossHandled } + await harness.bluetooth.simulateReconnected() + try await waitUntil("same-request BLE recovery should install a new ready attempt") { + harness.manager.currentConnection?.generation != importedGeneration && harness.manager.connectionState == .ready + } + let successorSnapshot = harness.manager.currentConnection + let successor = try #require(successorSnapshot) + let nextAttempt = harness.manager.desiredRequest?.attempt + let next = try #require(nextAttempt) + let sameRequest = harness.manager.connectionRequestID == requestID + let distinctAttempt = next !== old + #expect(sameRequest) + #expect(distinctAttempt) + setup.open() + let result = await importing.result + let oldImportFailed = if case .failure = result { true } else { false } + let successorStillCurrent = harness.manager.isCurrent(successor) + let successorActive = next.binding.isActive + let requestStillCurrent = harness.manager.connectionRequestID == requestID + let laterIOWorks = try await harness.manager.services?.settingsService.getTime() != nil + #expect(oldImportFailed) + #expect(successorStillCurrent) + #expect(successorActive) + #expect(requestStillCurrent) + #expect(laterIOWorks) + } + } + + @Test(arguments: [false, true]) + func `ordinary and standalone setup hydrate before wiring even when initial contacts fail`(standalone: Bool) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + if standalone { try await harness.connectBluetooth() } + let sourceServices = harness.manager.services + let store = harness.manager.persistenceStore + let secret = Data(repeating: 0xCD, count: 16) + await harness.bluetooth.setChannel(index: 0, name: "Hydrated", secret: secret) + try await store.saveChannel(ChannelDTO.testChannel(radioID: harness.deviceA.radioID, name: "Hydrated", secret: secret)) + let message = MessageDTO.testChannelMessage( + radioID: harness.deviceA.radioID, text: "Retained before initial sync", status: .pending + ) + try await store.saveMessage(message) + let envelope = ChannelMessageEnvelope( + messageID: message.id, channelIndex: 0, isResend: false, messageText: message.text, + messageTimestamp: message.timestamp, localNodeName: "Hydration control" + ) + _ = try await store.insertPendingSendAssigningSequence(PendingSendDTO(envelope: envelope, radioID: harness.deviceA.radioID)) + await harness.bluetooth.rejectNext(.getContacts) + var hydratedBeforeWiring = false + harness.manager.onConnectionReady = { _ in + do { + try await waitUntil("hydrated work should enter its real send before initial sync") { + await (try? store.fetchMessage(id: message.id))?.status == .sent + } + hydratedBeforeWiring = true + } catch {} + } + if standalone { + let source = try #require(sourceServices) + await harness.bluetooth.setIdentityImportPublicKey(CanonicalIdentityFixture.publicKey) + _ = try await harness.manager.importIdentity( + CanonicalIdentityFixture.privateKey, expectedServices: source, deviceID: harness.deviceA.id + ) + } else { + _ = try await harness.manager.connect(to: harness.deviceA.id, forceReconnect: true) + } + let retainedWhileSyncing = harness.manager.connectionState == .syncing + let pendingSettled = try await store.fetchPendingSends(radioID: harness.deviceA.radioID).isEmpty + #expect(hydratedBeforeWiring) + #expect(retainedWhileSyncing) + #expect(pendingSettled) + try await waitUntil(timeout: .seconds(12), "ordinary retry should retain and recover the runtime") { + harness.manager.connectionState == .ready + } + let laterIOWorks = try await harness.manager.services?.settingsService.getTime() != nil + #expect(laterIOWorks) + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/IdentityImportResponseProvenanceTests.swift b/MC1Services/Tests/MC1ServicesTests/IdentityImportResponseProvenanceTests.swift new file mode 100644 index 0000000000..d114ce0962 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/IdentityImportResponseProvenanceTests.swift @@ -0,0 +1,111 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Identity import response provenance") +@MainActor +struct IdentityImportResponseProvenanceTests { + @Test(arguments: [false, true], [false, true]) + func `a generic reply past its actual timeout cannot acknowledge or reject identity import`( + oldReplyWasOK: Bool, cancelOrdinaryCaller: Bool + ) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await harness.connectBluetooth() + let source = try #require(harness.manager.installedLink) + let gate = Gate() + harness.manager.testIdentityBeforeAdmission = { await gate.wait() } + var importFinished = false + let importing = harness.track(Task { + defer { importFinished = true } + try await source.services.nodeConfigService.importConfig( + MeshCoreNodeConfig( + name: "Identity tail must not run", privateKey: CanonicalIdentityFixture.privateKeyHex, + channels: [.init(name: "Unattributed tail", secret: String(repeating: "AB", count: 16))] + ), + sections: ConfigSections(nodeIdentity: true, channels: true), radioID: harness.deviceA.radioID + ) + }) + do { + try await waitUntil("config preflight should reach identity admission") { gate.arrived } + await harness.bluetooth.setResponsePackets( + for: .setName, + packets: [oldReplyWasOK ? Data([ResponseCode.ok.rawValue]) : Data([ResponseCode.error.rawValue, 1])] + ) + await harness.bluetooth.holdReplies(for: .setName) + let ordinary = harness.track(Task { + let _: Bool = try await source.resource.session.sendAndWait( + PacketBuilder.setName("Earlier ordinary command"), matching: { event in + switch event { + case .ok, .error: true + default: nil + } + }, timeout: 0.05 + ) + }) + try await waitUntil("ordinary exchange must be physically submitted after preflight") { + await harness.bluetooth.sentData.contains { $0.first == CommandCode.setName.rawValue } + } + if cancelOrdinaryCaller { ordinary.cancel() } + _ = await ordinary.result + await source.resource.session.waitForQuiescence() + if oldReplyWasOK { await harness.bluetooth.rejectNext(.importPrivateKey) } + await harness.bluetooth.holdReplies(for: .importPrivateKey) + gate.open() + try await waitUntil("identity should either refuse uncertain history or submit its exchange") { + if importFinished { return true } + return await harness.bluetooth.sentData.contains { $0.first == CommandCode.importPrivateKey.rawValue } + } + await harness.bluetooth.releaseReplies(for: .setName) + await harness.bluetooth.releaseReplies(for: .importPrivateKey) + let result = await importing.result + if case .success = result { Issue.record("Unattributed generic response completed the identity import") } + let frames = await harness.bluetooth.sentData + let importWasNotSubmitted = !frames.contains { $0.first == CommandCode.importPrivateKey.rawValue } + let tailWasNotSubmitted = !frames.contains { $0.first == CommandCode.setChannel.rawValue } + let nameWriteCount = frames.filter { $0.first == CommandCode.setName.rawValue }.count + #expect(importWasNotSubmitted) + #expect(tailWasNotSubmitted) + #expect(nameWriteCount == 1) + #expect(try await harness.manager.persistenceStore.fetchDevice(id: harness.deviceA.id)?.publicKey == harness.deviceA.publicKey) + } catch { + gate.open() + await harness.bluetooth.releaseAllGates() + _ = await importing.result + harness.manager.testIdentityBeforeAdmission = nil + throw error + } + harness.manager.testIdentityBeforeAdmission = nil + _ = try await harness.manager.connect(to: harness.deviceA.id, forceReconnect: true) + let fresh = try #require(harness.manager.services) + await harness.bluetooth.rejectNext(.importPrivateKey, count: 0) + await harness.bluetooth.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + try await fresh.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + let keyWriteCount = await IdentityRecoveryFixture.keyWriteCount(harness) + #expect(keyWriteCount == 1) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } + + @MainActor + private final class Gate { + var arrived = false + private var opened = false + private var continuation: CheckedContinuation? + + func wait() async { + arrived = true + guard !opened else { return } + await withCheckedContinuation { continuation = $0 } + } + + func open() { + opened = true + continuation?.resume() + continuation = nil + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/IdentityImportRuntimeAdmissionTests.swift b/MC1Services/Tests/MC1ServicesTests/IdentityImportRuntimeAdmissionTests.swift new file mode 100644 index 0000000000..f4a092fbdd --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/IdentityImportRuntimeAdmissionTests.swift @@ -0,0 +1,274 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Identity import runtime admission") +@MainActor +struct IdentityImportRuntimeAdmissionTests { + @Test(arguments: [false, true], [false, true]) + func `foreground cannot restart the source during identity observation`( + hasGhost: Bool, holdBeforeCommit: Bool + ) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + harness.manager.testNotificationSystemOperations = .init( + setBadgeCount: { _ in }, deliveredRequests: { [] }, removeDeliveredNotifications: { _ in } + ) + if hasGhost { try await CanonicalIdentityFixture.prepareGhost(in: harness) } + try await harness.connectBluetooth() + await setPhysicallyConnected(harness) + let source = try #require(harness.manager.currentConnection) + let commitGate = IdentityRecoveryFixture.Gate() + defer { + commitGate.open() + harness.manager.testIdentityBeforeCommit = nil + } + await harness.bluetooth.setIdentityImportPublicKey(CanonicalIdentityFixture.publicKey) + if holdBeforeCommit { + harness.manager.testIdentityBeforeCommit = { await commitGate.wait() } + } else { + await harness.bluetooth.holdReplies(for: .appStart) + } + let importing = harness.track(Task { + try await source.services.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + }) + try await waitUntil("identity observation should reach the held production boundary") { + if holdBeforeCommit { return commitGate.arrived } + return await harness.bluetooth.heldReplyCount(for: .appStart) == 1 + } + let physicalStateConnected = await harness.stateMachine.isConnected + #expect(physicalStateConnected) + let physicalDeviceMatches = await harness.stateMachine.connectedDeviceID == harness.deviceA.id + #expect(physicalDeviceMatches) + let notAutoReconnecting = await harness.stateMachine.isAutoReconnecting == false + #expect(notAutoReconnecting) + let physicalTransportConnected = await harness.bluetooth.isConnected + #expect(physicalTransportConnected) + let sourceStillPublished = harness.manager.currentConnection?.generation == source.generation + #expect(sourceStillPublished) + let monitoringStopped = !source.services.isEventMonitoringActive + #expect(monitoringStopped) + let autoFetchStopped = await source.services.messagePollingService.isAutoFetching == false + #expect(autoFetchStopped) + let connectionsBeforeForeground = await harness.bluetooth.connectCount + let disconnectsBeforeForeground = await harness.bluetooth.disconnectCount + + await harness.manager.appDidEnterBackground() + await harness.manager.appDidBecomeActive() + + let restarted = source.services.isEventMonitoringActive + #expect(!restarted) + let autoFetchStopped2 = await source.services.messagePollingService.isAutoFetching == false + #expect(autoFetchStopped2) + let noForegroundConnect = await harness.bluetooth.connectCount == connectionsBeforeForeground + #expect(noForegroundConnect) + let noForegroundDisconnect = await harness.bluetooth.disconnectCount == disconnectsBeforeForeground + #expect(noForegroundDisconnect) + let sourceStillPublished2 = harness.manager.currentConnection?.generation == source.generation + #expect(sourceStillPublished2) + let advertKey = Data(repeating: 0xD7, count: ProtocolLimits.publicKeySize) + let events = await source.services.session.events() + let observed = harness.track(Task { + for await event in events { + if case let .newContact(contact) = event, contact.publicKey == advertKey { return } + } + }) + await harness.bluetooth.inject(newAdvertisement(key: advertKey)) + await observed.value + if restarted { + try await waitUntil("a restarted source must demonstrate its actual obsolete-partition effect") { + await (try? harness.manager.persistenceStore.fetchDiscoveredNodes(radioID: harness.deviceA.radioID) + .contains { $0.publicKey == advertKey }) == true + } + } + let sourceDiscovery = try await harness.manager.persistenceStore.fetchDiscoveredNodes(radioID: harness.deviceA.radioID) + .contains { $0.publicKey == advertKey } + #expect(!sourceDiscovery) + + commitGate.open() + await harness.bluetooth.releaseReplies(for: .appStart) + try await importing.value + let canonicalRadioID = hasGhost ? harness.deviceB.radioID : harness.deviceA.radioID + let canonicalPartitionPublished = harness.manager.connectedDevice?.radioID == canonicalRadioID + #expect(canonicalPartitionPublished) + let runtimeReady = harness.manager.connectionState == .ready + #expect(runtimeReady) + let laterAdvertKey = Data(repeating: 0xD8, count: ProtocolLimits.publicKeySize) + await harness.bluetooth.inject(newAdvertisement(key: laterAdvertKey)) + try await waitUntil("the replacement runtime should process later discovery") { + await (try? harness.manager.persistenceStore.fetchDiscoveredNodes(radioID: canonicalRadioID) + .contains { $0.publicKey == laterAdvertKey }) == true + } + if hasGhost { + let laterSourceDiscovery = try await harness.manager.persistenceStore.fetchDiscoveredNodes(radioID: harness.deviceA.radioID) + .contains { $0.publicKey == laterAdvertKey } + #expect(!laterSourceDiscovery) + } + let laterIOWorks = try await harness.manager.services?.settingsService.getTime() != nil + #expect(laterIOWorks) + } + } + + @Test + func `foreground still repairs an ordinary stopped runtime on its connected transport`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await harness.connectBluetooth() + await setPhysicallyConnected(harness) + let source = try #require(harness.manager.currentConnection) + await source.services.stopEventMonitoring() + let monitoringStopped2 = !source.services.isEventMonitoringActive + #expect(monitoringStopped2) + let autoFetchStopped3 = await source.services.messagePollingService.isAutoFetching == false + #expect(autoFetchStopped3) + + await harness.manager.appDidBecomeActive() + + let sourceStillPublished3 = harness.manager.currentConnection?.generation == source.generation + #expect(sourceStillPublished3) + let monitoringActive = source.services.isEventMonitoringActive + #expect(monitoringActive) + let autoFetchActive = await source.services.messagePollingService.isAutoFetching + #expect(autoFetchActive) + let repairedIOWorks = try await source.services.settingsService.getTime().timeIntervalSince1970 > 0 + #expect(repairedIOWorks) + } + } + + private func setPhysicallyConnected(_ harness: ConnectionRadioHandoffHarness) async { + await harness.stateMachine.setStubbedIsConnected(true) + await harness.stateMachine.setStubbedConnectedDeviceID(harness.deviceA.id) + await harness.stateMachine.setStubbedIsAutoReconnecting(false) + } + + @Test + func `identity waits for an already-entered listener repair before its key write`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await harness.connectBluetooth() + await setPhysicallyConnected(harness) + let sourceSnapshot = harness.manager.currentConnection + let source = try #require(sourceSnapshot) + await source.services.stopEventMonitoring() + let repairGate = IdentityRecoveryFixture.Gate() + defer { + repairGate.open() + harness.manager.testMessageListenerRepairHandler = nil + } + harness.manager.testMessageListenerRepairHandler = { _ in await repairGate.wait() } + let repairing = harness.track(Task { await harness.manager.appDidBecomeActive() }) + try await waitUntil("ordinary repair should reach its direct auto-fetch admission") { repairGate.arrived } + await harness.bluetooth.setIdentityImportPublicKey(CanonicalIdentityFixture.publicKey) + let importing = harness.track(Task { + try await source.services.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + }) + try await waitUntil("identity preparation should close the source while repair remains entered") { + !source.services.isAcceptingRuntimeWork + } + let beforeRelease = await harness.bluetooth.sentData + let keyNotSubmitted = !beforeRelease.contains { $0.first == CommandCode.importPrivateKey.rawValue } + #expect(keyNotSubmitted) + repairGate.open() + await repairing.value + try await importing.value + let sourceMonitoringStopped = !source.services.isEventMonitoringActive + let sourceFetchingStopped = await !source.services.messagePollingService.isAutoFetching + let laterIOWorks = try await harness.manager.services?.settingsService.getTime() != nil + #expect(sourceMonitoringStopped) + #expect(sourceFetchingStopped) + #expect(laterIOWorks) + } + } + + @Test + func `identity joins monitoring startup already entered by connected foreground repair`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await harness.connectBluetooth() + await setPhysicallyConnected(harness) + let sourceSnapshot = harness.manager.currentConnection + let source = try #require(sourceSnapshot) + await source.services.stopEventMonitoring() + let startup = IdentityRecoveryFixture.Gate() + defer { + startup.open() + source.services.testEventMonitoringStartHandler = nil + } + source.services.testEventMonitoringStartHandler = { await startup.wait() } + let repairing = harness.track(Task { await harness.manager.appDidBecomeActive() }) + try await waitUntil("foreground repair should enter monitoring startup") { startup.arrived } + await harness.bluetooth.setIdentityImportPublicKey(CanonicalIdentityFixture.publicKey) + let importing = harness.track(Task { + try await source.services.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + }) + try await waitUntil("identity preparation should close the entered startup") { + !source.services.isAcceptingRuntimeWork + } + let frames = await harness.bluetooth.sentData + let keyNotSubmitted = !frames.contains { $0.first == CommandCode.importPrivateKey.rawValue } + #expect(keyNotSubmitted) + startup.open() + await repairing.value + try await importing.value + await source.services.startEventMonitoring(radioID: harness.deviceA.radioID) + let sourceMonitoringStopped = !source.services.isEventMonitoringActive + let sourceFetchingStopped = await !source.services.messagePollingService.isAutoFetching + let sourceAckWorkerStopped = await !source.services.messageService.isAckExpiryCheckingActive + let ready = harness.manager.connectionState == .ready + let laterIOWorks = try await harness.manager.services?.settingsService.getTime() != nil + #expect(sourceMonitoringStopped) + #expect(sourceFetchingStopped) + #expect(sourceAckWorkerStopped) + #expect(ready) + #expect(laterIOWorks) + } + } + + @Test(arguments: [false, true]) + func `identity-only entry points still activate ordinary setup`(standalone: Bool) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await harness.connectBluetooth() + let sourceServices = harness.manager.services + let source = try #require(sourceServices) + await harness.bluetooth.setIdentityImportPublicKey(CanonicalIdentityFixture.publicKey) + if standalone { + _ = try await harness.manager.importIdentity( + CanonicalIdentityFixture.privateKey, expectedServices: source, deviceID: harness.deviceA.id + ) + } else { + try await source.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + } + let ready = harness.manager.connectionState == .ready + let canonical = harness.manager.connectedDevice?.publicKey == CanonicalIdentityFixture.publicKey + let frames = await harness.bluetooth.sentData + let keyIndex = frames.firstIndex { $0.first == CommandCode.importPrivateKey.rawValue } + let index = try #require(keyIndex) + let synced = frames.suffix(from: index).contains { $0.first == CommandCode.getChannel.rawValue } + let laterIOWorks = try await harness.manager.services?.settingsService.getTime() != nil + #expect(ready) + #expect(canonical) + #expect(synced) + #expect(laterIOWorks) + } + } + + private func newAdvertisement(key: Data) -> Data { + let name = Data("Runtime discovery".utf8) + var packet = Data([ResponseCode.newAdvertisement.rawValue]) + key + packet.append(contentsOf: [ContactType.chat.rawValue, 0, 0xFF]) + packet.append(Data(repeating: 0, count: 64)) + packet.append(name) + packet.append(Data(repeating: 0, count: 32 - name.count)) + packet.append(Data(repeating: 0, count: 16)) + return packet + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/IdentityImportTailOrderingTests.swift b/MC1Services/Tests/MC1ServicesTests/IdentityImportTailOrderingTests.swift new file mode 100644 index 0000000000..5e63cf272d --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/IdentityImportTailOrderingTests.swift @@ -0,0 +1,129 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Identity import selected tail ordering") +@MainActor +struct IdentityImportTailOrderingTests { + @Test + func `same-secret Ghost history survives the actual planned channel restore before ordinary sync`() async throws { + try await ConnectionRadioHandoffHarness.withHarness(maxChannels: 2) { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + await harness.bluetooth.setChannel(index: 0, name: "Public", secret: Data(repeating: 0x11, count: 16)) + try await harness.connectBluetooth() + let store = harness.manager.persistenceStore + let source = try #require(harness.manager.services) + let secret = Data(repeating: 0xCD, count: 16) + let channel = ChannelDTO.testChannel(radioID: harness.deviceB.radioID, index: 1, name: "Restored", secret: secret) + try await store.saveChannel(channel) + let history = MessageDTO.testChannelMessage( + radioID: harness.deviceB.radioID, channelIndex: 1, text: "B existing history" + ) + try await store.saveMessage(history) + let pendingB = try await source.messageService.createPendingChannelMessage( + text: "B saved pending", channelIndex: 1, radioID: harness.deviceB.radioID + ) + _ = try await store.insertPendingSendAssigningSequence( + PendingSendDTO(envelope: envelope(pendingB), radioID: harness.deviceB.radioID) + ) + let pendingA = try await source.messageService.createPendingChannelMessage( + text: "A saved pending", channelIndex: 0, radioID: harness.deviceA.radioID + ) + _ = try await store.insertPendingSendAssigningSequence( + PendingSendDTO(envelope: envelope(pendingA), radioID: harness.deviceA.radioID) + ) + let initiallyConfigured = await harness.bluetooth.isChannelConfigured(index: 1) + #expect(!initiallyConfigured) + await harness.bluetooth.setIdentityImportPublicKey(CanonicalIdentityFixture.publicKey) + await harness.bluetooth.holdSubmissions(for: .setChannel) + let contactKey = Data(repeating: 0xC7, count: ProtocolLimits.publicKeySize) + let config = MeshCoreNodeConfig( + privateKey: CanonicalIdentityFixture.privateKeyHex, + channels: [.init(name: "Restored", secret: secret.hexString)], + contacts: [.init( + type: 1, name: "Tail contact", publicKey: contactKey.hexString, + flags: 0, latitude: "0", longitude: "0", lastAdvert: 0, lastModified: 0 + )] + ) + let importing = harness.track(Task { + try await source.nodeConfigService.importConfig( + config, sections: ConfigSections(nodeIdentity: true, channels: true, contacts: true), + radioID: harness.deviceA.radioID + ) + }) + try await waitUntil("the real planner must reach its selected channel write before physical apply") { + await harness.bluetooth.submissionIsHeld(for: .setChannel) + } + let frames = await harness.bluetooth.sentData + let identityCommandIndex = frames.firstIndex { $0.first == CommandCode.importPrivateKey.rawValue } + let keyIndex = try #require(identityCommandIndex) + let afterIdentity = frames.suffix(from: frames.index(after: keyIndex)) + let noEarlyChannelReads = afterIdentity.filter { $0.first == CommandCode.getChannel.rawValue }.isEmpty + #expect(noEarlyChannelReads) + let noEarlyCatchUp = afterIdentity.filter { $0.first == CommandCode.getMessage.rawValue }.isEmpty + #expect(noEarlyCatchUp) + let noEarlySends = afterIdentity.filter { $0.first == CommandCode.sendChannelMessage.rawValue }.isEmpty + #expect(noEarlySends) + let candidateNotPublished = harness.manager.currentConnection == nil + #expect(candidateNotPublished) + let candidateServicesPrivate = harness.manager.services == nil + #expect(candidateServicesPrivate) + let candidateSessionPrivate = harness.manager.session == nil + #expect(candidateSessionPrivate) + let candidateDevicePrivate = harness.manager.connectedDevice == nil + #expect(candidateDevicePrivate) + let historyPreserved = try await store.fetchMessage(id: history.id) != nil + #expect(historyPreserved) + let pendingMessagePreserved = try await store.fetchMessage(id: pendingB.id) != nil + #expect(pendingMessagePreserved) + let pendingSendPreserved = try await store.fetchPendingSends(radioID: harness.deviceB.radioID).contains { $0.messageID == pendingB.id } + #expect(pendingSendPreserved) + let configuredBeforeRestore = await harness.bluetooth.isChannelConfigured(index: 1) + #expect(!configuredBeforeRestore) + let noChannelAppliedBeforeRelease = await harness.bluetooth.channelWriteIndices.isEmpty + #expect(noChannelAppliedBeforeRelease) + + await harness.bluetooth.releaseSubmissions(for: .setChannel) + try await importing.value + + let canonicalPartitionPublished = harness.manager.connectedDevice?.radioID == harness.deviceB.radioID + #expect(canonicalPartitionPublished) + let runtimeReady = harness.manager.connectionState == .ready + #expect(runtimeReady) + let plannerUsedPrivateSlot = await harness.bluetooth.channelWriteIndices == [1] + #expect(plannerUsedPrivateSlot) + let restored = await harness.bluetooth.channelMatches(index: 1, secret: secret) + #expect(restored) + let historyPreserved2 = try await store.fetchMessage(id: history.id) != nil + #expect(historyPreserved2) + let pendingMessagePreserved2 = try await store.fetchMessage(id: pendingB.id) != nil + #expect(pendingMessagePreserved2) + if try await store.fetchMessage(id: pendingB.id) != nil { + try await waitUntil("the restored canonical queue should send its preserved pending row") { + await (try? store.fetchMessage(id: pendingB.id))?.status == .sent + } + } + let canonicalContactSaved = try await store.fetchContacts(radioID: harness.deviceB.radioID).contains { $0.publicKey == contactKey } + #expect(canonicalContactSaved) + let noSourceContactSaved = try await store.fetchContacts(radioID: harness.deviceA.radioID).contains { $0.publicKey == contactKey } == false + #expect(noSourceContactSaved) + let sourcePendingPreserved = try await store.fetchPendingSends(radioID: harness.deviceA.radioID).contains { $0.messageID == pendingA.id } + #expect(sourcePendingPreserved) + let sent = await harness.bluetooth.sentData.filter { $0.first == CommandCode.sendChannelMessage.rawValue } + let noSourceSend = sent.contains { $0.range(of: Data("A saved pending".utf8)) != nil } == false + #expect(noSourceSend) + let noUnconfiguredSend = await harness.bluetooth.unconfiguredChannelSendCount == 0 + #expect(noUnconfiguredSend) + let laterIOWorks = try await harness.manager.services?.settingsService.getTime() != nil + #expect(laterIOWorks) + } + } + + private func envelope(_ message: MessageDTO) -> ChannelMessageEnvelope { + ChannelMessageEnvelope( + messageID: message.id, channelIndex: message.channelIndex ?? 0, isResend: false, + messageText: message.text, messageTimestamp: message.timestamp, localNodeName: "Test Radio" + ) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/IdentityImportTailSettlementTests.swift b/MC1Services/Tests/MC1ServicesTests/IdentityImportTailSettlementTests.swift new file mode 100644 index 0000000000..ddb972349a --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/IdentityImportTailSettlementTests.swift @@ -0,0 +1,239 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Identity import tail settlement") +@MainActor +struct IdentityImportTailSettlementTests { + @Test + func `cancelled tail waits for its submitted exchange before canonical activation`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await harness.connectBluetooth() + let originalServices = harness.manager.services + let source = try #require(originalServices) + await harness.bluetooth.setIdentityImportPublicKey(CanonicalIdentityFixture.publicKey) + await harness.bluetooth.holdReplies(for: .setChannel) + var selectedWithReplyHeld: Bool? + defer { harness.manager.testConnectionSelectionHandler = nil } + harness.manager.testConnectionSelectionHandler = { _ in + selectedWithReplyHeld = await harness.bluetooth.heldReplyCount(for: .setChannel) > 0 + } + let importing = harness.track(Task { + try await source.nodeConfigService.importConfig( + config(), sections: ConfigSections(nodeIdentity: true, channels: true, contacts: true), + radioID: harness.deviceA.radioID + ) + }) + try await waitUntil("the selected channel should be applied with its real reply still held") { + await harness.bluetooth.heldReplyCount(for: .setChannel) == 1 + } + importing.cancel() + await harness.manager.appDidBecomeActive() + let privateBeforeReply = harness.manager.currentConnection == nil + let noSelectionBeforeReply = selectedWithReplyHeld == nil + #expect(privateBeforeReply) + #expect(noSelectionBeforeReply) + await harness.bluetooth.releaseReplies(for: .setChannel) + let result = await importing.result + let cancelled: Bool = if case let .failure(error) = result { error is CancellationError } else { false } + let selectionFollowedSettlement = selectedWithReplyHeld == false + let ready = harness.manager.connectionState == .ready + let noSkippedContact = try await harness.manager.persistenceStore.fetchContacts(radioID: harness.deviceA.radioID).isEmpty + let laterIOWorks = try await harness.manager.services?.settingsService.getTime() != nil + #expect(cancelled) + #expect(selectionFollowedSettlement) + #expect(ready) + #expect(noSkippedContact) + #expect(laterIOWorks) + } + } + + @Test + func `superseding a submitted tail retires its private candidate without publishing it`() async throws { + try await ConnectionRadioHandoffHarness.withHarness(wifiIsSameRadio: false) { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let originalServices = harness.manager.services + let source = try #require(originalServices) + await harness.bluetooth.setIdentityImportPublicKey(CanonicalIdentityFixture.publicKey) + await harness.bluetooth.holdReplies(for: .setChannel) + let canonicalRadioID = harness.deviceB.radioID + var publishedCanonical = false + harness.manager.onConnectionReady = { snapshot in + if snapshot.device.radioID == canonicalRadioID { publishedCanonical = true } + } + let importing = harness.track(Task { + try await source.nodeConfigService.importConfig( + config(), sections: ConfigSections(nodeIdentity: true, channels: true, contacts: true), + radioID: harness.deviceA.radioID + ) + }) + try await waitUntil("canonical preparation should hold a submitted channel tail") { + await harness.bluetooth.heldReplyCount(for: .setChannel) == 1 + } + let sourceRequest = harness.manager.connectionRequestID + let successor = harness.track(Task { try await harness.manager.connectViaWiFi(host: "successor.local", port: 4242) }) + try await waitUntil("the successor must revoke the captured private candidate") { + harness.manager.connectionRequestID != sourceRequest + } + await harness.bluetooth.releaseReplies(for: .setChannel) + _ = await importing.result + _ = try await successor.value + let successorOwnsPublication = harness.manager.connectedDevice?.publicKey == harness.deviceB.publicKey + let laterIOWorks = try await harness.manager.services?.settingsService.getTime() != nil + #expect(!publishedCanonical) + #expect(successorOwnsPublication) + #expect(laterIOWorks) + } + } + + @Test(arguments: [false, true]) + func `final selection failure preserves an earlier tail error and retires the candidate`(tailFails: Bool) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await harness.connectBluetooth() + let originalServices = harness.manager.services + let source = try #require(originalServices) + await harness.bluetooth.setIdentityImportPublicKey(CanonicalIdentityFixture.publicKey) + if tailFails { await harness.bluetooth.rejectNext(.updateContact, code: ErrorCode.unsupportedCommand.rawValue) } + defer { harness.manager.testConnectionSelectionHandler = nil } + harness.manager.testConnectionSelectionHandler = { _ in throw Failure.selection } + let importing = harness.track(Task { + try await source.nodeConfigService.importConfig( + config(), sections: ConfigSections(nodeIdentity: true, channels: true, contacts: true), + radioID: harness.deviceA.radioID + ) + }) + let result = await importing.result + let expectedError: Bool = if case let .failure(error) = result { + if tailFails, let contactError = error as? ContactServiceError, + case let .sessionError(.deviceError(code)) = contactError { + code == ErrorCode.unsupportedCommand.rawValue + } else { + !tailFails && error is Failure + } + } else { + false + } + let unpublished = harness.manager.currentConnection == nil + let retired = await !harness.bluetooth.isConnected + let canonicalDevice = try await harness.manager.persistenceStore.fetchDevice(publicKey: CanonicalIdentityFixture.publicKey) + let canonicalSaved = canonicalDevice?.radioID == harness.deviceA.radioID + let actualChannelApplied = await harness.bluetooth.channelWriteIndices == [0] + #expect(expectedError) + #expect(unpublished) + #expect(retired) + #expect(canonicalSaved) + #expect(actualChannelApplied) + harness.manager.testConnectionSelectionHandler = nil + _ = try await harness.manager.connect(to: harness.deviceA.id, forceReconnect: true) + let laterIOWorks = try await harness.manager.services?.settingsService.getTime() != nil + #expect(laterIOWorks) + } + } + + @Test + func `supersession during final selection cannot publish or retire the successor`() async throws { + try await ConnectionRadioHandoffHarness.withHarness(wifiIsSameRadio: false) { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let sourceServices = harness.manager.services + let source = try #require(sourceServices) + await harness.bluetooth.setIdentityImportPublicKey(CanonicalIdentityFixture.publicKey) + let selection = IdentityRecoveryFixture.Gate() + defer { + selection.open() + harness.manager.testConnectionSelectionHandler = nil + } + var heldRequest: UUID? + harness.manager.testConnectionSelectionHandler = { requestID in + guard heldRequest == nil else { return } + heldRequest = requestID + await selection.wait() + } + let canonicalRadioID = harness.deviceB.radioID + var publishedCanonical = false + harness.manager.onConnectionReady = { snapshot in + if snapshot.device.radioID == canonicalRadioID { publishedCanonical = true } + } + let importing = harness.track(Task { + try await source.nodeConfigService.importConfig( + config(), sections: ConfigSections(nodeIdentity: true, channels: true, contacts: true), + radioID: harness.deviceA.radioID + ) + }) + try await waitUntil("the selected tail should finish before final metadata selection") { selection.arrived } + let successor = harness.track(Task { try await harness.manager.connectViaWiFi(host: "successor.local", port: 4242) }) + try await waitUntil("a new request should supersede held final selection") { + harness.manager.connectionRequestID != heldRequest + } + let noSuccessorDialBeforeMetadataSettles = await harness.wifi.connectCount == 0 + #expect(noSuccessorDialBeforeMetadataSettles) + selection.open() + let result = await importing.result + _ = try await successor.value + let oldImportFailed = if case .failure = result { true } else { false } + let successorOwnsPublication = harness.manager.connectedDevice?.publicKey == harness.deviceB.publicKey + let laterIOWorks = try await harness.manager.services?.settingsService.getTime() != nil + #expect(oldImportFailed) + #expect(!publishedCanonical) + #expect(successorOwnsPublication) + #expect(laterIOWorks) + } + } + + @Test + func `a rejected selected contact still activates the settled canonical channel runtime`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let sourceServices = harness.manager.services + let source = try #require(sourceServices) + await harness.bluetooth.setIdentityImportPublicKey(CanonicalIdentityFixture.publicKey) + await harness.bluetooth.rejectNext(.updateContact, code: ErrorCode.unsupportedCommand.rawValue) + let importing = harness.track(Task { + try await source.nodeConfigService.importConfig( + config(), sections: ConfigSections(nodeIdentity: true, channels: true, contacts: true), + radioID: harness.deviceA.radioID + ) + }) + let result = await importing.result + let rejected = if case let .failure(error) = result, let contactError = error as? ContactServiceError, + case let .sessionError(.deviceError(code)) = contactError { + code == ErrorCode.unsupportedCommand.rawValue + } else { + false + } + let frames = await harness.bluetooth.sentData + let contactIndex = frames.firstIndex { $0.first == CommandCode.updateContact.rawValue } + let tailIndex = try #require(contactIndex) + let firstChannelSync = frames.suffix(from: tailIndex).firstIndex { $0.first == CommandCode.getChannel.rawValue } + let firstCatchUp = frames.suffix(from: tailIndex).firstIndex { $0.first == CommandCode.getMessage.rawValue } + let syncFollowedRejection = firstChannelSync != nil && firstCatchUp != nil + let canonicalReady = harness.manager.connectedDevice?.radioID == harness.deviceB.radioID && + harness.manager.connectionState == .ready + let acceptedChannelRetained = await harness.bluetooth.channelMatches(index: 0, secret: Data(repeating: 0xCD, count: 16)) + let rejectedContactAbsent = try await harness.manager.persistenceStore.fetchContacts(radioID: harness.deviceB.radioID).isEmpty + let laterIOWorks = try await harness.manager.services?.settingsService.getTime() != nil + #expect(rejected) + #expect(syncFollowedRejection) + #expect(canonicalReady) + #expect(acceptedChannelRetained) + #expect(rejectedContactAbsent) + #expect(laterIOWorks) + } + } + + private func config() -> MeshCoreNodeConfig { + MeshCoreNodeConfig( + privateKey: CanonicalIdentityFixture.privateKeyHex, + channels: [.init(name: "Settled", secret: String(repeating: "CD", count: 16))], + contacts: [.init( + type: 1, name: "Selected tail", publicKey: Data(repeating: 0xC8, count: 32).hexString, + flags: 0, latitude: "0", longitude: "0", lastAdvert: 0, lastModified: 0 + )] + ) + } + + private enum Failure: Error { case selection } +} diff --git a/MC1Services/Tests/MC1ServicesTests/IdentityImportTransportFailureTests.swift b/MC1Services/Tests/MC1ServicesTests/IdentityImportTransportFailureTests.swift new file mode 100644 index 0000000000..e8216116f8 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/IdentityImportTransportFailureTests.swift @@ -0,0 +1,316 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Identity import after a transport completion failure") +@MainActor +struct IdentityImportTransportFailureTests { + @Test(arguments: Failure.allCases, [false, true]) + func `an admitted queue send failure cannot lend its terminal response to identity import`( + failure: Failure, oldReplyWasOK: Bool + ) async throws { + try await exerciseFailure( + failure, oldReplyWasOK: oldReplyWasOK, cancelCaller: false, settledBeforeAdmission: false + ) + } + + @Test + func `cancelling the old caller cannot hide its actual transport completion failure`() async throws { + try await exerciseFailure( + .bluetoothTimeout, oldReplyWasOK: true, cancelCaller: true, settledBeforeAdmission: false + ) + } + + @Test + func `a transport failure already settled before identity admission also refuses the key write`() async throws { + try await exerciseFailure( + .bluetoothTimeout, oldReplyWasOK: false, cancelCaller: false, settledBeforeAdmission: true + ) + } + + @Test(arguments: PriorOutcome.allCases) + func `a consumed rejection or local next-write cancellation does not taint identity admission`( + priorOutcome: PriorOutcome + ) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await harness.connectBluetooth() + let source = try #require(harness.manager.installedLink) + let scopesBefore = await harness.bluetooth.sentData.filter { $0.first == CommandCode.setFloodScope.rawValue }.count + await harness.bluetooth.holdReplies(for: .setFloodScope) + if priorOutcome == .rejectedScope { await harness.bluetooth.rejectNext(.setFloodScope) } + let ordinary = harness.track(Task { + try await source.resource.session.sendChannelMessage( + channel: 0, text: "No next message", timestamp: Date(), floodScope: .unscoped + ) + }) + var importing: Task? + do { + try await waitUntil("the ordinary scope exchange must have its own outstanding response") { + let scopes = await harness.bluetooth.sentData.filter { $0.first == CommandCode.setFloodScope.rawValue }.count + let scopeHeld = await harness.bluetooth.heldReplyCount(for: .setFloodScope) >= 1 + return scopes > scopesBefore && scopeHeld + } + if priorOutcome == .cancelledBeforeMessage { + ordinary.cancel() + // The submitted scope exchange keeps the caller until its reply settles. + await harness.bluetooth.releaseReplies(for: .setFloodScope) + await #expect(throws: CancellationError.self) { try await ordinary.value } + } else { + await harness.bluetooth.releaseReplies(for: .setFloodScope) + await #expect(throws: MeshCoreError.self) { try await ordinary.value } + } + await source.resource.session.waitForQuiescence() + let messageWasSubmitted = await harness.bluetooth.sentData.contains { $0.first == CommandCode.sendChannelMessage.rawValue } + #expect(messageWasSubmitted == false) + await harness.bluetooth.holdReplies(for: .importPrivateKey) + importing = harness.track(Task { + try await source.services.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + }) + try await waitUntil("clean response history must permit a real identity exchange on the same session") { + await IdentityRecoveryFixture.keyWriteCount(harness) == 1 + } + await harness.bluetooth.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + await harness.bluetooth.releaseReplies(for: .importPrivateKey) + try await importing?.value + #expect(harness.manager.connectedDevice?.radioID == harness.deviceA.radioID) + #expect(harness.manager.connectedDevice?.publicKey == CanonicalIdentityFixture.publicKey) + #expect(harness.manager.identityImportRecoveries.isEmpty) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } catch { + await harness.bluetooth.releaseAllGates() + _ = await ordinary.result + _ = await importing?.result + throw error + } + } + } + + private func exerciseFailure( + _ failure: Failure, oldReplyWasOK: Bool, cancelCaller: Bool, settledBeforeAdmission: Bool + ) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + let radio = failure.usesWiFi ? harness.wifi : harness.bluetooth + await radio.setChannel(index: 0, name: "Retained", secret: Data(repeating: 0xCD, count: 16)) + try await connect(harness, overWiFi: failure.usesWiFi) + let source = try #require(harness.manager.installedLink) + let store = harness.manager.persistenceStore + let stateA = source.services.settingsService.radioWiFiState + let stateB = harness.manager.radioWiFiState(for: harness.deviceB.radioID) + _ = try await source.services.settingsService.runCliCommand("set wifi.enabled 0") + let gate = IdentityRecoveryFixture.Gate() + harness.manager.testIdentityBeforeAdmission = { await gate.wait() } + var importFinished = false + let importing = harness.track(Task { + defer { importFinished = true } + try await source.services.nodeConfigService.importConfig( + config(name: "Unattributed name", channel: "Unattributed channel"), + sections: ConfigSections(nodeIdentity: true, channels: true), radioID: harness.deviceA.radioID + ) + }) + var ordinary: Task? + do { + try await waitUntil("config preflight should finish before the ordinary send") { + gate.arrived || importFinished + } + if !gate.arrived { try await importing.value } + try #require(gate.arrived) + let scopesBefore = await radio.sentData.filter { $0.first == CommandCode.setFloodScope.rawValue }.count + await radio.holdReplies(for: .setFloodScope) + await radio.holdReplies(for: .sendChannelMessage) + await radio.setResponsePackets( + for: .sendChannelMessage, + packets: [oldReplyWasOK ? Data([ResponseCode.ok.rawValue]) : Data([ResponseCode.error.rawValue, 1])] + ) + await radio.failNextSendAfterSubmission(.sendChannelMessage, error: failure.error) + if cancelCaller { + ordinary = harness.track(Task { + try await source.resource.session.sendChannelMessage( + channel: 0, text: "Cancelled ordinary caller", timestamp: Date(), floodScope: .unscoped + ) + }) + } else { + let pending = try await source.services.messageService.createPendingChannelMessage( + text: "Admitted queue worker", channelIndex: 0, radioID: harness.deviceA.radioID + ) + try await source.services.chatSendQueueService.enqueueChannel(envelope(pending)) + } + try await waitUntil("the actual channel operation should hold its scope ACK") { + let scopes = await radio.sentData.filter { $0.first == CommandCode.setFloodScope.rawValue }.count + let scopeHeld = await radio.heldReplyCount(for: .setFloodScope) >= 1 + return scopes > scopesBefore && scopeHeld + } + await radio.holdNextSendCompletion() + await radio.releaseReplies(for: .setFloodScope) + try await waitUntil("the channel frame must be physically submitted before its completion fails") { + let submitted = await radio.sentData.contains { $0.first == CommandCode.sendChannelMessage.rawValue } + let completionIsHeld = await radio.sendCompletionIsHeld + return submitted && completionIsHeld + } + #expect(await radio.failedSendCount == 0) + #expect(await radio.isConnected) + if let ordinary { + ordinary.cancel() + // The caller stays suspended until the submitted write settles. + #expect(await radio.sendCompletionIsHeld) + } + if oldReplyWasOK { await radio.rejectNext(.importPrivateKey) } + await radio.holdReplies(for: .importPrivateKey) + if settledBeforeAdmission { + await radio.releaseSendCompletion() + try await waitUntil("the actual send failure must settle before the early history check") { + await radio.failedSendCount == 1 + } + await source.resource.session.waitForQuiescence() + gate.open() + } else { + gate.open() + try await waitUntil("identity admission must close while the actual old send is still held") { + await source.services.settingsService.radioWiFiOperationsRetired + } + if !cancelCaller { + try await waitUntil("identity retirement must reach the admitted queue worker") { + source.services.chatSendQueueService.isRetiredForTesting + } + } + let submittedBeforeFailure = await radio.sentData.contains { $0.first == CommandCode.importPrivateKey.rawValue } + #expect(submittedBeforeFailure == false) + #expect(importFinished == false) + #expect(await radio.sendCompletionIsHeld) + await radio.releaseSendCompletion() + if let ordinary { + _ = await ordinary.result + } + } + try await waitUntil("the actual transport failure must either refuse identity or reveal a key frame") { + if importFinished { return true } + return await radio.sentData.contains { $0.first == CommandCode.importPrivateKey.rawValue } + } + let keyWasSubmitted = await radio.sentData.contains { $0.first == CommandCode.importPrivateKey.rawValue } + if keyWasSubmitted, !oldReplyWasOK { + await radio.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + } + await radio.releaseReplies(for: .sendChannelMessage) + await radio.releaseReplies(for: .importPrivateKey) + let result = await importing.result + let importFailed = if case .failure = result { true } else { false } + let frames = await radio.sentData + let keyWriteCount = frames.filter { $0.first == CommandCode.importPrivateKey.rawValue }.count + let nameWasSubmitted = frames.contains { $0.first == CommandCode.setName.rawValue } + let channelTailWasSubmitted = frames.contains { $0.first == CommandCode.setChannel.rawValue } + #expect(importFailed) + #expect(keyWriteCount == 0) + #expect(nameWasSubmitted == false) + #expect(channelTailWasSubmitted == false) + #expect(await radio.failedSendCount == 1) + #expect(harness.manager.pendingIdentityReconciliations[harness.deviceA.id] == nil) + #expect(try await store.fetchDevice(id: harness.deviceA.id)?.publicKey == harness.deviceA.publicKey) + #expect(try await store.fetchDevice(id: harness.deviceA.id)?.radioID == harness.deviceA.radioID) + let ghostWasPreserved = try await store.fetchDevice(publicKey: CanonicalIdentityFixture.publicKey)?.radioID + == harness.deviceB.radioID + #expect(ghostWasPreserved) + #expect(stateA.rebootPending) + #expect(stateB.rebootPending == false) + } catch { + gate.open() + await radio.releaseAllGates() + _ = await ordinary?.result + _ = await importing.result + harness.manager.testIdentityBeforeAdmission = nil + throw error + } + harness.manager.testIdentityBeforeAdmission = nil + await radio.rejectNext(.importPrivateKey, count: 0) + await radio.setResponsePackets(for: .sendChannelMessage, packets: [Data([ResponseCode.ok.rawValue])]) + try await connect(harness, overWiFi: failure.usesWiFi) + let fresh = try #require(harness.manager.services) + let writesBefore = await IdentityRecoveryFixture.keyWriteCount(harness) + await radio.holdReplies(for: .importPrivateKey) + let freshImport = harness.track(Task { + try await fresh.nodeConfigService.importConfig( + config(name: "Fresh identity name", channel: "Fresh identity channel"), + sections: ConfigSections(nodeIdentity: true, channels: true), radioID: harness.deviceA.radioID + ) + }) + do { + try await waitUntil("a fresh session must submit its own private-key exchange") { + await IdentityRecoveryFixture.keyWriteCount(harness) == writesBefore + 1 + } + await radio.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + await radio.releaseReplies(for: .importPrivateKey) + try await freshImport.value + } catch { + await radio.releaseAllGates() + _ = await freshImport.result + throw error + } + let current = try #require(harness.manager.services) + #expect(harness.manager.connectedDevice?.radioID == harness.deviceB.radioID) + let canonicalUsesSourceHandle = try await store.fetchDevice(publicKey: CanonicalIdentityFixture.publicKey)?.id + == harness.deviceA.id + #expect(canonicalUsesSourceHandle) + #expect(harness.manager.identityImportRecoveries.isEmpty) + #expect(current.settingsService.radioWiFiState === stateB) + #expect(stateB.rebootPending) + let freshChannelWasSaved = try await store.fetchChannels(radioID: harness.deviceB.radioID) + .contains { $0.name == "Fresh identity channel" } + #expect(freshChannelWasSaved) + #expect(try await current.settingsService.getTime().timeIntervalSince1970 > 0) + let freshMessage = try await current.messageService.createPendingChannelMessage( + text: "Fresh identity queue remains live", channelIndex: 0, radioID: harness.deviceB.radioID + ) + try await current.chatSendQueueService.enqueueChannel(envelope(freshMessage)) + try await waitUntil("the replacement queue must complete a real channel send") { + await (try? store.fetchMessage(id: freshMessage.id)?.status) == .sent + } + } + } + + private func connect(_ harness: ConnectionRadioHandoffHarness, overWiFi: Bool) async throws { + if overWiFi { + await harness.wifi.setDeviceID(harness.deviceA.id) + _ = try await harness.manager.connectViaWiFi(host: "source.local", port: 4242) + } else { + try await harness.connectBluetooth() + } + } + + private func config(name: String, channel: String) -> MeshCoreNodeConfig { + MeshCoreNodeConfig( + name: name, privateKey: CanonicalIdentityFixture.privateKeyHex, + channels: [.init(name: channel, secret: String(repeating: "CD", count: 16))] + ) + } + + private func envelope(_ message: MessageDTO) -> ChannelMessageEnvelope { + ChannelMessageEnvelope( + messageID: message.id, channelIndex: 0, isResend: false, messageText: message.text, + messageTimestamp: message.timestamp, localNodeName: "Provenance radio" + ) + } + + enum Failure: CaseIterable, Sendable { + case bluetoothTimeout, bluetoothCancellation, wifiTimeout, wifiSendFailed + + var usesWiFi: Bool { + self == .wifiTimeout || self == .wifiSendFailed + } + + var error: any Error { + switch self { + case .bluetoothTimeout: BLEError.operationTimeout + case .bluetoothCancellation: CancellationError() + case .wifiTimeout: WiFiTransportError.sendTimeout + case .wifiSendFailed: WiFiTransportError.sendFailed("Synthetic completion failure") + } + } + } + + enum PriorOutcome: CaseIterable, Sendable { + case cancelledBeforeMessage, rejectedScope + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/IdentityRebuildPublicationTests.swift b/MC1Services/Tests/MC1ServicesTests/IdentityRebuildPublicationTests.swift new file mode 100644 index 0000000000..cc5e933e11 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/IdentityRebuildPublicationTests.swift @@ -0,0 +1,28 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Identity rebuild publication") +@MainActor +struct IdentityRebuildPublicationTests { + @Test + func `an unpublished identity rebuild stays on the request through connecting`() throws { + let defaults = try #require(UserDefaults(suiteName: "test.\(UUID().uuidString)")) + let (manager, _) = try ConnectionManager.createForTesting(defaults: defaults) + manager.setTestState(connectionIntent: .wantsConnection(), identityRebuildUnpublished: true) + let request = ConnectionRequest( + targets: [.bluetooth(UUID())], origin: .explicit, forceFullSync: false, forceReconnect: false, + continuing: nil + ) + manager.desiredRequest = request + + manager.detachPublication(phase: .connected) + #expect(manager.identityRebuildUnpublished) + + manager.publishPending(request, phase: .connecting) + #expect(manager.identityRebuildUnpublished) + + manager.detachPublication(phase: .disconnected) + #expect(!manager.identityRebuildUnpublished) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/IdentityRecoveryAssociationTests.swift b/MC1Services/Tests/MC1ServicesTests/IdentityRecoveryAssociationTests.swift new file mode 100644 index 0000000000..423e031ddb --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/IdentityRecoveryAssociationTests.swift @@ -0,0 +1,115 @@ +#if canImport(UIKit) + import AccessorySetupKit +#endif +import Foundation +@testable import MC1Services +import Testing + +@Suite("Identity recovery after association removal") +@MainActor +struct IdentityRecoveryAssociationTests { + @Test + func `native removal that demotes an idle source is validated without dialing its old association`() async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + registerSource(in: harness) + try await harness.connectBluetooth() + let confirmation = try await IdentityRecoveryFixture.interrupt(harness) + harness.pairing.simulateAccessoryRemoved(harness.deviceA.id) + await harness.manager.metadataCommitTask?.value + let oldHandleWasRemoved = try await harness.manager.persistenceStore.fetchDevice(id: harness.deviceA.id) == nil + #expect(oldHandleWasRemoved) + let ghost = try #require(try await harness.manager.persistenceStore.fetchDevice(radioID: harness.deviceA.radioID)) + #expect(ghost.id != harness.deviceA.id) + #expect(ghost.publicKey == harness.deviceA.publicKey) + #expect(ghost.connectionMethods.isEmpty) + let connectsBefore = await IdentityRecoveryFixture.connectCount(harness) + var validations = 0 + harness.manager.testIdentityBeforeSourceValidation = { validations += 1 } + await #expect(throws: (any Error).self) { + _ = try await harness.manager.retryIdentityImport( + confirmation: confirmation, privateKey: CanonicalIdentityFixture.privateKey + ) + } + harness.manager.testIdentityBeforeSourceValidation = nil + #expect(validations == 1) + let connectsAfter = await IdentityRecoveryFixture.connectCount(harness) + let keyWrites = await IdentityRecoveryFixture.keyWriteCount(harness) + #expect(connectsAfter == connectsBefore) + #expect(keyWrites == 1) + #expect(harness.manager.prepareIdentityImportRecovery(receiptID: confirmation.receiptID) == nil) + await harness.wifi.setDeviceID(harness.deviceB.id) + await harness.wifi.setPublicKey(harness.deviceB.publicKey, for: harness.deviceB.id) + _ = try await harness.manager.connectViaWiFi(host: "unrelated-after-native-removal.local", port: 4242) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } + + @Test(arguments: [false, true]) + func `surviving WiFi preserves uncertainty while an unavailable Bluetooth target cannot replace B`(viaWiFi: Bool) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + registerSource(in: harness) + if viaWiFi { + await harness.wifi.setDeviceID(harness.deviceA.id) + _ = try await harness.manager.connectViaWiFi(host: "surviving-source.local", port: 4242) + } else { + try await harness.manager.persistenceStore.saveDevice(harness.deviceA.copy { + $0.connectionMethods.append(.wifi(host: "surviving-source.local", port: 4242, displayName: nil)) + }) + try await harness.connectBluetooth() + } + let original = try await IdentityRecoveryFixture.interrupt(harness) + harness.pairing.simulateAccessoryRemoved(harness.deviceA.id) + await harness.manager.metadataCommitTask?.value + let kept = try #require(try await harness.manager.persistenceStore.fetchDevice(id: harness.deviceA.id)) + #expect(kept.radioID == harness.deviceA.radioID) + #expect(kept.publicKey == harness.deviceA.publicKey) + let onlyWiFiRemains = kept.connectionMethods.allSatisfy(\.isWiFi) + #expect(onlyWiFiRemains) + #expect(!kept.connectionMethods.isEmpty) + let confirmation = try #require(harness.manager.prepareIdentityImportRecovery(receiptID: original.receiptID)) + #expect(confirmation.capturedConnectionMethod == original.capturedConnectionMethod) + if viaWiFi { + _ = try await harness.manager.retryIdentityImport( + confirmation: confirmation, privateKey: CanonicalIdentityFixture.privateKey + ) + #expect(harness.manager.connectedDevice?.radioID == harness.deviceA.radioID) + #expect(harness.manager.identityImportRecoveries.isEmpty) + let keyWrites = await IdentityRecoveryFixture.keyWriteCount(harness) + #expect(keyWrites == 2) + } else { + await harness.wifi.setDeviceID(harness.deviceB.id) + await harness.wifi.setPublicKey(harness.deviceB.publicKey, for: harness.deviceB.id) + _ = try await harness.manager.connectViaWiFi(host: "current-b-during-association-retry.local", port: 4242) + let currentConfirmation = try #require(harness.manager.prepareIdentityImportRecovery(receiptID: original.receiptID)) + let successorRequestID = harness.manager.connectionRequestID + let successorGeneration = harness.manager.currentConnection?.generation + let connectsBefore = await IdentityRecoveryFixture.connectCount(harness) + var validations = 0 + harness.manager.testIdentityBeforeSourceValidation = { validations += 1 } + await #expect(throws: (any Error).self) { + _ = try await harness.manager.retryIdentityImport( + confirmation: currentConfirmation, privateKey: CanonicalIdentityFixture.privateKey + ) + } + harness.manager.testIdentityBeforeSourceValidation = nil + #expect(validations == 1) + let connectsAfter = await IdentityRecoveryFixture.connectCount(harness) + let keyWrites = await IdentityRecoveryFixture.keyWriteCount(harness) + #expect(connectsAfter == connectsBefore) + #expect(keyWrites == 1) + #expect(harness.manager.prepareIdentityImportRecovery(receiptID: original.receiptID) != nil) + #expect(harness.manager.connectionRequestID == successorRequestID) + #expect(harness.manager.currentConnection?.generation == successorGeneration) + #expect(harness.manager.connectedDevice?.radioID == harness.deviceB.radioID) + } + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } + + private func registerSource(in harness: ConnectionRadioHandoffHarness) { + harness.pairing.isSessionActive = true + harness.pairing.setPairedAccessories([ + ASAccessory(bluetoothIdentifier: harness.deviceA.id, displayName: "Original source association") + ]) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/IdentityRecoveryOwnershipTests.swift b/MC1Services/Tests/MC1ServicesTests/IdentityRecoveryOwnershipTests.swift new file mode 100644 index 0000000000..e4b2b16b1b --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/IdentityRecoveryOwnershipTests.swift @@ -0,0 +1,198 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Identity recovery ownership") +@MainActor +struct IdentityRecoveryOwnershipTests { + @Test(arguments: [false, true]) + func `confirmed removal revokes retry and follows any accepted canonical result`(holdAfterCommit: Bool) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let source = try #require(harness.manager.services) + _ = try await source.settingsService.runCliCommand("set wifi.enabled 0") + let recovery = try await IdentityRecoveryFixture.interrupt(harness) + let gate = IdentityRecoveryFixture.Gate() + if holdAfterCommit { + harness.manager.testIdentityAfterCommit = { await gate.wait() } + } else { + harness.manager.testIdentityBeforeCommit = { await gate.wait() } + } + let retrying = harness.track(Task { + try await harness.manager.retryIdentityImport(confirmation: recovery, privateKey: CanonicalIdentityFixture.privateKey) + }) + var removing: Task? + do { + try await waitUntil("retry should reach the removal boundary") { gate.arrived } + let context = try await harness.manager.captureRemoval(id: harness.deviceA.id) + let requestID = harness.manager.connectionRequestID + removing = harness.track(Task { + try await harness.manager.removeDevice( + context, policy: .wholeDevice(deleteData: false), reason: .forgetDevice, systemPolicy: .bestEffort + ) + }) + try await waitUntil("confirmed removal should revoke the captured request") { + harness.manager.connectionRequestID != requestID + } + gate.open() + _ = await retrying.result + _ = try await removing?.value + harness.manager.testIdentityBeforeCommit = nil + harness.manager.testIdentityAfterCommit = nil + let oldHandleIsAbsent = try await harness.manager.persistenceStore.fetchDevice(id: harness.deviceA.id) == nil + #expect(oldHandleIsAbsent) + let expectedRadioID = holdAfterCommit ? harness.deviceB.radioID : harness.deviceA.radioID + let stored = try #require(try await harness.manager.persistenceStore.fetchDevice(radioID: expectedRadioID)) + #expect(stored.id != harness.deviceA.id) + #expect(stored.publicKey == (holdAfterCommit ? CanonicalIdentityFixture.publicKey : harness.deviceA.publicKey)) + #expect(stored.connectionMethods.isEmpty) + #expect(stored.radioID == expectedRadioID) + #expect(harness.manager.radioWiFiState(for: harness.deviceB.radioID).rebootPending == holdAfterCommit) + let wasNotPublished = harness.manager.connectedDevice == nil && harness.manager.services == nil + #expect(wasNotPublished) + #expect(harness.manager.pendingIdentityReconciliations[harness.deviceA.id] == nil) + await harness.wifi.setDeviceID(harness.deviceB.id) + await harness.wifi.setPublicKey(harness.deviceB.publicKey, for: harness.deviceB.id) + _ = try await harness.manager.connectViaWiFi(host: "unrelated-after-removal.local", port: 4242) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } catch { + gate.open() + _ = await retrying.result + _ = await removing?.result + harness.manager.testIdentityBeforeCommit = nil + harness.manager.testIdentityAfterCommit = nil + throw error + } + } + } + + @Test(arguments: [false, true], [false, true]) + func `retry cancellation and supersession respect the actual durable admission boundary`( + holdAfterCommit: Bool, cancelWaiter: Bool + ) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let source = try #require(harness.manager.services) + _ = try await source.settingsService.runCliCommand("set wifi.enabled 0") + let original = try await IdentityRecoveryFixture.interrupt(harness) + let gate = IdentityRecoveryFixture.Gate() + if holdAfterCommit { + harness.manager.testIdentityAfterCommit = { await gate.wait() } + } else { + harness.manager.testIdentityBeforeCommit = { await gate.wait() } + } + let retrying = harness.track(Task { + try await harness.manager.retryIdentityImport(confirmation: original, privateKey: CanonicalIdentityFixture.privateKey) + }) + var successor: Task? + do { + try await waitUntil("retry should reach its actual durable boundary") { gate.arrived } + if cancelWaiter { + retrying.cancel() + try await waitUntil("cancellation should revoke the retry worker before the gate opens") { + harness.manager.desiredRequest?.worker?.isCancelled == true + } + } else { + await harness.wifi.setDeviceID(harness.deviceB.id) + await harness.wifi.setPublicKey(harness.deviceB.publicKey, for: harness.deviceB.id) + let oldRequest = harness.manager.connectionRequestID + successor = harness.track(Task { try await harness.manager.connectViaWiFi(host: "successor.local", port: 4242) }) + try await waitUntil("new choice should supersede the captured retry") { + harness.manager.connectionRequestID != oldRequest + } + } + gate.open() + _ = await retrying.result + _ = try await successor?.value + harness.manager.testIdentityBeforeCommit = nil + harness.manager.testIdentityAfterCommit = nil + let stored = try #require(try await harness.manager.persistenceStore.fetchDevice(id: harness.deviceA.id)) + #expect(stored.radioID == (holdAfterCommit ? harness.deviceB.radioID : harness.deviceA.radioID)) + #expect(harness.manager.radioWiFiState(for: harness.deviceB.radioID).rebootPending == holdAfterCommit) + if holdAfterCommit { + #expect(harness.manager.pendingIdentityReconciliations[harness.deviceA.id] == nil) + } else { + #expect(harness.manager.pendingIdentityReconciliations[harness.deviceA.id]?.publicKey == CanonicalIdentityFixture.publicKey) + } + if !cancelWaiter { + #expect(harness.manager.connectedDevice?.publicKey == harness.deviceB.publicKey) + #expect(harness.manager.services?.settingsService.radioWiFiState.rebootPending == false) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + let writesBeforeKnownRetry = await IdentityRecoveryFixture.keyWriteCount(harness) + _ = try await harness.manager.connect(to: harness.deviceA.id, forceReconnect: true) + let writesAfterKnownRetry = await IdentityRecoveryFixture.keyWriteCount(harness) + #expect(writesAfterKnownRetry == writesBeforeKnownRetry) + #expect(harness.manager.connectedDevice?.radioID == harness.deviceB.radioID) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } catch { + gate.open() + _ = await retrying.result + _ = await successor?.result + harness.manager.testIdentityBeforeCommit = nil + harness.manager.testIdentityAfterCommit = nil + throw error + } + } + } + + @Test(.timeLimit(.minutes(1))) + func `cancelled identity recovery settles while its link is still retiring`() async throws { + try await ConnectionRadioHandoffHarness.withHarness(wifiIsSameRadio: false) { harness in + try await harness.connectBluetooth() + let original = try await IdentityRecoveryFixture.interrupt(harness) + await harness.wifi.setDeviceID(harness.deviceB.id) + _ = try await harness.manager.connectViaWiFi(host: "other.local", port: 4242) + let recovery = try #require(harness.manager.prepareIdentityImportRecovery(receiptID: original.receiptID)) + let previousRequest = harness.manager.connectionRequestID + let gate = IdentityRecoveryFixture.Gate() + harness.manager.testConnectionTeardownHandler = { await gate.wait() } + let retry = harness.track(Task { + try await harness.manager.retryIdentityImport( + confirmation: recovery, privateKey: CanonicalIdentityFixture.privateKey + ) + }) + do { + try await waitUntil("recovery must be admitted and waiting for the unrelated link to retire") { + gate.arrived && harness.manager.connectionRequestID != previousRequest + } + #expect(harness.manager.connectionState == .connecting) + let connectCount = await IdentityRecoveryFixture.connectCount(harness) + let keyWrites = await IdentityRecoveryFixture.keyWriteCount(harness) + retry.cancel() + try await waitUntil("UI cancellation must reach the admitted recovery worker") { + harness.manager.desiredRequest?.worker?.isCancelled == true + } + gate.open() + harness.manager.testConnectionTeardownHandler = nil + let result = try await retry.value + if case .cancelled = result {} else { Issue.record("Expected cancelled recovery result") } + await harness.manager.retirementTask?.value + #expect(harness.manager.currentConnection == nil) + #expect(harness.manager.desiredRequest?.attempt == nil) + #expect(harness.manager.connectionTeardownCount == 0) + #expect(await IdentityRecoveryFixture.connectCount(harness) == connectCount) + #expect(await IdentityRecoveryFixture.keyWriteCount(harness) == keyWrites) + #expect(harness.manager.prepareIdentityImportRecovery(receiptID: original.receiptID) != nil) + #expect(harness.manager.desiredRequest?.target.deviceID == harness.deviceA.id) + #expect(harness.manager.connectionIntent == .wantsConnection(forceFullSync: false)) + #expect(harness.manager.connectionState == .disconnected) + await harness.bluetooth.releaseAllGates() + await harness.wifi.releaseAllGates() + await harness.manager.checkBLEConnectionHealth() + await harness.manager.checkWiFiConnectionHealth() + #expect(harness.manager.connectionState != .connecting) + if harness.manager.connectionState == .ready { + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } catch { + gate.open() + harness.manager.testConnectionTeardownHandler = nil + throw error + } + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/IdentityRecoveryPreflightTests.swift b/MC1Services/Tests/MC1ServicesTests/IdentityRecoveryPreflightTests.swift new file mode 100644 index 0000000000..968625c54c --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/IdentityRecoveryPreflightTests.swift @@ -0,0 +1,128 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Identity recovery preflight") +@MainActor +struct IdentityRecoveryPreflightTests { + @Test(arguments: [false, true]) + func `a replaced source is refused before either transport dials`(viaWiFi: Bool) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + if viaWiFi { + await harness.wifi.setDeviceID(harness.deviceA.id) + _ = try await harness.manager.connectViaWiFi(host: "replaced-source.local", port: 4242) + } else { + try await harness.connectBluetooth() + } + let source = try #require(harness.manager.services) + _ = try await source.settingsService.runCliCommand("set wifi.enabled 0") + let confirmation = try await IdentityRecoveryFixture.interrupt(harness) + let replacementRadioID = UUID() + let replacementKey = Data(repeating: 0xE7, count: ProtocolLimits.publicKeySize) + try await harness.manager.persistenceStore.saveDevice(harness.deviceA.copy { + $0.radioID = replacementRadioID + $0.publicKey = replacementKey + }) + let requestID = harness.manager.connectionRequestID + let connectsBefore = await IdentityRecoveryFixture.connectCount(harness) + var validations = 0 + harness.manager.testIdentityBeforeSourceValidation = { validations += 1 } + await #expect(throws: (any Error).self) { + _ = try await harness.manager.retryIdentityImport( + confirmation: confirmation, privateKey: CanonicalIdentityFixture.privateKey + ) + } + harness.manager.testIdentityBeforeSourceValidation = nil + #expect(validations == 1) + let connectsAfter = await IdentityRecoveryFixture.connectCount(harness) + let keyWrites = await IdentityRecoveryFixture.keyWriteCount(harness) + #expect(connectsAfter == connectsBefore) + #expect(keyWrites == 1) + #expect(harness.manager.connectionRequestID == requestID) + #expect(harness.manager.prepareIdentityImportRecovery(receiptID: confirmation.receiptID) == nil) + let replacement = try #require(try await harness.manager.persistenceStore.fetchDevice(id: harness.deviceA.id)) + #expect(replacement.radioID == replacementRadioID) + #expect(replacement.publicKey == replacementKey) + #expect(source.settingsService.radioWiFiState.rebootPending) + #expect(!harness.manager.radioWiFiState(for: replacementRadioID).rebootPending) + let sourceWasNotPublished = harness.manager.connectedDevice == nil && harness.manager.services == nil + #expect(sourceWasNotPublished) + await harness.wifi.setDeviceID(harness.deviceB.id) + await harness.wifi.setPublicKey(harness.deviceB.publicKey, for: harness.deviceB.id) + _ = try await harness.manager.connectViaWiFi(host: "unrelated-after-replacement.local", port: 4242) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } + + @Test(arguments: [false, true]) + func `cancelled or superseded preflight cannot consume its stale receipt or dial`(superseded: Bool) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await harness.connectBluetooth() + let confirmation = try await IdentityRecoveryFixture.interrupt(harness) + try await harness.manager.persistenceStore.deleteDevice(id: harness.deviceA.id) + let gate = IdentityRecoveryFixture.Gate() + harness.manager.testIdentityBeforeSourceValidation = { await gate.wait() } + let initialRequestID = harness.manager.connectionRequestID + let connectsBefore = await IdentityRecoveryFixture.connectCount(harness) + let retrying = harness.track(Task { + try await harness.manager.retryIdentityImport( + confirmation: confirmation, privateKey: CanonicalIdentityFixture.privateKey + ) + }) + var successor: Task? + do { + try await waitUntil("retry should hold its ordered source preflight before a physical dial") { gate.arrived } + #expect(harness.manager.connectionRequestID == initialRequestID) + if superseded { + await harness.wifi.setDeviceID(harness.deviceB.id) + await harness.wifi.setPublicKey(harness.deviceB.publicKey, for: harness.deviceB.id) + successor = harness.track(Task { + try await harness.manager.connectViaWiFi(host: "successor-during-preflight.local", port: 4242) + }) + try await waitUntil("a fresh choice should invalidate the held confirmation") { + harness.manager.connectionRequestID != initialRequestID + } + } else { + retrying.cancel() + } + let connectsWhileHeld = await IdentityRecoveryFixture.connectCount(harness) + #expect(connectsWhileHeld == connectsBefore) + gate.open() + _ = await retrying.result + _ = try await successor?.value + harness.manager.testIdentityBeforeSourceValidation = nil + #expect(harness.manager.prepareIdentityImportRecovery(receiptID: confirmation.receiptID) != nil) + let keyWritesAfterCancelledChoice = await IdentityRecoveryFixture.keyWriteCount(harness) + #expect(keyWritesAfterCancelledChoice == 1) + if !superseded { + #expect(harness.manager.connectionRequestID == initialRequestID) + await harness.wifi.setDeviceID(harness.deviceB.id) + await harness.wifi.setPublicKey(harness.deviceB.publicKey, for: harness.deviceB.id) + _ = try await harness.manager.connectViaWiFi(host: "successor-after-cancelled-preflight.local", port: 4242) + } + let currentConfirmation = try #require(harness.manager.prepareIdentityImportRecovery(receiptID: confirmation.receiptID)) + let successorRequestID = harness.manager.connectionRequestID + let successorGeneration = harness.manager.currentConnection?.generation + let connectsBeforeFreshConfirmation = await IdentityRecoveryFixture.connectCount(harness) + await #expect(throws: (any Error).self) { + _ = try await harness.manager.retryIdentityImport( + confirmation: currentConfirmation, privateKey: CanonicalIdentityFixture.privateKey + ) + } + let connectsAfterFreshConfirmation = await IdentityRecoveryFixture.connectCount(harness) + #expect(connectsAfterFreshConfirmation == connectsBeforeFreshConfirmation) + #expect(harness.manager.prepareIdentityImportRecovery(receiptID: confirmation.receiptID) == nil) + #expect(harness.manager.connectionRequestID == successorRequestID) + #expect(harness.manager.currentConnection?.generation == successorGeneration) + #expect(harness.manager.connectedDevice?.radioID == harness.deviceB.radioID) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } catch { + gate.open() + _ = await retrying.result + _ = await successor?.result + harness.manager.testIdentityBeforeSourceValidation = nil + throw error + } + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/IdentityRecoverySourceValidationTests.swift b/MC1Services/Tests/MC1ServicesTests/IdentityRecoverySourceValidationTests.swift new file mode 100644 index 0000000000..499a7b4cbb --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/IdentityRecoverySourceValidationTests.swift @@ -0,0 +1,99 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Identity recovery source validation") +@MainActor +struct IdentityRecoverySourceValidationTests { + @Test(arguments: SourceChange.allCases, [false, true]) + func `fresh source validation refuses a deleted demoted or replaced original`( + change: SourceChange, afterConfirmedImport: Bool + ) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await CanonicalIdentityFixture.prepareGhost(in: harness) + try await harness.connectBluetooth() + let source = try #require(harness.manager.services) + _ = try await source.settingsService.runCliCommand("set wifi.enabled 0") + let recovery = try await IdentityRecoveryFixture.interrupt(harness) + let gate = IdentityRecoveryFixture.Gate() + if afterConfirmedImport { + harness.manager.testIdentityBeforeCommit = { await gate.wait() } + } else { + await harness.bluetooth.setPublicKey(harness.deviceA.publicKey, for: harness.deviceA.id) + harness.manager.testIdentityBeforeSourceValidation = { await gate.wait() } + } + let operation = harness.track(Task { + if afterConfirmedImport { + return try await harness.manager.retryIdentityImport(confirmation: recovery, privateKey: CanonicalIdentityFixture.privateKey) + } + return try await harness.manager.connect(to: harness.deviceA.id, forceReconnect: true) + }) + do { + try await waitUntil("source validation should hold before its actor operation") { gate.arrived } + try await change.apply(to: harness) + gate.open() + _ = await operation.result + harness.manager.testIdentityBeforeSourceValidation = nil + harness.manager.testIdentityBeforeCommit = nil + let wasNotPublished = harness.manager.connectedDevice == nil && harness.manager.services == nil + #expect(wasNotPublished) + #expect(harness.manager.identityImportRecoveries.isEmpty) + #expect(!harness.manager.radioWiFiState(for: harness.deviceB.radioID).rebootPending) + let stored = try await harness.manager.persistenceStore.fetchDevice(id: harness.deviceA.id) + switch change { + case .deleted: #expect(stored == nil) + case .demoted: + #expect(stored == nil) + let ghost = try #require(try await harness.manager.persistenceStore.fetchDevice(radioID: harness.deviceA.radioID)) + #expect(ghost.id != harness.deviceA.id) + #expect(ghost.publicKey == harness.deviceA.publicKey) + #expect(ghost.connectionMethods.isEmpty) + case .replaced: + #expect(stored?.publicKey == replacementKey) + #expect(stored?.radioID == replacementRadioID) + } + let writes = await IdentityRecoveryFixture.keyWriteCount(harness) + #expect(writes == (afterConfirmedImport ? 2 : 1)) + await harness.wifi.setDeviceID(harness.deviceB.id) + await harness.wifi.setPublicKey(harness.deviceB.publicKey, for: harness.deviceB.id) + _ = try await harness.manager.connectViaWiFi(host: "fresh-choice.local", port: 4242) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } catch { + gate.open() + _ = await operation.result + harness.manager.testIdentityBeforeSourceValidation = nil + harness.manager.testIdentityBeforeCommit = nil + throw error + } + } + } + + private static let replacementKey = Data(repeating: 0xE2, count: ProtocolLimits.publicKeySize) + private static let replacementRadioID = UUID() + private var replacementKey: Data { + Self.replacementKey + } + + private var replacementRadioID: UUID { + Self.replacementRadioID + } + + enum SourceChange: CaseIterable, Sendable { + case deleted, demoted, replaced + + @MainActor + func apply(to harness: ConnectionRadioHandoffHarness) async throws { + let store = harness.manager.persistenceStore + switch self { + case .deleted: try await store.deleteDevice(id: harness.deviceA.id) + case .demoted: try await store.demoteDeviceToGhost(id: harness.deviceA.id) + case .replaced: + try await store.saveDevice(harness.deviceA.copy { + $0.publicKey = IdentityRecoverySourceValidationTests.replacementKey + $0.radioID = IdentityRecoverySourceValidationTests.replacementRadioID + }) + } + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/IdleIdentityRecoveryRemovalTests.swift b/MC1Services/Tests/MC1ServicesTests/IdleIdentityRecoveryRemovalTests.swift new file mode 100644 index 0000000000..ab0cee35d2 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/IdleIdentityRecoveryRemovalTests.swift @@ -0,0 +1,100 @@ +#if canImport(UIKit) + import AccessorySetupKit +#endif +import Foundation +@testable import MC1Services +import Testing + +@Suite("Idle identity recovery removal") +@MainActor +struct IdleIdentityRecoveryRemovalTests { + @Test(arguments: [false, true], [false, true]) + func `retry of a removed idle source validates and disposes its recovery before another dial`( + deleteData: Bool, viaWiFi: Bool + ) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + harness.pairing.isSessionActive = true + harness.pairing.setPairedAccessories([ + ASAccessory(bluetoothIdentifier: harness.deviceA.id, displayName: "Unresolved source") + ]) + if viaWiFi { + await harness.wifi.setDeviceID(harness.deviceA.id) + _ = try await harness.manager.connectViaWiFi(host: "removed-source.local", port: 4242) + } else { + try await harness.connectBluetooth() + } + let source = try #require(harness.manager.services) + _ = try await source.settingsService.runCliCommand("set wifi.enabled 0") + let history = try await source.messageService.createPendingChannelMessage( + text: "Original saved data", channelIndex: 0, radioID: harness.deviceA.radioID + ) + let confirmation = try await IdentityRecoveryFixture.interrupt(harness) + let sourceWasTerminal = harness.manager.desiredRequest?.target == .disconnected + && harness.manager.connectedDevice == nil && harness.manager.services == nil + #expect(sourceWasTerminal) + let terminalRequestID = harness.manager.connectionRequestID + if deleteData { + let context = try await harness.manager.captureRemoval(id: harness.deviceA.id) + _ = try await harness.manager.forgetDevice(context, deleteData: true) + } else { + try await harness.manager.deleteDevice(id: harness.deviceA.id) + } + #expect(harness.pairing.removeAccessoryCallCount == 1) + let associationWasRemoved = harness.pairing.accessory(for: harness.deviceA.id) == nil + #expect(associationWasRemoved) + #expect(harness.manager.connectionRequestID == terminalRequestID) + let oldHandleWasRemoved = try await harness.manager.persistenceStore.fetchDevice(id: harness.deviceA.id) == nil + #expect(oldHandleWasRemoved) + let retained = try await harness.manager.persistenceStore.fetchDevice(radioID: harness.deviceA.radioID) + let storedHistory = try await harness.manager.persistenceStore.fetchMessage(id: history.id) + if deleteData { + #expect(retained == nil) + #expect(storedHistory == nil) + } else { + let ghost = try #require(retained) + #expect(ghost.id != harness.deviceA.id) + #expect(ghost.publicKey == harness.deviceA.publicKey) + #expect(ghost.connectionMethods.isEmpty) + #expect(storedHistory?.radioID == harness.deviceA.radioID) + } + #expect(source.settingsService.radioWiFiState.rebootPending) + let connectsBeforeStaleConfirmation = await IdentityRecoveryFixture.connectCount(harness) + var sourceValidationCount = 0 + harness.manager.testIdentityBeforeSourceValidation = { sourceValidationCount += 1 } + await #expect(throws: (any Error).self) { + _ = try await harness.manager.retryIdentityImport( + confirmation: confirmation, privateKey: CanonicalIdentityFixture.privateKey + ) + } + harness.manager.testIdentityBeforeSourceValidation = nil + #expect(sourceValidationCount == 1) + let connectsAfterStaleConfirmation = await IdentityRecoveryFixture.connectCount(harness) + let keyWritesAfterStaleConfirmation = await IdentityRecoveryFixture.keyWriteCount(harness) + #expect(connectsAfterStaleConfirmation == connectsBeforeStaleConfirmation) + #expect(keyWritesAfterStaleConfirmation == 1) + #expect(harness.manager.connectionRequestID == terminalRequestID) + let failedRetryDidNotRestoreRecovery = harness.manager.prepareIdentityImportRecovery(receiptID: confirmation.receiptID) == nil + #expect(failedRetryDidNotRestoreRecovery) + let receiptWasDisposed = harness.manager.pendingIdentityReconciliations[harness.deviceA.id] == nil + #expect(receiptWasDisposed) + + await harness.wifi.setDeviceID(harness.deviceB.id) + await harness.wifi.setPublicKey(harness.deviceB.publicKey, for: harness.deviceB.id) + _ = try await harness.manager.connectViaWiFi(host: "unrelated-after-idle-removal.local", port: 4242) + let successorRequestID = harness.manager.connectionRequestID + let successorGeneration = harness.manager.currentConnection?.generation + await #expect(throws: (any Error).self) { + _ = try await harness.manager.retryIdentityImport( + confirmation: confirmation, privateKey: CanonicalIdentityFixture.privateKey + ) + } + #expect(harness.manager.connectionRequestID == successorRequestID) + #expect(harness.manager.currentConnection?.generation == successorGeneration) + #expect(harness.manager.connectedDevice?.radioID == harness.deviceB.radioID) + #expect(harness.manager.services?.settingsService.radioWiFiState.rebootPending == false) + let finalKeyWriteCount = await IdentityRecoveryFixture.keyWriteCount(harness) + #expect(finalKeyWriteCount == 1) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/InterruptedIdentityImportRecoveryTests.swift b/MC1Services/Tests/MC1ServicesTests/InterruptedIdentityImportRecoveryTests.swift new file mode 100644 index 0000000000..5bbd8c62ea --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/InterruptedIdentityImportRecoveryTests.swift @@ -0,0 +1,268 @@ +import Foundation +@testable import MC1Services +import MeshCore +import MeshCoreTestSupport +import os +import Testing + +@Suite("Interrupted identity import recovery") +@MainActor +struct InterruptedIdentityImportRecoveryTests { + struct RecoverySample: Sendable { + var route: RecoveryRoute + var hasGhost: Bool + } + + /// One case for each lost reply, the canonical ghost partition, and a WiFi source. + nonisolated static let recoverySamples: [RecoverySample] = [ + RecoverySample(route: .bluetoothAfterLostSelfInfo, hasGhost: false), + RecoverySample(route: .bluetoothAfterLostAcknowledgement, hasGhost: false), + RecoverySample(route: .bluetoothAfterLostAcknowledgement, hasGhost: true), + RecoverySample(route: .wifiAfterLostSelfInfo, hasGhost: false), + ] + + @Test(arguments: recoverySamples) + func `ordinary source reconnect stops until explicit identity recovery after lost replies`( + _ sample: RecoverySample + ) async throws { + let route = sample.route + let hasGhost = sample.hasGhost + try await ConnectionRadioHandoffHarness.withHarness { harness in + if hasGhost { try await CanonicalIdentityFixture.prepareGhost(in: harness) } + let secret = Data(repeating: 0xCD, count: 16) + await harness.bluetooth.setChannel(index: 0, name: "Retained", secret: secret) + await harness.wifi.setChannel(index: 0, name: "Retained", secret: secret) + let activeRadio = route.usesWiFi ? harness.wifi : harness.bluetooth + let clock = TestClock() + if route.usesWiFi { await harness.wifi.setDeviceID(harness.deviceA.id) } + try await openSource(harness, overWiFi: route.usesWiFi, clock: clock, radio: activeRadio) + let source = try #require(harness.manager.services) + let store = harness.manager.persistenceStore + let stateA = source.settingsService.radioWiFiState + let stateB = harness.manager.radioWiFiState(for: harness.deviceB.radioID) + _ = try await source.settingsService.runCliCommand("set wifi.enabled 0") + let oldPending = try await source.messageService.createPendingChannelMessage( + text: "Original partition unsent", channelIndex: 0, radioID: harness.deviceA.radioID + ) + _ = try await store.insertPendingSendAssigningSequence( + PendingSendDTO(envelope: envelope(oldPending), radioID: harness.deviceA.radioID) + ) + var canonicalPending: MessageDTO? + if hasGhost { + try await store.saveChannel(ChannelDTO.testChannel( + radioID: harness.deviceB.radioID, name: "Retained", secret: secret + )) + let pending = try await source.messageService.createPendingChannelMessage( + text: "Canonical partition waiting", channelIndex: 0, radioID: harness.deviceB.radioID + ) + canonicalPending = pending + _ = try await store.insertPendingSendAssigningSequence( + PendingSendDTO(envelope: envelope(pending), radioID: harness.deviceB.radioID) + ) + } + let startsBefore = await activeRadio.sentData.filter { $0.first == CommandCode.appStart.rawValue }.count + if route.losesAcknowledgement { + await activeRadio.enqueueResponsePackets(for: .importPrivateKey, packets: []) + } else { + await activeRadio.enqueueResponsePackets(for: .appStart, packets: []) + } + let importFinished = OSAllocatedUnfairLock(initialState: false) + let importing = harness.track(Task { + defer { importFinished.withLock { $0 = true } } + try await source.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + }) + try await waitUntil("the actual private-key import should reach the firmware") { + await activeRadio.sentData.contains { $0.first == CommandCode.importPrivateKey.rawValue } + } + await activeRadio.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceA.id) + try await waitForLostImportReply(clock, radio: activeRadio, harness: harness, finished: importFinished) + await #expect(throws: (any Error).self) { try await importing.value } + let startsAfter = await activeRadio.sentData.filter { $0.first == CommandCode.appStart.rawValue }.count + #expect(startsAfter == startsBefore + (route.losesAcknowledgement ? 0 : 1)) + let servicesWereRetired = harness.manager.services == nil + #expect(servicesWereRetired) + #expect(stateA.rebootPending) + #expect(stateA.stableRevision() == nil) + #expect(try await store.fetchDevice(id: harness.deviceA.id)?.publicKey == harness.deviceA.publicKey) + #expect(try await store.fetchDevice(id: harness.deviceA.id)?.radioID == harness.deviceA.radioID) + + let startsBeforeReconnect = await activeRadio.sentData.filter { $0.first == CommandCode.appStart.rawValue }.count + if route.usesWiFi { + await #expect(throws: ConnectionRequestFailure.self) { + _ = try await harness.manager.connectViaWiFi(host: "source.local", port: 4242) + } + } else { + await #expect(throws: ConnectionRequestFailure.self) { + _ = try await harness.manager.connect(to: harness.deviceA.id, forceReconnect: true) + } + } + let sourceWasNotPublished = harness.manager.connectedDevice == nil && harness.manager.services == nil + #expect(sourceWasNotPublished) + #expect(harness.manager.desiredRequest?.target == .disconnected) + #expect(!harness.manager.connectionIntent.wantsConnection) + #expect(stateA.rebootPending) + #expect(!stateB.rebootPending) + #expect(harness.manager.pendingIdentityReconciliations[harness.deviceA.id]?.publicKey == nil) + #expect(try await store.fetchDevice(id: harness.deviceA.id)?.radioID == harness.deviceA.radioID) + #expect(try await store.fetchDevice(id: harness.deviceA.id)?.publicKey == harness.deviceA.publicKey) + #expect(try await store.fetchMessage(id: oldPending.id)?.status == .pending) + #expect(try await store.fetchPendingSends(radioID: harness.deviceA.radioID).contains { $0.messageID == oldPending.id }) + if let canonicalPending { + #expect(try await store.fetchMessage(id: canonicalPending.id)?.status == .pending) + } + let frames = await activeRadio.sentData + let startsAfterReconnect = frames.filter { $0.first == CommandCode.appStart.rawValue }.count + let importsBeforeRetry = frames.filter { $0.first == CommandCode.importPrivateKey.rawValue }.count + let originalQueueWasNotSent = !frames.contains { $0.range(of: Data(oldPending.text.utf8)) != nil } + #expect(startsAfterReconnect == startsBeforeReconnect + 1) + #expect(importsBeforeRetry == 1) + #expect(originalQueueWasNotSent) + if let canonicalPending { + let canonicalQueueWasNotSent = !frames.contains { $0.range(of: Data(canonicalPending.text.utf8)) != nil } + #expect(canonicalQueueWasNotSent) + } + + let recovery = try #require(harness.manager.identityImportRecoveries.first) + let result = try await harness.manager.retryIdentityImport( + confirmation: recovery, privateKey: CanonicalIdentityFixture.privateKey + ) + guard case .operational = result else { Issue.record("Identity recovery did not become operational"); return } + let recovered = try #require(harness.manager.connectedDevice) + let live = try #require(harness.manager.services) + let expectedRadioID = hasGhost ? harness.deviceB.radioID : harness.deviceA.radioID + #expect(recovered.id == harness.deviceA.id) + #expect(recovered.radioID == expectedRadioID) + #expect(recovered.publicKey == CanonicalIdentityFixture.publicKey) + #expect(live.settingsService.radioWiFiState === (hasGhost ? stateB : stateA)) + #expect(live.settingsService.radioWiFiState.rebootPending) + #expect(live.settingsService.radioWiFiState.stableRevision() != nil) + #expect(harness.manager.identityImportRecoveries.isEmpty) + let replayed = canonicalPending ?? oldPending + try await waitUntil("explicit recovery should hydrate only its canonical partition") { + let message = try? await store.fetchMessage(id: replayed.id) + let rows = await (try? store.fetchPendingSends(radioID: expectedRadioID)) ?? [] + return message?.status == .sent && !rows.contains { $0.messageID == replayed.id } + } + if hasGhost { + #expect(try await store.fetchPendingSends(radioID: harness.deviceA.radioID).contains { $0.messageID == oldPending.id }) + #expect(try await store.fetchMessage(id: oldPending.id)?.status == .pending) + } + let fresh = try await live.messageService.createPendingChannelMessage( + text: "Explicit recovery queue is live", channelIndex: 0, radioID: expectedRadioID + ) + try await live.chatSendQueueService.enqueueChannel(envelope(fresh)) + try await waitUntil("fresh recovered send should complete on the actual session") { + await (try? store.fetchMessage(id: fresh.id)?.status) == .sent + } + let recoveredFrames = await activeRadio.sentData + let importCount = recoveredFrames.filter { $0.first == CommandCode.importPrivateKey.rawValue }.count + let sentCanonical = recoveredFrames.contains { $0.range(of: Data(replayed.text.utf8)) != nil } + let sentFresh = recoveredFrames.contains { $0.range(of: Data(fresh.text.utf8)) != nil } + #expect(importCount == 2) + #expect(sentCanonical) + #expect(sentFresh) + if hasGhost { + let oldQueueStayedPut = !recoveredFrames.contains { $0.range(of: Data(oldPending.text.utf8)) != nil } + #expect(oldQueueStayedPut) + } + _ = try await live.settingsService.runCliCommand("set wifi.enabled 1") + #expect(live.settingsService.radioWiFiState.rebootPending) + #expect(try await live.settingsService.getTime().timeIntervalSince1970 > 0) + } + } + + @Test(arguments: [false, true]) + func `fresh WiFi endpoint after interrupted Bluetooth import is a separate ordinary choice`(hasGhost: Bool) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + if hasGhost { try await CanonicalIdentityFixture.prepareGhost(in: harness) } + let clock = TestClock() + try await openSource(harness, overWiFi: false, clock: clock, radio: harness.bluetooth) + let source = try #require(harness.manager.services) + _ = try await source.settingsService.runCliCommand("set wifi.enabled 0") + await harness.bluetooth.enqueueResponsePackets(for: .importPrivateKey, packets: []) + let importFinished = OSAllocatedUnfairLock(initialState: false) + let importing = harness.track(Task { + defer { importFinished.withLock { $0 = true } } + try await source.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: harness.deviceA.radioID + ) + }) + try await waitForLostImportReply(clock, radio: harness.bluetooth, harness: harness, finished: importFinished) + await #expect(throws: (any Error).self) { try await importing.value } + await harness.wifi.setDeviceID(harness.deviceB.id) + await harness.wifi.setPublicKey(CanonicalIdentityFixture.publicKey, for: harness.deviceB.id) + _ = try await harness.manager.connectViaWiFi(host: "fresh.local", port: 4242) + #expect(harness.manager.connectedDevice?.publicKey == CanonicalIdentityFixture.publicKey) + #expect(harness.manager.connectedDevice?.radioID != harness.deviceA.radioID) + #expect((harness.manager.connectedDevice?.radioID == harness.deviceB.radioID) == hasGhost) + #expect(source.settingsService.radioWiFiState.rebootPending) + #expect(harness.manager.services?.settingsService.radioWiFiState.rebootPending == false) + #expect(harness.manager.pendingIdentityReconciliations[harness.deviceA.id] != nil) + #expect(try await harness.manager.services?.settingsService.getTime() != nil) + } + } + + private func openSource( + _ harness: ConnectionRadioHandoffHarness, + overWiFi: Bool, + clock: TestClock, + radio: ConnectionTestRadioTransport + ) async throws { + harness.manager.sessionClockForTesting = clock + try await resultAdvancingMatchedSessionClock(clock, observation: { + await sessionClockObservation(radio: radio, session: harness.manager.session) + }) { + if overWiFi { + _ = try await harness.manager.connectViaWiFi(host: "source.local", port: 4242) + } else { + try await harness.connectBluetooth() + } + } + harness.manager.sessionClockForTesting = nil + } + + private func waitForLostImportReply( + _ clock: TestClock, + radio: ConnectionTestRadioTransport, + harness: ConnectionRadioHandoffHarness, + finished: OSAllocatedUnfairLock + ) async throws { + try await advanceParkedMatchedSessionClock(clock, "lost identity reply should time out", observation: { + await sessionClockObservation(radio: radio, session: harness.manager.session) + }) { + finished.withLock { $0 } + } + } + + private func envelope(_ message: MessageDTO) -> ChannelMessageEnvelope { + ChannelMessageEnvelope( + messageID: message.id, channelIndex: 0, isResend: false, messageText: message.text, + messageTimestamp: message.timestamp, localNodeName: "Recovery radio" + ) + } + + enum RecoveryRoute: Sendable { + case bluetoothAfterLostSelfInfo + case bluetoothAfterLostAcknowledgement + case wifiAfterLostSelfInfo + case wifiAfterLostAcknowledgement + + var usesWiFi: Bool { + switch self { + case .bluetoothAfterLostSelfInfo, .bluetoothAfterLostAcknowledgement: false + case .wifiAfterLostSelfInfo, .wifiAfterLostAcknowledgement: true + } + } + + var losesAcknowledgement: Bool { + switch self { + case .bluetoothAfterLostSelfInfo, .wifiAfterLostSelfInfo: false + case .bluetoothAfterLostAcknowledgement, .wifiAfterLostAcknowledgement: true + } + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/MECP/en.lproj/Chats.strings b/MC1Services/Tests/MC1ServicesTests/MECP/en.lproj/Chats.strings new file mode 100644 index 0000000000..1fea3d72cf --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/MECP/en.lproj/Chats.strings @@ -0,0 +1,2 @@ +/* Location: MECPCatalog - Person count line in an MECP reading */ +"chats.message.mecpPersonCount" = "%lld people"; diff --git a/MC1Services/Tests/MC1ServicesTests/MECP/en.lproj/Chats.stringsdict b/MC1Services/Tests/MC1ServicesTests/MECP/en.lproj/Chats.stringsdict new file mode 100644 index 0000000000..7fc515f847 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/MECP/en.lproj/Chats.stringsdict @@ -0,0 +1,22 @@ + + + + + chats.message.mecpPersonCount + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + lld + one + %lld person + other + %lld people + + + + diff --git a/MC1Services/Tests/MC1ServicesTests/MECPCatalogTests.swift b/MC1Services/Tests/MC1ServicesTests/MECPCatalogTests.swift new file mode 100644 index 0000000000..60650608bd --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/MECPCatalogTests.swift @@ -0,0 +1,144 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("MECP catalog") +struct MECPCatalogTests { + private let canonical = "MECP/0/M01 M02 T04 3pax 48.8566,2.3522 @1430 @en" + private let englishReading = [ + "MAYDAY", + "Injury", + "Unconscious person", + "Flooding", + "3 people", + "14:30 UTC", + "48.8566,2.3522 @en", + ].joined(separator: "\n") + + @Test + func `the canonical reading joins severity, phrases, the count, the clock, and the leftover tail`() throws { + let reading = try #require(MECPCatalog.reading(canonical, bundle: .module, preferredLocalizations: ["en"])) + #expect(reading == englishReading) + let display = MECPCatalog.displayText(canonical, bundle: .module, preferredLocalizations: ["en"]) + #expect(display == englishReading.replacingOccurrences(of: "\n", with: " ")) + #expect(!display.contains("3pax")) + #expect(!display.contains("@1430")) + #expect(!display.contains("Person count")) + } + + @Test + func `one person uses the singular quantity line`() { + let display = MECPCatalog.displayText("MECP/3/M01 1pax", bundle: .module, preferredLocalizations: ["en"]) + #expect(display.contains("1 person")) + #expect(!display.contains("1 people")) + } + + @Test + func `an R03 eta replaces the bracket slot and leaves the unit word`() { + #expect(display("MECP/1/R03 15", localization: "en") == "URGENT ETA 15 minutes") + #expect(display("MECP/1/R03 15", localization: "de") == "DRINGEND Ankunft in 15 Minuten") + #expect(display("MECP/1/R03 15", localization: "zh-Hans") == "紧急 预计到达 15 分钟") + + let slots = [ + "es": "Llegada est. 15 minutos", + "fr": "Arrivée dans 15 minutes", + "it": "Arrivo stimato 15 minuti", + "nl": "Aankomst over 15 minuten", + "pl": "Czas przybycia 15 minuty", + "pt": "Chegada em 15 minutos", + "ru": "Время прибытия 15 минут", + "uk": "Час прибуття 15 хвилин", + ] + for (localization, phrase) in slots { + let text = display("MECP/1/R03 15", localization: localization) + #expect(text.contains(phrase)) + #expect(!text.contains("[")) + #expect(text.filter { $0 == "1" }.count == 1) + } + + let unset = display("MECP/1/R03 near 15", localization: "en") + #expect(unset.contains("[minutes]")) + } + + @Test + func `H07 replaces the N slot with the person count`() { + let text = display("MECP/3/H07 4pax", localization: "en") + #expect(text.contains("Have shelter / space for 4pax")) + #expect(!text.contains("[N]")) + } + + @Test + func `pack choice uses the first preferred localization`() { + let available = ["en", "de", "zh-Hans", "ko"] + let simplified = Bundle.preferredLocalizations(from: available, forPreferences: ["zh-Hans"]) + #expect(MECPCatalog.firstPreferredLocalization(simplified) == "zh-Hans") + let simplifiedText = MECPCatalog.displayText( + "MECP/0/M01", + bundle: .module, + preferredLocalizations: simplified + ) + #expect(simplifiedText.contains("受伤")) + #expect(!simplifiedText.contains("Injury")) + + #expect(display("MECP/0/M01", localization: "de").contains("Verletzung")) + + let korean = display("MECP/0/M01 1pax", localization: "ko") + #expect(korean.contains("Injury")) + #expect(korean.contains("1 person")) + let koreanMany = display("MECP/0/M01 3pax", localization: "ko") + #expect(koreanMany.contains("3 people")) + } + + @Test + func `a code missing from English uses the active pack unknown label`() throws { + let english = try #require(MECPCatalog.languagePack(stem: "en")) + let unknown = try #require(english.unknownCode) + #expect(unknown == "Unknown code") + let englishText = display("MECP/0/Z99", localization: "en") + #expect(englishText.hasSuffix("Z99: \(unknown)")) + + let german = display("MECP/0/Z99", localization: "de") + #expect(german.hasSuffix("Unbekannter Code")) + } + + @Test + func `a pack with no unknown label uses the literal fallback`() throws { + let data = Data(#"{"severities":{"0":{"local":"MAYDAY"}},"codes":{},"ui":{}}"#.utf8) + let pack = try #require(MECPCatalog.LanguagePack(data: data)) + let english = MECPCatalog.LanguagePack(severityLocal: [:], codes: [:], unknownCode: nil) + let message = try #require(MECPDecode.decode("MECP/0/Z99")) + #expect(MECPCatalog.phrase(for: "Z99", message: message, pack: pack, english: english) == "Z99: Unknown code") + } + + @Test + func `every English code exists in the other packs`() throws { + let english = try #require(MECPCatalog.languagePack(stem: "en")) + let others = MECPCatalog.packStems.filter { $0 != "en" } + for stem in others { + let pack = try #require(MECPCatalog.languagePack(stem: stem)) + let missing = english.codes.keys.filter { pack.codes[$0] == nil }.sorted() + #expect(missing.isEmpty) + } + } + + @Test + func `a failed pack load returns the input unchanged`() { + let input = "MECP/0/M01" + let display = MECPCatalog.displayText( + input, + bundle: .module, + preferredLocalizations: ["en"], + resourceBundle: .module + ) + #expect(display == input) + } + + @Test + func `text that does not decode is unchanged`() { + #expect(MECPCatalog.displayText("hello", bundle: .module, preferredLocalizations: ["en"]) == "hello") + } + + private func display(_ text: String, localization: String) -> String { + MECPCatalog.displayText(text, bundle: .module, preferredLocalizations: [localization]) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/MECPDecodeTests.swift b/MC1Services/Tests/MC1ServicesTests/MECPDecodeTests.swift new file mode 100644 index 0000000000..cbf6f17f3a --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/MECPDecodeTests.swift @@ -0,0 +1,96 @@ +@testable import MC1Services +import Testing + +@Suite("MECP decode") +struct MECPDecodeTests { + @Test + func `empty string, bare prefix, bad severity, and lowercase prefix are nil`() { + #expect(MECPDecode.decode("") == nil) + #expect(MECPDecode.decode("MECP/") == nil) + #expect(MECPDecode.decode("MECP/5/M01") == nil) + #expect(MECPDecode.decode("mecp/0/M01") == nil) + } + + @Test + func `a valid severity is a message when the slash is missing`() throws { + let bare = try #require(MECPDecode.decode("MECP/0")) + #expect(bare.severity == .mayday) + #expect(bare.codes.isEmpty) + #expect(bare.freetext == nil) + + let skippedDelimiter = try #require(MECPDecode.decode("MECP/0XM01")) + #expect(skippedDelimiter.codes == ["M01"]) + #expect(skippedDelimiter.freetext == nil) + + let emptyBody = try #require(MECPDecode.decode("MECP/0/")) + #expect(emptyBody.codes.isEmpty) + #expect(emptyBody.freetext == nil) + } + + @Test + func `codes stop at the first token that is not a code and a later code stays in the tail`() throws { + let message = try #require(MECPDecode.decode("MECP/1/M09 12pax T03")) + #expect(message.codes == ["M09"]) + #expect(message.personCount == 12) + #expect(message.displayTail == "T03") + } + + @Test + func `drill and beacon codes are ordinary codes`() throws { + let drill = try #require(MECPDecode.decode("MECP/0/D01 M01")) + #expect(drill.codes == ["D01", "M01"]) + #expect(drill.freetext == nil) + + let beacon = try #require(MECPDecode.decode("MECP/0/B01 M01")) + #expect(beacon.codes == ["B01", "M01"]) + #expect(beacon.freetext == nil) + } + + @Test + func `empty tokens are dropped before the code scan`() throws { + let message = try #require(MECPDecode.decode("MECP/0/M01 M02")) + #expect(message.codes == ["M01", "M02"]) + #expect(message.freetext == nil) + } + + @Test + func `a repeated space before an R03 eta still fills eta and clears the tail`() throws { + let message = try #require(MECPDecode.decode("MECP/1/R03 15")) + #expect(message.codes == ["R03"]) + #expect(message.eta == 15) + #expect(message.displayTail == nil) + + let spaced = try #require(MECPDecode.decode("MECP/1/R03 15")) + #expect(spaced.eta == 15) + #expect(spaced.displayTail == nil) + + let kept = try #require(MECPDecode.decode("MECP/1/R03 15 near")) + #expect(kept.eta == 15) + #expect(kept.displayTail == "near") + } + + @Test + func `a timestamp must be four digits at a token boundary and in range`() throws { + let punctuated = try #require(MECPDecode.decode("MECP/1/M01 arrived @1430.")) + #expect(punctuated.timestampHHMM == nil) + #expect(punctuated.displayTail == "arrived @1430.") + + let invalid = try #require(MECPDecode.decode("MECP/3/R01 @2400 @1430")) + #expect(invalid.timestampHHMM == nil) + #expect(invalid.displayTail == "@2400 @1430") + + let accepted = try #require(MECPDecode.decode("MECP/0/M01 @1430 @en")) + #expect(accepted.timestampHHMM == "1430") + #expect(accepted.displayTail == "@en") + } + + @Test + func `decode keeps a string longer than the sender byte budget`() throws { + #expect(MECPMessage.maxUTF8Bytes == 200) + let input = "MECP/0/" + String(repeating: "A", count: MECPMessage.maxUTF8Bytes) + let message = try #require(MECPDecode.decode(input)) + #expect(message.severity == .mayday) + #expect(message.codes.isEmpty) + #expect(message.freetext == String(repeating: "A", count: MECPMessage.maxUTF8Bytes)) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/MECPNotificationTests.swift b/MC1Services/Tests/MC1ServicesTests/MECPNotificationTests.swift new file mode 100644 index 0000000000..06baad2e10 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/MECPNotificationTests.swift @@ -0,0 +1,31 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("MECP notifications") +struct MECPNotificationTests { + private let canonical = "MECP/0/M01 M02 T04 3pax 48.8566,2.3522 @1430 @en" + + @Test + func `channel arrival body prefixes the sender after the space-joined reading`() { + let reading = MECPCatalog.displayText(canonical, bundle: .module, preferredLocalizations: ["en"]) + let body = NotificationService.arrivalBody( + messageText: canonical, + senderName: "Ada", + bundle: .module + ) + #expect(body == "Ada: \(reading)") + #expect(body.hasPrefix("Ada: MAYDAY")) + #expect(body != "Ada: \(canonical)") + #expect(!body.contains("Ada: MECP")) + } + + @Test + func `reaction quote truncates the space-joined reading`() { + let reading = MECPCatalog.displayText(canonical, bundle: .module, preferredLocalizations: ["en"]) + let quote = NotificationActionHandler.reactionPreview(for: reading) + #expect(reading.count > NotificationActionHandler.reactionPreviewMaxLength) + #expect(quote.hasPrefix("MAYDAY")) + #expect(quote != NotificationActionHandler.reactionPreview(for: canonical)) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/MessageTranslationChromeTests.swift b/MC1Services/Tests/MC1ServicesTests/MessageTranslationChromeTests.swift index e0f6b111c1..6acbf9868d 100644 --- a/MC1Services/Tests/MC1ServicesTests/MessageTranslationChromeTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/MessageTranslationChromeTests.swift @@ -3,9 +3,21 @@ import Testing @Suite("MessageTranslationChrome.resolved") struct MessageTranslationChromeTests { + @Test + func `a reading is none even when a translation is in flight`() { + #expect( + resolve( + detected: .identified(languageCode: "de"), + phase: .inProgress, + preferredLanguageCode: "en", + text: "MECP/0/M01" + ) == nil + ) + } + @Test func `detected German against English is an offer`() { - let chrome = MessageTranslationChrome.resolved( + let chrome = resolve( detected: .identified(languageCode: "de"), phase: nil, preferredLanguageCode: "en" @@ -17,21 +29,21 @@ struct MessageTranslationChromeTests { @Test func `same language as preferred is none`() { #expect( - MessageTranslationChrome.resolved( + resolve( detected: .identified(languageCode: "de"), phase: nil, preferredLanguageCode: "de" ) == nil ) #expect( - MessageTranslationChrome.resolved( + resolve( detected: .identified(languageCode: "de"), phase: nil, preferredLanguageCode: "de-DE" ) == nil ) #expect( - MessageTranslationChrome.resolved( + resolve( detected: .identified(languageCode: "zh"), phase: nil, preferredLanguageCode: "zh-Hans" @@ -42,21 +54,21 @@ struct MessageTranslationChromeTests { @Test func `present nil detection is none`() { #expect( - MessageTranslationChrome.resolved( + resolve( detected: nil, phase: nil, preferredLanguageCode: "en" ) == nil ) #expect( - MessageTranslationChrome.resolved( + resolve( detected: nil, phase: .offer, preferredLanguageCode: "en" ) == nil ) #expect( - MessageTranslationChrome.resolved( + resolve( detected: .undetermined, phase: .offer, preferredLanguageCode: "en" @@ -66,7 +78,7 @@ struct MessageTranslationChromeTests { @Test func `inProgress is kept`() { - let chrome = MessageTranslationChrome.resolved( + let chrome = resolve( detected: .identified(languageCode: "de"), phase: .inProgress, preferredLanguageCode: "en" @@ -80,7 +92,7 @@ struct MessageTranslationChromeTests { translatedText: "Hello", targetLanguageCode: "en" ) - let chrome = MessageTranslationChrome.resolved( + let chrome = resolve( detected: .identified(languageCode: "de"), phase: showing, preferredLanguageCode: "en" @@ -90,7 +102,7 @@ struct MessageTranslationChromeTests { @Test func `showing for a different target falls back to offer`() { - let chrome = MessageTranslationChrome.resolved( + let chrome = resolve( detected: .identified(languageCode: "de"), phase: .showing(translatedText: "Hello", targetLanguageCode: "en"), preferredLanguageCode: "fr" @@ -101,11 +113,25 @@ struct MessageTranslationChromeTests { @Test func `showing for a different target that matches the source is none`() { #expect( - MessageTranslationChrome.resolved( + resolve( detected: .identified(languageCode: "de"), phase: .showing(translatedText: "Hello", targetLanguageCode: "en"), preferredLanguageCode: "de" ) == nil ) } + + private func resolve( + detected: DetectedLanguage?, + phase: MessageTranslationChrome.Phase?, + preferredLanguageCode: String, + text: String = "Hello" + ) -> MessageTranslationChrome? { + MessageTranslationChrome.resolved( + detected: detected, + phase: phase, + preferredLanguageCode: preferredLanguageCode, + text: text + ) + } } diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockAccessorySetupKitService.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockAccessorySetupKitService.swift index 8c96d591bd..114df0d956 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockAccessorySetupKitService.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockAccessorySetupKitService.swift @@ -44,6 +44,8 @@ public final class MockAccessorySetupKitService: AccessorySetupKitServicing { /// modelling the user declining the system removal confirmation so the /// accessory stays registered. public var removeAccessoryError: Error? + public var removeAccessoryGate: AsyncStream? + public var beforeRemovalResult: (@MainActor () async -> Void)? public init() {} @@ -55,6 +57,11 @@ public final class MockAccessorySetupKitService: AccessorySetupKitServicing { storedPairedAccessories = accessories } + public func simulateAccessoryRemoved(_ bluetoothID: UUID) { + storedPairedAccessories.removeAll { $0.bluetoothIdentifier == bluetoothID } + delegate?.accessorySetupKitService(AccessorySetupKitService(), didRemoveAccessoryWithID: bluetoothID) + } + public func activateSession() async throws { activateSessionCallCount += 1 hasActivatedSession = true @@ -79,6 +86,12 @@ public final class MockAccessorySetupKitService: AccessorySetupKitServicing { public func removeAccessory(_ accessory: ASAccessory) async throws { removeAccessoryCallCount += 1 lastRemovedDeviceID = accessory.bluetoothIdentifier + if let gate = removeAccessoryGate { + for await _ in gate { + break + } + } + await beforeRemovalResult?() if let removeAccessoryError { throw removeAccessoryError } diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockBLEStateMachine.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockBLEStateMachine.swift index fea1ec6515..6790377186 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockBLEStateMachine.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockBLEStateMachine.swift @@ -17,6 +17,8 @@ public actor MockBLEStateMachine: BLEStateMachineProtocol { public var stubbedIsDeviceConnectedToSystem: Bool = false public var isDeviceConnectedToSystemHandler: (@Sendable (UUID) -> Bool)? public var stubbedDidStartAdoptingSystemConnectedPeripheral: Bool = false + private var claimsRestorationOnNextAdoption = false + private var releasesOwnershipAfterNextConnectedIDRead = false // MARK: - Protocol Properties @@ -29,7 +31,21 @@ public actor MockBLEStateMachine: BLEStateMachineProtocol { } public var connectedDeviceID: UUID? { - stubbedConnectedDeviceID + let identifier = stubbedConnectedDeviceID + if releasesOwnershipAfterNextConnectedIDRead { + // The restoration predicate compares the id returned below. Later reads + // belong to the handoff, which must see the phase already ended. + releasesOwnershipAfterNextConnectedIDRead = false + stubbedConnectedDeviceID = nil + stubbedIsAutoReconnecting = false + stubbedIsConnected = false + stubbedLinkDiagnostics = BLELinkDiagnostics( + centralState: stubbedLinkDiagnostics.centralState, + phase: .idle, + peripheralState: nil + ) + } + return identifier } public var linkDiagnostics: BLELinkDiagnostics { @@ -40,10 +56,6 @@ public actor MockBLEStateMachine: BLEStateMachineProtocol { stubbedIsBluetoothPoweredOff } - public var hasAutoReconnectingHandler: Bool { - autoReconnectingHandler != nil - } - // MARK: - Recorded Invocations public private(set) var activateCallCount = 0 @@ -55,12 +67,13 @@ public actor MockBLEStateMachine: BLEStateMachineProtocol { // MARK: - Captured Handlers - private var autoReconnectingHandler: (@Sendable (UUID, String) -> Void)? private var bluetoothPoweredOnHandler: (@Sendable () -> Void)? private var bluetoothStateChangeHandler: (@Sendable (CBManagerState) -> Void)? private var deviceDiscoveredHandler: (@Sendable (UUID, String?, Int) -> Void)? public private(set) var recordedBondVerifications: [UUID: Date] = [:] public private(set) var appSessionLiveDeviceID: UUID? + public private(set) var writePacingDelay: TimeInterval = 0 + private var currentSessionBinding: SessionTransportBinding? // MARK: - Initialization @@ -82,6 +95,18 @@ public actor MockBLEStateMachine: BLEStateMachineProtocol { public func startAdoptingSystemConnectedPeripheral(_ deviceID: UUID) -> Bool { startAdoptingSystemConnectedPeripheralCalls.append(deviceID) + if claimsRestorationOnNextAdoption { + claimsRestorationOnNextAdoption = false + stubbedIsAutoReconnecting = true + stubbedIsConnected = false + stubbedConnectedDeviceID = deviceID + stubbedLinkDiagnostics = BLELinkDiagnostics( + centralState: stubbedLinkDiagnostics.centralState, + phase: .restoringState, + peripheralState: "connected" + ) + return false + } return stubbedDidStartAdoptingSystemConnectedPeripheral } @@ -89,12 +114,6 @@ public actor MockBLEStateMachine: BLEStateMachineProtocol { activateCallCount += 1 } - public func setAutoReconnectingHandler(_ handler: @escaping @Sendable (UUID, String) -> Void) { - autoReconnectingHandler = handler - } - - public func setRemoteLinkLostHandler(_ handler: @escaping @Sendable (UUID, CFAbsoluteTime) -> Void) {} - public func setBluetoothPoweredOnHandler(_ handler: @escaping @Sendable () -> Void) { bluetoothPoweredOnHandler = handler } @@ -103,6 +122,13 @@ public actor MockBLEStateMachine: BLEStateMachineProtocol { recordedBondVerifications[deviceID] = date } + public func recordBondVerification(deviceID: UUID, at date: Date, sessionBinding: SessionTransportBinding) { + try? sessionBinding.performIfActive { + currentSessionBinding = sessionBinding + recordedBondVerifications[deviceID] = date + } + } + public func clearBondVerification(deviceID: UUID) { recordedBondVerifications[deviceID] = nil } @@ -111,6 +137,18 @@ public actor MockBLEStateMachine: BLEStateMachineProtocol { appSessionLiveDeviceID = deviceID } + public func setAppSessionLive(deviceID: UUID?, sessionBinding: SessionTransportBinding) { + if deviceID == nil { + guard currentSessionBinding === sessionBinding else { return } + appSessionLiveDeviceID = nil + } else { + try? sessionBinding.performIfActive { + currentSessionBinding = sessionBinding + appSessionLiveDeviceID = deviceID + } + } + } + public func hasBondVerification(deviceID: UUID) -> Bool { recordedBondVerifications[deviceID] != nil } @@ -146,7 +184,14 @@ public actor MockBLEStateMachine: BLEStateMachineProtocol { } public func setWritePacingDelay(_ delay: TimeInterval) { - // No-op for testing + writePacingDelay = delay + } + + public func setWritePacingDelay(_ delay: TimeInterval, sessionBinding: SessionTransportBinding) { + try? sessionBinding.performIfActive { + currentSessionBinding = sessionBinding + writePacingDelay = delay + } } public private(set) var shutdownCallCount = 0 @@ -179,6 +224,8 @@ public actor MockBLEStateMachine: BLEStateMachineProtocol { stubbedIsDeviceConnectedToSystem = false isDeviceConnectedToSystemHandler = nil stubbedDidStartAdoptingSystemConnectedPeripheral = false + claimsRestorationOnNextAdoption = false + releasesOwnershipAfterNextConnectedIDRead = false activateCallCount = 0 isDeviceConnectedToSystemCalls = [] startAdoptingSystemConnectedPeripheralCalls = [] @@ -187,17 +234,13 @@ public actor MockBLEStateMachine: BLEStateMachineProtocol { isScanning = false appDidEnterBackgroundCallCount = 0 appDidBecomeActiveCallCount = 0 - autoReconnectingHandler = nil bluetoothPoweredOnHandler = nil bluetoothStateChangeHandler = nil deviceDiscoveredHandler = nil recordedBondVerifications = [:] appSessionLiveDeviceID = nil - } - - /// Simulates auto-reconnecting event - public func simulateAutoReconnecting(deviceID: UUID, errorInfo: String = "none") { - autoReconnectingHandler?(deviceID, errorInfo) + currentSessionBinding = nil + writePacingDelay = 0 } /// Simulates Bluetooth powered on event @@ -243,6 +286,15 @@ extension MockBLEStateMachine { stubbedDidStartAdoptingSystemConnectedPeripheral = value } + /// The next `startAdoptingSystemConnectedPeripheral` loses to state restoration. + func claimRestorationOnNextAdoption() { + claimsRestorationOnNextAdoption = true + } + + func releaseOwnershipAfterNextConnectedDeviceIDRead() { + releasesOwnershipAfterNextConnectedIDRead = true + } + func setStubbedPhase(_ value: BLEPhaseKind) { stubbedLinkDiagnostics = BLELinkDiagnostics( centralState: stubbedLinkDiagnostics.centralState, diff --git a/MC1Tests/Views/Tools/CLI/MockConfigurationSession.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockConfigurationSession.swift similarity index 85% rename from MC1Tests/Views/Tools/CLI/MockConfigurationSession.swift rename to MC1Services/Tests/MC1ServicesTests/Mocks/MockConfigurationSession.swift index d6809a38f7..e178b86d99 100644 --- a/MC1Tests/Views/Tools/CLI/MockConfigurationSession.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockConfigurationSession.swift @@ -13,12 +13,25 @@ actor MockConfigurationSession: ConfigurationSessionOps { private var deviceTime: Date private var customVars: [String: String] private var suppressWrites = false + /// When set, `exportPrivateKey` returns this key instead of failing the read. + var stubbedExportedPrivateKey: Data? private var nextSetCustomVarErrorCode: UInt8? private var nextGetCustomVarsErrorCode: UInt8? private var nextSetPathHashModeErrorCode: UInt8? + private var coreStatsUptime: UInt32? + private(set) var coreStatsReadCount = 0 + + func setCoreStatsUptime(_ uptime: UInt32?) { + coreStatsUptime = uptime + } private(set) var readCount = 0 private(set) var rebootCalled = false + private(set) var rebootCallCount = 0 + private var rebootError: (any Error & Sendable)? + private var holdReboot = false + private var rebootContinuation: CheckedContinuation? + private(set) var rebootHeld = false private(set) var powerOffCallCount = 0 private var powerOffBehavior: PowerOffBehavior = .poweredOff private(set) var setNameCalls: [String] = [] @@ -43,6 +56,31 @@ actor MockConfigurationSession: ConfigurationSessionOps { private var holdNextCLI = false private var holdSkip: Int? private var heldCLIContinuation: CheckedContinuation? + private var wiFiFirmware: RadioWiFiFirmware? + private var heldWiFiReply: String? + private var wiFiFailures: [String: WiFiFailure] = [:] + + enum WiFiFailure: Sendable { + case rejected + case timeoutBeforeApply + case timeoutAfterApply + } + + func failWiFiCommand(_ command: String, with failure: WiFiFailure) { + wiFiFailures[command] = failure + } + + func useWiFiFirmware(_ firmware: RadioWiFiFirmware) { + wiFiFirmware = firmware + } + + func wiFiBootUses(ssid: String, password: String) -> Bool { + wiFiFirmware?.bootUses(ssid: ssid, password: password) == true + } + + func bootWiFiFirmware() { + wiFiFirmware?.boot() + } func setCLIReply(_ reply: String) { cliReply = reply @@ -75,7 +113,8 @@ actor MockConfigurationSession: ConfigurationSessionOps { /// Returns the parked CLI reply. The reply is the queue head, or `cliReply`. func releaseHeldCLIReply() { - let reply = dequeueCLIReply() + let reply = heldWiFiReply ?? dequeueCLIReply() + heldWiFiReply = nil let continuation = heldCLIContinuation heldCLIContinuation = nil Task.detached { continuation?.resume(returning: reply) } @@ -284,6 +323,28 @@ actor MockConfigurationSession: ConfigurationSessionOps { func reboot() async throws { rebootCalled = true + rebootCallCount += 1 + if holdReboot { + holdReboot = false + rebootHeld = true + await withCheckedContinuation { rebootContinuation = $0 } + rebootHeld = false + } + if let rebootError { throw rebootError } + } + + func holdNextReboot() { + holdReboot = true + } + + func releaseReboot() { + let continuation = rebootContinuation + rebootContinuation = nil + continuation?.resume() + } + + func failReboot(_ error: any Error & Sendable) { + rebootError = error } enum PowerOffBehavior: Sendable { @@ -361,8 +422,21 @@ actor MockConfigurationSession: ConfigurationSessionOps { } } + func runCorrelatedCliCommand(_ command: String) async throws -> String { + try await runCliCommand(command) + } + func runCliCommand(_ command: String) async throws -> String { runCliCommandCalls.append(command) + if let failure = wiFiFailures.removeValue(forKey: command) { + switch failure { + case .rejected: return RadioWiFiFirmware.reflectedReply("Error: rejected", to: command) + case .timeoutBeforeApply: throw MeshCoreError.timeout + case .timeoutAfterApply: + _ = wiFiFirmware?.reply(to: command) + throw MeshCoreError.timeout + } + } if let failure = takeDueCLIFailure() { throw failure } @@ -381,6 +455,9 @@ actor MockConfigurationSession: ConfigurationSessionOps { holdNextCLI = false return await parkCLI(command) } + if let reply = wiFiFirmware?.reply(to: command) { + return reply + } return dequeueCLIReply() } @@ -396,6 +473,7 @@ actor MockConfigurationSession: ConfigurationSessionOps { private func parkCLI(_ command: String) async -> String { heldCLICommand = command + heldWiFiReply = wiFiFirmware?.reply(to: command) let reply = await withCheckedContinuation { (continuation: CheckedContinuation) in heldCLIContinuation = continuation } @@ -429,7 +507,9 @@ actor MockConfigurationSession: ConfigurationSessionOps { func factoryReset() async throws {} func getStatsCore() async throws -> CoreStats { - throw MeshCoreError.timeout + coreStatsReadCount += 1 + guard let coreStatsUptime else { throw MeshCoreError.timeout } + return CoreStats(batteryMV: 3700, uptimeSeconds: coreStatsUptime, errors: 0, queueLength: 0) } func getStatsRadio() async throws -> RadioStats { @@ -440,7 +520,12 @@ actor MockConfigurationSession: ConfigurationSessionOps { throw MeshCoreError.timeout } + func setStubbedExportedPrivateKey(_ key: Data?) { + stubbedExportedPrivateKey = key + } + func exportPrivateKey() async throws -> Data { + if let stubbedExportedPrivateKey { return stubbedExportedPrivateKey } throw MeshCoreError.timeout } diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift index 2000d30e1d..6a8b5113e2 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift @@ -8,7 +8,7 @@ import MeshCore /// /// Also conforms to ``AdvertisingSessionOps`` so services such as /// `AdvertisementService` can be exercised without a second fake session type. -public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps { +public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps, DiagnosticsSessionOps { // MARK: - Connection State public var connectionState: AsyncStream { @@ -32,14 +32,26 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps private var eventSubscriptions: [UUID: EventSubscription] = [:] public func events() async -> AsyncStream { - makeEventStream(filter: nil) + makeEventStream(filter: nil).stream } public func events(filter: EventFilter) async -> AsyncStream { - makeEventStream(filter: filter) + makeEventStream(filter: filter).stream } - private func makeEventStream(filter: EventFilter?) -> AsyncStream { + public func eventsTracked(filter: EventFilter) async -> (id: UUID, stream: AsyncStream) { + let tracked = makeEventStream(filter: filter) + if let event = stubbedWaitForEventResult, filter.matches(event) { + eventSubscriptions[tracked.id]?.continuation.yield(event) + } + return tracked + } + + public func finishEvents(id: UUID) async { + eventSubscriptions.removeValue(forKey: id)?.continuation.finish() + } + + private func makeEventStream(filter: EventFilter?) -> (id: UUID, stream: AsyncStream) { let id = UUID() let (stream, continuation) = AsyncStream.makeStream() eventSubscriptions[id] = EventSubscription(filter: filter, continuation: continuation) @@ -47,7 +59,7 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps guard let self else { return } Task { await self.removeEventSubscription(id: id) } } - return stream + return (id, stream) } private func removeEventSubscription(id: UUID) { @@ -143,6 +155,7 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps /// Channel info to return from getChannel, keyed by index public var stubbedChannels: [UInt8: ChannelInfo] = [:] + private var stubbedGetChannelResults: [Result] = [] public func setStubbedChannels(_ channels: [UInt8: ChannelInfo]) { stubbedChannels = channels @@ -208,17 +221,23 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps /// Results to return from successive `sendLogin` calls, consumed FIFO. public var stubbedSendLoginResults: [Result] = [] + private var sendLoginHold: (@Sendable () async throws -> Void)? /// Result to return from `sendCommand`. The short suggested timeout keeps /// CLI polling loops in tests brief. public var stubbedSendCommandResult: Result = .success( MessageSentInfo(route: 0, expectedAck: Data(), suggestedTimeoutMs: 100) ) + private var sendCommandHold: (@Sendable () async throws -> Void)? public func setSendCommandResult(_ result: Result) { stubbedSendCommandResult = result } + public func setSendCommandHold(_ hold: (@Sendable () async throws -> Void)?) { + sendCommandHold = hold + } + /// Result to return from `requestStatus` when the FIFO list is empty. public var stubbedRequestStatusResult: Result = .failure(NotStubbed.method("requestStatus")) @@ -288,6 +307,7 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps public private(set) var getContactPublicKeys: [Data] = [] public private(set) var addContactInvocations: [AddContactInvocation] = [] public private(set) var sendLoginInvocations: [SendLoginInvocation] = [] + public private(set) var completedSendLoginCount = 0 public private(set) var sendCommandInvocations: [SendCommandInvocation] = [] public private(set) var removeContactPublicKeys: [Data] = [] public private(set) var resetPathPublicKeys: [Data] = [] @@ -347,6 +367,10 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps sendMessageObserver = observer } + public func setWaitForEventResult(_ event: MeshEvent?) { + stubbedWaitForEventResult = event + } + public func setSendChannelMessageError(_ error: Error?) { stubbedSendChannelMessageError = error } @@ -355,11 +379,19 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps stubbedGetChannelError = error } + public func setGetChannelResults(_ results: [Result]) { + stubbedGetChannelResults = results + } + /// Sets the results returned by successive `sendLogin` calls (isolated setter). public func setSendLoginResults(_ results: [Result]) { stubbedSendLoginResults = results } + public func setSendLoginHold(_ hold: (@Sendable () async throws -> Void)?) { + sendLoginHold = hold + } + /// Sets the result returned by `requestStatus` (isolated setter). public func setRequestStatusResult(_ result: Result) { stubbedRequestStatusResult = result @@ -640,6 +672,9 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps public func getChannel(index: UInt8) async throws -> ChannelInfo { getChannelIndices.append(index) + if !stubbedGetChannelResults.isEmpty { + return try stubbedGetChannelResults.removeFirst().get() + } if let error = stubbedGetChannelErrorsByIndex[index] ?? stubbedGetChannelError { throw error } @@ -762,6 +797,10 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps startAutoMessageFetchingCallCount += 1 } + public func suspendMessageFetching() async throws {} + + public func resumeMessageFetching() {} + public func stopAutoMessageFetching() { stopAutoMessageFetchingCallCount += 1 } @@ -779,6 +818,7 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps getContactPublicKeys = [] addContactInvocations = [] sendLoginInvocations = [] + completedSendLoginCount = 0 sendCommandInvocations = [] removeContactPublicKeys = [] resetPathPublicKeys = [] @@ -797,8 +837,11 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps extension MockMeshCoreSession: RemoteAccessSessionOps { public func sendLogin(to destination: Data, password: String) async throws -> MessageSentInfo { sendLoginInvocations.append(SendLoginInvocation(destination: destination, password: password)) + defer { completedSendLoginCount += 1 } guard !stubbedSendLoginResults.isEmpty else { throw NotStubbed.method("sendLogin") } - switch stubbedSendLoginResults.removeFirst() { + let result = stubbedSendLoginResults.removeFirst() + try await sendLoginHold?() + switch result { case let .success(info): return info case let .failure(error): throw error } @@ -815,13 +858,19 @@ extension MockMeshCoreSession: RemoteAccessSessionOps { sendCommandInvocations.append( SendCommandInvocation(destination: destination, command: command, textType: textType) ) - switch stubbedSendCommandResult { + let result = stubbedSendCommandResult + try await sendCommandHold?() + switch result { case let .success(info): return info case let .failure(error): throw error } } - public func sendKeepAlive(to publicKey: Data, syncSince: UInt32) async throws -> MessageSentInfo { + public func sendKeepAlive( + to publicKey: Data, + syncSince: @escaping @Sendable () async throws -> UInt32, + beforeSend: @escaping @Sendable () throws -> Void + ) async throws -> MessageSentInfo { throw NotStubbed.method("sendKeepAlive") } @@ -838,6 +887,10 @@ extension MockMeshCoreSession: RemoteAccessSessionOps { } } + public func requestStatus(from publicKey: Data) async throws -> StatusResponse { + try await requestStatus(from: publicKey, type: .repeater) + } + public func requestStatus(from publicKey: Data, type: ContactType) async throws -> StatusResponse { if !stubbedRequestStatusResults.isEmpty { switch stubbedRequestStatusResults.removeFirst() { @@ -864,6 +917,35 @@ extension MockMeshCoreSession: RemoteAccessSessionOps { } } + public func fetchAllNeighbours( + from publicKey: Data, + orderBy: UInt8, + pubkeyPrefixLength: UInt8 + ) async throws -> NeighboursResponse { + throw NotStubbed.method("fetchAllNeighbours") + } + + public func requestMMA(from publicKey: Data, start: Date, end: Date) async throws -> MMAResponse { + throw NotStubbed.method("requestMMA") + } + + public func requestACL(from publicKey: Data) async throws -> ACLResponse { + throw NotStubbed.method("requestACL") + } + + public func getSelfTelemetry() async throws -> TelemetryResponse { + throw NotStubbed.method("getSelfTelemetry") + } + + public func sendTrace( + tag: UInt32?, + authCode: UInt32?, + flags: UInt8, + path: Data? + ) async throws -> MessageSentInfo { + throw NotStubbed.method("sendTrace") + } + public func requestNeighbours( from publicKey: Data, count: UInt8, diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshTransport.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshTransport.swift index 336f59e37c..331d5a31d7 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshTransport.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshTransport.swift @@ -2,11 +2,7 @@ import Foundation @testable import MC1Services @testable import MeshCore -/// In-memory iOS mesh transport used by the pairing-race integration suite. -/// Records `connect`/`switchDevice` invocations so tests can assert on what -/// the chokepoint actually dispatched. `connect()` deliberately stalls without -/// yielding session bytes — chokepoint-dispatch tests don't need a "ready" -/// session to fire their assertions. +/// Records pairing dispatch and source lifecycle events; session bytes are injected explicitly. public actor MockMeshTransport: iOSMeshTransport { public struct ConnectInvocation: Sendable, Equatable { public let deviceID: UUID? @@ -15,18 +11,19 @@ public actor MockMeshTransport: iOSMeshTransport { public private(set) var connectInvocations: [ConnectInvocation] = [] public private(set) var disconnectInvocations = 0 + public private(set) var sentData: [Data] = [] private var currentDeviceID: UUID? - private var disconnectionHandler: (@Sendable (UUID, Error?) -> Void)? - private var reconnectionHandler: (@Sendable (UUID) -> Void)? - private let dataStream: AsyncStream - /// Retains the stream's continuation so it stays open. Tests don't yield bytes; - /// the stalled stream models a transport that connected at the BLE layer but - /// never delivers session data, letting cancellation/teardown tests run without - /// driving a full session lifecycle. Without this property the continuation - /// would deinit and the stream would finish, ending consumer awaits prematurely. - private let dataContinuation: AsyncStream.Continuation + private var currentBinding: SessionTransportBinding? + private var lifecycleHandler: (@Sendable (BLELifecycleEvent) -> Void)? + private var lifecycleGeneration: UInt64 = 0 + private var lifecycleEventTime = CFAbsoluteTimeGetCurrent() + private var recovering = false + private var dataStream: AsyncStream + /// Keeps the physical stream open until the test injects a reply or renews it. + private var dataContinuation: AsyncStream.Continuation private var connected = false private var connectError: Error? + private var beforeConnect: (@Sendable () async -> Void)? public init() { var continuation: AsyncStream.Continuation! @@ -47,15 +44,80 @@ public actor MockMeshTransport: iOSMeshTransport { public func connect() async throws { connectInvocations.append(ConnectInvocation(deviceID: currentDeviceID, timestamp: Date())) if let connectError { throw connectError } + lifecycleGeneration += 1 + lifecycleEventTime = CFAbsoluteTimeGetCurrent() + recovering = false connected = true } public func disconnect() async { disconnectInvocations += 1 connected = false + recovering = false } - public func send(_ data: Data) async throws {} + public func makeSessionTransport(deviceID: UUID, binding: SessionTransportBinding) -> SessionBoundTransport { + try? binding.performIfActive { + if currentBinding !== binding { currentBinding?.revoke() } + currentDeviceID = deviceID + currentBinding = binding + } + return SessionBoundTransport(transport: self, binding: binding) + } + + public func disconnect(sessionBinding: SessionTransportBinding) async { + guard currentBinding === sessionBinding else { return } + await disconnect() + } + + // Connect completes in one actor turn, so this fixture has no pending setup to cancel. + public func cancelPendingEstablishment(sessionBinding: SessionTransportBinding) {} + public func cancelUnsubmittedWrites(sessionBinding: SessionTransportBinding) {} + + public func connect(sessionBinding: SessionTransportBinding) async throws { + guard currentBinding === sessionBinding else { throw CancellationError() } + await beforeConnect?() + try sessionBinding.performIfActive { + connectInvocations.append(ConnectInvocation(deviceID: currentDeviceID, timestamp: Date())) + if let connectError { throw connectError } + lifecycleGeneration += 1 + lifecycleEventTime = CFAbsoluteTimeGetCurrent() + recovering = false + connected = true + } + } + + public func send(_ data: Data, sessionBinding: SessionTransportBinding) throws { + guard currentBinding === sessionBinding else { throw CancellationError() } + try sessionBinding.performIfActive { sentData.append(data) } + } + + public func receivedData(sessionBinding: SessionTransportBinding) -> AsyncStream { + guard currentBinding === sessionBinding, sessionBinding.isActive else { return AsyncStream { $0.finish() } } + return dataStream + } + + public func refreshDataStream(sessionBinding: SessionTransportBinding) { + guard currentBinding === sessionBinding, sessionBinding.isActive else { return } + refreshDataStream() + } + + public var lifecycleOrigin: BLELifecycleOrigin? { + guard let currentDeviceID, connected || recovering else { return nil } + return BLELifecycleOrigin(deviceID: currentDeviceID, generation: lifecycleGeneration, eventTime: lifecycleEventTime) + } + + public var hasLifecycleHandler: Bool { + lifecycleHandler != nil + } + + public func setLifecycleHandler(_ handler: @escaping @Sendable (BLELifecycleEvent) -> Void) { + lifecycleHandler = handler + } + + public func send(_ data: Data) async throws { + sentData.append(data) + } // MARK: - iOSMeshTransport @@ -63,23 +125,23 @@ public actor MockMeshTransport: iOSMeshTransport { currentDeviceID = id } - public func switchDevice(to deviceID: UUID) async throws { - connectInvocations.append(ConnectInvocation(deviceID: deviceID, timestamp: Date())) - currentDeviceID = deviceID + public func refreshDataStream() { + dataContinuation.finish() + (dataStream, dataContinuation) = AsyncStream.makeStream(of: Data.self) } - public func setDisconnectionHandler(_ handler: @escaping @Sendable (UUID, Error?) -> Void) { - disconnectionHandler = handler + public func primePhysicalLink(deviceID: UUID, generation: UInt64 = 1, recovering: Bool = false) { + currentDeviceID = deviceID + lifecycleGeneration = generation + lifecycleEventTime = CFAbsoluteTimeGetCurrent() + self.recovering = recovering + connected = !recovering } - public func setReconnectionHandler(_ handler: @escaping @Sendable (UUID) -> Void) { - reconnectionHandler = handler + public func simulateReceive(_ data: Data) { + dataContinuation.yield(data) } - /// Protocol stub only. This fixture's contract is that it never yields - /// session bytes, so there is no stream to re-vend. - public func refreshDataStream() {} - // MARK: - Test Helpers /// When set, `connect()` records the invocation then throws this error on every attempt, @@ -89,16 +151,38 @@ public actor MockMeshTransport: iOSMeshTransport { connectError = error } - /// Indicates whether `setReconnectionHandler` was wired up during init. - /// Tests poll this before invoking `simulateReconnection` to avoid races. - public var hasReconnectionHandler: Bool { - reconnectionHandler != nil + /// Runs before the invocation is recorded, so the dial can be rejected in the phase set here. + public func setBeforeConnect(_ hook: (@Sendable () async -> Void)?) { + beforeConnect = hook } - /// Invokes the registered reconnection handler as if iOS auto-reconnect completed - /// for `deviceID`. Mirrors `MockBLEStateMachine.simulateAutoReconnecting` for the - /// completion side of the auto-reconnect lifecycle. + /// Emits a reconnected lifecycle event as if iOS auto-reconnect completed + /// for `deviceID`, including synchronous renewed-stream capture. public func simulateReconnection(deviceID: UUID) { - reconnectionHandler?(deviceID) + currentDeviceID = deviceID + connected = true + recovering = false + refreshDataStream() + let origin = BLELifecycleOrigin(deviceID: deviceID, generation: lifecycleGeneration, eventTime: CFAbsoluteTimeGetCurrent()) + lifecycleHandler?(.reconnected(origin)) + } + + public func simulateAutoReconnecting(deviceID: UUID, errorInfo: String = "none") { + currentBinding?.revoke() + currentDeviceID = deviceID + lifecycleGeneration += 1 + lifecycleEventTime = CFAbsoluteTimeGetCurrent() + connected = false + recovering = true + let origin = BLELifecycleOrigin(deviceID: deviceID, generation: lifecycleGeneration, eventTime: lifecycleEventTime) + lifecycleHandler?(.autoReconnecting(origin, errorInfo: errorInfo)) + } + + public func simulateDisconnection(deviceID: UUID, error: BLEError? = nil) { + currentBinding?.revoke() + connected = false + recovering = false + let origin = BLELifecycleOrigin(deviceID: deviceID, generation: lifecycleGeneration, eventTime: CFAbsoluteTimeGetCurrent()) + lifecycleHandler?(.disconnected(origin, error: error)) } } diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMessagePollingService.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMessagePollingService.swift index c7de04e461..4534afbf67 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMessagePollingService.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMessagePollingService.swift @@ -56,28 +56,28 @@ public actor MockMessagePollingService: MessagePollingServiceProtocol { // MARK: - Captured Handlers /// Captured contact message handler (set via setContactMessageHandler) - public private(set) var capturedContactMessageHandler: (@Sendable (ContactMessage, ContactDTO?, DeliveryContext) async -> Void)? + public private(set) var capturedContactMessageHandler: (@Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void)? /// Captured channel message handler (set via setChannelMessageHandler) - public private(set) var capturedChannelMessageHandler: (@Sendable (ChannelMessage, ChannelDTO?, DeliveryContext) async -> Void)? + public private(set) var capturedChannelMessageHandler: (@Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void)? /// Captured signed message handler (set via setSignedMessageHandler) - public private(set) var capturedSignedMessageHandler: (@Sendable (ContactMessage, ContactDTO?) async -> Void)? + public private(set) var capturedSignedMessageHandler: (@Sendable (ContactMessage, ReceiveScope) async -> Void)? /// Captured CLI message handler (set via setCLIMessageHandler) public private(set) var capturedCLIMessageHandler: (@Sendable (ContactMessage, ContactDTO?) async -> Void)? // MARK: - Handler Setter Methods (matching MessagePollingService) - public func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext) async -> Void) { + public func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void) { capturedContactMessageHandler = handler } - public func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext) async -> Void) { + public func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void) { capturedChannelMessageHandler = handler } - public func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) { + public func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ReceiveScope) async -> Void) { capturedSignedMessageHandler = handler } diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift index b14ae77518..c74506cf44 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift @@ -19,6 +19,7 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { public var stubbedSaveMessageError: Error? public var stubbedFetchMessageError: Error? public var stubbedUpdateMessageStatusError: Error? + public var stubbedResolvePendingAcknowledgementError: Error? public var stubbedSaveContactError: Error? public var stubbedFetchContactError: Error? public var stubbedFetchContactPublicKeysError: Error? @@ -41,6 +42,10 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { public private(set) var deletedChannelMessagesFromSenderCalls: [(senderName: String, radioID: UUID)] = [] public private(set) var updatedMessageStatuses: [(id: UUID, status: MessageStatus)] = [] public private(set) var updatedMessageAcks: [(id: UUID, ackCode: UInt32, status: MessageStatus, roundTripTime: UInt32?)] = [] + public private(set) var resolvePendingAcknowledgementCallCount = 0 + private var resolvePendingAcknowledgementObserver: (@Sendable () async -> Void)? + private var resolvePendingAcknowledgementCompletionObserver: (@Sendable () async -> Void)? + private var updateMessageAckObserver: (@Sendable (MessageStatus) async -> Void)? // MARK: - Initialization @@ -48,6 +53,26 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { // MARK: - Stub Configuration + public func setStubbedUpdateMessageStatusError(_ error: Error?) { + stubbedUpdateMessageStatusError = error + } + + public func setStubbedResolvePendingAcknowledgementError(_ error: Error?) { + stubbedResolvePendingAcknowledgementError = error + } + + public func setResolvePendingAcknowledgementObserver(_ observer: (@Sendable () async -> Void)?) { + resolvePendingAcknowledgementObserver = observer + } + + public func setResolvePendingAcknowledgementCompletionObserver(_ observer: (@Sendable () async -> Void)?) { + resolvePendingAcknowledgementCompletionObserver = observer + } + + public func setUpdateMessageAckObserver(_ observer: (@Sendable (MessageStatus) async -> Void)?) { + updateMessageAckObserver = observer + } + public func setStubbedFetchContactError(_ error: Error?) { stubbedFetchContactError = error } @@ -64,6 +89,10 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { stubbedDeleteContactError = error } + public func setStubbedDebugLogError(_ error: Error?) { + stubbedDebugLogError = error + } + // MARK: - Message Operations public func isDuplicateMessage(deduplicationKey: String, radioID: UUID) async throws -> Bool { @@ -352,6 +381,7 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { public func updateMessageAck(id: UUID, ackCode: UInt32, status: MessageStatus, roundTripTime: UInt32?) async throws { updatedMessageAcks.append((id: id, ackCode: ackCode, status: status, roundTripTime: roundTripTime)) + await updateMessageAckObserver?(status) if let error = stubbedUpdateMessageStatusError { throw error } @@ -420,6 +450,53 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { } } + public func commitOutgoingDirectMessageTimestamp(id: UUID, timestamp: UInt32) async throws -> UInt32? { + guard var message = messages[id] else { return nil } + let replacedTimestamp = message.status == .delivered ? message.timestamp : nil + message.timestamp = timestamp + if replacedTimestamp != nil { + message.status = .pending + } + messages[id] = message + return replacedTimestamp + } + + public func restoreUnacceptedDeliveredDirectMessage(id: UUID, timestamp: UInt32) async throws -> Bool { + guard var message = messages[id] else { return false } + if message.status == .delivered { return true } + guard message.status == .pending else { return false } + message.timestamp = timestamp + message.status = .delivered + messages[id] = message + for row in pendingSends.values where row.messageID == id && row.ackDeadline == nil { + pendingSends[row.id] = replacingAttemptCount(row, with: PersistenceStore.initialAttemptCount) + } + return true + } + + private func replacingAttemptCount(_ row: PendingSendDTO, with attemptCount: Int) -> PendingSendDTO { + PendingSendDTO( + id: row.id, + radioID: row.radioID, + messageID: row.messageID, + kind: row.kind, + contactID: row.contactID, + channelIndex: row.channelIndex, + isResend: row.isResend, + messageText: row.messageText, + messageTimestamp: row.messageTimestamp, + localNodeName: row.localNodeName, + sequence: row.sequence, + enqueuedAt: row.enqueuedAt, + attemptCount: attemptCount, + nextWireAttempt: row.nextWireAttempt, + ackCodes: row.ackCodes, + ackSentAt: row.ackSentAt, + ackDeadline: row.ackDeadline, + isSingleAttempt: row.isSingleAttempt + ) + } + public func updateMessageTimestamp(id: UUID, timestamp: UInt32) async throws { if let message = messages[id] { messages[id] = MessageDTO( @@ -449,32 +526,12 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { } } - public func updateMessageHeardRepeats(id: UUID, heardRepeats: Int) async throws { - if let message = messages[id] { - messages[id] = MessageDTO( - id: message.id, - radioID: message.radioID, - contactID: message.contactID, - channelIndex: message.channelIndex, - text: message.text, - timestamp: message.timestamp, - createdAt: message.createdAt, - direction: message.direction, - status: message.status, - textType: message.textType, - ackCode: message.ackCode, - pathLength: message.pathLength, - snr: message.snr, - senderKeyPrefix: message.senderKeyPrefix, - senderNodeName: message.senderNodeName, - isRead: message.isRead, - replyToID: message.replyToID, - roundTripTime: message.roundTripTime, - heardRepeats: heardRepeats, - retryAttempt: message.retryAttempt, - maxRetryAttempts: message.maxRetryAttempts - ) - } + public func prepareChannelMessageResend(id: UUID, timestamp: UInt32) async throws { + guard var message = messages[id] else { throw PersistenceStoreError.messageNotFound } + message.timestamp = timestamp + message.heardRepeats = 0 + repeatRows.removeAll { $0.messageID == id } + messages[id] = message } public func markMessageAsRead(id: UUID) async throws { @@ -1778,10 +1835,6 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { [] // Stub } - public func deleteMessageRepeats(messageID: UUID) async throws { - // Stub - no-op - } - public func messageRepeatExists(rxLogEntryID: UUID) async throws -> Bool { false // Stub } @@ -1829,6 +1882,7 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { public func admitSentEcho( messageID: UUID, + expectedTimestamp: UInt32, receivedAt: Date, pathNodes: Data, pathLength: UInt8, @@ -1837,6 +1891,7 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { rxLogEntryID: UUID? ) async throws -> Int? { guard var message = messages[messageID] else { throw PersistenceStoreError.messageNotFound } + guard message.timestamp == expectedTimestamp else { return nil } if let rxLogEntryID, repeatRows.contains(where: { $0.rxLogEntryID == rxLogEntryID }) { return nil } @@ -1979,107 +2034,14 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { devices[dto.radioID] = dto } - public func updateDeviceNodeName(radioID: UUID, name: String) async throws { - try mutateDevice(radioID) { $0.nodeName = name } - } - - public func updateDeviceCoordinates(radioID: UUID, latitude: Double, longitude: Double) async throws { - try mutateDevice(radioID) { - $0.latitude = latitude - $0.longitude = longitude - } - } - - public func updateDeviceRadio( - radioID: UUID, - frequency: UInt32, - bandwidth: UInt32, - spreadingFactor: UInt8, - codingRate: UInt8, - appliedRadioPresetID: String? - ) async throws { - try mutateDevice(radioID) { - $0.frequency = frequency - $0.bandwidth = bandwidth - $0.spreadingFactor = spreadingFactor - $0.codingRate = codingRate - $0.appliedRadioPresetID = appliedRadioPresetID - } - } - - public func updateDeviceTxPower(radioID: UUID, txPower: Int8) async throws { - try mutateDevice(radioID) { $0.txPower = txPower } - } - - public func updateDeviceObservation(radioID: UUID, mapped: DeviceDTO) async throws { - try mutateDevice(radioID) { device in - device.publicKey = mapped.publicKey - device.nodeName = mapped.nodeName - device.latitude = mapped.latitude - device.longitude = mapped.longitude - device.frequency = mapped.frequency - device.bandwidth = mapped.bandwidth - device.spreadingFactor = mapped.spreadingFactor - device.codingRate = mapped.codingRate - device.txPower = mapped.txPower - device.manualAddContacts = mapped.manualAddContacts - device.multiAcks = mapped.multiAcks - device.telemetryModeBase = mapped.telemetryModeBase - device.telemetryModeLoc = mapped.telemetryModeLoc - device.telemetryModeEnv = mapped.telemetryModeEnv - device.advertLocationPolicy = mapped.advertLocationPolicy - device.appliedRadioPresetID = mapped.appliedRadioPresetID - } - } - - public func updateDeviceOtherParams(radioID: UUID, intent: OtherParamsIntent) async throws { - try mutateDevice(radioID) { device in - if let manualAddContacts = intent.manualAddContacts { - device.manualAddContacts = manualAddContacts - } - if let telemetryModeBase = intent.telemetryModeBase { - device.telemetryModeBase = telemetryModeBase - } - if let telemetryModeLocation = intent.telemetryModeLocation { - device.telemetryModeLoc = telemetryModeLocation - } - if let telemetryModeEnvironment = intent.telemetryModeEnvironment { - device.telemetryModeEnv = telemetryModeEnvironment - } - if let advertisementLocationPolicy = intent.advertisementLocationPolicy { - device.advertLocationPolicy = advertisementLocationPolicy - } - if let multiAcks = intent.multiAcks { - device.multiAcks = multiAcks - } - } - } - - public func updateDeviceClientRepeat(radioID: UUID, enabled: Bool) async throws { - try mutateDevice(radioID) { $0.clientRepeat = enabled } - } - - public func updateDevicePathHashMode(radioID: UUID, mode: UInt8) async throws { - try mutateDevice(radioID) { $0.pathHashMode = mode } - } - - public func updateDeviceAutoAdd(radioID: UUID, config: UInt8, maxHops: UInt8) async throws { - try mutateDevice(radioID) { - $0.autoAddConfig = config - $0.autoAddMaxHops = maxHops + public func updateDeviceOCVSettings(id: UUID, preset: String, customArray: String?) async throws -> DeviceDTO? { + guard let current = devices.values.first(where: { $0.id == id }) else { return nil } + let updated = current.copy { + $0.ocvPreset = preset + $0.customOCVArrayString = customArray } - } - - public func updateDeviceDefaultFloodScopeName(radioID: UUID, name: String?) async throws { - try mutateDevice(radioID) { $0.defaultFloodScopeName = name } - } - - private func mutateDevice(_ radioID: UUID, _ body: (inout DeviceDTO) -> Void) throws { - guard var device = devices[radioID] else { - throw PersistenceStoreError.deviceNotFound - } - body(&device) - devices[radioID] = device + devices[updated.radioID] = updated + return updated } // MARK: - Room Session State @@ -2091,6 +2053,11 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { public private(set) var savedRemoteNodeSessions: [RemoteNodeSessionDTO] = [] public private(set) var updatedSessionConnections: [(id: UUID, isConnected: Bool, permissionLevel: RoomPermissionLevel)] = [] public private(set) var deletedRemoteNodeSessionIDs: [UUID] = [] + private var updateRemoteNodeSessionConnectionHold: (@Sendable () async -> Void)? + + public func setUpdateRemoteNodeSessionConnectionHold(_ hold: (@Sendable () async -> Void)?) { + updateRemoteNodeSessionConnectionHold = hold + } public func fetchRemoteNodeSession(id: UUID) async throws -> RemoteNodeSessionDTO? { remoteNodeSessions[id] @@ -2167,6 +2134,7 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { public func updateRemoteNodeSessionConnection(id: UUID, isConnected: Bool, permissionLevel: RoomPermissionLevel) async throws { updatedSessionConnections.append((id: id, isConnected: isConnected, permissionLevel: permissionLevel)) + await updateRemoteNodeSessionConnectionHold?() if let session = remoteNodeSessions[id] { remoteNodeSessions[id] = RemoteNodeSessionDTO( id: session.id, @@ -2659,6 +2627,23 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { return id } + public func recordSelfTelemetrySnapshot( + deviceID: UUID, + radioID: UUID, + nodePublicKey: Data, + telemetry: [TelemetrySnapshotEntry]?, + location: NodeLocationFix? + ) async throws -> UUID? { + nil + } + + public func fetchSelfTelemetrySnapshots( + radioID: UUID, + nodePublicKey: Data + ) async throws -> [NodeStatusSnapshotDTO] { + [] + } + /// Rewrites the stored DTO's location by index. The DTO is a value type, so an /// in-place mutation is a full rebuild; the mock keeps this in one helper. private func applyLocation(_ location: NodeLocationFix, to id: UUID) { @@ -2714,12 +2699,78 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { localNodeName: dto.localNodeName, sequence: nextSequence, enqueuedAt: dto.enqueuedAt, - attemptCount: dto.attemptCount + attemptCount: dto.attemptCount, + nextWireAttempt: dto.nextWireAttempt, + ackCodes: dto.ackCodes, + ackSentAt: dto.ackSentAt, + ackDeadline: dto.ackDeadline, + isSingleAttempt: dto.isSingleAttempt ) pendingSends[dto.id] = assigned return nextSequence } + public func savePendingAcknowledgement( + _ dto: PendingSendDTO, replacingPendingSendID: UUID?, markSent: Bool = true + ) async throws -> Bool { + guard var message = messages[dto.messageID], + message.status != .delivered, + message.status != .failed || replacingPendingSendID != nil else { return false } + if let replacingPendingSendID { + guard let existing = pendingSends[replacingPendingSendID], existing.messageID == dto.messageID, + existing.ackDeadline == nil else { return false } + pendingSends[existing.id] = PendingSendDTO( + id: existing.id, + radioID: existing.radioID, + messageID: existing.messageID, + kind: existing.kind, + contactID: existing.contactID, + channelIndex: existing.channelIndex, + isResend: existing.isResend, + messageText: existing.messageText, + messageTimestamp: existing.messageTimestamp, + localNodeName: existing.localNodeName, + sequence: existing.sequence, + enqueuedAt: existing.enqueuedAt, + attemptCount: existing.attemptCount, + nextWireAttempt: existing.nextWireAttempt, + ackCodes: dto.ackCodes, + ackSentAt: dto.ackSentAt, + ackDeadline: dto.ackDeadline, + isSingleAttempt: existing.isSingleAttempt + ) + } else if pendingSends.values.contains(where: { $0.messageID == dto.messageID }) { + return false + } else { + pendingSends[dto.id] = dto + } + if markSent { + message.status = .sent + } else if message.status == .failed { + message.status = .pending + } + messages[dto.messageID] = message + return true + } + + public func resolvePendingAcknowledgement( + id: UUID, expectedDeadline: Date?, status: MessageStatus, ackCode: UInt32?, roundTripTime: UInt32? + ) async throws -> Bool { + resolvePendingAcknowledgementCallCount += 1 + await resolvePendingAcknowledgementObserver?() + if let error = stubbedResolvePendingAcknowledgementError { throw error } + guard let row = pendingSends[id], row.ackDeadline == expectedDeadline else { return false } + if row.ackDeadline != nil { pendingSends[id] = nil } + guard var message = messages[row.messageID], message.status != .delivered, message.status != .failed else { return false } + message.status = status + if status == .failed { message.failureSeen = false } + if let ackCode { message.ackCode = ackCode } + if let roundTripTime { message.roundTripTime = roundTripTime } + messages[row.messageID] = message + await resolvePendingAcknowledgementCompletionObserver?() + return true + } + public func fetchPendingSends(radioID: UUID) async throws -> [PendingSendDTO] { pendingSends.values.filter { $0.radioID == radioID }.sorted { $0.sequence < $1.sequence } } @@ -2740,8 +2791,14 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { } @discardableResult - public func incrementPendingSendAttemptCount(messageID: UUID) async throws -> Int? { - guard let row = pendingSends.values.first(where: { $0.messageID == messageID }) else { return nil } + public func preparePendingSendAttempt(messageID: UUID) async throws -> (pendingSendID: UUID, attemptCount: Int)? { + guard let row = pendingSends.values.first(where: { $0.messageID == messageID && $0.ackDeadline == nil }) else { return nil } + if row.kind == .dm, row.attemptCount == 0, !row.isResend, !row.isSingleAttempt, + var message = messages[messageID], message.radioID == row.radioID, + message.reactionTargetMessageID == nil, message.status == .failed { + message.status = .pending + messages[messageID] = message + } let nextCount = (row.attemptCount ?? 0) + 1 pendingSends[row.id] = PendingSendDTO( id: row.id, @@ -2756,9 +2813,81 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { localNodeName: row.localNodeName, sequence: row.sequence, enqueuedAt: row.enqueuedAt, - attemptCount: nextCount + attemptCount: nextCount, + nextWireAttempt: row.nextWireAttempt, + ackCodes: row.ackCodes, + ackSentAt: row.ackSentAt, + ackDeadline: row.ackDeadline, + isSingleAttempt: row.isSingleAttempt + ) + return (row.id, nextCount) + } + + public func pendingSendWireAttempt(id: UUID) async throws -> UInt8? { + guard let row = pendingSends[id], row.ackDeadline == nil else { return nil } + return row.nextWireAttempt + } + + public func queuedDirectMessageWireAttempts() async throws -> [QueuedDirectMessageWireAttempt] { + pendingSends.values + .filter { $0.ackDeadline == nil && $0.kind == .dm && $0.nextWireAttempt > 0 } + .sorted { $0.sequence < $1.sequence } + .compactMap { row in + guard let message = messages[row.messageID], + message.channelIndex == nil, + message.status != .delivered else { return nil } + return QueuedDirectMessageWireAttempt( + pendingSendID: row.id, + messageID: row.messageID, + timestamp: message.timestamp, + text: message.text, + consumedAttempts: row.nextWireAttempt + ) + } + } + + public func deliverQueuedDirectMessage( + pendingSendID: UUID, + ackCode: UInt32, + roundTripTime: UInt32? + ) async throws -> MessageDTO? { + guard let row = pendingSends[pendingSendID], row.ackDeadline == nil, row.kind == .dm else { return nil } + guard var message = messages[row.messageID], + message.channelIndex == nil, + message.status != .delivered else { return nil } + message.status = .delivered + message.ackCode = ackCode + if let roundTripTime { + message.roundTripTime = roundTripTime + } + messages[row.messageID] = message + pendingSends[pendingSendID] = nil + return message + } + + public func setPendingSendWireAttempt(id: UUID, to next: UInt8) async throws -> Bool { + guard let row = pendingSends[id], row.ackDeadline == nil else { return false } + pendingSends[id] = PendingSendDTO( + id: row.id, + radioID: row.radioID, + messageID: row.messageID, + kind: row.kind, + contactID: row.contactID, + channelIndex: row.channelIndex, + isResend: row.isResend, + messageText: row.messageText, + messageTimestamp: row.messageTimestamp, + localNodeName: row.localNodeName, + sequence: row.sequence, + enqueuedAt: row.enqueuedAt, + attemptCount: row.attemptCount, + nextWireAttempt: next, + ackCodes: row.ackCodes, + ackSentAt: row.ackSentAt, + ackDeadline: row.ackDeadline, + isSingleAttempt: row.isSingleAttempt ) - return nextCount + return true } // MARK: - Test Helpers diff --git a/MC1Services/Tests/MC1ServicesTests/OpportunisticBluetoothStandDownTests.swift b/MC1Services/Tests/MC1ServicesTests/OpportunisticBluetoothStandDownTests.swift index cf5b5bb6fa..f11756f421 100644 --- a/MC1Services/Tests/MC1ServicesTests/OpportunisticBluetoothStandDownTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/OpportunisticBluetoothStandDownTests.swift @@ -2,94 +2,65 @@ import Foundation @testable import MC1Services import Testing -/// Foreground health checks and Bluetooth power-on follow the saved transport. -/// Launch is the only path that falls back from WiFi to Bluetooth. -@Suite("Opportunistic Bluetooth reconnect follows the saved transport") +@Suite("Opportunistic reconnect follows request authority") @MainActor struct OpportunisticBluetoothStandDownTests { - private func dualRow(id: UUID, wifiLast: Bool) -> DeviceDTO { - let bluetooth = ConnectionMethod.bluetooth(peripheralUUID: id, displayName: nil) - let wifi = ConnectionMethod.wifi(host: "10.0.0.4", port: 5000, displayName: nil) - return DeviceDTO.testDevice(id: id).copy { - $0.connectionMethods = wifiLast ? [bluetooth, wifi] : [wifi, bluetooth] - } + @Test(arguments: [false, true]) + func `admitted wifi remains authoritative after recovery gives up`(bluetoothLast: Bool) async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + _ = try await env.connect(.wifi) + let saved = try #require(env.manager.connectedDevice) + env.manager.testWiFiMaxReconnectDuration = .seconds(-1) + await env.wifi.simulateRemoteLoss() + try await waitUntil("wifi should finish bounded recovery") { env.manager.connectionState == .disconnected } + let requestID = env.manager.connectionRequestID + let bluetooth = ConnectionMethod.bluetooth(peripheralUUID: env.deviceID, displayName: nil) + let wifi = ConnectionMethod.wifi(host: "radio.test", port: 5123, displayName: nil) + let updated = saved.copy { $0.connectionMethods = bluetoothLast ? [wifi, bluetooth] : [bluetooth, wifi] } + try await env.manager.persistenceStore.saveDevice(updated) + env.manager.testLastConnectedDeviceID = saved.id + await env.manager.checkBLEConnectionHealth() + await env.manager.handleBluetoothPoweredOn() + #expect(await env.ble.connectCount == 0) + #expect(env.manager.connectionRequestID == requestID) + #expect(env.manager.connectionState == .disconnected) + #expect(env.manager.desiredRequest?.target == .wifi(host: "radio.test", port: 5123)) + } catch { await env.close(); throw error } + await env.close() } - /// WiFi reconnect times out, then a foreground WiFi connect fails. The saved - /// row and the intent to connect stay in place, and no transport is current. - private func giveUpWiFiThenFailForegroundConnect( - env: PairingTestEnvironment, - device: DeviceDTO - ) async throws { - try await env.manager.persistenceStore.saveDevice(device) - env.manager.persistConnection(deviceID: device.id, radioID: device.radioID, deviceName: device.nodeName) - env.manager.testWiFiMaxReconnectDuration = .seconds(-1) - env.manager.setTestState( - connectionState: .ready, - currentTransportType: .wifi, - connectionIntent: .wantsConnection() - ) - env.manager.wifiTransport = WiFiTransport() - await env.manager.checkWiFiConnectionHealth() - try await waitUntil("WiFi reconnect timeout should release the transport") { - env.manager.wifiTransport == nil - && env.manager.currentTransportType == nil - && env.manager.wifiReconnectTask == nil - } - - env.manager.testWiFiConnectHandler = { _, _ in - throw WiFiTransportError.connectionFailed("down") - } - await #expect(throws: WiFiTransportError.self) { - try await env.manager.connectViaWiFi(host: "10.0.0.4", port: 5000) - } - #expect(env.manager.currentTransportType == nil) - #expect(env.manager.connectionIntent.wantsConnection) - } - - @Test - func `wifi last stands down the foreground check and bluetooth power on`() async throws { - let env = try ConnectionManager.createForPairingTesting() - defer { env.cleanup() } - let peripheralID = UUID() - let device = dualRow(id: peripheralID, wifiLast: true) - try await giveUpWiFiThenFailForegroundConnect(env: env, device: device) - await env.transport.setConnectError(BLEError.connectionFailed("down")) - await env.manager.wireTransportHandlers() - - await env.manager.checkBLEConnectionHealth() - let runsBefore = env.manager.testBluetoothPoweredOnHandlerRuns - await env.stateMachine.simulateBluetoothPoweredOn() - try await waitUntil("Bluetooth powered-on handler should finish") { - env.manager.testBluetoothPoweredOnHandlerRuns > runsBefore - } - - let dialed = await env.transport.connectInvocations - #expect(dialed.isEmpty) - let row = try await env.manager.persistenceStore.fetchDevice(id: peripheralID) - #expect(row?.lastUsedConnectionMethod?.isWiFi == true) - } - - @Test - func `bluetooth last lets the powered-on handler dial the peripheral`() async throws { - let env = try ConnectionManager.createForPairingTesting() - defer { env.cleanup() } - let peripheralID = UUID() - let device = dualRow(id: peripheralID, wifiLast: false) - try await giveUpWiFiThenFailForegroundConnect(env: env, device: device) - try await env.manager.persistenceStore.saveDevice(device) - await env.transport.setConnectError(BLEError.connectionFailed("down")) - // An inactive pairing session skips the accessory-list check, so the dial reaches the transport. - env.accessorySetupKit.isSessionActive = false - await env.manager.wireTransportHandlers() - - let runsBefore = env.manager.testBluetoothPoweredOnHandlerRuns - await env.stateMachine.simulateBluetoothPoweredOn() - try await waitUntil("Bluetooth powered-on handler should dial") { - env.manager.testBluetoothPoweredOnHandlerRuns > runsBefore - } - - let dialed = await env.transport.connectInvocations.compactMap(\.deviceID) - #expect(dialed.contains(peripheralID)) + @Test(arguments: [false, true], [false, true]) + func `without a request foreground and power on use saved last method`(bluetoothLast: Bool, powerOn: Bool) async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + let bluetooth = ConnectionMethod.bluetooth(peripheralUUID: env.deviceID, displayName: nil) + let wifi = ConnectionMethod.wifi(host: "radio.test", port: 5123, displayName: nil) + let saved = DeviceDTO.testDevice(id: env.deviceID, publicKey: env.ble.publicKey, isActive: false).copy { + $0.connectionMethods = bluetoothLast ? [wifi, bluetooth] : [bluetooth, wifi] + } + try await env.manager.persistenceStore.saveDevice(saved) + env.manager.testLastConnectedDeviceID = saved.id + env.manager.setTestState(connectionIntent: .wantsConnection()) + #expect(env.manager.connectionRequestID == nil) + if powerOn { + await env.manager.wireTransportHandlers() + let handled = env.manager.testBluetoothPoweredOnHandlerRuns + await env.stateMachine.simulateBluetoothPoweredOn() + try await waitUntil("installed power callback should settle") { env.manager.testBluetoothPoweredOnHandlerRuns == handled + 1 } + } else { + await env.manager.appDidBecomeActive() + } + #expect(await env.ble.connectCount == (bluetoothLast ? 1 : 0)) + if bluetoothLast { + #expect(env.manager.currentTransportType == .bluetooth) + let probed = try await env.manager.session?.getTime() != nil + #expect(probed) + } else { + #expect(env.manager.connectionState == .disconnected) + #expect(env.manager.connectionRequestID == nil) + } + } catch { await env.close(); throw error } + await env.close() } } diff --git a/MC1Services/Tests/MC1ServicesTests/OutgoingReactionPersistenceTests.swift b/MC1Services/Tests/MC1ServicesTests/OutgoingReactionPersistenceTests.swift new file mode 100644 index 0000000000..8261b31747 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/OutgoingReactionPersistenceTests.swift @@ -0,0 +1,235 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Outgoing reaction persistence") +struct OutgoingReactionPersistenceTests { + @Test(arguments: [false, true]) + func `concurrent reaction admission creates one wire message and durable send without a badge`(isDM: Bool) async throws { + let harness = try await makeHarness(isDM: isDM) + let first = harness.outgoing() + let second = harness.outgoing() + + async let firstAdmission = harness.store.admitOutgoingReaction(first) + async let secondAdmission = harness.store.admitOutgoingReaction(second) + let admissions = try await [firstAdmission, secondAdmission] + + let admitted = try #require(admissions.compactMap(\.self).first) + #expect(admissions.compactMap(\.self).count == 1) + let pending = try await harness.store.fetchPendingSends(radioID: harness.target.radioID) + #expect(pending.count == 1) + #expect(pending.first?.messageID == admitted.id) + #expect(pending.first?.attemptCount == 0) + #expect(pending.first?.isSingleAttempt == isDM) + #expect(try await harness.store.fetchMessage(id: admitted.id)?.reactionTargetMessageID == harness.target.id) + #expect(try await harness.store.fetchMessage(id: admitted.id)?.reactionSenderName == "Nate") + #expect(try await harness.store.fetchReactions(for: harness.target.id).isEmpty) + #expect(try await harness.store.fetchMessage(id: harness.target.id)?.reactionSummary == nil) + } + + @Test(arguments: [false, true]) + func `only an accepted reaction materializes one badge and prevents a duplicate send`(isDM: Bool) async throws { + let harness = try await makeHarness(isDM: isDM) + let outgoing = try #require(try await harness.store.admitOutgoingReaction(harness.outgoing())) + #expect(try await harness.store.completeOutgoingReaction(messageID: outgoing.id) == nil) + + try await harness.store.updateMessageStatus(id: outgoing.id, status: .sent) + + let reaction = try #require(try await harness.store.fetchReactions(for: harness.target.id).first) + #expect(reaction.senderName == "Nate") + #expect(reaction.emoji == "👍") + #expect(reaction.rawText == outgoing.text) + #expect(try await harness.store.fetchMessage(id: harness.target.id)?.reactionSummary == "👍:1") + #expect(try await harness.store.completeOutgoingReaction(messageID: outgoing.id)?.inserted == false) + #expect(try await harness.store.admitOutgoingReaction(harness.outgoing()) == nil) + #expect(try await harness.store.fetchReactions(for: harness.target.id).count == 1) + } + + @Test + func `ACK owner conversion commits the badge and a fast delivered ACK keeps it idempotent`() async throws { + let harness = try await makeHarness(isDM: true) + let outgoing = try #require(try await harness.store.admitOutgoingReaction(harness.outgoing())) + let pending = try #require(try await harness.store.fetchPendingSends(radioID: outgoing.radioID).first) + let sentAt = Date() + let deadline = sentAt.addingTimeInterval(60) + let owner = try PendingSendDTO( + id: pending.id, + envelope: DirectMessageEnvelope(messageID: outgoing.id, contactID: #require(outgoing.contactID)), + radioID: outgoing.radioID, ackCodes: [Data([1, 2, 3, 4])], ackSentAt: sentAt, ackDeadline: deadline + ) + + #expect(try await harness.store.savePendingAcknowledgement(owner, replacingPendingSendID: pending.id)) + #expect(try await harness.store.fetchMessage(id: outgoing.id)?.status == .sent) + #expect(try await harness.store.fetchMessage(id: harness.target.id)?.reactionSummary == "👍:1") + #expect(try await harness.store.fetchPendingSends(radioID: outgoing.radioID).first?.ackDeadline == deadline) + #expect(try await harness.store.resolvePendingAcknowledgement( + id: owner.id, expectedDeadline: deadline, status: .delivered, ackCode: 0x0403_0201, roundTripTime: 123 + )) + #expect(try await harness.store.fetchPendingSends(radioID: outgoing.radioID).isEmpty) + #expect(try await harness.store.fetchReactions(for: harness.target.id).count == 1) + #expect(try await harness.store.completeOutgoingReaction(messageID: outgoing.id)?.summary == "👍:1") + } + + @Test + func `a delivered ACK before owner conversion atomically materializes the badge`() async throws { + let harness = try await makeHarness(isDM: true) + let outgoing = try #require(try await harness.store.admitOutgoingReaction(harness.outgoing())) + + try await harness.store.updateMessageAck(id: outgoing.id, ackCode: 0x0403_0201, status: .delivered) + + #expect(try await harness.store.fetchMessage(id: outgoing.id)?.status == .delivered) + #expect(try await harness.store.fetchMessage(id: harness.target.id)?.reactionSummary == "👍:1") + #expect(try await harness.store.completeOutgoingReaction(messageID: outgoing.id)?.inserted == false) + #expect(try await harness.store.fetchReactions(for: harness.target.id).count == 1) + } + + @Test + func `a failed ACK owner save rolls back status and badge together and can retry locally`() async throws { + let harness = try await makeHarness(isDM: true) + let outgoing = try #require(try await harness.store.admitOutgoingReaction(harness.outgoing())) + let pending = try #require(try await harness.store.fetchPendingSends(radioID: outgoing.radioID).first) + let sentAt = Date() + let owner = try PendingSendDTO( + id: pending.id, + envelope: DirectMessageEnvelope(messageID: outgoing.id, contactID: #require(outgoing.contactID)), + radioID: outgoing.radioID, ackCodes: [Data([1, 2, 3, 4])], + ackSentAt: sentAt, ackDeadline: sentAt.addingTimeInterval(60) + ) + await harness.store.setSavePendingAcknowledgementFaultInjection { throw PersistenceFailure.save } + + await #expect(throws: PersistenceFailure.self) { + try await harness.store.savePendingAcknowledgement(owner, replacingPendingSendID: pending.id) + } + + #expect(try await harness.store.fetchMessage(id: outgoing.id)?.status == .pending) + #expect(try await harness.store.fetchReactions(for: harness.target.id).isEmpty) + #expect(try await harness.store.fetchMessage(id: harness.target.id)?.reactionSummary == nil) + #expect(try await harness.store.fetchPendingSends(radioID: outgoing.radioID).first?.ackDeadline == nil) + await harness.store.setSavePendingAcknowledgementFaultInjection(nil) + #expect(try await harness.store.savePendingAcknowledgement(owner, replacingPendingSendID: pending.id)) + #expect(try await harness.store.fetchMessage(id: outgoing.id)?.status == .sent) + #expect(try await harness.store.fetchMessage(id: harness.target.id)?.reactionSummary == "👍:1") + } + + @Test(arguments: [false, true]) + func `terminal failure admits a fresh reaction but active durable work deduplicates it`(isDM: Bool) async throws { + let harness = try await makeHarness(isDM: isDM) + let outgoing = try #require(try await harness.store.admitOutgoingReaction(harness.outgoing())) + try await harness.store.updateMessageStatus(id: outgoing.id, status: .failed) + #expect(try await harness.store.admitOutgoingReaction(harness.outgoing()) == nil) + try await harness.store.deletePendingSendsForMessage(messageID: outgoing.id) + + #expect(try await harness.store.admitOutgoingReaction(harness.outgoing()) != nil) + #expect(try await harness.store.fetchReactions(for: harness.target.id).isEmpty) + } + + @Test(arguments: [false, true]) + func `deleting a target removes its queued reaction and completion cannot resurrect it`(isDM: Bool) async throws { + let harness = try await makeHarness(isDM: isDM) + let outgoing = try #require(try await harness.store.admitOutgoingReaction(harness.outgoing())) + + let deletedCount = try await harness.store.deleteMessageAndCount(id: harness.target.id) + + #expect(deletedCount == 2) + #expect(try await harness.store.fetchMessage(id: outgoing.id) == nil) + #expect(try await harness.store.fetchPendingSends(radioID: outgoing.radioID).isEmpty) + #expect(try await harness.store.completeOutgoingReaction(messageID: outgoing.id) == nil) + #expect(try await harness.store.fetchReactions(for: harness.target.id).isEmpty) + } + + @Test + func `deleting a channel sender also removes reactions targeting that sender`() async throws { + let harness = try await makeHarness(isDM: false) + let outgoing = try #require(try await harness.store.admitOutgoingReaction(harness.outgoing())) + + try await harness.store.deleteChannelMessages(fromSender: "Ada", radioID: outgoing.radioID) + + #expect(try await harness.store.fetchMessage(id: outgoing.id) == nil) + #expect(try await harness.store.fetchPendingSends(radioID: outgoing.radioID).isEmpty) + } + + @Test(arguments: [false, true]) + func `deleting a target also removes reactions and queued sends beneath a failed reaction`(isDM: Bool) async throws { + let harness = try await makeHarness(isDM: isDM) + let failed = try #require(try await harness.store.admitOutgoingReaction(harness.outgoing())) + try await harness.store.updateMessageStatus(id: failed.id, status: .failed) + try await harness.store.deletePendingSendsForMessage(messageID: failed.id) + let failedHarness = Harness(store: harness.store, target: failed) + let nested = try #require(try await harness.store.admitOutgoingReaction(failedHarness.outgoing(emoji: "👀"))) + _ = try await harness.store.admitReaction(ReactionDTO( + messageID: failed.id, emoji: "❤️", senderName: "Bea", messageHash: "reactionhash", rawText: "reaction", + channelIndex: failed.channelIndex, contactID: failed.contactID, radioID: failed.radioID + )) + try await harness.store.saveMessageRepeat(.testRepeat(messageID: failed.id)) + try await harness.store.saveMessageRepeat(.testRepeat(messageID: nested.id)) + + let deletedCount = try await harness.store.deleteMessageAndCount(id: harness.target.id) + + #expect(deletedCount == 3) + #expect(try await harness.store.fetchMessage(id: failed.id) == nil) + #expect(try await harness.store.fetchMessage(id: nested.id) == nil) + #expect(try await harness.store.fetchPendingSends(radioID: failed.radioID).isEmpty) + #expect(try await harness.store.fetchReactions(for: failed.id).isEmpty) + #expect(try await harness.store.fetchMessageRepeats(messageID: failed.id).isEmpty) + #expect(try await harness.store.fetchMessageRepeats(messageID: nested.id).isEmpty) + #expect(try await harness.store.completeOutgoingReaction(messageID: nested.id) == nil) + } + + @Test(arguments: [false, true]) + func `admission rejects a stale or differently scoped target`(isDM: Bool) async throws { + let harness = try await makeHarness(isDM: isDM) + var outgoing = harness.outgoing() + outgoing.radioID = UUID() + #expect(try await harness.store.admitOutgoingReaction(outgoing) == nil) + outgoing = harness.outgoing() + outgoing.text = harness.outgoing(emoji: "👀").text.replacingOccurrences(of: "\n", with: "invalid\n") + #expect(try await harness.store.admitOutgoingReaction(outgoing) == nil) + try await harness.store.deleteMessage(id: harness.target.id) + #expect(try await harness.store.admitOutgoingReaction(harness.outgoing()) == nil) + #expect(try await harness.store.fetchPendingSends(radioID: harness.target.radioID).isEmpty) + } + + private func makeHarness(isDM: Bool) async throws -> Harness { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radioID = UUID() + let target: MessageDTO + if isDM { + let contact = ContactDTO.testContact(radioID: radioID) + try await store.saveContact(contact) + target = .testDirectMessage(radioID: radioID, contactID: contact.id, text: "Target", direction: .incoming) + } else { + let channel = ChannelDTO.testChannel(radioID: radioID) + try await store.saveChannel(channel) + target = .testChannelMessage( + radioID: radioID, channelIndex: channel.index, text: "Target", direction: .incoming, senderNodeName: "Ada" + ) + } + try await store.saveMessage(target) + return Harness(store: store, target: target) + } + + private struct Harness { + let store: PersistenceStore + let target: MessageDTO + + func outgoing(emoji: String = "👍") -> MessageDTO { + let service = ReactionService() + let text: String = if target.channelIndex != nil { + service.buildReactionText( + emoji: emoji, targetSender: target.isOutgoing ? "Nate" : "Ada", + targetText: target.text, targetTimestamp: target.reactionTimestamp + ) + } else { + service.buildDMReactionText(emoji: emoji, targetText: target.text, targetTimestamp: target.reactionTimestamp) + } + return MessageDTO(from: Message( + radioID: target.radioID, contactID: target.contactID, channelIndex: target.channelIndex, + text: text, reactionTargetMessageID: target.id, reactionSenderName: "Nate" + )) + } + } + + private enum PersistenceFailure: Error { + case save + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/PairingStrandedAssociationTests.swift b/MC1Services/Tests/MC1ServicesTests/PairingStrandedAssociationTests.swift index 918d0bc262..ba731a8aed 100644 --- a/MC1Services/Tests/MC1ServicesTests/PairingStrandedAssociationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/PairingStrandedAssociationTests.swift @@ -39,7 +39,8 @@ struct PairingStrandedAssociationTests { try await #expect { try await manager.pairNewDevice() } throws: { error in - guard let pairingError = error as? PairingError else { return false } + guard let failure = error as? ConnectionRequestFailure, + manager.isCurrent(failure), let pairingError = failure.underlying as? PairingError else { return false } return pairingError.isAuthenticationFailure && pairingError.deviceID == deviceID } @@ -68,7 +69,8 @@ struct PairingStrandedAssociationTests { try await #expect { try await manager.pairNewDevice() } throws: { error in - guard let pairingError = error as? PairingError else { return false } + guard let failure = error as? ConnectionRequestFailure, + manager.isCurrent(failure), let pairingError = failure.underlying as? PairingError else { return false } return !pairingError.isAuthenticationFailure && pairingError.deviceID == deviceID } @@ -382,9 +384,14 @@ struct PairingStrandedAssociationTests { connectionIntent: .wantsConnection() ) manager.testPairingAdoptionSettleTimeout = .milliseconds(80) + let request = ConnectionRequest( + targets: [.bluetooth(UUID())], origin: .explicit, forceFullSync: false, forceReconnect: false, continuing: nil + ) + manager.desiredRequest = request + let requestID = request.id try await #expect { - try await manager.waitForPairingAdoptionToSettle() + try await manager.waitForPairingAdoptionToSettle(expectedRequestID: requestID) } throws: { error in if case let BLEError.connectionFailed(detail) = error { return detail == ConnectionManager.pairingAdoptionTimedOutDetail @@ -412,7 +419,8 @@ struct PairingStrandedAssociationTests { try await #expect { try await manager.connect(to: deviceID, forceFullSync: true, forceReconnect: true) } throws: { error in - if case BLEError.deviceConnectedToOtherApp = error { return true } + if let failure = error as? ConnectionRequestFailure, + manager.isCurrent(failure), case BLEError.deviceConnectedToOtherApp = failure.underlying { return true } return false } } @@ -426,132 +434,97 @@ struct PairingStrandedAssociationTests { } } + private func withRadioHarness( + _ operation: @MainActor (ConnectionManagerRadioTestHarness) async throws -> Void + ) async throws { + let env = try ConnectionManagerRadioTestHarness() + do { try await operation(env) } catch { await env.close(); throw error } + await env.close() + } + @Test func `settings removal during a wifi session keeps the row and the session`() async throws { - let suiteName = "test.\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: suiteName)) - defer { defaults.removePersistentDomain(forName: suiteName) } - let env = try ConnectionManager.createForPairingTesting(defaults: defaults) - defer { env.cleanup() } - let manager = env.manager - let peripheralID = UUID() - let radioID = UUID() - let device = dualDevice(id: peripheralID, peripheralID: peripheralID, radioID: radioID) - - try await manager.persistenceStore.saveDevice(device) - manager.persistConnection(deviceID: peripheralID, radioID: radioID, deviceName: device.nodeName) - await manager.recordBondVerification(deviceID: peripheralID) - var clearedLastConnection = false - manager.onLastConnectedDeviceCleared = { clearedLastConnection = true } - manager.wifiTransport = WiFiTransport() - manager.setTestState( - connectionState: .ready, - connectedDevice: device, - currentTransportType: .wifi, - connectionIntent: .wantsConnection() - ) + try await withRadioHarness { env in + _ = try await env.connect(.bluetooth) + _ = try await env.connect(.wifi) + let manager = env.manager + let before = try #require(manager.currentConnection) + let binding = try #require(manager.installedLink?.resource.binding) + await manager.recordBondVerification(deviceID: before.device.id, binding: binding) + var clearedLastConnection = false + manager.onLastConnectedDeviceCleared = { clearedLastConnection = true } + + manager.devicePairing(manager.pairing, didRemoveDeviceWithID: before.device.id) + await manager.metadataCommitTask?.value + try await waitUntil("live WiFi projection should reflect confirmed Bluetooth removal") { + manager.connectedDevice?.bluetoothPeripheralID == nil + } - manager.devicePairing(manager.pairing, didRemoveDeviceWithID: peripheralID) - try await waitUntil("settings removal should strip Bluetooth and keep WiFi") { - let row = try? await manager.persistenceStore.fetchDevice(id: peripheralID) - return row?.connectionMethods == [.wifi(host: "10.0.0.4", port: 5000, displayName: nil)] + #expect(manager.isCurrent(before)) + #expect(manager.connectionState == .ready) + #expect(manager.wifiTransport != nil) + #expect(manager.lastConnectedDeviceID == before.device.id) + #expect(!clearedLastConnection) + #expect(await env.stateMachine.recordedBondVerifications[before.device.id] == nil) + let rows = try await manager.persistenceStore.fetchDevices() + #expect(rows.map(\.id) == [before.device.id]) + #expect(rows.first?.radioID == before.device.radioID) + #expect(rows.first?.connectionMethods.allSatisfy(\.isWiFi) == true) + #expect(try await manager.session?.getTime() != nil) } - - #expect(manager.connectionState == .ready) - #expect(manager.wifiTransport != nil) - #expect(manager.lastConnectedDeviceID == peripheralID) - #expect(clearedLastConnection == false) - #expect(manager.connectedDevice?.bluetoothPeripheralID == nil) - #expect(manager.connectedDevice?.id == peripheralID) - #expect(LastConnectionStore(defaults: defaults).bondVerificationDate(for: peripheralID) == nil) - #expect(await env.stateMachine.recordedBondVerifications[peripheralID] == nil) - let rows = try await manager.persistenceStore.fetchDevices() - #expect(rows.map(\.id) == [peripheralID]) - #expect(rows.first?.radioID == radioID) } @Test func `settings removal during a bluetooth session disconnects and keeps wifi`() async throws { - let env = try ConnectionManager.createForPairingTesting() - defer { env.cleanup() } - let manager = env.manager - let peripheralID = UUID() - let radioID = UUID() - let device = dualDevice(id: peripheralID, peripheralID: peripheralID, radioID: radioID) - - try await manager.persistenceStore.saveDevice(device) - manager.persistConnection(deviceID: peripheralID, radioID: radioID, deviceName: device.nodeName) - manager.setTestState( - connectionState: .connected, - connectedDevice: device, - currentTransportType: .bluetooth, - connectionIntent: .wantsConnection() - ) - let disconnectsBefore = await env.transport.disconnectInvocations - - manager.devicePairing(manager.pairing, didRemoveDeviceWithID: peripheralID) - try await waitUntil("settings removal should disconnect the Bluetooth session") { - manager.connectionState == .disconnected - && manager.connectedDevice == nil - && manager.currentTransportType == nil + try await withRadioHarness { env in + _ = try await env.connect(.bluetooth) + let manager = env.manager + let before = try #require(manager.currentConnection) + let wifi = ConnectionMethod.wifi(host: "radio.test", port: 5123, displayName: nil) + try await manager.persistenceStore.saveDevice(before.device.copy { $0.connectionMethods.append(wifi) }) + let disconnectsBefore = await env.ble.disconnectCount + + manager.devicePairing(manager.pairing, didRemoveDeviceWithID: before.device.id) + await manager.retirementTask?.value + await manager.metadataCommitTask?.value + + #expect(manager.connectionState == .disconnected) + #expect(manager.connectedDevice == nil) + #expect(manager.currentTransportType == nil) + let row = try await manager.persistenceStore.fetchDevice(id: before.device.id) + #expect(row?.connectionMethods == [wifi]) + #expect(row?.radioID == before.device.radioID) + #expect(manager.lastConnectedDeviceID == before.device.id) + #expect(await env.ble.disconnectCount > disconnectsBefore) } - - let row = try await manager.persistenceStore.fetchDevice(id: peripheralID) - #expect(row?.connectionMethods == [.wifi(host: "10.0.0.4", port: 5000, displayName: nil)]) - #expect(row?.radioID == radioID) - #expect(manager.lastConnectedDeviceID == peripheralID) - #expect(await env.transport.disconnectInvocations > disconnectsBefore) } @Test func `settings removal after a wifi give-up disconnects the bluetooth transport`() async throws { - let env = try ConnectionManager.createForPairingTesting() - defer { env.cleanup() } - let manager = env.manager - let peripheralID = UUID() - let radioID = UUID() - let device = dualDevice(id: peripheralID, peripheralID: peripheralID, radioID: radioID) - try await manager.persistenceStore.saveDevice(device) - - manager.testWiFiMaxReconnectDuration = .seconds(-1) - manager.setTestState( - connectionState: .ready, - currentTransportType: .wifi, - connectionIntent: .wantsConnection() - ) - manager.wifiTransport = WiFiTransport() - await manager.checkWiFiConnectionHealth() - try await waitUntil("WiFi reconnect timeout should release the transport") { - manager.wifiTransport == nil && manager.currentTransportType == nil - } - - let session = MeshCoreSession(transport: SimulatorMockTransport()) - let services = try await ServiceContainer.forTesting(session: session, radioID: radioID) - manager.setTestState( - connectionState: .connected, - services: services, - session: session, - connectedDevice: device, - connectionIntent: .wantsConnection() - ) - let promoted = await manager.promoteToReady( - syncResult: FullSyncResult(contacts: .clean, channels: .clean, messages: .clean), - expectedServices: services, - transportType: .bluetooth - ) - #expect(promoted) - #expect(manager.connectionState == .ready) - #expect(manager.wifiTransport == nil) - - let disconnectsBefore = await env.transport.disconnectInvocations - manager.devicePairing(manager.pairing, didRemoveDeviceWithID: peripheralID) - try await waitUntil("settings removal should disconnect Bluetooth") { - manager.connectionState == .disconnected - && manager.currentTransportType == nil + try await withRadioHarness { env in + let manager = env.manager + _ = try await env.connect(.bluetooth) + _ = try await env.connect(.wifi) + manager.testWiFiMaxReconnectDuration = .seconds(-1) + await env.wifi.simulateRemoteLoss() + try await waitUntil("owned WiFi give-up should finish retirement") { + manager.connectionState == .disconnected && manager.connectionTeardownCount == 0 + && manager.wifiReconnectTask == nil + } + _ = try await env.connect(.bluetooth) + let before = try #require(manager.currentConnection) + let disconnectsBefore = await env.ble.disconnectCount + manager.devicePairing(manager.pairing, didRemoveDeviceWithID: before.device.id) + await manager.retirementTask?.value + await manager.metadataCommitTask?.value + + #expect(manager.connectionState == .disconnected) + #expect(manager.wifiTransport == nil) + #expect(await env.ble.disconnectCount > disconnectsBefore) + let row = try await manager.persistenceStore.fetchDevice(id: before.device.id) + #expect(row?.radioID == before.device.radioID) + #expect(row?.connectionMethods.allSatisfy(\.isWiFi) == true) } - - #expect(await env.transport.disconnectInvocations > disconnectsBefore) - #expect(manager.wifiTransport == nil) } @Test diff --git a/MC1Services/Tests/MC1ServicesTests/PairingWhileConnectedTests.swift b/MC1Services/Tests/MC1ServicesTests/PairingWhileConnectedTests.swift index 923eea8354..9ac42a5201 100644 --- a/MC1Services/Tests/MC1ServicesTests/PairingWhileConnectedTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/PairingWhileConnectedTests.swift @@ -21,7 +21,7 @@ struct PairingWhileConnectedTests { let env = try ConnectionManager.createForPairingTesting() defer { env.cleanup() } let manager = env.manager - let stateMachine = env.stateMachine + let transport = env.transport let mockASK = env.accessorySetupKit let oldDeviceID = UUID() let newDeviceID = UUID() @@ -35,6 +35,7 @@ struct PairingWhileConnectedTests { currentTransportType: .bluetooth, connectionIntent: .wantsConnection() ) + _ = manager.seedBLERecoveryRequest(deviceID: oldDeviceID) let waitStarted = AsyncStream.makeStream() let releaseWait = AsyncStream.makeStream() @@ -47,7 +48,7 @@ struct PairingWhileConnectedTests { } try await waitUntil("auto-reconnect handler should be installed") { - await stateMachine.hasAutoReconnectingHandler + await transport.hasLifecycleHandler } let pairTask = Task { try? await manager.pairNewDevice() } @@ -57,7 +58,7 @@ struct PairingWhileConnectedTests { break } - await stateMachine.simulateAutoReconnecting(deviceID: oldDeviceID) + await transport.simulateAutoReconnecting(deviceID: oldDeviceID) // The suppression branch routes through handleConnectionLoss to clear the // stale old-device session. Observing the state transition and connectedDevice @@ -66,7 +67,7 @@ struct PairingWhileConnectedTests { manager.connectionState == .disconnected && manager.connectedDevice == nil } - #expect(manager.activeReconnectDeviceID == nil) + #expect(manager.reconnectionCoordinator.reconnectingDeviceID == nil) #expect(manager.connectedDevice == nil) releaseWait.continuation.finish() @@ -111,8 +112,8 @@ struct PairingWhileConnectedTests { return false } - try await waitUntil("reconnection handler should be installed") { - await mockTransport.hasReconnectionHandler + try await waitUntil("lifecycle handler should be installed") { + await mockTransport.hasLifecycleHandler } let pairTask = Task { try? await manager.pairNewDevice() } @@ -142,79 +143,46 @@ struct PairingWhileConnectedTests { _ = await pairTask.value } - /// pairNewDevice routes through `connect(to:)`'s switch-device branch when an - /// old radio is still connected. Without the catch in `switchDevice`, a mid- - /// switch throw propagates without resetting `connectionState`, `connectedDevice`, - /// or `services` — leaving the UI on `.ready` pointing at the old device while - /// the failure-alert recovery actions act on stale state. - /// - /// The mock ASK starts with empty `pairedAccessories`, so `switchDevice`'s ASK - /// validation throws `ConnectionError.deviceNotFound` for the new device. That - /// throw must drive a clean teardown. @Test - func `pair-while-connected with switchDevice throw leaves state .disconnected`() async throws { - let env = try ConnectionManager.createForPairingTesting() - defer { env.cleanup() } - let manager = env.manager - let mockASK = env.accessorySetupKit - let oldDeviceID = UUID() - let newDeviceID = UUID() - - mockASK.setPickerResult(.success(newDeviceID)) - - // Skip the polling wait so the test exercises the connect/switch path directly. - manager.otherAppWaitStrategyOverride = { _ in false } - - manager.testLastConnectedDeviceID = oldDeviceID - manager.setTestState( - connectionState: .ready, - connectedDevice: DeviceDTO.testDevice(id: oldDeviceID), - currentTransportType: .bluetooth, - connectionIntent: .wantsConnection() - ) - - await #expect(throws: PairingError.self) { - try await manager.pairNewDevice() + func `failed pairing replacement leaves state disconnected`() async throws { + try await withFailedReplacement { manager in + await #expect(throws: ConnectionRequestFailure.self) { try await manager.pairNewDevice() } + #expect(manager.connectionState == .disconnected) + #expect(manager.connectedDevice == nil) + #expect(manager.services == nil) } - - #expect(manager.connectionState == .disconnected, "switchDevice catch must reset state") - #expect(manager.connectedDevice == nil, "switchDevice catch must clear stale device") - #expect(manager.services == nil, "switchDevice catch must clear stale services") } - /// `cleanupConnection` in switchDevice's catch resets state without firing - /// `onConnectionLost`, so AppState observers — and the old radio's Live Activity — - /// would stay stranded on the prior device's connected state. The catch must route - /// through `onConnectionLost` like the transport-loss and reconnect-failure paths. @Test - func `failed switchDevice fires onConnectionLost so observers tear down`() async throws { - let env = try ConnectionManager.createForPairingTesting() - defer { env.cleanup() } - let manager = env.manager - let mockASK = env.accessorySetupKit - let oldDeviceID = UUID() - let newDeviceID = UUID() - - mockASK.setPickerResult(.success(newDeviceID)) - manager.otherAppWaitStrategyOverride = { _ in false } - - manager.testLastConnectedDeviceID = oldDeviceID - manager.setTestState( - connectionState: .ready, - connectedDevice: DeviceDTO.testDevice(id: oldDeviceID), - currentTransportType: .bluetooth, - connectionIntent: .wantsConnection() - ) - - let tracker = SwitchFailureLostTracker() - manager.onConnectionLost = { await tracker.markConnectionLost() } - - await #expect(throws: PairingError.self) { - try await manager.pairNewDevice() + func `failed pairing replacement fires onConnectionLost so observers tear down`() async throws { + try await withFailedReplacement { manager in + let tracker = SwitchFailureLostTracker() + manager.onConnectionLost = { _ in await tracker.markConnectionLost() } + await #expect(throws: ConnectionRequestFailure.self) { try await manager.pairNewDevice() } + #expect(await tracker.connectionLostCalled) } + } - let wasCalled = await tracker.connectionLostCalled - #expect(wasCalled, "switchDevice catch must fire onConnectionLost so AppState retires the orphaned Live Activity") + private func withFailedReplacement(_ body: (ConnectionManager) async throws -> Void) async throws { + let env = try ConnectionManagerRadioTestHarness() + do { + _ = try await env.connect(.bluetooth) + let target = UUID() + env.pairing.isSessionActive = true + env.pairing.setPairedAccessories([ + ASAccessory(bluetoothIdentifier: env.deviceID, displayName: "Current"), + ASAccessory(bluetoothIdentifier: target, displayName: "Replacement") + ]) + try await env.pairing.activateSession() + env.pairing.setPickerResult(.success(target)) + env.manager.otherAppWaitStrategyOverride = { _ in false } + await env.ble.setConnectError(BLEError.deviceNotFound) + try await body(env.manager) + await env.close() + } catch { + await env.close() + throw error + } } } diff --git a/MC1Services/Tests/MC1ServicesTests/PendingAcknowledgementPersistenceTests.swift b/MC1Services/Tests/MC1ServicesTests/PendingAcknowledgementPersistenceTests.swift new file mode 100644 index 0000000000..e2069793cd --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/PendingAcknowledgementPersistenceTests.swift @@ -0,0 +1,216 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Pending acknowledgement persistence") +struct PendingAcknowledgementPersistenceTests { + @Test(arguments: [MessageStatus.delivered, .failed]) + func `a stale ACK owner cannot resolve a replacement manual retry`(status: MessageStatus) async throws { + let fixture = try await makeFixture() + let waiting = acknowledgement(for: fixture.row) + #expect(try await fixture.store.savePendingAcknowledgement(waiting, replacingPendingSendID: fixture.row.id)) + let replacement = PendingSendDTO( + envelope: DirectMessageEnvelope(messageID: fixture.message.id, contactID: fixture.contact.id), + radioID: fixture.row.radioID + ) + _ = try await fixture.store.replacePendingSendForRetry(messageID: fixture.message.id, dto: replacement) + #expect(try await fixture.store.resolvePendingAcknowledgement( + id: waiting.id, expectedDeadline: waiting.ackDeadline, + status: status, ackCode: 123, roundTripTime: nil + ) == false) + #expect(try await fixture.store.fetchMessage(id: fixture.message.id)?.status == .pending) + #expect(try await fixture.store.fetchPendingSends(radioID: fixture.row.radioID).map(\.id) == [replacement.id]) + } + + @Test + func `handoff requires the original ordinary row and cannot convert a replacement`() async throws { + let fixture = try await makeFixture() + let replacement = PendingSendDTO( + envelope: DirectMessageEnvelope(messageID: fixture.message.id, contactID: fixture.contact.id), + radioID: fixture.row.radioID + ) + _ = try await fixture.store.replacePendingSendForRetry(messageID: fixture.message.id, dto: replacement) + #expect(try await fixture.store.savePendingAcknowledgement( + acknowledgement(for: fixture.row), replacingPendingSendID: fixture.row.id + ) == false) + let row = try #require(await fixture.store.fetchPendingSends(radioID: fixture.row.radioID).first) + #expect(row.id == replacement.id) + #expect(row.ackDeadline == nil) + #expect(try await fixture.store.fetchMessage(id: fixture.message.id)?.status == .pending) + } + + @Test + func `a changed phase with the same row id cannot be expired by an old owner`() async throws { + let fixture = try await makeFixture() + let waiting = acknowledgement(for: fixture.row) + #expect(try await fixture.store.savePendingAcknowledgement(waiting, replacingPendingSendID: fixture.row.id)) + try await fixture.store.upsertPendingSend(fixture.row) + #expect(try await fixture.store.resolvePendingAcknowledgement( + id: waiting.id, expectedDeadline: waiting.ackDeadline, + status: .failed, ackCode: nil, roundTripTime: nil + ) == false) + #expect(try await fixture.store.fetchPendingSends(radioID: fixture.row.radioID).first?.ackDeadline == nil) + #expect(try await fixture.store.fetchMessage(id: fixture.message.id)?.status == .sent) + } + + @Test + func `expiry preserves a delivered row and removes only its old owner`() async throws { + let fixture = try await makeFixture() + let waiting = acknowledgement(for: fixture.row) + #expect(try await fixture.store.savePendingAcknowledgement(waiting, replacingPendingSendID: fixture.row.id)) + try await fixture.store.updateMessageAck(id: fixture.message.id, ackCode: 123, status: .delivered, roundTripTime: 456) + #expect(try await fixture.store.resolvePendingAcknowledgement( + id: waiting.id, expectedDeadline: waiting.ackDeadline, + status: .failed, ackCode: nil, roundTripTime: nil + ) == false) + #expect(try await fixture.store.fetchMessage(id: fixture.message.id)?.status == .delivered) + #expect(try await fixture.store.fetchMessage(id: fixture.message.id)?.roundTripTime == 456) + #expect(try await fixture.store.fetchPendingSends(radioID: fixture.row.radioID).isEmpty) + } + + @Test(arguments: [false, true]) + func `restored expiry uses the original absolute deadline across configuration changes`(future: Bool) async throws { + let fixture = try await makeFixture() + let now = Date() + let sentAt = now.addingTimeInterval(-120) + let deadline = now.addingTimeInterval(future ? 120 : -1) + let waiting = acknowledgement(for: fixture.row, sentAt: sentAt, deadline: deadline) + #expect(try await fixture.store.savePendingAcknowledgement(waiting, replacingPendingSendID: fixture.row.id)) + let service = MessageService( + session: MockMeshCoreSession(), dataStore: fixture.store, contactService: nil, + config: MessageServiceConfig(ackGiveUpWindow: future ? 0 : 1000) + ) + try await service.restorePendingAcknowledgements(radioID: fixture.row.radioID) + try await service.checkExpiredAcks() + #expect(try await fixture.store.fetchMessage(id: fixture.message.id)?.status == (future ? .sent : .failed)) + #expect(try await fixture.store.fetchPendingSends(radioID: fixture.row.radioID).isEmpty == !future) + } + + @Test + func `another Radio ID cannot adopt or resolve an ACK owner`() async throws { + let fixture = try await makeFixture() + let waiting = acknowledgement(for: fixture.row) + #expect(try await fixture.store.savePendingAcknowledgement(waiting, replacingPendingSendID: fixture.row.id)) + let service = MessageService(session: MockMeshCoreSession(), dataStore: fixture.store, contactService: nil) + try await service.restorePendingAcknowledgements(radioID: UUID()) + await service.handleAcknowledgement(code: Data([1, 2, 3, 4]), tripTime: 1) + #expect(await service.pendingAckCount == 0) + #expect(try await fixture.store.fetchMessage(id: fixture.message.id)?.status == .sent) + #expect(try await fixture.store.fetchPendingSends(radioID: fixture.row.radioID).count == 1) + } + + @Test + func `ordinary rows default to replay while an inline ACK owner has a new sequence and zero attempts`() async throws { + let fixture = try await makeFixture() + #expect(fixture.row.ackCodes == nil) + #expect(fixture.row.ackSentAt == nil) + #expect(fixture.row.ackDeadline == nil) + #expect(fixture.row.directMessageEnvelope() != nil) + let inlineMessage = MessageDTO.testDirectMessage(radioID: fixture.row.radioID, contactID: fixture.contact.id) + try await fixture.store.saveMessage(inlineMessage) + let sentAt = Date() + let owner = PendingSendDTO( + envelope: DirectMessageEnvelope(messageID: inlineMessage.id, contactID: fixture.contact.id), radioID: fixture.row.radioID, + ackCodes: [Data([1, 2, 3, 4])], ackSentAt: sentAt, ackDeadline: sentAt.addingTimeInterval(60) + ) + #expect(try await fixture.store.savePendingAcknowledgement(owner, replacingPendingSendID: nil)) + let saved = try #require(await fixture.store.fetchPendingSends(radioID: fixture.row.radioID).last) + #expect(saved.sequence > fixture.row.sequence) + #expect(saved.attemptCount == 0) + #expect(saved.directMessageEnvelope() == nil) + } + + @Test + func `an already delivered message drops its owner without a new status`() async throws { + let live = try await serviceRestoringOwner() + try await live.store.updateMessageAck(id: live.message.id, ackCode: 111, status: .delivered, roundTripTime: 222) + let events = live.service.statusEvents() + await live.service.handleAcknowledgement(code: Self.ackCode, tripTime: 999) + #expect(try await live.store.fetchMessage(id: live.message.id)?.status == .delivered) + #expect(try await live.store.fetchMessage(id: live.message.id)?.roundTripTime == 222) + #expect(try await live.store.fetchPendingSends(radioID: live.contact.radioID).isEmpty) + #expect(await live.service.pendingAckCount == 0) + let recorded = await live.service.drainStatusEvents(events) + #expect(recorded.resolvedIDs.isEmpty) + #expect(recorded.failedIDs.isEmpty) + } + + @Test + func `an already failed message drops its owner without a new status`() async throws { + let live = try await serviceRestoringOwner() + try await live.store.updateMessageStatus(id: live.message.id, status: .failed) + let events = live.service.statusEvents() + try await live.service.checkExpiredAcks() + #expect(try await live.store.fetchMessage(id: live.message.id)?.status == .failed) + #expect(try await live.store.fetchPendingSends(radioID: live.contact.radioID).isEmpty) + #expect(await live.service.pendingAckCount == 0) + let recorded = await live.service.drainStatusEvents(events) + #expect(recorded.resolvedIDs.isEmpty) + #expect(recorded.failedIDs.isEmpty) + } + + @Test + func `a missing message drops its owner without a new status`() async throws { + let live = try await serviceRestoringOwner() + let owner = try #require(await live.store.fetchPendingSends(radioID: live.contact.radioID).first) + try await live.store.deleteMessage(id: live.message.id) + try await live.store.upsertPendingSend(owner) + let saved = try #require(await live.store.fetchPendingSends(radioID: live.contact.radioID).first) + try await live.service.setPendingAckForTest(PendingAck( + messageID: live.message.id, + contactID: live.contact.id, + ackCodes: Set(saved.ackCodes ?? []), + sentAt: saved.ackSentAt ?? Date(), + timeout: 1, + owner: .init(id: saved.id, radioID: saved.radioID, deadline: #require(saved.ackDeadline), phase: .saved) + )) + let events = live.service.statusEvents() + await live.service.handleAcknowledgement(code: Self.ackCode, tripTime: 9) + #expect(try await live.store.fetchMessage(id: live.message.id) == nil) + #expect(try await live.store.fetchPendingSends(radioID: live.contact.radioID).isEmpty) + #expect(await live.service.pendingAckCount == 0) + let recorded = await live.service.drainStatusEvents(events) + #expect(recorded.resolvedIDs.isEmpty) + #expect(recorded.failedIDs.isEmpty) + } + + private static let ackCode = Data([1, 2, 3, 4]) + + private func serviceRestoringOwner() async throws -> ( + store: PersistenceStore, contact: ContactDTO, message: MessageDTO, service: MessageService + ) { + let fixture = try await makeFixture() + let sentAt = Date().addingTimeInterval(-60) + let waiting = acknowledgement(for: fixture.row, sentAt: sentAt) + #expect(try await fixture.store.savePendingAcknowledgement(waiting, replacingPendingSendID: fixture.row.id)) + let service = MessageService(session: MockMeshCoreSession(), dataStore: fixture.store, contactService: nil) + try await service.restorePendingAcknowledgements(radioID: fixture.row.radioID) + #expect(await service.pendingAckCount == 1) + return (fixture.store, fixture.contact, fixture.message, service) + } + + private func makeFixture() async throws -> ( + store: PersistenceStore, contact: ContactDTO, message: MessageDTO, row: PendingSendDTO + ) { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radioID = UUID() + let contact = ContactDTO.testContact(radioID: radioID) + try await store.saveDevice(.testDevice(radioID: radioID)) + try await store.saveContact(contact) + let message = MessageDTO.testDirectMessage(radioID: radioID, contactID: contact.id, status: .pending) + try await store.saveMessage(message) + let row = PendingSendDTO(envelope: DirectMessageEnvelope(messageID: message.id, contactID: contact.id), radioID: radioID) + try await store.upsertPendingSend(row) + return (store, contact, message, row) + } + + private func acknowledgement( + for row: PendingSendDTO, sentAt: Date = Date(), deadline: Date? = nil + ) -> PendingSendDTO { + PendingSendDTO( + id: row.id, envelope: DirectMessageEnvelope(messageID: row.messageID, contactID: row.contactID!), + radioID: row.radioID, enqueuedAt: row.enqueuedAt, ackCodes: [Data([1, 2, 3, 4])], + ackSentAt: sentAt, ackDeadline: deadline ?? sentAt.addingTimeInterval(30) + ) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/PendingSendAttemptPreparationTests.swift b/MC1Services/Tests/MC1ServicesTests/PendingSendAttemptPreparationTests.swift new file mode 100644 index 0000000000..e1988e8c08 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/PendingSendAttemptPreparationTests.swift @@ -0,0 +1,78 @@ +import Foundation +@testable import MC1Services +import MeshCore +import SwiftData +import Testing + +@Suite("Pending send attempt preparation") +@MainActor +struct PendingSendAttemptPreparationTests { + @Test + func `failed preparation rolls back status and attempt count while preserving buffered RX entries`() async throws { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let contact = ContactDTO.testContact() + try await store.saveContact(contact) + let message = MessageDTO.testDirectMessage(radioID: contact.radioID, contactID: contact.id, status: .failed) + try await store.saveMessage(message) + let pending = PendingSendDTO( + envelope: DirectMessageEnvelope(messageID: message.id, contactID: contact.id), radioID: contact.radioID + ) + _ = try await store.insertPendingSendAssigningSequence(pending) + let entry = RxLogEntryDTO( + radioID: contact.radioID, + from: ParsedRxLogData( + snr: 10, rssi: -65, rawPayload: Data([0x15]), routeType: .flood, + payloadType: .groupText, payloadVersion: 0, payloadTypeBits: 5, transportCode: nil, + pathLength: 0, pathNodes: [], packetPayload: Data([0xAB]) + ) + ) + try await store.bufferRxLogEntryForAttemptPreparation(entry) + #expect(await store.unsavedRxLogInsertCount == 1) + await store.setPendingSendAttemptSaveFaultInjection { _ in throw CocoaError(.fileWriteUnknown) } + + await #expect(throws: CocoaError.self) { + _ = try await store.preparePendingSendAttempt(messageID: message.id) + } + + #expect(try await store.fetchMessage(id: message.id)?.status == .failed) + #expect(try await store.fetchPendingSends(radioID: contact.radioID).first?.attemptCount == 0) + #expect(await store.unsavedRxLogInsertCount == 0) + let persisted = ModelContext(store.modelContainer) + #expect(try persisted.fetch(FetchDescriptor()).first?.status == .failed) + #expect(try persisted.fetch(FetchDescriptor()).first?.attemptCount == 0) + #expect(try persisted.fetch(FetchDescriptor()).map(\.id) == [entry.id]) + + await store.setPendingSendAttemptSaveFaultInjection(nil) + let prepared = try #require(try await store.preparePendingSendAttempt(messageID: message.id)) + #expect(prepared.pendingSendID == pending.id) + #expect(prepared.attemptCount == 1) + #expect(try await store.fetchMessage(id: message.id)?.status == .pending) + #expect(try await store.fetchPendingSends(radioID: contact.radioID).first?.attemptCount == 1) + #expect(try await store.fetchRxLogEntries(radioID: contact.radioID).map(\.id) == [entry.id]) + } + + @Test + func `preparing a first attempt preserves delivery recorded before the drain`() async throws { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let message = MessageDTO.testDirectMessage(status: .delivered) + try await store.saveMessage(message) + let pending = try PendingSendDTO( + envelope: DirectMessageEnvelope(messageID: message.id, contactID: #require(message.contactID)), + radioID: message.radioID + ) + _ = try await store.insertPendingSendAssigningSequence(pending) + + _ = try await store.preparePendingSendAttempt(messageID: message.id) + + #expect(try await store.fetchMessage(id: message.id)?.status == .delivered) + } +} + +private extension PersistenceStore { + func bufferRxLogEntryForAttemptPreparation(_ entry: RxLogEntryDTO) throws { + try saveRxLogEntry(entry) + // Keep the partial batch uncommitted until preparation owns the save. + rxLogFlushTask?.cancel() + rxLogFlushTask = nil + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/PendingSendPersistenceTests.swift b/MC1Services/Tests/MC1ServicesTests/PendingSendPersistenceTests.swift index 32e4783628..e3aeebb350 100644 --- a/MC1Services/Tests/MC1ServicesTests/PendingSendPersistenceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/PendingSendPersistenceTests.swift @@ -31,6 +31,36 @@ struct PendingSendPersistenceTests { #expect(fetched.first == dto) } + @Test(arguments: [false, true]) + func `single-attempt policy survives persistence and existing-row updates`(isSingleAttempt: Bool) async throws { + let store = try makeStore() + let radioID = UUID() + let envelope = DirectMessageEnvelope( + messageID: UUID(), contactID: UUID(), isSingleAttempt: isSingleAttempt + ) + let dto = PendingSendDTO(envelope: envelope, radioID: radioID) + _ = try await store.insertPendingSendAssigningSequence(dto) + + let inserted = try #require(try await store.fetchPendingSends(radioID: radioID).first) + #expect(inserted.isSingleAttempt == isSingleAttempt) + #expect(inserted.directMessageEnvelope()?.isSingleAttempt == isSingleAttempt) + + let replacement = PendingSendDTO( + id: inserted.id, + envelope: DirectMessageEnvelope( + messageID: envelope.messageID, contactID: envelope.contactID, isSingleAttempt: !isSingleAttempt + ), + radioID: radioID + ) + try await store.upsertPendingSend(replacement) + + let rows = try await store.fetchPendingSends(radioID: radioID) + #expect(rows.count == 1) + let updated = try #require(rows.first) + #expect(updated.isSingleAttempt == !isSingleAttempt) + #expect(updated.directMessageEnvelope()?.isSingleAttempt == !isSingleAttempt) + } + @Test func `Pending sends are scoped by radioID`() async throws { let store = try makeStore() @@ -325,6 +355,117 @@ struct PendingSendPersistenceTests { #expect(unrelated.sequence == 3, "Unrelated row keeps its prior sequence") } + @Test + func `wire attempt writes stay on the owned pending row`() async throws { + let store = try makeStore() + let radioID = UUID() + let messageID = UUID() + let contactID = UUID() + let otherMessageID = UUID() + try await store.saveMessage(makeOutgoingDM(id: messageID, radioID: radioID, contactID: contactID, status: .pending)) + try await store.saveMessage(makeOutgoingDM(id: otherMessageID, radioID: radioID, contactID: contactID, status: .pending)) + + let original = PendingSendDTO( + envelope: DirectMessageEnvelope(messageID: messageID, contactID: contactID), + radioID: radioID + ) + _ = try await store.insertPendingSendAssigningSequence(original) + let other = PendingSendDTO( + envelope: DirectMessageEnvelope(messageID: otherMessageID, contactID: contactID), + radioID: radioID + ) + _ = try await store.insertPendingSendAssigningSequence(other) + + #expect(try await store.pendingSendWireAttempt(id: original.id) == 0) + #expect(try await store.setPendingSendWireAttempt(id: original.id, to: 1)) + #expect(try await store.pendingSendWireAttempt(id: original.id) == 1) + #expect(try await store.setPendingSendWireAttempt(id: UUID(), to: 4) == false) + #expect(try await store.fetchPendingSends(radioID: radioID).count == 2) + + #expect(try await store.setPendingSendWireAttempt(id: original.id, to: 3)) + let deadline = Date().addingTimeInterval(30) + #expect(try await store.savePendingAcknowledgement( + PendingSendDTO( + id: original.id, + envelope: DirectMessageEnvelope(messageID: messageID, contactID: contactID), + radioID: radioID, + ackCodes: [Data([0x01, 0x02, 0x03, 0x04])], + ackSentAt: Date(), + ackDeadline: deadline + ), + replacingPendingSendID: original.id + )) + #expect(try await store.setPendingSendWireAttempt(id: original.id, to: 4) == false) + #expect(try await store.pendingSendWireAttempt(id: original.id) == nil) + let owned = try #require(try await store.fetchPendingSends(radioID: radioID).first { $0.id == original.id }) + #expect(owned.nextWireAttempt == 3) + + let replacement = PendingSendDTO( + envelope: DirectMessageEnvelope(messageID: messageID, contactID: contactID), + radioID: radioID + ) + _ = try await store.replacePendingSendForRetry(messageID: messageID, dto: replacement) + #expect(try await store.setPendingSendWireAttempt(id: original.id, to: 6) == false) + let rows = try await store.fetchPendingSends(radioID: radioID) + let replaced = try #require(rows.first { $0.messageID == messageID }) + #expect(replaced.id == replacement.id) + #expect(replaced.nextWireAttempt == 0) + let otherRow = try #require(rows.first { $0.messageID == otherMessageID }) + #expect(otherRow.nextWireAttempt == 0) + } + + @Test + func `a failed queued direct message exposes its consumed attempts and accepts delivery`() async throws { + let store = try makeStore() + let radioID = UUID() + let contactID = UUID() + let sender = Data(repeating: 0x11, count: 32) + let failedID = UUID() + try await store.saveMessage(makeOutgoingDM(id: failedID, radioID: radioID, contactID: contactID, status: .failed)) + let failedPending = PendingSendDTO( + envelope: DirectMessageEnvelope(messageID: failedID, contactID: contactID), + radioID: radioID + ) + _ = try await store.insertPendingSendAssigningSequence(failedPending) + #expect(try await store.setPendingSendWireAttempt(id: failedPending.id, to: 1)) + let visible = try await store.queuedDirectMessageWireAttempts() + let failedAttempt = try #require(visible.first { $0.messageID == failedID }) + #expect(failedAttempt.pendingSendID == failedPending.id) + #expect(failedAttempt.consumedAttempts == 1) + #expect(failedAttempt.timestamp == 1_700_000_000) + #expect(failedAttempt.text == "retry me") + let consumed = AckCodeBuilder.expectedAck( + timestamp: failedAttempt.timestamp, attempt: 0, text: failedAttempt.text, senderPublicKey: sender + ) + let claimed = try await store.deliverQueuedDirectMessage( + pendingSendID: failedAttempt.pendingSendID, + ackCode: consumed.ackCodeUInt32, + roundTripTime: 12 + ) + #expect(claimed?.id == failedID) + #expect(claimed?.roundTripTime == 12) + #expect(try await store.fetchMessage(id: failedID)?.status == .delivered) + #expect(try await store.fetchPendingSends(radioID: radioID).contains { $0.messageID == failedID } == false) + + let deliveredID = UUID() + try await store.saveMessage(makeOutgoingDM(id: deliveredID, radioID: radioID, contactID: contactID, status: .delivered)) + let deliveredPending = PendingSendDTO( + envelope: DirectMessageEnvelope(messageID: deliveredID, contactID: contactID), + radioID: radioID + ) + _ = try await store.insertPendingSendAssigningSequence(deliveredPending) + #expect(try await store.setPendingSendWireAttempt(id: deliveredPending.id, to: 1)) + #expect(try await store.queuedDirectMessageWireAttempts().contains { $0.messageID == deliveredID } == false) + let ignored = try await store.deliverQueuedDirectMessage( + pendingSendID: deliveredPending.id, + ackCode: consumed.ackCodeUInt32, + roundTripTime: 12 + ) + #expect(ignored == nil) + #expect(try await store.fetchMessage(id: deliveredID)?.status == .delivered) + #expect(try await store.pendingSendWireAttempt(id: deliveredPending.id) == 1) + } + /// Sequence assignment matches `insertPendingSendAssigningSequence`: /// the new row gets `max(sequence) + 1` for the radio. Verifies the /// per-radio monotonic invariant survives the delete-then-insert diff --git a/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift b/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift index a2fe58d736..e88c748e15 100644 --- a/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift @@ -1198,7 +1198,7 @@ struct PersistenceStoreTests { fetched = try await store.fetchRemoteNodeSession(id: session.id) #expect(fetched?.lastSyncTimestamp == 2000) #expect(fetched?.lastMessageDate != nil) - #expect(try #require(fetched?.lastMessageDate) >= firstDate!) + #expect(try #require(fetched?.lastMessageDate) >= #require(firstDate)) } @Test @@ -1777,26 +1777,26 @@ struct PersistenceStoreTests { } @Test - func `incrementPendingSendAttemptCount from 0 bumps to 1`() async throws { + func `preparePendingSendAttempt from 0 bumps to 1`() async throws { let store = try await createTestStore() let messageID = UUID() let dto = makePendingSendDTO(messageID: messageID, attemptCount: 0) try await store.upsertPendingSend(dto) - let result = try await store.incrementPendingSendAttemptCount(messageID: messageID) - #expect(result == 1, "first drain attempt should bump 0 → 1") + let result = try await store.preparePendingSendAttempt(messageID: messageID) + #expect(result?.attemptCount == 1, "first drain attempt should bump 0 → 1") let persisted = try await store.fetchPendingSends(radioID: dto.radioID).first #expect(persisted?.attemptCount == 1, "persisted attemptCount should match return value") } @Test - func `incrementPendingSendAttemptCount returns nil when no row matches`() async throws { + func `preparePendingSendAttempt returns nil when no row matches`() async throws { let store = try await createTestStore() let messageID = UUID() - let result = try await store.incrementPendingSendAttemptCount(messageID: messageID) - #expect(result == nil, "missing-row case is terminal — return nil instead of creating a new row") + let result = try await store.preparePendingSendAttempt(messageID: messageID) + #expect(result?.pendingSendID == nil, "missing-row case is terminal — return nil instead of creating a new row") } @Test @@ -2377,6 +2377,37 @@ struct PersistenceStoreTests { "unrelated channel's Message row must be preserved") } + @Test + func `deleteMessagesForChannel removes a queued channel send whose message is already gone`() async throws { + let store = try await createTestStore() + let device = createTestDevice() + try await store.saveDevice(device) + + let orphan = PendingSendDTO( + envelope: ChannelMessageEnvelope( + messageID: UUID(), channelIndex: 0, isResend: false, + messageText: "gone", messageTimestamp: 1, localNodeName: nil + ), + radioID: device.id + ) + let otherSlot = PendingSendDTO( + envelope: ChannelMessageEnvelope( + messageID: UUID(), channelIndex: 1, isResend: false, + messageText: "keep", messageTimestamp: 2, localNodeName: nil + ), + radioID: device.id + ) + let direct = makePendingSendDTO(radioID: device.id, sequence: 3) + _ = try await store.insertPendingSendAssigningSequence(orphan) + _ = try await store.insertPendingSendAssigningSequence(otherSlot) + try await store.upsertPendingSend(direct) + + try await store.deleteMessagesForChannel(radioID: device.id, channelIndex: 0) + + let remaining = try await store.fetchPendingSends(radioID: device.id) + #expect(remaining.map(\.messageID).sorted() == [otherSlot.messageID, direct.messageID].sorted()) + } + @Test func `deleteMessagesForChannel save throw rolls back messages and cascade`() async throws { let store = try await createTestStore() @@ -4359,4 +4390,335 @@ struct PersistenceStoreTests { ) #expect(base != mutated) } + + // MARK: - Self telemetry + + @Test + func `deleteDeviceAndData removes self telemetry and keeps unrelated history`() async throws { + let store = try await createTestStore() + let device = createTestDevice() + let other = createTestDevice() + try await store.saveDevice(device) + try await store.saveDevice(other) + + let selfFix = NodeLocationFix(latitude: 47.6062, longitude: -122.3321, altitude: 15) + let selfID = try #require( + try await store.recordSelfTelemetrySnapshot( + deviceID: device.id, + radioID: device.radioID, + nodePublicKey: device.publicKey, + telemetry: [TelemetrySnapshotEntry(channel: 1, type: "voltage", value: 4.1)], + location: selfFix + ) + ) + let otherID = try #require( + try await store.recordSelfTelemetrySnapshot( + deviceID: other.id, + radioID: other.radioID, + nodePublicKey: other.publicKey, + telemetry: [TelemetrySnapshotEntry(channel: 1, type: "voltage", value: 3.9)], + location: nil + ) + ) + try await store.saveRemoteNodeSessionDTO( + .testSession(radioID: other.radioID, publicKey: device.publicKey) + ) + _ = try await store.recordNodeStatusSnapshot( + nodePublicKey: device.publicKey, + status: nil, + telemetry: [TelemetrySnapshotEntry(channel: 2, type: "temperature", value: 21)], + neighbors: nil, + location: NodeLocationFix(latitude: 1, longitude: 2) + ) + + let before = try await store.fetchBackupExportSnapshot() + #expect(before.nodeStatusSnapshots.contains { $0.id == selfID && $0.latitude == selfFix.latitude }) + + try await store.deleteDeviceAndData(id: device.id) + + let removed = try await store.fetchSelfTelemetrySnapshots( + radioID: device.radioID, + nodePublicKey: device.publicKey + ) + #expect(removed.isEmpty) + let exported = try await store.fetchBackupExportSnapshot() + #expect(exported.nodeStatusSnapshots.contains { $0.id == selfID } == false) + #expect(exported.nodeStatusSnapshots.contains { $0.id == otherID }) + + let remote = try await store.fetchNodeStatusSnapshots(nodePublicKey: device.publicKey, since: nil) + #expect(remote.count == 1) + #expect(remote.first?.selfRadioID == nil) + #expect(remote.first?.latitude == 1) + let otherHistory = try await store.fetchSelfTelemetrySnapshots( + radioID: other.radioID, + nodePublicKey: other.publicKey + ) + #expect(otherHistory.map(\.id) == [otherID]) + } + + @Test + func `Self and remote readings in one window stay separate and self readings enrich`() async throws { + let store = try await createTestStore() + let device = createTestDevice() + try await store.saveDevice(device) + let key = device.publicKey + let firstFix = NodeLocationFix(latitude: 47.6, longitude: -122.3, altitude: 10) + let laterFix = NodeLocationFix(latitude: 40, longitude: -100, altitude: 20) + + _ = try await store.recordNodeStatusSnapshot( + nodePublicKey: key, + status: nil, + telemetry: [TelemetrySnapshotEntry(channel: 1, type: "temperature", value: 20)], + neighbors: nil, + location: nil + ) + let first = try #require( + try await store.recordSelfTelemetrySnapshot( + deviceID: device.id, + radioID: device.radioID, + nodePublicKey: key, + telemetry: [TelemetrySnapshotEntry(channel: 1, type: "voltage", value: 4.1)], + location: firstFix + ) + ) + let second = try await store.recordSelfTelemetrySnapshot( + deviceID: device.id, + radioID: device.radioID, + nodePublicKey: key, + telemetry: [TelemetrySnapshotEntry(channel: 1, type: "voltage", value: 4.2)], + location: laterFix + ) + #expect(second == first) + + let remote = try await store.fetchNodeStatusSnapshots(nodePublicKey: key, since: nil) + #expect(remote.count == 1) + #expect(remote.first?.selfRadioID == nil) + #expect(remote.first?.telemetryEntries?.first?.value == 20) + + let selfRows = try await store.fetchSelfTelemetrySnapshots( + radioID: device.radioID, + nodePublicKey: key + ) + #expect(selfRows.count == 1) + #expect(selfRows.first?.telemetryEntries?.first?.value == 4.2) + #expect(selfRows.first?.latitude == firstFix.latitude) + #expect(selfRows.first?.altitude == firstFix.altitude) + } + + @Test + func `First self telemetry GPS fix keeps its own capture time`() async throws { + let store = try await createTestStore() + let device = createTestDevice() + try await store.saveDevice(device) + let voltage = TelemetrySnapshotEntry(channel: 1, type: "voltage", value: 4.1) + let initialID = try #require( + try await store.recordSelfTelemetrySnapshot( + deviceID: device.id, + radioID: device.radioID, + nodePublicKey: device.publicKey, + telemetry: [voltage], + location: nil + ) + ) + + let fix = NodeLocationFix(latitude: 47.6, longitude: -122.3, altitude: 10) + let fixRequestStarted = Date.now + let fixID = try #require( + try await store.recordSelfTelemetrySnapshot( + deviceID: device.id, + radioID: device.radioID, + nodePublicKey: device.publicKey, + telemetry: [voltage], + location: fix + ) + ) + + let history = try await store.fetchSelfTelemetrySnapshots( + radioID: device.radioID, + nodePublicKey: device.publicKey + ) + #expect(fixID != initialID) + #expect(history.map(\.id) == [initialID, fixID]) + let initial = try #require(history.first) + let capturedFix = try #require(history.last) + #expect(initial.latitude == nil) + #expect(capturedFix.latitude == fix.latitude) + #expect(capturedFix.longitude == fix.longitude) + #expect(capturedFix.altitude == fix.altitude) + #expect(capturedFix.timestamp >= fixRequestStarted) + } + + @Test + func `Demote and re-pair keep self telemetry`() async throws { + let store = try await createTestStore() + let device = createTestDevice().copy { + $0.isActive = true + $0.connectionMethods = [.bluetooth(peripheralUUID: UUID(), displayName: nil)] + } + try await store.saveDevice(device) + let readingID = try #require( + try await store.recordSelfTelemetrySnapshot( + deviceID: device.id, + radioID: device.radioID, + nodePublicKey: device.publicKey, + telemetry: [TelemetrySnapshotEntry(channel: 1, type: "voltage", value: 3.8)], + location: NodeLocationFix(latitude: 47.6, longitude: -122.3) + ) + ) + + try await store.demoteDeviceToGhost(id: device.id) + let afterDemote = try await store.fetchSelfTelemetrySnapshots( + radioID: device.radioID, + nodePublicKey: device.publicKey + ) + #expect(afterDemote.map(\.id) == [readingID]) + + let repaired = createTestDevice().copy { + $0.publicKey = device.publicKey + $0.radioID = UUID() + $0.isActive = true + $0.connectionMethods = [.bluetooth(peripheralUUID: UUID(), displayName: nil)] + } + try await store.saveDevice(repaired) + let adopted = try await store.reconcileGhostIdentity( + currentDeviceID: repaired.id, + newPublicKey: device.publicKey + ) + #expect(adopted == device.radioID) + let afterRepair = try await store.fetchSelfTelemetrySnapshots( + radioID: device.radioID, + nodePublicKey: device.publicKey + ) + #expect(afterRepair.map(\.id) == [readingID]) + #expect(afterRepair.first?.selfRadioID == device.radioID) + } + + @Test + func `deleteDeviceAndData removes every captured key and a later write cannot restore it`() async throws { + let store = try await createTestStore() + let device = createTestDevice() + try await store.saveDevice(device) + let originalKey = device.publicKey + let rotatedKey = Data(repeating: 0x44, count: ProtocolLimits.publicKeySize) + let fix = NodeLocationFix(latitude: 10, longitude: 20) + + let first = try #require( + try await store.recordSelfTelemetrySnapshot( + deviceID: device.id, + radioID: device.radioID, + nodePublicKey: originalKey, + telemetry: [TelemetrySnapshotEntry(channel: 1, type: "voltage", value: 4)], + location: fix + ) + ) + try await store.saveDevice(device.copy { $0.publicKey = rotatedKey }) + let second = try #require( + try await store.recordSelfTelemetrySnapshot( + deviceID: device.id, + radioID: device.radioID, + nodePublicKey: rotatedKey, + telemetry: [TelemetrySnapshotEntry(channel: 1, type: "voltage", value: 3.5)], + location: nil + ) + ) + #expect(first != second) + + try await store.deleteDeviceAndData(id: device.id) + let originalHistory = try await store.fetchSelfTelemetrySnapshots( + radioID: device.radioID, + nodePublicKey: originalKey + ) + let rotatedHistory = try await store.fetchSelfTelemetrySnapshots( + radioID: device.radioID, + nodePublicKey: rotatedKey + ) + #expect(originalHistory.isEmpty) + #expect(rotatedHistory.isEmpty) + + let repaired = createTestDevice().copy { + $0.publicKey = rotatedKey + $0.radioID = UUID() + } + try await store.saveDevice(repaired) + let restored = try await store.recordSelfTelemetrySnapshot( + deviceID: device.id, + radioID: device.radioID, + nodePublicKey: originalKey, + telemetry: [TelemetrySnapshotEntry(channel: 1, type: "voltage", value: 4)], + location: fix + ) + #expect(restored == nil) + let exported = try await store.fetchBackupExportSnapshot() + #expect(exported.nodeStatusSnapshots.contains { $0.latitude == fix.latitude } == false) + let repairedHistory = try await store.fetchSelfTelemetrySnapshots( + radioID: repaired.radioID, + nodePublicKey: rotatedKey + ) + #expect(repairedHistory.isEmpty) + } + + @Test + func `Ghost reconciliation moves self telemetry and deletion removes the adopted owner`() async throws { + let store = try await createTestStore() + let departingKey = Data(repeating: 0x11, count: ProtocolLimits.publicKeySize) + let otherKey = Data(repeating: 0x33, count: ProtocolLimits.publicKeySize) + let adoptedKey = Data(repeating: 0x22, count: ProtocolLimits.publicKeySize) + let departingRadioID = UUID() + let adoptedRadioID = UUID() + let current = createTestDevice().copy { + $0.publicKey = departingKey + $0.radioID = departingRadioID + $0.isActive = true + } + try await store.saveDevice(current) + _ = try await store.recordSelfTelemetrySnapshot( + deviceID: current.id, + radioID: departingRadioID, + nodePublicKey: departingKey, + telemetry: [TelemetrySnapshotEntry(channel: 1, type: "voltage", value: 4)], + location: NodeLocationFix(latitude: 11, longitude: 22) + ) + try await store.saveDevice(current.copy { $0.publicKey = otherKey }) + _ = try await store.recordSelfTelemetrySnapshot( + deviceID: current.id, + radioID: departingRadioID, + nodePublicKey: otherKey, + telemetry: [TelemetrySnapshotEntry(channel: 1, type: "voltage", value: 3)], + location: nil + ) + let ghost = createTestDevice().copy { + $0.publicKey = adoptedKey + $0.radioID = adoptedRadioID + $0.isActive = false + $0.connectionMethods = [] + } + try await store.saveDevice(ghost) + + let adopted = try await store.reconcileGhostIdentity( + currentDeviceID: current.id, + newPublicKey: adoptedKey + ) + #expect(adopted == adoptedRadioID) + + let movedFirst = try await store.fetchSelfTelemetrySnapshots( + radioID: adoptedRadioID, + nodePublicKey: departingKey + ) + let movedSecond = try await store.fetchSelfTelemetrySnapshots( + radioID: adoptedRadioID, + nodePublicKey: otherKey + ) + let leftBehind = try await store.fetchSelfTelemetrySnapshots( + radioID: departingRadioID, + nodePublicKey: departingKey + ) + #expect(movedFirst.count == 1) + #expect(movedFirst.first?.selfRadioID == adoptedRadioID) + #expect(movedSecond.count == 1) + #expect(leftBehind.isEmpty) + + try await store.deleteDeviceAndData(id: current.id) + let exported = try await store.fetchBackupExportSnapshot() + #expect(exported.nodeStatusSnapshots.isEmpty) + } } diff --git a/MC1Services/Tests/MC1ServicesTests/RadioWiFiResetEvidenceTests.swift b/MC1Services/Tests/MC1ServicesTests/RadioWiFiResetEvidenceTests.swift new file mode 100644 index 0000000000..0583ab33a8 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/RadioWiFiResetEvidenceTests.swift @@ -0,0 +1,415 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Radio WiFi reset evidence") +@MainActor +struct RadioWiFiResetEvidenceTests { + @Test(arguments: [false, true]) + func `consumed reboot permits a fresh WiFi session only while runtime WiFi is enabled`(enabled: Bool) async throws { + let firmware = RadioWiFiResetFirmware(scenario: .consumed) + let session = MeshCoreSession(transport: firmware) + let successor = MeshCoreSession(transport: firmware) + let settings = SettingsService(session: session) + let state = settings.radioWiFiState + let outcome: Result + do { + try await session.start(disconnectTransportOnFailure: false) + try #require(await firmware.savedEnabled) + try #require(await firmware.runtimeEnabled) + let initialRevision = state.revision + let revision = try #require(try await settings.setRadioWiFiEnabled( + enabled, expectedContextID: settings.radioWiFiContextID, expectedRevision: initialRevision + )) + let setter = "set wifi.enabled \(enabled ? 1 : 0)" + let setterFrames = await firmware.sentData.filter { data in + guard data.first == CommandCode.runCliCommand.rawValue else { return false } + let command = String(decoding: data.dropFirst(), as: UTF8.self) + return ConnectionTestRadioTransport.splitCLICommand(command).command == setter + } + try #require(setterFrames.count == 1) + try #require(state.rebootPending) + try #require(revision > initialRevision) + try #require(state.stableRevision() == revision) + try #require(await firmware.savedEnabled == enabled) + try #require(await firmware.runtimeEnabled) + try await settings.reboot(expectedContextID: settings.radioWiFiContextID, expectedRevision: revision) + let rebootFrameWasSubmitted = await firmware.sentData.contains(PacketBuilder.reboot()) + try #require(rebootFrameWasSubmitted) + try #require(await firmware.rebootSubmissions == 1) + try #require(await firmware.savedEnabled == enabled) + try #require(await firmware.runtimeEnabled == enabled) + await settings.retireRadioWiFiOperations() + await session.stop() + await session.waitForQuiescence() + try #require(await !firmware.isConnected) + let framesBeforeReconnect = await firmware.sentData.count + + if enabled { + try await successor.start(disconnectTransportOnFailure: false) + let time = try await successor.getTime() + #expect(time.timeIntervalSince1970 > 0) + #expect(await firmware.isConnected) + let laterTimeFrameWasSubmitted = await firmware.sentData.dropFirst(framesBeforeReconnect).contains( + PacketBuilder.getTime() + ) + #expect(laterTimeFrameWasSubmitted) + } else { + let error = await #expect(throws: MeshTransportError.self) { + try await successor.start(disconnectTransportOnFailure: false) + } + if let error { #expect(error == .notConnected) } + #expect(await firmware.isConnected == false) + #expect(await firmware.sentData.count == framesBeforeReconnect) + } + #expect(await firmware.savedEnabled == enabled) + #expect(await firmware.runtimeEnabled == enabled) + #expect(await firmware.rebootSubmissions == 1) + outcome = .success(()) + } catch { + outcome = .failure(error) + } + await firmware.releaseResetStats() + await settings.retireRadioWiFiOperations() + await session.stop() + await successor.stop() + await firmware.disconnect() + await session.waitForQuiescence() + await successor.waitForQuiescence() + #expect(await firmware.isConnected == false) + try outcome.get() + } + + @Test(arguments: ResetScenario.allCases) + func `same-request socket recovery clears apply evidence only when firmware actually reset`( + scenario: ResetScenario + ) async throws { + let suite = "test.reset-evidence.\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suite)) + let model = try PersistenceStore.createContainer(inMemory: true) + let firmware = RadioWiFiResetFirmware(scenario: scenario) + let pairing = MockAccessorySetupKitService() + pairing.isSessionActive = false + let manager = ConnectionManager( + modelContainer: model, defaults: defaults, stateMachine: MockBLEStateMachine(), + transport: ConnectionTestRadioTransport(), + pairing: AccessorySetupPairingService(accessorySetupKit: pairing), makeWiFiTransport: { firmware } + ) + manager.testWiFiReconnectCooldown = 0 + do { + _ = try await manager.connectViaWiFi(host: "reset.local", port: 4242) + let first = try #require(manager.currentConnection) + let requestID = first.requestID + let settings = first.services.settingsService + let state = settings.radioWiFiState + let enabled = scenario.consumesReboot + let initialRevision = state.revision + let revision = try #require(try await settings.setRadioWiFiEnabled( + enabled, expectedContextID: settings.radioWiFiContextID, expectedRevision: initialRevision + )) + let setter = "set wifi.enabled \(enabled ? 1 : 0)" + let setterFrames = await firmware.sentData.filter { data in + guard data.first == CommandCode.runCliCommand.rawValue else { return false } + let command = String(decoding: data.dropFirst(), as: UTF8.self) + return ConnectionTestRadioTransport.splitCLICommand(command).command == setter + } + try #require(setterFrames.count == 1) + try #require(state.rebootPending) + try #require(revision > initialRevision) + try #require(state.stableRevision() == revision) + try #require(await firmware.savedEnabled == enabled) + try #require(await firmware.runtimeEnabled) + try await settings.reboot(expectedContextID: settings.radioWiFiContextID, expectedRevision: revision) + #expect(await firmware.rebootSubmissions == 1) + #expect(await firmware.runtimeEnabled) + await firmware.loseSocket() + try await waitUntil("same request should recover to a new fully completed context") { + manager.currentConnection?.generation != first.generation + && manager.installedLink?.didCompleteSync == true && manager.connectionState == .ready + } + #expect(manager.currentConnection?.requestID == requestID) + #expect(manager.services?.settingsService.radioWiFiState === state) + #expect(state.rebootPending == !scenario.provesReset) + if scenario == .consumedWithFailedDisplayReads { + #expect(await firmware.displayReads.isEmpty) + } + #expect(try await manager.services?.settingsService.getTime() != nil) + #expect(await firmware.savedEnabled == enabled) + #expect(await firmware.runtimeEnabled) + if scenario == .notConsumed { + let replacement = try #require(manager.services?.settingsService) + guard case let .supported(probe) = try await replacement.probeRadioWiFiSettings() else { + throw SettingsServiceError.invalidResponse + } + let observation = try #require(await replacement.readRadioWiFiObservation(probe: probe)) + #expect(observation.error == nil) + #expect(observation.networkNameWasRead) + #expect(observation.associated != nil) + #expect(observation.ipAddressWasRead) + #expect(!observation.enabled) + #expect(observation.associated == true) + #expect(state.rebootPending) + } + } catch { + _ = await manager.disconnect(reason: .userInitiated) + await manager.retirementTask?.value + UserDefaults().removePersistentDomain(forName: suite) + throw error + } + _ = await manager.disconnect(reason: .userInitiated) + await manager.retirementTask?.value + await manager.metadataCommitTask?.value + UserDefaults().removePersistentDomain(forName: suite) + #expect(manager.services == nil) + #expect(await firmware.isConnected == false) + } + + @Test(arguments: HeldStatsInterference.allCases) + func `old reset proof cannot clear evidence after a mutation or replacement request`( + interference: HeldStatsInterference + ) async throws { + let suite = "test.reset-evidence-held.\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suite)) + let model = try PersistenceStore.createContainer(inMemory: true) + let firmware = RadioWiFiResetFirmware(scenario: .consumed) + let pairing = MockAccessorySetupKitService() + pairing.isSessionActive = false + let manager = ConnectionManager( + modelContainer: model, defaults: defaults, stateMachine: MockBLEStateMachine(), + transport: ConnectionTestRadioTransport(), + pairing: AccessorySetupPairingService(accessorySetupKit: pairing), makeWiFiTransport: { firmware } + ) + manager.testWiFiReconnectCooldown = 0 + var mutation: Task? + var replacement: Task? + do { + _ = try await manager.connectViaWiFi(host: "reset.local", port: 4242) + let first = try #require(manager.currentConnection) + let settings = first.services.settingsService + let state = settings.radioWiFiState + let initialRevision = state.revision + let revision = try #require(try await settings.setRadioWiFiEnabled( + true, expectedContextID: settings.radioWiFiContextID, expectedRevision: initialRevision + )) + let setterFrames = await firmware.sentData.filter { data in + guard data.first == CommandCode.runCliCommand.rawValue else { return false } + let command = String(decoding: data.dropFirst(), as: UTF8.self) + return ConnectionTestRadioTransport.splitCLICommand(command).command == "set wifi.enabled 1" + } + try #require(setterFrames.count == 1) + try #require(state.rebootPending) + try #require(revision > initialRevision) + try #require(state.stableRevision() == revision) + try #require(await firmware.savedEnabled) + try #require(await firmware.runtimeEnabled) + try await settings.reboot(expectedContextID: settings.radioWiFiContextID, expectedRevision: revision) + try #require(await firmware.rebootSubmissions == 1) + try #require(await firmware.savedEnabled) + try #require(await firmware.runtimeEnabled) + await firmware.holdResetStats() + await firmware.loseSocket() + try await waitUntil("post-recovery reset proof should hold its stats reply") { await firmware.resetStatsHeld } + let recovered = try #require(manager.installedLink) + let completion = try #require(recovered.completionWorker) + #expect(recovered.generation != first.generation) + #expect(state.expectedRebootID != nil) + switch interference { + case .mutation: + let currentSettings = recovered.services.settingsService + mutation = Task { + try await currentSettings.setRadioWiFiEnabled( + false, expectedContextID: currentSettings.radioWiFiContextID, expectedRevision: state.revision + ) + } + try await waitUntil("new WiFi mutation should revoke the captured proof before its reply") { + state.stableRevision() == nil + } + case .replacementRequest: + replacement = Task { try await manager.connectViaWiFi(host: "replacement.local", port: 4242) } + try await waitUntil("explicit replacement should supersede the proof owner") { + manager.connectionRequestID != first.requestID + } + } + await firmware.releaseResetStats() + _ = try await mutation?.value + _ = try await replacement?.value + _ = await completion.value + #expect(state.rebootPending) + #expect(state.expectedRebootID == nil) + #expect(manager.services?.settingsService.radioWiFiState === state) + #expect(try await manager.services?.settingsService.getTime() != nil) + } catch { + await firmware.releaseResetStats() + _ = await mutation?.result + _ = await replacement?.result + _ = await manager.disconnect(reason: .userInitiated) + await manager.retirementTask?.value + UserDefaults().removePersistentDomain(forName: suite) + throw error + } + _ = await manager.disconnect(reason: .userInitiated) + await manager.retirementTask?.value + await manager.metadataCommitTask?.value + UserDefaults().removePersistentDomain(forName: suite) + #expect(await firmware.isConnected == false) + } + + enum HeldStatsInterference: Sendable, CaseIterable { + case mutation, replacementRequest + } + + enum ResetScenario: Sendable, CaseIterable { + case notConsumed, consumed, consumedWithFailedDisplayReads, shortUptime + case normalProgression, rolloverCompatible, unsupportedBefore, failedAfter + + var consumesReboot: Bool { + self == .consumed || self == .consumedWithFailedDisplayReads || self == .shortUptime + || self == .rolloverCompatible || self == .unsupportedBefore || self == .failedAfter + } + + var provesReset: Bool { + self == .consumed || self == .consumedWithFailedDisplayReads + } + + var before: UInt32 { + switch self { + case .shortUptime: 1 + case .rolloverCompatible: 4_294_967 + default: 1000 + } + } + + var after: UInt32 { + switch self { + case .consumed, .consumedWithFailedDisplayReads, .shortUptime, .unsupportedBefore, .failedAfter: 1 + case .rolloverCompatible: 0 + case .normalProgression: 1001 + case .notConsumed: 1000 + } + } + } +} + +private actor RadioWiFiResetFirmware: WiFiMeshTransport { + private let wire = ConnectionTestRadioTransport() + private let scenario: RadioWiFiResetEvidenceTests.ResetScenario + private(set) var savedEnabled = true + private(set) var runtimeEnabled = true + private(set) var rebootSubmissions = 0 + private(set) var displayReads: [String] = [] + private(set) var resetStatsHeld = false + private var holdsResetStats = false + private var uptime: UInt32 + + init(scenario: RadioWiFiResetEvidenceTests.ResetScenario) { + self.scenario = scenario + uptime = scenario.before + } + + var connectionInfo: (host: String, port: UInt16)? { + get async { await wire.connectionInfo } + } + + var isConnected: Bool { + get async { await wire.isConnected } + } + + var sentData: [Data] { + get async { await wire.sentData } + } + + var receivedData: AsyncStream { + get async { await wire.receivedData } + } + + var supportsPipelinedReads: Bool { + true + } + + func connect() async throws { + guard runtimeEnabled else { throw MeshTransportError.notConnected } + try await wire.connect() + } + + func disconnect() async { + await wire.disconnect() + } + + func setConnectionInfo(host: String, port: UInt16) async { + await wire.setConnectionInfo(host: host, port: port) + } + + func setDisconnectionHandler(_ handler: @escaping @Sendable (Error?, CFAbsoluteTime) -> Void) async { + await wire.setDisconnectionHandler(handler) + } + + func loseSocket() async { + await wire.simulateRemoteLoss() + } + + func holdResetStats() async { + holdsResetStats = true + await wire.holdReplies(for: .getStats) + } + + func releaseResetStats() async { + holdsResetStats = false + resetStatsHeld = false + await wire.releaseReplies(for: .getStats) + } + + func send(_ data: Data) async throws { + guard let code = data.first else { return } + if code == CommandCode.runCliCommand.rawValue { + let original = String(decoding: data.dropFirst(), as: UTF8.self) + let (prefix, command) = ConnectionTestRadioTransport.splitCLICommand(original) + let isDisplayRead = ["get wifi.enabled", "get wifi.ssid", "get wifi.status", "get wifi.ip"].contains(command) + if isDisplayRead { displayReads.append(command) } + let reply: String + if isDisplayRead, scenario == .consumedWithFailedDisplayReads { + reply = "Error: display read unavailable" + } else if command == "set wifi.enabled 0" || command == "set wifi.enabled 1" { + savedEnabled = command == "set wifi.enabled 1" + reply = "> wifi.enabled is now \(savedEnabled ? 1 : 0) (reboot to apply)" + } else if command == "get wifi.enabled" { + reply = savedEnabled ? "> 1" : "> 0" + } else if command == "get wifi.status" { + reply = runtimeEnabled ? "> connected" : "> disconnected" + } else if command == "get wifi.ssid" { + reply = "> synthetic-network" + } else if command == "get wifi.ip" { + reply = runtimeEnabled ? "> 192.0.2.1" : "> (not connected)" + } else { + reply = command.hasPrefix("get ") ? "> 0" : "OK" + } + await wire.setCLIResponse(original, response: prefix + reply) + } else if code == CommandCode.reboot.rawValue { + rebootSubmissions += 1 + if scenario.consumesReboot { + runtimeEnabled = savedEnabled + } + uptime = scenario.after + await wire.setResponsePackets(for: .reboot, packets: []) + } else if code == CommandCode.getStats.rawValue { + if scenario == .unsupportedBefore, rebootSubmissions == 0 { + await wire.setResponsePackets(for: .getStats, packets: [Data([ResponseCode.error.rawValue, 1])]) + try await wire.send(data) + return + } + if scenario == .failedAfter, rebootSubmissions > 0 { + await wire.setResponsePackets(for: .getStats, packets: [Data([ResponseCode.error.rawValue, 5])]) + try await wire.send(data) + return + } + var packet = Data([ResponseCode.stats.rawValue, 0, 0x74, 0x0E]) + packet.append(withUnsafeBytes(of: uptime.littleEndian) { Data($0) }) + packet.append(contentsOf: [0, 0, 0]) + await wire.setResponsePackets(for: .getStats, packets: [packet]) + } + try await wire.send(data) + if code == CommandCode.getStats.rawValue, rebootSubmissions > 0, holdsResetStats { + resetStatsHeld = true + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ReconnectRebuildLifecycleTests.swift b/MC1Services/Tests/MC1ServicesTests/ReconnectRebuildLifecycleTests.swift index 16918a60bf..2210d096f7 100644 --- a/MC1Services/Tests/MC1ServicesTests/ReconnectRebuildLifecycleTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ReconnectRebuildLifecycleTests.swift @@ -1,246 +1,99 @@ import CoreBluetooth import Foundation @testable import MC1Services -import MeshCore +@testable import MeshCore import ObjectiveC import Testing -/// Covers the iOS auto-reconnect rebuild window: the presentation state it -/// surfaces while the session is being rebuilt and its first sync runs, and the -/// guided pairing-failure recovery reaching the user when a bond turns out to be -/// invalidated mid-reconnect. @Suite("Reconnect Rebuild Lifecycle") @MainActor struct ReconnectRebuildLifecycleTests { @Test - func `restored session advances past handshake when startup adoption is superseded`() async throws { - let container = try PersistenceStore.createContainer(inMemory: true) - let suiteName = "test.\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: suiteName)) - defer { UserDefaults().removePersistentDomain(forName: suiteName) } - let stateMachine = MockBLEStateMachine() - let transport = RevendingHandshakeTransport() - let manager = ConnectionManager( - modelContainer: container, defaults: defaults, stateMachine: stateMachine, transport: transport - ) - let deviceID = UUID() - manager.testLastConnectedDeviceID = deviceID - manager.setTestState(connectionState: .disconnected, connectionIntent: .wantsConnection()) - await stateMachine.setStubbedIsDeviceConnectedToSystem(true) - let (releaseStream, release) = AsyncStream.makeStream() - await transport.setBeforeNextAppStartReply { - for await _ in releaseStream { - break - } - } - var rebuildTask: Task? - manager.onAutoReconnectStarted = { - manager.onAutoReconnectStarted = nil - await manager.reconnectionCoordinator.handleEnteringAutoReconnect(deviceID: deviceID) - rebuildTask = Task { try await manager.rebuildSession(deviceID: deviceID) } - try? await waitUntil(timeout: .seconds(2), "restored session should start its handshake") { - await transport.appStartReplyCount == 1 + func `reconnect rebuild surfaces connected while its handshake is pending`() async throws { + let harness = try ConnectionManagerRadioTestHarness() + do { + _ = try await harness.connect(.bluetooth) + await harness.ble.holdReplies(for: .appStart) + await harness.ble.simulateAutoReconnecting(deviceID: harness.deviceID) + try await waitUntil("source loss should claim recovery") { harness.manager.reconnectionCoordinator.reconnectingDeviceID == harness.deviceID } + await harness.ble.simulateReconnected() + try await waitUntil("rebuilt handshake should preserve connected presentation") { + let starts = await harness.ble.sentData.filter { $0.first == CommandCode.appStart.rawValue }.count + return harness.manager.connectionState == .connected && starts == 2 } - } - - let handled = await manager.startAdoptingLastSystemConnectedPeripheralIfAvailable( - deviceID: deviceID, context: "test" - ) - release.yield(()) - release.finish() - let task = try #require(rebuildTask) - _ = await task.result - - #expect(handled) - #expect(await transport.appStartReplyCount == 1) - #expect(await transport.deviceQueryCount == 1) - manager.reconnectionCoordinator.cancelTimeout() - await manager.session?.stop(disconnectTransport: false) + await harness.ble.releaseReplies(for: .appStart) + try await waitUntil("rebuilt stack should become ready") { harness.manager.connectionState == .ready } + _ = try await harness.manager.session?.getTime() + await harness.close() + } catch { await harness.close(); throw error } } - // MARK: - Presentation state during rebuild + sync - - /// Fresh connect shows `.connected` (link up, sync running) so the syncing pill - /// is visible; the auto-reconnect rebuild must show the same rung instead of a - /// prolonged `.connecting` that no UI window bounds. The transport pins the - /// appStart handshake so the rebuild stays inside its setup+sync window while - /// the surfaced state is observed. @Test - func `reconnect rebuild surfaces connected while the sync window is still open`() async throws { - let container = try PersistenceStore.createContainer(inMemory: true) - let suiteName = "test.\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: suiteName)) - defer { UserDefaults().removePersistentDomain(forName: suiteName) } - - let transport = PinnedHandshakeTransport() - let manager = ConnectionManager( - modelContainer: container, - defaults: defaults, - stateMachine: MockBLEStateMachine(), - transport: transport - ) - - let deviceID = UUID() - // The coordinator sets .connecting immediately before invoking rebuildSession. - manager.setTestState( - connectionState: .connecting, - currentTransportType: .bluetooth, - connectionIntent: .wantsConnection() - ) - - let rebuildTask = Task { try? await manager.rebuildSession(deviceID: deviceID) } - - // The handshake is pinned in the transport, so the rebuild cannot advance to - // promotion; the state observed here is the rung the reconnect window shows. - try await waitUntil(timeout: .seconds(2), "rebuild should surface .connected during its sync window") { - manager.connectionState == .connected - } - #expect(manager.connectionState == .connected) - - // Release the pinned handshake so the rebuild unwinds and the task finishes. - await transport.releaseSend() - _ = await rebuildTask.value - } - - // MARK: - Bond loss mid-reconnect - - /// An established radio can lose its bond while iOS is auto-reconnecting: the - /// rebuild's GATT discovery/subscribe surfaces `authenticationFailed` for the - /// same device the coordinator is reconnecting. That failure must reach the - /// guided recovery (not be swallowed as a stale-device disconnect), clear the - /// reconnect claim so silent retries can't hide it, and leave the manager ready - /// for a re-pair that returns to a working paired state. - @Test - func `bond loss during an active reconnect surfaces guided recovery and re-pairs`() async throws { - let env = try ConnectionManager.createForPairingTesting() - defer { env.cleanup() } - let manager = env.manager - let deviceID = UUID() - var surfaced: [UUID] = [] - manager.onAuthenticationFailure = { surfaced.append($0) } - - manager.setTestState(connectionIntent: .wantsConnection()) - - // iOS auto-reconnect claims the cycle: state → .connecting, the coordinator - // now owns deviceID as the reconnecting device. - await manager.reconnectionCoordinator.handleEnteringAutoReconnect(deviceID: deviceID) - #expect(manager.connectionState == .connecting) - #expect(manager.reconnectionCoordinator.reconnectingDeviceID == deviceID) - - // The rebuild finds the bond invalidated: an authenticationFailed disconnect - // arrives for the same device mid-reconnect. - await manager.handleConnectionLoss(deviceID: deviceID, error: BLEError.authenticationFailed) - - #expect(surfaced == [deviceID], "auth failure mid-reconnect must reach guided recovery") - #expect(manager.connectionState == .disconnected) - #expect( - manager.reconnectionCoordinator.reconnectingDeviceID == nil, - "the stale reconnect claim must be cleared so retries don't hide the recovery" - ) - - // Guided recovery leads the user through a re-pair; the fresh connection - // promotes to .ready, returning the radio to a working paired state. - let session = MeshCoreSession(transport: SimulatorMockTransport()) - let services = try await ServiceContainer.forTesting(session: session) - manager.setTestState( - connectionState: .connected, - services: services, - session: session, - connectedDevice: DeviceDTO.testDevice(id: deviceID), - connectionIntent: .wantsConnection() - ) - let promoted = await manager.promoteToReady( - syncResult: FullSyncResult(contacts: .clean, channels: .clean, messages: .clean), - expectedServices: services, - transportType: .bluetooth - ) - #expect(promoted) - #expect(manager.connectionState == .ready) - - manager.stopReconnectionWatchdog() + func `bond loss during active reconnect surfaces guided recovery and connects again`() async throws { + let harness = try ConnectionManagerRadioTestHarness() + do { + _ = try await harness.connect(.bluetooth) + var surfaced: [UUID] = [] + harness.manager.onAuthenticationFailure = { surfaced.append($0) } + await harness.ble.simulateAutoReconnecting(deviceID: harness.deviceID) + try await waitUntil("recovery should own the radio") { harness.manager.reconnectionCoordinator.reconnectingDeviceID == harness.deviceID } + await harness.ble.simulateRemoteLoss(error: .authenticationFailed) + try await waitUntil("bond failure should reach guided recovery") { + surfaced == [harness.deviceID] && harness.manager.connectionState == .disconnected + } + #expect(harness.manager.reconnectionCoordinator.reconnectingDeviceID == nil) + guard case .operational = try await harness.connect(.bluetooth) else { + Issue.record("a fresh connection should recover the radio") + await harness.close() + return + } + #expect(harness.manager.connectionState == .ready) + _ = try await harness.manager.session?.getTime() + await harness.close() + } catch { await harness.close(); throw error } } - /// The mid-reconnect surfacing above must stay specific to the reconnecting - /// device: a disconnect for a different peripheral (a stale link tearing down - /// while iOS reconnects the current one) is ignored, and the active reconnect - /// for the current device survives. @Test - func `a stale-device disconnect during reconnect is ignored and preserves the cycle`() async throws { - let env = try ConnectionManager.createForPairingTesting() - defer { env.cleanup() } - let manager = env.manager - let deviceID = UUID() - let staleDeviceID = UUID() - var surfaced: [UUID] = [] - manager.onAuthenticationFailure = { surfaced.append($0) } - - manager.setTestState(connectionIntent: .wantsConnection()) - await manager.reconnectionCoordinator.handleEnteringAutoReconnect(deviceID: deviceID) - - await manager.handleConnectionLoss(deviceID: staleDeviceID, error: BLEError.authenticationFailed) - - #expect(surfaced.isEmpty, "a disconnect for a different device must not surface recovery") - #expect(manager.connectionState == .connecting, "the active reconnect for the current device must survive") - #expect(manager.reconnectionCoordinator.reconnectingDeviceID == deviceID) - - manager.reconnectionCoordinator.cancelTimeout() + func `a stale-device disconnect during reconnect preserves the current cycle`() async throws { + let harness = try ConnectionManagerRadioTestHarness() + do { + _ = try await harness.connect(.bluetooth) + var surfaced: [UUID] = [] + harness.manager.onAuthenticationFailure = { surfaced.append($0) } + await harness.ble.simulateAutoReconnecting(deviceID: harness.deviceID) + try await waitUntil("recovery should own the radio") { harness.manager.reconnectionCoordinator.reconnectingDeviceID == harness.deviceID } + let cycle = try #require(harness.manager.reconnectionCoordinator.currentCycle) + let stale = BLELifecycleOrigin(deviceID: UUID(), generation: 1, eventTime: CFAbsoluteTimeGetCurrent()) + await harness.manager.handleBLELifecycleEvent(.disconnected(stale, error: .authenticationFailed)) + #expect(surfaced.isEmpty) + #expect(harness.manager.connectionState == .connecting) + #expect(harness.manager.reconnectionCoordinator.currentCycle == cycle) + await harness.ble.simulateReconnected() + try await waitUntil("current recovery should still become ready") { harness.manager.connectionState == .ready } + _ = try await harness.manager.session?.getTime() + await harness.close() + } catch { await harness.close(); throw error } } - // MARK: - Data stream renewal across rebuild - - /// The rebuild regression gate: stopping the predecessor session cancels its - /// receive loop, and that cancellation terminates the vended stream's shared - /// storage. A rebuild over the still-live link must consume a renewed stream, - /// or its appStart handshake iterates a dead stream and times out. Pins the - /// `refreshDataStream` call in `rebuildSession`. - /// - /// Intent is revoked during the handshake, so rebuild returns before query and sync. - /// Abandon then clears the session; success is the refreshed handshake, not `manager.session`. @Test - func `rebuild after a stopped predecessor completes its handshake over a refreshed stream`() async throws { - let container = try PersistenceStore.createContainer(inMemory: true) - let suiteName = "test.\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: suiteName)) - defer { UserDefaults().removePersistentDomain(forName: suiteName) } - - let transport = RevendingHandshakeTransport() - let manager = ConnectionManager( - modelContainer: container, - defaults: defaults, - stateMachine: MockBLEStateMachine(), - transport: transport - ) - - // The predecessor completes a real handshake over the vended stream, so its - // stop inside rebuildSession kills that stream's storage. - let predecessor = MeshCoreSession(transport: transport) - try await predecessor.start() - #expect(await transport.appStartReplyCount == 1) - #expect(await transport.refreshCount == 0) - - manager.setTestState( - connectionState: .connected, - session: predecessor, - currentTransportType: .bluetooth, - connectionIntent: .wantsConnection() - ) - await transport.setBeforeNextAppStartReply { [weak manager] in - manager?.setTestState(connectionIntent: ConnectionIntent.none) - } - - // Non-throwing return means session.start completed (dead stream would time out). - try await manager.rebuildSession(deviceID: UUID()) - - #expect( - await transport.refreshCount == 1, - "rebuild must refresh the data stream after stopping the predecessor" - ) - #expect( - await transport.appStartReplyCount == 2, - "rebuilt session must complete appStart on the refreshed stream" - ) - #expect(manager.session == nil, "abandon must drop the session when intent does not want connection") - #expect(manager.connectionState == .disconnected) + func `rebuild after a stopped predecessor completes over a refreshed stream`() async throws { + let harness = try ConnectionManagerRadioTestHarness() + do { + _ = try await harness.connect(.bluetooth) + let predecessor = try #require(harness.manager.session) + await harness.ble.simulateAutoReconnecting(deviceID: harness.deviceID) + try await waitUntil("predecessor should retire before rebuild") { + harness.manager.reconnectionCoordinator.reconnectingDeviceID == harness.deviceID && harness.manager.connectionTeardownCount == 0 + } + await harness.ble.simulateReconnected() + try await waitUntil("replacement handshake and sync should finish") { harness.manager.connectionState == .ready } + #expect(harness.manager.session !== predecessor) + #expect(await harness.ble.sentData.filter { $0.first == CommandCode.appStart.rawValue }.count == 2) + #expect(await harness.ble.connectCount == 1) + #expect(await predecessor.subscriberCountForTest == 0) + _ = try await harness.manager.session?.getTime() + await harness.close() + } catch { await harness.close(); throw error } } /// A renewal outside `.connected` is declined: the slot owner keeps its @@ -304,159 +157,6 @@ struct ReconnectRebuildLifecycleTests { } } -/// Transport that lets the BLE link "connect" but pins the appStart handshake -/// send until the test releases it, holding a session rebuild inside its -/// setup+sync window so the surfaced connection state can be observed. -private actor PinnedHandshakeTransport: iOSMeshTransport { - private let dataStream: AsyncStream - private let dataContinuation: AsyncStream.Continuation - private let releaseStream: AsyncStream - private let releaseContinuation: AsyncStream.Continuation - private var connected = false - - init() { - var dataCont: AsyncStream.Continuation! - dataStream = AsyncStream { dataCont = $0 } - dataContinuation = dataCont - var releaseCont: AsyncStream.Continuation! - releaseStream = AsyncStream { releaseCont = $0 } - releaseContinuation = releaseCont - } - - var receivedData: AsyncStream { - dataStream - } - - var isConnected: Bool { - connected - } - - func connect() async throws { - connected = true - } - - func disconnect() async { - connected = false - dataContinuation.finish() - } - - func send(_ data: Data) async throws { - // Pin the appStart handshake until the test releases it; an AsyncStream gate - // (rather than a checked continuation) can't crash on an unreleased leak. - for await _ in releaseStream { - break - } - throw MeshTransportError.notConnected - } - - /// Unpins the handshake, failing the pending send so the rebuild unwinds - /// through session.start's failure path. - func releaseSend() { - releaseContinuation.yield(()) - releaseContinuation.finish() - } - - func setDeviceID(_ id: UUID) {} - func switchDevice(to deviceID: UUID) async throws {} - func setDisconnectionHandler(_ handler: @escaping @Sendable (UUID, Error?) -> Void) {} - func setReconnectionHandler(_ handler: @escaping @Sendable (UUID) -> Void) {} - - /// Protocol stub only. The pinned handshake never completes, so a rebuilt - /// session never consumes a renewed stream. - func refreshDataStream() {} -} - -/// Completes appStart over a single-slot stream so rebuilds must renew -/// a stream terminated by the previous session's receive loop. -private actor RevendingHandshakeTransport: iOSMeshTransport { - private var slot: AsyncStream? - private var slotContinuation: AsyncStream.Continuation? - private var connected = false - private(set) var refreshCount = 0 - private(set) var appStartReplyCount = 0 - private(set) var deviceQueryCount = 0 - private var beforeNextAppStartReply: (@MainActor @Sendable () async -> Void)? - - func setBeforeNextAppStartReply(_ handler: @escaping @MainActor @Sendable () async -> Void) { - beforeNextAppStartReply = handler - } - - var receivedData: AsyncStream { - slot ?? AsyncStream { $0.finish() } - } - - var isConnected: Bool { - connected - } - - func connect() async throws { - connected = true - if slot == nil { - vendStream() - } - } - - func disconnect() async { - connected = false - slotContinuation?.finish() - slot = nil - slotContinuation = nil - } - - func send(_ data: Data) async throws { - // Complete the handshake, then fail deviceQuery so rebuild tests stop - // before service setup and sync. - if data.first == CommandCode.appStart.rawValue { - appStartReplyCount += 1 - let beforeReply = beforeNextAppStartReply - beforeNextAppStartReply = nil - await beforeReply?() - slotContinuation?.yield(Self.selfInfoPacket()) - } else if data.first == CommandCode.deviceQuery.rawValue { - deviceQueryCount += 1 - throw MeshTransportError.notConnected - } - } - - func refreshDataStream() { - refreshCount += 1 - vendStream() - } - - func setDeviceID(_ id: UUID) {} - func switchDevice(to deviceID: UUID) async throws {} - func setDisconnectionHandler(_ handler: @escaping @Sendable (UUID, Error?) -> Void) {} - func setReconnectionHandler(_ handler: @escaping @Sendable (UUID) -> Void) {} - - private func vendStream() { - let (stream, continuation) = AsyncStream.makeStream( - of: Data.self, - bufferingPolicy: .bufferingOldest(512) - ) - slot = stream - slotContinuation = continuation - } - - private static func selfInfoPacket() -> Data { - var payload = Data([ResponseCode.selfInfo.rawValue]) - payload.append(1) // adv type - payload.append(UInt8(bitPattern: 22)) // tx power - payload.append(UInt8(bitPattern: 22)) // max tx power - payload.append(Data(repeating: 0x01, count: 32)) // pubkey - payload.append(contentsOf: withUnsafeBytes(of: Int32(0).littleEndian) { Array($0) }) // lat - payload.append(contentsOf: withUnsafeBytes(of: Int32(0).littleEndian) { Array($0) }) // lon - payload.append(0) // multi acks - payload.append(0) // adv loc policy - payload.append(0) // telemetry mode - payload.append(0) // manual add - payload.append(contentsOf: withUnsafeBytes(of: UInt32(869_525).littleEndian) { Array($0) }) // freq - payload.append(contentsOf: withUnsafeBytes(of: UInt32(250_000).littleEndian) { Array($0) }) // bw - payload.append(11) // sf - payload.append(5) // cr - return payload - } -} - /// A `CBPeripheral` double with a stable identity and `.connected` state. private final class RebuildConnectedPeripheral: CBPeripheral, @unchecked Sendable { static let uuid = UUID() diff --git a/MC1Services/Tests/MC1ServicesTests/RemoteNodeLoginContactRecoveryTests.swift b/MC1Services/Tests/MC1ServicesTests/RemoteNodeLoginContactRecoveryTests.swift new file mode 100644 index 0000000000..adad878e6b --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/RemoteNodeLoginContactRecoveryTests.swift @@ -0,0 +1,66 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("Remote login contact recovery") +struct RemoteNodeLoginContactRecoveryTests { + @Test(arguments: [true, false]) + @MainActor + func `real login heals only a contact present locally after readiness`(hasLocalContact: Bool) async throws { + try await ConnectionRadioHandoffHarness.withHarness { harness in + try await harness.connectBluetooth() + let link = try #require(harness.manager.installedLink) + _ = await link.completionWorker?.value + try #require(link.didCompleteSync) + let session = link.resource.session + let store = harness.manager.persistenceStore + let publicKey = Data(repeating: 0xC4, count: ProtocolLimits.publicKeySize) + let contact = ContactDTO.testContact( + radioID: harness.deviceA.radioID, publicKey: publicKey, typeRawValue: ContactType.room.rawValue, + outPathLength: 2, outPath: Data([0x12, 0x34]) + ) + if hasLocalContact { try await store.saveContact(contact) } + let membership = RemoteNodeSessionDTO.testSession( + radioID: harness.deviceA.radioID, publicKey: publicKey, isConnected: false + ) + try await store.saveRemoteNodeSessionDTO(membership) + let local = try await store.fetchContact(radioID: harness.deviceA.radioID, publicKey: publicKey) + try #require((local != nil) == hasLocalContact) + if let local { try #require(!local.isFloodRouted) } + let radioContacts = try await session.getContacts() + let contactIsAbsentOnRadio = !radioContacts.contains { $0.publicKey == publicKey } + try #require(contactIsAbsentOnRadio) + try #require(try await !harness.isConnected(membership)) + let frameCount = await harness.bluetooth.sentData.count + let login = harness.track(Task { + try await link.services.remoteNodeService.login(sessionID: membership.id, password: "test-fixture") + }) + if hasLocalContact { + #expect(try await login.value.success) + } else { + let error = await #expect(throws: RemoteNodeError.self) { _ = try await login.value } + if let error { + let isContactNotFound = if case .contactNotFound = error { true } else { false } + #expect(isContactNotFound) + } + } + let commands = await harness.bluetooth.sentData.dropFirst(frameCount).compactMap { data -> CommandCode? in + guard let raw = data.first, let command = CommandCode(rawValue: raw), + command == .sendLogin || command == .updateContact else { return nil } + return command + } + let expectedCommands: [CommandCode] = hasLocalContact ? [.sendLogin, .updateContact, .sendLogin] : [.sendLogin] + #expect(commands == expectedCommands) + #expect(try await harness.isConnected(membership) == hasLocalContact) + let healed = try await store.fetchContact(radioID: harness.deviceA.radioID, publicKey: publicKey) + #expect(healed?.isFloodRouted == (hasLocalContact ? true : nil)) + let updatedContacts = try await session.getContacts() + let contactIsNowOnRadio = updatedContacts.contains { $0.publicKey == publicKey } + #expect(contactIsNowOnRadio == hasLocalContact) + let timeReads = await harness.bluetooth.timeReads + _ = try await session.getTime() + #expect(await harness.bluetooth.timeReads == timeReads + 1) + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/ServiceContainerWiringTests.swift b/MC1Services/Tests/MC1ServicesTests/ServiceContainerWiringTests.swift index 3bb9b4addb..f8919be058 100644 --- a/MC1Services/Tests/MC1ServicesTests/ServiceContainerWiringTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ServiceContainerWiringTests.swift @@ -121,4 +121,41 @@ struct ServiceContainerWiringTests { await container.stopEventMonitoring() #expect(await container.messageService.isAckExpiryCheckingActive == false) } + + @Test + @MainActor + func `tearDown permanently prevents event monitoring resurrection`() async throws { + let container = try await makeContainer() + await container.tearDown() + + await container.startEventMonitoring( + radioID: UUID(), + enableAutoFetch: false, + enableAdvertisementMonitoring: false + ) + + #expect(container.isEventMonitoringActive == false) + #expect(await container.messageService.isAckExpiryCheckingActive == false) + await container.stopEventMonitoring() + } + + @Test + @MainActor + func `tearDown joins overlapping event monitoring startup`() async throws { + let container = try await makeContainer() + let starting = Task { + await container.startEventMonitoring( + radioID: UUID(), + enableAutoFetch: false, + enableAdvertisementMonitoring: false + ) + } + await Task.yield() + await container.tearDown() + await starting.value + + #expect(container.isEventMonitoringActive == false) + #expect(await container.messageService.isAckExpiryCheckingActive == false) + await container.stopEventMonitoring() + } } diff --git a/MC1Services/Tests/MC1ServicesTests/Services/AccessoryPickerStateTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/AccessoryPickerStateTests.swift new file mode 100644 index 0000000000..5e5a2333fb --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/AccessoryPickerStateTests.swift @@ -0,0 +1,251 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("AccessoryPickerState") +@MainActor +struct AccessoryPickerStateTests { + @Test + func `selection resolves once and keeps picker occupied until dismissal`() async throws { + let harness = Harness() + defer { harness.state.invalidate() } + let selectedID = UUID() + let task = await harness.begin(id: UUID()) + + #expect(harness.state.accessoryAdded(bluetoothID: selectedID) == .selected) + #expect(try await task.value == selectedID) + #expect(harness.state.isActive) + #expect(harness.state.accessoryAdded(bluetoothID: UUID()) == .ignored) + let overlappingTask = await harness.begin(id: UUID()) + await #expect { try await overlappingTask.value } throws: { error in + if case AccessorySetupKitError.pickerAlreadyActive = error { return true } + return false + } + + #expect(harness.state.dismiss()?.outcome == .selected) + #expect(!harness.state.isActive) + let nextTask = await harness.begin(id: UUID()) + #expect(harness.state.accessoryAdded(bluetoothID: selectedID) == .selected) + #expect(try await nextTask.value == selectedID) + } + + @Test + func `cancellation keeps late selection cleanup owned until dismissal`() async { + let harness = Harness() + defer { harness.state.invalidate() } + let attemptID = UUID() + let task = await harness.begin(id: attemptID) + + harness.state.cancel(attemptID: attemptID) + await #expect(throws: CancellationError.self) { try await task.value } + #expect(harness.state.isActive) + let overlappingTask = await harness.begin(id: UUID()) + await #expect { try await overlappingTask.value } throws: { error in + if case AccessorySetupKitError.pickerAlreadyActive = error { return true } + return false + } + #expect(harness.state.accessoryAdded(bluetoothID: UUID()) == .removeAccessory) + #expect(harness.state.accessoryAdded(bluetoothID: UUID()) == .ignored) + #expect(harness.state.isActive) + #expect(harness.state.dismiss()?.outcome == .orphanedAfterCancellation) + #expect(!harness.state.isActive) + } + + @Test + func `dismissal and invalidation do not resolve an attempt twice`() async { + let harness = Harness() + let task = await harness.begin(id: UUID()) + + harness.state.dismiss() + harness.state.dismiss() + harness.state.invalidate() + + await #expect { try await task.value } throws: { error in + if case AccessorySetupKitError.pickerDismissed = error { return true } + return false + } + #expect(!harness.state.isActive) + } + + @Test + func `invalidation rejects old completion and cancellation during new attempt`() async throws { + let harness = Harness() + defer { harness.state.invalidate() } + let oldID = UUID() + let oldTask = await harness.begin(id: oldID) + harness.state.invalidate() + await #expect { try await oldTask.value } throws: { error in + if case AccessorySetupKitError.sessionInvalidated = error { return true } + return false + } + + let newID = UUID() + let newTask = await harness.begin(id: newID) + harness.state.cancel(attemptID: oldID) + harness.state.userCancelled(attemptID: oldID) + harness.state.fail( + AccessorySetupKitError.pickerRestricted, + attemptID: oldID + ) + + #expect(harness.state.attempt?.id == newID) + let selectedID = UUID() + #expect(harness.state.accessoryAdded(bluetoothID: selectedID) == .selected) + #expect(try await newTask.value == selectedID) + } + + @Test + func `rejected presentation permits retry without dismissal`() async throws { + let harness = Harness() + defer { harness.state.invalidate() } + let attemptID = UUID() + let task = await harness.begin(id: attemptID) + harness.state.fail( + AccessorySetupKitError.pickerRestricted, + attemptID: attemptID + ) + + await #expect { try await task.value } throws: { error in + if case AccessorySetupKitError.pickerRestricted = error { return true } + return false + } + #expect(!harness.state.isActive) + let retryTask = await harness.begin(id: UUID()) + let selectedID = UUID() + #expect(harness.state.accessoryAdded(bluetoothID: selectedID) == .selected) + #expect(try await retryTask.value == selectedID) + } + + @Test + func `failure after caller cancellation preserves late selection cleanup`() async { + let harness = Harness() + defer { harness.state.invalidate() } + let attemptID = UUID() + let task = await harness.begin(id: attemptID) + harness.state.didPresent() + harness.state.cancel(attemptID: attemptID) + harness.state.fail( + AccessorySetupKitError.pairingFailed("PIN rejected"), + attemptID: attemptID + ) + + await #expect(throws: CancellationError.self) { try await task.value } + #expect(harness.state.accessoryAdded(bluetoothID: UUID()) == .removeAccessory) + #expect(harness.state.dismiss()?.outcome == .orphanedAfterCancellation) + } + + @Test + func `failure before queued cancellation still cleans up late selection`() async { + let harness = Harness() + defer { harness.state.invalidate() } + let attemptID = UUID() + let task = await harness.begin(id: attemptID) + harness.state.didPresent() + harness.state.fail( + AccessorySetupKitError.pairingFailed("PIN rejected"), + attemptID: attemptID + ) + harness.state.cancel(attemptID: attemptID) + + await #expect { try await task.value } throws: { error in + if case AccessorySetupKitError.pairingFailed = error { return true } + return false + } + #expect(harness.state.accessoryAdded(bluetoothID: UUID()) == .removeAccessory) + #expect(harness.state.dismiss()?.outcome == .orphanedAfterCancellation) + } + + @Test + func `user cancellation callback waits for dismissal`() async { + let harness = Harness() + let attemptID = UUID() + let task = await harness.begin(id: attemptID) + + harness.state.userCancelled(attemptID: attemptID) + #expect(harness.state.isActive) + harness.state.dismiss() + + await #expect { try await task.value } throws: { error in + if case AccessorySetupKitError.pickerDismissed = error { return true } + return false + } + } + + @Test + func `selection without bluetooth identifier fails but retains picker`() async { + let harness = Harness() + let task = await harness.begin(id: UUID()) + + #expect(harness.state.accessoryAdded(bluetoothID: nil) == .selected) + await #expect { try await task.value } throws: { error in + if case AccessorySetupKitError.noBluetoothIdentifier = error { return true } + return false + } + #expect(harness.state.isActive) + harness.state.dismiss() + } + + @Test(arguments: [false, true]) + func `generic failure releases only an unpresented picker`(hasPresented: Bool) async throws { + let harness = Harness() + defer { harness.state.invalidate() } + let attemptID = UUID() + let task = await harness.begin(id: attemptID) + if hasPresented { harness.state.didPresent() } + harness.state.fail( + AccessorySetupKitError.connectionFailed, + attemptID: attemptID + ) + await #expect(throws: AccessorySetupKitError.self) { try await task.value } + let retryTask = await harness.begin(id: UUID()) + if hasPresented { + await #expect { try await retryTask.value } throws: { error in + if case AccessorySetupKitError.pickerAlreadyActive = error { return true } + return false + } + } else { + let selectedID = UUID() + #expect(harness.state.accessoryAdded(bluetoothID: selectedID) == .selected) + #expect(try await retryTask.value == selectedID) + } + } + + @Test + func `late failure cannot replace selection or transfer cleanup ownership`() async throws { + let harness = Harness() + defer { harness.state.invalidate() } + let attemptID = UUID() + let selectedID = UUID() + let task = await harness.begin(id: attemptID) + #expect(harness.state.accessoryAdded(bluetoothID: selectedID) == .selected) + harness.state.fail( + AccessorySetupKitError.pickerRestricted, + attemptID: attemptID + ) + harness.state.cancel(attemptID: attemptID) + #expect(try await task.value == selectedID) + #expect(harness.state.isActive) + #expect(harness.state.accessoryAdded(bluetoothID: selectedID) == .ignored) + #expect(harness.state.dismiss()?.outcome == .cancelledAfterSelection) + } + + @MainActor + private final class Harness { + var state = AccessoryPickerState() + + func begin(id: UUID) async -> Task { + let started = AsyncStream.makeStream() + let task = Task { + try await withCheckedThrowingContinuation { continuation in + state.begin(id: id, presentedAt: Date(), filteredDiscovery: false, continuation: continuation) + started.continuation.yield() + started.continuation.finish() + } + } + for await _ in started.stream { + break + } + return task + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/AckCodeBuilderTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/AckCodeBuilderTests.swift index b8d8e85cd2..2070efd250 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/AckCodeBuilderTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/AckCodeBuilderTests.swift @@ -50,10 +50,7 @@ struct AckCodeBuilderTests { #expect(Set(codes).count == 4) } - /// The firmware masks the attempt index with & 0x03, so the flood attempt - /// (index 4) intentionally reuses attempt 0's code. This is safe: a single - /// message accumulates its codes in a Set, so the wrap is a no-op re-add and - /// any returned ACK still matches the right message. + /// The firmware masks the attempt to two bits; each message retains all of its ACK codes. @Test func `attempt 4 wraps to attempt 0's code`() { let pubkey = Data(repeating: 0x03, count: 32) @@ -61,4 +58,14 @@ struct AckCodeBuilderTests { let attempt4 = AckCodeBuilder.expectedAck(timestamp: 100, attempt: 4, text: "hi", senderPublicKey: pubkey) #expect(attempt0 == attempt4) } + + @Test + func `attempts 5 through 7 reuse attempts 1 through 3`() { + let pubkey = Data(repeating: 0x04, count: 32) + for (later, earlier) in [(UInt8(5), UInt8(1)), (6, 2), (7, 3)] { + let wrapped = AckCodeBuilder.expectedAck(timestamp: 100, attempt: later, text: "hi", senderPublicKey: pubkey) + let first = AckCodeBuilder.expectedAck(timestamp: 100, attempt: earlier, text: "hi", senderPublicKey: pubkey) + #expect(wrapped == first) + } + } } diff --git a/MC1Services/Tests/MC1ServicesTests/Services/BinaryProtocolPathResetTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/BinaryProtocolPathResetTests.swift new file mode 100644 index 0000000000..b489ad4e89 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/BinaryProtocolPathResetTests.swift @@ -0,0 +1,85 @@ +import Foundation +@testable import MC1Services +import MeshCore +import os +import Testing + +@Suite("Binary protocol path reset") +struct BinaryProtocolPathResetTests { + private static let publicKey = Data(repeating: 0xCD, count: 32) + + private final class RecordingContactRadio: ContactRadioOwning, @unchecked Sendable { + private let keys = OSAllocatedUnfairLock(initialState: [Data]()) + + var resetPathPublicKeys: [Data] { + keys.withLock { $0 } + } + + func resetPath(radioID: UUID, publicKey: Data) async throws { + keys.withLock { $0.append(publicKey) } + } + + func healAbsentRadioContact(radioID: UUID, publicKey: Data) async throws -> Bool { + false + } + + func importRadioContact(radioID: UUID, contact: MeshContact) async throws {} + } + + private struct Harness { + let service: BinaryProtocolService + let session: MockMeshCoreSession + let radio: RecordingContactRadio + let suiteName: String + } + + private func makeHarness(fallbackEnabled: Bool?) throws -> Harness { + let suiteName = "BinaryProtocolPathReset.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defaults.removePersistentDomain(forName: suiteName) + if let fallbackEnabled { + defaults.set(fallbackEnabled, forKey: AppStorageKey.remoteFloodFallback.rawValue) + } + let session = MockMeshCoreSession() + let radio = RecordingContactRadio() + let service = BinaryProtocolService( + session: session, + radioID: UUID(), + contactRadio: radio, + defaults: defaults + ) + return Harness(service: service, session: session, radio: radio, suiteName: suiteName) + } + + @Test + func `telemetry timeout resets once when fallback is on`() async throws { + let harness = try makeHarness(fallbackEnabled: nil) + defer { UserDefaults(suiteName: harness.suiteName)?.removePersistentDomain(forName: harness.suiteName) } + await harness.session.setRequestTelemetryResults([ + .failure(MeshCoreError.timeout), + .failure(MeshCoreError.timeout), + ]) + + await #expect(throws: BinaryProtocolError.self) { + _ = try await harness.service.requestTelemetry(from: Self.publicKey) + } + #expect(harness.radio.resetPathPublicKeys == [Self.publicKey]) + #expect(await harness.session.stubbedRequestTelemetryResults.isEmpty) + } + + @Test + func `telemetry timeout does not reset when fallback is off`() async throws { + let harness = try makeHarness(fallbackEnabled: false) + defer { UserDefaults(suiteName: harness.suiteName)?.removePersistentDomain(forName: harness.suiteName) } + await harness.session.setRequestTelemetryResults([ + .failure(MeshCoreError.timeout), + .failure(MeshCoreError.timeout), + ]) + + await #expect(throws: BinaryProtocolError.self) { + _ = try await harness.service.requestTelemetry(from: Self.publicKey) + } + #expect(harness.radio.resetPathPublicKeys.isEmpty) + #expect(await harness.session.stubbedRequestTelemetryResults.count == 1) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChannelInlineSendRetirementTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChannelInlineSendRetirementTests.swift new file mode 100644 index 0000000000..31a4ec254f --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChannelInlineSendRetirementTests.swift @@ -0,0 +1,66 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Inline channel send retirement") +@MainActor +struct ChannelInlineSendRetirementTests { + @Test + func `terminal scope recovery reports connection loss after the inline send commits Sent`() async throws { + let harness = try ConnectionManagerRadioTestHarness() + let commitGate = AsyncStream.makeStream() + do { + _ = try await harness.connect(.bluetooth) + let radioID = try #require(harness.manager.connectedDevice?.radioID) + let store = harness.manager.persistenceStore + let channel = ChannelDTO.testChannel(radioID: radioID, index: 0, floodScope: .region("Selected")) + try await store.saveChannel(channel) + await harness.ble.setChannel(index: channel.index, name: channel.name, secret: channel.secret) + let service = try #require(harness.manager.services?.messageService) + await service.setInlineSendAcceptedGateForTesting { + var iterator = commitGate.stream.makeAsyncIterator() + _ = await iterator.next() + } + await harness.ble.setConnectError(BLEError.deviceNotFound) + await harness.ble.enqueueResponsePackets(for: .setFloodScope, packets: [Data([ResponseCode.ok.rawValue])]) + await harness.ble.enqueueResponsePackets( + for: .setFloodScope, packets: [Data([ResponseCode.error.rawValue, ErrorCode.unsupportedCommand.rawValue])] + ) + + var lossObserved = false + var statusAtLoss: MessageStatus? + harness.manager.onConnectionLost = { _ in + statusAtLoss = try? await store.fetchMessages( + radioID: radioID, channelIndex: channel.index, limit: 1, offset: 0 + ).first?.status + lossObserved = true + } + + let send = Task { + try await service.sendChannelMessage(text: "quick reply", channelIndex: channel.index, radioID: radioID) + } + try await waitUntil("recovery should either wait for the inline send or report loss") { + let waiterCount = await service.inlineSendWaiterCountForTesting + return waiterCount > 0 || lossObserved + } + #expect(!lossObserved) + #expect(try await store.fetchMessages( + radioID: radioID, channelIndex: channel.index, limit: 1, offset: 0 + ).first?.status == .pending) + + commitGate.continuation.finish() + _ = try await send.value + try await waitUntil("the replacement connection should fail") { lossObserved } + #expect(harness.manager.connectionState == .disconnected) + #expect(statusAtLoss == .sent) + #expect(await harness.ble.sentData.filter { $0.first == CommandCode.sendChannelMessage.rawValue }.count == 1) + #expect(try await store.fetchPendingSends(radioID: radioID).isEmpty) + await harness.close() + } catch { + commitGate.continuation.finish() + await harness.close() + throw error + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChannelMessageFloodScopeTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChannelMessageFloodScopeTests.swift index 5ef7cd1220..6ee07defb1 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/ChannelMessageFloodScopeTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChannelMessageFloodScopeTests.swift @@ -69,9 +69,9 @@ struct ChannelMessageFloodScopeTests { #expect(await transport.scopesAtChannelSend == [scopePacket("Gamma")]) } - @Test(arguments: [true, false]) + @Test @MainActor - func `Inherited scope restores the device default or clears the previous region`(hasDefault: Bool) async throws { + func `Inherited scope clears the override without writing the cached default`() async throws { let radioID = UUID() let transport = ChannelScopeTestTransport() let session = MeshCoreSession(transport: transport) @@ -82,7 +82,7 @@ struct ChannelMessageFloodScopeTests { let channel = ChannelDTO.testChannel(radioID: radioID, floodScope: .inherit) try await services.dataStore.saveChannel(channel) try await services.dataStore.saveDevice(DeviceDTO.testDevice(radioID: radioID).copy { - $0.defaultFloodScopeName = hasDefault ? "Alpha" : nil + $0.defaultFloodScopeName = "Alpha" }) try await session.setFloodScope(.region("Beta")) @@ -90,11 +90,12 @@ struct ChannelMessageFloodScopeTests { text: "region-test", channelIndex: channel.index, radioID: radioID ) - let expected = PacketBuilder.setFloodScope((hasDefault ? FloodScope.region("Alpha") : .disabled).scopeKey()) - #expect(await transport.scopesAtChannelSend == [expected]) + let baseline = PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey()) + #expect(await transport.scopesAtChannelSend == [baseline]) + #expect(await transport.scopePackets == [scopePacket("Beta"), baseline]) } - @Test(arguments: [UInt8(8), UInt8(12)]) + @Test(arguments: [UInt8(7), UInt8(8), UInt8(11), UInt8(12)]) @MainActor func `Explicit Unscoped uses only supported firmware commands`(firmwareVersion: UInt8) async throws { let radioID = UUID() @@ -115,7 +116,12 @@ struct ChannelMessageFloodScopeTests { text: "region-test", channelIndex: channel.index, radioID: radioID ) - let expected = firmwareVersion == 12 + if firmwareVersion < 8 { + #expect(await transport.scopePackets == [scopePacket("Beta")]) + #expect(await transport.scopesAtChannelSend == [scopePacket("Beta")]) + return + } + let expected = firmwareVersion >= 12 ? PacketBuilder.setFloodScopeUnscoped() : PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey()) #expect(await transport.scopesAtChannelSend == [expected]) @@ -198,6 +204,43 @@ struct ChannelMessageFloodScopeTests { #expect(await transport.scopesAtChannelSend == [scopePacket("Alpha"), scopePacket("Gamma")]) } + @Test + @MainActor + func `Explicit region send restores the baseline before the next contact command`() async throws { + let radioID = UUID() + let transport = ChannelScopeTestTransport(channelOutcome: .accept) + let session = MeshCoreSession(transport: transport) + try await session.start() + defer { Task { await session.stop() } } + + let services = try await ServiceContainer.forTesting(session: session, radioID: radioID) + let secret = Data(repeating: 0x5A, count: 16) + let channel = ChannelDTO.testChannel(radioID: radioID, index: 3, secret: secret, floodScope: .region("Selected")) + try await services.dataStore.saveChannel(channel) + try await services.dataStore.saveDevice(DeviceDTO.testDevice(radioID: radioID, firmwareVersion: 8).copy { + $0.defaultFloodScopeName = "Persisted" + }) + + _ = try await services.messageService.sendChannelMessage( + text: "region-test", channelIndex: channel.index, radioID: radioID + ) + _ = try await session.sendMessage(to: Data(repeating: 0x22, count: 32), text: "after") + + let selected = scopePacket("Selected") + let baseline = PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey()) + let frames = await transport.sentFrames + let channelFrame = try #require(frames.first { $0.first == CommandCode.sendChannelMessage.rawValue }) + #expect(channelFrame.dropFirst(2).first == channel.index) + #expect(frames.compactMap(\.first) == [ + CommandCode.appStart, .setFloodScope, .sendChannelMessage, .setFloodScope, .sendMessage + ].map(\.rawValue)) + #expect(await transport.scopePackets == [selected, baseline]) + let stored = try #require(try await services.dataStore.fetchMessages( + radioID: radioID, channelIndex: channel.index, limit: 10, offset: 0 + ).first) + #expect(stored.status == .sent) + } + enum SendPath: CaseIterable { case inline, pending, resend } diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChannelResendPreparationTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChannelResendPreparationTests.swift new file mode 100644 index 0000000000..7a5ba949d0 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChannelResendPreparationTests.swift @@ -0,0 +1,102 @@ +import Foundation +@testable import MC1Services +import MeshCore +import SwiftData +import Testing + +@Suite("Channel resend preparation") +struct ChannelResendPreparationTests { + private static let originalTimestamp: UInt32 = 1_700_000_000 + private static let nextTimestamp: UInt32 = originalTimestamp + 60 + private static let previousPath = Data([0x11]) + private static let nextPath = Data([0x22]) + + @Test + func `an echo matched before preparation cannot enter the next wire packet's repeats`() async throws { + let (store, message) = try await makeStoreAndMessage() + let channelIndex = try #require(message.channelIndex) + let stale = try #require(try await store.findSentChannelMessage( + radioID: message.radioID, channelIndex: channelIndex, + timestamp: Self.originalTimestamp, text: message.text + )) + try await store.prepareChannelMessageResend(id: message.id, timestamp: Self.nextTimestamp) + let staleRX = UUID() + let rejected = try await store.admitSentEcho( + messageID: stale.id, expectedTimestamp: stale.timestamp, + receivedAt: Date(), pathNodes: Self.previousPath, pathLength: 1, + snr: nil, rssi: nil, rxLogEntryID: staleRX + ) + #expect(rejected == nil) + #expect(try await store.fetchMessageRepeats(messageID: message.id).isEmpty) + #expect(try await store.fetchMessage(id: message.id)?.heardRepeats == 0) + #expect(try await !store.messageRepeatExists(rxLogEntryID: staleRX)) + + let accepted = try await store.admitSentEcho( + messageID: message.id, expectedTimestamp: Self.nextTimestamp, + receivedAt: Date(), pathNodes: Self.nextPath, pathLength: 1, + snr: nil, rssi: nil, rxLogEntryID: UUID() + ) + #expect(accepted == 1) + #expect(try await store.fetchMessageRepeats(messageID: message.id).map(\.pathNodes) == [Self.nextPath]) + #expect(try await store.fetchMessage(id: message.id)?.heardRepeats == 1) + } + + @Test + @MainActor + func `failed preparation rolls back timestamp and repeats while preserving buffered RX`() async throws { + let (store, message) = try await makeStoreAndMessage() + let originalRepeats = try await store.fetchMessageRepeats(messageID: message.id) + let entry = RxLogEntryDTO( + radioID: message.radioID, + from: ParsedRxLogData( + snr: 10, rssi: -65, rawPayload: Data([0x15]), routeType: .flood, + payloadType: .groupText, payloadVersion: 0, payloadTypeBits: 5, transportCode: nil, + pathLength: 0, pathNodes: [], packetPayload: Data([0xAB]) + ) + ) + try await store.bufferRxLogEntryForResendPreparation(entry) + #expect(await store.unsavedRxLogInsertCount == 1) + await store.setPrepareChannelMessageResendSaveFaultInjection { throw CocoaError(.fileWriteUnknown) } + + await #expect(throws: CocoaError.self) { + try await store.prepareChannelMessageResend(id: message.id, timestamp: Self.nextTimestamp) + } + + let stored = try #require(try await store.fetchMessage(id: message.id)) + #expect(stored.timestamp == message.timestamp) + #expect(stored.heardRepeats == message.heardRepeats) + #expect(try await store.fetchMessageRepeats(messageID: message.id) == originalRepeats) + #expect(await store.unsavedRxLogInsertCount == 0) + let persisted = ModelContext(store.modelContainer) + #expect(try persisted.fetch(FetchDescriptor()).first?.timestamp == message.timestamp) + #expect(try persisted.fetch(FetchDescriptor()).map(\.id) == originalRepeats.map(\.id)) + #expect(try persisted.fetch(FetchDescriptor()).map(\.id) == [entry.id]) + + await store.setPrepareChannelMessageResendSaveFaultInjection(nil) + try await store.prepareChannelMessageResend(id: message.id, timestamp: Self.nextTimestamp) + #expect(try await store.fetchMessage(id: message.id)?.timestamp == Self.nextTimestamp) + #expect(try await store.fetchMessageRepeats(messageID: message.id).isEmpty) + } + + private func makeStoreAndMessage() async throws -> (PersistenceStore, MessageDTO) { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let message = MessageDTO.testChannelMessage(timestamp: Self.originalTimestamp, heardRepeats: 1) + try await store.saveMessage(message) + try await store.saveMessageRepeat(.testRepeat(messageID: message.id, pathNodes: Self.previousPath)) + return (store, message) + } +} + +extension PersistenceStore { + func setPrepareChannelMessageResendSaveFaultInjection(_ hook: (@Sendable () throws -> Void)?) { + prepareChannelMessageResendSaveFaultInjection = hook + } +} + +private extension PersistenceStore { + func bufferRxLogEntryForResendPreparation(_ entry: RxLogEntryDTO) throws { + try saveRxLogEntry(entry) + rxLogFlushTask?.cancel() + rxLogFlushTask = nil + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChannelResendRepeatTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChannelResendRepeatTests.swift new file mode 100644 index 0000000000..38c27ff63b --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChannelResendRepeatTests.swift @@ -0,0 +1,176 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("Channel resend repeats", .timeLimit(.minutes(1))) +struct ChannelResendRepeatTests { + private static let originalTimestamp: UInt32 = 1_700_000_000 + private static let previousPaths: [Data] = [Data([0x11]), Data([0x22])] + private static let earlyEchoPath = Data([0x33]) + private static let initialSendCount = 1 + + @Test(arguments: [false, true]) + func `early echoes survive fresh resends and recovery`(preserveTimestamp: Bool) async throws { + let fixture = try await makeFixture() + defer { Task { await fixture.session.stop() } } + let sendTask = Task { + try await fixture.service.resendChannelMessage( + messageID: fixture.message.id, preserveTimestamp: preserveTimestamp + ) + } + try await reachChannelSend(fixture) + + let beforeAcceptance = try #require(try await fixture.store.fetchMessage(id: fixture.message.id)) + let previousCount = preserveTimestamp ? Self.previousPaths.count : 0 + #expect(beforeAcceptance.heardRepeats == previousCount) + #expect(try await fixture.store.fetchMessageRepeats(messageID: fixture.message.id).count == previousCount) + if preserveTimestamp { + #expect(beforeAcceptance.timestamp == Self.originalTimestamp) + } else { + #expect(beforeAcceptance.timestamp != Self.originalTimestamp) + } + + _ = await fixture.repeats.processForRepeats(echo( + message: beforeAcceptance, path: Self.earlyEchoPath + )) + await fixture.transport.simulateOK() + _ = try await sendTask.value + + let stored = try #require(try await fixture.store.fetchMessage(id: fixture.message.id)) + let repeats = try await fixture.store.fetchMessageRepeats(messageID: fixture.message.id) + let expectedPaths = preserveTimestamp ? Self.previousPaths + [Self.earlyEchoPath] : [Self.earlyEchoPath] + #expect(repeats.map(\.pathNodes) == expectedPaths) + #expect(stored.heardRepeats == repeats.count) + } + + @Test + func `a rejected new resend leaves its prepared repeat state and prior send count`() async throws { + let fixture = try await makeFixture() + defer { Task { await fixture.session.stop() } } + let sendTask = Task { try await fixture.service.resendChannelMessage(messageID: fixture.message.id) } + try await reachChannelSend(fixture) + await fixture.transport.simulateError(code: ErrorCode.unsupportedCommand.rawValue) + await #expect(throws: MessageServiceError.self) { try await sendTask.value } + + let stored = try #require(try await fixture.store.fetchMessage(id: fixture.message.id)) + #expect(stored.timestamp != Self.originalTimestamp) + #expect(stored.status == .failed) + #expect(stored.sendCount == Self.initialSendCount) + #expect(stored.heardRepeats == 0) + #expect(try await fixture.store.fetchMessageRepeats(messageID: fixture.message.id).isEmpty) + } + + @Test + func `failed preparation prevents radio commands`() async throws { + let fixture = try await makeFixture() + defer { Task { await fixture.session.stop() } } + await fixture.store.setPrepareChannelMessageResendSaveFaultInjection { throw CocoaError(.fileWriteUnknown) } + + await #expect(throws: CocoaError.self) { + try await fixture.service.resendChannelMessage(messageID: fixture.message.id) + } + + #expect(await fixture.transport.sentData.count == 1) + let stored = try #require(try await fixture.store.fetchMessage(id: fixture.message.id)) + #expect(stored.status == .failed) + } + + @Test + func `pool retries retain earlier echoes of the same wire packet`() async throws { + let config = MessageServiceConfig(poolBackoff: PoolBackoffConfig( + attemptCap: 1, baseDelay: 0, exponentBase: 1, jitterRange: 1...1 + )) + let fixture = try await makeFixture(config: config) + defer { Task { await fixture.session.stop() } } + let sendTask = Task { + try await fixture.service.resendChannelMessage(messageID: fixture.message.id, preserveTimestamp: true) + } + try await reachChannelSend(fixture) + let prepared = try #require(try await fixture.store.fetchMessage(id: fixture.message.id)) + _ = await fixture.repeats.processForRepeats(echo(message: prepared, path: Self.earlyEchoPath)) + await fixture.transport.simulateError(code: FirmwareDeviceErrorCode.channelMessageNotFound) + try await waitUntil("pool retry should reapply the channel scope") { await fixture.transport.sentData.count == 4 } + await fixture.transport.simulateOK() + try await waitUntil("pool retry should resend the same channel packet") { await fixture.transport.sentData.count == 5 } + let packets = await fixture.transport.sentData + #expect(packets[2] == packets[4]) + await fixture.transport.simulateOK() + _ = try await sendTask.value + + let stored = try #require(try await fixture.store.fetchMessage(id: fixture.message.id)) + let expectedPaths = Self.previousPaths + [Self.earlyEchoPath] + #expect(stored.timestamp == prepared.timestamp) + #expect(stored.heardRepeats == expectedPaths.count) + #expect(try await fixture.store.fetchMessageRepeats(messageID: fixture.message.id).map(\.pathNodes) == expectedPaths) + #expect(stored.sendCount == Self.initialSendCount + 1) + } + + private struct Fixture { + let transport: MockTransport + let session: MeshCoreSession + let store: PersistenceStore + let service: MessageService + let repeats: HeardRepeatsService + let message: MessageDTO + } + + private func makeFixture(config: MessageServiceConfig = .default) async throws -> Fixture { + let transport = MockTransport() + let session = MeshCoreSession(transport: transport) + let startTask = Task { try await session.start() } + try await waitUntil("session should request self info") { await transport.sentData.count == 1 } + await transport.simulateReceive(selfInfoPacket()) + try await startTask.value + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let service = MessageService(session: session, dataStore: store, contactService: nil, config: config) + let repeats = HeardRepeatsService(dataStore: store) + let message = MessageDTO.testChannelMessage( + timestamp: Self.originalTimestamp, + createdAt: Date(timeIntervalSince1970: TimeInterval(Self.originalTimestamp)), + sendCount: Self.initialSendCount + ) + try await store.saveMessage(message) + await repeats.configure(radioID: message.radioID) + for path in Self.previousPaths { + _ = await repeats.processForRepeats(echo(message: message, path: path)) + } + return Fixture(transport: transport, session: session, store: store, service: service, repeats: repeats, message: message) + } + + private func reachChannelSend(_ fixture: Fixture) async throws { + try await waitUntil("resend should set the channel flood scope") { await fixture.transport.sentData.count == 2 } + #expect(await fixture.transport.sentData.last == PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey())) + await fixture.transport.simulateOK() + try await waitUntil("resend should send the channel packet") { await fixture.transport.sentData.count == 3 } + #expect(await fixture.transport.sentData.last?.first == CommandCode.sendChannelMessage.rawValue) + } + + private func echo(message: MessageDTO, path: Data) -> RxLogEntryDTO { + RxLogEntryDTO( + radioID: message.radioID, + from: ParsedRxLogData( + snr: 8, rssi: -70, rawPayload: Data([0x01]), routeType: .flood, + payloadType: .groupText, payloadVersion: 0, payloadTypeBits: 5, transportCode: nil, + pathLength: UInt8(path.count), pathNodes: Array(path), packetPayload: Data([0xAB]) + ), + channelIndex: message.channelIndex, + decryptStatus: .success, + senderTimestamp: message.timestamp, + decodedText: "Test: \(message.text)" + ) + } + + private func selfInfoPacket() -> Data { + var packet = Data([ResponseCode.selfInfo.rawValue, 1, 22, 22]) + packet.append(Data(repeating: 0x01, count: ProtocolLimits.publicKeySize)) + packet.append(Data(repeating: 0, count: MemoryLayout.size * 2)) + packet.append(contentsOf: [0, 0, 0]) + for value: UInt32 in [915_000, 125_000] { + packet.append(contentsOf: withUnsafeBytes(of: value.littleEndian) { Array($0) }) + } + packet.append(contentsOf: [7, 5]) + packet.append(contentsOf: "Test".utf8) + return packet + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChannelServiceTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChannelServiceTests.swift index 5db39fbf3d..8251bb3442 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/ChannelServiceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChannelServiceTests.swift @@ -284,14 +284,28 @@ struct ChannelServiceTests { @Test func `setChannel fires the slot handler on a new secret and not on a same-secret rename or first insert`() async throws { let radioID = UUID() - let (service, _, _, capture) = try await makeService(radioID: radioID) + let (service, _, store, capture) = try await makeService(radioID: radioID) + let index: UInt8 = 5 + + try await service.setChannel(radioID: radioID, index: index, name: "First", passphrase: "one") + let first = try #require(try await store.fetchChannel(radioID: radioID, index: index)) + let firstIdentity = try #require(first.textRulesID) + try await store.setTextRulesOverride( + .on, kind: .privateChannel, key: .init(radioID: radioID, conversationID: firstIdentity) + ) - try await service.setChannel(radioID: radioID, index: 5, name: "First", passphrase: "one") - try await service.setChannel(radioID: radioID, index: 5, name: "Renamed", passphrase: "one") + try await service.setChannel(radioID: radioID, index: index, name: "Renamed", passphrase: "one") + let renamed = try #require(try await store.fetchChannel(radioID: radioID, index: index)) + #expect(renamed.textRulesID == firstIdentity) + #expect(renamed.textRulesOverride == .on) #expect(await capture.received.isEmpty) - try await service.setChannel(radioID: radioID, index: 5, name: "Replaced", passphrase: "two") - #expect(await capture.received == [Set([5])]) + try await service.setChannel(radioID: radioID, index: index, name: "Replaced", passphrase: "two") + let replaced = try #require(try await store.fetchChannel(radioID: radioID, index: index)) + let replacementIdentity = try #require(replaced.textRulesID) + #expect(replacementIdentity != firstIdentity) + #expect(replaced.textRulesOverride == .inherit) + #expect(await capture.received == [Set([index])]) } @Test diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueAdmissionRecoveryTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueAdmissionRecoveryTests.swift new file mode 100644 index 0000000000..c80400e7ed --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueAdmissionRecoveryTests.swift @@ -0,0 +1,98 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Initial queued send reconnect recovery", .timeLimit(.minutes(1))) +@MainActor +struct ChatSendQueueAdmissionRecoveryTests { + private static let acknowledgementTimeoutMilliseconds: UInt32 = 30000 + + @Test + func `a replacement queue records delivery after retirement interrupted initial admission`() async throws { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radio = ConnectionTestRadioTransport() + let session = MeshCoreSession(transport: radio) + try await session.start() + let contact = ContactDTO.testContact() + try await store.saveContact(contact) + await radio.setContact(contact.toContactFrame().toMeshContact()) + let original = makeQueue(store: store, session: session, radioID: contact.radioID) + await store.setPendingSendInsertHandler { + Task { await original.shutdown() } + try await waitUntil("retirement should interrupt the pending-send write") { original.isRetiredForTesting } + } + + let message: MessageDTO + do { + let admission = try await original.enqueueDirectMessage(text: "Recover initial admission", to: contact) + await original.shutdown() + guard case let .enqueueFailed(saved, _) = admission else { + Issue.record("Expected retirement after Message creation to report an enqueue failure") + await session.stop() + return + } + message = saved + #expect(try await store.fetchMessage(id: message.id)?.status == .failed) + #expect(try await store.fetchPendingSends(radioID: contact.radioID).first?.attemptCount == 0) + } catch { + await original.shutdown() + await session.stop() + throw error + } + + await store.setPendingSendInsertHandler(nil) + let messageService = makeMessageService(store: store, session: session) + await messageService.startEventMonitoring() + let replacement = makeQueue(store: store, session: session, radioID: contact.radioID, messageService: messageService) + do { + await radio.holdSubmissions(for: .sendMessage) + await replacement.hydrate() + try await waitUntil("the replacement queue should submit the retained send") { + await radio.submissionIsHeld(for: .sendMessage) + } + let submitted = try #require(try await store.fetchMessage(id: message.id)) + let acknowledgement = AckCodeBuilder.expectedAck( + timestamp: submitted.timestamp, attempt: 0, text: submitted.text, senderPublicKey: radio.publicKey + ) + var accepted = Data([ResponseCode.messageSent.rawValue, 0]) + acknowledgement + withUnsafeBytes(of: Self.acknowledgementTimeoutMilliseconds.littleEndian) { accepted.append(contentsOf: $0) } + await radio.setResponsePackets(for: .sendMessage, packets: [accepted, Data([ResponseCode.ack.rawValue]) + acknowledgement]) + await radio.releaseSubmissions(for: .sendMessage) + await replacement.awaitDrainCompletion() + + let resolved = try await store.fetchMessage(id: message.id) + #expect(resolved?.status == .delivered) + #expect(try await !store.hasPendingSend(messageID: message.id)) + #expect(await radio.sentData.filter { $0.first == CommandCode.sendMessage.rawValue }.count == 1) + } catch { + await radio.releaseAllGates() + await replacement.shutdown() + await messageService.stopEventMonitoring() + await session.stop() + throw error + } + await replacement.shutdown() + await messageService.stopEventMonitoring() + await session.stop() + } + + private func makeMessageService(store: PersistenceStore, session: MeshCoreSession) -> MessageService { + MessageService( + session: session, dataStore: store, contactService: nil, + config: MessageServiceConfig(triggerPathDiscoveryAfterFlood: false), + dmSendBudget: { .singleAttempt } + ) + } + + private func makeQueue( + store: PersistenceStore, session: MeshCoreSession, radioID: UUID, messageService: MessageService? = nil + ) -> ChatSendQueueService { + ChatSendQueueService( + radioID: radioID, dataStore: store, + messageService: messageService ?? makeMessageService(store: store, session: session), + channelService: ChannelService(session: session, dataStore: store, rxLogService: nil), + reactionService: ReactionService() + ) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueAdmissionRetryTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueAdmissionRetryTests.swift new file mode 100644 index 0000000000..57da97fc58 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueAdmissionRetryTests.swift @@ -0,0 +1,157 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Initial queued send preparation retry", .timeLimit(.minutes(1))) +@MainActor +struct ChatSendQueueAdmissionRetryTests { + private static let acknowledgementTimeoutMilliseconds: UInt32 = 30000 + private static let originalTimestamp: UInt32 = 1_700_000_000 + + @Test + func `a failed recovery save parks its DM without preventing later hydration`() async throws { + let fixture = try await Fixture.make() + let interrupted = try #require(fixture.directMessages.first) + await fixture.store.setPendingSendAttemptSaveFaultInjection { messageID in + if messageID == interrupted.id { throw CocoaError(.fileWriteUnknown) } + } + + do { + await fixture.queue.hydrate() + try await waitUntil("the failed DM should park while the later channel send completes") { + guard await fixture.queue.parkedDrainCountForTesting > 0 else { return false } + guard try await fixture.store.fetchMessage(id: fixture.channelMessage.id)?.status == .sent else { return false } + return try await !fixture.store.hasPendingSend(messageID: fixture.channelMessage.id) + } + + let retained = try #require(try await fixture.store.fetchMessage(id: interrupted.id)) + #expect(retained.status == .failed) + #expect(retained.timestamp == Self.originalTimestamp) + let pending = try await fixture.store.fetchPendingSends(radioID: fixture.contact.radioID) + #expect(pending.map(\.messageID) == fixture.directMessages.map(\.id)) + #expect(pending.allSatisfy { $0.attemptCount == 0 && $0.ackDeadline == nil }) + #expect(await fixture.sendFrames(for: .sendMessage).isEmpty) + #expect(await fixture.sendFrames(for: .sendChannelMessage).count == 1) + + await fixture.store.setPendingSendAttemptSaveFaultInjection(nil) + fixture.queue.transportDidOpen() + for (index, message) in fixture.directMessages.enumerated() { + try await fixture.acknowledge(message, submissionCount: index + 1) + } + await fixture.queue.awaitDrainCompletion() + + #expect(try await fixture.store.fetchPendingSends(radioID: fixture.contact.radioID).isEmpty) + #expect(await fixture.sendFrames(for: .sendMessage).count == fixture.directMessages.count) + #expect(await fixture.sendFrames(for: .sendChannelMessage).count == 1) + #expect(!fixture.queue.isRetiredForTesting) + } catch { + await fixture.close() + throw error + } + await fixture.close() + } + + @MainActor + private struct Fixture { + let store: PersistenceStore + let contact: ContactDTO + let directMessages: [MessageDTO] + let channelMessage: MessageDTO + let radio: ConnectionTestRadioTransport + let session: MeshCoreSession + let messageService: MessageService + let queue: ChatSendQueueService + + static func make() async throws -> Fixture { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let contact = ContactDTO.testContact() + let channel = ChannelDTO.testChannel(radioID: contact.radioID) + try await store.saveContact(contact) + try await store.saveChannel(channel) + let interrupted = MessageDTO.testDirectMessage( + radioID: contact.radioID, contactID: contact.id, text: "Interrupted admission", + timestamp: ChatSendQueueAdmissionRetryTests.originalTimestamp, status: .failed + ) + let following = MessageDTO.testDirectMessage( + radioID: contact.radioID, contactID: contact.id, text: "Following DM" + ) + let channelMessage = MessageDTO.testChannelMessage( + radioID: channel.radioID, channelIndex: channel.index, text: "Following channel send", status: .pending + ) + for message in [interrupted, following] { + try await store.saveMessage(message) + _ = try await store.insertPendingSendAssigningSequence(PendingSendDTO( + envelope: DirectMessageEnvelope(messageID: message.id, contactID: contact.id), radioID: contact.radioID + )) + } + try await store.saveMessage(channelMessage) + _ = try await store.insertPendingSendAssigningSequence(PendingSendDTO( + envelope: ChannelMessageEnvelope( + messageID: channelMessage.id, channelIndex: channel.index, isResend: false, + messageText: channelMessage.text, messageTimestamp: channelMessage.timestamp, localNodeName: nil + ), + radioID: channel.radioID + )) + + let radio = ConnectionTestRadioTransport() + await radio.setContact(contact.toContactFrame().toMeshContact()) + await radio.setChannel(index: channel.index, name: channel.name, secret: channel.secret) + await radio.setResponsePackets(for: .sendMessage, packets: []) + let session = MeshCoreSession(transport: radio) + try await session.start() + let messageService = MessageService( + session: session, dataStore: store, contactService: nil, + config: MessageServiceConfig(triggerPathDiscoveryAfterFlood: false), dmSendBudget: { .singleAttempt } + ) + await messageService.startEventMonitoring() + let queue = ChatSendQueueService( + radioID: contact.radioID, dataStore: store, messageService: messageService, + channelService: ChannelService(session: session, dataStore: store, rxLogService: nil), + reactionService: ReactionService() + ) + return Fixture( + store: store, contact: contact, directMessages: [interrupted, following], channelMessage: channelMessage, + radio: radio, session: session, messageService: messageService, queue: queue + ) + } + + func acknowledge(_ message: MessageDTO, submissionCount: Int) async throws { + try await waitUntil("the same queue should submit the next retained DM") { + await sendFrames(for: .sendMessage).count == submissionCount + } + let submitted = try #require(try await store.fetchMessage(id: message.id)) + let pending = try #require(try await store.fetchPendingSendsForMessage(messageID: message.id).first) + #expect(pending.attemptCount == 1) + #expect(submitted.status == .pending) + let frames = await sendFrames(for: .sendMessage) + #expect(frames.last == PacketBuilder.sendMessage( + to: contact.publicKey.prefix(6), text: submitted.text, + timestamp: Date(timeIntervalSince1970: TimeInterval(submitted.timestamp)), attempt: 0 + )) + + let acknowledgement = AckCodeBuilder.expectedAck( + timestamp: submitted.timestamp, attempt: 0, text: submitted.text, senderPublicKey: radio.publicKey + ) + var accepted = Data([ResponseCode.messageSent.rawValue, 0]) + acknowledgement + withUnsafeBytes(of: ChatSendQueueAdmissionRetryTests.acknowledgementTimeoutMilliseconds.littleEndian) { + accepted.append(contentsOf: $0) + } + await radio.inject(accepted) + await radio.inject(Data([ResponseCode.ack.rawValue]) + acknowledgement) + try await waitUntil("the recovered DM should record delivery") { + try await store.fetchMessage(id: message.id)?.status == .delivered + } + } + + func sendFrames(for command: CommandCode) async -> [Data] { + await radio.sentData.filter { $0.first == command.rawValue } + } + + func close() async { + await session.stop() + await queue.shutdown() + await messageService.stopEventMonitoring() + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueAdmissionTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueAdmissionTests.swift new file mode 100644 index 0000000000..4138cede92 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueAdmissionTests.swift @@ -0,0 +1,170 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Initial queued send admission", .timeLimit(.minutes(1))) +@MainActor +struct ChatSendQueueAdmissionTests { + private nonisolated static let text = "Initial queued message" + private nonisolated static let localNodeName = "Local Radio" + + @Test(arguments: [false, true]) + func `admission publishes the persisted Message before queue execution`(isChannel: Bool) async throws { + let fixture = try await Fixture.make() + let observation = Observation() + await fixture.store.setPendingSendInsertHandler { + let published = try #require(await observation.message) + #expect(try await fixture.store.fetchMessage(id: published.id)?.text == Self.text) + #expect(try await fixture.store.fetchPendingSends(radioID: fixture.radioID).isEmpty) + #expect(await fixture.transport.sentData.isEmpty) + } + do { + let result = try await fixture.submit(isChannel: isChannel) { observation.message = $0 } + await fixture.queue.shutdown() + guard case let .queued(message) = result else { + Issue.record("Expected durable queue admission") + return + } + #expect(observation.message?.id == message.id) + #expect(try await fixture.messages(isChannel: isChannel).map(\.id) == [message.id]) + if !isChannel { + #expect(try await fixture.store.fetchContact(id: fixture.contact.id)?.lastMessageDate == message.date) + } + } catch { + await fixture.queue.shutdown() + throw error + } + } + + @Test(arguments: [false, true]) + func `foreign Radio IDs reject before creating a Message`(isChannel: Bool) async throws { + let fixture = try await Fixture.make(recipientRadioID: UUID()) + do { + _ = try await fixture.submit(isChannel: isChannel) + Issue.record("Expected admission to reject the unavailable queue") + } catch ChatSendQueueServiceError.notConnected { + #expect(try await fixture.messages(isChannel: isChannel).isEmpty) + #expect(try await fixture.store.fetchPendingSends(radioID: fixture.radioID).isEmpty) + #expect(try await fixture.store.fetchPendingSends(radioID: fixture.contact.radioID).isEmpty) + } catch { + await fixture.queue.shutdown() + throw error + } + await fixture.queue.shutdown() + } + + @Test(arguments: [false, true]) + func `retirement waits for admission repair and preserves inserted work for hydration`(isChannel: Bool) async throws { + let fixture = try await Fixture.make() + let gate = Gate() + let observation = Observation() + await fixture.store.setPendingSendInsertHandler { await gate.wait() } + let admission = Task { try await fixture.submit(isChannel: isChannel) } + do { + try await waitUntil("admission should reach pending-send insertion") { gate.arrived } + let retirement = Task { + await fixture.queue.shutdown() + observation.retirementFinished = true + } + try await waitUntil("retirement should revoke new admission") { fixture.queue.isRetiredForTesting } + #expect(!observation.retirementFinished) + gate.open() + let result = try await admission.value + await retirement.value + guard case let .enqueueFailed(message, error) = result else { + Issue.record("Text admission must report retirement after saving its Message") + return + } + #expect(error is CancellationError) + #expect(try await fixture.store.fetchMessage(id: message.id)?.status == .failed) + let pending = try #require(try await fixture.store.fetchPendingSends(radioID: fixture.radioID).first) + #expect(pending.messageID == message.id) + #expect(pending.attemptCount == 0) + #expect(await fixture.transport.sentData.isEmpty) + + } catch { + gate.open() + _ = await admission.result + await fixture.queue.shutdown() + throw error + } + } + + @MainActor + private struct Fixture { + let radioID: UUID + let store: PersistenceStore + let contact: ContactDTO + let channel: ChannelDTO + let transport: MockTransport + let queue: ChatSendQueueService + + static func make(recipientRadioID: UUID? = nil) async throws -> Fixture { + let radioID = UUID() + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let contact = ContactDTO.testContact(radioID: recipientRadioID ?? radioID) + let channel = ChannelDTO.testChannel(radioID: recipientRadioID ?? radioID) + try await store.saveContact(contact) + try await store.saveChannel(channel) + let transport = MockTransport() + let session = MeshCoreSession(transport: transport) + let queue = ChatSendQueueService( + radioID: radioID, dataStore: store, + messageService: MessageService(session: session, dataStore: store, contactService: nil), + channelService: ChannelService(session: session, dataStore: store, rxLogService: nil), + reactionService: ReactionService() + ) + return Fixture( + radioID: radioID, store: store, contact: contact, channel: channel, + transport: transport, queue: queue + ) + } + + func submit( + isChannel: Bool, onMessageCreated: (@MainActor (MessageDTO) -> Void)? = nil + ) async throws -> ChatSendAdmission { + if isChannel { + return try await queue.enqueueChannelMessage( + text: ChatSendQueueAdmissionTests.text, to: channel, + localNodeName: ChatSendQueueAdmissionTests.localNodeName, onMessageCreated: onMessageCreated + ) + } + return try await queue.enqueueDirectMessage( + text: ChatSendQueueAdmissionTests.text, to: contact, onMessageCreated: onMessageCreated + ) + } + + func messages(isChannel: Bool) async throws -> [MessageDTO] { + if isChannel { + return try await store.fetchMessages(radioID: channel.radioID, channelIndex: channel.index) + } + return try await store.fetchMessages(contactID: contact.id) + } + } + + @MainActor + private final class Observation { + var message: MessageDTO? + var retirementFinished = false + } + + @MainActor + private final class Gate { + var arrived = false + private var opened = false + private var continuation: CheckedContinuation? + + func wait() async { + arrived = true + guard !opened else { return } + await withCheckedContinuation { continuation = $0 } + } + + func open() { + opened = true + continuation?.resume() + continuation = nil + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueHydrationOccupancyTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueHydrationOccupancyTests.swift new file mode 100644 index 0000000000..0b7efee5ff --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueHydrationOccupancyTests.swift @@ -0,0 +1,208 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import MeshCoreTestSupport +import Testing + +@Suite("Hydrated channel sends") +@MainActor +struct ChatSendQueueHydrationOccupancyTests { + enum Scenario { + case reassignedBeforeSync, reassignedInBackground, unchangedWithPartialSync + + var isReassigned: Bool { + self != .unchangedWithPartialSync + } + } + + struct HydrationSample: Sendable { + var type: TransportType + var scenario: Scenario + } + + /// Bluetooth covers a send before sync, a skipped sync, and a partial sync. + /// One WiFi case covers the ESP32 pipelined channel read. + nonisolated static let hydrationSamples: [HydrationSample] = [ + HydrationSample(type: .bluetooth, scenario: .reassignedBeforeSync), + HydrationSample(type: .bluetooth, scenario: .reassignedInBackground), + HydrationSample(type: .bluetooth, scenario: .unchangedWithPartialSync), + HydrationSample(type: .wifi, scenario: .unchangedWithPartialSync), + ] + + @Test(.timeLimit(.minutes(1)), arguments: hydrationSamples) + func `hydration sends without reading the slot`(_ sample: HydrationSample) async throws { + let type = sample.type + let scenario = sample.scenario + let env = try ConnectionManagerRadioTestHarness() + let radio = type == .bluetooth ? env.ble : env.wifi + do { + let saved = DeviceDTO.testDevice(id: env.deviceID, publicKey: radio.publicKey) + try await env.manager.persistenceStore.saveDevice(saved) + let message = try await HydratedChannelSendHarness.seed(store: env.manager.persistenceStore, radioID: saved.radioID) + let actualSecret = scenario.isReassigned ? HydratedChannelSendHarness.secretB : HydratedChannelSendHarness.secretA + await radio.setChannel(index: 0, name: "Current", secret: actualSecret) + let model = Data("T-Deck".utf8) + let capabilities = Data([ResponseCode.deviceInfo.rawValue, 14, 50, 1]) + + Data(repeating: 0, count: 16) + model + Data(repeating: 0, count: 40 - model.count + 20) + await radio.setResponsePackets(for: .deviceQuery, packets: [capabilities]) + switch scenario { + case .reassignedInBackground: + env.manager.appStateProvider = MockAppStateProvider(isInForeground: false) + case .unchangedWithPartialSync: + await radio.setResponsePackets( + for: .getChannel, + packets: [Data([ResponseCode.error.rawValue, ErrorCode.fileIOError.rawValue])] + ) + case .reassignedBeforeSync: + break + } + env.manager.onConnectionReady = { snapshot in + await snapshot.services.chatSendQueueService.awaitDrainCompletion() + } + + if scenario == .unchangedWithPartialSync { + let clock = TestClock() + env.manager.sessionClockForTesting = clock + _ = try await resultAdvancingMatchedSessionClock(clock, observation: { + await sessionClockObservation(radio: radio, session: env.manager.session) + }) { + if type == .bluetooth { + return try await env.manager.connect(to: env.deviceID, forceFullSync: false, forceReconnect: true) + } + return try await env.manager.connectViaWiFi(host: "radio.test", port: 5123) + } + } else if type == .bluetooth { + _ = try await env.resultAdvancingClock { + try await env.manager.connect(to: env.deviceID, forceFullSync: false, forceReconnect: true) + } + } else { + _ = try await env.resultAdvancingClock { + try await env.manager.connectViaWiFi(host: "radio.test", port: 5123) + } + } + + let current = try #require(env.manager.currentConnection) + await current.services.chatSendQueueService.awaitDrainCompletion() + let frames = await radio.sentData + let sends = frames.filter { $0.first == CommandCode.sendChannelMessage.rawValue } + #expect(sends.count == 1) + if scenario == .reassignedBeforeSync { + // Sync adopts the radio's new secret and deletes the old slot's history, including this send. + #expect(try await env.manager.persistenceStore.fetchMessage(id: message.id) == nil) + } else { + #expect(try await env.manager.persistenceStore.fetchMessage(id: message.id)?.status == .sent) + } + #expect(try await !env.manager.persistenceStore.hasPendingSend(messageID: message.id)) + if scenario == .reassignedInBackground { + #expect(env.manager.installedLink?.usableSyncResult?.channels == .skipped) + #expect(frames.filter { $0.first == CommandCode.getChannel.rawValue }.isEmpty) + } else if scenario == .unchangedWithPartialSync { + #expect(env.manager.installedLink?.usableSyncResult?.channels == .partial) + } + } catch { + await env.close() + throw error + } + await env.close() + } + + @Test + func `a local slot rewrite drops a queued send without a radio read`() async throws { + let harness = try await HydratedChannelSendHarness.make() + do { + try await harness.channelService.setChannelWithSecret( + radioID: harness.radioID, index: 0, name: "Replacement", secret: HydratedChannelSendHarness.secretB + ) + await harness.queue.hydrate() + await harness.queue.awaitDrainCompletion() + + let frames = await harness.radio.sentData + #expect(frames.filter { $0.first == CommandCode.sendChannelMessage.rawValue }.isEmpty) + #expect(frames.filter { $0.first == CommandCode.getChannel.rawValue }.isEmpty) + #expect(try await harness.store.fetchMessage(id: harness.message.id) == nil) + #expect(try await !harness.store.hasPendingSend(messageID: harness.message.id)) + + let service = MessageService(session: harness.session, dataStore: harness.store, contactService: nil) + let message = try await service.createPendingChannelMessage( + text: "New message for the replacement", channelIndex: 0, radioID: harness.radioID + ) + let envelope = ChannelMessageEnvelope( + messageID: message.id, channelIndex: 0, isResend: false, + messageText: message.text, messageTimestamp: message.timestamp, localNodeName: nil + ) + try await harness.queue.enqueueChannel(envelope) + await harness.queue.awaitDrainCompletion() + #expect(await harness.sendFrames.count == 1) + #expect(try await harness.store.fetchMessage(id: message.id)?.status == .sent) + #expect(try await !harness.store.hasPendingSend(messageID: message.id)) + } catch { + await harness.close() + throw error + } + await harness.close() + } + + @Test + func `retirement while a slot write owns the channel preserves the unsent message`() async throws { + let harness = try await HydratedChannelSendHarness.make() + do { + await harness.radio.holdReplies(for: .setChannel) + let write = Task { + try await harness.channelService.setChannelWithSecret( + radioID: harness.radioID, index: 0, name: "Original", secret: HydratedChannelSendHarness.secretA + ) + } + try await waitUntil("the slot write must reach the radio") { + await harness.radio.sentData.contains { $0.first == CommandCode.setChannel.rawValue } + } + await harness.queue.hydrate() + try await waitUntil("the drain must wait for the slot write") { + await harness.channelService.channelOperationWaiterCountForTesting() >= 1 + } + let retirement = Task { await harness.queue.shutdown() } + try await waitUntil("retirement must revoke queue admission") { harness.queue.isRetiredForTesting } + await harness.radio.releaseReplies(for: .setChannel) + try await write.value + await retirement.value + #expect(await harness.sendFrames.isEmpty) + let pending = try #require(try await harness.store.fetchPendingSendsForMessage(messageID: harness.message.id).first) + #expect(pending.attemptCount == 0) + #expect(try await harness.store.fetchMessage(id: harness.message.id)?.status == .pending) + } catch { + await harness.close() + throw error + } + await harness.close() + } + + @Test + func `deleting the pending row while the drain waits prevents the send`() async throws { + let harness = try await HydratedChannelSendHarness.make() + do { + await harness.radio.holdReplies(for: .setChannel) + let write = Task { + try await harness.channelService.setChannelWithSecret( + radioID: harness.radioID, index: 0, name: "Original", secret: HydratedChannelSendHarness.secretA + ) + } + try await waitUntil("the slot write must reach the radio") { + await harness.radio.sentData.contains { $0.first == CommandCode.setChannel.rawValue } + } + await harness.queue.hydrate() + try await waitUntil("the drain must wait for the slot write") { + await harness.channelService.channelOperationWaiterCountForTesting() >= 1 + } + try await harness.store.deleteMessagesForChannel(radioID: harness.radioID, channelIndex: 0) + await harness.radio.releaseReplies(for: .setChannel) + try await write.value + await harness.queue.awaitDrainCompletion() + #expect(await harness.sendFrames.isEmpty) + #expect(try await !harness.store.hasPendingSend(messageID: harness.message.id)) + #expect(try await harness.store.fetchMessage(id: harness.message.id) == nil) + } catch { + await harness.close() + throw error + } + await harness.close() + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueReactionRecoveryTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueReactionRecoveryTests.swift new file mode 100644 index 0000000000..a1ee6df76b --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueReactionRecoveryTests.swift @@ -0,0 +1,113 @@ +import Foundation +@testable import MC1Services +import MeshCore +import SwiftData +import Testing + +@Suite("Queued reaction cold-store recovery", .timeLimit(.minutes(1))) +@MainActor +struct ChatSendQueueReactionRecoveryTests { + private static let channelSecret = Data(repeating: 0xC3, count: 16) + private static let senderName = "Original Reactor" + private static let timestampAdvance: UInt32 = 10 + private static let fixtureDirectory = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() + .appendingPathComponent("../../../../tmp", isDirectory: true) + .standardizedFileURL + + @Test + func `a cold store replays the original reaction intent onto its exact target`() async throws { + let directory = Self.fixtureDirectory.appendingPathComponent("reaction-recovery-\(UUID())", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + // SwiftData can retain contexts after this scope, so store files remain until the test process exits. + let url = directory.appendingPathComponent("messages.store") + let originalStore = try makeStore(at: url) + let original = try await open(store: originalStore) + let target = MessageDTO.testChannelMessage( + radioID: original.radioID, text: "Persisted target", direction: .incoming, senderNodeName: "Ada" + ) + let outgoing: MessageDTO + do { + try await originalStore.saveMessage(target) + await original.radio.setSendError(MeshCoreError.notConnected, for: .sendChannelMessage) + outgoing = try #require(try await original.services.chatSendQueueService.enqueueReaction( + to: target, emoji: "👍", senderName: Self.senderName + )) + try await waitUntil("the persisted reaction must park before replacing its services") { + await original.services.chatSendQueueService.parkedDrainCountForTesting > 0 + } + #expect(try await originalStore.fetchMessage(id: target.id)?.reactionSummary == nil) + #expect(try await originalStore.hasPendingSend(messageID: outgoing.id)) + try await originalStore.updateMessageTimestamp(id: target.id, timestamp: target.timestamp + Self.timestampAdvance) + } catch { + await original.close() + throw error + } + await original.close() + + let restoredStore = try makeStore(at: url) + let restored = try await open(store: restoredStore, radioID: original.radioID) + do { + await restored.services.chatSendQueueService.awaitDrainCompletion() + let saved = try #require(try await restoredStore.fetchMessage(id: outgoing.id)) + #expect(saved.status == .sent) + #expect(saved.text == outgoing.text, "Replay must preserve the hash chosen when the reaction was admitted") + #expect(saved.reactionTargetMessageID == target.id) + #expect(saved.reactionSenderName == Self.senderName) + let reactions = try await restoredStore.fetchReactions(for: target.id) + #expect(reactions.count == 1) + #expect(reactions.first?.senderName == Self.senderName) + #expect(reactions.first?.rawText == outgoing.text) + #expect(try await restoredStore.fetchMessage(id: target.id)?.reactionSummary == "👍:1") + #expect(try await !restoredStore.hasPendingSend(messageID: outgoing.id)) + #expect(await restored.sendCount == 1) + let duplicate = try await restored.services.chatSendQueueService.enqueueReaction( + to: target, emoji: "👍", senderName: Self.senderName + ) + #expect(duplicate == nil) + #expect(await restored.sendCount == 1) + } catch { + await restored.close() + throw error + } + await restored.close() + } + + private func makeStore(at url: URL) throws -> PersistenceStore { + let configuration = ModelConfiguration(schema: PersistenceStore.schema, url: url) + return try PersistenceStore(modelContainer: ModelContainer(for: PersistenceStore.schema, configurations: [configuration])) + } + + private func open(store: PersistenceStore, radioID: UUID = UUID()) async throws -> Connection { + let radio = ConnectionTestRadioTransport() + await radio.setChannel(index: 0, name: "Original", secret: Self.channelSecret) + try await radio.connect() + let session = MeshCoreSession(transport: radio) + try await session.start() + try await store.saveDevice(.testDevice(id: radioID, radioID: radioID, publicKey: radio.publicKey)) + if try await store.fetchChannel(radioID: radioID, index: 0) == nil { + try await store.saveChannel(.testChannel(radioID: radioID, secret: Self.channelSecret)) + } + let services = ServiceContainer(session: session, dataStore: store, radioID: radioID) + try await services.warmUp() + await services.chatSendQueueService.hydrate() + return Connection(radioID: radioID, radio: radio, session: session, services: services) + } + + private struct Connection { + let radioID: UUID + let radio: ConnectionTestRadioTransport + let session: MeshCoreSession + let services: ServiceContainer + + var sendCount: Int { + get async { await radio.sentData.filter { $0.first == CommandCode.sendChannelMessage.rawValue }.count } + } + + func close() async { + await radio.releaseAllGates() + await services.tearDown() + await session.stop() + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueReactionTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueReactionTests.swift new file mode 100644 index 0000000000..8e898b07a6 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueReactionTests.swift @@ -0,0 +1,265 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Queued reaction lifecycle", .timeLimit(.minutes(1))) +@MainActor +struct ChatSendQueueReactionTests { + private static let channelSecret = Data(repeating: 0xA1, count: 16) + private static let replacementSecret = Data(repeating: 0xB2, count: 16) + private static let senderName = "Local Radio" + private static let acknowledgementTimeoutMilliseconds: UInt32 = 30000 + + @Test + func `channel acceptance persists its target badge without an open conversation`() async throws { + let (env, target) = try await makeChannelEnvironment() + do { + let queue = try #require(env.manager.currentConnection?.services.chatSendQueueService) + let outgoing = try #require(try await queue.enqueueReaction(to: target, emoji: "👍", senderName: Self.senderName)) + await queue.awaitDrainCompletion() + + #expect(try await env.manager.persistenceStore.fetchMessage(id: outgoing.id)?.status == .sent) + #expect(try await env.manager.persistenceStore.fetchMessage(id: target.id)?.reactionSummary == "👍:1") + #expect(try await env.manager.persistenceStore.fetchReactions(for: target.id).count == 1) + #expect(try await !env.manager.persistenceStore.hasPendingSend(messageID: outgoing.id)) + #expect(await sendCount(env, command: .sendChannelMessage) == 1) + } catch { + await env.close() + throw error + } + await env.close() + } + + @Test + func `an accepted channel reaction retries a failed local save without another radio command`() async throws { + let (env, target) = try await makeChannelEnvironment() + do { + let store = env.manager.persistenceStore + let queue = try #require(env.manager.currentConnection?.services.chatSendQueueService) + await store.setUpdateMessageStatusFaultInjection { _, status in + if status == .sent { throw CocoaError(.fileWriteUnknown) } + } + let outgoing = try #require(try await queue.enqueueReaction(to: target, emoji: "👍", senderName: Self.senderName)) + try await waitUntil("the accepted reaction should park until its local save can commit") { + await queue.parkedDrainCountForTesting > 0 + } + + #expect(await sendCount(env, command: .sendChannelMessage) == 1) + #expect(try await store.fetchMessage(id: outgoing.id)?.status == .pending) + #expect(try await store.hasPendingSend(messageID: outgoing.id)) + #expect(try await store.fetchReactions(for: target.id).isEmpty) + #expect(try await store.fetchMessage(id: target.id)?.reactionSummary == nil) + + await store.setUpdateMessageStatusFaultInjection(nil) + queue.transportDidOpen() + try await waitUntil("the accepted reaction should finish its local bookkeeping") { + try await store.fetchMessage(id: target.id)?.reactionSummary == "👍:1" + } + await queue.awaitDrainCompletion() + + #expect(await sendCount(env, command: .sendChannelMessage) == 1) + #expect(try await store.fetchMessage(id: outgoing.id)?.status == .sent) + #expect(try await store.fetchReactions(for: target.id).count == 1) + #expect(try await !store.hasPendingSend(messageID: outgoing.id)) + } catch { + await env.close() + throw error + } + await env.close() + } + + @Test + func `concurrent taps admit one outstanding reaction and send one packet`() async throws { + let (env, target) = try await makeChannelEnvironment() + do { + let queue = try #require(env.manager.currentConnection?.services.chatSendQueueService) + await env.ble.holdSubmissions(for: .sendChannelMessage) + async let first = queue.enqueueReaction(to: target, emoji: "👍", senderName: Self.senderName) + async let second = queue.enqueueReaction(to: target, emoji: "👍", senderName: Self.senderName) + let admitted = try await [first, second].compactMap(\.self) + #expect(admitted.count == 1) + #expect(try await env.manager.persistenceStore.fetchPendingSends(radioID: target.radioID).count == 1) + #expect(try await env.manager.persistenceStore.fetchReactions(for: target.id).isEmpty) + + await env.ble.releaseSubmissions(for: .sendChannelMessage) + await queue.awaitDrainCompletion() + let duplicate = try await queue.enqueueReaction(to: target, emoji: "👍", senderName: Self.senderName) + + #expect(duplicate == nil) + #expect(await sendCount(env, command: .sendChannelMessage) == 1) + #expect(try await env.manager.persistenceStore.fetchMessage(id: target.id)?.reactionSummary == "👍:1") + } catch { + await env.close() + throw error + } + await env.close() + } + + @Test + func `a parked channel reaction resumes after ConnectionManager rebuilds services`() async throws { + let (env, target) = try await makeChannelEnvironment() + do { + let original = try #require(env.manager.currentConnection?.services.chatSendQueueService) + await env.ble.setSendError(MeshCoreError.notConnected, for: .sendChannelMessage) + let outgoing = try #require(try await original.enqueueReaction(to: target, emoji: "👍", senderName: Self.senderName)) + try await waitUntil("the reaction should park after its transport failure") { + await original.parkedDrainCountForTesting > 0 + } + #expect(try await env.manager.persistenceStore.fetchMessage(id: outgoing.id)?.status == .pending) + #expect(try await env.manager.persistenceStore.hasPendingSend(messageID: outgoing.id)) + #expect(try await env.manager.persistenceStore.fetchReactions(for: target.id).isEmpty) + + _ = await env.manager.disconnect(reason: .userInitiated) + await env.manager.retirementTask?.value + await env.ble.setSendError(nil, for: .sendChannelMessage) + _ = try await env.connect(.bluetooth) + let replacement = try #require(env.manager.currentConnection?.services.chatSendQueueService) + await replacement.awaitDrainCompletion() + + #expect(replacement !== original) + #expect(try await env.manager.persistenceStore.fetchMessage(id: outgoing.id)?.status == .sent) + #expect(try await env.manager.persistenceStore.fetchMessage(id: target.id)?.reactionSummary == "👍:1") + #expect(try await !env.manager.persistenceStore.hasPendingSend(messageID: outgoing.id)) + #expect(await sendCount(env, command: .sendChannelMessage) == 1) + } catch { + await env.close() + throw error + } + await env.close() + } + + @Test + func `an external slot change still sends the reaction`() async throws { + let (env, target) = try await makeChannelEnvironment() + do { + await env.ble.setChannel(index: 0, name: "Replacement", secret: Self.replacementSecret) + let queue = try #require(env.manager.currentConnection?.services.chatSendQueueService) + let outgoing = try #require(try await queue.enqueueReaction(to: target, emoji: "👍", senderName: Self.senderName)) + await queue.awaitDrainCompletion() + + #expect(try await env.manager.persistenceStore.fetchMessage(id: outgoing.id)?.status == .sent) + #expect(try await env.manager.persistenceStore.fetchMessage(id: target.id)?.reactionSummary == "👍:1") + #expect(try await !env.manager.persistenceStore.hasPendingSend(messageID: outgoing.id)) + #expect(await sendCount(env, command: .sendChannelMessage) == 1) + } catch { + await env.close() + throw error + } + await env.close() + } + + @Test + func `a removed target cannot admit reaction work`() async throws { + let (env, target) = try await makeChannelEnvironment() + do { + let queue = try #require(env.manager.currentConnection?.services.chatSendQueueService) + try await env.manager.persistenceStore.deleteMessage(id: target.id) + let outgoing = try await queue.enqueueReaction(to: target, emoji: "👍", senderName: Self.senderName) + await queue.awaitDrainCompletion() + + #expect(outgoing == nil) + #expect(try await env.manager.persistenceStore.fetchPendingSends(radioID: target.radioID).isEmpty) + #expect(await sendCount(env, command: .sendChannelMessage) == 0) + } catch { + await env.close() + throw error + } + await env.close() + } + + @Test(arguments: [false, true]) + func `a DM reaction keeps one submission and the badge through acceptance or a fast ACK`(fastACK: Bool) async throws { + let (env, target) = try await makeDMEnvironment() + do { + await env.ble.holdSubmissions(for: .sendMessage) + let queue = try #require(env.manager.currentConnection?.services.chatSendQueueService) + let outgoing = try #require(try await queue.enqueueReaction(to: target, emoji: "👍", senderName: Self.senderName)) + try await waitUntil("the reaction should reach command submission") { + await env.ble.submissionIsHeld(for: .sendMessage) + } + let submitted = try #require(try await env.manager.persistenceStore.fetchMessage(id: outgoing.id)) + let acknowledgement = AckCodeBuilder.expectedAck( + timestamp: submitted.timestamp, attempt: 0, text: submitted.text, senderPublicKey: env.ble.publicKey + ) + var responses = [messageSentPacket(acknowledgement: acknowledgement)] + if fastACK { responses.append(Data([ResponseCode.ack.rawValue]) + acknowledgement) } + await env.ble.setResponsePackets(for: .sendMessage, packets: responses) + await env.ble.releaseSubmissions(for: .sendMessage) + try await waitUntil("radio acceptance should persist the reaction badge") { + try await env.manager.persistenceStore.fetchMessage(id: target.id)?.reactionSummary == "👍:1" + } + await queue.awaitDrainCompletion() + + #expect(try await env.manager.persistenceStore.fetchMessage(id: outgoing.id)?.status == (fastACK ? .delivered : .sent)) + #expect(try await env.manager.persistenceStore.fetchReactions(for: target.id).count == 1) + #expect(await sendCount(env, command: .sendMessage) == 1) + let owners = try await env.manager.persistenceStore.fetchPendingSends(radioID: target.radioID) + if fastACK { + #expect(owners.isEmpty) + } else { + #expect(owners.count == 1) + #expect(owners.first?.ackDeadline != nil) + #expect(owners.first?.isSingleAttempt == true) + } + } catch { + await env.close() + throw error + } + await env.close() + } + + private func makeChannelEnvironment() async throws -> (ConnectionManagerRadioTestHarness, MessageDTO) { + let env = try ConnectionManagerRadioTestHarness() + configureNotifications(env) + await env.ble.setChannel(index: 0, name: "Original", secret: Self.channelSecret) + do { + _ = try await env.connect(.bluetooth) + let connection = try #require(env.manager.currentConnection) + let target = MessageDTO.testChannelMessage( + radioID: connection.device.radioID, text: "Channel reaction target", direction: .incoming, senderNodeName: "Ada" + ) + try await env.manager.persistenceStore.saveMessage(target) + return (env, target) + } catch { + await env.close() + throw error + } + } + + private func makeDMEnvironment() async throws -> (ConnectionManagerRadioTestHarness, MessageDTO) { + let env = try ConnectionManagerRadioTestHarness() + configureNotifications(env) + do { + _ = try await env.connect(.bluetooth) + let connection = try #require(env.manager.currentConnection) + let contact = ContactDTO.testContact(radioID: connection.device.radioID) + try await env.manager.persistenceStore.saveContact(contact) + await env.ble.setContact(contact.toContactFrame().toMeshContact()) + let target = MessageDTO.testDirectMessage( + radioID: connection.device.radioID, contactID: contact.id, text: "DM reaction target", direction: .incoming, status: .delivered + ) + try await env.manager.persistenceStore.saveMessage(target) + return (env, target) + } catch { + await env.close() + throw error + } + } + + private func configureNotifications(_ env: ConnectionManagerRadioTestHarness) { + env.manager.testNotificationSystemOperations = .init( + setBadgeCount: { _ in }, deliveredRequests: { [] }, removeDeliveredNotifications: { _ in } + ) + } + + private func sendCount(_ env: ConnectionManagerRadioTestHarness, command: CommandCode) async -> Int { + await env.ble.sentData.filter { $0.first == command.rawValue }.count + } + + private func messageSentPacket(acknowledgement: Data) -> Data { + var packet = Data([ResponseCode.messageSent.rawValue, 0]) + acknowledgement + withUnsafeBytes(of: Self.acknowledgementTimeoutMilliseconds.littleEndian) { packet.append(contentsOf: $0) } + return packet + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceAttemptCountTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceAttemptCountTests.swift index 9bc59c308a..beba6c364d 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceAttemptCountTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceAttemptCountTests.swift @@ -4,34 +4,9 @@ import Foundation import MeshCoreTestSupport import Testing -/// Acceptance suite for the persistent `PendingSend.attemptCount` surface. -/// Covers three cases: -/// 1. Fresh send: enqueue then drain bumps 0 → 1, `preserveTimestamp == false`. -/// 2. Process restart: a row left at `attemptCount = 1` on disk (prior process -/// bumped then died before deleting the row) rehydrates, drains, bumps to -/// `2`, and uses `preserveTimestamp == true` so the recipient's mesh dedup -/// catches a duplicate landing. -/// 3. Bump failure: `incrementPendingSendAttemptCount` is forced to throw, the -/// envelope parks on the transport-open trigger, the row survives, and no -/// wire send happens. @Suite("ChatSendQueueService.attemptCount") @MainActor struct ChatSendQueueServiceAttemptCountTests { - /// Helper: build a Device + Contact + Message + PendingSend with the - /// requested attemptCount, returning the service, the store it shares, - /// the messageID, the radioID, and the message's original wire timestamp. - /// The service is not hydrated — the caller decides whether to hydrate or - /// to first run `store.warmUp()`. - /// - /// The message's `timestamp` is pinned to one hour ago so a "fresh wire - /// timestamp" stamp by `updateMessageTimestamp` (preserveTimestamp=false) - /// is observably different from a "preserved" timestamp - /// (preserveTimestamp=true). UInt32 epoch-second granularity would - /// otherwise collide on a fast test run. - /// - /// `radioID` comes from `Device.radioID` (not `Device.id`) so the - /// in-progress radio survives `purgeOrphanPendingSends`, which keys on - /// `Device.radioID`. private struct QueueHarness { let service: ChatSendQueueService let store: PersistenceStore @@ -63,11 +38,15 @@ struct ChatSendQueueServiceAttemptCountTests { try container.mainContext.save() let contactDTO = try #require(try await store.fetchContact(id: contact.id)) - let transport = SimulatorMockTransport() - let session = MeshCoreSession(transport: transport) + let session = MockMeshCoreSession() + await session.setCurrentSelfInfo(.testSelfInfo()) + await session.setSendMessageResult(.success( + MessageSentInfo(route: 0, expectedAck: Data([0x01, 0x02, 0x03, 0x04]), suggestedTimeoutMs: 10) + )) let messageService = MessageService(session: session, dataStore: store, contactService: nil) let pending = try await messageService.createPendingMessage(text: "Hello", to: contactDTO) + // An older timestamp makes the first-attempt refresh observable despite whole-second precision. let pinnedTimestamp = UInt32(Date().addingTimeInterval(-3600).timeIntervalSince1970) try await store.updateMessageTimestamp(id: pending.id, timestamp: pinnedTimestamp) let message = try #require(try await store.fetchMessage(id: pending.id)) @@ -108,13 +87,6 @@ struct ChatSendQueueServiceAttemptCountTests { ) } - /// Case 1 / Fresh send: a row with `attemptCount = 0` (current-build - /// race-window row that persisted but never progressed past the - /// top-of-drain bump) drains with `preserveTimestamp = false` because - /// `postBumpCount = 1 > 1` is false. The recipient never saw the packet, - /// so a fresh wire timestamp is correct. Observable side effect: - /// `Message.timestamp` changes (updateMessageTimestamp was called by - /// `sendPendingDirectMessage`). @Test func `fresh send: row with attemptCount=0 first drain uses fresh timestamp`() async throws { let harness = try await Self.setupQueueWithRow(attemptCount: 0) @@ -125,7 +97,7 @@ struct ChatSendQueueServiceAttemptCountTests { try await waitUntil(timeout: .seconds(10), "first drain must bump 0 → 1 and stamp a fresh timestamp") { guard let row = await (try? harness.store.fetchPendingSends(radioID: harness.radioID))? - .first(where: { $0.messageID == harness.messageID }), + .first(where: { $0.messageID == harness.messageID }), let timestamp = await (try? harness.store.fetchMessage(id: harness.messageID))?.timestamp else { return false } return row.attemptCount == 1 && timestamp != harness.originalTimestamp @@ -137,16 +109,11 @@ struct ChatSendQueueServiceAttemptCountTests { let postDrainMessage = try await harness.store.fetchMessage(id: harness.messageID) #expect(postDrainMessage?.timestamp != harness.originalTimestamp, - "preserveTimestamp=false: updateMessageTimestamp must stamp a fresh wire timestamp") + "preserveTimestamp=false: the command save must stamp a fresh wire timestamp") await harness.service.shutdown() } - /// Case 2 / Process restart: a row left at `attemptCount = 1` simulates - /// "prior process bumped before sending then died before - /// deletePendingSendsForMessage". On rehydrate the drain bumps to 2 and - /// preserves the wire timestamp so mesh dedup catches a duplicate - /// landing if the wire send completed. @Test func `process restart: row with attemptCount=1 rehydrates with preserveTimestamp=true`() async throws { let harness = try await Self.setupQueueWithRow(attemptCount: 1) @@ -168,39 +135,4 @@ struct ChatSendQueueServiceAttemptCountTests { await harness.service.shutdown() } - - /// Case 3 / Bump failure: when `incrementPendingSendAttemptCount` throws, - /// the drain closure must park the envelope on the transport-open trigger - /// (status reverts to `.pending`), leave the PendingSend row intact, and - /// must not call `sendPendingDirectMessage`. Without this guarantee a - /// SwiftData failure during the bump could either drop the envelope - /// silently or double-send on retry. - @Test - func `bump failure parks envelope, preserves row, does not call sendPendingDirectMessage`() async throws { - let harness = try await Self.setupQueueWithRow(attemptCount: 0) - - // Force every subsequent incrementPendingSendAttemptCount call to throw - // so the drain closure takes the bump-failure park branch. - struct FakeSaveFailure: Error {} - await harness.store.setIncrementPendingSendAttemptCountFaultInjection { - throw FakeSaveFailure() - } - - await harness.service.hydrate() - try? await Task.sleep(for: .milliseconds(500)) - - let rows = try await harness.store.fetchPendingSends(radioID: harness.radioID) - #expect(rows.count == 1, - "PendingSend row must survive the bump-failure park so the next transport-open can retry") - #expect(rows.first?.attemptCount == 0, - "attemptCount must not advance when the bump throws — the next drain bumps to the same target") - - let postDrainMessage = try await harness.store.fetchMessage(id: harness.messageID) - #expect(postDrainMessage?.timestamp == harness.originalTimestamp, - "bump-failure park must run before any wire-affecting work — wire timestamp untouched") - #expect(postDrainMessage?.status == .pending, - "park branch must remap status back to .pending so the bubble does not flicker .failed") - - await harness.service.shutdown() - } } diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceReconnectTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceReconnectTests.swift index aa83e85ae3..569ab218f8 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceReconnectTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceReconnectTests.swift @@ -40,6 +40,10 @@ struct ChatSendQueueServiceReconnectTests { timeoutMilliseconds: Self.interruptedAckTimeoutMilliseconds )) try await waitForAckWait(original, messageID: message.id) + let accepted = try #require( + try await store.fetchPendingSends(radioID: radioID).first { $0.messageID == message.id } + ) + #expect(accepted.nextWireAttempt == 1) let beforeDisconnect = try #require(await store.fetchMessage(id: message.id)) await original.session.stop() @@ -70,16 +74,16 @@ struct ChatSendQueueServiceReconnectTests { to: contact.publicKey.prefix(6), text: message.text, timestamp: Date(timeIntervalSince1970: TimeInterval(beforeDisconnect.timestamp)), - attempt: 0 + attempt: 1 )) await replay.transport.simulateReceive(messageSentPacket( message: replayedMessage, - attempt: 0, + attempt: 1, timeoutMilliseconds: Self.interruptedAckTimeoutMilliseconds )) try await waitForAckWait(replay, messageID: message.id) var ackPacket = Data([ResponseCode.ack.rawValue]) - ackPacket.append(expectedAck(message: replayedMessage, attempt: 0)) + ackPacket.append(expectedAck(message: replayedMessage, attempt: 1)) await replay.transport.simulateReceive(ackPacket) // finalizeSend reads the contact path after the ACK, so the drain stays in flight until that read returns. @@ -109,7 +113,8 @@ struct ChatSendQueueServiceReconnectTests { session: session, dataStore: store, contactService: nil, - config: MessageServiceConfig(maxAttempts: 3, floodAfter: 3, triggerPathDiscoveryAfterFlood: false) + config: MessageServiceConfig(triggerPathDiscoveryAfterFlood: false), + dmSendBudget: { DMSendBudget(directAttempts: 3, floodAttempts: 0) } ) let queue = ChatSendQueueService( radioID: radioID, diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceTests.swift index 091c77ac9c..068ac9a3de 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceTests.swift @@ -268,8 +268,8 @@ struct ChatSendQueueServiceTests { func `channel drain fails when fetchChannel confirms the channel is gone`() async throws { let harness = try await Self.setUpChannelCapHarness(attemptCount: 7) defer { Task { await harness.queue.shutdown() } } - await harness.session.setGetChannelError( - MeshCoreError.deviceError(code: FirmwareDeviceErrorCode.channelMessageNotFound) + await harness.session.setGetChannelResults( + harness.channelReads(endingWith: MeshCoreError.deviceError(code: FirmwareDeviceErrorCode.channelMessageNotFound)) ) await harness.queue.hydrate() @@ -281,6 +281,7 @@ struct ChatSendQueueServiceTests { #expect(try await harness.dataStore.fetchMessage(id: harness.messageID)?.status == .failed) #expect(await harness.session.getChannelIndices == [0]) + #expect(await harness.session.sendChannelMessageInvocations.count == harness.poolAttempts) await harness.queue.shutdown() } @@ -288,13 +289,12 @@ struct ChatSendQueueServiceTests { func `channel drain parks deviceError(2) below disambiguateAfterAttempts`() async throws { let harness = try await Self.setUpChannelCapHarness(attemptCount: 0) defer { Task { await harness.queue.shutdown() } } - try await harness.dataStore.updateMessageStatus(id: harness.messageID, status: .failed) - await harness.queue.hydrate() - try await waitUntil("channel send should fail and return to pending") { + try await waitUntil("channel pool exhaustion should park the pending send") { let sent = await harness.session.sendChannelMessageInvocations.count let message = try? await harness.dataStore.fetchMessage(id: harness.messageID) - return sent >= 2 && message?.status == .pending + let parked = await harness.queue.parkedDrainCountForTesting + return sent == harness.poolAttempts && message?.status == .pending && parked > 0 } #expect(try await harness.dataStore.hasPendingSend(messageID: harness.messageID)) @@ -304,18 +304,22 @@ struct ChatSendQueueServiceTests { @Test func `persistent channel fetch failures stop at the configured cap`() async throws { + let failureCap = 2 let harness = try await Self.setUpChannelCapHarness( attemptCount: 7, - queueConfig: ChatSendQueueConfig(maxConsecutiveFetchChannelFailures: 2) + queueConfig: ChatSendQueueConfig(maxConsecutiveFetchChannelFailures: failureCap) ) defer { Task { await harness.queue.shutdown() } } - await harness.session.setGetChannelError(MeshCoreError.deviceError(code: 1)) + let fetchError = MeshCoreError.deviceError(code: ErrorCode.unsupportedCommand.rawValue) + let readResults = (0.. 0 } #expect(try await harness.dataStore.hasPendingSend(messageID: harness.messageID)) @@ -326,7 +330,8 @@ struct ChatSendQueueServiceTests { } await harness.queue.awaitDrainCompletion() - #expect(await harness.session.getChannelIndices == [0, 0]) + #expect(await harness.session.getChannelIndices == Array(repeating: 0, count: failureCap)) + #expect(await harness.session.sendChannelMessageInvocations.count == failureCap * harness.poolAttempts) #expect(try await harness.dataStore.fetchMessage(id: harness.messageID)?.status == .failed) await harness.queue.shutdown() } @@ -338,6 +343,12 @@ struct ChatSendQueueServiceTests { let session: MockMeshCoreSession let dataStore: PersistenceStore let messageID: UUID + let channel: ChannelInfo + let poolAttempts: Int + + func channelReads(endingWith error: Error) -> [Result] { + [.failure(error)] + } } private static func setUpChannelCapHarness( @@ -365,6 +376,8 @@ struct ChatSendQueueServiceTests { try container.mainContext.save() let session = MockMeshCoreSession() + let channelInfo = ChannelInfo(index: channelIndex, name: channel.name, secret: channel.secret) + await session.setStubbedChannels([channelIndex: channelInfo]) await session.setSendChannelMessageError( MeshCoreError.deviceError(code: FirmwareDeviceErrorCode.channelMessageNotFound) ) @@ -416,7 +429,9 @@ struct ChatSendQueueServiceTests { queue: queueService, session: session, dataStore: store, - messageID: pending.id + messageID: pending.id, + channel: channelInfo, + poolAttempts: messageConfig.poolBackoff.attemptCap + 1 ) } @@ -461,14 +476,8 @@ struct ChatSendQueueServiceTests { "second hydrate on same instance must not re-enqueue persisted rows") } - /// Regression: when a DM send fails with a transient firmware code - /// (e.g. `directMessageTableFull`), `failMessageAndRethrow` writes - /// `.failed` and broadcasts the failure before the queue's - /// catch reclassifies the error and remaps the status back to - /// `.pending`. The broadcast propagates an in-memory `.failed` - /// snapshot to the UI even though the persisted state is `.pending`, - /// causing the bubble to flicker "Failed" while the queue is parked. - /// Transient errors must not broadcast `.failed` at all. + /// A transient firmware code such as `directMessageTableFull` stays queued. + /// The drain must not broadcast `.failed` while that row is parked. @Test func `Transient DM send error must not broadcast .failed`() async throws { // Tight pool-backoff so the failure surfaces fast. The invariant @@ -522,6 +531,138 @@ struct ChatSendQueueServiceTests { #expect(ids.first == harness.messageID, ".failed must carry the failed envelope's messageID") } + @Test + func `a table-full rejection keeps the attempt byte for the next drain`() async throws { + let messageConfig = MessageServiceConfig( + poolBackoff: PoolBackoffConfig(attemptCap: 1, baseDelay: 0.01) + ) + let harness = try await Self.setUpDMHarness(messageConfig: messageConfig) + defer { Task { await harness.tearDown() } } + + await harness.session.setSendMessageResult(.failure( + MeshCoreError.deviceError(code: FirmwareDeviceErrorCode.directMessageTableFull) + )) + try await harness.drainUntilParked() + + let parked = try await harness.dataStore.fetchPendingSends(radioID: harness.radioID) + .first { $0.messageID == harness.messageID } + #expect(parked?.nextWireAttempt == 0) + let firstCount = await harness.session.sendMessageInvocations.count + #expect(await harness.session.sendMessageInvocations.allSatisfy { $0.attempt == 0 }) + + harness.queue.observeConnectionState(initial: .ready, events: AsyncStream { $0.finish() }) + try await waitUntil(timeout: .seconds(10), "the parked drain should retry the same byte") { + await harness.session.sendMessageInvocations.count > firstCount + } + #expect(await harness.session.sendMessageInvocations.allSatisfy { $0.attempt == 0 }) + let stillParked = try await harness.dataStore.fetchPendingSends(radioID: harness.radioID) + .first { $0.messageID == harness.messageID } + #expect(stillParked?.nextWireAttempt == 0) + } + + @Test + func `a host timeout consumes the attempt byte`() async throws { + let harness = try await Self.setUpDMHarness( + messageConfig: MessageServiceConfig(minTimeout: 0, poolBackoff: PoolBackoffConfig(attemptCap: 0, baseDelay: 0)) + ) + defer { Task { await harness.tearDown() } } + + await harness.session.setSendMessageResult(.failure(MeshCoreError.timeout)) + await harness.queue.hydrate() + try await waitUntil("a timed-out command should park with the next byte stored") { + let row = try? await harness.dataStore.fetchPendingSends(radioID: harness.radioID) + .first { $0.messageID == harness.messageID } + let message = try? await harness.dataStore.fetchMessage(id: harness.messageID) + let parked = await harness.queue.parkedDrainCountForTesting + return row?.nextWireAttempt == 1 && message?.status == .pending && parked > 0 + } + let timedOut = await harness.session.sendMessageInvocations + #expect(timedOut.map(\.attempt) == [0]) + let timestamp = try #require(timedOut.first?.timestamp) + + await harness.session.setSendMessageResult(.success( + MessageSentInfo(route: 0, expectedAck: Data([0x01, 0x02, 0x03, 0x04]), suggestedTimeoutMs: 10) + )) + harness.queue.observeConnectionState(initial: .ready, events: AsyncStream { $0.finish() }) + try await waitUntil(timeout: .seconds(10), "the next drain should submit the unused byte") { + await harness.session.sendMessageInvocations.contains { $0.attempt == 1 } + } + let invocations = await harness.session.sendMessageInvocations + #expect(invocations.filter { $0.attempt == 0 }.count == 1) + #expect(invocations.first { $0.attempt == 1 }?.timestamp == timestamp) + } + + @Test + func `an acknowledgement during resume stops the next attempt`() async throws { + let harness = try await Self.setUpDMHarness( + messageConfig: MessageServiceConfig(minTimeout: 0, poolBackoff: PoolBackoffConfig(attemptCap: 0, baseDelay: 0)) + ) + defer { Task { await harness.tearDown() } } + + await harness.session.setSendMessageResult(.failure(MeshCoreError.timeout)) + await harness.queue.hydrate() + try await waitUntil("a timed-out command should park before the resume") { + let row = try? await harness.dataStore.fetchPendingSends(radioID: harness.radioID) + .first { $0.messageID == harness.messageID } + return row?.nextWireAttempt == 1 + } + + let service = harness.messageService + let store = harness.dataStore + let messageID = harness.messageID + await service.setDirectMessageSubmitGateForTesting { attempt in + guard attempt == 1 else { return } + let message = try? await store.fetchMessage(id: messageID) + guard let message else { return } + let code = AckCodeBuilder.expectedAck( + timestamp: message.timestamp, + attempt: 0, + text: message.text, + senderPublicKey: Data(repeating: 0xAB, count: 32) + ) + await service.handleAcknowledgement(code: code, tripTime: 40) + } + await harness.session.setSendMessageResult(.success( + MessageSentInfo(route: 0, expectedAck: Data([0x01, 0x02, 0x03, 0x04]), suggestedTimeoutMs: 10) + )) + harness.queue.observeConnectionState(initial: .ready, events: AsyncStream { $0.finish() }) + try await waitUntil(timeout: .seconds(10), "the resume should record delivery without another command") { + let message = try? await harness.dataStore.fetchMessage(id: harness.messageID) + let parked = await harness.queue.parkedDrainCountForTesting + return message?.status == .delivered && parked == 0 + } + let invocations = await harness.session.sendMessageInvocations + #expect(invocations.map(\.attempt) == [0]) + } + + @Test + func `a missed attempt-byte save does not record delivery`() async throws { + let harness = try await Self.setUpDMHarness( + messageConfig: MessageServiceConfig(minTimeout: 0, poolBackoff: PoolBackoffConfig(attemptCap: 0, baseDelay: 0)) + ) + defer { Task { await harness.tearDown() } } + + await harness.dataStore.setPendingSendWireAttemptSaveFaultInjection { () async throws in + throw ForcedSaveFailure() + } + await harness.session.setSendMessageResult(.success( + MessageSentInfo(route: 0, expectedAck: Data([0x01, 0x02, 0x03, 0x04]), suggestedTimeoutMs: 10) + )) + await harness.queue.hydrate() + try await waitUntil(timeout: .seconds(10), "the accepted command should stay an acknowledgement owner") { + let message = try? await harness.dataStore.fetchMessage(id: harness.messageID) + return message?.status == .sent || message?.status == .delivered + } + let message = try #require(try await harness.dataStore.fetchMessage(id: harness.messageID)) + #expect(message.status == .sent) + let owner = try #require( + try await harness.dataStore.fetchPendingSends(radioID: harness.radioID) + .first { $0.messageID == harness.messageID } + ) + #expect(owner.ackDeadline != nil) + #expect(await harness.session.sendMessageInvocations.map(\.attempt) == [0]) + } + /// A container built after the connection already reached `.ready` receives /// the edge through `observeConnectionState`'s initial value: an already-ready /// initial state must fire the trigger so a drain parked in @@ -583,14 +724,14 @@ struct ChatSendQueueServiceTests { #expect(parkedRow?.attemptCount == 1, ".connected must not wake the drain during the sync window") // Entering `.ready` fires the trigger and the drain wakes for its second attempt. - try await harness.dataStore.updateMessageStatus(id: harness.messageID, status: .failed) continuation.yield(.ready) try await waitUntil(timeout: .seconds(10), "ready should wake the parked send") { let sent = await harness.session.sendMessageInvocations.count let row = try? await harness.dataStore.fetchPendingSends(radioID: harness.radioID) .first(where: { $0.messageID == harness.messageID }) let message = try? await harness.dataStore.fetchMessage(id: harness.messageID) - return sent >= 4 && row?.attemptCount == 2 && message?.status == .pending + let parked = await harness.queue.parkedDrainCountForTesting + return sent >= 4 && row?.attemptCount == 2 && message?.status == .pending && parked > 0 } continuation.yield(.ready) continuation.finish() @@ -600,6 +741,154 @@ struct ChatSendQueueServiceTests { #expect(settledRow?.attemptCount == 2, "duplicate ready states must not fire another trigger") } + @Test + func `a delivery during the timeout consume sends no further command`() async throws { + let harness = try await Self.setUpDMHarness( + messageConfig: MessageServiceConfig(minTimeout: 0, poolBackoff: PoolBackoffConfig(attemptCap: 0, baseDelay: 0)) + ) + defer { Task { await harness.tearDown() } } + + let service = harness.messageService + let store = harness.dataStore + let messageID = harness.messageID + let sender = Data(repeating: 0xAB, count: 32) + await store.setPendingSendWireAttemptSaveFaultInjection { + guard let message = try await store.fetchMessage(id: messageID) else { return } + let code = AckCodeBuilder.expectedAck( + timestamp: message.timestamp, + attempt: 0, + text: message.text, + senderPublicKey: sender + ) + await service.handleAcknowledgement(code: code, tripTime: 40) + } + await harness.session.setSendMessageResult(.failure(MeshCoreError.timeout)) + await harness.queue.hydrate() + try await waitUntil(timeout: .seconds(10), "delivery during the consume should finish the row") { + let message = try? await harness.dataStore.fetchMessage(id: harness.messageID) + let remaining = try? await harness.dataStore.fetchPendingSends(radioID: harness.radioID) + .filter { $0.messageID == harness.messageID } + let parked = await harness.queue.parkedDrainCountForTesting + return message?.status == .delivered && remaining?.isEmpty == true && parked == 0 + } + let deliveredCount = await harness.session.sendMessageInvocations.count + #expect(await harness.session.sendMessageInvocations.map(\.attempt) == [0]) + + await harness.session.setSendMessageResult(.success( + MessageSentInfo(route: 0, expectedAck: Data([0x01, 0x02, 0x03, 0x04]), suggestedTimeoutMs: 10) + )) + harness.queue.observeConnectionState(initial: .ready, events: AsyncStream { $0.finish() }) + try await waitUntil(timeout: .seconds(10), "a second drain should find nothing to send") { + await harness.queue.parkedDrainCountForTesting == 0 + } + #expect(await harness.session.sendMessageInvocations.count == deliveredCount) + } + + @Test + func `a not submitted resend stays delivered and retries when the transport opens`() async throws { + let harness = try await Self.setUpDMHarness( + messageConfig: MessageServiceConfig(minTimeout: 0, poolBackoff: PoolBackoffConfig(attemptCap: 0, baseDelay: 0)) + ) + defer { Task { await harness.tearDown() } } + let original: UInt32 = 1_700_000_000 + try await prepareDeliveredResend(harness, timestamp: original) + let statusEvents = harness.messageService.statusEvents() + await harness.session.setSendMessageResult(.failure(MeshCoreError.notConnected)) + await harness.queue.hydrate() + try await waitUntil("a not submitted resend should park still delivered") { + let message = try? await harness.dataStore.fetchMessage(id: harness.messageID) + let row = try? await harness.dataStore.fetchPendingSends(radioID: harness.radioID) + .first { $0.messageID == harness.messageID } + let parked = await harness.queue.parkedDrainCountForTesting + return message?.status == .delivered + && message?.timestamp == original + && row?.attemptCount == PersistenceStore.initialAttemptCount + && row?.nextWireAttempt == 0 + && parked > 0 + } + let parkedCommands = await harness.session.sendMessageInvocations + #expect(parkedCommands.map(\.attempt) == [0]) + #expect(await harness.messageService.drainStatusEvents(statusEvents).failedIDs.isEmpty) + + await harness.session.setSendMessageResult(.success( + MessageSentInfo(route: 0, expectedAck: Data([0x01, 0x02, 0x03, 0x04]), suggestedTimeoutMs: 10) + )) + harness.queue.observeConnectionState(initial: .ready, events: AsyncStream { $0.finish() }) + try await waitUntil(timeout: .seconds(10), "the parked resend should submit attempt zero again") { + await harness.session.sendMessageInvocations.count > parkedCommands.count + } + let retried = await harness.session.sendMessageInvocations.dropFirst(parkedCommands.count) + #expect(retried.first?.attempt == 0) + let stamped = try UInt32(#require(retried.first).timestamp.timeIntervalSince1970) + #expect(stamped != original) + #expect(try await harness.dataStore.hasPendingSend(messageID: harness.messageID)) + } + + @Test + func `a new packet commits its timestamp with the command`() async throws { + let harness = try await Self.setUpDMHarness() + defer { Task { await harness.tearDown() } } + let original: UInt32 = 1_700_000_000 + try await prepareDeliveredResend(harness, timestamp: original) + await harness.session.setSendMessageResult(.success( + MessageSentInfo(route: 0, expectedAck: Data([0x01, 0x02, 0x03, 0x04]), suggestedTimeoutMs: 10) + )) + _ = try await sendQueued(harness, preserveTimestamp: false) + let command = try #require(await harness.session.sendMessageInvocations.first) + let stamped = UInt32(command.timestamp.timeIntervalSince1970) + let stored = try #require(try await harness.dataStore.fetchMessage(id: harness.messageID)) + #expect(stamped != original) + #expect(stored.timestamp == stamped) + #expect(stored.status != .delivered) + } + + @Test + func `a new packet keeps the old timestamp when the command is not submitted`() async throws { + let harness = try await Self.setUpDMHarness() + defer { Task { await harness.tearDown() } } + let original: UInt32 = 1_700_000_000 + try await prepareDeliveredResend(harness, timestamp: original) + await harness.session.setCurrentSelfInfo(nil) + await #expect(throws: CancellationError.self) { + try await sendQueued(harness, preserveTimestamp: false) + } + #expect(await harness.session.sendMessageInvocations.isEmpty) + let stored = try #require(try await harness.dataStore.fetchMessage(id: harness.messageID)) + #expect(stored.timestamp == original) + #expect(stored.status == .delivered) + } + + @Test + func `a timed out new packet keeps its timestamp for the next byte`() async throws { + let harness = try await Self.setUpDMHarness( + messageConfig: MessageServiceConfig(minTimeout: 0, poolBackoff: PoolBackoffConfig(attemptCap: 0, baseDelay: 0)) + ) + defer { Task { await harness.tearDown() } } + let original: UInt32 = 1_700_000_000 + try await prepareDeliveredResend(harness, timestamp: original) + await harness.session.setSendMessageResult(.failure(MeshCoreError.timeout)) + await #expect(throws: MessageServiceError.self) { + try await sendQueued(harness, preserveTimestamp: false) + } + let first = await harness.session.sendMessageInvocations + #expect(first.map(\.attempt) == [0]) + let stamped = try UInt32(#require(first.first).timestamp.timeIntervalSince1970) + #expect(stamped != original) + let stored = try #require(try await harness.dataStore.fetchMessage(id: harness.messageID)) + #expect(stored.timestamp == stamped) + let pendingID = try await queuedPendingID(harness) + #expect(try await harness.dataStore.pendingSendWireAttempt(id: pendingID) == 1) + + await harness.session.setSendMessageResult(.success( + MessageSentInfo(route: 0, expectedAck: Data([0x01, 0x02, 0x03, 0x04]), suggestedTimeoutMs: 10) + )) + _ = try await sendQueued(harness, preserveTimestamp: true) + let next = try #require(await harness.session.sendMessageInvocations.dropFirst(first.count).first) + #expect(next.attempt == 1) + #expect(UInt32(next.timestamp.timeIntervalSince1970) == stamped) + #expect(try await harness.dataStore.fetchMessage(id: harness.messageID)?.timestamp == stamped) + } + // MARK: - DM drain helpers private struct DMHarness { @@ -611,15 +900,14 @@ struct ChatSendQueueServiceTests { let messageID: UUID func drainUntilParked() async throws { - // A transition from failed to pending witnesses the completed error handling. - try await dataStore.updateMessageStatus(id: messageID, status: .failed) await queue.hydrate() - try await waitUntil("DM send should fail and return to pending") { + try await waitUntil("DM pool exhaustion should park the pending send") { let sent = await session.sendMessageInvocations.count let row = try? await dataStore.fetchPendingSends(radioID: radioID) .first(where: { $0.messageID == messageID }) let message = try? await dataStore.fetchMessage(id: messageID) - return sent >= 2 && (row?.attemptCount ?? 0) >= 1 && message?.status == .pending + let parked = await queue.parkedDrainCountForTesting + return sent >= 2 && (row?.attemptCount ?? 0) >= 1 && message?.status == .pending && parked > 0 } } @@ -628,6 +916,36 @@ struct ChatSendQueueServiceTests { } } + private func prepareDeliveredResend(_ harness: DMHarness, timestamp: UInt32) async throws { + try await harness.dataStore.updateMessageTimestamp(id: harness.messageID, timestamp: timestamp) + try await harness.dataStore.updateMessageStatus(id: harness.messageID, status: .delivered) + } + + private func queuedPendingID(_ harness: DMHarness) async throws -> UUID { + try #require( + try await harness.dataStore.fetchPendingSends(radioID: harness.radioID) + .first { $0.messageID == harness.messageID }?.id + ) + } + + private func sendQueued(_ harness: DMHarness, preserveTimestamp: Bool) async throws -> MessageDTO { + let contact = try #require( + try await harness.dataStore.fetchContact( + radioID: harness.radioID, + publicKey: Data(repeating: 0x33, count: 32) + ) + ) + return try await harness.messageService.performQueuedDirectMessageSend( + messageID: harness.messageID, + to: contact, + preserveTimestamp: preserveTimestamp, + isResend: true, + isSingleAttempt: false, + pendingSendID: queuedPendingID(harness), + sendLease: nil + ) + } + private static func setUpDMHarness( queueConfig: ChatSendQueueConfig = .default, messageConfig: MessageServiceConfig = .default @@ -682,3 +1000,5 @@ struct ChatSendQueueServiceTests { ) } } + +private struct ForcedSaveFailure: Error {} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ContactServiceSyncTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ContactServiceSyncTests.swift index 253b751120..ffb55fea53 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/ContactServiceSyncTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/ContactServiceSyncTests.swift @@ -200,7 +200,7 @@ struct ContactServiceSyncTests { cleanupCoordinator: nil ) - let gated = GatedSyncContactService() + let gated = GatedContactService() let advertTask = Task { await coordinator.performAdvertContactSync( fullRefetch: false, @@ -252,7 +252,7 @@ struct ContactServiceSyncTests { cleanupCoordinator: nil ) - let gated = GatedSyncContactService() + let gated = GatedContactService() let firstAdvert = Task { await coordinator.performAdvertContactSync( fullRefetch: false, @@ -309,7 +309,7 @@ struct ContactServiceSyncTests { cleanupCoordinator: nil ) - let gated = GatedSyncContactService() + let gated = GatedContactService() let advertTask = Task { await coordinator.performAdvertContactSync( fullRefetch: false, @@ -456,34 +456,3 @@ struct ContactServiceSyncTests { #expect(try await store.fetchContact(radioID: radioID, publicKey: listedKey)?.name == "Listed") } } - -/// Contact service stub that parks inside `syncContacts` until released, so a test can -/// hold an advert-driven delta sync open. -private actor GatedSyncContactService: ContactServiceProtocol { - private var hasStarted = false - private var startWaiters: [CheckedContinuation] = [] - private var gate: CheckedContinuation? - private var isReleased = false - - func waitForSyncStart() async { - if hasStarted { return } - await withCheckedContinuation { startWaiters.append($0) } - } - - func release() { - isReleased = true - gate?.resume() - gate = nil - } - - func syncContacts(radioID _: UUID, since _: Date?) async throws -> ContactSyncResult { - hasStarted = true - while !startWaiters.isEmpty { - startWaiters.removeFirst().resume() - } - if !isReleased { - await withCheckedContinuation { gate = $0 } - } - return ContactSyncResult(contactsReceived: 0, lastSyncTimestamp: 0, isIncremental: true) - } -} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/DMSendBudgetTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/DMSendBudgetTests.swift new file mode 100644 index 0000000000..8da9363d60 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/DMSendBudgetTests.swift @@ -0,0 +1,71 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("DMSendBudget reader") +struct DMSendBudgetTests { + @Test + func `missing preferences use four initial and four fallback attempts`() { + let (defaults, suiteName) = makeDefaults() + defer { defaults.removePersistentDomain(forName: suiteName) } + let budget = DMSendBudget.current(defaults: defaults) + #expect(budget.directAttempts == 4) + #expect(budget.floodAttempts == 4) + #expect(budget.totalAttempts == 8) + } + + @Test + func `stored flood 0 stays 0`() { + let (defaults, suiteName) = makeDefaults() + defer { defaults.removePersistentDomain(forName: suiteName) } + defaults.set(0, forKey: AppStorageKey.dmFloodAttempts.rawValue) + let budget = DMSendBudget.current(defaults: defaults) + #expect(budget.directAttempts == 4) + #expect(budget.floodAttempts == 0) + #expect(budget.totalAttempts == 4) + } + + @Test + func `out of range values clamp to the picker ranges`() { + let (defaults, suiteName) = makeDefaults() + defer { defaults.removePersistentDomain(forName: suiteName) } + defaults.set(0, forKey: AppStorageKey.dmDirectAttempts.rawValue) + defaults.set(9, forKey: AppStorageKey.dmFloodAttempts.rawValue) + let highFlood = DMSendBudget.current(defaults: defaults) + #expect(highFlood.directAttempts == 1) + #expect(highFlood.floodAttempts == 4) + #expect(highFlood.totalAttempts == 5) + + defaults.set(8, forKey: AppStorageKey.dmDirectAttempts.rawValue) + defaults.set(-1, forKey: AppStorageKey.dmFloodAttempts.rawValue) + let lowFlood = DMSendBudget.current(defaults: defaults) + #expect(lowFlood.directAttempts == 4) + #expect(lowFlood.floodAttempts == 0) + #expect(lowFlood.totalAttempts == 4) + } + + @Test + func `turning fallback off stores zero and on restores the default only from zero`() { + #expect(DMSendBudget.floodAttempts(enablingFallback: false, stored: 3) == 0) + #expect(DMSendBudget.floodAttempts(enablingFallback: true, stored: 0) == 4) + #expect(DMSendBudget.floodAttempts(enablingFallback: true, stored: 2) == 2) + #expect(DMSendBudget.floodAttempts(enablingFallback: true, stored: 9) == 9) + } + + @Test + func `the flood menu shows a count from 1 to 4 and clamps a write`() { + #expect(DMSendBudget.menuFloodAttempts(stored: 3) == 3) + #expect(DMSendBudget.menuFloodAttempts(stored: 0) == 4) + #expect(DMSendBudget.menuFloodAttempts(stored: 9) == 4) + #expect(DMSendBudget.clampedMenuFloodAttempts(0) == 1) + #expect(DMSendBudget.clampedMenuFloodAttempts(2) == 2) + #expect(DMSendBudget.clampedMenuFloodAttempts(9) == 4) + } + + private func makeDefaults() -> (UserDefaults, String) { + let name = "test.dm-budget.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: name)! + defaults.removePersistentDomain(forName: name) + return (defaults, name) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/DebugLogBufferTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/DebugLogBufferTests.swift index df80333c0d..6c120f9b52 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/DebugLogBufferTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/DebugLogBufferTests.swift @@ -2,28 +2,38 @@ import Foundation @testable import MC1Services import Testing -/// Serialized because both tests reassign the process-global DebugLogBuffer.shared, -/// so running them in parallel breaks each other's assertions on that global. -/// `ServiceContainer.init` also reassigns this same global, and other test suites -/// that build a `ServiceContainer` run concurrently with this suite, so a read -/// right after a write can observe a foreign buffer written in between. Assertions -/// below read back through a bounded retry to absorb that interleaving. +/// Serialized because each test reassigns `DebugLogBuffer.shared`, which `ServiceContainer.init` also reassigns. +/// A read right after a write can see another suite's buffer, so assertions retry. @Suite("DebugLogBuffer Tests", .serialized) struct DebugLogBufferTests { private static let maxReadBackAttempts = 5 /// `pruneIfDue` stamps cutoff with `Date()` at call time; the test reads it a tick later. private static let pruneCutoffSlack: TimeInterval = 2 + /// On-path tests pin `collectDebugLogs` true. `record` drops entries when the key is missing. + private static let collectionKey = AppStorageKey.collectDebugLogs.rawValue + + private func enableCollectionForTesting() -> Any? { + let captured = UserDefaults.standard.object(forKey: Self.collectionKey) + UserDefaults.standard.set(true, forKey: Self.collectionKey) + return captured + } + + private func restoreCollection(_ captured: Any?) { + if let captured { + UserDefaults.standard.set(captured, forKey: Self.collectionKey) + } else { + UserDefaults.standard.removeObject(forKey: Self.collectionKey) + } + } + private func makeBuffer() async throws -> DebugLogBuffer { let container = try PersistenceStore.createContainer(inMemory: true) let store = PersistenceStore(modelContainer: container) return DebugLogBuffer(dataStore: store) } - /// Writes `buffer` to the global and reads it back, retrying because a - /// concurrently running suite may reassign the global between the write and - /// the read. Succeeds as soon as one attempt reads back the value just - /// written; only fails if every attempt observes a foreign buffer instead. + /// Assigns `buffer` to `DebugLogBuffer.shared` and reads it back. Retries because another suite can reassign the global in between. private func writeAndReadBack(_ buffer: DebugLogBuffer, attempts: Int = maxReadBackAttempts) -> Bool { for _ in 0.. Bool { + for _ in 0..= 1 + } + } catch { + await store.releaseHeldSaves(.succeed) + _ = await flushTask.value + throw error + } + guard DebugLogBuffer.shared === buffer else { + await store.releaseHeldSaves(.succeed) + _ = await flushTask.value + continue + } + + let finished = OSAllocatedUnfairLock(initialState: false) + let disableTask = Task { + try await DebugLogBuffer.disableCollection(persistenceStore: store) + finished.withLock { $0 = true } + } + + do { + try await waitUntil("disable should take the key false while the save is held") { + let keyIsOff = UserDefaults.standard.bool(forKey: Self.key) == false + let saveIsHeld = await store.heldSaveCount >= 1 + return keyIsOff && saveIsHeld + } + } catch { + await store.releaseHeldSaves(.succeed) + _ = try? await disableTask.value + _ = await flushTask.value + throw error + } + + try await Task.sleep(for: .milliseconds(50)) + guard DebugLogBuffer.shared === buffer else { + await store.releaseHeldSaves(.succeed) + _ = try? await disableTask.value + _ = await flushTask.value + continue + } + + let returnedWhileHeld = finished.withLock { $0 } + let stillHeld = await store.heldSaveCount >= 1 + let clearedWhileHeld = await store.clearCount > 0 + + let release: HoldingDebugLogStore.Release = releaseSucceeds ? .succeed : .fail + await store.releaseHeldSaves(release) + try await disableTask.value + _ = await flushTask.value + + #expect(returnedWhileHeld == false) + #expect(stillHeld) + #expect(clearedWhileHeld == false) + #expect(UserDefaults.standard.bool(forKey: Self.key) == false) + #expect(try await store.countDebugLogEntries() == 0) + + await buffer.flush() + await buffer.shutdown() + #expect(try await store.countDebugLogEntries() == 0) + return + } + + Issue.record("shared buffer was replaced before disable could wait out the save") + } + + /// Parks `saveDebugLogEntries` on an await, so `clearDebugLogEntries` can reenter while a save is held. + private actor HoldingDebugLogStore: DebugLogPersisting { + enum Release: Sendable { + case succeed + case fail + } + + struct SaveFailure: Error {} + + private var entries: [DebugLogEntryDTO] = [] + private var saveWaiters: [CheckedContinuation] = [] + private(set) var clearCount = 0 + + var heldSaveCount: Int { + saveWaiters.count + } + + func seed(_ entry: DebugLogEntryDTO) { + entries.append(entry) + } + + func saveDebugLogEntries(_ dtos: [DebugLogEntryDTO]) async throws { + let release = await withCheckedContinuation { continuation in + saveWaiters.append(continuation) + } + switch release { + case .succeed: + entries.append(contentsOf: dtos) + case .fail: + throw SaveFailure() + } + } + + func releaseHeldSaves(_ release: Release) { + let waiters = saveWaiters + saveWaiters.removeAll() + for waiter in waiters { + waiter.resume(returning: release) + } + } + + func fetchDebugLogEntries(since date: Date, limit: Int) async throws -> [DebugLogEntryDTO] { + [] + } + + func countDebugLogEntries() async throws -> Int { + entries.count + } + + func pruneDebugLogEntries(olderThan cutoff: Date, keepCount: Int) async throws {} + + func clearDebugLogEntries() async throws { + clearCount += 1 + entries.removeAll() + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/HeardRepeatSnapshotWriteTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/HeardRepeatSnapshotWriteTests.swift index 9383a34144..a6b7d1c6ed 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/HeardRepeatSnapshotWriteTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/HeardRepeatSnapshotWriteTests.swift @@ -167,6 +167,7 @@ struct HeardRepeatSnapshotWriteTests { let secondRX = UUID() let first = try await store.admitSentEcho( messageID: message.id, + expectedTimestamp: message.timestamp, receivedAt: Date(timeIntervalSince1970: 1_700_000_040), pathNodes: Data([0x11]), pathLength: 1, @@ -176,6 +177,7 @@ struct HeardRepeatSnapshotWriteTests { ) let second = try await store.admitSentEcho( messageID: message.id, + expectedTimestamp: message.timestamp, receivedAt: Date(timeIntervalSince1970: 1_700_000_041), pathNodes: Data([0x11]), pathLength: 1, @@ -185,6 +187,7 @@ struct HeardRepeatSnapshotWriteTests { ) let sameRX = try await store.admitSentEcho( messageID: message.id, + expectedTimestamp: message.timestamp, receivedAt: Date(timeIntervalSince1970: 1_700_000_042), pathNodes: Data([0x22]), pathLength: 1, diff --git a/MC1Services/Tests/MC1ServicesTests/Services/MessagePollingServiceTextTypeTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessagePollingServiceTextTypeTests.swift index a9247e6eff..47a44cbe65 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/MessagePollingServiceTextTypeTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessagePollingServiceTextTypeTests.swift @@ -37,7 +37,7 @@ struct MessagePollingServiceTextTypeTests { let polling = MessagePollingService(session: session, dataStore: store) let hits = HandlerHits() - await polling.setContactMessageHandler { _, _, _ in + await polling.setContactMessageHandler { _, _, _, _, _ in await hits.recordContact() } await polling.setCLIMessageHandler { _, _ in diff --git a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKFinalizationTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKFinalizationTests.swift new file mode 100644 index 0000000000..fdd2008969 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKFinalizationTests.swift @@ -0,0 +1,191 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("MessageService ACK finalization") +@MainActor +struct MessageServiceACKFinalizationTests { + private let senderKey = Data(repeating: 0xAB, count: 32) + + @Test + func `an owner installed during ownerless delivery is deleted before settlement finishes`() async throws { + let fixture = try await makeFixture() + let command = FirstWriteGate() + let delivery = FirstWriteGate() + defer { command.release(); delivery.release() } + await fixture.session.setSendMessageObserver { await command.park() } + await fixture.store.setUpdateMessageAckObserver { status in + if status == .delivered { await delivery.park() } + } + let events = fixture.service.statusEvents() + let send = Task { + try await fixture.service.sendDirectMessage(text: "early ACK", to: fixture.contact) + } + try await waitUntil("the inline command is held") { command.isParked } + let invocation = try #require(await fixture.session.sendMessageInvocations.first) + let code = AckCodeBuilder.expectedAck( + timestamp: UInt32(invocation.timestamp.timeIntervalSince1970), attempt: invocation.attempt, + text: invocation.text, senderPublicKey: senderKey + ) + let acknowledgement = Task { + await fixture.service.handleAcknowledgement(code: code, tripTime: 77) + } + try await waitUntil("ownerless terminal persistence is held") { delivery.isParked } + + command.release() + let accepted = try await send.value + #expect(accepted.status == .sent) + let owner = try #require(await fixture.store.fetchPendingSends(radioID: fixture.contact.radioID).first) + #expect(owner.messageID == accepted.id) + #expect(owner.ackDeadline != nil) + let nextSend = Task { try await fixture.gate.acquire() } + defer { nextSend.cancel() } + try await waitUntil("admission waits for terminal persistence") { + await fixture.gate.waiterCountForTesting == 1 + } + + delivery.release() + await acknowledgement.value + let admitted = try await nextSend.value + await fixture.gate.stopIssuing(admitted) + let delivered = try #require(await fixture.store.fetchMessage(id: accepted.id)) + #expect(delivered.status == .delivered) + #expect(delivered.roundTripTime == 77) + #expect(try await fixture.store.fetchPendingSends(radioID: fixture.contact.radioID).isEmpty) + #expect(await fixture.service.pendingAckCount == 0) + #expect(await fixture.session.sendMessageInvocations.count == 1) + let recorded = await fixture.service.drainStatusEvents(events) + #expect(recorded.failedIDs.isEmpty) + let deliveries = recorded.compactMap { event -> UUID? in + guard case let .statusResolved(messageID, .delivered, roundTripTime) = event else { return nil } + #expect(roundTripTime == 77) + return messageID + } + #expect(deliveries == [accepted.id]) + } + + @Test + func `waiter-first delivery retains ownership through a failed save and retry`() async throws { + let fixture = try await makeFixture() + await fixture.session.setWaitForEventResult(.acknowledgement(code: fixture.code, tripTime: nil)) + let terminal = FirstWriteGate() + defer { terminal.release() } + await fixture.store.setResolvePendingAcknowledgementObserver { await terminal.park() } + await fixture.store.setStubbedResolvePendingAcknowledgementError(InjectedError.save) + let events = fixture.service.statusEvents() + var sendFinished = false + let send = Task { + defer { sendFinished = true } + return try await fixture.service.sendMessageWithRetry(text: "waiter ACK", to: fixture.contact) + } + try await waitUntil("the waiter reaches terminal persistence") { terminal.isParked || sendFinished } + try #require(terminal.isParked, "The waiter must use the common durable settlement path") + let message = try #require( + await fixture.store.fetchMessages(contactID: fixture.contact.id, limit: 1, offset: 0).first + ) + let owner = try #require(await fixture.store.fetchPendingSends(radioID: fixture.contact.radioID).first) + let nextSend = Task { try await fixture.gate.acquire() } + defer { nextSend.cancel() } + try await waitUntil("a competing send waits for the waiter settlement") { + await fixture.gate.waiterCountForTesting == 1 + } + await fixture.service.handleAcknowledgement(code: fixture.code, tripTime: 999) + try await fixture.service.checkExpiredAcks() + #expect(await fixture.store.resolvePendingAcknowledgementCallCount == 1) + #expect(await fixture.gate.waiterCountForTesting == 1) + + terminal.release() + let result = try await send.value + #expect(result.status == .sent) + #expect(try await fixture.store.fetchPendingSends(radioID: fixture.contact.radioID) == [owner]) + #expect(await fixture.service.pendingAckCount == 1) + #expect(await fixture.gate.waiterCountForTesting == 1) + await fixture.store.setStubbedResolvePendingAcknowledgementError(nil) + let deadline = try #require(owner.ackDeadline) + try await waitUntil("the original ACK deadline has elapsed") { Date() > deadline } + try await fixture.service.checkExpiredAcks() + let admitted = try await nextSend.value + await fixture.gate.stopIssuing(admitted) + let delivered = try #require(await fixture.store.fetchMessage(id: message.id)) + #expect(delivered.status == .delivered) + #expect(delivered.roundTripTime == nil) + #expect(try await fixture.store.fetchPendingSends(radioID: fixture.contact.radioID).isEmpty) + #expect(await fixture.service.pendingAckCount == 0) + #expect(await fixture.session.sendMessageInvocations.count == 1) + #expect(await fixture.store.resolvePendingAcknowledgementCallCount == 2) + let recorded = await fixture.service.drainStatusEvents(events) + #expect(recorded.failedIDs.isEmpty) + let deliveries = recorded.compactMap { event -> UUID? in + guard case let .statusResolved(messageID, .delivered, roundTripTime) = event else { return nil } + #expect(roundTripTime == delivered.roundTripTime) + return messageID + } + #expect(deliveries == [message.id]) + } + + private struct Fixture { + let store: MockPersistenceStore + let session: MockMeshCoreSession + let service: MessageService + let gate: PlainTextSendGate + let contact: ContactDTO + let code: Data + } + + private func makeFixture() async throws -> Fixture { + let store = MockPersistenceStore() + let session = MockMeshCoreSession() + let gate = PlainTextSendGate() + let code = Data([0x11, 0x22, 0x33, 0x44]) + await session.setCurrentSelfInfo(.testSelfInfo(publicKey: senderKey)) + await session.setSendMessageResult(.success(MessageSentInfo( + route: 0, expectedAck: code, suggestedTimeoutMs: 0 + ))) + let service = MessageService( + session: session, dataStore: store, contactService: nil, + config: MessageServiceConfig(minTimeout: 0, ackGiveUpWindow: 0), plainTextSendGate: gate + ) + let contact = ContactDTO.testContact() + try await store.saveContact(contact) + return Fixture(store: store, session: session, service: service, gate: gate, contact: contact, code: code) + } + + private enum InjectedError: Error { + case save + } + + private final class FirstWriteGate: @unchecked Sendable { + private let lock = NSLock() + private var continuation: CheckedContinuation? + private var didEnter = false + + var isParked: Bool { + lock.lock() + defer { lock.unlock() } + return continuation != nil + } + + func park() async { + await withCheckedContinuation { (continuation: CheckedContinuation) in + lock.lock() + if didEnter { + lock.unlock() + continuation.resume() + return + } + didEnter = true + self.continuation = continuation + lock.unlock() + } + } + + func release() { + lock.lock() + let continuation = continuation + self.continuation = nil + lock.unlock() + continuation?.resume() + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKRecoveryTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKRecoveryTests.swift new file mode 100644 index 0000000000..8aae69fb11 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKRecoveryTests.swift @@ -0,0 +1,397 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import SwiftData +import Testing + +@Suite("MessageService ACK recovery", .serialized) +@MainActor +struct MessageServiceACKRecoveryTests { + private nonisolated static let senderKey = Data(repeating: 0x41, count: 32) + + @Test(arguments: [false, true]) + func `exhausted send survives a cold store and accepts an earlier attempt ACK without replay`( + firmwareCode: Bool + ) async throws { + let previousLogBuffer = DebugLogBuffer.shared + defer { DebugLogBuffer.shared = previousLogBuffer } + let storeURL = FileManager.default.temporaryDirectory + .appendingPathComponent("ack-recovery-\(UUID().uuidString).store") + defer { removeStoreFiles(at: storeURL) } + let originalStore = try makeDiskStore(at: storeURL) + let radioID = UUID() + try await originalStore.saveDevice(.testDevice(radioID: radioID, publicKey: Self.senderKey)) + let contact = ContactDTO.testContact(radioID: radioID, publicKey: Data(repeating: 0x42, count: 32)) + try await originalStore.saveContact(contact) + let original = try await Connection.open(store: originalStore, radioID: radioID) + let message = try await original.services.messageService.createPendingMessage(text: "ACK recovery", to: contact) + try await original.services.chatSendQueueService.enqueueDM( + DirectMessageEnvelope(messageID: message.id, contactID: contact.id) + ) + await original.services.chatSendQueueService.awaitDrainCompletion() + let exhausted = try #require(await originalStore.fetchMessage(id: message.id)) + #expect(exhausted.status == .sent) + #expect(await original.radio.sendCount == 8) + #expect(await original.services.messageService.pendingAckCount == 1) + #expect(try await originalStore.fetchPendingSends(radioID: radioID).count == 1, + "Accepted sends need a durable ACK owner after the send queue finishes") + let owner = try #require(await originalStore.fetchPendingSends(radioID: radioID).first) + #expect(owner.ackSentAt != nil) + #expect(owner.ackDeadline != nil) + #expect(owner.attemptCount == 1) + let code = try #require(await original.radio.firstCode(firmware: firmwareCode)) + #expect(owner.ackCodes?.contains(code) == true) + await original.close() + + let restoredStore = try makeDiskStore(at: storeURL) + let persisted = try #require(await restoredStore.fetchPendingSends(radioID: radioID).first) + #expect(persisted.ackCodes == owner.ackCodes) + #expect(persisted.ackSentAt == owner.ackSentAt) + #expect(persisted.ackDeadline == owner.ackDeadline) + let restored = try await Connection.open(store: restoredStore, radioID: radioID) + await restored.services.chatSendQueueService.awaitDrainCompletion() + #expect(await restored.radio.sendCount == 0, "ACK recovery must not retransmit the message") + await restored.services.messageService.handleAcknowledgement(code: code, tripTime: 123) + let delivered = try #require(await restoredStore.fetchMessage(id: message.id)) + #expect(delivered.status == .delivered) + #expect(delivered.roundTripTime == 123) + #expect(try await restoredStore.fetchPendingSends(radioID: radioID).isEmpty) + await restored.close() + } + + @Test + func `hydrated DM waits for every live restored ACK owner`() async throws { + let previousLogBuffer = DebugLogBuffer.shared + defer { DebugLogBuffer.shared = previousLogBuffer } + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radioID = UUID() + try await store.saveDevice(.testDevice(radioID: radioID, publicKey: Self.senderKey)) + let contact = ContactDTO.testContact(radioID: radioID) + try await store.saveContact(contact) + let sentAt = Date() + let deadline = sentAt.addingTimeInterval(60) + let codes = [Data([1, 2, 3, 4]), Data([5, 6, 7, 8])] + var restoredMessageIDs: [UUID] = [] + for code in codes { + let message = MessageDTO.testDirectMessage(radioID: radioID, contactID: contact.id, status: .pending) + try await store.saveMessage(message) + let owner = PendingSendDTO( + envelope: DirectMessageEnvelope(messageID: message.id, contactID: contact.id), + radioID: radioID, ackCodes: [code], ackSentAt: sentAt, ackDeadline: deadline + ) + try #require(await store.savePendingAcknowledgement(owner, replacingPendingSendID: nil)) + restoredMessageIDs.append(message.id) + } + let queued = MessageDTO.testDirectMessage(radioID: radioID, contactID: contact.id, status: .pending) + try await store.saveMessage(queued) + let row = PendingSendDTO( + envelope: DirectMessageEnvelope(messageID: queued.id, contactID: contact.id), radioID: radioID + ) + _ = try await store.insertPendingSendAssigningSequence(row) + + let successor = try await Connection.open(store: store, radioID: radioID) + defer { Task { await successor.close() } } + try await waitUntil("the hydrated message reaches admission or is sent") { + if await successor.services.plainTextSendGate.waiterCountForTesting == 1 { return true } + return await successor.radio.sendCount > 0 + } + #expect(await successor.radio.sendCount == 0) + await successor.services.messageService.handleAcknowledgement(code: codes[0], tripTime: 100) + #expect(try await store.fetchMessage(id: restoredMessageIDs[0])?.status == .delivered) + #expect(await successor.services.plainTextSendGate.waiterCountForTesting == 1) + #expect(await successor.radio.sendCount == 0) + + await successor.services.messageService.handleAcknowledgement(code: codes[1], tripTime: 100) + #expect(try await store.fetchMessage(id: restoredMessageIDs[1])?.status == .delivered) + try await waitUntil("the queued message sends after both ACKs") { await successor.radio.sendCount > 0 } + await successor.services.chatSendQueueService.awaitDrainCompletion() + #expect(await successor.radio.sendCount == 8) + } + + @Test(arguments: [false, true]) + func `held inline owner save blocks teardown and the successor delivers it without another send`(beforeOwnerSave: Bool) async throws { + let previousLogBuffer = DebugLogBuffer.shared + defer { DebugLogBuffer.shared = previousLogBuffer } + let held = try await holdInlineSave(text: "Held reply", beforeOwnerSave: beforeOwnerSave) + let code = try #require(await held.original.radio.firstCode(firmware: true)) + #expect(await held.successor.services.messageService.pendingAckCount == 1) + await held.successor.services.chatSendQueueService.awaitDrainCompletion() + #expect(await held.successor.radio.sendCount == 0) + await held.successor.services.messageService.handleAcknowledgement(code: code, tripTime: 321) + #expect(try await held.store.fetchMessage(id: held.messageID)?.status == .delivered) + #expect(try await held.store.fetchMessage(id: held.messageID)?.roundTripTime == 321) + #expect(try await held.store.fetchPendingSends(radioID: held.radioID).isEmpty) + await held.successor.close() + } + + @Test(arguments: [false, true]) + func `held inline owner save still expires on the successor without another send`(beforeOwnerSave: Bool) async throws { + let previousLogBuffer = DebugLogBuffer.shared + defer { DebugLogBuffer.shared = previousLogBuffer } + let held = try await holdInlineSave( + text: "Held expiry", beforeOwnerSave: beforeOwnerSave, messageConfig: MessageServiceConfig(ackGiveUpWindow: 0) + ) + let row = try #require(await held.store.fetchPendingSends(radioID: held.radioID).first) + let deadline = try #require(row.ackDeadline) + try await waitUntil("stored ACK deadline is in the past") { Date() > deadline } + #expect(await held.successor.services.messageService.pendingAckCount == 1) + await held.successor.services.chatSendQueueService.awaitDrainCompletion() + #expect(await held.successor.radio.sendCount == 0) + try await held.successor.services.messageService.checkExpiredAcks() + #expect(try await held.store.fetchMessage(id: held.messageID)?.status == .failed) + #expect(try await held.store.fetchPendingSends(radioID: held.radioID).isEmpty) + #expect(await held.successor.services.messageService.pendingAckCount == 0) + await held.successor.close() + } + + @Test + func `held queued exhaustion save leaves the converted owner for the successor`() async throws { + let previousLogBuffer = DebugLogBuffer.shared + defer { DebugLogBuffer.shared = previousLogBuffer } + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radioID = UUID() + try await store.saveDevice(.testDevice(radioID: radioID, publicKey: Self.senderKey)) + let contact = ContactDTO.testContact(radioID: radioID, publicKey: Data(repeating: 0x42, count: 32)) + try await store.saveContact(contact) + let original = try await Connection.open(store: store, radioID: radioID) + await original.services.messageService.stopAckExpiryChecking() + let message = try await original.services.messageService.createPendingMessage(text: "Held queue", to: contact) + let gate = SuspendGate() + await original.services.messageService.setAcknowledgementSaveGateForTesting { + await gate.park() + } + try await original.services.chatSendQueueService.enqueueDM( + DirectMessageEnvelope(messageID: message.id, contactID: contact.id) + ) + try await waitUntil("queued owner save is held") { gate.isParked } + #expect(await original.radio.sendCount == 8) + let successor = try await successorAfterHeldSave( + original: original, store: store, radioID: radioID, gate: gate + ) + await successor.services.messageService.stopAckExpiryChecking() + let row = try #require(await store.fetchPendingSends(radioID: radioID).first) + #expect(row.messageID == message.id) + #expect(row.ackDeadline != nil) + #expect(row.ackSentAt != nil) + #expect(row.attemptCount == 1) + #expect(await successor.services.messageService.pendingAckForTest(message.id)?.owner?.id == row.id) + await successor.services.chatSendQueueService.awaitDrainCompletion() + #expect(await successor.radio.sendCount == 0) + await successor.close() + } + + private func makeDiskStore(at url: URL) throws -> PersistenceStore { + let configuration = ModelConfiguration(schema: PersistenceStore.schema, url: url) + return try PersistenceStore(modelContainer: ModelContainer( + for: PersistenceStore.schema, configurations: [configuration] + )) + } + + private func removeStoreFiles(at url: URL) { + for suffix in ["", "-shm", "-wal"] { + try? FileManager.default.removeItem(atPath: url.path + suffix) + } + } + + private struct HeldInlineSave { + let store: PersistenceStore + let radioID: UUID + let original: Connection + let successor: Connection + let messageID: UUID + } + + private func holdInlineSave( + text: String, beforeOwnerSave: Bool, messageConfig: MessageServiceConfig = .default + ) async throws -> HeldInlineSave { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radioID = UUID() + try await store.saveDevice(.testDevice(radioID: radioID, publicKey: Self.senderKey)) + let contact = ContactDTO.testContact(radioID: radioID) + try await store.saveContact(contact) + let original = try await Connection.open(store: store, radioID: radioID, messageConfig: messageConfig) + await original.services.messageService.stopAckExpiryChecking() + let gate = SuspendGate() + if beforeOwnerSave { + await original.services.messageService.setInlineSendAcceptedGateForTesting { await gate.park() } + } else { + await original.services.messageService.setAcknowledgementSaveGateForTesting { await gate.park() } + } + let send = Task { + try await original.services.messageService.sendDirectMessage(text: text, to: contact) + } + try await waitUntil("inline owner save is held") { gate.isParked } + #expect(await original.radio.sendCount == 1) + let messageID = try #require( + try await store.fetchMessages(contactID: contact.id, limit: 1, offset: 0).first?.id + ) + let successor = try await successorAfterHeldSave( + original: original, store: store, radioID: radioID, gate: gate, messageConfig: messageConfig + ) + let message = try await send.value + #expect(message.status == .sent) + await successor.services.messageService.stopAckExpiryChecking() + let row = try #require(await store.fetchPendingSends(radioID: radioID).first) + #expect(row.attemptCount == 1) + #expect(row.ackDeadline != nil) + return HeldInlineSave( + store: store, radioID: radioID, original: original, successor: successor, messageID: messageID + ) + } + + /// Starts teardown while the owner save is held, then opens the successor only after that teardown returns. + private func successorAfterHeldSave( + original: Connection, + store: PersistenceStore, + radioID: UUID, + gate: SuspendGate, + messageConfig: MessageServiceConfig = .default + ) async throws -> Connection { + var handoffFinished = false + let handoff = Task { + await original.close() + let successor = try await Connection.open(store: store, radioID: radioID, messageConfig: messageConfig) + handoffFinished = true + return successor + } + defer { gate.release() } + try await waitUntil("teardown waits for the owner save") { + let service = original.services.messageService + let acknowledgementWaiters = await service.acknowledgementSaveWaiterCountForTesting + let inlineWaiters = await service.inlineSendWaiterCountForTesting + return acknowledgementWaiters + inlineWaiters > 0 || handoffFinished + } + #expect(!handoffFinished, "The successor must not restore before the accepted inline send persists its owner") + let owners = try await store.fetchPendingSends(radioID: radioID) + #expect(owners.allSatisfy { $0.ackDeadline == nil }) + gate.release() + return try await handoff.value + } + + @MainActor + private final class Connection { + let session: MeshCoreSession + let services: ServiceContainer + let radio: Radio + private let responder: Task + + private init(session: MeshCoreSession, services: ServiceContainer, radio: Radio, responder: Task) { + self.session = session + self.services = services + self.radio = radio + self.responder = responder + } + + static func open( + store: PersistenceStore, radioID: UUID, messageConfig: MessageServiceConfig = .default + ) async throws -> Connection { + let transport = MockTransport() + let radio = Radio(transport: transport) + let responder = Task { await radio.run() } + let session = MeshCoreSession(transport: transport) + try await session.start() + let services = ServiceContainer( + session: session, dataStore: store, radioID: radioID, messageConfig: messageConfig + ) + try await services.warmUp() + await services.chatSendQueueService.hydrate() + await services.startEventMonitoring(radioID: radioID, enableAutoFetch: false, enableAdvertisementMonitoring: false) + return Connection(session: session, services: services, radio: radio, responder: responder) + } + + func close() async { + await services.tearDown() + await session.stop() + responder.cancel() + await responder.value + } + } + + private actor Radio { + let transport: MockTransport + private var processedCount = 0 + private(set) var sendCount = 0 + private var predictedCodes: [Data] = [] + private var firmwareCodes: [Data] = [] + + init(transport: MockTransport) { + self.transport = transport + } + + func firstCode(firmware: Bool) -> Data? { + firmware ? firmwareCodes.first : predictedCodes.first + } + + func run() async { + while !Task.isCancelled { + let frames = await transport.sentData + while processedCount < frames.count { + let frame = frames[processedCount] + processedCount += 1 + switch frame.first { + case CommandCode.appStart.rawValue: + await transport.simulateReceive(selfInfoPacket()) + case CommandCode.sendMessage.rawValue: + let timestamp = frame.readUInt32LE(at: 3) + let text = String(decoding: frame.dropFirst(13), as: UTF8.self) + predictedCodes.append(AckCodeBuilder.expectedAck( + timestamp: timestamp, attempt: frame[2], text: text, senderPublicKey: MessageServiceACKRecoveryTests.senderKey + )) + let firmwareCode = Data([0xDE, 0xAD, 0xBE, UInt8(sendCount)]) + firmwareCodes.append(firmwareCode) + sendCount += 1 + var response = Data([ResponseCode.messageSent.rawValue, 0]) + response.append(firmwareCode) + response.append(Data(repeating: 0, count: 4)) + await transport.simulateReceive(response) + case CommandCode.resetPath.rawValue: + await transport.simulateOK() + default: + await transport.simulateError(code: 2) + } + } + try? await Task.sleep(for: .milliseconds(1)) + } + } + + private func selfInfoPacket() -> Data { + var response = Data([ResponseCode.selfInfo.rawValue, 1, 22, 22]) + response.append(MessageServiceACKRecoveryTests.senderKey) + response.append(Data(repeating: 0, count: 12)) + response.append(contentsOf: withUnsafeBytes(of: UInt32(869_525).littleEndian) { Array($0) }) + response.append(contentsOf: withUnsafeBytes(of: UInt32(250_000).littleEndian) { Array($0) }) + response.append(contentsOf: [11, 5]) + return response + } + } +} + +private final class SuspendGate: @unchecked Sendable { + private let lock = NSLock() + private var continuation: CheckedContinuation? + private var parked = false + + var isParked: Bool { + lock.lock() + defer { lock.unlock() } + return parked + } + + func park() async { + await withCheckedContinuation { (continuation: CheckedContinuation) in + lock.lock() + parked = true + self.continuation = continuation + lock.unlock() + } + } + + func release() { + lock.lock() + let continuation = continuation + self.continuation = nil + parked = false + lock.unlock() + continuation?.resume() + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKSettlementTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKSettlementTests.swift new file mode 100644 index 0000000000..8cf3405f15 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKSettlementTests.swift @@ -0,0 +1,191 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("MessageService ACK settlement") +@MainActor +struct MessageServiceACKSettlementTests { + @Test(arguments: [false, true]) + func `competing ACK and expiry callers leave terminal persistence to one owner`(afterCommit: Bool) async throws { + let fixture = try await makeFixture() + let events = fixture.service.statusEvents() + let heldWrite = FirstWriteGate() + defer { heldWrite.release() } + if afterCommit { + await fixture.store.setResolvePendingAcknowledgementCompletionObserver { await heldWrite.park() } + } else { + await fixture.store.setResolvePendingAcknowledgementObserver { await heldWrite.park() } + } + let nextSend = Task { try await fixture.gate.acquire() } + defer { nextSend.cancel() } + try await waitUntil("the next send waits for ACK settlement") { + await fixture.gate.waiterCountForTesting == 1 + } + let resolution = Task { + await fixture.service.handleAcknowledgement(code: fixture.code, tripTime: 40) + } + try await waitUntil("the first terminal write is held") { heldWrite.isParked } + + await fixture.service.handleAcknowledgement(code: fixture.code, tripTime: 999) + try await fixture.service.failAllPendingMessages() + try await fixture.service.checkExpiredAcks() + + #expect(await fixture.store.resolvePendingAcknowledgementCallCount == 1) + #expect(await fixture.gate.waiterCountForTesting == 1) + #expect(await fixture.service.pendingAckCount == 1) + #expect(try await fixture.store.fetchMessage(id: fixture.message.id)?.status == (afterCommit ? .delivered : .sent)) + let heldOwners = try await fixture.store.fetchPendingSends(radioID: fixture.contact.radioID) + #expect(heldOwners == (afterCommit ? [] : [fixture.owner])) + + heldWrite.release() + await resolution.value + let admitted = try await nextSend.value + await fixture.gate.stopIssuing(admitted) + let delivered = try #require(await fixture.store.fetchMessage(id: fixture.message.id)) + #expect(delivered.status == .delivered) + #expect(delivered.roundTripTime == 40) + #expect(try await fixture.store.fetchPendingSends(radioID: fixture.contact.radioID).isEmpty) + #expect(await fixture.service.pendingAckCount == 0) + #expect(await fixture.session.sendMessageInvocations.count == 1) + let recorded = await fixture.service.drainStatusEvents(events) + #expect(recorded.failedIDs.isEmpty) + #expect(recorded.resolvedIDs == [fixture.message.id]) + guard case let .statusResolved(_, status, roundTripTime) = try #require(recorded.first) else { + Issue.record("Settlement must publish the committed delivery") + return + } + #expect(status == .delivered) + #expect(roundTripTime == delivered.roundTripTime) + } + + @Test(arguments: [false, true]) + func `ACK during an expiry write only changes the outcome when that write fails`(saveFails: Bool) async throws { + let fixture = try await makeFixture() + let events = fixture.service.statusEvents() + let heldWrite = FirstWriteGate() + defer { heldWrite.release() } + await fixture.store.setResolvePendingAcknowledgementObserver { await heldWrite.park() } + if saveFails { + await fixture.store.setStubbedResolvePendingAcknowledgementError(InjectedError.save) + } + let nextSend = Task { try await fixture.gate.acquire() } + defer { nextSend.cancel() } + try await waitUntil("the next send waits for ACK settlement") { + await fixture.gate.waiterCountForTesting == 1 + } + let expiry = Task { try await fixture.service.checkExpiredAcks() } + try await waitUntil("the expiry write is held") { heldWrite.isParked } + + await fixture.service.handleAcknowledgement(code: fixture.code, tripTime: 77) + #expect(await fixture.store.resolvePendingAcknowledgementCallCount == 1) + #expect(await fixture.gate.waiterCountForTesting == 1) + + heldWrite.release() + try await expiry.value + if saveFails { + #expect(try await fixture.store.fetchMessage(id: fixture.message.id)?.status == .sent) + #expect(try await fixture.store.fetchPendingSends(radioID: fixture.contact.radioID) == [fixture.owner]) + #expect(await fixture.service.pendingAckCount == 1) + #expect(await fixture.gate.waiterCountForTesting == 1) + + await fixture.store.setStubbedResolvePendingAcknowledgementError(nil) + try await fixture.service.checkExpiredAcks() + } + let admitted = try await nextSend.value + await fixture.gate.stopIssuing(admitted) + let settled = try #require(await fixture.store.fetchMessage(id: fixture.message.id)) + #expect(settled.status == (saveFails ? .delivered : .failed)) + #expect(settled.ackCode == fixture.code.ackCodeUInt32) + #expect(settled.roundTripTime == (saveFails ? 77 : nil)) + #expect(try await fixture.store.fetchPendingSends(radioID: fixture.contact.radioID).isEmpty) + #expect(await fixture.service.pendingAckCount == 0) + #expect(await fixture.store.resolvePendingAcknowledgementCallCount == (saveFails ? 2 : 1)) + #expect(await fixture.session.sendMessageInvocations.count == 1) + let recorded = await fixture.service.drainStatusEvents(events) + #expect(recorded.failedIDs == (saveFails ? [] : [fixture.message.id])) + #expect(recorded.resolvedIDs == (saveFails ? [fixture.message.id] : [])) + if saveFails { + guard case let .statusResolved(_, status, roundTripTime) = try #require(recorded.first) else { + Issue.record("Settlement must publish the committed delivery") + return + } + #expect(status == .delivered) + #expect(roundTripTime == settled.roundTripTime) + } + } + + private struct Fixture { + let store: MockPersistenceStore + let session: MockMeshCoreSession + let service: MessageService + let gate: PlainTextSendGate + let contact: ContactDTO + let message: MessageDTO + let owner: PendingSendDTO + let code: Data + } + + private func makeFixture() async throws -> Fixture { + let store = MockPersistenceStore() + let session = MockMeshCoreSession() + let gate = PlainTextSendGate() + let code = Data([0x11, 0x22, 0x33, 0x44]) + await session.setCurrentSelfInfo(.testSelfInfo()) + await session.setSendMessageResult(.success(MessageSentInfo( + route: 0, expectedAck: code, suggestedTimeoutMs: 0 + ))) + let service = MessageService( + session: session, dataStore: store, contactService: nil, + config: MessageServiceConfig(ackGiveUpWindow: 0), plainTextSendGate: gate + ) + let contact = ContactDTO.testContact() + try await store.saveContact(contact) + let message = try await service.sendDirectMessage(text: "ACK settlement", to: contact) + let owner = try #require(await store.fetchPendingSends(radioID: contact.radioID).first) + let deadline = try #require(owner.ackDeadline) + try await waitUntil("the original ACK deadline has elapsed") { Date() > deadline } + return Fixture( + store: store, session: session, service: service, gate: gate, + contact: contact, message: message, owner: owner, code: code + ) + } + + private enum InjectedError: Error { + case save + } + + private final class FirstWriteGate: @unchecked Sendable { + private let lock = NSLock() + private var continuation: CheckedContinuation? + private var didEnter = false + + var isParked: Bool { + lock.lock() + defer { lock.unlock() } + return continuation != nil + } + + func park() async { + await withCheckedContinuation { (continuation: CheckedContinuation) in + lock.lock() + if didEnter { + lock.unlock() + continuation.resume() + return + } + didEnter = true + self.continuation = continuation + lock.unlock() + } + } + + func release() { + lock.lock() + let continuation = continuation + self.continuation = nil + lock.unlock() + continuation?.resume() + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKTests.swift index 65ebe31d0c..4e14d9779e 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKTests.swift @@ -21,7 +21,7 @@ struct MessageServiceACKTests { ackCodes: ackCodes, sentAt: sentAt, timeout: timeout, - isDelivered: isDelivered + resolution: isDelivered ? .resolved : .awaitingAck ) } @@ -624,18 +624,13 @@ struct MessageServiceACKTests { "Listener should have written RTT=500 before finalizeSend runs") // Retry loop's waitForEvent matched the same ACK, so finalizeSend runs - // with sentInfo != nil. It must NOT clobber the listener-written RTT. - let sentInfo = MessageSentInfo( - route: 0, - expectedAck: ackCode, - suggestedTimeoutMs: 5000 - ) + // with the ACK code and must preserve the listener-written RTT. _ = try await service.finalizeSend( messageID: messageID, contactID: contactID, radioID: radioID, publicKey: publicKey, - sentInfo: sentInfo, + acknowledgedCode: ackCode, initialPathLength: 0 ) @@ -665,23 +660,16 @@ struct MessageServiceACKTests { let statusEvents = service.statusEvents() - // Seed a non-delivered pendingAcks entry so finalizeSend's `if let sentInfo` - // branch is taken (isDelivered == false, sentInfo != nil). await service.setPendingAckForTest( makePending(messageID: messageID, contactID: contactID, ackCodes: [ackCode]) ) - let sentInfo = MessageSentInfo( - route: 0, - expectedAck: ackCode, - suggestedTimeoutMs: 5000 - ) _ = try await service.finalizeSend( messageID: messageID, contactID: contactID, radioID: radioID, publicKey: publicKey, - sentInfo: sentInfo, + acknowledgedCode: ackCode, initialPathLength: 0 ) @@ -712,6 +700,57 @@ struct MessageServiceACKTests { #expect(await service.pendingAckCount == 0) } + @Test + func `a consumed attempt matches after the tracker is gone`() async throws { + let (service, dataStore) = try await MessageService.createForTesting() + let messageID = UUID() + let contactID = UUID() + let text = "parked" + let timestamp: UInt32 = 1_700_000_100 + try await dataStore.saveMessage(MessageDTO.testDirectMessage( + id: messageID, + radioID: testDeviceID, + contactID: contactID, + text: text, + timestamp: timestamp, + status: .pending + )) + let pendingID = UUID() + _ = try await dataStore.insertPendingSendAssigningSequence(PendingSendDTO( + id: pendingID, + envelope: DirectMessageEnvelope(messageID: messageID, contactID: contactID), + radioID: testDeviceID + )) + #expect(try await dataStore.setPendingSendWireAttempt(id: pendingID, to: 1)) + + let senderKey = Data(repeating: 0xAB, count: 32) + await service.installSelfInfoForTest(publicKey: senderKey) + let restarted = await MessageService( + session: service.sessionForTest, + dataStore: dataStore, + contactService: nil + ) + let events = restarted.statusEvents() + let laterAttempt = AckCodeBuilder.expectedAck( + timestamp: timestamp, attempt: 1, text: text, senderPublicKey: senderKey + ) + await restarted.handleAcknowledgement(code: laterAttempt, tripTime: 10) + #expect(try await dataStore.fetchMessage(id: messageID)?.status == .pending) + #expect(try await dataStore.pendingSendWireAttempt(id: pendingID) == 1) + + let consumed = AckCodeBuilder.expectedAck( + timestamp: timestamp, attempt: 0, text: text, senderPublicKey: senderKey + ) + await restarted.handleAcknowledgement(code: consumed, tripTime: 25) + + let delivered = try #require(try await dataStore.fetchMessage(id: messageID)) + #expect(delivered.status == .delivered) + #expect(delivered.roundTripTime == 25) + #expect(try await dataStore.fetchPendingSends(radioID: testDeviceID).isEmpty) + #expect(await restarted.pendingAckCount == 0) + #expect(await restarted.drainStatusEvents(events).resolvedIDs == [messageID]) + } + // MARK: - failMessageAndRethrow cleanup @Test @@ -828,7 +867,7 @@ struct MessageServiceACKTests { contactID: contactID, radioID: radioID, publicKey: Data((0.. 5` via a precondition. -/// The firmware ACK hash masks the attempt index with `& 0x03`; a single -/// message's `ackCodes` set dedupes the attempt-4 wrap, so 5 (4 direct + 1 -/// flood) stays unambiguous, and the cap then bounds mesh airtime. Swift -/// Testing has no precondition matcher, so the failing case is documented -/// inline rather than asserted at runtime; the boundary case is exercised here. -@Suite("MessageServiceConfig precondition") -struct MessageServiceConfigTests { - @Test - func `maxAttempts == 5 is accepted at the precondition boundary`() { - let config = MessageServiceConfig(maxAttempts: 5) - #expect(config.maxAttempts == 5) - } -} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceDMBudgetTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceDMBudgetTests.swift new file mode 100644 index 0000000000..b53c900832 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceDMBudgetTests.swift @@ -0,0 +1,573 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import MeshCoreTestSupport +import os +import Testing + +@Suite("DM send budget") +@MainActor +struct MessageServiceDMBudgetTests { + private let senderKey = Data(repeating: 0xAB, count: 32) + private let preservedTimestamp: UInt32 = 1_700_000_000 + /// A device rejection other than the direct-message table-full code. + private let rejectedDirectMessageCode: UInt8 = 1 + + @Test(arguments: DMSendBudget.directRange, DMSendBudget.floodRange) + func `each budget sends its attempts and resets only before fallback`( + directAttempts: Int, + floodAttempts: Int + ) async throws { + let observed = try await exhaust(budget: DMSendBudget(directAttempts: directAttempts, floodAttempts: floodAttempts)) + let totalAttempts = directAttempts + floodAttempts + #expect(observed.attempts == Array(0.. 0 ? [directAttempts] : [])) + #expect(observed.retryMaxAttempts == Array(repeating: totalAttempts - 1, count: totalAttempts - 1)) + } + + @Test + func `a rejected path reset still uses the remaining attempts without another reset`() async throws { + let observed = try await exhaust( + budget: DMSendBudget(directAttempts: 2, floodAttempts: 2), + resetPathFails: true + ) + #expect(observed.attempts == [0, 1, 2, 3]) + #expect(observed.resetIndexes == [2]) + } + + @Test + func `a resumed drain at the path boundary with no flood attempts does not reset`() async throws { + let observed = try await drainPreserved( + startingAttempt: 2, + budget: DMSendBudget(directAttempts: 2, floodAttempts: 0) + ) + #expect(observed.attempts == [2, 3]) + #expect(observed.resetIndexes.isEmpty) + } + + @Test + func `a resumed drain resets the path before the first byte at the flood boundary`() async throws { + let observed = try await drainPreserved( + startingAttempt: 2, + budget: DMSendBudget(directAttempts: 2, floodAttempts: 2) + ) + #expect(observed.attempts == [2, 3, 4, 5]) + #expect(observed.resetIndexes == [0]) + } + + @Test + func `a resumed drain below the flood boundary sends before resetting`() async throws { + let observed = try await drainPreserved( + startingAttempt: 1, + budget: DMSendBudget(directAttempts: 2, floodAttempts: 2) + ) + #expect(observed.attempts == [1, 2, 3, 4]) + #expect(observed.resetIndexes == [1]) + } + + @Test + func `a single-attempt replay submits only the next byte`() async throws { + let observed = try await drainPreserved(startingAttempt: 1, budget: .singleAttempt) + #expect(observed.attempts == [1]) + #expect(observed.resetIndexes.isEmpty) + #expect(observed.messageIDs.count == 1) + } + + @Test + func `an exhausted wire timestamp stays matchable and sends no new command`() async throws { + let harness = try await makePreservedHarness(startingAttempt: AckCodeBuilder.attemptCount, budget: .singleAttempt) + defer { Task { await harness.session.stop() } } + let before = await harness.transport.sentData.count + let returned = try await harness.service.performQueuedDirectMessageSend( + messageID: harness.messageID, + to: harness.contact, + preserveTimestamp: true, + isResend: false, + isSingleAttempt: false, + pendingSendID: harness.pendingID, + sendLease: nil + ) + let commands = await sendCommands(on: harness.transport, after: before) + #expect(commands.isEmpty) + #expect(returned.status == .pending) + let stored = try #require(try await harness.store.fetchMessage(id: harness.messageID)) + #expect(stored.status == .pending) + #expect(stored.timestamp == preservedTimestamp) + #expect(try await harness.store.fetchMessages(contactID: harness.contact.id).count == 1) + let owner = try await pendingRow(in: harness) + #expect(owner.ackDeadline != nil) + #expect(owner.ackCodes?.isEmpty == false) + #expect(owner.nextWireAttempt == AckCodeBuilder.attemptCount) + #expect(try await harness.store.pendingSendWireAttempt(id: harness.pendingID) == nil) + + let code = AckCodeBuilder.expectedAck( + timestamp: stored.timestamp, + attempt: 0, + text: stored.text, + senderPublicKey: senderKey + ) + await harness.service.handleAcknowledgement(code: code, tripTime: 40) + let delivered = try #require(try await harness.store.fetchMessage(id: harness.messageID)) + #expect(delivered.status == .delivered) + #expect(try await harness.store.hasPendingSend(messageID: harness.messageID) == false) + let afterAck = await sendCommands(on: harness.transport, after: before) + #expect(afterAck.isEmpty) + } + + @Test + func `an exhausted failed row becomes pending with an acknowledgement deadline`() async throws { + let harness = try await makePreservedHarness( + startingAttempt: AckCodeBuilder.attemptCount, + budget: .singleAttempt, + config: MessageServiceConfig(minTimeout: 0, ackGiveUpWindow: 0) + ) + defer { Task { await harness.session.stop() } } + try await harness.store.updateMessageStatus(id: harness.messageID, status: .failed) + let before = await harness.transport.sentData.count + let returned = try await harness.service.performQueuedDirectMessageSend( + messageID: harness.messageID, + to: harness.contact, + preserveTimestamp: true, + isResend: false, + isSingleAttempt: false, + pendingSendID: harness.pendingID, + sendLease: nil + ) + #expect(returned.status == .pending) + let commands = await sendCommands(on: harness.transport, after: before) + #expect(commands.isEmpty) + let stored = try #require(try await harness.store.fetchMessage(id: harness.messageID)) + #expect(stored.status == .pending) + #expect(stored.timestamp == preservedTimestamp) + let owner = try await pendingRow(in: harness) + #expect(owner.ackDeadline != nil) + try await Task.sleep(for: .milliseconds(20)) + try await harness.service.checkExpiredAcks() + let failed = try #require(try await harness.store.fetchMessage(id: harness.messageID)) + #expect(failed.status == .failed) + #expect(failed.timestamp == preservedTimestamp) + #expect(try await harness.store.hasPendingSend(messageID: harness.messageID) == false) + } + + @Test + func `an accepted command still stores sent when the attempt byte is exhausted`() async throws { + let harness = try await makePreservedHarness(startingAttempt: AckCodeBuilder.attemptCount - 1, budget: .singleAttempt) + defer { Task { await harness.session.stop() } } + let responder = Task { await answerCommands(on: harness.transport, after: 1, resetPathFails: false) } + defer { responder.cancel() } + let returned = try await harness.service.performQueuedDirectMessageSend( + messageID: harness.messageID, + to: harness.contact, + preserveTimestamp: true, + isResend: false, + isSingleAttempt: false, + pendingSendID: harness.pendingID, + sendLease: nil + ) + responder.cancel() + #expect(returned.status == .sent) + let stored = try #require(try await harness.store.fetchMessage(id: harness.messageID)) + #expect(stored.status == .sent) + #expect(stored.timestamp == preservedTimestamp) + } + + @Test + func `a rejected resend of a delivered message keeps the delivery and the old timestamp`() async throws { + let harness = try await makePreservedHarness(startingAttempt: 0, budget: .singleAttempt) + defer { Task { await harness.session.stop() } } + try await harness.store.updateMessageStatus(id: harness.messageID, status: .delivered) + let events = harness.service.statusEvents() + let responder = Task { + await answerCommands(on: harness.transport, after: 1, resetPathFails: false, rejectSend: true) + } + defer { responder.cancel() } + let returned = try await harness.service.performQueuedDirectMessageSend( + messageID: harness.messageID, + to: harness.contact, + preserveTimestamp: false, + isResend: true, + isSingleAttempt: false, + pendingSendID: harness.pendingID, + sendLease: nil + ) + responder.cancel() + #expect(returned.status == .delivered) + #expect(returned.timestamp == preservedTimestamp) + let stored = try #require(try await harness.store.fetchMessage(id: harness.messageID)) + #expect(stored.status == .delivered) + #expect(stored.timestamp == preservedTimestamp) + #expect(try await harness.store.hasPendingSend(messageID: harness.messageID) == false) + #expect(await deliveredResolutions(on: harness.service, from: events) == [harness.messageID]) + } + + @Test + func `a table full resend keeps the new timestamp and resubmits attempt zero`() async throws { + let harness = try await makePreservedHarness( + startingAttempt: 0, + budget: .singleAttempt, + config: MessageServiceConfig(minTimeout: 0, poolBackoff: PoolBackoffConfig(attemptCap: 0, baseDelay: 0)) + ) + defer { Task { await harness.session.stop() } } + try await harness.store.updateMessageStatus(id: harness.messageID, status: .delivered) + let bumped = try #require(try await harness.store.preparePendingSendAttempt(messageID: harness.messageID)) + #expect(bumped.attemptCount == 1) + let events = harness.service.statusEvents() + let responder = Task { + await answerCommands(on: harness.transport, after: 1, resetPathFails: false, tableFull: true) + } + defer { responder.cancel() } + let error = await #expect(throws: MeshCoreError.self) { + try await harness.service.performQueuedDirectMessageSend( + messageID: harness.messageID, + to: harness.contact, + preserveTimestamp: false, + isResend: true, + isSingleAttempt: false, + pendingSendID: harness.pendingID, + sendLease: nil + ) + } + responder.cancel() + guard case let .deviceError(code)? = error else { + Issue.record("Expected table full, got \(String(describing: error))") + return + } + #expect(code == FirmwareDeviceErrorCode.directMessageTableFull) + let stored = try #require(try await harness.store.fetchMessage(id: harness.messageID)) + #expect(stored.status == .pending) + #expect(stored.timestamp != preservedTimestamp) + let parked = try await pendingRow(in: harness) + #expect(parked.ackDeadline == nil) + #expect(parked.nextWireAttempt == 0) + #expect(parked.attemptCount == bumped.attemptCount) + #expect(await deliveredResolutions(on: harness.service, from: events).isEmpty) + + let before = await harness.transport.sentData.count + let accepted = Task { await answerCommands(on: harness.transport, after: before, resetPathFails: false) } + defer { accepted.cancel() } + _ = try await harness.service.performQueuedDirectMessageSend( + messageID: harness.messageID, + to: harness.contact, + preserveTimestamp: true, + isResend: true, + isSingleAttempt: false, + pendingSendID: harness.pendingID, + sendLease: nil + ) + accepted.cancel() + let commands = await sendCommands(on: harness.transport, after: before) + #expect(commands.count == 1) + #expect(commands.first.map { $0.count > 2 ? $0[2] : 255 } == 0) + let retried = try #require(try await harness.store.fetchMessage(id: harness.messageID)) + #expect(retried.timestamp == stored.timestamp) + } + + @Test + func `a not submitted resend restores delivery and keeps the pending row`() async throws { + let harness = try await makePreservedHarness(startingAttempt: 0, budget: .singleAttempt) + defer { Task { await harness.session.stop() } } + try await harness.store.updateMessageStatus(id: harness.messageID, status: .delivered) + let bumped = try #require(try await harness.store.preparePendingSendAttempt(messageID: harness.messageID)) + #expect(bumped.attemptCount == 1) + let events = harness.service.statusEvents() + await harness.transport.rejectNextSendBeforeSubmission() + let error = await #expect(throws: MeshCoreError.self) { + try await harness.service.performQueuedDirectMessageSend( + messageID: harness.messageID, + to: harness.contact, + preserveTimestamp: false, + isResend: true, + isSingleAttempt: false, + pendingSendID: harness.pendingID, + sendLease: nil + ) + } + guard case .notConnected? = error else { + Issue.record("Expected not submitted, got \(String(describing: error))") + return + } + let stored = try #require(try await harness.store.fetchMessage(id: harness.messageID)) + #expect(stored.status == .delivered) + #expect(stored.timestamp == preservedTimestamp) + let parked = try await pendingRow(in: harness) + #expect(parked.ackDeadline == nil) + #expect(parked.nextWireAttempt == 0) + #expect(parked.attemptCount == PersistenceStore.initialAttemptCount) + #expect(await deliveredResolutions(on: harness.service, from: events) == [harness.messageID]) + } + + @Test + func `a preserved drain of a delivered message sends nothing`() async throws { + let harness = try await makePreservedHarness(startingAttempt: 1, budget: .default) + defer { Task { await harness.session.stop() } } + try await harness.store.updateMessageStatus(id: harness.messageID, status: .delivered) + let before = await harness.transport.sentData.count + let returned = try await harness.service.performQueuedDirectMessageSend( + messageID: harness.messageID, + to: harness.contact, + preserveTimestamp: true, + isResend: true, + isSingleAttempt: false, + pendingSendID: harness.pendingID, + sendLease: nil + ) + #expect(returned.status == .delivered) + #expect(returned.timestamp == 1_700_000_000) + let commands = await sendCommands(on: harness.transport, after: before) + #expect(commands.isEmpty) + let stored = try #require(try await harness.store.fetchMessage(id: harness.messageID)) + #expect(stored.timestamp == 1_700_000_000) + } + + @Test + func `the retry loop reads the budget provider once`() async throws { + let calls = OSAllocatedUnfairLock(initialState: 0) + let observed = try await exhaust(budgetProvider: { + calls.withLock { count in + count += 1 + return count == 1 + ? .singleAttempt + : .default + } + }) + #expect(calls.withLock { $0 } == 1) + #expect(observed.attempts == [0]) + #expect(observed.resetIndexes.isEmpty) + } + + private struct Observation { + var attempts: [UInt8] + var resetIndexes: [Int] + var retryMaxAttempts: [Int] + var timestamps: [UInt32] = [] + var restamped: UInt32 = 0 + var messageIDs: [UUID] = [] + } + + private func exhaust( + budget: DMSendBudget, + resetPathFails: Bool = false + ) async throws -> Observation { + try await exhaust(budgetProvider: { budget }, resetPathFails: resetPathFails) + } + + private func exhaust( + budgetProvider: @escaping @Sendable () -> DMSendBudget, + resetPathFails: Bool = false + ) async throws -> Observation { + let transport = MockTransport() + let session = MeshCoreSession(transport: transport, configuration: SessionConfiguration(defaultTimeout: 10)) + let start = Task { try await session.start() } + try await waitUntil("session should send app start") { await transport.sentData.count == 1 } + await transport.simulateReceive(selfInfoPacket(publicKey: senderKey)) + try await start.value + defer { Task { await session.stop() } } + + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let service = MessageService( + session: session, + dataStore: store, + contactService: nil, + config: MessageServiceConfig(minTimeout: 0), + dmSendBudget: budgetProvider + ) + let events = service.statusEvents() + let contact = ContactDTO.testContact(radioID: UUID(), publicKey: Data(repeating: 0x42, count: 32)) + let responder = Task { await answerCommands(on: transport, after: 1, resetPathFails: resetPathFails) } + defer { responder.cancel() } + + let sent = try await service.sendMessageWithRetry(text: "budget", to: contact) + #expect(sent.status == .sent) + responder.cancel() + + let packets = await transport.sentData + var attempts: [UInt8] = [] + var resetIndexes: [Int] = [] + var directBeforeReset = 0 + for packet in packets { + switch packet.first { + case CommandCode.sendMessage.rawValue: + attempts.append(packet.count > 2 ? packet[2] : 255) + if resetIndexes.isEmpty { directBeforeReset += 1 } + case CommandCode.resetPath.rawValue: + resetIndexes.append(directBeforeReset) + default: + break + } + } + let retries = await service.drainStatusEvents(events).retryUpdates.map(\.maxAttempts) + return Observation(attempts: attempts, resetIndexes: resetIndexes, retryMaxAttempts: retries) + } + + private struct PreservedHarness { + let service: MessageService + let store: PersistenceStore + let transport: MockTransport + let session: MeshCoreSession + let contact: ContactDTO + let messageID: UUID + let pendingID: UUID + } + + private func makePreservedHarness( + startingAttempt: UInt8, + budget: DMSendBudget, + config: MessageServiceConfig = MessageServiceConfig(minTimeout: 0) + ) async throws -> PreservedHarness { + let transport = MockTransport() + let session = MeshCoreSession( + transport: transport, + configuration: SessionConfiguration(defaultTimeout: 10) + ) + let start = Task { try await session.start() } + try await waitUntil("session should send app start") { await transport.sentData.count == 1 } + await transport.simulateReceive(selfInfoPacket(publicKey: senderKey)) + try await start.value + + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let service = MessageService( + session: session, + dataStore: store, + contactService: nil, + config: config, + dmSendBudget: { budget } + ) + let contact = ContactDTO.testContact(radioID: UUID(), publicKey: Data(repeating: 0x42, count: 32)) + let message = try await service.createPendingMessage(text: "budget", to: contact) + try await store.updateMessageTimestamp(id: message.id, timestamp: preservedTimestamp) + let pendingID = UUID() + _ = try await store.insertPendingSendAssigningSequence(PendingSendDTO( + id: pendingID, + envelope: DirectMessageEnvelope(messageID: message.id, contactID: contact.id), + radioID: contact.radioID + )) + #expect(try await store.setPendingSendWireAttempt(id: pendingID, to: startingAttempt)) + return PreservedHarness( + service: service, + store: store, + transport: transport, + session: session, + contact: contact, + messageID: message.id, + pendingID: pendingID + ) + } + + private func deliveredResolutions(on service: MessageService, from events: AsyncStream) async -> [UUID] { + await service.drainStatusEvents(events).compactMap { event in + guard case let .statusResolved(id, status, roundTripTime) = event, + status == .delivered, roundTripTime == nil else { return nil } + return id + } + } + + private func pendingRow(in harness: PreservedHarness) async throws -> PendingSendDTO { + let rows = try await harness.store.fetchPendingSends(radioID: harness.contact.radioID) + return try #require(rows.first { $0.id == harness.pendingID }) + } + + private func sendCommands(on transport: MockTransport, after answered: Int) async -> [Data] { + let packets = await transport.sentData + return packets.dropFirst(answered).filter { $0.first == CommandCode.sendMessage.rawValue } + } + + private func drainPreserved(startingAttempt: UInt8, budget: DMSendBudget) async throws -> Observation { + let harness = try await makePreservedHarness(startingAttempt: startingAttempt, budget: budget) + defer { Task { await harness.session.stop() } } + let responder = Task { await answerCommands(on: harness.transport, after: 1, resetPathFails: false) } + defer { responder.cancel() } + _ = try await harness.service.performQueuedDirectMessageSend( + messageID: harness.messageID, + to: harness.contact, + preserveTimestamp: true, + isResend: false, + isSingleAttempt: false, + pendingSendID: harness.pendingID, + sendLease: nil + ) + responder.cancel() + + let packets = await harness.transport.sentData + var attempts: [UInt8] = [] + var timestamps: [UInt32] = [] + var resetIndexes: [Int] = [] + var directBeforeReset = 0 + for packet in packets { + switch packet.first { + case CommandCode.sendMessage.rawValue: + attempts.append(packet.count > 2 ? packet[2] : 255) + if packet.count >= 7 { + let raw = packet.subdata(in: 3..<7).withUnsafeBytes { $0.loadUnaligned(as: UInt32.self) } + timestamps.append(UInt32(littleEndian: raw)) + } + if resetIndexes.isEmpty { directBeforeReset += 1 } + case CommandCode.resetPath.rawValue: + resetIndexes.append(directBeforeReset) + default: + break + } + } + let messages = try await harness.store.fetchMessages(contactID: harness.contact.id) + let stored = try #require(try await harness.store.fetchMessage(id: harness.messageID)) + return Observation( + attempts: attempts, + resetIndexes: resetIndexes, + retryMaxAttempts: [], + timestamps: timestamps, + restamped: stored.timestamp, + messageIDs: messages.map(\.id) + ) + } + + private func answerCommands( + on transport: MockTransport, + after answered: Int, + resetPathFails: Bool, + rejectSend: Bool = false, + tableFull: Bool = false + ) async { + var responded = answered + while !Task.isCancelled { + let packets = await transport.sentData + guard packets.count > responded else { + try? await Task.sleep(for: .milliseconds(2)) + continue + } + for packet in packets[responded...] { + switch packet.first { + case CommandCode.resetPath.rawValue: + if resetPathFails { + await transport.simulateReceive(Data([ResponseCode.error.rawValue])) + } else { + await transport.simulateOK() + } + case CommandCode.getContactByKey.rawValue: + await transport.simulateReceive(Data([ResponseCode.error.rawValue])) + case CommandCode.sendMessage.rawValue where rejectSend || tableFull: + let code = tableFull ? FirmwareDeviceErrorCode.directMessageTableFull : rejectedDirectMessageCode + await transport.simulateReceive(Data([ResponseCode.error.rawValue, code])) + default: + var frame = Data([ResponseCode.messageSent.rawValue, 0]) + frame.append(Data([0xA1, 0xB2, 0xC3, 0xD4])) + frame.append(contentsOf: withUnsafeBytes(of: UInt32(10).littleEndian) { Array($0) }) + await transport.simulateReceive(frame) + } + } + responded = packets.count + } + } + + private func selfInfoPacket(publicKey: Data) -> Data { + var payload = Data([1, 22, 22]) + payload.append(publicKey) + payload.append(Data(repeating: 0, count: 8)) + payload.append(contentsOf: [0, 0, 0]) + payload.append(contentsOf: withUnsafeBytes(of: UInt32(915_000).littleEndian) { Array($0) }) + payload.append(contentsOf: withUnsafeBytes(of: UInt32(125_000).littleEndian) { Array($0) }) + payload.append(contentsOf: [7, 5]) + payload.append(contentsOf: "Test".utf8) + var packet = Data([ResponseCode.selfInfo.rawValue]) + packet.append(payload) + return packet + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendDMBookkeepingTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendDMBookkeepingTests.swift index 76656f6e05..71dab6e651 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendDMBookkeepingTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendDMBookkeepingTests.swift @@ -7,7 +7,7 @@ import Testing struct MessageServiceSendDMBookkeepingTests { @Test @MainActor - func `sendDirectMessage keeps ACK tracking and does not report failure when post-send bookkeeping fails`() async throws { + func `deleting a DM during send removes orphan ACK tracking without reporting failure`() async throws { let transport = MockTransport() let session = MeshCoreSession( transport: transport, @@ -37,8 +37,8 @@ struct MessageServiceSendDMBookkeepingTests { await transport.sentData.count == 2 } - // Delete the saved row mid-send so post-send bookkeeping fails after - // the radio has already accepted the message. + // Delete before the acceptance response; no Message remains for + // delivery tracking. let saved = try await dataStore.fetchMessages(contactID: contact.id, limit: 10, offset: 0) let messageID = try #require(saved.first?.id) try await dataStore.deleteMessage(id: messageID) @@ -53,10 +53,217 @@ struct MessageServiceSendDMBookkeepingTests { _ = try await sendTask.value } - #expect(await service.pendingAckCount == 1, - "post-send bookkeeping failure must keep the pendingAcks entry alive for the genuine ACK") - #expect(await service.drainStatusEvents(statusEvents).failedIDs.isEmpty, - "post-send bookkeeping failure must not report the DM as failed") + #expect(await service.pendingAckCount == 0) + #expect(try await dataStore.fetchPendingSends(radioID: contact.radioID).isEmpty) + #expect(try await dataStore.fetchMessage(id: messageID) == nil) + #expect(await service.drainStatusEvents(statusEvents).failedIDs.isEmpty) + } + + @Test + func `a genuine post-send write failure retains both ACK owners and accepts the valid ACK`() async throws { + let store = MockPersistenceStore() + let session = MockMeshCoreSession() + await session.setCurrentSelfInfo(.testSelfInfo()) + let code = Data([0xAB, 0xCD, 0xEF, 0x12]) + await session.setSendMessageResult(.success(MessageSentInfo( + route: 0, expectedAck: code, suggestedTimeoutMs: 5000 + ))) + await session.setSendMessageObserver { + await store.setStubbedUpdateMessageStatusError(InjectedBookkeepingError.simulated) + } + let service = MessageService(session: session, dataStore: store, contactService: nil) + let events = service.statusEvents() + let contact = ContactDTO.testContact() + try await store.saveContact(contact) + + let accepted = try await service.sendDirectMessage(text: "hi", to: contact) + + #expect(accepted.status == .sent) + #expect(await session.sendMessageInvocations.count == 1) + #expect(await store.updatedMessageAcks.count == 1, "The post-send write must have been attempted") + #expect(await service.pendingAckCount == 1) + let owner = try #require(await store.fetchPendingSends(radioID: contact.radioID).first) + #expect(owner.messageID == accepted.id) + #expect(owner.ackCodes?.contains(code) == true) + #expect(owner.ackDeadline != nil) + #expect(owner.attemptCount == 1) + + await store.setStubbedUpdateMessageStatusError(nil) + await service.handleAcknowledgement(code: code, tripTime: 123) + + #expect(try await store.fetchMessage(id: accepted.id)?.status == .delivered) + #expect(try await store.fetchMessage(id: accepted.id)?.roundTripTime == 123) + #expect(await service.pendingAckCount == 0) + #expect(try await store.fetchPendingSends(radioID: contact.radioID).isEmpty) + let recorded = await service.drainStatusEvents(events) + #expect(recorded.failedIDs.isEmpty) + #expect(recorded.resolvedIDs == [accepted.id]) + } + + @Test + @MainActor + func `a matched ACK survives a terminal write failure when the owner is saved`() async throws { + let code = Data([0xAB, 0xCD, 0xEF, 0x12]) + let harness = try await makeHarness(ackGiveUpWindow: 0, suggestedTimeoutMs: 0, code: code) + let gate = SuspendGate() + defer { gate.release() } + await harness.service.setAcknowledgementSaveGateForTesting { + await gate.park() + } + await harness.store.setStubbedResolvePendingAcknowledgementError(InjectedBookkeepingError.simulated) + let send = Task { + try await harness.service.sendDirectMessage(text: "held delivery", to: harness.contact) + } + try await waitUntil("owner save is held") { gate.isParked } + let messageID = try #require( + try await harness.store.fetchMessages(contactID: harness.contact.id, limit: 1, offset: 0).first?.id + ) + await harness.service.handleAcknowledgement(code: code, tripTime: 77) + #expect(try await harness.store.fetchMessage(id: messageID)?.status == .pending) + + gate.release() + let accepted = try await send.value + #expect(accepted.status == .sent) + #expect(await harness.service.pendingAckForTest(messageID)?.matchedAckCode == code.ackCodeUInt32) + let owner = try #require(await harness.store.fetchPendingSends(radioID: harness.contact.radioID).first) + #expect(owner.ackDeadline != nil) + + await harness.store.setStubbedResolvePendingAcknowledgementError(nil) + try await harness.service.checkExpiredAcks() + let delivered = try await harness.store.fetchMessage(id: messageID) + #expect(delivered?.status == .delivered) + #expect(delivered?.roundTripTime == 77) + #expect(await harness.service.pendingAckCount == 0) + #expect(try await harness.store.fetchPendingSends(radioID: harness.contact.radioID).isEmpty) + } + + @Test + func `an installed owner resolves one acknowledgement into delivery`() async throws { + let code = Data([0x11, 0x22, 0x33, 0x44]) + let harness = try await makeHarness(code: code) + let accepted = try await harness.service.sendDirectMessage(text: "installed", to: harness.contact) + #expect(await harness.service.pendingAckForTest(accepted.id)?.owner?.id != nil) + let events = harness.service.statusEvents() + await harness.service.handleAcknowledgement(code: code, tripTime: 15) + #expect(try await harness.store.fetchMessage(id: accepted.id)?.status == .delivered) + #expect(try await harness.store.fetchMessage(id: accepted.id)?.roundTripTime == 15) + #expect(try await harness.store.fetchPendingSends(radioID: harness.contact.radioID).isEmpty) + #expect(await harness.service.pendingAckCount == 0) + let recorded = await harness.service.drainStatusEvents(events) + #expect(recorded.failedIDs.isEmpty) + #expect(recorded.resolvedIDs == [accepted.id]) + } + + @Test + @MainActor + func `expiry without a matched acknowledgement fails the message and deletes the owner`() async throws { + let harness = try await makeHarness(ackGiveUpWindow: 0, suggestedTimeoutMs: 0) + let accepted = try await harness.service.sendDirectMessage(text: "expire", to: harness.contact) + #expect(await harness.service.pendingAckForTest(accepted.id)?.matchedAckCode == nil) + #expect(await harness.service.pendingAckForTest(accepted.id)?.owner?.id != nil) + let events = harness.service.statusEvents() + try await waitUntil("give-up deadline has elapsed") { + guard let tracking = await harness.service.pendingAckForTest(accepted.id) else { return false } + let deadline = tracking.owner?.deadline ?? tracking.sentAt + return Date() > deadline + } + try await harness.service.checkExpiredAcks() + #expect(try await harness.store.fetchMessage(id: accepted.id)?.status == .failed) + #expect(try await harness.store.fetchPendingSends(radioID: harness.contact.radioID).isEmpty) + #expect(await harness.service.pendingAckCount == 0) + let recorded = await harness.service.drainStatusEvents(events) + #expect(recorded.failedIDs == [accepted.id]) + #expect(recorded.resolvedIDs.isEmpty) + } + + @Test + @MainActor + func `a thrown resolve leaves the owner and retries the matched code without another acknowledgement`() async throws { + let code = Data([0xAB, 0xCD, 0xEF, 0x12]) + let harness = try await makeHarness(ackGiveUpWindow: 0, suggestedTimeoutMs: 0, code: code) + let accepted = try await harness.service.sendDirectMessage(text: "resolve throws", to: harness.contact) + #expect(await harness.service.pendingAckForTest(accepted.id)?.owner?.id != nil) + await harness.store.setStubbedResolvePendingAcknowledgementError(InjectedBookkeepingError.simulated) + await harness.service.handleAcknowledgement(code: code, tripTime: 40) + #expect(try await harness.store.fetchMessage(id: accepted.id)?.status == .sent) + #expect(await harness.service.pendingAckForTest(accepted.id)?.isResolved == false) + #expect(await harness.service.pendingAckForTest(accepted.id)?.matchedAckCode == code.ackCodeUInt32) + #expect(await harness.service.pendingAckForTest(accepted.id)?.owner?.id != nil) + #expect(try await harness.store.fetchPendingSends(radioID: harness.contact.radioID).count == 1) + await harness.store.setStubbedResolvePendingAcknowledgementError(nil) + try await waitUntil("give-up deadline has elapsed") { + guard let tracking = await harness.service.pendingAckForTest(accepted.id) else { return false } + let deadline = tracking.owner?.deadline ?? tracking.sentAt + return Date() > deadline + } + try await harness.service.checkExpiredAcks() + #expect(try await harness.store.fetchMessage(id: accepted.id)?.status == .delivered) + #expect(try await harness.store.fetchMessage(id: accepted.id)?.roundTripTime == 40) + #expect(try await harness.store.fetchPendingSends(radioID: harness.contact.radioID).isEmpty) + #expect(await harness.service.pendingAckCount == 0) + } + + @Test + func `retired inline admission rejects a stale caller before saving a message`() async throws { + let store = MockPersistenceStore() + let session = MockMeshCoreSession() + let service = MessageService(session: session, dataStore: store, contactService: nil) + let contact = ContactDTO.testContact() + await service.retireInlineSends() + await #expect(throws: MessageServiceError.self) { + _ = try await service.sendDirectMessage(text: "stale reply", to: contact) + } + #expect(try await store.fetchMessages(contactID: contact.id, limit: 1, offset: 0).isEmpty) + #expect(await session.sendMessageInvocations.isEmpty) + } + + @Test + @MainActor + func `a failed inline send releases a parked retirement`() async throws { + let session = MockMeshCoreSession() + await session.setCurrentSelfInfo(.testSelfInfo()) + await session.setSendMessageResult(.failure(CancellationError())) + let gate = SuspendGate() + await session.setSendMessageObserver { await gate.park() } + let service = MessageService( + session: session, dataStore: MockPersistenceStore(), contactService: nil + ) + let send = Task { + try await service.sendDirectMessage(text: "failed reply", to: .testContact()) + } + try await waitUntil("the radio exchange is held") { gate.isParked } + let retirement = Task { await service.retireInlineSends() } + try await waitUntil("retirement is parked on the inline send") { + await service.inlineSendWaiterCountForTesting > 0 + } + gate.release() + await #expect(throws: Error.self) { _ = try await send.value } + await retirement.value + #expect(await service.inlineSendsInFlight == 0) + } + + private func makeHarness( + ackGiveUpWindow: TimeInterval = 30, + suggestedTimeoutMs: UInt32 = 5000, + code: Data = Data([0xAB, 0xCD, 0xEF, 0x12]) + ) async throws -> (store: MockPersistenceStore, service: MessageService, contact: ContactDTO, code: Data) { + let store = MockPersistenceStore() + let session = MockMeshCoreSession() + await session.setCurrentSelfInfo(.testSelfInfo()) + await session.setSendMessageResult(.success(MessageSentInfo( + route: 0, expectedAck: code, suggestedTimeoutMs: suggestedTimeoutMs + ))) + let service = MessageService( + session: session, dataStore: store, contactService: nil, + config: MessageServiceConfig(ackGiveUpWindow: ackGiveUpWindow) + ) + let contact = ContactDTO.testContact() + try await store.saveContact(contact) + return (store, service, contact, code) + } + + private enum InjectedBookkeepingError: Error { + case simulated } private func makeSelfInfoPacket() -> Data { @@ -89,3 +296,33 @@ struct MessageServiceSendDMBookkeepingTests { withUnsafeBytes(of: value.littleEndian) { Data($0) } } } + +private final class SuspendGate: @unchecked Sendable { + private let lock = NSLock() + private var continuation: CheckedContinuation? + private var parked = false + + var isParked: Bool { + lock.lock() + defer { lock.unlock() } + return parked + } + + func park() async { + await withCheckedContinuation { (continuation: CheckedContinuation) in + lock.lock() + parked = true + self.continuation = continuation + lock.unlock() + } + } + + func release() { + lock.lock() + let continuation = continuation + self.continuation = nil + parked = false + lock.unlock() + continuation?.resume() + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendTests.swift index 912f1d8103..03c25d0bdb 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendTests.swift @@ -483,20 +483,6 @@ struct MessageServiceSendTests { let statusEvents = service.statusEvents() - // Pre-populate the pending-ack entry as already delivered so the - // retry loop short-circuits after sendMessage returns. - let ackCode = Data([0xAB, 0xCD, 0xEF, 0x12]) - await service.setPendingAckForTest( - PendingAck( - messageID: messageID, - contactID: contactID, - ackCodes: [ackCode], - sentAt: Date(), - timeout: 30, - isDelivered: true - ) - ) - let resendTask = Task { try await service.resendDirectMessage(messageID: messageID, to: contact) } @@ -505,6 +491,13 @@ struct MessageServiceSendTests { await transport.sentData.count == 2 } + let timestamp = try #require(try await dataStore.fetchMessage(id: messageID)?.timestamp) + let senderKey = try #require(await session.currentSelfInfo?.publicKey) + let ackCode = AckCodeBuilder.expectedAck( + timestamp: timestamp, attempt: 0, text: delivered.text, senderPublicKey: senderKey + ) + await service.handleAcknowledgement(code: ackCode, tripTime: 40) + var msgSent = Data([ResponseCode.messageSent.rawValue]) msgSent.append(0) msgSent.append(ackCode) @@ -565,20 +558,6 @@ struct MessageServiceSendTests { let statusEvents = service.statusEvents() - // Pre-populate the pending-ack entry as already delivered so the - // retry loop short-circuits after sendMessage returns. - let ackCode = Data([0xAB, 0xCD, 0xEF, 0x12]) - await service.setPendingAckForTest( - PendingAck( - messageID: messageID, - contactID: contactID, - ackCodes: [ackCode], - sentAt: Date(), - timeout: 30, - isDelivered: true - ) - ) - let sendTask = Task { try await service.sendPendingDirectMessage(messageID: messageID, to: contact) } @@ -587,6 +566,13 @@ struct MessageServiceSendTests { await transport.sentData.count == 2 } + let timestamp = try #require(try await dataStore.fetchMessage(id: messageID)?.timestamp) + let senderKey = try #require(await session.currentSelfInfo?.publicKey) + let ackCode = AckCodeBuilder.expectedAck( + timestamp: timestamp, attempt: 0, text: pending.text, senderPublicKey: senderKey + ) + await service.handleAcknowledgement(code: ackCode, tripTime: 40) + var msgSent = Data([ResponseCode.messageSent.rawValue]) msgSent.append(0) msgSent.append(ackCode) @@ -607,6 +593,7 @@ struct MessageServiceSendTests { ".resent must not broadcast on first send") let stored = try await dataStore.fetchMessage(id: messageID) + #expect(stored?.status == .delivered) #expect(stored?.sendCount == 1, "successful sendPendingDirectMessage must leave sendCount at 1") } @@ -692,7 +679,7 @@ struct MessageServiceSendTests { ackCodes: [ackCode], sentAt: Date(), timeout: 30, - isDelivered: true + resolution: .resolved ) ) @@ -733,7 +720,7 @@ struct MessageServiceSendTests { ackCodes: [ackCode], sentAt: Date(), timeout: 30, - isDelivered: false + resolution: .awaitingAck ) ) @@ -742,7 +729,7 @@ struct MessageServiceSendTests { contactID: contactID, radioID: radioID, publicKey: publicKey, - sentInfo: nil, + acknowledgedCode: nil, initialPathLength: 0 ) @@ -771,12 +758,13 @@ struct MessageServiceSendTests { let container = try PersistenceStore.createContainer(inMemory: true) let dataStore = PersistenceStore(modelContainer: container) - // maxAttempts 2 so the loop writes .retrying once; floodAfter high so no path reset fires. + // Two initial attempts exercise retrying without resetting the out path. let service = MessageService( session: session, dataStore: dataStore, contactService: nil, - config: MessageServiceConfig(maxAttempts: 2, floodAfter: 5, minTimeout: 0) + config: MessageServiceConfig(minTimeout: 0), + dmSendBudget: { DMSendBudget(directAttempts: 2, floodAttempts: 0) } ) let contact = ContactDTO.testContact(id: UUID(), radioID: testDeviceID) @@ -883,7 +871,7 @@ struct MessageServiceSendTests { session: session, dataStore: dataStore, contactService: nil, - config: MessageServiceConfig(maxAttempts: 2, floodAfter: 5) + dmSendBudget: { DMSendBudget(directAttempts: 2, floodAttempts: 0) } ) let contactID = UUID() @@ -954,7 +942,8 @@ struct MessageServiceSendTests { session: session, dataStore: dataStore, contactService: nil, - config: MessageServiceConfig(maxAttempts: 2, floodAfter: 5, ackGiveUpWindow: 1) + config: MessageServiceConfig(ackGiveUpWindow: 1), + dmSendBudget: { DMSendBudget(directAttempts: 2, floodAttempts: 0) } ) let contactID = UUID() @@ -997,147 +986,4 @@ struct MessageServiceSendTests { let delivered = try await sendTask.value #expect(delivered.status == .delivered) } - - // MARK: - Retry budget count and direct->flood escalation - - @Test - @MainActor - func `the retry loop sends exactly config.maxAttempts times under sustained non-ACK`() async throws { - let transport = MockTransport() - let session = MeshCoreSession( - transport: transport, - configuration: SessionConfiguration(defaultTimeout: 10) - ) - let startTask = Task { try await session.start() } - try await waitUntil("session should send app start") { - await transport.sentData.count == 1 - } - await transport.simulateReceive(makeSelfInfoPacket()) - try await startTask.value - defer { Task { await session.stop() } } - - let container = try PersistenceStore.createContainer(inMemory: true) - let dataStore = PersistenceStore(modelContainer: container) - // floodAfter above maxAttempts so no path reset fires; this case isolates the budget count. - let maxAttempts = 2 - let service = MessageService( - session: session, - dataStore: dataStore, - contactService: nil, - config: MessageServiceConfig(maxAttempts: maxAttempts, floodAfter: maxAttempts + 3, minTimeout: 0) - ) - - let contact = ContactDTO.testContact(id: UUID(), radioID: testDeviceID) - let ackCode = Data([0xA1, 0xB2, 0xC3, 0xD4]) - - // Accept every CMD_SEND_TXT_MSG with a messageSent frame so session.sendMessage - // returns, but never emit the end-to-end ACK, so each attempt's waitForEvent - // times out and the loop retries until the budget is spent. Answer the - // routing-check contact query with "not found" so finalizeSend returns fast. - let responder = Task { - var responded = 1 // app start already accounted for - while !Task.isCancelled { - let count = await transport.sentData.count - if count > responded { - responded = count - let newest = await transport.sentData.last - if newest?.first == CommandCode.getContactByKey.rawValue { - await transport.simulateReceive(Data([ResponseCode.error.rawValue])) - } else { - var msgSent = Data([ResponseCode.messageSent.rawValue]) - msgSent.append(0) - msgSent.append(ackCode) - msgSent.append(uint32Bytes(10)) // ~12ms ack window - await transport.simulateReceive(msgSent) - } - } - await Task.yield() - } - } - defer { responder.cancel() } - - let sent = try await service.sendMessageWithRetry(text: "count me", to: contact) - #expect(sent.status == .sent) - - let sends = await transport.sentData - let directSendCount = sends.count(where: { $0.first == CommandCode.sendMessage.rawValue }) - #expect(directSendCount == maxAttempts, - "the retry loop must send exactly config.maxAttempts times, not maxAttempts+1") - } - - @Test - @MainActor - func `the retry loop escalates from direct to flood via resetPath after exactly config.floodAfter direct failures`() async throws { - let transport = MockTransport() - let session = MeshCoreSession( - transport: transport, - configuration: SessionConfiguration(defaultTimeout: 10) - ) - let startTask = Task { try await session.start() } - try await waitUntil("session should send app start") { - await transport.sentData.count == 1 - } - await transport.simulateReceive(makeSelfInfoPacket()) - try await startTask.value - defer { Task { await session.stop() } } - - let container = try PersistenceStore.createContainer(inMemory: true) - let dataStore = PersistenceStore(modelContainer: container) - // floodAfter < maxAttempts so the loop must switch to flood mid-run. - let maxAttempts = 3 - let floodAfter = 2 - let service = MessageService( - session: session, - dataStore: dataStore, - contactService: nil, - config: MessageServiceConfig(maxAttempts: maxAttempts, floodAfter: floodAfter, minTimeout: 0) - ) - - let contact = ContactDTO.testContact(id: UUID(), radioID: testDeviceID) - let ackCode = Data([0xA1, 0xB2, 0xC3, 0xD4]) - - // Never emit the end-to-end ACK, so every attempt times out. Answer - // resetPath with OK and every contact query with "not found" so the flood - // switch and finalizeSend proceed without stalling on the session timeout. - let responder = Task { - var responded = 1 // app start already accounted for - while !Task.isCancelled { - let count = await transport.sentData.count - if count > responded { - responded = count - let newest = await transport.sentData.last - switch newest?.first { - case CommandCode.resetPath.rawValue: - await transport.simulateOK() - case CommandCode.getContactByKey.rawValue: - await transport.simulateReceive(Data([ResponseCode.error.rawValue])) - default: - var msgSent = Data([ResponseCode.messageSent.rawValue]) - msgSent.append(0) - msgSent.append(ackCode) - msgSent.append(uint32Bytes(10)) // ~12ms ack window - await transport.simulateReceive(msgSent) - } - } - await Task.yield() - } - } - defer { responder.cancel() } - - let sent = try await service.sendMessageWithRetry(text: "escalate me", to: contact) - #expect(sent.status == .sent) - - let sends = await transport.sentData - let resetIndex = sends.firstIndex { $0.first == CommandCode.resetPath.rawValue } - #expect(resetIndex != nil, - "the loop must escalate to flood via resetPath after config.floodAfter direct failures") - - if let resetIndex { - let directSendsBeforeReset = sends[.. (NodeConfigService, MockMeshCoreSession) { + let configuration = MockConfigurationSession(publicKey: selfPublicKey) + await configuration.setStubbedExportedPrivateKey(exportedPrivateKey) + let settings = SettingsService(session: configuration) + let mesh = MockMeshCoreSession() + await mesh.setStubbedContacts(deviceContacts) + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let channels = ChannelService(session: mesh, dataStore: store, rxLogService: nil) + let service = NodeConfigService( + session: mesh, settingsService: settings, + channelService: channels, dataStore: store, syncCoordinator: nil + ) + return (service, mesh) + } + + private func meshContact(name: String, publicKey: Data) -> MeshContact { + MeshContact( + id: publicKey.hexString, + publicKey: publicKey, + type: .chat, + flags: ContactFlags(rawValue: 0), + outPathLength: 0xFF, + outPath: Data(), + advertisedName: name, + lastAdvertisement: Date(timeIntervalSince1970: 0), + latitude: 0, + longitude: 0, + lastModified: Date(timeIntervalSince1970: 0) + ) + } + + private func fileContact(name: String, publicKey: String, lastModified: UInt32 = 0) -> MeshCoreNodeConfig.ContactConfig { + MeshCoreNodeConfig.ContactConfig( + type: 1, name: name, publicKey: publicKey, flags: 0, + latitude: "0", longitude: "0", lastAdvert: 0, lastModified: lastModified + ) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/NotificationStringProviderTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/NotificationStringProviderTests.swift index 65a91bb18a..f227a7272f 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/NotificationStringProviderTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/NotificationStringProviderTests.swift @@ -10,5 +10,6 @@ struct NotificationStringProviderTests { #expect(service.defaultDiscoveryTitle(for: .chat) == "New Contact Discovered") #expect(service.defaultDiscoveryTitle(for: .repeater) == "New Repeater Discovered") #expect(service.defaultDiscoveryTitle(for: .room) == "New Room Discovered") + #expect(service.defaultDiscoveryTitle(for: .sensor) == "New Sensor Discovered") } } diff --git a/MC1Services/Tests/MC1ServicesTests/Services/PersistentLoggerTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/PersistentLoggerTests.swift index 988b50f123..d8299d74a4 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/PersistentLoggerTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/PersistentLoggerTests.swift @@ -41,8 +41,20 @@ struct PersistentLoggerTests { .map(\.message) } + /// Pins collection on. `PersistentLogger` still skips `.debug` and persists `.info`. @Test func `debug does not persist and info does`() async { + let capturedValue = UserDefaults.standard.object(forKey: AppStorageKey.collectDebugLogs.rawValue) + UserDefaults.standard.set(true, forKey: AppStorageKey.collectDebugLogs.rawValue) + defer { + if let capturedValue { + UserDefaults.standard.set(capturedValue, forKey: AppStorageKey.collectDebugLogs.rawValue) + } else { + UserDefaults.standard.removeObject(forKey: AppStorageKey.collectDebugLogs.rawValue) + } + DebugLogBuffer.shared = nil + } + let store = MockPersistenceStore() let buffer = DebugLogBuffer(dataStore: store) @@ -63,7 +75,6 @@ struct PersistentLoggerTests { ) if messages.contains("info-line") { break } } - defer { DebugLogBuffer.shared = nil } #expect(!messages.contains("debug-line")) #expect(messages.contains("info-line")) diff --git a/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+Inline.swift b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+Inline.swift new file mode 100644 index 0000000000..dcc4827741 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+Inline.swift @@ -0,0 +1,99 @@ +@testable import MC1Services +import Testing + +extension PlainTextSendGateTests { + private enum AttemptPersistenceError: Error { + case unavailable + } + + @Test + func `quick reply is saved while it waits for admission and sends once the lease is free`() async throws { + let harness = try await RadioHarness(budget: .singleAttempt, senderKey: senderKey) + defer { harness.stop() } + let contact = try await harness.contact(byte: 0x41) + let handler = try quickReplyHandler(harness) + let owner = try await harness.gate.acquire() + let reply = Task { await handler.handler.handleQuickReply(contactID: contact.id, text: "from notification") } + defer { reply.cancel() } + try await waitUntil("quick reply is waiting for admission") { + await harness.gate.waiterCountForTesting == 1 + } + let sendsWhileHeld = await harness.sendCount() + #expect(sendsWhileHeld == 0) + let saved = try await harness.store.fetchMessages(contactID: contact.id, limit: 2, offset: 0) + #expect(saved.map(\.text) == ["from notification"]) + #expect(saved.first?.status == .pending) + await harness.gate.stopIssuing(owner) + try await waitUntil("quick reply sends after admission") { await harness.sendCount() == 1 } + await reply.value + let messageID = try #require(saved.first?.id) + #expect(try await harness.store.fetchMessage(id: messageID)?.status == .sent) + let ackOwner = try await harness.pendingRow(messageID) + #expect(ackOwner?.ackDeadline != nil) + #expect(ackOwner?.attemptCount == 1) + } + + @Test + func `an invalidated gate keeps a failed quick reply and offers a draft`() async throws { + let harness = try await RadioHarness(budget: .singleAttempt, senderKey: senderKey) + defer { harness.stop() } + let contact = try await harness.contact(byte: 0x42) + let handler = try quickReplyHandler(harness) + let owner = try await harness.gate.acquire() + let draft = Task { await handler.handler.handleQuickReply(contactID: contact.id, text: "saved draft") } + try await waitUntil("quick reply is waiting for admission") { + await harness.gate.waiterCountForTesting == 1 + } + #expect(await harness.sendCount() == 0) + await harness.gate.invalidate() + _ = owner + await draft.value + #expect(handler.notifications.consumeDraft(for: contact.id) == "saved draft") + let saved = try await harness.store.fetchMessages(contactID: contact.id, limit: 2, offset: 0) + #expect(saved.map(\.text) == ["saved draft"]) + #expect(saved.first?.status == .failed) + #expect(try await harness.store.fetchPendingSends(radioID: harness.radioID).isEmpty) + } + + @Test + func `a quick reply does not transmit when its attempt cannot be persisted`() async throws { + let harness = try await RadioHarness(budget: .default, senderKey: senderKey) + defer { harness.stop() } + let contact = try await harness.contact(byte: 0x47) + let handler = try quickReplyHandler(harness) + await harness.store.setPreparePendingSendAttemptFaultInjection { + throw AttemptPersistenceError.unavailable + } + + await handler.handler.handleQuickReply(contactID: contact.id, text: "saved after write failure") + + #expect(await harness.sendCount() == 0) + #expect(handler.notifications.consumeDraft(for: contact.id) == "saved after write failure") + let saved = try await harness.store.fetchMessages(contactID: contact.id, limit: 2, offset: 0) + #expect(saved.map(\.text) == ["saved after write failure"]) + #expect(saved.first?.status == .failed) + #expect(try await harness.store.fetchPendingSends(radioID: harness.radioID).isEmpty) + } + + @Test + func `deleting a saved inline dm while it waits prevents its send`() async throws { + let harness = try await RadioHarness(budget: .singleAttempt, senderKey: senderKey) + defer { harness.stop() } + let contact = try await harness.contact(byte: 0x43) + let owner = try await harness.gate.acquire() + let send = Task { try await harness.service.sendDirectMessage(text: "removed", to: contact) } + defer { send.cancel() } + try await waitUntil("the inline DM is waiting for admission") { + await harness.gate.waiterCountForTesting == 1 + } + let messages = try await harness.store.fetchMessages(contactID: contact.id, limit: 1, offset: 0) + let message = try #require(messages.first) + try await harness.store.deleteMessage(id: message.id) + await harness.gate.stopIssuing(owner) + + await #expect(throws: CancellationError.self) { try await send.value } + #expect(await harness.sendCount() == 0) + #expect(try await harness.store.fetchMessage(id: message.id) == nil) + #expect(try await harness.store.fetchPendingSends(radioID: harness.radioID).isEmpty) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+PartialSend.swift b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+PartialSend.swift new file mode 100644 index 0000000000..38609e11a8 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+PartialSend.swift @@ -0,0 +1,101 @@ +import Foundation +@testable import MC1Services +import os +import Testing + +extension PlainTextSendGateTests { + @Test + func `table full after acceptance ends the pass and keeps the accepted ack window`() async throws { + let ackWindow: TimeInterval = 2 + let script = RadioScript(senderKey: senderKey, suggestedTimeoutMs: { $0 == 4 ? 250 : 10 }, sendReply: { attempt, _ in + attempt == 5 ? .tableFull : .accepted + }) + let harness = try await partialSendHarness(script: script, ackGiveUpWindow: ackWindow) + defer { harness.stop() } + let contact = try await harness.contact(byte: 0xC1) + let message = try await harness.service.createPendingMessage(text: "partial acceptance", to: contact) + try await harness.queue.enqueueDM(DirectMessageEnvelope(messageID: message.id, contactID: contact.id)) + + try await waitUntil("the last accepted command is waiting for its ACK") { + await harness.service.pendingAckForTest(message.id)?.timeout == 0.3 + } + let acceptedAt = try #require(await harness.service.pendingAckForTest(message.id)?.sentAt) + try await waitUntil("the rejected command ends the wire pass") { + await !harness.queue.isDMDrainingForTesting + } + let owner = try #require(try await harness.pendingRow(message.id)) + #expect(owner.ackDeadline == acceptedAt.addingTimeInterval(ackWindow)) + + let earlierAck = try #require(script.codes().dropFirst().first) + await harness.service.handleAcknowledgement(code: earlierAck, tripTime: 25) + #expect(try await harness.store.fetchMessage(id: message.id)?.status == .delivered) + #expect(try await harness.pendingRow(message.id) == nil) + #expect(await harness.sendPackets().map { $0[2] } == [0, 1, 2, 3, 4, 5, 5, 5, 5]) + } + + @Test + func `an earlier ack during pool backoff prevents the next submission`() async throws { + let script = RadioScript(senderKey: senderKey, sendReply: { attempt, submission in + attempt == 5 && submission == 1 ? .tableFull : .accepted + }) + let harness = try await partialSendHarness(script: script, poolDelay: 0.2) + defer { harness.stop() } + let contact = try await harness.contact(byte: 0xC2) + let message = try await harness.service.createPendingMessage(text: "ack in backoff", to: contact) + try await harness.queue.enqueueDM(DirectMessageEnvelope(messageID: message.id, contactID: contact.id)) + try await waitUntil("the first attempt-5 command is on the wire") { await harness.sendCount() == 6 } + + let earlierAck = try #require(script.codes().dropFirst().first) + await harness.service.handleAcknowledgement(code: earlierAck, tripTime: 30) + try await waitUntil("delivery ends the wire pass") { await !harness.queue.isDMDrainingForTesting } + #expect(try await harness.store.fetchMessage(id: message.id)?.status == .delivered) + #expect(await harness.sendPackets().map { $0[2] } == [0, 1, 2, 3, 4, 5]) + } + + @Test + func `a timeout keeps the predicted ack from the last pool submission`() async throws { + let uncertainSubmission = OSAllocatedUnfairLock(initialState: nil) + let script = RadioScript(senderKey: senderKey, sendReply: { attempt, submission in + guard attempt == 2 else { return .accepted } + guard submission == 4 else { return .tableFull } + uncertainSubmission.withLock { $0 = Date() } + return .missing + }) + let ackWindow: TimeInterval = 1 + let schedulingTolerance: TimeInterval = 0.1 + let harness = try await partialSendHarness(script: script, ackGiveUpWindow: ackWindow, poolDelay: 0.2) + defer { harness.stop() } + let contact = try await harness.contact(byte: 0xC3) + let message = try await harness.service.createPendingMessage(text: "timeout after pool backoff", to: contact) + try await harness.queue.enqueueDM(DirectMessageEnvelope(messageID: message.id, contactID: contact.id)) + + try await waitUntil("the timed-out command ends the wire pass") { await !harness.queue.isDMDrainingForTesting } + let submittedAt = try #require(uncertainSubmission.withLock { $0 }) + let owner = try #require(try await harness.pendingRow(message.id)) + let deadline = try #require(owner.ackDeadline) + #expect(deadline >= submittedAt.addingTimeInterval(ackWindow - schedulingTolerance)) + let packets = await harness.sendPackets() + #expect(packets.map { $0[2] } == [0, 1, 2, 2, 2, 2]) + let uncertainPacket = try #require(packets.last) + await harness.service.handleAcknowledgement( + code: expectedAck(packet: uncertainPacket, text: message.text, sender: senderKey), tripTime: 90 + ) + #expect(try await harness.store.fetchMessage(id: message.id)?.status == .delivered) + } + + func partialSendHarness( + script: RadioScript, + ackGiveUpWindow: TimeInterval = 2, + poolDelay: TimeInterval = 0.002 + ) async throws -> RadioHarness { + try await RadioHarness( + budget: .default, + senderKey: senderKey, + ackGiveUpWindow: ackGiveUpWindow, + poolBackoff: PoolBackoffConfig(baseDelay: poolDelay, exponentBase: 1, jitterRange: 1...1), + commandTimeout: 0.2, + transportWaitTimeout: 0.05, + script: script + ) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+PartialSendPersistence.swift b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+PartialSendPersistence.swift new file mode 100644 index 0000000000..6899ea01b1 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+PartialSendPersistence.swift @@ -0,0 +1,100 @@ +import Foundation +@testable import MC1Services +import os +import Testing + +extension PlainTextSendGateTests { + @Test(arguments: [MessageStatus.delivered, .failed]) + func `a failed owner save resolves the accepted dm without replay`(outcome: MessageStatus) async throws { + let ackWindow: TimeInterval = 0.4 + let script = RadioScript(senderKey: senderKey, sendReply: { attempt, _ in + attempt == 1 ? .tableFull : .accepted + }) + let harness = try await partialSendHarness(script: script, ackGiveUpWindow: ackWindow) + defer { harness.stop() } + let failedSave = await failFirstOwnerSave(harness) + let contact = try await harness.contact(byte: 0xD1) + let message = try await harness.service.createPendingMessage(text: "owner write failure", to: contact) + try await harness.queue.enqueueDM(DirectMessageEnvelope(messageID: message.id, contactID: contact.id)) + try await waitUntil("the failed owner conversion ends the wire pass") { + await !harness.queue.isDMDrainingForTesting && failedSave.withLock { $0 } + } + let original = try #require(try await harness.pendingRow(message.id)) + #expect(original.ackDeadline == nil) + + if outcome == .delivered { + let ack = try #require(script.codes().first) + await harness.service.handleAcknowledgement(code: ack, tripTime: 50) + } else { + let tracking = try #require(await harness.service.pendingAckForTest(message.id)) + let deadline = tracking.sentAt.addingTimeInterval(max(ackWindow, tracking.timeout)) + try await waitUntil("the original ACK deadline expires") { Date() > deadline } + } + try await harness.service.checkExpiredAcks() + #expect(try await harness.store.fetchMessage(id: message.id)?.status == outcome) + #expect(try await harness.pendingRow(message.id) == nil) + #expect(await harness.gate.ownerLeaseIDForTesting == nil) + #expect(await harness.sendPackets().map { $0[2] } == [0, 1, 1, 1, 1]) + } + + @Test + func `a deferred owner save leaves a replacement manual retry untouched`() async throws { + let script = RadioScript(senderKey: senderKey, sendReply: { attempt, _ in + attempt == 1 ? .tableFull : .accepted + }) + let harness = try await partialSendHarness(script: script) + defer { harness.stop() } + let failedSave = await failFirstOwnerSave(harness) + let contact = try await harness.contact(byte: 0xD2) + let message = try await harness.service.createPendingMessage(text: "replacement retry", to: contact) + let envelope = DirectMessageEnvelope(messageID: message.id, contactID: contact.id) + try await harness.queue.enqueueDM(envelope) + try await waitUntil("the failed owner conversion ends the wire pass") { + await !harness.queue.isDMDrainingForTesting && failedSave.withLock { $0 } + } + _ = try await harness.store.replacePendingSendForRetry( + messageID: message.id, dto: PendingSendDTO(envelope: envelope, radioID: harness.radioID) + ) + let replacement = try #require(try await harness.pendingRow(message.id)) + + try await harness.service.checkExpiredAcks() + #expect(try await harness.pendingRow(message.id) == replacement) + #expect(try await harness.store.fetchMessage(id: message.id)?.status == .pending) + #expect(await harness.gate.ownerLeaseIDForTesting == nil) + } + + @Test + func `an inline send keeps its row when the ack owner save fails`() async throws { + let script = RadioScript(senderKey: senderKey) + let harness = try await partialSendHarness(script: script) + defer { harness.stop() } + _ = await failFirstOwnerSave(harness) + let contact = try await harness.contact(byte: 0xD3) + let message = try await harness.service.sendDirectMessage(text: "inline owner failure", to: contact) + let row = try #require(try await harness.pendingRow(message.id)) + #expect(row.ackDeadline == nil) + + let ack = try #require(script.codes().first) + await harness.service.handleAcknowledgement(code: ack, tripTime: 80) + try await harness.service.checkExpiredAcks() + #expect(try await harness.store.fetchMessage(id: message.id)?.status == .delivered) + #expect(try await harness.pendingRow(message.id) == nil) + #expect(await harness.sendCount() == 1) + } + + private func failFirstOwnerSave(_ harness: RadioHarness) async -> OSAllocatedUnfairLock { + let failed = OSAllocatedUnfairLock(initialState: false) + await harness.store.setSavePendingAcknowledgementFaultInjection { + try failed.withLock { didFail in + guard !didFail else { return } + didFail = true + throw OwnerSaveError.injected + } + } + return failed + } + + private enum OwnerSaveError: Error { + case injected + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+Queue.swift b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+Queue.swift new file mode 100644 index 0000000000..e9fb0c286f --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+Queue.swift @@ -0,0 +1,165 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +extension PlainTextSendGateTests { + @Test + func `queued exhaustion keeps the next dm off the wire until ack or expiry`() async throws { + let harness = try await RadioHarness(budget: .default, senderKey: senderKey) + defer { harness.stop() } + await harness.service.startEventMonitoring() + let contactA = try await harness.contact(byte: 0x71) + let contactB = try await harness.contact(byte: 0x72) + let messageA = try await harness.service.createPendingMessage(text: "alpha", to: contactA) + let messageB = try await harness.service.createPendingMessage(text: "beta", to: contactB) + try await harness.queue.enqueueDM(DirectMessageEnvelope(messageID: messageA.id, contactID: contactA.id)) + try await harness.queue.enqueueDM(DirectMessageEnvelope(messageID: messageB.id, contactID: contactB.id)) + try await waitUntil("A spends 4 and 4 and B is waiting") { + await harness.isWaiting(afterSends: 8) + } + #expect(harness.script.codes().count == 8) + let pendingB = try await harness.pendingRow(messageB.id) + #expect(pendingB?.attemptCount == 0) + #expect(try await harness.store.fetchMessage(id: messageB.id)?.status == .pending) + + let attemptZero = try #require(harness.script.codes().first) + await harness.session.dispatchForTesting(.acknowledgement(code: attemptZero, tripTime: 20)) + try await waitUntil("A is delivered and B then sends") { + let delivered = try await harness.store.fetchMessage(id: messageA.id)?.status == .delivered + let sends = await harness.sendCount() + return delivered && sends > 8 + } + #expect(try await harness.store.fetchMessage(id: messageB.id)?.status != .delivered) + } + + @Test + func `queued exhaustion fails A on the expiry path before B can send`() async throws { + let harness = try await RadioHarness(budget: .default, senderKey: senderKey, ackGiveUpWindow: 0) + defer { harness.stop() } + let contactA = try await harness.contact(byte: 0x81) + let contactB = try await harness.contact(byte: 0x82) + let messageA = try await harness.service.createPendingMessage(text: "expire-a", to: contactA) + let messageB = try await harness.service.createPendingMessage(text: "expire-b", to: contactB) + try await harness.queue.enqueueDM(DirectMessageEnvelope(messageID: messageA.id, contactID: contactA.id)) + try await harness.queue.enqueueDM(DirectMessageEnvelope(messageID: messageB.id, contactID: contactB.id)) + try await waitUntil("A is exhausted and B is waiting") { + await harness.isWaiting(afterSends: 8) + } + try await waitUntil("A's give-up deadline has elapsed") { + guard let tracking = await harness.service.pendingAckForTest(messageA.id) else { return false } + let deadline = tracking.owner?.deadline ?? tracking.sentAt + return Date() > deadline + } + try await harness.service.checkExpiredAcks() + try await waitUntil("expiry fails A and then admits B") { + let failed = try await harness.store.fetchMessage(id: messageA.id)?.status == .failed + let sends = await harness.sendCount() + return failed && sends > 8 + } + } + + @Test + func `identical text at 1 and 0 delivers only the admitted dm`() async throws { + let harness = try await RadioHarness(budget: .singleAttempt, senderKey: senderKey) + defer { harness.stop() } + await harness.service.startEventMonitoring() + let contactA = try await harness.contact(byte: 0x91) + let contactB = try await harness.contact(byte: 0x92) + let messageA = try await harness.service.createPendingMessage(text: "same", to: contactA) + let messageB = try await harness.service.createPendingMessage(text: "same", to: contactB) + try await harness.queue.enqueueDM(DirectMessageEnvelope(messageID: messageA.id, contactID: contactA.id)) + try await harness.queue.enqueueDM(DirectMessageEnvelope(messageID: messageB.id, contactID: contactB.id)) + try await waitUntil("A finished its single attempt and B is waiting") { + await harness.isWaiting(afterSends: 1) + } + #expect(try await harness.store.fetchMessage(id: messageB.id)?.status == .pending) + #expect(try await harness.pendingRow(messageB.id)?.attemptCount == 0) + let code = try #require(harness.script.codes().first) + await harness.session.dispatchForTesting(.acknowledgement(code: code, tripTime: 11)) + try await waitUntil("A is delivered") { + try await harness.store.fetchMessage(id: messageA.id)?.status == .delivered + } + #expect(try await harness.store.fetchMessage(id: messageB.id)?.status != .delivered) + try await waitUntil("B sends only after A's ack") { await harness.sendCount() > 1 } + #expect(try await harness.store.fetchMessage(id: messageB.id)?.status != .delivered) + } + + @Test(arguments: [false, true]) + func `retiring a waiting dm leaves its row and a fresh queue can send it`(invalidateFirst: Bool) async throws { + let harness = try await RadioHarness(budget: .singleAttempt, senderKey: senderKey) + defer { harness.stop() } + await harness.service.startEventMonitoring() + let contactA = try await harness.contact(byte: 0xA1) + let contactB = try await harness.contact(byte: 0xA2) + let messageA = try await harness.service.createPendingMessage(text: "owner", to: contactA) + let messageB = try await harness.service.createPendingMessage(text: "queued", to: contactB) + try await harness.queue.enqueueDM(DirectMessageEnvelope(messageID: messageA.id, contactID: contactA.id)) + try await harness.queue.enqueueDM(DirectMessageEnvelope(messageID: messageB.id, contactID: contactB.id)) + try await waitUntil("B is blocked on the gate") { + await harness.isWaiting(afterSends: 1) + } + let attemptCount = try await harness.pendingRow(messageB.id)?.attemptCount + if invalidateFirst { + await harness.gate.invalidate() + await harness.queue.awaitDrainCompletion() + #expect(await harness.queue.isDMDrainingForTesting == false) + } + await harness.queue.shutdown() + let afterCancel = try await harness.pendingRow(messageB.id) + #expect(afterCancel?.attemptCount == attemptCount) + #expect(try await harness.store.fetchMessage(id: messageB.id)?.status == .pending) + + let code = try #require(harness.script.codes().first) + await harness.session.dispatchForTesting(.acknowledgement(code: code, tripTime: 8)) + try await waitUntil("the owner still reaches delivered") { + try await harness.store.fetchMessage(id: messageA.id)?.status == .delivered + } + + let freshGate = PlainTextSendGate() + let freshService = MessageService( + session: harness.session, + dataStore: harness.store, + contactService: nil, + dmSendBudget: { .singleAttempt }, + plainTextSendGate: freshGate + ) + let freshQueue = ChatSendQueueService( + radioID: harness.radioID, + dataStore: harness.store, + messageService: freshService, + channelService: harness.channelService, + reactionService: ReactionService(), + plainTextSendGate: freshGate + ) + await freshQueue.hydrate() + try await waitUntil("the fresh queue sends the persisted dm") { await harness.sendCount() > 1 } + await freshQueue.shutdown() + } + + @Test + func `clearing a waiting dm sends no command after it is admitted`() async throws { + let harness = try await RadioHarness(budget: .singleAttempt, senderKey: senderKey) + defer { harness.stop() } + await harness.service.startEventMonitoring() + let contactA = try await harness.contact(byte: 0xB1) + let contactB = try await harness.contact(byte: 0xB2) + let messageA = try await harness.service.createPendingMessage(text: "keep", to: contactA) + let messageB = try await harness.service.createPendingMessage(text: "cleared", to: contactB) + try await harness.queue.enqueueDM(DirectMessageEnvelope(messageID: messageA.id, contactID: contactA.id)) + try await harness.queue.enqueueDM(DirectMessageEnvelope(messageID: messageB.id, contactID: contactB.id)) + try await waitUntil("B is waiting") { + await harness.isWaiting(afterSends: 1) + } + try await harness.store.deletePendingSendsForMessage(messageID: messageB.id) + let code = try #require(harness.script.codes().first) + await harness.session.dispatchForTesting(.acknowledgement(code: code, tripTime: 6)) + try await waitUntil("A is delivered and the queue finishes") { + let delivered = try await harness.store.fetchMessage(id: messageA.id)?.status == .delivered + let waiting = await harness.gate.waiterCountForTesting + return delivered && waiting == 0 + } + try await Task.sleep(for: .milliseconds(50)) + #expect(await harness.sendCount() == 1) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+RadioHarness.swift b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+RadioHarness.swift new file mode 100644 index 0000000000..74409196b4 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+RadioHarness.swift @@ -0,0 +1,144 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import MeshCoreTestSupport + +extension PlainTextSendGateTests { + @MainActor + final class RadioHarness { + let transport: MockTransport + let session: MeshCoreSession + let store: PersistenceStore + let gate: PlainTextSendGate + let service: MessageService + let queue: ChatSendQueueService + let channelService: ChannelService + let roomService: RoomServerService + let remoteNodeService: RemoteNodeService + let radioID: UUID + let script: RadioScript + private let responder: Task + + init( + budget: DMSendBudget, + senderKey: Data, + ackGiveUpWindow: TimeInterval = 30, + poolBackoff: PoolBackoffConfig = .default, + commandTimeout: TimeInterval = 10, + transportWaitTimeout: TimeInterval = 30, + script: RadioScript? = nil + ) async throws { + let transport = MockTransport() + let session = MeshCoreSession(transport: transport, configuration: SessionConfiguration(defaultTimeout: commandTimeout)) + let start = Task { try await session.start() } + try await waitUntil("session should send app start") { await transport.sentData.count == 1 } + await transport.simulateReceive(Self.selfInfo(publicKey: senderKey)) + try await start.value + + let radioID = UUID() + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + try await store.saveDevice(.testDevice(radioID: radioID, publicKey: senderKey)) + let gate = PlainTextSendGate() + let service = MessageService( + session: session, + dataStore: store, + contactService: nil, + config: MessageServiceConfig(minTimeout: 0, ackGiveUpWindow: ackGiveUpWindow, poolBackoff: poolBackoff), + dmSendBudget: { budget }, + plainTextSendGate: gate + ) + let channelService = ChannelService(session: session, dataStore: store, rxLogService: nil) + let queue = ChatSendQueueService( + radioID: radioID, + dataStore: store, + messageService: service, + channelService: channelService, + reactionService: ReactionService(), + config: ChatSendQueueConfig(transportWaitTimeout: transportWaitTimeout), + plainTextSendGate: gate + ) + let remote = RemoteNodeService( + session: session, + dataStore: store, + keychainService: KeychainService() + ) + let roomService = RoomServerService( + session: session, + remoteNodeService: remote, + dataStore: store, + radioID: radioID, + plainTextSendGate: gate + ) + let script = script ?? RadioScript() + self.transport = transport + self.session = session + self.store = store + self.gate = gate + self.service = service + self.queue = queue + self.channelService = channelService + self.roomService = roomService + remoteNodeService = remote + self.radioID = radioID + self.script = script + responder = Task { await script.answer(transport) } + } + + func stop() { + responder.cancel() + Task { + await session.stop() + await queue.shutdown() + await service.stopEventMonitoring() + } + } + + func contact(byte: UInt8) async throws -> ContactDTO { + let contact = ContactDTO.testContact(radioID: radioID, publicKey: Data(repeating: byte, count: 32)) + try await store.saveContact(contact) + return contact + } + + func sendPackets() async -> [Data] { + await transport.sentData.filter { $0.first == CommandCode.sendMessage.rawValue } + } + + func sendCount() async -> Int { + await sendPackets().count + } + + func isWaiting(afterSends expected: Int) async -> Bool { + let sends = await sendCount() + let waiting = await gate.waiterCountForTesting + return sends == expected && waiting == 1 + } + + func channelCount() async -> Int { + await transport.sentData.count { $0.first == CommandCode.sendChannelMessage.rawValue } + } + + func resetIndex() async -> Int? { + let packets = await transport.sentData + guard let index = packets.firstIndex(where: { $0.first == CommandCode.resetPath.rawValue }) else { return nil } + return packets[.. PendingSendDTO? { + try await store.fetchPendingSends(radioID: radioID).first { $0.messageID == messageID } + } + + private static func selfInfo(publicKey: Data) -> Data { + var payload = Data([1, 22, 22]) + payload.append(publicKey) + payload.append(Data(repeating: 0, count: 8)) + payload.append(contentsOf: [0, 0, 0]) + payload.append(contentsOf: withUnsafeBytes(of: UInt32(915_000).littleEndian) { Array($0) }) + payload.append(contentsOf: withUnsafeBytes(of: UInt32(125_000).littleEndian) { Array($0) }) + payload.append(contentsOf: [7, 5]) + payload.append(contentsOf: "Test".utf8) + var packet = Data([ResponseCode.selfInfo.rawValue]) + packet.append(payload) + return packet + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+RadioScript.swift b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+RadioScript.swift new file mode 100644 index 0000000000..1674e5a551 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+RadioScript.swift @@ -0,0 +1,103 @@ +import Foundation +@testable import MC1Services +import MeshCore +import MeshCoreTestSupport +import os + +extension PlainTextSendGateTests { + final class RadioScript: @unchecked Sendable { + enum SendReply { + case accepted + case tableFull + case missing + } + + private let hold = OSAllocatedUnfairLock(initialState: false) + private let table = OSAllocatedUnfairLock(initialState: [Data]()) + private let senderKey: Data? + private let sendReply: @Sendable (UInt8, Int) -> SendReply + private let suggestedTimeoutMs: @Sendable (UInt8) -> UInt32 + + init( + senderKey: Data? = nil, + suggestedTimeoutMs: @escaping @Sendable (UInt8) -> UInt32 = { _ in 10 }, + sendReply: @escaping @Sendable (UInt8, Int) -> SendReply = { _, _ in .accepted } + ) { + self.senderKey = senderKey + self.sendReply = sendReply + self.suggestedTimeoutMs = suggestedTimeoutMs + } + + func holdSendMessages(_ held: Bool) { + hold.withLock { $0 = held } + } + + func codes() -> [Data] { + table.withLock { $0 } + } + + func answer(_ transport: MockTransport) async { + var responded = 1 + var submissions: [UInt8: Int] = [:] + while !Task.isCancelled { + let packets = await transport.sentData + guard packets.count > responded else { + try? await Task.sleep(for: .milliseconds(2)) + continue + } + var cursor = responded + var paused = false + for packet in packets[responded...] { + if packet.first == CommandCode.sendMessage.rawValue, hold.withLock({ $0 }) { + paused = true + break + } + switch packet.first { + case CommandCode.sendMessage.rawValue: + let attempt = packet.count > 2 ? packet[2] : 0 + submissions[attempt, default: 0] += 1 + switch sendReply(attempt, submissions[attempt, default: 0]) { + case .tableFull: + await transport.simulateReceive(Data([ + ResponseCode.error.rawValue, FirmwareDeviceErrorCode.directMessageTableFull + ])) + case .missing: + break + case .accepted: + let derivedAck = senderKey.map { expectedAck(packet, senderKey: $0) } + let code = table.withLock { slots -> Data in + let sequence = UInt8(truncatingIfNeeded: slots.count) + let ack = derivedAck ?? Data([attempt, sequence, 0x22, 0x33]) + if slots.count == 8 { slots.removeFirst() } + slots.append(ack) + return ack + } + var frame = Data([ResponseCode.messageSent.rawValue, 0]) + frame.append(code) + frame.append(contentsOf: withUnsafeBytes(of: suggestedTimeoutMs(attempt).littleEndian) { Array($0) }) + await transport.simulateReceive(frame) + } + case CommandCode.getContactByKey.rawValue: + await transport.simulateReceive(Data([ResponseCode.error.rawValue])) + default: + await transport.simulateOK() + } + cursor += 1 + } + responded = paused ? cursor : packets.count + if paused { try? await Task.sleep(for: .milliseconds(2)) } + } + } + + private func expectedAck(_ packet: Data, senderKey: Data) -> Data { + let timestamp = UInt32(packet[3]) | (UInt32(packet[4]) << 8) + | (UInt32(packet[5]) << 16) | (UInt32(packet[6]) << 24) + return AckCodeBuilder.expectedAck( + timestamp: timestamp, + attempt: packet[2], + text: String(decoding: packet.dropFirst(13), as: UTF8.self), + senderPublicKey: senderKey + ) + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+Recovery.swift b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+Recovery.swift new file mode 100644 index 0000000000..ddde51f401 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+Recovery.swift @@ -0,0 +1,205 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import os +import Testing + +extension PlainTextSendGateTests { + @Test + func `a quick reply waiting for admission restarts from its pending send and transmits once`() async throws { + let harness = try await RadioHarness(budget: .singleAttempt, senderKey: senderKey) + defer { harness.stop() } + let contact = try await harness.contact(byte: 0x44) + let handler = try quickReplyHandler(harness) + let owner = try await harness.gate.acquire() + let reply = Task { await handler.handler.handleQuickReply(contactID: contact.id, text: "from notification") } + var recoveryQueue: ChatSendQueueService? + var replayQueue: ChatSendQueueService? + func finish() async { + await recoveryQueue?.shutdown() + await replayQueue?.shutdown() + reply.cancel() + await harness.gate.invalidate() + await reply.value + } + + do { + try await waitUntil("quick reply is waiting with a recoverable send") { + guard await harness.gate.waiterCountForTesting == 1, await harness.gate.ownerLeaseIDForTesting == owner.id else { return false } + let messages = try await harness.store.fetchMessages(contactID: contact.id, limit: 2, offset: 0) + guard let message = messages.first, message.text == "from notification", message.status == .pending else { + return false + } + let row = try await harness.pendingRow(message.id) + return row?.ackDeadline == nil && row?.attemptCount == 0 && row?.isResend == false + } + #expect(await harness.sendCount() == 0) + let messageID = try #require( + try await harness.store.fetchMessages(contactID: contact.id, limit: 1, offset: 0).first?.id + ) + let saved = try #require(try await harness.pendingRow(messageID)) + #expect(saved.contactID == contact.id) + + let recovery = makeRestartedQueue(harness) + recoveryQueue = recovery + await recovery.hydrate() + try await waitUntil("the restarted queue transmits the saved reply") { + await harness.sendCount() == 1 + } + await recovery.awaitDrainCompletion() + #expect(await harness.gate.waiterCountForTesting == 1) + #expect(await harness.gate.ownerLeaseIDForTesting == owner.id) + #expect(await harness.sendCount() == 1) + #expect(await harness.resetIndex() == nil) + #expect(try await harness.store.fetchMessage(id: messageID)?.status == .sent) + #expect(try await harness.store.fetchMessage(id: messageID)?.text == "from notification") + #expect(try await harness.pendingRow(messageID)?.ackDeadline != nil) + #expect(handler.notifications.consumeDraft(for: contact.id) == nil) + + let replay = makeRestartedQueue(harness) + replayQueue = replay + await replay.hydrate() + await replay.awaitDrainCompletion() + #expect(await harness.sendCount() == 1) + #expect(await harness.gate.waiterCountForTesting == 1) + await finish() + } catch { + await finish() + throw error + } + } + + @Test + func `an accepted quick reply restarts with the same timestamp and one attempt`() async throws { + let harness = try await RadioHarness(budget: .default, senderKey: senderKey) + defer { harness.stop() } + let contact = try await harness.contact(byte: 0x45) + let handler = try quickReplyHandler(harness) + let accepted = OSAllocatedUnfairLock(initialState: false) + let (acceptanceEvents, acceptanceContinuation) = AsyncStream.makeStream() + await harness.service.setInlineSendAcceptedGateForTesting { + accepted.withLock { $0 = true } + for await _ in acceptanceEvents {} + } + harness.script.holdSendMessages(true) + let reply = Task { await handler.handler.handleQuickReply(contactID: contact.id, text: "accepted reply") } + var recoveryQueue: ChatSendQueueService? + var replayQueue: ChatSendQueueService? + func finish() async { + await recoveryQueue?.shutdown() + await replayQueue?.shutdown() + harness.script.holdSendMessages(false) + reply.cancel() + acceptanceContinuation.finish() + await harness.gate.invalidate() + await reply.value + } + + do { + try await waitUntil("the reply command is on the wire") { + await harness.sendCount() == 1 + } + let originalPacket = try #require(await harness.sendPackets().first) + let originalTimestamp = wireTimestamp(originalPacket) + let messageID = try #require( + try await harness.store.fetchMessages(contactID: contact.id, limit: 1, offset: 0).first?.id + ) + let pending = try #require(try await harness.pendingRow(messageID)) + #expect((pending.attemptCount ?? 0) >= 1) + #expect(pending.ackDeadline == nil) + #expect(await harness.sendCount() == 1) + + harness.script.holdSendMessages(false) + try await waitUntil("the radio accepted the reply before ACK persistence") { + accepted.withLock { $0 } + } + #expect(try await harness.pendingRow(messageID)?.ackDeadline == nil) + try await waitUntil("recovery starts in a later timestamp second") { + UInt32(Date().timeIntervalSince1970) > originalTimestamp + } + let recovery = makeRestartedQueue(harness) + recoveryQueue = recovery + await recovery.hydrate() + await recovery.awaitDrainCompletion() + + let packets = await harness.sendPackets() + #expect(packets.count == 2) + #expect(packets.map(wireTimestamp) == [originalTimestamp, originalTimestamp]) + #expect(await harness.resetIndex() == nil) + #expect(try await harness.store.fetchMessage(id: messageID)?.status == .sent) + #expect(try await harness.pendingRow(messageID)?.ackDeadline != nil) + #expect(handler.notifications.consumeDraft(for: contact.id) == nil) + + let replay = makeRestartedQueue(harness) + replayQueue = replay + await replay.hydrate() + await replay.awaitDrainCompletion() + #expect(await harness.sendCount() == 2) + await finish() + } catch { + await finish() + throw error + } + } + + @Test(arguments: [MessageStatus.delivered, .failed]) + func `a terminal quick reply is not replayed before its pending send is cleaned up`( + status: MessageStatus + ) async throws { + let harness = try await RadioHarness(budget: .default, senderKey: senderKey) + defer { harness.stop() } + let contact = try await harness.contact(byte: 0x46) + let handler = try quickReplyHandler(harness) + let accepted = OSAllocatedUnfairLock(initialState: false) + let (acceptanceEvents, acceptanceContinuation) = AsyncStream.makeStream() + await harness.service.setInlineSendAcceptedGateForTesting { + accepted.withLock { $0 = true } + for await _ in acceptanceEvents {} + } + let text = "terminal reply" + let reply = Task { await handler.handler.handleQuickReply(contactID: contact.id, text: text) } + var recoveryQueue: ChatSendQueueService? + func finish() async { + await recoveryQueue?.shutdown() + reply.cancel() + acceptanceContinuation.finish() + await harness.gate.invalidate() + await reply.value + } + + do { + try await waitUntil("the radio accepted the reply before ACK persistence") { + accepted.withLock { $0 } + } + let packet = try #require(await harness.sendPackets().first) + let messageID = try #require( + try await harness.store.fetchMessages(contactID: contact.id, limit: 1, offset: 0).first?.id + ) + if status == .delivered { + await harness.service.handleAcknowledgement( + code: expectedAck(packet: packet, text: text, sender: senderKey), + tripTime: 10 + ) + } else { + try await harness.store.updateMessageStatus(id: messageID, status: status) + } + #expect(try await harness.store.fetchMessage(id: messageID)?.status == status) + let pending = try #require(try await harness.pendingRow(messageID)) + #expect(pending.ackDeadline == nil) + + let recovery = makeRestartedQueue(harness) + recoveryQueue = recovery + await recovery.hydrate() + await recovery.awaitDrainCompletion() + + #expect(await harness.sendCount() == 1) + #expect(await harness.resetIndex() == nil) + #expect(try await harness.store.fetchMessage(id: messageID)?.status == status) + #expect(try await harness.pendingRow(messageID) == nil) + await finish() + } catch { + await finish() + throw error + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+Rooms.swift b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+Rooms.swift new file mode 100644 index 0000000000..bdfca4f57b --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+Rooms.swift @@ -0,0 +1,172 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +extension PlainTextSendGateTests { + @Test + func `room posts keep the room budget and a channel send proceeds during a dm hold`() async throws { + let harness = try await RadioHarness(budget: .singleAttempt, senderKey: senderKey) + defer { harness.stop() } + let contact = try await harness.contact(byte: 0x51) + let accepted = try await harness.service.sendDirectMessage(text: "holding", to: contact) + #expect(accepted.status == .sent) + let sendsWhileHeld = await harness.sendCount() + + let channel = Task { + try await harness.service.sendChannelMessage(text: "channel", channelIndex: 0, radioID: harness.radioID) + } + try await waitUntil("a channel send proceeds while the dm lease is held") { + await harness.channelCount() == 1 + } + #expect(await harness.sendCount() == sendsWhileHeld) + _ = try await channel.value + + let roomSession = RemoteNodeSessionDTO( + radioID: harness.radioID, + publicKey: Data(repeating: 0x61, count: 32), + name: "Room", + role: .roomServer, + permissionLevel: .readWrite + ) + try await harness.store.saveRemoteNodeSessionDTO(roomSession) + _ = try await harness.roomService.postMessage(sessionID: roomSession.id, text: "post") + try await waitUntil("the room post waits for the dm lease") { + await harness.gate.waiterCountForTesting == 1 + } + #expect(await harness.sendCount() == sendsWhileHeld) + + let code = try #require(harness.script.codes().first) + await harness.service.startEventMonitoring() + await harness.service.waitForSubscriberCount(1) + await harness.session.dispatchForTesting(.acknowledgement(code: code, tripTime: 9)) + try await waitUntil("the room post sends after the dm ack") { + await harness.sendCount() > sendsWhileHeld + } + + let limits = try await RadioHarness(budget: .singleAttempt, senderKey: senderKey) + defer { limits.stop() } + let limitSession = RemoteNodeSessionDTO( + radioID: limits.radioID, + publicKey: Data(repeating: 0x62, count: 32), + name: "Limits", + role: .roomServer, + permissionLevel: .admin + ) + try await limits.store.saveRemoteNodeSessionDTO(limitSession) + _ = try await limits.roomService.postMessage(sessionID: limitSession.id, text: "limits") + try await waitUntil("the room post finishes its own budget") { + let messages = try await limits.store.fetchRoomMessages(sessionID: limitSession.id) + return messages.contains { $0.status == .sent || $0.status == .delivered } + } + let roomPackets = await limits.sendPackets() + #expect(roomPackets.count == 5) + let resetAt = await limits.resetIndex() + #expect(resetAt == 4) + + let failed = RoomMessageDTO( + sessionID: limitSession.id, + authorKeyPrefix: Data(repeating: 0, count: 4), + text: "retry", + timestamp: 10, + isFromSelf: true, + status: .failed + ) + try await limits.store.saveRoomMessage(failed) + _ = try await limits.roomService.retryMessage(id: failed.id) + let afterRetry = await limits.sendPackets().count + #expect(afterRetry == 10) + } + + @Test + func `room posts queued together have distinct timestamps and keep them across attempts`() async throws { + let harness = try await RadioHarness(budget: .singleAttempt, senderKey: senderKey) + defer { harness.stop() } + let room = RemoteNodeSessionDTO( + radioID: harness.radioID, + publicKey: Data(repeating: 0x63, count: 32), + name: "Room", + role: .roomServer, + permissionLevel: .readWrite + ) + try await harness.store.saveRemoteNodeSessionDTO(room) + + let owner = try await harness.gate.acquire() + let first = try await harness.roomService.postMessage(sessionID: room.id, text: "First") + try await waitUntil("the first post is queued") { + await harness.gate.waiterCountForTesting == 1 + } + let second = try await harness.roomService.postMessage(sessionID: room.id, text: "Second") + try await waitUntil("the second post is queued") { + await harness.gate.waiterCountForTesting == 2 + } + + // Give both sends a full wall-clock second in which to reproduce a timestamp collision. + let now = Date().timeIntervalSince1970 + try await Task.sleep(for: .seconds(now.rounded(.down) + 1 - now)) + await harness.gate.stopIssuing(owner) + try await waitUntil("both posts finish sending") { + let messages = try await harness.store.fetchRoomMessages(sessionID: room.id) + return messages.count { $0.status == .sent } == 2 + } + + let timestamps = await harness.sendPackets().map(wireTimestamp) + #expect(timestamps.count == 10) + let firstTimestamp = try #require(timestamps.first) + let secondTimestamp = try #require(timestamps.last) + #expect(firstTimestamp < secondTimestamp) + #expect(timestamps.prefix(5).allSatisfy { $0 == firstTimestamp }) + #expect(timestamps.suffix(5).allSatisfy { $0 == secondTimestamp }) + #expect(try await harness.store.fetchRoomMessage(id: first.id)?.timestamp == first.timestamp) + #expect(try await harness.store.fetchRoomMessage(id: second.id)?.timestamp == second.timestamp) + } + + @Test(arguments: [false, true]) + func `room send queued before logout fails without sending`(isRetry: Bool) async throws { + let harness = try await RadioHarness(budget: .singleAttempt, senderKey: senderKey) + defer { harness.stop() } + let room = RemoteNodeSessionDTO( + radioID: harness.radioID, + publicKey: Data(repeating: 0x64, count: 32), + name: "Room", + role: .roomServer, + isConnected: true, + permissionLevel: .readWrite + ) + try await harness.store.saveRemoteNodeSessionDTO(room) + + let owner = try await harness.gate.acquire() + let message: RoomMessageDTO + let retry: Task? + if isRetry { + message = RoomMessageDTO( + sessionID: room.id, + authorKeyPrefix: senderKey.prefix(4), + text: "Retry", + timestamp: 10, + isFromSelf: true, + status: .failed + ) + try await harness.store.saveRoomMessage(message) + retry = Task { [id = message.id] in try await harness.roomService.retryMessage(id: id) } + } else { + message = try await harness.roomService.postMessage(sessionID: room.id, text: "Post") + retry = nil + } + try await waitUntil("the room send is parked") { + await harness.gate.waiterCountForTesting == 1 + } + try await harness.remoteNodeService.logout(sessionID: room.id) + await harness.gate.stopIssuing(owner) + + if let retry { + #expect(try await retry.value.status == .failed) + } else { + try await waitUntil("the queued post finishes") { + try await harness.store.fetchRoomMessage(id: message.id)?.status != .pending + } + #expect(try await harness.store.fetchRoomMessage(id: message.id)?.status == .failed) + } + #expect(await harness.sendCount() == 0) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests.swift new file mode 100644 index 0000000000..219fde7d7a --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests.swift @@ -0,0 +1,148 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import MeshCoreTestSupport +import Testing + +@Suite("Plain-text send admission") +@MainActor +struct PlainTextSendGateTests { + let senderKey = Data(repeating: 0xAB, count: 32) + + @Test + func `invalidate cancels a waiter and a monitoring pause keeps the lease`() async throws { + let transport = MockTransport() + let session = MeshCoreSession(transport: transport) + let container = try await ServiceContainer.forTesting(session: session) + let owner = try await container.plainTextSendGate.acquire() + let waiter = Task { try await container.plainTextSendGate.acquire() } + try await waitUntil("second send is waiting") { + await container.plainTextSendGate.waiterCountForTesting == 1 + } + await container.stopEventMonitoring() + #expect(await container.plainTextSendGate.waiterCountForTesting == 1) + #expect(await container.plainTextSendGate.ownerLeaseIDForTesting == owner.id) + await container.tearDown() + await #expect(throws: CancellationError.self) { try await waiter.value } + } + + @Test + func `an ack during a suspended command does not admit the next send until the owner returns`() async throws { + let harness = try await RadioHarness(budget: .singleAttempt, senderKey: senderKey) + defer { harness.stop() } + harness.script.holdSendMessages(true) + await harness.service.startEventMonitoring() + await harness.service.waitForSubscriberCount(1) + + let contactA = try await harness.contact(byte: 0x21) + let contactB = try await harness.contact(byte: 0x22) + let first = Task { try await harness.service.sendDirectMessage(text: "held", to: contactA) } + try await waitUntil("the command is on the wire") { await harness.sendCount() == 1 } + let packet = try #require(await harness.sendPackets().first) + await harness.session.dispatchForTesting(.acknowledgement( + code: expectedAck(packet: packet, text: "held", sender: senderKey), + tripTime: 40 + )) + + let second = Task { try await harness.service.sendDirectMessage(text: "next", to: contactB) } + try await waitUntil("the competing send is waiting") { + await harness.gate.waiterCountForTesting == 1 + } + #expect(await harness.sendCount() == 1) + + harness.script.holdSendMessages(false) + let accepted = try await first.value + #expect(accepted.status == .sent || accepted.status == .delivered) + try await waitUntil("the competing send starts after the owner returns") { + await harness.sendCount() == 2 + } + harness.script.holdSendMessages(false) + _ = try await second.value + let stored = try await harness.store.fetchMessages(contactID: contactA.id, limit: 1, offset: 0) + #expect(stored.first?.status == .delivered) + } + + @Test + func `a single-attempt send returns sent and holds admission until its ack`() async throws { + let harness = try await RadioHarness(budget: .singleAttempt, senderKey: senderKey) + defer { harness.stop() } + await harness.service.startEventMonitoring() + await harness.service.waitForSubscriberCount(1) + let contactA = try await harness.contact(byte: 0x31) + let contactB = try await harness.contact(byte: 0x32) + let accepted = try await harness.service.sendDirectMessage(text: "once", to: contactA) + #expect(accepted.status == .sent) + #expect(await harness.service.pendingAckCount == 1) + + let second = Task { try await harness.service.sendDirectMessage(text: "later", to: contactB) } + try await waitUntil("the next single-attempt send waits") { + await harness.gate.waiterCountForTesting == 1 + } + #expect(await harness.sendCount() == 1) + + let code = try #require(harness.script.codes().first) + await harness.session.dispatchForTesting(.acknowledgement(code: code, tripTime: 15)) + try await waitUntil("the held ack admits the next send") { await harness.sendCount() == 2 } + _ = try await second.value + let delivered = try await harness.store.fetchMessage(id: accepted.id) + #expect(delivered?.status == .delivered) + let other = try await harness.store.fetchMessages(contactID: contactB.id, limit: 1, offset: 0) + #expect(other.first?.status != .delivered || other.first?.id == accepted.id) + } + + func makeRestartedQueue(_ harness: RadioHarness) -> ChatSendQueueService { + let gate = PlainTextSendGate() + let service = MessageService( + session: harness.session, + dataStore: harness.store, + contactService: nil, + config: MessageServiceConfig(minTimeout: 0), + dmSendBudget: { .default }, + plainTextSendGate: gate + ) + return ChatSendQueueService( + radioID: harness.radioID, + dataStore: harness.store, + messageService: service, + channelService: harness.channelService, + reactionService: ReactionService(), + plainTextSendGate: gate + ) + } + + func quickReplyHandler(_ harness: RadioHarness) throws -> (handler: NotificationActionHandler, notifications: NotificationService) { + let defaults = try #require(UserDefaults(suiteName: "plain-text-gate.\(UUID().uuidString)")) + let notifications = NotificationService( + notificationDefaults: defaults, + systemOperations: .init( + setBadgeCount: { _ in }, + deliveredRequests: { [] }, + removeDeliveredNotifications: { _ in } + ) + ) + let handler = NotificationActionHandler( + dataStore: harness.store, + messageService: harness.service, + notificationService: notifications, + roomServerService: harness.roomService, + syncCoordinator: SyncCoordinator() + ) + handler.configure(isConnectionReady: { _ in true }, localNodeName: { "Test" }) + return (handler: handler, notifications: notifications) + } + + func expectedAck(packet: Data, text: String, sender: Data) -> Data { + let attempt = packet.count > 2 ? packet[2] : 0 + return AckCodeBuilder.expectedAck( + timestamp: wireTimestamp(packet), attempt: attempt, text: text, senderPublicKey: sender + ) + } + + func wireTimestamp(_ packet: Data) -> UInt32 { + let raw = [UInt8](packet.subdata(in: 3..<7)) + return UInt32(raw[0]) + | (UInt32(raw[1]) << 8) + | (UInt32(raw[2]) << 16) + | (UInt32(raw[3]) << 24) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/RadioCLIReplyTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RadioCLIReplyTests.swift index 0ac919eebe..655b61083b 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/RadioCLIReplyTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/RadioCLIReplyTests.swift @@ -8,9 +8,10 @@ struct RadioCLIReplyTests { func `value lines keep the text after the prompt verbatim`() { #expect(RadioCLIReply(text: "> -7") == .value("-7")) #expect(RadioCLIReply(text: "> ") == .value("")) + #expect(RadioCLIReply(text: "> \r\n") == .value("\r\n")) #expect(RadioCLIReply(text: "> my net ") == .value("my net ")) - #expect(RadioCLIReply(text: "> my net \r\n") == .value("my net ")) - #expect(RadioCLIReply(text: "> -7\r\n") == .value("-7")) + #expect(RadioCLIReply(text: "> my net \r\n") == .value("my net \r\n")) + #expect(RadioCLIReply(text: "> -7\r\n") == .value("-7\r\n")) #expect( RadioCLIReply(text: "> wifi.ssid is now x (set wifi.pwd too, then reboot)") == .value("wifi.ssid is now x (set wifi.pwd too, then reboot)") @@ -20,6 +21,7 @@ struct RadioCLIReplyTests { @Test func `OK lines are ok`() { #expect(RadioCLIReply(text: "OK - interval rounded to 16") == .ok("OK - interval rounded to 16")) + #expect(RadioCLIReply(text: "OK\r\n") == .ok("OK")) } @Test @@ -28,11 +30,13 @@ struct RadioCLIReplyTests { #expect(RadioCLIReply(text: "ERROR: af must be 0-9") == .error("ERROR: af must be 0-9")) #expect(RadioCLIReply(text: "ERR - repeat now deprecated") == .error("ERR - repeat now deprecated")) #expect(RadioCLIReply(text: "Error: unsupported") == .error("Error: unsupported")) + #expect(RadioCLIReply(text: "Error: unsupported\r\n") == .error("Error: unsupported")) } @Test func `Unknown command is its own case and empty text is other`() { #expect(RadioCLIReply(text: "Unknown command") == .unknownCommand) + #expect(RadioCLIReply(text: "Unknown command\r\n") == .unknownCommand) #expect(RadioCLIReply(text: "") == .other("")) #expect(RadioCLIReply(text: "\r\n") == .other("")) } diff --git a/MC1Services/Tests/MC1ServicesTests/Services/RadioWiFiResetObservationTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RadioWiFiResetObservationTests.swift new file mode 100644 index 0000000000..ab62105391 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/RadioWiFiResetObservationTests.swift @@ -0,0 +1,57 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Radio WiFi uptime proof") +struct RadioWiFiResetObservationTests { + @Test(arguments: Scenario.allCases) + func `only supported uptime observations exclude continuous firmware progress`(_ scenario: Scenario) { + let start = ContinuousClock.now + let before = RadioWiFiResetObservation( + uptimeSeconds: scenario.before, startedAt: start, completedAt: start + ) + let end = start + .seconds(scenario.elapsed) + let after = RadioWiFiResetObservation( + uptimeSeconds: scenario.after, startedAt: end, completedAt: end + ) + #expect(after.provesReset(since: before) == (scenario == .reset)) + } + + @Test + func `overlapping observation windows cannot prove reset`() { + let start = ContinuousClock.now + let before = RadioWiFiResetObservation(uptimeSeconds: 1000, startedAt: start, completedAt: start + .seconds(2)) + let overlap = RadioWiFiResetObservation(uptimeSeconds: 0, startedAt: start + .seconds(1), completedAt: start + .seconds(3)) + #expect(!overlap.provesReset(since: before)) + } + + enum Scenario: CaseIterable, Sendable { + case reset, normalProgress, shortUptime, millisWrap, longGap, invalidUptime, impossibleBoot, lateReply + + var before: UInt32 { + switch self { + case .shortUptime: 1 + case .millisWrap: 4_294_967 + case .invalidUptime: .max + default: 1000 + } + } + + var after: UInt32 { + switch self { + case .normalProgress: 1001 + case .impossibleBoot: 100 + case .millisWrap: 0 + default: 1 + } + } + + var elapsed: Int64 { + switch self { + case .longGap: 4_294_968 + case .lateReply: 4_294_000 + default: 1 + } + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/RadioWiFiStateTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RadioWiFiStateTests.swift new file mode 100644 index 0000000000..22578df6a4 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/RadioWiFiStateTests.swift @@ -0,0 +1,94 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Radio WiFi state") +@MainActor +struct RadioWiFiStateTests { + @Test + func `a mutation invalidates old reads and only its token may settle`() throws { + let state = RadioWiFiState(radioID: UUID()) + let initial = try #require(state.stableRevision()) + let first = try #require(state.beginMutation(expectedRevision: initial)) + #expect(state.stableRevision() == nil) + #expect(state.beginMutation(expectedRevision: initial) == nil) + let second = try #require(state.beginMutation(expectedRevision: nil)) + #expect(!state.isUncontended(first)) + #expect(state.settle(first, outcome: .accepted) == nil) + #expect(state.stableRevision() == nil) + #expect(state.rebootPending) + #expect(state.settle(first, outcome: .rejected) == nil) + state.settle(second, outcome: .rejected) + #expect(state.stableRevision() != initial) + #expect(state.rebootPending) + } + + @Test + func `expected reboot clears only after successful submission ended context and supported reset proof`() throws { + let state = RadioWiFiState(radioID: UUID()) + let mutation = try #require(state.beginMutation(expectedRevision: nil)) + state.settle(mutation, outcome: .accepted) + let oldContext = UUID() + let (before, after) = resetObservations() + let id = try #require(state.prepareExpectedReboot(contextID: oldContext, observation: before)) + let revision = try #require(state.stableRevision()) + let newContext = UUID() + + #expect(!state.clearExpectedReboot(id: id, contextID: newContext, readRevision: revision, observation: after)) + state.noteLinkEnded(contextID: oldContext) + #expect(!state.clearExpectedReboot(id: id, contextID: newContext, readRevision: revision, observation: after)) + state.completeRebootSubmission(id: id, succeeded: true) + #expect(!state.clearExpectedReboot(id: id, contextID: oldContext, readRevision: revision, observation: after)) + #expect(state.clearExpectedReboot(id: id, contextID: newContext, readRevision: revision, observation: after)) + #expect(!state.rebootPending) + } + + @Test(arguments: [RadioWiFiState.MutationOutcome.accepted, .uncertain, .rejected]) + func `a newer mutation cannot be hidden by an older reboot candidate`( + _ outcome: RadioWiFiState.MutationOutcome + ) throws { + let state = RadioWiFiState(radioID: UUID()) + let first = try #require(state.beginMutation(expectedRevision: nil)) + state.settle(first, outcome: .accepted) + let oldContext = UUID() + let (beforeReset, afterReset) = resetObservations() + let id = try #require(state.prepareExpectedReboot(contextID: oldContext, observation: beforeReset)) + state.completeRebootSubmission(id: id, succeeded: true) + state.noteLinkEnded(contextID: oldContext) + let before = try #require(state.stableRevision()) + let newer = try #require(state.beginMutation(expectedRevision: nil)) + + #expect(!state.clearExpectedReboot(id: id, contextID: UUID(), readRevision: before, observation: afterReset)) + state.settle(newer, outcome: outcome) + let after = try #require(state.stableRevision()) + #expect(!state.clearExpectedReboot(id: id, contextID: UUID(), readRevision: after, observation: afterReset)) + #expect(state.rebootPending) + } + + @Test + func `ambiguous reboot and superseding choice retain apply evidence`() throws { + let state = RadioWiFiState(radioID: UUID()) + let mutation = try #require(state.beginMutation(expectedRevision: nil)) + state.settle(mutation, outcome: .uncertain) + let context = UUID() + let failed = try #require(state.prepareExpectedReboot(contextID: context)) + state.noteLinkEnded(contextID: context) + state.completeRebootSubmission(id: failed, succeeded: false) + #expect(state.expectedRebootID == nil) + #expect(state.rebootPending) + let superseded = try #require(state.prepareExpectedReboot(contextID: context)) + state.completeRebootSubmission(id: superseded, succeeded: true) + state.noteLinkEnded(contextID: context) + state.cancelExpectedReboot() + #expect(!state.clearExpectedReboot(id: superseded, contextID: UUID(), readRevision: state.revision)) + #expect(state.rebootPending) + } + + private func resetObservations() -> (RadioWiFiResetObservation, RadioWiFiResetObservation) { + let start = ContinuousClock.now + return ( + RadioWiFiResetObservation(uptimeSeconds: 1000, startedAt: start, completedAt: start), + RadioWiFiResetObservation(uptimeSeconds: 1, startedAt: start + .seconds(1), completedAt: start + .seconds(1)) + ) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/RemoteFloodFallbackTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RemoteFloodFallbackTests.swift new file mode 100644 index 0000000000..5410d6734f --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/RemoteFloodFallbackTests.swift @@ -0,0 +1,29 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Remote flood fallback") +struct RemoteFloodFallbackTests { + @Test + func `a missing key is on`() throws { + let suiteName = "RemoteFloodFallback.missing.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + + #expect(RemoteFloodFallback.isEnabled(defaults: defaults)) + } + + @Test + func `stored false is off and stored true is on`() throws { + let suiteName = "RemoteFloodFallback.stored.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + let key = AppStorageKey.remoteFloodFallback.rawValue + + defaults.set(false, forKey: key) + #expect(RemoteFloodFallback.isEnabled(defaults: defaults) == false) + + defaults.set(true, forKey: key) + #expect(RemoteFloodFallback.isEnabled(defaults: defaults)) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeCLICancellationTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeCLICancellationTests.swift index f320219e97..efd5a1891b 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeCLICancellationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeCLICancellationTests.swift @@ -39,7 +39,7 @@ struct RemoteNodeCLICancellationTests { ) } try await waitUntil("CLI request should be admitted while the message fetch is outstanding") { - await harness.service.pendingCLIRequests[destinationPrefix]?.command == "shutdown" + await harness.service.cliSlots[destinationPrefix]?.pendingRequest?.command == "shutdown" } #expect(await harness.transport.sentData.count == blockedFrameCount) diff --git a/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeCLICorrelationTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeCLICorrelationTests.swift index b3ff4c64dd..5951d4af5a 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeCLICorrelationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeCLICorrelationTests.swift @@ -3,9 +3,6 @@ import Foundation import MeshCore import Testing -/// Covers CLI response correlation: one command in flight per node, replies -/// that don't match the pending command's shape are dropped, and queued -/// commands wait for the slot instead of racing for replies. @Suite("RemoteNodeService CLI correlation") struct RemoteNodeCLICorrelationTests { private static let publicKey = Data(repeating: 0xCC, count: 32) @@ -109,35 +106,6 @@ struct RemoteNodeCLICorrelationTests { } } - @Test - func `second command waits for the slot until the first resolves`() async throws { - let harness = try await makeHarness() - - let firstTask = Task { - try await harness.service.sendCLICommand(sessionID: harness.sessionID, command: "get tx") - } - try await waitUntil("first command was never sent") { - await harness.session.sendCommandInvocations.count == 1 - } - - let secondTask = Task { - try await harness.service.sendCLICommand(sessionID: harness.sessionID, command: "get radio") - } - - // The second command must not reach the radio while the first is pending. - try await Task.sleep(for: .milliseconds(100)) - #expect(await harness.session.sendCommandInvocations.count == 1) - - await yieldReply("> 22", to: harness.session) - #expect(try await firstTask.value == "> 22") - - try await waitUntil("second command was never sent") { - await harness.session.sendCommandInvocations.count == 2 - } - await yieldReply("> 915.000,250.0,10,5", to: harness.session) - #expect(try await secondTask.value == "> 915.000,250.0,10,5") - } - @Test func `raw command accepts a free-form reply`() async throws { let harness = try await makeHarness() diff --git a/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeCLILifecycleTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeCLILifecycleTests.swift new file mode 100644 index 0000000000..630f9278ea --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeCLILifecycleTests.swift @@ -0,0 +1,246 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("RemoteNodeService CLI lifecycle", .timeLimit(.minutes(1))) +struct RemoteNodeCLILifecycleTests { + private static let publicKey = Data(repeating: 0xCC, count: 32) + private static let otherPublicKey = Data(repeating: 0xDD, count: 32) + private static let requestTimeout: Duration = .seconds(5) + private static let sentInfo = MessageSentInfo(route: 0, expectedAck: Data(), suggestedTimeoutMs: 100) + + @Test + func `cancelling a middle waiter preserves FIFO for the remaining commands`() async throws { + try await withHarness { harness in + let first = harness.send("get name") + try await harness.waitForSubmissions(1) + let second = harness.send("board") + try await harness.waitForWaiters(1) + let cancelled = harness.send("shutdown") + try await harness.waitForWaiters(2) + let last = harness.send("ver") + try await harness.waitForWaiters(3) + + cancelled.cancel() + await #expect(throws: CancellationError.self) { try await cancelled.value } + try await harness.waitForWaiters(2) + #expect(await harness.commands == ["get name"]) + + try await harness.reply("Contact", index: 0) + #expect(try await first.value == "Contact") + try await harness.waitForSubmissions(2) + #expect(await harness.commands == ["get name", "board"]) + try await harness.reply("Heltec", index: 1) + #expect(try await second.value == "Heltec") + try await harness.waitForSubmissions(3) + #expect(await harness.commands == ["get name", "board", "ver"]) + try await harness.reply("1.18.0", index: 2) + #expect(try await last.value == "1.18.0") + } + } + + @Test + func `another destination completes while the first destination is waiting`() async throws { + try await withHarness { harness in + let first = harness.send("get name") + try await harness.waitForSubmissions(1) + let other = harness.send("board", publicKey: Self.otherPublicKey) + try await harness.waitForSubmissions(2) + + try await harness.reply("Heltec", index: 1) + #expect(try await other.value == "Heltec") + #expect(await harness.session.sendCommandInvocations.map(\.destination) == [ + Self.publicKey, Self.otherPublicKey + ]) + try await harness.reply("Contact", index: 0) + #expect(try await first.value == "Contact") + } + } + + @Test(arguments: [false, true]) + func `reply during submission wins and late submission completion cannot affect the next request`( + submissionFails: Bool + ) async throws { + try await withHarness { harness in + await harness.session.setSendCommandResult( + submissionFails ? .failure(MeshCoreError.timeout) : .success(Self.sentInfo) + ) + await harness.session.setSendCommandHold { await harness.sendGate.wait() } + let first = harness.send("get name") + try await waitUntil("first submission should be suspended") { await harness.sendGate.isWaiting } + let prefix = Data(Self.publicKey.prefix(6)) + let firstWorker = try #require(await harness.service.cliSlots[prefix]?.pendingRequest?.worker) + let second = harness.send("board") + try await harness.waitForWaiters(1) + + await harness.session.setSendCommandHold(nil) + await harness.session.setSendCommandResult(.success(Self.sentInfo)) + try await harness.reply("Contact", index: 0) + #expect(try await first.value == "Contact") + try await harness.waitForSubmissions(2) + + await harness.sendGate.release() + await firstWorker.value + try await harness.reply("stale first reply", index: 0) + try await harness.reply("Heltec", index: 1) + #expect(try await second.value == "Heltec") + #expect(await harness.commands == ["get name", "board"]) + } + } + + @Test + func `retirement cancels active and queued commands and rejects further commands`() async throws { + try await withHarness { harness in + let first = harness.send("get name") + try await harness.waitForSubmissions(1) + let second = harness.send("board") + try await harness.waitForWaiters(1) + let third = harness.send("shutdown") + try await harness.waitForWaiters(2) + + await harness.service.retire() + await #expect(throws: CancellationError.self) { try await first.value } + await #expect(throws: CancellationError.self) { try await second.value } + await #expect(throws: CancellationError.self) { try await third.value } + await #expect { + try await harness.service.sendRadioCLICommand( + to: Self.publicKey, command: "ver", timeout: Self.requestTimeout + ) + } throws: { error in + guard case RemoteNodeError.notConnected = error else { return false } + return true + } + #expect(await harness.commands == ["get name"]) + } + } + + @Test + func `Direct-to-Flood retry keeps its slot ahead of queued commands`() async throws { + try await withHarness { harness in + try await harness.dataStore.saveContact(ContactDTO.testContact( + radioID: harness.radioID, publicKey: Self.publicKey, + typeRawValue: ContactType.repeater.rawValue, outPathLength: 1, outPath: Data([0x0A]) + )) + let remoteSession = RemoteNodeSessionDTO.testSession( + radioID: harness.radioID, publicKey: Self.publicKey, role: .repeater, permissionLevel: .admin + ) + try await harness.dataStore.saveRemoteNodeSessionDTO(remoteSession) + await harness.session.setSendCommandResult(.failure(MeshCoreError.timeout)) + await harness.session.setSendCommandHold { await harness.sendGate.wait() } + let first = Task { + try await harness.service.sendRawCLICommand( + sessionID: remoteSession.id, command: "get name", timeout: Self.requestTimeout + ) + } + try await waitUntil("Direct submission should be suspended") { await harness.sendGate.isWaiting } + let second = harness.send("board") + try await harness.waitForWaiters(1) + await harness.session.setSendCommandHold(nil) + await harness.session.setSendCommandResult(.success(Self.sentInfo)) + await harness.sendGate.release() + + try await harness.waitForSubmissions(2) + #expect(await harness.commands == ["get name", "get name"]) + #expect(await harness.session.resetPathPublicKeys == [Self.publicKey]) + try await harness.reply("stale Direct reply", index: 0) + try await harness.reply("Contact", index: 1) + #expect(try await first.value == "Contact") + try await harness.waitForSubmissions(3) + #expect(await harness.commands == ["get name", "get name", "board"]) + try await harness.reply("Heltec", index: 2) + #expect(try await second.value == "Heltec") + } + } + + private func withHarness(_ operation: (Harness) async throws -> Void) async throws { + let radioID = UUID() + let dataStore = try await PersistenceStore.createTestDataStore(radioID: radioID) + let session = MockMeshCoreSession() + let service = RemoteNodeService(session: session, dataStore: dataStore, keychainService: KeychainService()) + let harness = Harness(service: service, session: session, dataStore: dataStore, radioID: radioID) + await service.startEventMonitoring() + do { + try await waitUntil("CLI event monitor should subscribe") { await session.eventSubscriptionCount == 1 } + try await operation(harness) + } catch { + await harness.stop() + throw error + } + await harness.stop() + } + + private struct Harness { + let service: RemoteNodeService + let session: MockMeshCoreSession + let dataStore: PersistenceStore + let radioID: UUID + let sendGate = Gate() + + var commands: [String] { + get async { + await session.sendCommandInvocations.compactMap { CLIResponse.splitEchoedPrefix($0.command)?.body } + } + } + + func send(_ command: String, publicKey: Data = RemoteNodeCLILifecycleTests.publicKey) -> Task { + Task { + try await service.sendRadioCLICommand( + to: publicKey, command: command, timeout: RemoteNodeCLILifecycleTests.requestTimeout + ) + } + } + + func waitForSubmissions(_ count: Int) async throws { + try await waitUntil("expected \(count) CLI submissions") { await session.sendCommandInvocations.count == count } + } + + func waitForWaiters(_ count: Int) async throws { + let prefix = Data(RemoteNodeCLILifecycleTests.publicKey.prefix(6)) + try await waitUntil("expected \(count) queued CLI commands") { + await service.cliSlots[prefix]?.waiterCount == count + } + } + + func reply(_ text: String, index: Int) async throws { + let invocation = await session.sendCommandInvocations[index] + let command = try #require(CLIResponse.splitEchoedPrefix(invocation.command)) + await session.yieldEvent(.contactMessageReceived(ContactMessage( + senderPublicKeyPrefix: Data(invocation.destination.prefix(6)), + pathLength: 0, + textType: MeshCore.TextType.cliData.rawValue, + senderTimestamp: Date(), + signature: nil, + text: command.prefix + text, + snr: nil + ))) + } + + func stop() async { + await session.setSendCommandHold(nil) + await sendGate.release() + await service.retire() + service.finishEvents() + } + } + + private actor Gate { + private var continuation: CheckedContinuation? + private var isReleased = false + private(set) var isWaiting = false + + func wait() async { + guard !isReleased else { return } + await withCheckedContinuation { continuation in + self.continuation = continuation + isWaiting = true + } + } + + func release() { + isReleased = true + continuation?.resume() + continuation = nil + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeLoginLifecycleTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeLoginLifecycleTests.swift new file mode 100644 index 0000000000..30aef638df --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeLoginLifecycleTests.swift @@ -0,0 +1,258 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("RemoteNodeService login lifecycle", .timeLimit(.minutes(1))) +@MainActor +struct RemoteNodeLoginLifecycleTests { + @Test + func `reply before submission finishes completes login despite a later send failure`() async throws { + try await withHarness(expectedConnectedEvents: 1) { harness in + await harness.session.setSendLoginResults([.failure(MeshCoreError.timeout)]) + await harness.session.setSendLoginHold { await harness.sendGate.wait() } + let login = Task { try await harness.login() } + try await waitUntil("login submission should be suspended") { await harness.sendGate.isWaiting } + + await harness.deliverSuccess(isAdmin: true) + let result = try await login.value + #expect(result.success) + #expect(result.isAdmin) + #expect(await harness.session.completedSendLoginCount == 0) + #expect(try await harness.store.fetchRemoteNodeSession(id: harness.membership.id)?.permissionLevel == .admin) + + await harness.sendGate.release() + try await waitUntil("the old submission should return its error") { + await harness.session.completedSendLoginCount == 1 + } + #expect(await harness.store.updatedSessionConnections.count == 1) + #expect(await harness.store.markedDisconnectedSessionIDs.isEmpty) + } + } + + @Test + func `duplicate reply while result persistence is suspended cannot claim login twice`() async throws { + try await withHarness(expectedConnectedEvents: 1) { harness in + await harness.holdResultPersistence() + let login = Task { try await harness.login() } + try await harness.waitForSubmissions(1) + let firstReply = Task { await harness.deliverSuccess(isAdmin: true) } + try await waitUntil("the first reply should be persisting") { await harness.storeGate.isWaiting } + + await harness.deliverSuccess(isAdmin: false) + #expect(await harness.store.updatedSessionConnections.count == 1) + + await harness.storeGate.release() + await firstReply.value + #expect(try await login.value.isAdmin) + #expect(try await harness.store.fetchRemoteNodeSession(id: harness.membership.id)?.permissionLevel == .admin) + #expect(await harness.store.markedDisconnectedSessionIDs.isEmpty) + } + } + + @Test(arguments: [false, true]) + func `old result persistence cannot finish or disconnect a replacement login`(cancelFirst: Bool) async throws { + try await withHarness(expectedConnectedEvents: 1) { harness in + await harness.holdResultPersistence() + let original = Task { try await harness.login() } + try await harness.waitForSubmissions(1) + let originalReply = Task { await harness.deliverSuccess(isAdmin: true) } + try await waitUntil("the old reply should be persisting") { await harness.storeGate.isWaiting } + + if cancelFirst { original.cancel() } + let replacement = Task { try await harness.login() } + try await harness.waitForSubmissions(2) + await harness.storeGate.release() + await originalReply.value + await expectCancelled(original) + #expect(await harness.store.markedDisconnectedSessionIDs.isEmpty) + + await harness.deliverSuccess(isAdmin: false) + let result = try await replacement.value + #expect(result.success) + #expect(!result.isAdmin) + #expect(await harness.store.updatedSessionConnections.count == 2) + #expect(await harness.store.markedDisconnectedSessionIDs.isEmpty) + #expect(try await harness.store.fetchRemoteNodeSession(id: harness.membership.id)?.permissionLevel == .guest) + } + } + + @Test + func `cancelled result persistence compensates its late connection write without a replacement`() async throws { + try await withHarness(expectedConnectedEvents: 0) { harness in + await harness.holdResultPersistence() + let login = Task { try await harness.login() } + try await harness.waitForSubmissions(1) + let reply = Task { await harness.deliverSuccess(isAdmin: true) } + try await waitUntil("the reply should be persisting before cancellation") { await harness.storeGate.isWaiting } + + await harness.service.cancelPendingLogin(for: harness.prefix) + await harness.storeGate.release() + await reply.value + await expectCancelled(login) + + #expect(await harness.store.updatedSessionConnections.count == 1) + #expect(await harness.store.markedDisconnectedSessionIDs == [harness.membership.id]) + } + } + + @Test + func `submission failure ignores late reply and permits another login`() async throws { + try await withHarness(expectedConnectedEvents: 1) { harness in + await harness.session.setSendLoginResults([ + .failure(MeshCoreError.deviceError(code: ProtocolError.tableFull.rawValue)), + .success(Harness.sentInfo) + ]) + await #expect { + _ = try await harness.login() + } throws: { error in + guard let error = error as? RemoteNodeError, + case let .sessionError(.deviceError(code)) = error else { return false } + return code == ProtocolError.tableFull.rawValue + } + + await harness.deliverSuccess(isAdmin: true) + #expect(await harness.store.updatedSessionConnections.isEmpty) + + let retry = Task { try await harness.login() } + try await harness.waitForSubmissions(2) + await harness.deliverSuccess(isAdmin: false) + #expect(try await retry.value.success) + #expect(await harness.store.updatedSessionConnections.count == 1) + #expect(await harness.store.markedDisconnectedSessionIDs.isEmpty) + } + } + + @Test + func `response timeout ignores late reply and permits another login`() async throws { + try await withHarness(expectedConnectedEvents: 1) { harness in + await #expect { + _ = try await harness.login() + } throws: { error in + guard let error = error as? RemoteNodeError, case .timeout = error else { return false } + return true + } + let submissions = await harness.session.sendLoginInvocations.count + #expect(submissions > 1) + await harness.deliverSuccess(isAdmin: true) + #expect(await harness.store.updatedSessionConnections.isEmpty) + + await harness.session.setSendLoginResults([.success(Harness.sentInfo)]) + let retry = Task { try await harness.login() } + try await harness.waitForSubmissions(submissions + 1) + await harness.deliverSuccess(isAdmin: false) + #expect(try await retry.value.success) + #expect(await harness.store.updatedSessionConnections.count == 1) + #expect(await harness.store.markedDisconnectedSessionIDs.isEmpty) + } + } + + private func expectCancelled(_ task: Task) async { + await #expect { + _ = try await task.value + } throws: { error in + guard let error = error as? RemoteNodeError, case .cancelled = error else { return false } + return true + } + } + + private func withHarness( + expectedConnectedEvents: Int, + _ body: (Harness) async throws -> Void + ) async throws { + let session = MockMeshCoreSession() + await session.setSendLoginResults(Array(repeating: .success(Harness.sentInfo), count: 8)) + let store = MockPersistenceStore() + let membership = RemoteNodeSessionDTO.testSession(radioID: UUID()) + try await store.saveRemoteNodeSessionDTO(membership) + let service = RemoteNodeService(session: session, dataStore: store, keychainService: KeychainService()) + let stream = service.events() + let events = Task { + var received: [RemoteNodeEvent] = [] + for await event in stream { + received.append(event) + } + return received + } + let harness = Harness(service: service, session: session, store: store, membership: membership) + do { + try await body(harness) + } catch { + await harness.stop() + _ = await events.value + throw error + } + await harness.stop() + let received = await events.value + #expect(received.count == expectedConnectedEvents) + for case let .sessionStateChanged(sessionID, isConnected) in received { + #expect(sessionID == membership.id) + #expect(isConnected) + } + } + + private struct Harness: Sendable { + static let sentInfo = MessageSentInfo(route: 0, expectedAck: Data([1, 2, 3, 4]), suggestedTimeoutMs: 100) + let service: RemoteNodeService + let session: MockMeshCoreSession + let store: MockPersistenceStore + let membership: RemoteNodeSessionDTO + let sendGate = Gate() + let storeGate = Gate() + + var prefix: Data { + Data(membership.publicKey.prefix(6)) + } + + func login() async throws -> LoginResult { + try await service.login(sessionID: membership.id, password: "test-password") + } + + func deliverSuccess(isAdmin: Bool) async { + await service.handleLoginResult( + LoginResult(success: true, isAdmin: isAdmin, aclPermissions: 0, publicKeyPrefix: prefix), + fromPublicKeyPrefix: prefix + ) + } + + func holdResultPersistence() async { + await store.setUpdateRemoteNodeSessionConnectionHold { await storeGate.wait() } + } + + @MainActor + func waitForSubmissions(_ count: Int) async throws { + try await waitUntil("expected login submission was not sent") { + await session.sendLoginInvocations.count == count + } + } + + func stop() async { + await session.setSendLoginHold(nil) + await store.setUpdateRemoteNodeSessionConnectionHold(nil) + await sendGate.release() + await storeGate.release() + await service.retire() + service.finishEvents() + } + } + + private actor Gate { + private var continuation: CheckedContinuation? + private var isReleased = false + private(set) var isWaiting = false + + func wait() async { + guard !isReleased else { return } + await withCheckedContinuation { continuation in + self.continuation = continuation + isWaiting = true + } + } + + func release() { + isReleased = true + continuation?.resume() + continuation = nil + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodePathRecoveryTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodePathRecoveryTests.swift index 1adede4039..78ca8be492 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodePathRecoveryTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodePathRecoveryTests.swift @@ -10,47 +10,86 @@ struct RemoteNodePathRecoveryTests { private static let publicKey = Data(repeating: 0xCD, count: 32) private static let directPath = Data([0x0A, 0x0B, 0x0C]) - private struct Harness { + private final class Harness { let service: RemoteNodeService let session: MockMeshCoreSession let dataStore: PersistenceStore let sessionID: UUID let radioID: UUID + let defaultsSuiteName: String + + init( + service: RemoteNodeService, + session: MockMeshCoreSession, + dataStore: PersistenceStore, + sessionID: UUID, + radioID: UUID, + defaultsSuiteName: String + ) { + self.service = service + self.session = session + self.dataStore = dataStore + self.sessionID = sessionID + self.radioID = radioID + self.defaultsSuiteName = defaultsSuiteName + } + + deinit { + UserDefaults(suiteName: defaultsSuiteName)?.removePersistentDomain(forName: defaultsSuiteName) + } } - private func makeHarness(outPathLength: UInt8, outPath: Data) async throws -> Harness { - let radioID = UUID() - let dataStore = try await PersistenceStore.createTestDataStore(radioID: radioID) - let contact = ContactDTO.testContact( - radioID: radioID, - publicKey: Self.publicKey, - typeRawValue: ContactType.repeater.rawValue, - outPathLength: outPathLength, - outPath: outPath - ) - try await dataStore.saveContact(contact) + private func makeHarness( + outPathLength: UInt8, + outPath: Data, + fallbackEnabled: Bool? = nil + ) async throws -> Harness { + let suiteName = "RemoteNodePathRecovery.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defaults.removePersistentDomain(forName: suiteName) + if let fallbackEnabled { + defaults.set(fallbackEnabled, forKey: AppStorageKey.remoteFloodFallback.rawValue) + } - let remoteSession = RemoteNodeSessionDTO.testSession( - radioID: radioID, - publicKey: Self.publicKey, - role: .repeater, - permissionLevel: .admin - ) - try await dataStore.saveRemoteNodeSessionDTO(remoteSession) + do { + let radioID = UUID() + let dataStore = try await PersistenceStore.createTestDataStore(radioID: radioID) + let contact = ContactDTO.testContact( + radioID: radioID, + publicKey: Self.publicKey, + typeRawValue: ContactType.repeater.rawValue, + outPathLength: outPathLength, + outPath: outPath + ) + try await dataStore.saveContact(contact) - let session = MockMeshCoreSession() - let service = RemoteNodeService( - session: session, - dataStore: dataStore, - keychainService: KeychainService() - ) - return Harness( - service: service, - session: session, - dataStore: dataStore, - sessionID: remoteSession.id, - radioID: radioID - ) + let remoteSession = RemoteNodeSessionDTO.testSession( + radioID: radioID, + publicKey: Self.publicKey, + role: .repeater, + permissionLevel: .admin + ) + try await dataStore.saveRemoteNodeSessionDTO(remoteSession) + + let session = MockMeshCoreSession() + let service = RemoteNodeService( + session: session, + dataStore: dataStore, + keychainService: KeychainService(), + defaults: defaults + ) + return Harness( + service: service, + session: session, + dataStore: dataStore, + sessionID: remoteSession.id, + radioID: radioID, + defaultsSuiteName: suiteName + ) + } catch { + defaults.removePersistentDomain(forName: suiteName) + throw error + } } private func makeStatusResponse() -> StatusResponse { @@ -193,6 +232,31 @@ struct RemoteNodePathRecoveryTests { #expect(await harness.session.resetPathPublicKeys == [Self.publicKey]) } + @Test + func `a normal command that times out keeps the path when fallback is off`() async throws { + let harness = try await makeHarness( + outPathLength: 3, + outPath: Self.directPath, + fallbackEnabled: false + ) + + await #expect(throws: RemoteNodeError.self) { + _ = try await harness.service.sendRawCLICommand( + sessionID: harness.sessionID, + command: "get name", + timeout: .milliseconds(1) + ) + } + #expect(await harness.session.sendCommandInvocations.count == 1) + #expect(await harness.session.resetPathPublicKeys.isEmpty) + + let contact = try await harness.dataStore.fetchContact( + radioID: harness.radioID, + publicKey: Self.publicKey + ) + #expect(contact?.isFloodRouted == false) + } + @Test func `owner info timeout does not reset the path`() async throws { let harness = try await makeHarness(outPathLength: 1, outPath: Data([0xFF])) diff --git a/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeSensorTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeSensorTests.swift new file mode 100644 index 0000000000..e79c2c8134 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeSensorTests.swift @@ -0,0 +1,293 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Remote sensor operations") +struct RemoteNodeSensorTests { + @Test + func `sensor has its own session role`() { + #expect(RemoteNodeRole(contactType: .sensor) == .sensor) + } +} + +extension RemoteNodeSensorTests { + private struct Harness { + let store: PersistenceStore + let service: RemoteNodeService + let session: MockMeshCoreSession + let remote: RemoteNodeSessionDTO + } + + private func harness(connected: Bool = true, permission: RoomPermissionLevel = .admin) async throws -> Harness { + let radioID = UUID() + let store = try await PersistenceStore.createTestDataStore(radioID: radioID) + let remote = RemoteNodeSessionDTO.testSession(radioID: radioID, role: .sensor, + isConnected: connected, permissionLevel: permission) + try await store.saveRemoteNodeSessionDTO(remote) + let session = MockMeshCoreSession() + let service = RemoteNodeService(session: session, dataStore: store, keychainService: KeychainService()) + await service.startEventMonitoring() + try await waitUntil("event stream should be registered") { await session.eventSubscriptionCount == 1 } + return Harness(store: store, service: service, session: session, remote: remote) + } + + private func reply(_ text: String, harness: Harness, index: Int) async throws { + try await waitUntil("command should be sent") { await harness.session.sendCommandInvocations.count > index } + let command = await harness.session.sendCommandInvocations[index].command + let prefix = try #require(CLIResponse.splitEchoedPrefix(command)?.prefix) + await harness.session.yieldEvent(.contactMessageReceived(ContactMessage( + senderPublicKeyPrefix: Data(harness.remote.publicKey.prefix(6)), pathLength: 0, textType: 1, + senderTimestamp: Date(), signature: nil, text: prefix + text, snr: nil + ))) + } + + @Test(arguments: [UInt8(0), 1, 2, 0xC1, 0xC2, 0xC3]) + func `sensor permission requires the admin boolean`(acl: UInt8) { + let nonadmin = LoginResult(success: true, isAdmin: false, aclPermissions: acl, publicKeyPrefix: Data()) + #expect(nonadmin.permissionLevel(for: .sensor) == .guest) + let admin = LoginResult(success: true, isAdmin: true, aclPermissions: acl, publicKeyPrefix: Data()) + #expect(admin.permissionLevel(for: .sensor) == .admin) + } + + @Test + func `settings load all pages without get fanout`() async throws { + let h = try await harness() + let task = Task { try await h.service.fetchSensorSettings(sessionID: h.remote.id) } + try await reply("3 vars\na=1\nb=x=y\n... next:2", harness: h, index: 0) + try await reply("3 vars\nc=", harness: h, index: 1) + #expect(try await task.value.map(\.value) == ["1", "x=y", ""]) + let sent = await h.session.sendCommandInvocations.map(\.command) + #expect(sent.map { CLIResponse.splitEchoedPrefix($0)?.body } == ["sensor list", "sensor list 2"]) + await h.service.retire() + } + + @Test + func `accepted setter reads back exactly once`() async throws { + let h = try await harness() + let task = Task { + try await h.service.setSensorSetting(sessionID: h.remote.id, setting: SensorSetting(key: "gps", value: "0"), value: "1") + } + try await reply("ok", harness: h, index: 0) + try await reply("> 1", harness: h, index: 1) + #expect(try await task.value == SensorSetting(key: "gps", value: "1")) + #expect(await h.session.sendCommandInvocations.count == 2) + #expect(await h.session.resetPathPublicKeys.isEmpty) + await h.service.retire() + } + + @Test(arguments: ["reboot", " rebootx", "clkreboot", "poweroff", "shutdownx"]) + func `no reply submission needs only host acceptance`(command: String) async throws { + let h = try await harness() + #expect(try await h.service.sendRawCLICommand(sessionID: h.remote.id, command: command) == "") + #expect(await h.session.sendCommandInvocations.count == 1) + #expect(await h.session.getMessageTimeouts.isEmpty) + #expect(try await h.store.fetchRemoteNodeSession(id: h.remote.id)?.isConnected == false) + await h.service.retire() + } + + @Test + func `host timeout is an error and does not repeat reboot`() async throws { + let h = try await harness() + await h.session.setSendCommandResult(.failure(MeshCoreError.timeout)) + await #expect(throws: RemoteNodeError.self) { try await h.service.rebootSensor(sessionID: h.remote.id) } + #expect(await h.session.sendCommandInvocations.count == 1) + #expect(await h.session.getMessageTimeouts.isEmpty) + await h.service.retire() + } + + @Test + func `ordinary sensor CLI has one attempt on timeout`() async throws { + let h = try await harness() + await #expect(throws: RemoteNodeError.self) { + try await h.service.sendRawCLICommand(sessionID: h.remote.id, command: "sensor set gps 1", timeout: .milliseconds(20)) + } + #expect(await h.session.sendCommandInvocations.count == 1) + #expect(await h.session.resetPathPublicKeys.isEmpty) + #expect(RemoteCLINoReplyCommand.sensorCommand("REBOOT") == nil) + await h.service.retire() + } + + @Test + func `guest and disconnected sensors cannot issue management commands`() async throws { + for (connected, permission) in [(true, RoomPermissionLevel.guest), (false, .admin)] { + let h = try await harness(connected: connected, permission: permission) + await #expect(throws: RemoteNodeError.self) { try await h.service.fetchSensorSettings(sessionID: h.remote.id) } + await #expect(throws: RemoteNodeError.self) { try await h.service.rebootSensor(sessionID: h.remote.id) } + #expect(await h.session.sendCommandInvocations.isEmpty) + await h.service.retire() + } + } +} + +extension RemoteNodeSensorTests { + @Test(arguments: [true, false]) + func `nonadmin ACL can authenticate telemetry but cannot open management`(requireAdmin: Bool) async throws { + let h = try await harness(connected: false) + let contact = ContactDTO.testContact(radioID: h.remote.radioID, publicKey: h.remote.publicKey, typeRawValue: 4) + await h.session.setSendLoginResults([.success(MessageSentInfo(route: 0, expectedAck: Data(), suggestedTimeoutMs: 100))]) + let task = Task { + try await h.service.connectSensor(radioID: contact.radioID, contact: contact, password: "", + rememberPassword: false, requireAdmin: requireAdmin, pathLength: 0, onTimeoutKnown: nil) + } + try await waitUntil("ACL login should be sent") { await h.session.sendLoginInvocations.count == 1 } + await h.service.handleLoginResult(LoginResult(success: true, isAdmin: false, aclPermissions: 2, + publicKeyPrefix: Data(contact.publicKey.prefix(6))), + fromPublicKeyPrefix: Data(contact.publicKey.prefix(6))) + if requireAdmin { + await #expect(throws: RemoteNodeError.self) { try await task.value } + #expect(try await h.store.fetchRemoteNodeSession(id: h.remote.id)?.isConnected == false) + } else { + let result = try await task.value + #expect(result.isConnected) + #expect(!result.isAdmin) + } + #expect(await h.session.sendCommandInvocations.isEmpty) + await h.service.retire() + } + + @Test(arguments: ["1234567890123456", "éééééééé"]) + func `oversized password is rejected before any send`(password: String) async throws { + let h = try await harness() + await #expect(throws: RemoteNodeError.self) { try await h.service.login(sessionID: h.remote.id, password: password) } + #expect(await h.session.sendLoginInvocations.isEmpty) + await h.service.retire() + } + + @Test + func `reconnect authenticates roles sequentially and keeps failures local`() async throws { + let h = try await harness(connected: false) + let keychain = KeychainService() + let roles: [RemoteNodeRole] = [.sensor, .repeater, .roomServer] + var nodes: [RemoteNodeSessionDTO] = [] + for (index, role) in roles.enumerated() { + let node = RemoteNodeSessionDTO.testSession(radioID: h.remote.radioID, + publicKey: Data(repeating: UInt8(0xD0 + index), count: 32), role: role, permissionLevel: .admin) + nodes.append(node) + try await h.store.saveRemoteNodeSessionDTO(node) + try await keychain.storePassword("test", forNodeKey: node.publicKey) + } + await h.session.setSendLoginResults(Array(repeating: .success( + MessageSentInfo(route: 0, expectedAck: Data(), suggestedTimeoutMs: 100) + ), count: roles.count)) + let task = Task { + await h.service.handleLinkReconnection(radioID: h.remote.radioID, sessionIDs: Set(nodes.map(\.id))) + } + for index in roles.indices { + try await waitUntil("one login should be outstanding") { await h.session.sendLoginInvocations.count == index + 1 } + #expect(await h.service.pendingLoginCount == 1) + let sent = await h.session.sendLoginInvocations[index] + let prefix = Data(sent.destination.prefix(6)) + await h.service.handleLoginResult(LoginResult(success: index != 1, isAdmin: true, aclPermissions: nil, + publicKeyPrefix: prefix), fromPublicKeyPrefix: prefix) + } + await task.value + #expect(await h.session.sendLoginInvocations.count == 3) + #expect(await h.service.pendingLoginCount == 0) + for node in nodes { + try await keychain.deletePassword(forNodeKey: node.publicKey) + } + await h.service.retire() + } +} + +extension RemoteNodeSensorTests { + @Test + func `unsupported binary operations fail before dispatch`() async throws { + let h = try await harness() + await #expect { try await h.service.requestStatus(sessionID: h.remote.id) } throws: { error in + guard case RemoteNodeError.invalidResponse = error else { return false } + return true + } + await #expect { try await h.service.requestOwnerInfo(sessionID: h.remote.id) } throws: { error in + guard case RemoteNodeError.invalidResponse = error else { return false } + return true + } + await #expect { try await h.service.sendKeepAlive(sessionID: h.remote.id) } throws: { error in + guard case RemoteNodeError.invalidResponse = error else { return false } + return true + } + await h.service.retire() + } + + @Test + func `queued command rechecks authorization before dispatch`() async throws { + let h = try await harness() + let first = Task { try await h.service.sendRawCLICommand(sessionID: h.remote.id, command: "sensor list") } + try await waitUntil("first command should hold the slot") { await h.session.sendCommandInvocations.count == 1 } + let second = Task { try await h.service.sendRawCLICommand(sessionID: h.remote.id, command: "reboot") } + try await waitUntil("second command should wait") { await h.service.cliSlots.values.contains { $0.waiterCount > 0 } } + await h.service.disconnect(sessionID: h.remote.id) + try await reply("no custom var", harness: h, index: 0) + #expect(try await first.value == "no custom var") + await #expect(throws: RemoteNodeError.self) { try await second.value } + #expect(await h.session.sendCommandInvocations.count == 1) + await h.service.retire() + } +} + +extension RemoteNodeSensorTests { + @Test + func `same sensor key keeps separate radio sessions and permissions`() async throws { + let h = try await harness() + let otherRadio = UUID() + let contact = ContactDTO.testContact(radioID: otherRadio, publicKey: h.remote.publicKey, typeRawValue: 4) + try await h.store.saveContact(contact) + let other = try await h.service.createSession(radioID: otherRadio, contact: contact) + #expect(other.id != h.remote.id) + #expect(other.radioID == otherRadio) + #expect(other.isSensor) + #expect(!other.isConnected) + #expect(!other.isAdmin) + #expect(try await h.store.fetchRemoteNodeSession(id: h.remote.id)?.isAdmin == true) + #expect(try await h.store.fetchRemoteNodeSessions(radioID: h.remote.radioID).count == 1) + await h.service.retire() + } + + @Test + func `a cancelled attempt cannot cancel its replacement`() async throws { + let h = try await harness(connected: false) + await h.session.setSendLoginResults(Array(repeating: .success( + MessageSentInfo(route: 0, expectedAck: Data(), suggestedTimeoutMs: 100) + ), count: 2)) + let prefix = Data(h.remote.publicKey.prefix(6)) + let first = Task { try await h.service.login(sessionID: h.remote.id, password: "old") } + try await waitUntil("first login should send") { await h.session.sendLoginInvocations.count == 1 } + let firstID = try #require(await h.service.loginAttempts[prefix]?.id) + let second = Task { try await h.service.login(sessionID: h.remote.id, password: "new") } + try await waitUntil("replacement login should send") { await h.session.sendLoginInvocations.count == 2 } + await h.service.cancelPendingLogin(for: prefix, attemptID: firstID) + #expect(await h.service.pendingLoginCount == 1) + await h.service.handleLoginResult(LoginResult(success: true, isAdmin: true, aclPermissions: nil, + publicKeyPrefix: prefix), fromPublicKeyPrefix: prefix) + await #expect(throws: RemoteNodeError.self) { try await first.value } + #expect(try await second.value.isAdmin) + await h.service.retire() + } +} + +extension RemoteNodeSensorTests { + @Test + func `a retired sensor connect cannot disconnect the replacement`() async throws { + let h = try await harness(connected: false) + let contact = ContactDTO.testContact(radioID: h.remote.radioID, publicKey: h.remote.publicKey, typeRawValue: 4) + await h.session.setSendLoginResults(Array(repeating: .success( + MessageSentInfo(route: 0, expectedAck: Data(), suggestedTimeoutMs: 100) + ), count: 2)) + func connect() async throws -> RemoteNodeSessionDTO { + try await h.service.connectSensor(radioID: contact.radioID, contact: contact, password: "", + rememberPassword: false, requireAdmin: false, pathLength: 0, onTimeoutKnown: nil) + } + let first = Task { try await connect() } + try await waitUntil("first login should send") { await h.session.sendLoginInvocations.count == 1 } + let second = Task { try await connect() } + try await waitUntil("replacement login should send") { await h.session.sendLoginInvocations.count == 2 } + let prefix = Data(contact.publicKey.prefix(6)) + await h.service.handleLoginResult(LoginResult(success: true, isAdmin: true, aclPermissions: nil, + publicKeyPrefix: prefix), fromPublicKeyPrefix: prefix) + #expect(try await second.value.isConnected) + await #expect(throws: RemoteNodeError.self) { try await first.value } + #expect(try await h.store.fetchRemoteNodeSession(id: h.remote.id)?.isConnected == true) + await h.service.retire() + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/RoomKeepAliveRecoveryTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RoomKeepAliveRecoveryTests.swift new file mode 100644 index 0000000000..df4d3389b7 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/RoomKeepAliveRecoveryTests.swift @@ -0,0 +1,398 @@ +import Foundation +@testable import MC1Services +import MeshCore +import MeshCoreTestSupport +import Testing + +@Suite("Room keep-alive recovery", .timeLimit(.minutes(1))) +struct RoomKeepAliveRecoveryTests { + private static let savedBookmark: UInt32 = 40 + private static let missingPost: UInt32 = 41 + private static let newestPost: UInt32 = 42 + + private struct Harness { + let room: RemoteNodeSessionDTO + let store: PersistenceStore + let transport: RoomReplayTransport + let mesh: MeshCoreSession + let service: RemoteNodeService + let roomService: RoomServerService + let lifetime: ReceiveScope.Lifetime + let policy: Policy + } + + private actor Policy { + private var preference = TextRulesPreference() + + init() { + preference.setSelection(.all, for: .room) + } + + func snapshot() -> TextRulesPreference { + preference + } + + func turnOff() { + preference.setSelection(.off, for: .room) + } + + func block(_ text: String) { + preference.append(.init(phrase: text, lookIn: .message, match: .wholeField)) + } + } + + private func makeHarness( + bookmark: UInt32 = Self.savedBookmark, + clock: TestClock? = nil + ) async throws -> Harness { + let radioID = UUID() + let store = try await PersistenceStore.createTestDataStore(radioID: radioID) + let room = RemoteNodeSessionDTO.testSession( + radioID: radioID, + isConnected: true, + lastSyncTimestamp: bookmark + ) + try await store.saveRemoteNodeSessionDTO(room) + try await store.saveContact(ContactDTO.testContact( + radioID: radioID, + publicKey: room.publicKey, + outPathLength: 0 + )) + let saved = try #require(try await store.fetchRemoteNodeSession(id: room.id)) + let transport = RoomReplayTransport(serverCursor: Self.newestPost) + let mesh = MeshCoreSession(transport: transport, clock: clock) + try await mesh.start() + + let lifetime = ReceiveScope.Lifetime() + let policy = Policy() + let service = RemoteNodeService( + session: mesh, + dataStore: store, + keychainService: KeychainService(), + textRulesPreference: { await policy.snapshot() }, + receiveLifetime: lifetime + ) + let roomService = RoomServerService( + session: mesh, remoteNodeService: service, dataStore: store, radioID: radioID, + textRulesPreference: { await policy.snapshot() }, receiveLifetime: lifetime + ) + return Harness( + room: saved, store: store, transport: transport, mesh: mesh, service: service, + roomService: roomService, lifetime: lifetime, policy: policy + ) + } + + private func admitNextPost(_ harness: Harness) async throws -> RoomMessageDTO? { + guard let timestamp = await harness.transport.nextPost else { return nil } + let saved = try await harness.roomService.handleIncomingMessage( + senderPublicKeyPrefix: Data(harness.room.publicKey.prefix(6)), + timestamp: timestamp, + authorPrefix: Data([0xAB, 0xCD, 0xEF, 0x12]), + text: "Post \(timestamp)" + ) + await harness.transport.acknowledgeNextPost() + return saved + } + + private func holdRequestSlot(_ harness: Harness) async throws -> Task { + let held = Task { + try await harness.mesh.sendAndWait(Data([CommandCode.setTime.rawValue])) { event in + if case .ok = event { return true } + return nil + } + } + try await waitUntil("unrelated command never held the request slot") { + await harness.transport.isRequestHeld + } + return held + } + + private func reserveRecovery(_ harness: Harness) async throws -> Task { + let key = try #require(harness.room.textRulesID) + await harness.service.startSessionKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + try await waitUntil("no recovery reserved") { + await harness.service.roomKeepAliveSchedules[key]?.recovery != nil + } + return try #require(await harness.service.roomKeepAliveSchedules[key]?.recovery) + } + + @Test + func `restarting a room before submission still rewinds once to recover the missed post`() async throws { + let harness = try await makeHarness() + defer { + Task { + await harness.service.stopAllKeepAlives() + await harness.mesh.stop() + } + } + let hiddenText = "Filtered post" + await harness.policy.block(hiddenText) + #expect(try await harness.roomService.handleIncomingMessage( + senderPublicKeyPrefix: Data(harness.room.publicKey.prefix(6)), + timestamp: Self.newestPost, + authorPrefix: Data([0xAB, 0xCD, 0xEF, 0x12]), + text: hiddenText + ) == nil) + #expect(try await harness.store.recentlyBlockedMessages().map(\.body) == [hiddenText]) + #expect(try await harness.store.fetchRemoteNodeSession(id: harness.room.id)?.lastSyncTimestamp == Self.savedBookmark) + + let held = try await holdRequestSlot(harness) + let recovery = try await reserveRecovery(harness) + + #expect(await harness.transport.watermarks.isEmpty) + #expect(await harness.transport.nextPost == nil) + await harness.service.stopSessionKeepAlive(sessionID: harness.room.id) + await harness.service.startSessionKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + await harness.transport.releaseRequest() + #expect(try await held.value) + try await recovery.value + + await harness.service.stopSessionKeepAlive(sessionID: harness.room.id) + #expect(try await admitNextPost(harness)?.timestamp == Self.missingPost) + + for _ in 0..<2 { + try await harness.service.sendScheduledKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + } + let watermarks = await harness.transport.watermarks + #expect(watermarks.first == Self.savedBookmark) + #expect(watermarks.count >= 3) + #expect(watermarks.dropFirst().allSatisfy { $0 == 0 }) + } + + @Test + func `slow replay advances across routine keep-alives and a policy change`() async throws { + let harness = try await makeHarness() + defer { Task { await harness.mesh.stop() } } + try await harness.service.sendScheduledKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + #expect(try await admitNextPost(harness)?.timestamp == Self.missingPost) + + try await harness.service.sendScheduledKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + #expect(await harness.transport.nextPost == Self.newestPost) + await harness.policy.turnOff() + + try await harness.service.sendScheduledKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + #expect(try await admitNextPost(harness)?.timestamp == Self.newestPost) + #expect(await harness.transport.watermarks == [Self.savedBookmark, 0, 0]) + } + + @Test + func `a retired Link record cannot submit its reservation and replacement owns a new rewind`() async throws { + let harness = try await makeHarness() + defer { + Task { + await harness.service.stopAllKeepAlives() + await harness.mesh.stop() + } + } + let held = try await holdRequestSlot(harness) + let recovery = try await reserveRecovery(harness) + + harness.lifetime.retire() + await harness.service.stopSessionKeepAlive(sessionID: harness.room.id) + await harness.transport.releaseRequest() + #expect(try await held.value) + await #expect(throws: CancellationError.self) { try await recovery.value } + #expect(await harness.transport.watermarks.isEmpty) + + await harness.mesh.stop(disconnectTransport: false) + let replacementMesh = MeshCoreSession(transport: harness.transport) + try await replacementMesh.start() + defer { Task { await replacementMesh.stop() } } + + let replacement = RemoteNodeService( + session: replacementMesh, + dataStore: harness.store, + keychainService: KeychainService(), + textRulesPreference: { await harness.policy.snapshot() } + ) + try await replacement.sendScheduledKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + try await replacement.sendScheduledKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + #expect(await harness.transport.watermarks == [Self.savedBookmark, 0]) + } + + @Test + func `a rejected rewind retries the bookmark before routine keep-alives send zero`() async throws { + let harness = try await makeHarness() + defer { Task { await harness.mesh.stop() } } + let sessionID = harness.room.id + let publicKey = harness.room.publicKey + + await harness.transport.rejectNextRequest() + await #expect { + try await harness.service.sendScheduledKeepAlive(sessionID: sessionID, publicKey: publicKey) + } throws: { error in + guard case let .sessionError(meshError) = error as? RemoteNodeError else { return false } + return meshError.deviceErrorCode == .tableFull + } + #expect(await harness.transport.nextPost == nil) + + try await harness.service.sendScheduledKeepAlive(sessionID: sessionID, publicKey: publicKey) + #expect(try await admitNextPost(harness)?.timestamp == Self.missingPost) + try await harness.service.sendScheduledKeepAlive(sessionID: sessionID, publicKey: publicKey) + #expect(await harness.transport.watermarks == [Self.savedBookmark, Self.savedBookmark, 0]) + #expect(await harness.transport.nextPost == Self.newestPost) + } + + @Test + func `a lost rewind response preserves the replay cursor`() async throws { + let clock = TestClock() + let harness = try await makeHarness(clock: clock) + defer { Task { await harness.mesh.stop() } } + let sessionID = harness.room.id + let publicKey = harness.room.publicKey + + await harness.transport.loseNextResponse() + let recovery = Task { + try await harness.service.sendScheduledKeepAlive(sessionID: sessionID, publicKey: publicKey) + } + try await waitUntil("rewind was not sent or the timeout did not start") { + await harness.transport.watermarks == [Self.savedBookmark] && clock.sleeperCount == 1 + } + clock.advance(by: .seconds(SessionConfiguration.default.defaultTimeout)) + await #expect { + try await recovery.value + } throws: { error in + guard case .sessionError(.timeout) = error as? RemoteNodeError else { return false } + return true + } + + #expect(try await admitNextPost(harness)?.timestamp == Self.missingPost) + try await harness.service.sendScheduledKeepAlive(sessionID: sessionID, publicKey: publicKey) + #expect(await harness.transport.watermarks == [Self.savedBookmark, 0]) + #expect(await harness.transport.nextPost == Self.newestPost) + } + + @Test + func `zero bookmark starts a zero-only schedule`() async throws { + let harness = try await makeHarness(bookmark: 0) + defer { Task { await harness.mesh.stop() } } + try await harness.service.sendScheduledKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + try await harness.store.updateRoomActivity(harness.room.id, syncTimestamp: Self.missingPost) + try await harness.service.sendScheduledKeepAlive(sessionID: harness.room.id, publicKey: harness.room.publicKey) + #expect(await harness.transport.watermarks == [0, 0]) + } + + @Test + func `distinct refreshes send the latest bookmark even after a lost request`() async throws { + let harness = try await makeHarness() + defer { Task { await harness.mesh.stop() } } + await harness.transport.dropNextRequest() + try await harness.service.refreshRoom(harness.room) + #expect(await harness.transport.nextPost == nil) + #expect(await harness.transport.watermarks == [Self.savedBookmark]) + + let held = try await holdRequestSlot(harness) + let key = try #require(harness.room.textRulesID) + async let first: Void = harness.service.refreshRoom(harness.room) + async let concurrent: Void = harness.service.refreshRoom(harness.room) + try await waitUntil("no refresh reserved") { await harness.service.roomKeepAliveSchedules[key]?.refresh != nil } + try await harness.store.updateRoomActivity(harness.room.id, syncTimestamp: Self.missingPost) + await harness.transport.releaseRequest() + #expect(try await held.value) + _ = try await (first, concurrent) + #expect(await harness.transport.watermarks == [Self.savedBookmark, Self.missingPost]) + #expect(await harness.transport.nextPost == Self.newestPost) + } + + /// Direct keep-alive semantics from the room server: a positive watermark rewinds, + /// zero preserves the cursor, and a post ACK advances it. + private actor RoomReplayTransport: MeshTransport { + private var stream = AsyncStream.makeStream(of: Data.self) + private var serverCursor: UInt32 + private var dropRequest = false + private var nextResponse: NextResponse? + + private enum NextResponse { + case tableFull + case lost + } + + private(set) var isConnected = false + private(set) var isRequestHeld = false + private(set) var watermarks: [UInt32] = [] + + var receivedData: AsyncStream { + stream.stream + } + + var nextPost: UInt32? { + [RoomKeepAliveRecoveryTests.missingPost, RoomKeepAliveRecoveryTests.newestPost].first { $0 > serverCursor } + } + + init(serverCursor: UInt32) { + self.serverCursor = serverCursor + } + + func connect() { + stream = AsyncStream.makeStream(of: Data.self) + isConnected = true + } + + func disconnect() { + isConnected = false + stream.continuation.finish() + } + + func acknowledgeNextPost() { + if let nextPost { serverCursor = nextPost } + } + + func dropNextRequest() { + dropRequest = true + } + + func rejectNextRequest() { + nextResponse = .tableFull + } + + func loseNextResponse() { + nextResponse = .lost + } + + func releaseRequest() { + stream.continuation.yield(Data([ResponseCode.ok.rawValue])) + isRequestHeld = false + } + + func send(_ data: Data) throws { + switch data.first { + case CommandCode.appStart.rawValue: + stream.continuation.yield(Self.selfInfoPacket()) + case CommandCode.setTime.rawValue: + isRequestHeld = true + case CommandCode.binaryRequest.rawValue: + guard data.count == 38, data[33] == BinaryRequestType.keepAlive.rawValue else { + throw MeshTransportError.sendFailed("Invalid keep-alive command") + } + let watermark = data.suffix(4).withUnsafeBytes { UInt32(littleEndian: $0.loadUnaligned(as: UInt32.self)) } + watermarks.append(watermark) + let response = nextResponse + nextResponse = nil + if response == .tableFull { + stream.continuation.yield(Data([ResponseCode.error.rawValue, ErrorCode.tableFull.rawValue])) + return + } + if dropRequest { + dropRequest = false + } else if watermark > 0 { + serverCursor = watermark + } + if response == .lost { return } + stream.continuation.yield(Data([ResponseCode.messageSent.rawValue, 0, 1, 2, 3, 4, 1, 0, 0, 0])) + default: + throw MeshTransportError.sendFailed("Unexpected test command") + } + } + + private static func selfInfoPacket() -> Data { + var packet = Data([ResponseCode.selfInfo.rawValue, 1, 22, 22]) + packet.append(Data(repeating: 0x01, count: 32)) + packet.append(Data(repeating: 0, count: 12)) + for value: UInt32 in [915_000, 125_000] { + packet.append(withUnsafeBytes(of: value.littleEndian) { Data($0) }) + } + packet.append(contentsOf: [7, 5]) + return packet + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/RoomPostTextRulesTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RoomPostTextRulesTests.swift new file mode 100644 index 0000000000..68e9bfc514 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/RoomPostTextRulesTests.swift @@ -0,0 +1,140 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Signed room post text rules") +struct RoomPostTextRulesTests { + private static let bookmark: UInt32 = 40 + private static let author = Data([0xA1, 0xB2, 0xC3, 0xD4]) + + private struct Fixture { + let store: PersistenceStore + let room: RemoteNodeSessionDTO + let service: RoomServerService + let policy: Policy + let lifetime: ReceiveScope.Lifetime + + func receive(_ text: String, timestamp: UInt32 = 42) async throws -> RoomMessageDTO? { + try await service.handleIncomingMessage( + senderPublicKeyPrefix: Data(room.publicKey.prefix(6)), + timestamp: timestamp, + authorPrefix: RoomPostTextRulesTests.author, + text: text + ) + } + } + + private actor Policy { + private var preference = TextRulesPreference() + + init(_ rule: TextRulesPreference.Rule) { + preference.setSelection(.all, for: .room) + preference.append(rule) + } + + func snapshot() -> TextRulesPreference { + preference + } + + func turnOff() { + preference.setSelection(.off, for: .room) + } + } + + private func makeFixture( + phrase: String, + lookIn: TextRulesPreference.Rule.LookIn = .message + ) async throws -> Fixture { + let radioID = UUID() + let store = try await PersistenceStore.createTestDataStore(radioID: radioID) + let room = RemoteNodeSessionDTO.testSession( + radioID: radioID, lastSyncTimestamp: Self.bookmark, lastMessageDate: Date(timeIntervalSince1970: 39) + ) + try await store.saveRemoteNodeSessionDTO(room) + let saved = try #require(try await store.fetchRemoteNodeSession(id: room.id)) + let policy = Policy(.init(phrase: phrase, lookIn: lookIn, match: .wholeField)) + let mesh = MockMeshCoreSession() + let remoteNode = RemoteNodeService(session: mesh, dataStore: store, keychainService: KeychainService()) + let lifetime = ReceiveScope.Lifetime() + let service = RoomServerService( + session: mesh, remoteNodeService: remoteNode, dataStore: store, radioID: radioID, + textRulesPreference: { await policy.snapshot() }, receiveLifetime: lifetime + ) + return Fixture(store: store, room: saved, service: service, policy: policy, lifetime: lifetime) + } + + @Test + func `drop can recover a room without advancing its bookmark or visible activity`() async throws { + let fixture = try await makeFixture(phrase: " ALERT ") + #expect(try await fixture.receive(" ALERT ") == nil) + + let recovered = try #require(try await fixture.store.fetchRemoteNodeSession(id: fixture.room.id)) + #expect(recovered.isConnected) + #expect(recovered.lastSyncTimestamp == fixture.room.lastSyncTimestamp) + #expect(recovered.lastMessageDate == fixture.room.lastMessageDate) + #expect(recovered.unreadCount == 0) + #expect(try await fixture.service.fetchMessages(sessionID: fixture.room.id).isEmpty) + + let entries = try await fixture.store.recentlyBlockedMessages() + #expect(entries.count == 1) + #expect(entries.first?.body == " ALERT ") + #expect(entries.first?.identity.conversationID == recovered.textRulesID) + + await fixture.policy.turnOff() + #expect(try await fixture.receive(" ALERT ") == nil) + #expect(try await fixture.store.recentlyBlockedCount() == 1) + #expect(try await fixture.receive(" ALERT", timestamp: 41)?.timestamp == 41) + let saved = try #require(try await fixture.store.fetchRemoteNodeSession(id: fixture.room.id)) + #expect(saved.lastSyncTimestamp == 41) + #expect(saved.lastMessageDate != fixture.room.lastMessageDate) + #expect(saved.unreadCount == 1) + } + + @Test + func `short key collision reaches policy and each exact replay keeps its disposition`() async throws { + let allowed = "collision fixture 58777" + let hidden = "collision fixture 123682" + let fixture = try await makeFixture(phrase: hidden) + #expect(try await fixture.receive(allowed)?.text == allowed) + #expect(try await fixture.receive(hidden) == nil) + await fixture.policy.turnOff() + #expect(try await fixture.receive(allowed) == nil) + #expect(try await fixture.receive(hidden) == nil) + #expect(try await fixture.service.fetchMessages(sessionID: fixture.room.id).map(\.text) == [allowed]) + #expect(try await fixture.store.recentlyBlockedMessages().map(\.body) == [hidden]) + } + + @Test + func `only a unique author on the current Radio ID is available to sender rules`() async throws { + let fixture = try await makeFixture(phrase: "Match me", lookIn: .sender) + let foreign = UUID() + func key(tail: UInt8) -> Data { + Self.author + Data(repeating: tail, count: 28) + } + + try await fixture.store.saveContact(.testContact( + radioID: foreign, publicKey: key(tail: 1), name: "Match me" + )) + #expect(try await fixture.receive("Foreign display", timestamp: 41) != nil) + + try await fixture.store.saveContact(.testContact( + radioID: fixture.room.radioID, publicKey: key(tail: 2), name: "Match me" + )) + #expect(try await fixture.receive("Unique", timestamp: 42) == nil) + + try await fixture.store.saveContact(.testContact( + radioID: fixture.room.radioID, publicKey: key(tail: 3), name: "Another author" + )) + #expect(try await fixture.receive("Ambiguous", timestamp: 43) != nil) + #expect(try await fixture.store.recentlyBlockedMessages().map(\.body) == ["Unique"]) + } + + @Test + func `a retired Link record cannot recover a room or archive its post`() async throws { + let fixture = try await makeFixture(phrase: "Hidden") + fixture.lifetime.retire() + #expect(try await fixture.receive("Hidden") == nil) + #expect(try await fixture.store.recentlyBlockedCount() == 0) + #expect(try await fixture.store.fetchRemoteNodeSession(id: fixture.room.id)?.isConnected == false) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/SensorSettingsResponseParserTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/SensorSettingsResponseParserTests.swift new file mode 100644 index 0000000000..646f80de87 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/SensorSettingsResponseParserTests.swift @@ -0,0 +1,51 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Sensor settings replies") +struct SensorSettingsResponseParserTests { + @Test + func `values remain verbatim across pages`() throws { + let first = try SensorSettingsResponseParser.list("3 vars\na=1\nb=x=y\n... next:2", offset: 0) + #expect(first.total == 3) + #expect(first.next == 2) + #expect(first.settings == [SensorSetting(key: "a", value: "1"), SensorSetting(key: "b", value: "x=y")]) + let last = try SensorSettingsResponseParser.list("3 vars\nc=", offset: 2) + #expect(last.settings == [SensorSetting(key: "c", value: "")]) + #expect(last.next == nil) + #expect(try SensorSettingsResponseParser.value("> x=y ") == "x=y ") + #expect(try SensorSettingsResponseParser.value("> ") == "") + #expect(try SensorSettingsResponseParser.value("null") == nil) + #expect(try SensorSettingsResponseParser.list("no custom var", offset: 0).settings.isEmpty) + try SensorSettingsResponseParser.accepted("ok") + } + + @Test(arguments: ["", "0 vars", "-1 vars\na=1", "2 vars\na=1", "1 vars\na=1\na=2", + "2 vars\na=1\n... next:0", "2 vars\na=1\n... next:2", "1 vars\n=1", "1 vars\na"]) + func `malformed pages fail`(response: String) { + #expect(throws: RemoteNodeError.self) { try SensorSettingsResponseParser.list(response, offset: 0) } + } + + @Test + func `empty later page and uppercase setter are not success`() { + #expect(throws: RemoteNodeError.self) { try SensorSettingsResponseParser.list("no custom var", offset: 1) } + #expect(throws: RemoteNodeError.self) { try SensorSettingsResponseParser.accepted("OK") } + #expect(throws: RemoteNodeError.self) { try SensorSettingsResponseParser.accepted("can't find custom var") } + } + + @Test(arguments: ["", "two words", "a\tb", "a\nb", "\0"]) + func `unrepresentable values never become commands`(value: String) { + #expect(throws: RemoteNodeError.self) { try SensorSetting(key: "gps", value: "0").command(setting: value) } + } + + @Test + func `command budget includes correlation prefix in UTF 8`() throws { + let setting = SensorSetting(key: "a", value: "1") + let maximum = try setting.command(setting: String(repeating: "x", count: 144)) + #expect(maximum.utf8.count + SensorSetting.correlationPrefixBytes == 160) + #expect(throws: RemoteNodeError.self) { try setting.command(setting: String(repeating: "x", count: 145)) } + try SensorSetting.validateCommand(String(repeating: "é", count: 78) + "x") + #expect(throws: RemoteNodeError.self) { try SensorSetting.validateCommand(String(repeating: "é", count: 79)) } + #expect(try setting.command(setting: "x=y") == "sensor set a x=y") + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/SettingsServiceRadioWiFiCredentialsTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/SettingsServiceRadioWiFiCredentialsTests.swift new file mode 100644 index 0000000000..5145f7efce --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/SettingsServiceRadioWiFiCredentialsTests.swift @@ -0,0 +1,154 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("SettingsService WiFi credentials") +@MainActor +struct SettingsServiceRadioWiFiCredentialsTests { + @Test + func `password-only Save materializes the firmware default SSID`() async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in", defaultPassword: "build-key")) + let service = SettingsService(session: mock) + let editorID = UUID() + let baseline = try #require(try await service.readRadioWiFiCredentials(editorID: editorID)) + + let receipt = try await service.saveRadioWiFiCredentials( + ssid: baseline.ssid, password: "new-key", baseline: baseline, editorID: editorID, ownerIsCurrent: { true } + ) + + #expect(receipt.ssidAccepted) + #expect(receipt.passwordAccepted) + #expect(receipt.error == nil) + let calls = await mock.runCliCommandCalls + #expect(calls.dropFirst(2).first == "set wifi.ssid built-in") + #expect(calls.count == 4) + await mock.bootWiFiFirmware() + #expect(await mock.wiFiBootUses(ssid: "built-in", password: "new-key")) + await service.retireRadioWiFiOperations() + } + + @Test + func `partial Save keeps the accepted SSID and permits an owned retry`() async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in", defaultPassword: "build-key")) + let service = SettingsService(session: mock) + let editorID = UUID() + let baseline = try #require(try await service.readRadioWiFiCredentials(editorID: editorID)) + await mock.failWiFiCommand("set wifi.pwd new-key", with: .rejected) + + let partial = try await service.saveRadioWiFiCredentials( + ssid: "saved", password: "new-key", baseline: baseline, editorID: editorID, ownerIsCurrent: { true } + ) + + #expect(partial.ssidAccepted) + #expect(!partial.passwordAccepted) + #expect(!partial.uncertain) + #expect(partial.error != nil) + let updated = try #require(partial.updatedBaseline) + let retried = try await service.saveRadioWiFiCredentials( + ssid: "saved", password: "new-key", baseline: updated, editorID: editorID, ownerIsCurrent: { true } + ) + + #expect(retried.error == nil) + #expect(retried.passwordAccepted) + #expect(await mock.runCliCommandCalls.filter { $0 == "set wifi.ssid saved" }.count == 2) + await mock.bootWiFiFirmware() + #expect(await mock.wiFiBootUses(ssid: "saved", password: "new-key")) + await service.retireRadioWiFiOperations() + } + + @Test(arguments: [false, true]) + func `a lost setter reply is uncertain and fresh reads determine the stored value`(_ applied: Bool) async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in", defaultPassword: "build-key")) + let service = SettingsService(session: mock) + let editorID = UUID() + let baseline = try #require(try await service.readRadioWiFiCredentials(editorID: editorID)) + await mock.failWiFiCommand("set wifi.ssid submitted", with: applied ? .timeoutAfterApply : .timeoutBeforeApply) + + let receipt = try await service.saveRadioWiFiCredentials( + ssid: "submitted", password: baseline.password, baseline: baseline, editorID: editorID, ownerIsCurrent: { true } + ) + + #expect(receipt.uncertain) + #expect(!receipt.ssidAccepted) + #expect(await service.radioWiFiRebootPending) + let refreshed = try #require(try await service.readRadioWiFiCredentials(editorID: editorID)) + #expect(refreshed.ssid == (applied ? "submitted" : "built-in")) + await service.retireRadioWiFiOperations() + } + + @Test + func `an explicit empty password replaces a build password after SSID materialization`() async throws { + let mock = MockConfigurationSession() + var firmware = RadioWiFiFirmware(defaultSSID: "built-in", defaultPassword: "build-key") + firmware.savedSSID = "saved" + firmware.savedPassword = "saved-key" + firmware.boot() + await mock.useWiFiFirmware(firmware) + let service = SettingsService(session: mock) + let editorID = UUID() + let baseline = try #require(try await service.readRadioWiFiCredentials(editorID: editorID)) + + let receipt = try await service.saveRadioWiFiCredentials( + ssid: baseline.ssid, password: "", baseline: baseline, editorID: editorID, ownerIsCurrent: { true } + ) + + #expect(receipt.passwordAccepted) + await mock.bootWiFiFirmware() + #expect(await mock.wiFiBootUses(ssid: "saved", password: "")) + await service.retireRadioWiFiOperations() + } + + @Test + func `clear reads back the build default without disabling or changing association`() async throws { + let mock = MockConfigurationSession() + var firmware = RadioWiFiFirmware(defaultSSID: "built-in", defaultPassword: "build-key") + firmware.savedSSID = "saved" + firmware.boot() + await mock.useWiFiFirmware(firmware) + let service = SettingsService(session: mock) + let revision = try #require(service.radioWiFiState.stableRevision()) + + let snapshot = try #require(try await service.clearRadioWiFi(expectedContextID: service.radioWiFiContextID, expectedRevision: revision)) + + #expect(snapshot.networkName == "built-in") + #expect(snapshot.enabled) + #expect(snapshot.associated == true) + #expect(await mock.wiFiBootUses(ssid: "saved", password: "")) + await service.retireRadioWiFiOperations() + } + + @Test + func `configured disable retains association until boot`() async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + let service = SettingsService(session: mock) + let revision = try #require(service.radioWiFiState.stableRevision()) + + try await service.setRadioWiFiEnabled(false, expectedContextID: service.radioWiFiContextID, expectedRevision: revision) + guard case let .supported(probe) = try await service.probeRadioWiFiSettings() else { + throw SettingsServiceError.invalidResponse + } + let observation = try #require(await service.readRadioWiFiObservation(probe: probe)) + + #expect(observation.error == nil) + #expect(observation.networkNameWasRead) + #expect(observation.associated != nil) + #expect(observation.ipAddressWasRead) + #expect(!observation.enabled) + #expect(observation.associated == true) + await mock.bootWiFiFirmware() + guard case let .supported(afterBootProbe) = try await service.probeRadioWiFiSettings() else { + throw SettingsServiceError.invalidResponse + } + let afterBoot = try #require(await service.readRadioWiFiObservation(probe: afterBootProbe)) + #expect(afterBoot.error == nil) + #expect(afterBoot.networkNameWasRead) + #expect(afterBoot.associated != nil) + #expect(afterBoot.ipAddressWasRead) + #expect(afterBoot.associated == false) + await service.retireRadioWiFiOperations() + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/SettingsServiceRadioWiFiFirmwareTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/SettingsServiceRadioWiFiFirmwareTests.swift new file mode 100644 index 0000000000..02459609da --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/SettingsServiceRadioWiFiFirmwareTests.swift @@ -0,0 +1,55 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("SettingsService WiFi firmware defaults") +struct SettingsServiceRadioWiFiFirmwareTests { + @Test + func `build default SSID and raw empty saved password are independent`() async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in", defaultPassword: "build-key")) + let service = SettingsService(session: mock) + + let ssid = try await service.getRadioCLIValue("wifi.ssid") + let password = try await service.getRadioCLIValue("wifi.pwd") + + #expect(ssid == "built-in") + #expect(password?.isEmpty == true) + #expect(await mock.wiFiBootUses(ssid: "built-in", password: "build-key")) + } + + @Test + func `a saved password takes effect at boot only after SSID is materialized`() async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in", defaultPassword: "build-key")) + let service = SettingsService(session: mock) + + try await service.setRadioCLIValue("wifi.pwd", to: "replacement-key") + await mock.bootWiFiFirmware() + #expect(await mock.wiFiBootUses(ssid: "built-in", password: "build-key")) + + try await service.setRadioCLIValue("wifi.ssid", to: "built-in") + await mock.bootWiFiFirmware() + #expect(await mock.wiFiBootUses(ssid: "built-in", password: "replacement-key")) + } + + @Test + func `clear reveals the build default while association stays unchanged until boot`() async throws { + let mock = MockConfigurationSession() + var firmware = RadioWiFiFirmware(defaultSSID: "built-in", defaultPassword: "build-key") + firmware.savedSSID = "saved" + firmware.savedPassword = "saved-key" + firmware.boot() + await mock.useWiFiFirmware(firmware) + let service = SettingsService(session: mock) + + try await service.setRadioCLIValue("wifi.clear", to: nil) + + #expect(try await service.getRadioCLIValue("wifi.ssid") == "built-in") + #expect(try await service.getRadioCLIValue("wifi.pwd")?.isEmpty == true) + #expect(try await service.getRadioCLIValue("wifi.enabled") == "1") + #expect(await mock.wiFiBootUses(ssid: "saved", password: "saved-key")) + await mock.bootWiFiFirmware() + #expect(await mock.wiFiBootUses(ssid: "built-in", password: "build-key")) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/SettingsServiceRadioWiFiOwnershipTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/SettingsServiceRadioWiFiOwnershipTests.swift new file mode 100644 index 0000000000..f4450600f5 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/SettingsServiceRadioWiFiOwnershipTests.swift @@ -0,0 +1,238 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("SettingsService WiFi ownership") +@MainActor +struct SettingsServiceRadioWiFiOwnershipTests { + @Test + func `closing an editor invalidates its known baseline at the service boundary`() async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + let service = SettingsService(session: mock) + let editorID = UUID() + let baseline = try #require(try await service.readRadioWiFiCredentials(editorID: editorID)) + await service.closeRadioWiFiEditor(editorID: editorID) + let before = await mock.runCliCommandCalls.count + + await #expect(throws: CancellationError.self) { + try await service.saveRadioWiFiCredentials( + ssid: "editor", password: "", baseline: baseline, editorID: editorID, ownerIsCurrent: { true } + ) + } + + #expect(await mock.runCliCommandCalls.count == before) + await service.retireRadioWiFiOperations() + } + + @Test + func `raw mutation invalidates an editor baseline before Save admission`() async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + let service = SettingsService(session: mock) + let editorID = UUID() + let baseline = try #require(try await service.readRadioWiFiCredentials(editorID: editorID)) + _ = try await service.runCliCommand("set wifi.ssid terminal") + let before = await mock.runCliCommandCalls.count + + await #expect(throws: CancellationError.self) { + try await service.saveRadioWiFiCredentials( + ssid: "editor", password: "", baseline: baseline, editorID: editorID, ownerIsCurrent: { true } + ) + } + + #expect(await mock.runCliCommandCalls.count == before) + let currentRevision = try #require(service.radioWiFiState.stableRevision()) + let invented = baseline.updating(ssid: baseline.ssid, password: baseline.password, revision: currentRevision) + await #expect(throws: CancellationError.self) { + try await service.saveRadioWiFiCredentials( + ssid: "editor", password: "", baseline: invented, editorID: editorID, ownerIsCurrent: { true } + ) + } + #expect(await mock.runCliCommandCalls.count == before) + await service.retireRadioWiFiOperations() + } + + @Test + func `raw mutation during baseline read prevents issuing the password read`() async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + let service = SettingsService(session: mock) + await mock.holdNextCLIReply() + let read = Task { try await service.readRadioWiFiCredentials(editorID: UUID()) } + do { + try await waitUntil("SSID baseline read held") { await mock.heldCLICommand == "get wifi.ssid" } + } catch { + await mock.releaseHeldCLIReply() + _ = try? await read.value + throw error + } + + do { + _ = try await service.runCliCommand("set wifi.ssid terminal") + } catch { + await mock.releaseHeldCLIReply() + _ = try? await read.value + throw error + } + await mock.releaseHeldCLIReply() + + #expect(try await read.value == nil) + #expect(await mock.runCliCommandCalls.contains("get wifi.pwd") == false) + await service.retireRadioWiFiOperations() + } + + @Test + func `cancelled baseline read never supplies password knowledge or sends the next read`() async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + let service = SettingsService(session: mock) + await mock.holdNextCLIReply() + let read = Task { try await service.readRadioWiFiCredentials(editorID: UUID()) } + do { + try await waitUntil("SSID baseline read held") { await mock.heldCLICommand == "get wifi.ssid" } + } catch { + await mock.releaseHeldCLIReply() + _ = try? await read.value + throw error + } + + read.cancel() + await mock.releaseHeldCLIReply() + await #expect(throws: CancellationError.self) { try await read.value } + #expect(await mock.runCliCommandCalls.contains("get wifi.pwd") == false) + await service.retireRadioWiFiOperations() + } + + @Test + func `foreign mutation after SSID acceptance stops the remaining password command`() async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + let service = SettingsService(session: mock) + let editorID = UUID() + let baseline = try #require(try await service.readRadioWiFiCredentials(editorID: editorID)) + await mock.holdNextCLIReply() + let save = Task { + try await service.saveRadioWiFiCredentials( + ssid: "editor", password: "editor-key", baseline: baseline, editorID: editorID, ownerIsCurrent: { true } + ) + } + do { + try await waitUntil("typed SSID write held") { await mock.heldCLICommand == "set wifi.ssid editor" } + } catch { + await mock.releaseHeldCLIReply() + _ = try? await save.value + throw error + } + + do { + _ = try await service.runCliCommand("set wifi.enabled 0") + } catch { + await mock.releaseHeldCLIReply() + _ = try? await save.value + throw error + } + await mock.releaseHeldCLIReply() + let receipt = try await save.value + + #expect(receipt.ssidAccepted) + #expect(!receipt.passwordAccepted) + #expect(receipt.revision == nil) + #expect(await mock.runCliCommandCalls.filter { $0.hasPrefix("set wifi.pwd ") }.isEmpty) + await service.retireRadioWiFiOperations() + } + + @Test + func `cancelled Tools waiter and retired event consumer cannot discard captured-radio evidence`() async throws { + let stateA = RadioWiFiState(radioID: UUID()) + let stateB = RadioWiFiState(radioID: UUID()) + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + let first = SettingsService(session: mock, radioWiFiState: stateA) + let stream = await first.events() + let consumer = Task { for await _ in stream {} } + await mock.holdNextCLIReply() + let waiter = Task { try await first.runCliCommand("set wifi.ssid terminal") } + do { + try await waitUntil("Tools command held") { await mock.heldCLICommand == "set wifi.ssid terminal" } + } catch { + await mock.releaseHeldCLIReply() + _ = try? await waiter.value + consumer.cancel() + await consumer.value + throw error + } + + waiter.cancel() + consumer.cancel() + await consumer.value + let retirement = Task { await first.retireRadioWiFiOperations() } + do { + try await waitUntil("service closes mutation admission") { await first.radioWiFiOperationsRetired } + } catch { + await mock.releaseHeldCLIReply() + _ = try? await waiter.value + await retirement.value + throw error + } + #expect(stateA.stableRevision() == nil) + #expect(!stateA.rebootPending) + #expect(!stateB.rebootPending) + + await mock.releaseHeldCLIReply() + _ = try await waiter.value + await retirement.value + let replacement = SettingsService(session: mock, radioWiFiState: stateA) + #expect(stateA.rebootPending) + #expect(!stateB.rebootPending) + guard case let .supported(probe) = try await replacement.probeRadioWiFiSettings() else { + throw SettingsServiceError.invalidResponse + } + let observation = try #require(await replacement.readRadioWiFiObservation(probe: probe)) + #expect(observation.error == nil) + #expect(observation.networkNameWasRead) + #expect(observation.associated != nil) + #expect(observation.ipAddressWasRead) + #expect(await replacement.radioWiFiRebootPending) + await replacement.retireRadioWiFiOperations() + } + + @Test + func `retirement joins the held mutation and forbids its second command`() async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + let service = SettingsService(session: mock) + let editorID = UUID() + let baseline = try #require(try await service.readRadioWiFiCredentials(editorID: editorID)) + await mock.holdNextCLIReply() + let save = Task { + try await service.saveRadioWiFiCredentials( + ssid: "editor", password: "editor-key", baseline: baseline, editorID: editorID, ownerIsCurrent: { true } + ) + } + do { + try await waitUntil("SSID write held") { await mock.heldCLICommand == "set wifi.ssid editor" } + } catch { + await mock.releaseHeldCLIReply() + _ = try? await save.value + throw error + } + let retirement = Task { await service.retireRadioWiFiOperations() } + do { + try await waitUntil("retirement starts") { await service.radioWiFiOperationsRetired } + } catch { + await mock.releaseHeldCLIReply() + _ = try? await save.value + await retirement.value + throw error + } + + await mock.releaseHeldCLIReply() + let receipt = try await save.value + await retirement.value + #expect(receipt.ssidAccepted) + #expect(!receipt.passwordAccepted) + #expect(await mock.runCliCommandCalls.filter { $0.hasPrefix("set wifi.pwd ") }.isEmpty) + #expect(await service.radioWiFiWorkers.isEmpty) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/SettingsServiceRadioWiFiRebootTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/SettingsServiceRadioWiFiRebootTests.swift new file mode 100644 index 0000000000..c2748509fe --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/SettingsServiceRadioWiFiRebootTests.swift @@ -0,0 +1,176 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("SettingsService WiFi reboot evidence") +@MainActor +struct SettingsServiceRadioWiFiRebootTests { + @Test + func `generic reboot does not require WiFi apply evidence`() async throws { + let mock = MockConfigurationSession() + let service = SettingsService(session: mock) + #expect(!service.radioWiFiState.rebootPending) + + try await service.reboot() + + #expect(await mock.rebootCallCount == 1) + #expect(await mock.coreStatsReadCount == 0) + #expect(service.radioWiFiState.expectedRebootID == nil) + await service.retireRadioWiFiOperations() + await #expect(throws: CancellationError.self) { try await service.reboot() } + #expect(await mock.rebootCallCount == 1) + } + + @Test + func `a retired reboot cannot replace the current service submitted candidate`() async throws { + let oldMock = MockConfigurationSession() + await oldMock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + await oldMock.failReboot(WiFiTransportError.notConnected) + let state = RadioWiFiState(radioID: UUID()) + let retired = SettingsService(session: oldMock, radioWiFiState: state) + try await retired.setRadioCLIValue("wifi.enabled", to: "0") + await retired.retireRadioWiFiOperations() + let currentMock = MockConfigurationSession() + let current = SettingsService(session: currentMock, radioWiFiState: state) + try await current.reboot() + let submitted = try #require(state.expectedRebootID) + + await #expect(throws: CancellationError.self) { try await retired.reboot() } + + #expect(state.expectedRebootID == submitted) + #expect(await oldMock.rebootCalled == false) + #expect(await currentMock.rebootCalled) + await current.retireRadioWiFiOperations() + } + + @Test + func `retirement joins the actual reboot after its caller is cancelled`() async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + let state = RadioWiFiState(radioID: UUID()) + let old = SettingsService(session: mock, radioWiFiState: state) + try await old.setRadioCLIValue("wifi.enabled", to: "0") + await mock.holdNextReboot() + let caller = Task { try await old.reboot() } + var retirement: Task? + var retirementFinished = false + do { + try await waitUntil("reboot physical completion should remain held") { await mock.rebootHeld } + caller.cancel() + retirement = Task { + await old.retireRadioWiFiOperations() + retirementFinished = true + } + try await waitUntil("retirement should close admission") { await old.radioWiFiOperationsRetired } + #expect(await old.radioWiFiWorkers.count == 1) + #expect(!retirementFinished) + await mock.releaseReboot() + try await caller.value + await retirement?.value + #expect(retirementFinished) + state.noteLinkEnded(contextID: old.radioWiFiContextID) + let currentMock = MockConfigurationSession() + let current = SettingsService(session: currentMock, radioWiFiState: state) + try await current.reboot() + let submitted = try #require(state.expectedRebootID) + await #expect(throws: CancellationError.self) { try await old.reboot() } + #expect(state.expectedRebootID == submitted) + #expect(await currentMock.rebootCalled) + await current.retireRadioWiFiOperations() + } catch { + await mock.releaseReboot() + _ = await caller.result + await retirement?.value + await old.retireRadioWiFiOperations() + throw error + } + } + + @Test + func `submitted reboot candidate survives an early ended link until supported reset proof`() async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + let state = RadioWiFiState(radioID: UUID()) + let first = SettingsService(session: mock, radioWiFiState: state) + try await first.setRadioCLIValue("wifi.enabled", to: "0") + await mock.setCoreStatsUptime(1000) + + await mock.holdNextReboot() + let reboot = Task { try await first.reboot() } + do { + try await waitUntil("reboot write held") { await mock.rebootHeld } + } catch { + await mock.releaseReboot() + _ = try? await reboot.value + throw error + } + guard let candidate = state.expectedRebootID else { + await mock.releaseReboot() + _ = try? await reboot.value + Issue.record("expected an unsubmitted reboot candidate") + return + } + state.noteLinkEnded(contextID: first.radioWiFiContextID) + #expect(!state.clearExpectedReboot( + id: candidate, contextID: UUID(), readRevision: state.revision + )) + await mock.releaseReboot() + try await reboot.value + await mock.setCoreStatsUptime(1) + let replacement = SettingsService(session: mock, radioWiFiState: state) + let statsReads = await mock.coreStatsReadCount + let wrongRadioCleared = await replacement.confirmExpectedRadioWiFiReboot( + id: candidate, expectedRadioID: UUID(), ownerIsCurrent: { true } + ) + #expect(!wrongRadioCleared) + #expect(await mock.coreStatsReadCount == statsReads) + #expect(state.rebootPending) + + #expect(await replacement.confirmExpectedRadioWiFiReboot( + id: candidate, expectedRadioID: state.radioID, ownerIsCurrent: { true } + )) + #expect(!state.rebootPending) + await first.retireRadioWiFiOperations() + await replacement.retireRadioWiFiOperations() + } + + @Test + func `failed reboot submission cannot clear pending evidence`() async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + let state = RadioWiFiState(radioID: UUID()) + let service = SettingsService(session: mock, radioWiFiState: state) + try await service.setRadioCLIValue("wifi.enabled", to: "0") + await mock.failReboot(WiFiTransportError.sendTimeout) + + await #expect(throws: WiFiTransportError.self) { try await service.reboot() } + + #expect(state.expectedRebootID == nil) + #expect(state.rebootPending) + await service.retireRadioWiFiOperations() + } + + @Test + func `ordinary same-radio replacement retains apply evidence`() async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + let state = RadioWiFiState(radioID: UUID()) + let first = SettingsService(session: mock, radioWiFiState: state) + try await first.setRadioCLIValue("wifi.enabled", to: "0") + state.noteLinkEnded(contextID: first.radioWiFiContextID) + await first.retireRadioWiFiOperations() + let replacement = SettingsService(session: mock, radioWiFiState: state) + + guard case let .supported(probe) = try await replacement.probeRadioWiFiSettings() else { + throw SettingsServiceError.invalidResponse + } + let observation = try #require(await replacement.readRadioWiFiObservation(probe: probe)) + #expect(observation.error == nil) + #expect(observation.networkNameWasRead) + #expect(observation.associated != nil) + #expect(observation.ipAddressWasRead) + #expect(state.expectedRebootID == nil) + #expect(state.rebootPending) + await replacement.retireRadioWiFiOperations() + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/SettingsSnapshotWriteTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/SettingsSnapshotWriteTests.swift index 91f8792290..ccece4e385 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/SettingsSnapshotWriteTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/SettingsSnapshotWriteTests.swift @@ -168,17 +168,17 @@ struct SettingsSnapshotWriteTests { } @Test + @MainActor func `a field update does not replace the contact watermark or identity`() async throws { - let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let (manager, _) = try ConnectionManager.createForTesting() + let store = manager.persistenceStore let device = DeviceDTO.testDevice(nodeName: "Old", txPower: 20, lastContactSync: 42) try await store.saveDevice(device) + manager.updateDevice(with: device) - try await store.updateDeviceNodeName(radioID: device.radioID, name: "New") - try await store.updateDeviceTxPower(radioID: device.radioID, txPower: 9) - try await store.updateDeviceOtherParams( - radioID: device.radioID, - intent: OtherParamsIntent(multiAcks: 5) - ) + await manager.applyNodeName("New") + await manager.applyTxPower(9) + await manager.applyOtherParams(OtherParamsIntent(multiAcks: 5)) let loaded = try #require(await store.fetchDevice(radioID: device.radioID)) #expect(loaded.nodeName == "New") @@ -189,9 +189,9 @@ struct SettingsSnapshotWriteTests { #expect(loaded.publicKey == device.publicKey) #expect(loaded.isActive == device.isActive) - await #expect(throws: PersistenceStoreError.self) { - try await store.updateDeviceNodeName(radioID: UUID(), name: "Missing") - } + try await store.deleteDevice(id: device.id) + await manager.applyNodeName("Missing") + #expect(try await store.fetchDevice(id: device.id) == nil) } @Test @@ -527,6 +527,10 @@ private actor SnapshotConfigurationSession: ConfigurationSessionOps { "OK" } + func runCorrelatedCliCommand(_ command: String) async throws -> String { + try await runCliCommand(command) + } + func setCustomVar(key: String, value: String) async throws {} func exportPrivateKey() async throws -> Data { Data() diff --git a/MC1Services/Tests/MC1ServicesTests/Services/StockChannelTextRulesTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/StockChannelTextRulesTests.swift new file mode 100644 index 0000000000..6e8c77bb4f --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/StockChannelTextRulesTests.swift @@ -0,0 +1,135 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("Stock channel Text Rules", .timeLimit(.minutes(1))) +@MainActor +struct StockChannelTextRulesTests { + enum Delivery: CaseIterable { + case catchUp + case live + } + + @Test(arguments: Delivery.allCases) + func `stock arrivals use the rules of the ordinary delivery channel`(delivery: Delivery) async throws { + let radioID = UUID() + let store = try await PersistenceStore.createTestDataStore(radioID: radioID) + let filteredChannel = try await store.saveChannel( + radioID: radioID, + from: .init(index: 1, name: "Filtered", secret: Data(repeating: 0x11, count: ProtocolLimits.channelSecretSize)) + ) + let unfilteredChannel = try await store.saveChannel( + radioID: radioID, + from: .init(index: 2, name: "Unfiltered", secret: Data(repeating: 0x22, count: ProtocolLimits.channelSecretSize)) + ) + let filtered = try #require(try await store.fetchChannel(id: filteredChannel)) + let unfiltered = try #require(try await store.fetchChannel(id: unfilteredChannel)) + let filteredID = try #require(filtered.textRulesID) + let unfilteredID = try #require(unfiltered.textRulesID) + try await store.setTextRulesOverride( + .on, kind: .privateChannel, key: .init(radioID: radioID, conversationID: filteredID) + ) + try await store.setTextRulesOverride( + .off, kind: .privateChannel, key: .init(radioID: radioID, conversationID: unfilteredID) + ) + + let matchingText = "repeat promotion" + var preference = TextRulesPreference() + preference.append(.init(phrase: matchingText, lookIn: .message, match: .wholeField)) + let transport = MockTransport() + let session = MeshCoreSession(transport: transport) + let services = ServiceContainer( + session: session, dataStore: store, radioID: radioID, textRulesPreference: { [preference] in preference } + ) + defer { + Task { + await services.tearDown() + await session.stop() + } + } + services.notificationService.isSuppressingNotifications = true + let starting = Task { try await session.start() } + try await waitUntil("radio handshake command was not sent") { + await transport.sentData.last?.first == CommandCode.appStart.rawValue + } + await transport.simulateReceive(Self.selfInfoFrame()) + try await starting.value + + let coordinator = services.syncCoordinator + let poller = services.messagePollingService + await coordinator.wireMessageHandlers(dependencies: services.syncDependencies, radioID: radioID) + let subscriptions = await session.subscriberCountForTest + await poller.startMessageEventMonitoring(radioID: radioID) + try await waitUntil("message polling did not subscribe") { + await session.subscriberCountForTest > subscriptions + } + + let timestamp = UInt32(Date.now.timeIntervalSince1970) + let blocked = Self.channelFrame(slot: filtered.index, timestamp: timestamp, body: matchingText) + let allowed = Self.channelFrame(slot: unfiltered.index, timestamp: timestamp, body: matchingText) + + switch delivery { + case .catchUp: + let poll = Task { try await poller.pollAllMessages() } + for (offset, frame) in [blocked, allowed, Data([ResponseCode.noMoreMessages.rawValue])].enumerated() { + try await waitUntil("stock get-message command was not sent") { + await transport.sentData.count == offset + 2 + } + #expect(await transport.sentData.last == Data([CommandCode.getMessage.rawValue])) + await transport.simulateReceive(frame) + } + #expect(try await poll.value == 2) + case .live: + await transport.simulateReceive(blocked) + await transport.simulateReceive(allowed) + try await waitUntil("unfiltered channel arrival did not finish") { + coordinator.conversationsVersion >= 1 + } + #expect(await poller.waitForPendingHandlers(timeout: .seconds(2))) + } + + #expect(try await store.fetchMessages(radioID: radioID, channelIndex: filtered.index).isEmpty) + #expect(try await store.fetchMessages(radioID: radioID, channelIndex: unfiltered.index).map(\.text) == [matchingText]) + let drops = try await store.recentlyBlockedMessages() + #expect(drops.map(\.body) == [matchingText]) + #expect(drops.first?.identity.conversationID == filteredID) + #expect(drops.first?.conversationName == filtered.name) + + let unchanged = try #require(try await store.fetchChannel(radioID: radioID, index: filtered.index)) + #expect(unchanged.lastMessageDate == filtered.lastMessageDate) + #expect(unchanged.unreadCount == filtered.unreadCount) + #expect(unchanged.unreadMentionCount == filtered.unreadMentionCount) + #expect(coordinator.conversationsVersion == 1) + } + + private static func channelFrame(slot: UInt8, timestamp: UInt32, body: String) -> Data { + let snrQuarters: UInt8 = 32 + let reserved: UInt8 = 0 + let pathLength: UInt8 = 0 + let textType = MeshTextType.plain.rawValue + var frame = Data([ResponseCode.channelMessageReceivedV3.rawValue, snrQuarters, reserved, reserved, slot, pathLength, textType]) + frame.append(contentsOf: withUnsafeBytes(of: timestamp.littleEndian) { Array($0) }) + frame.append(contentsOf: "Sender: \(body)".utf8) + return frame + } + + private static func selfInfoFrame() -> Data { + let deviceType: UInt8 = 1 + let power: UInt8 = 22 + let publicKey = Data(repeating: 0xAB, count: 32) + let locationAndFlags = Data(repeating: 0, count: 12) + let frequency: UInt32 = 915_000 + let bandwidth: UInt32 = 125_000 + let spreadingFactor: UInt8 = 7 + let codingRate: UInt8 = 5 + var frame = Data([ResponseCode.selfInfo.rawValue, deviceType, power, power]) + frame.append(publicKey) + frame.append(locationAndFlags) + frame.append(contentsOf: withUnsafeBytes(of: frequency.littleEndian) { Array($0) }) + frame.append(contentsOf: withUnsafeBytes(of: bandwidth.littleEndian) { Array($0) }) + frame.append(contentsOf: [spreadingFactor, codingRate]) + frame.append(contentsOf: "Test".utf8) + return frame + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/SimulatorSeedTests.swift b/MC1Services/Tests/MC1ServicesTests/SimulatorSeedTests.swift index 8854ba8062..93c92fee28 100644 --- a/MC1Services/Tests/MC1ServicesTests/SimulatorSeedTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/SimulatorSeedTests.swift @@ -173,7 +173,7 @@ struct SimulatorSeedTests { // Unique-id upsert means a second pass does not duplicate rows. let channels = try await store.fetchChannels(radioID: radioID) - #expect(channels.count == 4) + #expect(channels.count == 5) let repeats = try await store.fetchMessageRepeats(messageID: MockDataProvider.frankRepeatMessageID) #expect(repeats.count == 3) let incoming = try await store.fetchMessageRepeats(messageID: MockDataProvider.aliceMultiPathMessageID) diff --git a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorBackgroundUnreadTests.swift b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorBackgroundUnreadTests.swift index 7cf5cdb4c3..04260d7ffd 100644 --- a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorBackgroundUnreadTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorBackgroundUnreadTests.swift @@ -11,8 +11,8 @@ struct SyncCoordinatorBackgroundUnreadTests { isChannel: Bool, isInForeground: Bool ) async throws { - let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) let radioID = UUID() + let store = try await PersistenceStore.createTestDataStore(radioID: radioID) let services = ServiceContainer( session: MeshCoreSession(transport: SimulatorMockTransport()), dataStore: store, @@ -32,16 +32,12 @@ struct SyncCoordinatorBackgroundUnreadTests { channelRadioID: radioID ) let message = MessageDTO.testChannelMessage(radioID: radioID, channelIndex: channel.index) + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) try await services.syncCoordinator.updateChannelUnreadsAndNotify( messageDTO: message, channel: channel, - channelIndex: channel.index, - senderNodeName: nil, - messageText: message.text, - timestamp: message.timestamp, - hasSelfMention: false, - radioID: radioID, - dependencies: services.syncDependencies + dependencies: services.syncDependencies, + scope: scope ) let saved = try #require(await store.fetchChannel(id: channel.id)) #expect(saved.unreadCount == expectedUnread) @@ -50,13 +46,13 @@ struct SyncCoordinatorBackgroundUnreadTests { try await store.saveContact(contact) services.notificationService.setActiveConversation(contactID: contact.id) let message = MessageDTO.testDirectMessage(radioID: radioID, contactID: contact.id) + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) + let persisted = try #require(await store.fetchContact(id: contact.id)) try await services.syncCoordinator.updateDMUnreadsAndNotify( messageDTO: message, - contactID: contact.id, - contact: contact, - messageText: message.text, - hasSelfMention: false, - dependencies: services.syncDependencies + contact: persisted, + dependencies: services.syncDependencies, + scope: scope ) let saved = try #require(await store.fetchContact(id: contact.id)) #expect(saved.unreadCount == expectedUnread) diff --git a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorClaimTests.swift b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorClaimTests.swift new file mode 100644 index 0000000000..ca712d6895 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorClaimTests.swift @@ -0,0 +1,129 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Sync coordinator claim ownership") +struct SyncCoordinatorClaimTests { + private static let contactWatermark: UInt32 = 1_704_067_200 + private static let waiterTimeout: Duration = .milliseconds(500) + + @Test + @MainActor + func `Ordinary sync completion preserves manual advert inhibition`() async throws { + let coordinator = SyncCoordinator() + let radioID = UUID() + let dataStore = try await PersistenceStore.createTestDataStore( + radioID: radioID, + lastContactSync: Self.contactWatermark + ) + let contacts = MockContactService() + let advertContacts = MockContactService() + try await coordinator.claimManualContactSync() + + let result = try await coordinator.performFullSync( + radioID: radioID, + dataStore: dataStore, + contactService: contacts, + channelService: MockChannelService(), + messagePollingService: MockMessagePollingService() + ) + #expect(result.contacts == .clean) + #expect(await contacts.syncContactsInvocations.count == 1) + + let inhibited = await coordinator.performAdvertContactSync( + fullRefetch: false, + radioID: radioID, + dataStore: dataStore, + contactService: advertContacts + ) + #expect(inhibited == .busy) + #expect(await advertContacts.syncContactsInvocations.isEmpty) + + await coordinator.releaseManualContactSync() + let released = await coordinator.performAdvertContactSync( + fullRefetch: false, + radioID: radioID, + dataStore: dataStore, + contactService: advertContacts + ) + #expect(released == .synced) + #expect(await advertContacts.syncContactsInvocations.count == 1) + } + + @Test(arguments: [false, true]) + @MainActor + func `An interrupted advert waiter leaves another sync waiting`(cancel: Bool) async throws { + let coordinator = SyncCoordinator() + let radioID = UUID() + let dataStore = try await PersistenceStore.createTestDataStore( + radioID: radioID, + lastContactSync: Self.contactWatermark + ) + let advertContacts = GatedContactService() + let contacts = MockContactService() + let channels = MockChannelService() + let messages = MockMessagePollingService() + defer { Task { await advertContacts.release() } } + + let advertTask = Task { + await coordinator.performAdvertContactSync( + fullRefetch: false, + radioID: radioID, + dataStore: dataStore, + contactService: advertContacts + ) + } + await advertContacts.waitForSyncStart() + + let fullSyncTask = Task { + try await coordinator.performFullSync( + radioID: radioID, + dataStore: dataStore, + contactService: contacts, + channelService: channels, + messagePollingService: messages + ) + } + defer { fullSyncTask.cancel() } + try await waitUntil { await coordinator.advertSyncWaiters.count == 1 } + + let interruptedTask = Task { + try await coordinator.waitForAdvertContactSync( + timeout: cancel ? nil : Self.waiterTimeout + ) + } + defer { interruptedTask.cancel() } + try await waitUntil { await coordinator.advertSyncWaiters.count == 2 } + if cancel { interruptedTask.cancel() } + + do { + try await interruptedTask.value + Issue.record("The interrupted waiter must throw") + } catch is CancellationError { + #expect(cancel) + } catch let error as SyncCoordinatorError { + #expect(!cancel) + guard case let .syncFailed(message) = error else { + Issue.record("Expected the advert wait timeout, got \(error)") + return + } + #expect(message == SyncCoordinator.advertContactSyncWaitTimedOutMessage) + } + + #expect(await coordinator.advertSyncWaiters.count == 1) + #expect(await contacts.syncContactsInvocations.isEmpty) + #expect(await channels.syncChannelsInvocations.isEmpty) + #expect(await messages.pollAllMessagesCallCount == 0) + + await advertContacts.release() + #expect(await advertTask.value == .synced) + let result = try await fullSyncTask.value + #expect(result.contacts == .clean) + #expect(result.channels == .clean) + #expect(result.messages == .clean) + #expect(await contacts.syncContactsInvocations.count == 1) + #expect(await channels.syncChannelsInvocations.count == 1) + #expect(await messages.pollAllMessagesCallCount == 1) + #expect(await coordinator.advertSyncWaiters.isEmpty) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorMessageHandlerTests.swift b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorMessageHandlerTests.swift index cc813c20e2..e65bfcafe1 100644 --- a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorMessageHandlerTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorMessageHandlerTests.swift @@ -11,7 +11,7 @@ struct SyncCoordinatorMessageHandlerTests { private func createTestDataStore(radioID: UUID) async throws -> PersistenceStore { let container = try PersistenceStore.createContainer(inMemory: true) let store = PersistenceStore(modelContainer: container) - let device = DeviceDTO.testDevice(id: radioID, nodeName: "TestNode") + let device = DeviceDTO.testDevice(id: radioID, radioID: radioID, nodeName: "TestNode") try await store.saveDevice(device) return store } @@ -267,7 +267,9 @@ struct SyncCoordinatorMessageHandlerTests { text: "hello mesh", snr: nil ) - await mockPolling.capturedContactMessageHandler?(message, contact, .live) + let scope = try #require(await dataStore.captureReceiveScope(radioID: radioID, link: .init())) + let persisted = try #require(await dataStore.fetchContact(id: contact.id)) + await mockPolling.capturedContactMessageHandler?(message, persisted, .live, scope, nil) let updated = try #require( await dataStore.fetchContact(radioID: radioID, publicKey: publicKey) @@ -304,13 +306,181 @@ struct SyncCoordinatorMessageHandlerTests { text: "get cad", snr: nil ) - await mockPolling.capturedContactMessageHandler?(message, contact, .live) + let scope = try #require(await dataStore.captureReceiveScope(radioID: radioID, link: .init())) + let persisted = try #require(await dataStore.fetchContact(id: contact.id)) + await mockPolling.capturedContactMessageHandler?(message, persisted, .live, scope, nil) let saved = try await dataStore.fetchMessages(contactID: contact.id) #expect(saved.count == 1) #expect(saved[0].textType == .cliCommand) } + @Test + func `DM rule drop and replay leave conversation effects untouched`() async throws { + let radioID = UUID() + let store = try await createTestDataStore(radioID: radioID) + let key = Data(repeating: 0xB6, count: 32) + let inputContact = ContactDTO.testContact(radioID: radioID, publicKey: key, name: "Peer", lastHeardTimestamp: 0) + try await store.saveContact(inputContact) + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) + let contact = try #require(await store.fetchContact(id: inputContact.id)) + let polling = MockMessagePollingService() + let (_, services) = try await createTestServices() + let coordinator = SyncCoordinator() + await coordinator.wireMessageHandlers( + dependencies: services.syncDependencies.with(dataStore: store, messagePollingService: polling), + radioID: radioID + ) + let deliver = try #require(await polling.capturedContactMessageHandler) + var preference = TextRulesPreference() + preference.setSelection(.all, for: .directMessage) + preference.append(.init(phrase: "ALERT", lookIn: .message, match: .contains)) + + let arrival = makeDirectArrival(" alert! ", key: key, timestamp: 50) + await deliver(arrival, contact, .live, scope, preference) + await deliver(arrival, contact, .live, scope, nil) + + let entries = try await store.recentlyBlockedMessages() + #expect(entries.count == 1) + #expect(entries.first?.body == arrival.text) + #expect(entries.first?.identity.senderTimestamp == 50) + #expect(entries.first?.contactID == contact.id) + #expect(try await store.fetchMessages(contactID: contact.id).isEmpty) + let current = try #require(await store.fetchContact(id: contact.id)) + #expect(current.unreadCount == 0) + #expect(current.lastMessageDate == nil) + #expect(current.lastHeardTimestamp == contact.lastHeardTimestamp) + #expect(await coordinator.conversationsVersion == 0) + + await deliver(makeDirectArrival("safe", key: key, timestamp: 51), contact, .live, scope, preference) + #expect(try await store.fetchMessages(contactID: contact.id).map(\.text) == ["safe"]) + #expect(try await store.fetchContact(id: contact.id)?.unreadCount == 1) + #expect(await coordinator.conversationsVersion == 1) + } + + @Test + func `DM short key collision uses current policy and exact saved replay`() async throws { + let radioID = UUID() + let store = try await createTestDataStore(radioID: radioID) + let key = Data(repeating: 0xB7, count: 32) + let inputContact = ContactDTO.testContact(radioID: radioID, publicKey: key) + try await store.saveContact(inputContact) + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) + let contact = try #require(await store.fetchContact(id: inputContact.id)) + let polling = MockMessagePollingService() + let (_, services) = try await createTestServices() + let coordinator = SyncCoordinator() + await coordinator.wireMessageHandlers( + dependencies: services.syncDependencies.with(dataStore: store, messagePollingService: polling), + radioID: radioID + ) + let deliver = try #require(await polling.capturedContactMessageHandler) + let first = makeDirectArrival("collision fixture 58777", key: key, timestamp: 50) + let second = makeDirectArrival("collision fixture 123682", key: key, timestamp: 50) + let firstKey = DeduplicationKey.contentBased( + contactID: contact.id, channelIndex: nil, senderNodeName: nil, timestamp: 50, content: first.text + ) + let secondKey = DeduplicationKey.contentBased( + contactID: contact.id, channelIndex: nil, senderNodeName: nil, timestamp: 50, content: second.text + ) + try #require(firstKey == secondKey) + + await deliver(first, contact, .live, scope, nil) + var preference = TextRulesPreference() + preference.setSelection(.all, for: .directMessage) + preference.append(.init(phrase: "collision", lookIn: .message, match: .contains)) + await deliver(second, contact, .live, scope, preference) + await deliver(first, contact, .live, scope, preference) + #expect(try await store.fetchMessages(contactID: contact.id).map(\.text) == [first.text]) + #expect(try await store.recentlyBlockedMessages().map(\.body) == [second.text]) + } + + @Test + func `removed Contact authority cannot write after same ID is restored`() async throws { + let radioID = UUID() + let store = try await createTestDataStore(radioID: radioID) + let key = Data(repeating: 0xB8, count: 32) + let inputContact = ContactDTO.testContact(radioID: radioID, publicKey: key) + try await store.saveContact(inputContact) + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) + let captured = try #require(await store.fetchContact(id: inputContact.id)) + let polling = MockMessagePollingService() + let (_, services) = try await createTestServices() + let coordinator = SyncCoordinator() + await coordinator.wireMessageHandlers( + dependencies: services.syncDependencies.with(dataStore: store, messagePollingService: polling), + radioID: radioID + ) + let deliver = try #require(await polling.capturedContactMessageHandler) + try await store.deleteContact(id: captured.id) + try await store.saveContact(inputContact) + let restored = try #require(await store.fetchContact(id: captured.id)) + try #require(restored.textRulesID != captured.textRulesID) + var preference = TextRulesPreference() + preference.setSelection(.all, for: .directMessage) + preference.append(.init(phrase: "alert", lookIn: .message, match: .contains)) + + await deliver(makeDirectArrival("alert", key: key, timestamp: 50), captured, .live, scope, preference) + await deliver(makeDirectArrival("safe", key: key, timestamp: 51), captured, .live, scope, preference) + #expect(try await store.fetchMessages(contactID: captured.id).isEmpty) + #expect(try await store.recentlyBlockedMessages().isEmpty) + #expect(await coordinator.conversationsVersion == 0) + } + + @Test + func `DM sender rule suppresses reactions while existing Contact block keeps ordinary history`() async throws { + let radioID = UUID() + let store = try await createTestDataStore(radioID: radioID) + let key = Data(repeating: 0xB9, count: 32) + let inputContact = ContactDTO.testContact(radioID: radioID, publicKey: key, name: "Peer") + try await store.saveContact(inputContact) + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) + let contact = try #require(await store.fetchContact(id: inputContact.id)) + let polling = MockMessagePollingService() + let (_, services) = try await createTestServices() + let coordinator = SyncCoordinator() + await coordinator.wireMessageHandlers( + dependencies: services.syncDependencies.with(dataStore: store, messagePollingService: polling), + radioID: radioID + ) + let deliver = try #require(await polling.capturedContactMessageHandler) + let target = MessageDTO.testDirectMessage(radioID: radioID, contactID: contact.id, text: "Ready") + try await store.saveMessage(target) + let reaction = services.reactionService.buildDMReactionText( + emoji: "👍", targetText: target.text, targetTimestamp: target.timestamp + ) + let arrival = makeDirectArrival(reaction, key: key, timestamp: target.timestamp) + var preference = TextRulesPreference() + preference.setSelection(.all, for: .directMessage) + preference.append(.init(phrase: "Peer", lookIn: .sender, match: .wholeField)) + await deliver(arrival, contact, .live, scope, preference) + #expect(try await store.fetchReactions(for: target.id).isEmpty) + #expect(try await store.recentlyBlockedMessages().isEmpty) + + await deliver(arrival, contact, .live, scope, nil) + #expect(try await store.fetchReactions(for: target.id).map(\.emoji) == ["👍"]) + + _ = try await store.updateContactLocalPreferences( + contactID: contact.id, nickname: .unchanged, isBlocked: true, isFavorite: nil, clearRemoteCLI: false + ) + await deliver(makeDirectArrival("ordinary body", key: key, timestamp: 60), contact, .live, scope, preference) + #expect(try await store.recentlyBlockedMessages().isEmpty) + #expect(try await store.fetchMessages(contactID: contact.id).contains { $0.text == "ordinary body" }) + #expect(try await store.fetchContact(id: contact.id)?.unreadCount == 0) + } + + private func makeDirectArrival(_ text: String, key: Data, timestamp: UInt32) -> ContactMessage { + ContactMessage( + senderPublicKeyPrefix: Data(key.prefix(6)), + pathLength: 0, + textType: 0, + senderTimestamp: Date(timeIntervalSince1970: TimeInterval(timestamp)), + signature: nil, + text: text, + snr: nil + ) + } + @Test func `cli data from a chat contact does not reach admin handlers`() async throws { let radioID = UUID() @@ -383,7 +553,8 @@ struct SyncCoordinatorMessageHandlerTests { text: "ChannelPeer: hello channel", snr: nil ) - await mockPolling.capturedChannelMessageHandler?(channelMessage, nil, .live) + let scope = try #require(await dataStore.captureReceiveScope(radioID: radioID, link: .init())) + await mockPolling.capturedChannelMessageHandler?(channelMessage, nil, .live, scope, nil, .now) let updated = try #require( await dataStore.fetchContact(radioID: radioID, publicKey: publicKey) @@ -393,6 +564,61 @@ struct SyncCoordinatorMessageHandlerTests { // MARK: - Live receive region propagation + @Test(.timeLimit(.minutes(1))) + func `channel arrival cannot cross a retired receive scope`() async throws { + let radioID = UUID() + let store = try await createTestDataStore(radioID: radioID) + let radio = try #require(await store.fetchDevice(radioID: radioID)) + let lifetime = ReceiveScope.Lifetime() + let mesh = MockMeshCoreSession() + let poller = MessagePollingService( + session: mesh, dataStore: store, receiveLifetime: lifetime + ) + let mockPolling = MockMessagePollingService() + let (_, services) = try await createTestServices() + let dependencies = services.syncDependencies.with(dataStore: store, messagePollingService: mockPolling) + let coordinator = SyncCoordinator() + await coordinator.wireMessageHandlers(dependencies: dependencies, radioID: radioID) + let handler = try #require(await mockPolling.capturedChannelMessageHandler) + + let (captured, capture) = AsyncStream.makeStream() + let (released, release) = AsyncStream.makeStream() + await poller.setChannelMessageHandler { message, channel, context, scope, preference, arrivedAt in + if message.text == "Peer: before erase" { + capture.yield(scope) + var iterator = released.makeAsyncIterator() + _ = await iterator.next() + } + await handler(message, channel, context, scope, preference, arrivedAt) + } + await poller.startMessageEventMonitoring(radioID: radioID) + try await waitUntil("poller did not subscribe") { await mesh.eventSubscriptionCount == 1 } + let stamp = Date() + await mesh.yieldEvent(.channelMessageReceived(ChannelMessage( + channelIndex: 0, pathLength: 0, textType: 0, senderTimestamp: stamp, text: "Peer: before erase", snr: nil + ))) + var captureIterator = captured.makeAsyncIterator() + let oldScope = try #require(await captureIterator.next()) + + _ = try await store.beginRadioErase(radio) + try await store.cancelRadioErase(radioID: radioID) + #expect(!oldScope.isCurrent) + let lateWrite = MessageDTO.testChannelMessage(radioID: radioID, channelIndex: 0, text: "Before erase") + #expect(try await store.saveReceivedChannelMessage(lateWrite, scope: oldScope, conversationID: nil) == false) + + release.finish() + await mesh.yieldEvent(.channelMessageReceived(ChannelMessage( + channelIndex: 0, pathLength: 0, textType: 0, senderTimestamp: stamp, text: "Peer: after cancellation", snr: nil + ))) + try await waitUntil("fresh channel arrival was not published") { + await coordinator.conversationsVersion == 1 + } + #expect(try await store.fetchMessages(radioID: radioID, channelIndex: 0).map(\.text) == ["after cancellation"]) + + await poller.stopMessageEventMonitoring() + await mesh.finishEventStreams() + } + @Test func `live channel receive with undecryptable RX does not copy regionScope onto Message`() async throws { let radioID = UUID() @@ -442,7 +668,8 @@ struct SyncCoordinatorMessageHandlerTests { text: "NodeAlpha: region scope test", snr: nil ) - await mockPolling.capturedChannelMessageHandler?(channelMessage, nil, .live) + let scope = try #require(await dataStore.captureReceiveScope(radioID: radioID, link: .init())) + await mockPolling.capturedChannelMessageHandler?(channelMessage, nil, .live, scope, nil, .now) let saved = try await dataStore.fetchMessages(radioID: radioID, channelIndex: channelIndex) let message = try #require(saved.first) @@ -489,6 +716,7 @@ struct SyncCoordinatorMessageHandlerTests { let events = coordinator.dataEventBroadcaster.subscribe() await coordinator.wireMessageHandlers(dependencies: dependencies, radioID: radioID) + let scope = try #require(await dataStore.captureReceiveScope(radioID: radioID, link: .init())) await mockPolling.capturedChannelMessageHandler?( ChannelMessage( channelIndex: channelIndex, @@ -499,7 +727,7 @@ struct SyncCoordinatorMessageHandlerTests { snr: nil ), nil, - .live + .live, scope, nil, .now ) let saved = try await dataStore.fetchMessages(radioID: radioID, channelIndex: channelIndex) @@ -512,7 +740,7 @@ struct SyncCoordinatorMessageHandlerTests { var broadcast: MessageDTO? for _ in 0..<8 { guard let event = await iterator.next() else { break } - if case let .channelMessageReceived(message, _) = event { + if case let .channelMessageReceived(message, _, _) = event { broadcast = message break } @@ -568,6 +796,7 @@ struct SyncCoordinatorMessageHandlerTests { let coordinator = SyncCoordinator() await coordinator.wireMessageHandlers(dependencies: dependencies, radioID: radioID) + let scope = try #require(await dataStore.captureReceiveScope(radioID: radioID, link: .init())) await mockPolling.capturedChannelMessageHandler?( ChannelMessage( channelIndex: channelIndex, @@ -578,7 +807,7 @@ struct SyncCoordinatorMessageHandlerTests { snr: nil ), channel, - .live + .live, scope, nil, .now ) let saved = try await dataStore.fetchMessages(radioID: radioID, channelIndex: channelIndex) @@ -636,6 +865,7 @@ struct SyncCoordinatorMessageHandlerTests { let coordinator = SyncCoordinator() await coordinator.wireMessageHandlers(dependencies: dependencies, radioID: radioID) + let scope = try #require(await dataStore.captureReceiveScope(radioID: radioID, link: .init())) await mockPolling.capturedChannelMessageHandler?( ChannelMessage( channelIndex: channelIndex, @@ -646,7 +876,7 @@ struct SyncCoordinatorMessageHandlerTests { snr: nil ), nil, - .live + .live, scope, nil, .now ) #expect(try await dataStore.fetchMessages(radioID: radioID, channelIndex: channelIndex).count == 1) diff --git a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorTests.swift b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorTests.swift index e49de2b638..7cf4faaeff 100644 --- a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorTests.swift @@ -888,48 +888,6 @@ struct SyncCoordinatorTests { #expect(try await dataStore.fetchContact(radioID: testDeviceID, publicKey: keptKey) != nil) } - @Test - @MainActor - func `performAdvertContactSync returns busy when manual contact sync is active`() async throws { - let coordinator = SyncCoordinator() - let mockContactService = MockContactService() - let testDeviceID = UUID() - let dataStore = try await createTestDataStore( - radioID: testDeviceID, - lastContactSync: 1_704_067_200 - ) - await mockContactService.setStubbedSyncContactsResult(.success( - ContactSyncResult( - contactsReceived: 1, - lastSyncTimestamp: UInt32(Date().timeIntervalSince1970), - isIncremental: true - ) - )) - - await coordinator.setManualContactSyncActive(true) - let busy = await coordinator.performAdvertContactSync( - fullRefetch: false, - radioID: testDeviceID, - dataStore: dataStore, - contactService: mockContactService - ) - #expect(busy == .busy) - #expect( - await mockContactService.syncContactsInvocations.isEmpty, - "manual refresh must block advert delta from reaching the radio" - ) - - await coordinator.setManualContactSyncActive(false) - let after = await coordinator.performAdvertContactSync( - fullRefetch: false, - radioID: testDeviceID, - dataStore: dataStore, - contactService: mockContactService - ) - #expect(after == .synced) - #expect(await mockContactService.syncContactsInvocations.count == 1) - } - @Test @MainActor func `far-future watermark recovers with one full refetch then incremental`() async throws { @@ -1511,83 +1469,7 @@ struct SyncCoordinatorTests { "After claimManualContactSync returns, manual flag must already be set" ) - await coordinator.setManualContactSyncActive(false) - } - - @Test - @MainActor - func `waitForAdvertContactSync throws when cancelled`() async throws { - let coordinator = SyncCoordinator() - let gatedContactService = GatedContactService() - let testDeviceID = UUID() - let dataStore = try await createTestDataStore( - radioID: testDeviceID, - lastContactSync: 1_704_067_200 - ) - - let advertTask = Task { - await coordinator.performAdvertContactSync( - fullRefetch: false, - radioID: testDeviceID, - dataStore: dataStore, - contactService: gatedContactService - ) - } - await gatedContactService.waitForSyncStart() - - let waitTask = Task { - try await coordinator.waitForAdvertContactSync() - } - try await Task.sleep(for: .milliseconds(50)) - waitTask.cancel() - - var threwCancellation = false - do { - try await waitTask.value - } catch is CancellationError { - threwCancellation = true - } catch { - Issue.record("Expected CancellationError, got \(error)") - } - #expect(threwCancellation, "Cancelled wait must throw CancellationError, not hang") - - await gatedContactService.release() - _ = await advertTask.value - } - - @Test - @MainActor - func `waitForAdvertContactSync throws when the bound is reached`() async throws { - let coordinator = SyncCoordinator() - let gatedContactService = GatedContactService() - let testDeviceID = UUID() - let dataStore = try await createTestDataStore( - radioID: testDeviceID, - lastContactSync: 1_704_067_200 - ) - - let advertTask = Task { - await coordinator.performAdvertContactSync( - fullRefetch: false, - radioID: testDeviceID, - dataStore: dataStore, - contactService: gatedContactService - ) - } - await gatedContactService.waitForSyncStart() - - var timedOut = false - do { - try await coordinator.waitForAdvertContactSync(timeout: .milliseconds(40)) - } catch let error as SyncCoordinatorError { - if case let .syncFailed(message) = error { - timedOut = message == SyncCoordinator.advertContactSyncWaitTimedOutMessage - } - } - #expect(timedOut, "Wait must surface a timeout error rather than hang or silent-skip") - - await gatedContactService.release() - _ = await advertTask.value + await coordinator.releaseManualContactSync() } @Test @@ -2326,11 +2208,11 @@ actor OrderTrackingMessagePollingService: MessagePollingServiceProtocol { func resumeAutoFetch() async {} - func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext) async -> Void) {} + func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void) {} - func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext) async -> Void) {} + func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void) {} - func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) {} + func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ReceiveScope) async -> Void) {} func setCLIMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) {} } @@ -2365,39 +2247,6 @@ actor DelayingContactService: ContactServiceProtocol { } } -/// Mock contact service that suspends inside `syncContacts` until the test releases it. -/// Lets a test hold an advert delta sync open while another sync path runs. -private actor GatedContactService: ContactServiceProtocol { - private var hasStarted = false - private var startWaiters: [CheckedContinuation] = [] - private var gate: CheckedContinuation? - private var isReleased = false - - /// Waits until `syncContacts` has entered and is holding at the gate. - func waitForSyncStart() async { - if hasStarted { return } - await withCheckedContinuation { startWaiters.append($0) } - } - - /// Lets the held `syncContacts` call return. - func release() { - isReleased = true - gate?.resume() - gate = nil - } - - func syncContacts(radioID _: UUID, since _: Date?) async throws -> ContactSyncResult { - hasStarted = true - while !startWaiters.isEmpty { - startWaiters.removeFirst().resume() - } - if !isReleased { - await withCheckedContinuation { gate = $0 } - } - return ContactSyncResult(contactsReceived: 0, lastSyncTimestamp: 0, isIncremental: true) - } -} - /// Mock channel service that blocks in syncChannels until cancelled. actor DelayingChannelService: ChannelServiceProtocol { private var hasStarted = false diff --git a/MC1Services/Tests/MC1ServicesTests/TextRulesOwnershipTests.swift b/MC1Services/Tests/MC1ServicesTests/TextRulesOwnershipTests.swift new file mode 100644 index 0000000000..f312598366 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/TextRulesOwnershipTests.swift @@ -0,0 +1,160 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Text Rules conversation ownership") +struct TextRulesOwnershipTests { + @Test + func `contact binding survives insert only rollback and later collision`() async throws { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radio = DeviceDTO.testDevice() + try await store.saveDevice(radio) + let prefix = Data([1, 2, 3, 4, 5, 6]) + let contact = ContactDTO.testContact(radioID: radio.radioID, publicKey: prefix + Data(repeating: 1, count: 26)) + let collision = ContactDTO.testContact(radioID: radio.radioID, publicKey: prefix + Data(repeating: 2, count: 26)) + let drop = try makeDrop(radioID: radio.radioID, prefix: prefix) + try await store.recordRecentlyBlockedMessage(drop) + + try await store.saveContact(contact) + let bound = try await store.recentlyBlockedMessages().first + #expect(bound?.contactID == contact.id) + try await store.deleteContactIfUnreferenced(id: contact.id) + #expect(try await store.fetchContact(id: contact.id) != nil) + #expect(try await store.recentlyBlockedMessages().first?.contactID == contact.id) + #expect(try await store.hasRecentlyBlockedMessage(drop.identity)) + + try await store.saveContact(collision) + try await store.deleteContactIfUnreferenced(id: collision.id) + #expect(try await store.fetchContact(id: collision.id) == nil) + #expect(try await store.recentlyBlockedMessages().first?.contactID == contact.id) + + try await store.deleteContact(id: contact.id) + #expect(try await store.recentlyBlockedCount() == 0) + #expect(try await store.fetchContact(id: contact.id) == nil) + } + + @Test + func `removing one of two prefix matches binds only the unbound dm`() async throws { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radio = DeviceDTO.testDevice() + try await store.saveDevice(radio) + let prefix = Data([1, 2, 3, 4, 5, 6]) + let first = ContactDTO.testContact(radioID: radio.radioID, publicKey: prefix + Data(repeating: 1, count: 26)) + let second = ContactDTO.testContact(radioID: radio.radioID, publicKey: prefix + Data(repeating: 2, count: 26)) + let room = RemoteNodeSessionDTO.testSession(radioID: radio.radioID) + try await store.saveContact(first) + try await store.saveContact(second) + try await store.saveRemoteNodeSessionDTO(room) + let roomID = try #require(await store.fetchRemoteNodeSession(id: room.id)?.textRulesID) + let dmDrop = try makeDrop(radioID: radio.radioID, prefix: prefix) + let roomDrop = try makeDrop(radioID: radio.radioID, prefix: Data(prefix.prefix(4)), conversationID: roomID) + try await store.recordRecentlyBlockedMessage(dmDrop) + try await store.recordRecentlyBlockedMessage(roomDrop) + + try await store.deleteContact(id: first.id) + let retained = try await store.recentlyBlockedMessages() + #expect(retained.first(where: { $0.id == dmDrop.id })?.contactID == second.id) + #expect(retained.first(where: { $0.id == roomDrop.id })?.contactID == nil) + + try await store.deleteContact(id: second.id) + #expect(try await store.recentlyBlockedMessages().map(\.id) == [roomDrop.id]) + try await store.deleteRemoteNodeSession(id: room.id) + #expect(try await store.recentlyBlockedCount() == 0) + } + + @Test + func `restoring the same contact UUID does not restore its selection identity or override`() async throws { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radio = DeviceDTO.testDevice() + let contact = ContactDTO.testContact(radioID: radio.radioID) + try await store.saveDevice(radio) + try await store.saveContact(contact) + let selected = try #require(await store.textRulesConversations(kind: .directMessage).first) + try await store.setTextRulesOverride(.on, kind: selected.kind, key: selected.key) + let backupService = AppBackupService() + let backup = try await backupService.export(persistenceStore: store) + let envelope = try parseBackup(data: backup.data) + let exportedContact = try #require(envelope.contacts.first) + #expect(exportedContact.id == contact.id) + + _ = try await backupService.importBackup(envelope: envelope, into: store) + #expect(try await store.textRulesConversation(kind: selected.kind, key: selected.key)?.override == .on) + try await store.deleteContact(id: contact.id) + _ = try await backupService.importBackup(envelope: envelope, into: store) + + let restored = try #require(await store.fetchContact(id: contact.id)) + #expect(restored.textRulesID != selected.key.conversationID) + #expect(restored.textRulesOverride == .inherit) + #expect(try await store.textRulesConversation(kind: selected.kind, key: selected.key) == nil) + await #expect(throws: PersistenceStoreError.self) { + try await store.setTextRulesOverride(.on, kind: selected.kind, key: selected.key) + } + } + + @Test(arguments: [false, true]) + func `ghost reconciliation retires only an abandoned partition`(stillOwned: Bool) async throws { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let current = DeviceDTO.testDevice(publicKey: Data(repeating: 1, count: 32)) + let ghost = DeviceDTO.testDevice(publicKey: Data(repeating: 2, count: 32)) + try await store.saveDevice(current) + try await store.saveDevice(ghost) + try await store.demoteDeviceToGhost(id: ghost.id) + if stillOwned { + try await store.saveDevice(.testDevice(radioID: current.radioID, publicKey: Data(repeating: 3, count: 32))) + } + let contact = ContactDTO.testContact(radioID: current.radioID) + try await store.saveContact(contact) + let before = try #require(await store.fetchContact(id: contact.id)?.textRulesID) + let scope = try #require(await store.captureReceiveScope(radioID: current.radioID, link: .init())) + let currentDrop = try makeDrop(radioID: current.radioID, prefix: nil) + let retainedDrop = try makeDrop(radioID: ghost.radioID, prefix: nil) + try await store.recordRecentlyBlockedMessage(currentDrop) + try await store.recordRecentlyBlockedMessage(retainedDrop) + + #expect(try await store.reconcileGhostIdentity(currentDeviceID: current.id, newPublicKey: ghost.publicKey) == ghost.radioID) + #expect(scope.isCurrent == stillOwned) + #expect(try await store.fetchContact(id: contact.id)?.textRulesID == (stillOwned ? before : nil)) + #expect(try await store.hasRecentlyBlockedMessage(currentDrop.identity) == stillOwned) + #expect(try await store.hasRecentlyBlockedMessage(retainedDrop.identity)) + } + + @Test + func `completing a pending erase preserves a radio that tried to adopt its identity`() async throws { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let current = DeviceDTO.testDevice(publicKey: Data(repeating: 1, count: 32)) + let target = DeviceDTO.testDevice(publicKey: Data(repeating: 2, count: 32), isActive: false).copy { + $0.connectionMethods = [] + } + try await store.saveDevice(current) + try await store.saveDevice(target) + _ = try await store.beginRadioErase(target) + + await #expect(throws: PersistenceStoreError.self) { + _ = try await store.reconcileGhostIdentity(currentDeviceID: current.id, newPublicKey: target.publicKey) + } + try await store.completeRadioErase(radioID: target.radioID) + + let surviving = try #require(await store.fetchDevice(id: current.id)) + #expect(surviving.radioID == current.radioID) + #expect(surviving.publicKey == current.publicKey) + #expect(try await store.fetchDevice(id: target.id) == nil) + } + + private func makeDrop( + radioID: UUID, + prefix: Data?, + conversationID: UUID? = nil + ) throws -> RecentlyBlockedMessageDTO { + let body = "Keep this original" + var preference = TextRulesPreference() + preference.append(.init(phrase: "original", lookIn: .message, match: .contains)) + return try RecentlyBlockedMessageDTO( + identity: .init( + radioID: radioID, conversationID: conversationID, senderPrefix: prefix, + senderTimestamp: 1, textType: 0, wireText: Data(body.utf8) + ), + arrivedAt: Date(), body: body, sender: nil, conversationName: nil, radioName: nil, + match: #require(preference.firstMatch(body: body, sender: nil)) + ) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/TextRulesPreferenceTests.swift b/MC1Services/Tests/MC1ServicesTests/TextRulesPreferenceTests.swift new file mode 100644 index 0000000000..fc7a61e21a --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/TextRulesPreferenceTests.swift @@ -0,0 +1,142 @@ +import Foundation +@testable import MC1Services +import Testing + +@Suite("Text Rules preference") +struct TextRulesPreferenceTests { + @Test + func `type defaults and explicit choices are independent`() { + var preference = TextRulesPreference() + let member = TextRulesPreference.Key(radioID: UUID(), conversationID: UUID()) + let otherRadio = TextRulesPreference.Key(radioID: UUID(), conversationID: member.conversationID) + + for kind in TextRulesPreference.Kind.allCases { + let onByDefault = kind == .publicChannel || kind == .hashtagChannel + #expect(preference.selection(for: kind) == (onByDefault ? .all : .off)) + #expect(preference.effective(for: kind, key: nil, override: .inherit).isOn == onByDefault) + #expect(preference.effective(for: kind, key: member, override: .on) == .init(isOn: true, source: .explicit)) + #expect(preference.effective(for: kind, key: member, override: .off) == .init(isOn: false, source: .explicit)) + + preference.setSelection(.fixed([member]), for: kind) + #expect(preference.effective(for: kind, key: member, override: .inherit) == .init(isOn: true, source: .type)) + #expect(preference.effective(for: kind, key: otherRadio, override: .inherit).source == .fixedExclusion) + #expect(preference.effective(for: kind, key: nil, override: .inherit).source == .fixedExclusion) + + preference.setSelection(.fixed([]), for: kind) + #expect(preference.selection(for: kind).isOn) + #expect(!preference.effective(for: kind, key: member, override: .inherit).isOn) + } + } + + @Test + func `comparison is literal and case insensitive across independent fields`() throws { + let first = TextRulesPreference.Rule(phrase: "CAFÉ*", lookIn: .messageOrSender, match: .contains) + let second = TextRulesPreference.Rule(phrase: "alert", lookIn: .message, match: .contains) + var preference = TextRulesPreference() + preference.append(first) + preference.append(second) + + let body = "Alert café* café*" + let sender = "café* store" + let matched = try #require(preference.firstMatch(body: body, sender: sender)) + #expect(matched.rule == first) + #expect(matched.bodyHighlights.compactMap { $0.range(in: body).map { String(body[$0]) } } == ["café*", "café*"]) + #expect(matched.senderHighlights.compactMap { $0.range(in: sender).map { String(sender[$0]) } } == ["café*"]) + #expect(preference.firstMatch(body: "cafe*", sender: nil) == nil) + #expect(preference.firstMatch(body: "cafe\u{301}*", sender: nil) == nil) + #expect(preference.firstMatch(body: "caféx", sender: nil) == nil) + #expect(preference.firstMatch(body: "", sender: nil) == nil) + #expect(preference.firstMatch(body: nil, sender: "alert") == nil) + #expect(preference.firstMatch(body: nil, sender: sender)?.rule == first) + } + + @Test + func `whole field keeps significant spaces and substring highlights expand to characters`() throws { + var preference = TextRulesPreference() + let whole = TextRulesPreference.Rule(phrase: " ALERT", lookIn: .messageOrSender, match: .wholeField) + preference.append(whole) + #expect(preference.firstMatch(body: " alert", sender: "ALERT")?.rule == whole) + #expect(preference.firstMatch(body: " alert", sender: "ALERT") == nil) + #expect(preference.firstMatch(body: " alert ", sender: nil) == nil) + + preference.append(.init(phrase: "👩", lookIn: .sender, match: .contains)) + let sender = "Radio 👩‍🚒" + let match = try #require(preference.firstMatch(body: nil, sender: sender)) + let range = try #require(match.senderHighlights.first?.range(in: sender)) + #expect(sender[range] == "👩‍🚒") + } + + @Test @MainActor + func `settings edits persist and failed saves leave committed values intact`() throws { + let directory = try makeDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appending(path: "rules.json") + let manager = try makeManager(url: url) + manager.loadTextRules() + + let rule = TextRulesPreference.Rule(phrase: " alert ", lookIn: .message, match: .contains) + try manager.updateTextRules { $0.append(rule) } + try manager.updateTextRules { $0.setSelection(.fixed([]), for: .publicChannel) } + let committed = try #require(manager.textRulesPreference) + #expect(committed.rules == [rule]) + #expect(committed.selection(for: .publicChannel) == .fixed([])) + + let reopened = try makeManager(url: url) + reopened.loadTextRules() + #expect(reopened.textRulesPreference == committed) + let committedBytes = try Data(contentsOf: url) + #expect(throws: CocoaError.self) { + try manager.updateTextRules { $0.append(.init(phrase: " \n", lookIn: .sender, match: .contains)) } + } + #expect(try Data(contentsOf: url) == committedBytes) + + try FileManager.default.removeItem(at: url) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false) + #expect(throws: CocoaError.self) { + try manager.updateTextRules { $0.removeRule(id: rule.id) } + } + #expect(manager.textRulesPreference == committed) + } + + @Test @MainActor + func `unreadable preference bytes survive until successful retry`() async throws { + let directory = try makeDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appending(path: "rules.json") + let malformed = Data("invalid settings".utf8) + try malformed.write(to: url) + + let manager = try makeManager(url: url) + manager.loadTextRules() + #expect(manager.textRulesPreference == nil) + #expect(!manager.isTextRulesLoading) + #expect(throws: CocoaError.self) { + try manager.updateTextRules { $0.setSelection(.all, for: .room) } + } + await manager.retryTextRulesLoad() + #expect(try Data(contentsOf: url) == malformed) + #expect(manager.textRulesPreference == nil) + + let recovered = TextRulesPreference() + try JSONEncoder().encode(recovered).write(to: url) + await manager.retryTextRulesLoad() + #expect(manager.textRulesPreference == recovered) + #expect(!manager.isTextRulesLoading) + } + + private func makeDirectory() throws -> URL { + let directory = URL.temporaryDirectory.appending(path: UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + return directory + } + + @MainActor + private func makeManager(url: URL) throws -> ConnectionManager { + try ConnectionManager( + modelContainer: PersistenceStore.createContainer(inMemory: true), + stateMachine: MockBLEStateMachine(), + transport: MockMeshTransport(), + textRulesURL: url + ) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLEIngressDiagnosticsTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLEIngressDiagnosticsTests.swift new file mode 100644 index 0000000000..a3b90a192d --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLEIngressDiagnosticsTests.swift @@ -0,0 +1,173 @@ +@preconcurrency import CoreBluetooth +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("BLE native ingress diagnostic correlation") +@MainActor +struct BLEIngressDiagnosticsTests { + @Test + func `stream totals retain their binding across native renewal`() async throws { + let fixture = try await Fixture.make() + do { + let firstBinding = String(describing: ObjectIdentifier(fixture.binding)) + let firstStream = await fixture.view.receivedData + fixture.native.rx.value = Data([1]) + for _ in 0..<514 { + fixture.bridge.peripheral(fixture.native.peripheral, didUpdateValueFor: fixture.native.rx, error: nil) + } + let consumer = Task { for await _ in firstStream {} } + consumer.cancel() + await consumer.value + fixture.bridge.peripheral(fixture.native.peripheral, didUpdateValueFor: fixture.native.rx, error: nil) + + let replacement = SessionTransportBinding() + let nextBinding = String(describing: ObjectIdentifier(replacement)) + let nextView = await fixture.adapter.makeSessionTransport(deviceID: fixture.native.deviceID, binding: replacement) + await fixture.adapter.refreshDataStream(sessionBinding: replacement) + let nextStream = await nextView.receivedData + let stale = BLETransportHarness(deviceID: fixture.native.deviceID) + stale.rx.value = Data([9]) + fixture.bridge.peripheral(stale.peripheral, didUpdateValueFor: stale.rx, error: nil) + fixture.native.rx.value = Data([2]) + fixture.bridge.peripheral(fixture.native.peripheral, didUpdateValueFor: fixture.native.rx, error: nil) + await fixture.machine.shutdown() + var received: [Data] = [] + for await frame in nextStream { + received.append(frame) + } + #expect(received == [Data([2])]) + #expect(fixture.native.connectCount == 1) + let messages = try await fixture.records { records in + records.contains { $0.contains("Ingress finished") && $0.contains("binding=\(nextBinding)") } + } + let first = messages.first { $0.contains("Ingress finished") && $0.contains("binding=\(firstBinding)") } + let next = messages.first { $0.contains("Ingress finished") && $0.contains("binding=\(nextBinding)") } + #expect(first?.contains("stream=1 ") == true) + #expect(first?.contains("accepted=512 dropped=2 rejected=0 terminated=1") == true) + #expect(next?.contains("stream=2 ") == true) + #expect(next?.contains("accepted=1 dropped=0 rejected=1 terminated=0") == true) + #expect(messages.contains { $0.contains("reason=buffer-full") && $0.contains("dropped=1") }) + #expect(messages.contains { $0.contains("reason=stream-terminated") && $0.contains("terminated=1") }) + #expect(messages.contains { $0.contains("Ingress rejected origin") && $0.contains("rejected=1") }) + for message in messages where message.contains("[BLE] Ingress") { + for field in ["payload=", "pin=", "password=", "host=", "secret="] { + #expect(!message.localizedCaseInsensitiveContains(field)) + } + } + await fixture.close() + } catch { + await fixture.close() + throw error + } + } + + @Test + func `liveness records distinguish a rejected binding from its successor`() async throws { + let fixture = try await Fixture.make() + do { + let oldBinding = String(describing: ObjectIdentifier(fixture.binding)) + await fixture.machine.setAppSessionLive(deviceID: fixture.native.deviceID, sessionBinding: fixture.binding) + let replacement = SessionTransportBinding() + let currentBinding = String(describing: ObjectIdentifier(replacement)) + _ = await fixture.adapter.makeSessionTransport(deviceID: fixture.native.deviceID, binding: replacement) + await fixture.machine.setAppSessionLive(deviceID: fixture.native.deviceID, sessionBinding: replacement) + await fixture.machine.setAppSessionLive(deviceID: nil, sessionBinding: fixture.binding) + #expect(await fixture.machine.isAppSessionLive(deviceID: fixture.native.deviceID)) + replacement.revoke() + await fixture.machine.setAppSessionLive(deviceID: fixture.native.deviceID, sessionBinding: replacement) + await fixture.machine.setAppSessionLive(deviceID: nil, sessionBinding: replacement) + #expect(await fixture.machine.currentAppSessionLiveDeviceID == nil) + let messages = try await fixture.records { records in + records.contains { $0.contains("Session revoked") && $0.contains("binding=\(currentBinding)") } + } + #expect(messages.contains { + $0.contains("Session live binding=\(currentBinding)") && $0.contains("device=\(fixture.native.deviceID.uuidString.prefix(8))") + }) + #expect(messages.contains { + $0.contains("Session live rejected") && $0.contains("binding=\(oldBinding)") + && $0.contains("currentBinding=\(currentBinding)") && $0.contains("reason=bindingMismatch") + }) + #expect(messages.contains { + $0.contains("Session live rejected") && $0.contains("binding=\(currentBinding)") && $0.contains("reason=revoked") + }) + #expect(messages.contains { $0.contains("Session revoked binding=\(currentBinding)") }) + await fixture.close() + } catch { + await fixture.close() + throw error + } + } + + @MainActor + private struct Fixture { + let native: BLETransportHarness + let machine: BLEStateMachine + let bridge: BLEDelegateHandler + let adapter: iOSBLETransport + let binding: SessionTransportBinding + let view: SessionBoundTransport + let store: PersistenceStore + let buffer: DebugLogBuffer + let previousBuffer: DebugLogBuffer? + let capturedPreference: Any? + + static func make(power: CBManagerState = .poweredOn) async throws -> Self { + let native = BLETransportHarness() + native.power = power + let machine = BLEStateMachine(centralManager: native.central) + let bridge = await machine.delegateHandler + native.enableAutomaticCallbacks(bridge, onWrite: { _ in [] }) + let adapter = iOSBLETransport(stateMachine: machine) + let binding = SessionTransportBinding() + let view = await adapter.makeSessionTransport(deviceID: native.deviceID, binding: binding) + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let buffer = DebugLogBuffer(dataStore: store) + let previous = DebugLogBuffer.shared + let captured = UserDefaults.standard.object(forKey: AppStorageKey.collectDebugLogs.rawValue) + DebugLogBuffer.enableCollection() + DebugLogBuffer.shared = buffer + do { + try await view.connect() + return Self( + native: native, machine: machine, bridge: bridge, adapter: adapter, binding: binding, + view: view, store: store, buffer: buffer, previousBuffer: previous, capturedPreference: captured + ) + } catch { + await machine.shutdown() + await buffer.shutdown() + if DebugLogBuffer.shared === buffer { DebugLogBuffer.shared = previous } + restorePreference(captured) + throw error + } + } + + func records(until isComplete: ([String]) -> Bool) async throws -> [String] { + let deadline = ContinuousClock.now.advanced(by: .seconds(2)) + var messages: [String] = [] + repeat { + await buffer.flush() + messages = try await store.fetchDebugLogEntries(since: .distantPast, limit: 2000).map(\.message) + if isComplete(messages) { return messages } + await Task.yield() + } while ContinuousClock.now < deadline + return messages + } + + private static func restorePreference(_ value: Any?) { + if let value { + UserDefaults.standard.set(value, forKey: AppStorageKey.collectDebugLogs.rawValue) + } else { + UserDefaults.standard.removeObject(forKey: AppStorageKey.collectDebugLogs.rawValue) + } + } + + func close() async { + await machine.shutdown() + await buffer.shutdown() + if DebugLogBuffer.shared === buffer { DebugLogBuffer.shared = previousBuffer } + Self.restorePreference(capturedPreference) + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLEPendingEstablishmentRetirementTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLEPendingEstablishmentRetirementTests.swift new file mode 100644 index 0000000000..a784afd19c --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLEPendingEstablishmentRetirementTests.swift @@ -0,0 +1,212 @@ +@preconcurrency import CoreBluetooth +import Foundation +@testable import MC1Services +@testable import MeshCore +import os +import Testing + +@Suite("BLE pending establishment retirement") +@MainActor +struct BLEPendingEstablishmentRetirementTests { + @Test(arguments: [false, true]) + func `owned close cancels cached dial and discovery before joining setup`(discoveryStarted: Bool) async throws { + let harness = await BLESetupRetirementHarness.make() + let binding = SessionTransportBinding() + let view = await harness.adapter.makeSessionTransport(deviceID: harness.peripheral.identifier, binding: binding) + let session = MeshCoreSession(transport: view) + let resource = ConnectionResource(binding: binding, transport: harness.adapter, session: session, wifi: nil, ble: harness.adapter) + let connectExited = OSAllocatedUnfairLock(initialState: false) + let connecting = Task { + defer { connectExited.withLock { $0 = true } } + do { try await view.connect(); return false } catch { return true } + } + var retirement: Task? + do { + try await harness.awaitCondition { await harness.machine.currentPhase.name == "connecting" } + #expect(harness.native.connectCount == 1) + if discoveryStarted { + await harness.beginDiscovery() + #expect(await harness.machine.currentPhase.name == "discoveringServices") + } + let retired = OSAllocatedUnfairLock(initialState: false) + retirement = Task { + await resource.retire(closePhysical: true) + retired.withLock { $0 = true } + } + try await harness.awaitCondition { !binding.isActive } + let closedPromptly = await harness.observedBeforeDeadline { + retired.withLock { $0 } && connectExited.withLock { $0 } + } + #expect(closedPromptly, "Owned retirement must cancel setup without a callback or setup watchdog") + if !closedPromptly { throw BLESetupRetirementHarness.WaitError.expired } + #expect(await connecting.value) + await retirement?.value + #expect(harness.native.cancellationCount == 1) + #expect(await harness.machine.currentDiscoveryTimeoutExtensions == 0) + #expect(await harness.machine.currentPhase.name == "idle") + + let replacementBinding = SessionTransportBinding() + let replacement = await harness.adapter.makeSessionTransport(deviceID: harness.peripheral.identifier, binding: replacementBinding) + let replacementConnect = Task { try await replacement.connect() } + do { + try await harness.awaitCondition { await harness.machine.currentPhase.name == "connecting" } + await harness.finishDiscovery() + try await replacementConnect.value + try await replacement.sendWithoutResponse(Data([0xA2])) + #expect(harness.native.connectCount == 2) + #expect(harness.native.writePayloads == [Data([0xA2])]) + await resource.retire(closePhysical: true) + #expect(await harness.machine.isConnected) + #expect(replacementBinding.isActive) + replacementBinding.revoke() + await harness.adapter.disconnect(sessionBinding: replacementBinding) + } catch { + await harness.machine.shutdown() + _ = await replacementConnect.result + throw error + } + } catch { + // Failure cleanup happens only after the bounded setup-cancellation assertion. + await harness.machine.shutdown() + _ = await connecting.value + await retirement?.value + await session.stop(disconnectTransport: false) + await session.waitForQuiescence() + throw error + } + await harness.machine.shutdown() + #expect(await !harness.machine.isRSSIKeepaliveActive) + #expect(await session.subscriberCountForTest == 0) + } + + @Test(arguments: [false, true]) + func `established retirement drains actual hardware completion and command reply`(replyBeforeCompletion: Bool) async throws { + let harness = await BLESetupRetirementHarness.make() + let binding = SessionTransportBinding() + let view = try await harness.connect(binding: binding) + let session = MeshCoreSession(transport: view, configuration: SessionConfiguration(defaultTimeout: 2)) + let resource = ConnectionResource(binding: binding, transport: harness.adapter, session: session, wifi: nil, ble: harness.adapter) + var caller: Task? + var retirement: Task? + do { + try await harness.start(session) + let request = Task { try await session.factoryReset() } + caller = request + try await harness.awaitCondition { await harness.machine.setupWriteIsPending } + request.cancel() + await #expect(throws: CancellationError.self) { try await request.value } + let retired = OSAllocatedUnfairLock(initialState: false) + retirement = Task { + await resource.retire(closePhysical: true) + retired.withLock { $0 = true } + } + try await harness.awaitCondition { await !session.sessionIsRunning } + #expect(!retired.withLock { $0 }) + #expect(harness.native.cancellationCount == 0) + if replyBeforeCompletion { await harness.inject(Data([ResponseCode.ok.rawValue])) } + await harness.completeWrite() + await binding.waitForQuiescence() + if !replyBeforeCompletion { + #expect(!retired.withLock { $0 }) + #expect(harness.native.cancellationCount == 0) + await harness.inject(Data([ResponseCode.ok.rawValue])) + } + try await harness.awaitCondition { retired.withLock { $0 } } + await retirement?.value + #expect(harness.native.cancellationCount == 1) + #expect(await session.subscriberCountForTest == 0) + } catch { + await harness.completeWrite() + await harness.inject(Data([ResponseCode.ok.rawValue])) + await harness.machine.shutdown() + _ = await caller?.result + await retirement?.value + await session.stop(disconnectTransport: false) + await session.waitForQuiescence() + throw error + } + await harness.machine.shutdown() + } + + @Test + func `stale adapter and actor cancellation cannot sever a successor dial`() async throws { + let harness = await BLESetupRetirementHarness.make() + let old = SessionTransportBinding() + _ = await harness.adapter.makeSessionTransport(deviceID: harness.peripheral.identifier, binding: old) + let current = SessionTransportBinding() + let view = await harness.adapter.makeSessionTransport(deviceID: harness.peripheral.identifier, binding: current) + let connecting = Task { try await view.connect() } + do { + try await harness.awaitCondition { await harness.machine.currentPhase.name == "connecting" } + #expect(!old.isActive) + let generation = await harness.machine.currentConnectionGeneration + await harness.adapter.cancelPendingEstablishment(sessionBinding: old) + await harness.machine.cancelPendingEstablishment(sessionBinding: old) + await harness.machine.disconnect(sessionBinding: old) + #expect(await harness.machine.currentPhase.name == "connecting") + #expect(await harness.machine.currentConnectionGeneration == generation) + #expect(harness.native.cancellationCount == 0) + await harness.finishDiscovery() + try await connecting.value + try await view.sendWithoutResponse(Data([0xA2])) + #expect(harness.native.writePayloads == [Data([0xA2])]) + current.revoke() + await harness.adapter.disconnect(sessionBinding: current) + } catch { + await harness.machine.shutdown() + _ = await connecting.result + throw error + } + await harness.machine.shutdown() + } + + @Test + func `preserved established lease renews its stream and rejects a stale resource close`() async throws { + let harness = await BLESetupRetirementHarness.make() + let binding = SessionTransportBinding() + let view = try await harness.connect(binding: binding) + let session = MeshCoreSession(transport: view, configuration: SessionConfiguration(defaultTimeout: 2)) + let resource = ConnectionResource(binding: binding, transport: harness.adapter, session: session, wifi: nil, ble: harness.adapter) + var successor: MeshCoreSession? + do { + try await harness.start(session) + await resource.retire(closePhysical: false) + #expect(harness.native.cancellationCount == 0) + #expect(await harness.machine.isConnected) + let replacementBinding = SessionTransportBinding() + let replacementView = await harness.adapter.makeSessionTransport(deviceID: harness.peripheral.identifier, binding: replacementBinding) + await harness.adapter.refreshDataStream(sessionBinding: replacementBinding) + let replacementSession = MeshCoreSession(transport: replacementView, configuration: SessionConfiguration(defaultTimeout: 2)) + successor = replacementSession + try await harness.start(replacementSession) + await resource.retire(closePhysical: true) + #expect(harness.native.cancellationCount == 0) + #expect(await harness.machine.isConnected) + let probe = Task { try await replacementSession.factoryReset() } + do { + try await harness.awaitCondition { await harness.machine.setupWriteIsPending } + await harness.completeWrite() + await harness.inject(Data([ResponseCode.ok.rawValue])) + try await probe.value + } catch { + await harness.machine.shutdown() + _ = await probe.result + throw error + } + #expect(harness.native.connectCount == 1) + replacementBinding.revoke() + await replacementSession.stop(disconnectTransport: false, drainExchanges: true) + await replacementSession.waitForQuiescence() + await harness.adapter.disconnect(sessionBinding: replacementBinding) + } catch { + await harness.machine.shutdown() + await session.stop(disconnectTransport: false) + await successor?.stop(disconnectTransport: false) + await session.waitForQuiescence() + await successor?.waitForQuiescence() + throw error + } + await harness.machine.shutdown() + #expect(await !harness.machine.isRSSIKeepaliveActive) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLEReceiveBurstTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLEReceiveBurstTests.swift new file mode 100644 index 0000000000..08434b51cb --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLEReceiveBurstTests.swift @@ -0,0 +1,231 @@ +import CommonCrypto +@preconcurrency import CoreBluetooth +import CryptoKit +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("BLE RX log burst delivery", .timeLimit(.minutes(1))) +@MainActor +struct BLEReceiveBurstTests { + private static let messageCount = 10 + private static let paths: [Data] = [Data([0x11]), Data([0x22]), Data([0x33])] + private static let timestamp: UInt32 = 1_700_000_000 + private static let secret = Data(repeating: 0x42, count: ChannelCrypto.keySize) + private static let snr: Double = 8 + private static let rssi = -70 + + @Test + func `thirty native notifications preserve every RX entry and outgoing repeat`() async throws { + let native = BLETransportHarness() + let machine = BLEStateMachine(centralManager: native.central) + let bridge = await machine.delegateHandler + native.enableAutomaticCallbacks(bridge, onWrite: BLETransportHarness.emptyRadioFrames) + let adapter = iOSBLETransport(stateMachine: machine) + await adapter.setDeviceID(native.deviceID) + let session = MeshCoreSession(transport: adapter) + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radioID = UUID() + let repeats = HeardRepeatsService(dataStore: store) + let service = RxLogService(session: session, dataStore: store, heardRepeatsService: repeats) + let messages = (1...Self.messageCount).map { index in + MessageDTO.testChannelMessage(radioID: radioID, text: "test\(index)", timestamp: Self.timestamp) + } + + do { + try await store.saveChannel(.testChannel(radioID: radioID, secret: Self.secret)) + for message in messages { + try await store.saveMessage(message) + } + await repeats.configure(radioID: radioID) + try await session.start() + try await waitUntil("the appStart subscription should finish") { + await session.subscriberCountForTest == 0 + } + await service.startEventMonitoring(radioID: radioID) + try await waitUntil("RX log monitoring should subscribe before the burst") { + await session.subscriberCountForTest == 1 + } + let before = try #require(bridge.ingressDiagnostics) + var expectedPayloads: Set = [] + + // Reuse one characteristic with no suspension between callbacks, as the serial BLE queue does. + for message in messages { + native.rx.value = Data([ResponseCode.ok.rawValue]) + bridge.peripheral(native.peripheral, didUpdateValueFor: native.rx, error: nil) + for path in Self.paths { + let frame = try Self.rxFrame(message: message, path: path) + expectedPayloads.insert(Data(frame.dropFirst(3))) + native.rx.value = frame + bridge.peripheral(native.peripheral, didUpdateValueFor: native.rx, error: nil) + } + } + + let expectedEntryCount = Self.messageCount * Self.paths.count + let lastID = try #require(messages.last?.id) + try await waitUntil("all burst entries and repeats should reach persistence") { + let count = try await store.fetchRxLogEntries(radioID: radioID).count + let last = try await store.fetchMessage(id: lastID) + return count == expectedEntryCount && last?.heardRepeats == Self.paths.count + } + + let entries = try await store.fetchRxLogEntries(radioID: radioID) + #expect(entries.count == expectedEntryCount) + #expect(Set(entries.map(\.rawPayload)) == expectedPayloads) + #expect(entries.allSatisfy { $0.decryptStatus == .success && $0.snr == Self.snr && $0.rssi == Self.rssi }) + for message in messages { + let stored = try #require(try await store.fetchMessage(id: message.id)) + let arrivals = try await store.fetchMessageRepeats(messageID: message.id) + #expect(stored.heardRepeats == Self.paths.count) + #expect(arrivals.map(\.pathNodes) == Self.paths) + } + let after = try #require(bridge.ingressDiagnostics) + #expect(after.acceptedFrames - before.acceptedFrames == expectedEntryCount + Self.messageCount) + #expect(after.droppedFrames == 0) + #expect(after.rejectedFrames == 0) + #expect(after.terminatedFrames == 0) + } catch { + await service.stopEventMonitoring() + await session.stop() + await machine.shutdown() + throw error + } + await service.stopEventMonitoring() + await session.stop() + await machine.shutdown() + } + + @Test(arguments: [false, true]) + func `channel sends retain RX notifications during command replies`(restoreScope: Bool) async throws { + let native = BLETransportHarness() + let machine = BLEStateMachine( + writePacingDelay: DevicePlatform.nrf52.recommendedWritePacing, centralManager: native.central + ) + let bridge = await machine.delegateHandler + let adapter = iOSBLETransport(stateMachine: machine) + await adapter.setDeviceID(native.deviceID) + let session = MeshCoreSession(transport: adapter) + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radioID = UUID() + let repeats = HeardRepeatsService(dataStore: store) + let service = RxLogService(session: session, dataStore: store, heardRepeatsService: repeats) + let sender = MessageService(session: session, dataStore: store, contactService: nil) + let messages = (1...Self.messageCount).map { index in + MessageDTO.testChannelMessage( + radioID: radioID, text: "test\(index)", timestamp: Self.timestamp, status: .pending + ) + } + var responses: [Data: [Data]] = [:] + var expectedPayloads: Set = [] + for message in messages { + let arrivals = try Self.paths.map { try Self.rxFrame(message: message, path: $0) } + expectedPayloads.formUnion(arrivals.map { Data($0.dropFirst(3)) }) + let command = PacketBuilder.sendChannelMessage( + channel: 0, text: message.text, timestamp: Date(timeIntervalSince1970: TimeInterval(message.timestamp)) + ) + responses[command] = [arrivals[0], Data([ResponseCode.ok.rawValue]), arrivals[1], arrivals[2]] + } + let responseFrames = responses + native.enableAutomaticCallbacks(bridge) { command in + responseFrames[command] ?? BLETransportHarness.emptyRadioFrames(for: command) + } + + do { + try await store.saveChannel(.testChannel( + radioID: radioID, secret: Self.secret, floodScope: restoreScope ? .region("#test") : .inherit + )) + for message in messages { + try await store.saveMessage(message) + } + await repeats.configure(radioID: radioID) + try await session.start() + try await waitUntil("the appStart subscription should finish") { + await session.subscriberCountForTest == 0 + } + await service.startEventMonitoring(radioID: radioID) + try await waitUntil("RX log monitoring should subscribe before sending") { + await session.subscriberCountForTest == 1 + } + let before = try #require(bridge.ingressDiagnostics) + + try await withThrowingTaskGroup(of: Void.self) { group in + for message in messages { + group.addTask { + try await sender.sendPendingChannelMessage(messageID: message.id) + } + } + try await group.waitForAll() + } + try await waitUntil("all sent echoes should reach persistence") { + for message in messages { + guard try await store.fetchMessage(id: message.id)?.heardRepeats == Self.paths.count else { return false } + } + return true + } + let entries = try await store.fetchRxLogEntries(radioID: radioID) + #expect(entries.count == Self.messageCount * Self.paths.count) + #expect(Set(entries.map(\.rawPayload)) == expectedPayloads) + for message in messages { + let stored = try #require(try await store.fetchMessage(id: message.id)) + #expect(stored.status == .sent) + #expect(stored.heardRepeats == Self.paths.count) + #expect(try await store.fetchMessageRepeats(messageID: message.id).map(\.pathNodes) == Self.paths) + } + let commandsPerMessage = restoreScope ? 3 : 2 + #expect(native.writePayloads.count == 1 + Self.messageCount * commandsPerMessage) + #expect(native.subscriptionCount == 1) + #expect(await session.subscriberCountForTest == 1) + let after = try #require(bridge.ingressDiagnostics) + #expect(after.streamSequence == before.streamSequence) + #expect(after.acceptedFrames - before.acceptedFrames == Self.messageCount * (Self.paths.count + commandsPerMessage)) + #expect(after.droppedFrames == 0) + #expect(after.rejectedFrames == 0) + #expect(after.terminatedFrames == 0) + } catch { + await service.stopEventMonitoring() + await session.stop() + await machine.shutdown() + throw error + } + await service.stopEventMonitoring() + await session.stop() + await machine.shutdown() + } + + private static func rxFrame(message: MessageDTO, path: Data) throws -> Data { + var plaintext = withUnsafeBytes(of: message.timestamp.littleEndian) { Data($0) } + plaintext.append(TextType.plain.rawValue) + plaintext.append(contentsOf: "Test: \(message.text)".utf8) + let blockSize = kCCBlockSizeAES128 + let paddedCount = (plaintext.count + blockSize - 1) / blockSize * blockSize + plaintext.append(Data(count: paddedCount - plaintext.count)) + + var ciphertext = Data(count: plaintext.count) + var encryptedCount: size_t = 0 + let status = ciphertext.withUnsafeMutableBytes { output in + plaintext.withUnsafeBytes { input in + secret.withUnsafeBytes { key in + CCCrypt( + CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionECBMode), + key.baseAddress, kCCKeySizeAES128, nil, input.baseAddress, plaintext.count, + output.baseAddress, plaintext.count, &encryptedCount + ) + } + } + } + try #require(status == kCCSuccess) + try #require(encryptedCount == ciphertext.count) + let mac = HMAC.authenticationCode(for: ciphertext, using: SymmetricKey(data: secret)) + let header = (PayloadType.groupText.rawValue << 2) | RouteType.flood.rawValue + var frame = Data([ + ResponseCode.logData.rawValue, UInt8(Int(snr * 4)), UInt8(bitPattern: Int8(rssi)), + header, UInt8(path.count) + ]) + frame.append(path) + frame.append(contentsOf: SHA256.hash(data: secret).prefix(1)) + frame.append(contentsOf: mac.prefix(ChannelCrypto.macSize)) + frame.append(ciphertext) + return frame + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLERetirementTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLERetirementTests.swift new file mode 100644 index 0000000000..cc9eade113 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLERetirementTests.swift @@ -0,0 +1,166 @@ +@preconcurrency import CoreBluetooth +import Foundation +@testable import MC1Services +@testable import MeshCore +import os +import Testing + +@Suite("Retirement contract BLE admission") +@MainActor +struct BLERetirementTests { + @Test + func `partially submitted pipeline drains its accepted reply after revoking the next unsent frame`() async throws { + let harness = await BLESetupRetirementHarness.make() + let binding = SessionTransportBinding() + let view = try await harness.connect(binding: binding) + let session = MeshCoreSession( + transport: view, + configuration: SessionConfiguration(channelPipelineIdleTimeout: 10, channelPipelineHardTimeout: 10) + ) + let resource = ConnectionResource(binding: binding, transport: harness.adapter, session: session, wifi: nil, ble: harness.adapter) + var pipeline: Task<(received: [ChannelInfo], missing: [UInt8]), Error>? + var retirement: Task? + do { + try await harness.start(session) + let peripheral = harness.peripheral + harness.native.setWriteHandler { data in + if data.first == CommandCode.getChannel.rawValue { + harness.native.isReadyToWrite = false + } + } + pipeline = Task { try await session.getChannels(indices: [0, 1]) } + try await harness.awaitCondition { await harness.machine.isAwaitingWriteWithoutResponseReady } + #expect(harness.native.writePayloads.filter { $0.first == CommandCode.getChannel.rawValue }.count == 1) + pipeline?.cancel() + let retired = OSAllocatedUnfairLock(initialState: false) + retirement = Task { + await resource.retire(closePhysical: false) + retired.withLock { $0 = true } + } + let unsentReleased = await harness.observedBeforeDeadline { + await !harness.machine.isAwaitingWriteWithoutResponseReady + } + #expect(unsentReleased) + guard unsentReleased else { throw BLESetupRetirementHarness.WaitError.expired } + #expect(!retired.withLock { $0 }, "A submitted frame retains the exchange until its reply or original timeout") + #expect(harness.native.cancellationCount == 0) + var reply = Data([ResponseCode.channelInfo.rawValue, 0]) + reply.append(Data(repeating: 0, count: 32 + 16)) + await harness.inject(reply) + try await harness.awaitCondition { retired.withLock { $0 } } + await retirement?.value + _ = await pipeline?.result + #expect(harness.native.writePayloads.filter { $0.first == CommandCode.getChannel.rawValue }.count == 1) + #expect(await session.subscriberCountForTest == 0) + harness.native.setWriteHandler(nil) + harness.native.isReadyToWrite = true + let nextBinding = SessionTransportBinding() + let nextView = await harness.adapter.makeSessionTransport(deviceID: peripheral.identifier, binding: nextBinding) + await harness.adapter.refreshDataStream(sessionBinding: nextBinding) + let next = MeshCoreSession(transport: nextView) + try await harness.start(next) + let probe = Task { try await next.factoryReset() } + do { + try await harness.awaitCondition { await harness.machine.setupWriteIsPending } + await harness.completeWrite() + await harness.inject(Data([ResponseCode.ok.rawValue])) + try await probe.value + } catch { + await harness.machine.shutdown() + _ = await probe.result + await next.stop(disconnectTransport: false) + throw error + } + nextBinding.revoke() + await next.stop(disconnectTransport: false, drainExchanges: true) + await next.waitForQuiescence() + await harness.adapter.disconnect(sessionBinding: nextBinding) + } catch { + harness.native.setWriteHandler(nil) + await harness.machine.shutdown() + _ = await pipeline?.result + await retirement?.value + await session.stop(disconnectTransport: false) + await session.waitForQuiescence() + throw error + } + await harness.machine.shutdown() + #expect(await !harness.machine.isRSSIKeepaliveActive) + } + + @Test(arguments: [false, true]) + func `retirement releases the first unsent pipeline write without a readiness callback`(closePhysical: Bool) async throws { + let harness = await BLESetupRetirementHarness.make() + let binding = SessionTransportBinding() + let view = try await harness.connect(binding: binding) + let session = MeshCoreSession(transport: view, configuration: SessionConfiguration(defaultTimeout: 10)) + let resource = ConnectionResource(binding: binding, transport: harness.adapter, session: session, wifi: nil, ble: harness.adapter) + var pipeline: Task<(received: [ChannelInfo], missing: [UInt8]), Error>? + var retirement: Task? + var successor: MeshCoreSession? + do { + try await harness.start(session) + let writesBeforePipeline = harness.native.writePayloads + harness.native.isReadyToWrite = false + pipeline = Task { try await session.getChannels(indices: [0, 1]) } + try await harness.awaitCondition { await harness.machine.isAwaitingWriteWithoutResponseReady } + #expect(harness.native.writePayloads == writesBeforePipeline) + + let retired = OSAllocatedUnfairLock(initialState: false) + retirement = Task { + await resource.retire(closePhysical: closePhysical) + retired.withLock { $0 = true } + } + let completed = await harness.observedBeforeDeadline { retired.withLock { $0 } } + #expect(completed, "Revocation must release a frame that has never reached the peripheral") + guard completed else { throw BLESetupRetirementHarness.WaitError.expired } + await retirement?.value + _ = await pipeline?.result + #expect(harness.native.writePayloads == writesBeforePipeline) + #expect(await !harness.machine.isAwaitingWriteWithoutResponseReady) + #expect(await session.subscriberCountForTest == 0) + #expect(harness.native.cancellationCount == (closePhysical ? 1 : 0)) + + harness.native.isReadyToWrite = true + let nextBinding = SessionTransportBinding() + let nextView: SessionBoundTransport + if closePhysical { + nextView = try await harness.connect(binding: nextBinding) + } else { + nextView = await harness.adapter.makeSessionTransport(deviceID: harness.peripheral.identifier, binding: nextBinding) + await harness.adapter.refreshDataStream(sessionBinding: nextBinding) + } + let nextSession = MeshCoreSession(transport: nextView, configuration: SessionConfiguration(defaultTimeout: 2)) + successor = nextSession + try await harness.start(nextSession) + let probe = Task { try await nextSession.factoryReset() } + do { + try await harness.awaitCondition { await harness.machine.setupWriteIsPending } + await harness.completeWrite() + await harness.inject(Data([ResponseCode.ok.rawValue])) + try await probe.value + } catch { + await harness.machine.shutdown() + _ = await probe.result + throw error + } + #expect(nextBinding.isActive) + #expect(await nextSession.subscriberCountForTest == 0) + nextBinding.revoke() + await nextSession.stop(disconnectTransport: false, drainExchanges: true) + await nextSession.waitForQuiescence() + await harness.adapter.disconnect(sessionBinding: nextBinding) + } catch { + await harness.machine.shutdown() + _ = await pipeline?.result + await retirement?.value + await session.stop(disconnectTransport: false) + await successor?.stop(disconnectTransport: false) + await session.waitForQuiescence() + await successor?.waitForQuiescence() + throw error + } + await harness.machine.shutdown() + #expect(await !harness.machine.isRSSIKeepaliveActive) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLESessionOwnershipTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLESessionOwnershipTests.swift new file mode 100644 index 0000000000..8c2e77615e --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLESessionOwnershipTests.swift @@ -0,0 +1,182 @@ +@preconcurrency import CoreBluetooth +import Foundation +@testable import MC1Services +import MeshCore +import os +import Testing + +@Suite("BLE session physical ownership") +@MainActor +struct BLESessionOwnershipTests { + @Test + func `revocation after a write slot wait cannot submit over the same physical lease`() async throws { + let native = BLETransportHarness(supportsWriteWithoutResponse: true) + let machine = BLEStateMachine(centralManager: native.central) + let peripheral = native.peripheral + await machine.primeOwnershipConnection(peripheral) + let old = SessionTransportBinding() + let submitted = Task { try await machine.send(Data([1]), sessionBinding: old) } + try await waitUntil { await machine.ownershipWriteIsPending } + let queued = Task { try await machine.send(Data([2]), sessionBinding: old) } + try await waitUntil { await machine.queuedWriteCount == 1 } + + old.revoke() + await machine.completeOwnershipWrite() + try await submitted.value + await #expect(throws: CancellationError.self) { try await queued.value } + #expect(native.writePayloads == [Data([1])]) + + let replacement = Task { + try await machine.send(Data([3]), sessionBinding: SessionTransportBinding()) + } + try await waitUntil { await machine.ownershipWriteIsPending } + await machine.completeOwnershipWrite() + try await replacement.value + #expect(native.writePayloads == [Data([1]), Data([3])]) + await machine.shutdown() + } + + @Test + func `revocation during Write Command backpressure prevents the physical write`() async throws { + let native = BLETransportHarness(supportsWriteWithoutResponse: true) + let machine = BLEStateMachine(centralManager: native.central) + let peripheral = native.peripheral + await machine.primeOwnershipConnection(peripheral) + let old = SessionTransportBinding() + let queued = Task { try await machine.sendWithoutResponse(Data([1]), sessionBinding: old) } + try await waitUntil { await machine.isAwaitingWriteWithoutResponseReady } + + old.revoke() + native.isReadyToWrite = true + await machine.handlePeripheralReadyForWriteWithoutResponse(peripheral) + await #expect(throws: CancellationError.self) { try await queued.value } + #expect(native.writePayloads.isEmpty) + + native.isReadyToWrite = true + try await machine.sendWithoutResponse(Data([2]), sessionBinding: SessionTransportBinding()) + #expect(native.writePayloads == [Data([2])]) + await machine.shutdown() + } + + @Test + func `an older disconnect cannot settle a newer physical generation to idle`() async throws { + let native = BLETransportHarness(supportsWriteWithoutResponse: true) + let machine = BLEStateMachine(centralManager: native.central) + let peripheral = native.peripheral + let central = native.central + await machine.primeOwnershipConnection(peripheral, central: central) + let closing = Task { await machine.disconnect(expectedGeneration: 0) } + try await waitUntil { await machine.currentPhase.name == "disconnecting" } + + await machine.advanceConnectionGeneration() + await machine.primeOwnershipConnection(peripheral) + await closing.value + #expect(await machine.currentPhase.name == "connected") + #expect(await machine.currentConnectionGeneration == 1) + native.isReadyToWrite = true + try await machine.sendWithoutResponse(Data([3]), sessionBinding: SessionTransportBinding()) + #expect(native.writePayloads == [Data([3])]) + await machine.shutdown() + } + + @Test + func `stale session binding cannot renew a stream or reset a replacement live flag`() async { + let native = BLETransportHarness(supportsWriteWithoutResponse: true) + let machine = BLEStateMachine(centralManager: native.central) + let peripheral = native.peripheral + await machine.primeOwnershipConnection(peripheral) + let old = SessionTransportBinding() + let replacement = SessionTransportBinding() + await machine.setSessionBinding(old) + old.revoke() + await machine.setSessionBinding(replacement) + await machine.setAppSessionLive(deviceID: peripheral.identifier, sessionBinding: replacement) + await machine.setWritePacingDelay(0, sessionBinding: replacement) + let staleDeviceID = UUID() + await machine.recordBondVerification(deviceID: peripheral.identifier, at: Date(), sessionBinding: replacement) + await machine.setSessionBinding(old) + await machine.setWritePacingDelay(1, sessionBinding: old) + await machine.recordBondVerification(deviceID: staleDeviceID, at: Date(), sessionBinding: old) + await machine.setAppSessionLive(deviceID: nil, sessionBinding: old) + #expect(await machine.isAppSessionLive(deviceID: peripheral.identifier)) + #expect(await machine.writePacingDelay == 0) + #expect(await machine.hasBondVerification(deviceID: peripheral.identifier)) + #expect(await !machine.hasBondVerification(deviceID: staleDeviceID)) + #expect(await machine.renewDataStream(sessionBinding: old) == nil) + #expect(await machine.renewDataStream(sessionBinding: replacement) != nil) + await machine.shutdown() + } + + @Test + func `a revoked adapter factory cannot replace the current target or physical binding`() async throws { + let native = BLETransportHarness(supportsWriteWithoutResponse: true) + let machine = BLEStateMachine(centralManager: native.central) + let peripheral = native.peripheral + await machine.primeOwnershipConnection(peripheral) + let adapter = iOSBLETransport(stateMachine: machine) + let old = SessionTransportBinding() + _ = await adapter.makeSessionTransport(deviceID: UUID(), binding: old) + let replacement = SessionTransportBinding() + let current = await adapter.makeSessionTransport(deviceID: peripheral.identifier, binding: replacement) + + #expect(!old.isActive) + let stale = await adapter.makeSessionTransport(deviceID: UUID(), binding: old) + await #expect(throws: CancellationError.self) { try await stale.connect() } + #expect(replacement.isActive) + try await current.connect() + native.isReadyToWrite = true + try await current.sendWithoutResponse(Data([3])) + #expect(native.writePayloads == [Data([3])]) + #expect(await machine.connectedDeviceID == peripheral.identifier) + await machine.shutdown() + } + + @Test + func `accepted physical loss revokes old IO and stamps events before later actor generations`() async { + let native = BLETransportHarness(supportsWriteWithoutResponse: true) + let machine = BLEStateMachine(centralManager: native.central) + let peripheral = native.peripheral + await machine.primeOwnershipConnection(peripheral) + let old = SessionTransportBinding() + await machine.setSessionBinding(old) + let events = OSAllocatedUnfairLock<[BLELifecycleEvent]>(initialState: []) + await machine.setLifecycleEventHandler { event, _ in events.withLock { $0.append(event) } } + let acceptedAt = CFAbsoluteTimeGetCurrent() + + await machine.handleDidDisconnect(peripheral, timestamp: acceptedAt, isReconnecting: false, error: nil) + await machine.advanceConnectionGeneration() + + #expect(!old.isActive) + let captured = events.withLock { $0 } + #expect(captured.count == 2) + #expect(captured.allSatisfy { $0.origin.generation == 0 && $0.origin.eventTime == acceptedAt }) + #expect(await machine.currentConnectionGeneration == 1) + await machine.shutdown() + } +} + +private extension BLEStateMachine { + var ownershipWriteIsPending: Bool { + pendingWriteContinuation != nil + } + + func primeOwnershipConnection(_ peripheral: CBPeripheral, central: CBCentralManager? = nil) { + if let central { centralManager = central } + let tx = CBMutableCharacteristic( + type: CBUUID(string: BLEServiceUUID.txCharacteristic), + properties: [.write, .writeWithoutResponse], value: nil, permissions: [.writeable] + ) + let rx = CBMutableCharacteristic( + type: CBUUID(string: BLEServiceUUID.rxCharacteristic), + properties: [.notify], value: nil, permissions: [.readable] + ) + let (_, continuation) = AsyncStream.makeStream(of: Data.self) + phase = .connected(peripheral: peripheral, tx: tx, rx: rx, dataContinuation: continuation) + captureWriteWithoutResponseCapability(from: tx) + } + + func completeOwnershipWrite() { + guard case let .connected(peripheral, tx, _, _) = phase else { return } + handleDidWriteValue(peripheral, characteristic: tx, error: nil, writeSequence: pendingWriteSequence) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineAutoReconnectRetryTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineAutoReconnectRetryTests.swift index 1593060616..feef3cbd2b 100644 --- a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineAutoReconnectRetryTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineAutoReconnectRetryTests.swift @@ -23,8 +23,9 @@ struct BLEStateMachineAutoReconnectRetryTests { private func makeRecorder(on sm: BLEStateMachine) async -> RetryDisconnectionRecorder { let recorder = RetryDisconnectionRecorder() - await sm.setDisconnectionHandler { deviceID, error in - recorder.append(deviceID: deviceID, error: error) + await sm.setLifecycleEventHandler { event, _ in + guard case let .disconnected(origin, error) = event else { return } + recorder.append(deviceID: origin.deviceID, error: error) } return recorder } @@ -153,7 +154,7 @@ struct BLEStateMachineAutoReconnectRetryTests { // MARK: - Test doubles and seams -/// Collects `(deviceID, error)` pairs delivered to `onDisconnection`. +/// Collects `(deviceID, error)` pairs delivered to `BLELifecycleEvent.disconnected`. private final class RetryDisconnectionRecorder: @unchecked Sendable { private(set) var events: [(deviceID: UUID, error: Error?)] = [] diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineBondSuspectRecoveryTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineBondSuspectRecoveryTests.swift index d03756beef..15f6ebd837 100644 --- a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineBondSuspectRecoveryTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineBondSuspectRecoveryTests.swift @@ -30,8 +30,9 @@ struct BLEStateMachineBondSuspectRecoveryTests { await sm.injectTestCentralManager() let peripheral = makeLeakedPeripheral(BondSuspectConnectedPeripheral.self) let recorder = BondSuspectDisconnectionRecorder() - await sm.setDisconnectionHandler { deviceID, error in - recorder.append(deviceID: deviceID, error: error) + await sm.setLifecycleEventHandler { event, _ in + guard case let .disconnected(origin, error) = event else { return } + recorder.append(deviceID: origin.deviceID, error: error) } await sm.appDidBecomeActive() @@ -63,12 +64,16 @@ struct BLEStateMachineBondSuspectRecoveryTests { let peripheral = makeLeakedPeripheral(BondSuspectConnectedPeripheral.self) let autoReconnectRecorder = BondSuspectAutoReconnectRecorder() - await sm.setAutoReconnectingHandler { deviceID, reason in - autoReconnectRecorder.append(deviceID: deviceID, reason: reason) - } let disconnectionRecorder = BondSuspectDisconnectionRecorder() - await sm.setDisconnectionHandler { deviceID, error in - disconnectionRecorder.append(deviceID: deviceID, error: error) + await sm.setLifecycleEventHandler { event, _ in + switch event { + case let .autoReconnecting(origin, reason): + autoReconnectRecorder.append(deviceID: origin.deviceID, reason: reason) + case let .disconnected(origin, error): + disconnectionRecorder.append(deviceID: origin.deviceID, error: error) + default: + break + } } await sm.primeDiscoveryComplete(peripheral: peripheral) @@ -98,7 +103,7 @@ struct BLEStateMachineBondSuspectRecoveryTests { // MARK: - Test doubles and seams -/// Collects `(deviceID, error)` pairs delivered to `onDisconnection`. +/// Collects `(deviceID, error)` pairs delivered to `BLELifecycleEvent.disconnected`. private final class BondSuspectDisconnectionRecorder: @unchecked Sendable { private(set) var events: [(deviceID: UUID, error: Error?)] = [] @@ -107,7 +112,7 @@ private final class BondSuspectDisconnectionRecorder: @unchecked Sendable { } } -/// Collects `(deviceID, reason)` pairs delivered to `onAutoReconnecting`. +/// Collects `(deviceID, reason)` pairs delivered to `BLELifecycleEvent.autoReconnecting`. private final class BondSuspectAutoReconnectRecorder: @unchecked Sendable { private(set) var events: [(deviceID: UUID, reason: String)] = [] diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineCallbackAdmissionTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineCallbackAdmissionTests.swift new file mode 100644 index 0000000000..49ba5510d9 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineCallbackAdmissionTests.swift @@ -0,0 +1,87 @@ +@preconcurrency import CoreBluetooth +import Foundation +@testable import MC1Services +import Testing + +@Suite("BLE delegate callback origin admission") +struct BLEStateMachineCallbackAdmissionTests { + @Test + func `data from replaced peripheral and characteristic does not enter current stream`() async throws { + let active = BLETransportHarness() + let old = BLETransportHarness(deviceID: active.deviceID) + let machine = BLEStateMachine(centralManager: active.central) + let stream = try await active.connect(machine) + let bridge = await machine.delegateHandler + old.rx.value = Data([1]) + active.tx.value = Data([2]) + active.rx.value = Data([3]) + + bridge.peripheral(old.peripheral, didUpdateValueFor: old.rx, error: nil) + bridge.peripheral(active.peripheral, didUpdateValueFor: active.tx, error: nil) + bridge.peripheral(active.peripheral, didUpdateValueFor: old.rx, error: nil) + bridge.peripheral(active.peripheral, didUpdateValueFor: active.rx, error: nil) + await machine.shutdown() + var received: [Data] = [] + for await frame in stream { + received.append(frame) + } + #expect(received == [Data([3])]) + } + + @Test(arguments: [false, true], [false, true]) + func `wrong-origin ACK cannot consume the current write sequence`(oldFails: Bool, wrongCharacteristic: Bool) async throws { + let active = BLETransportHarness() + let old = BLETransportHarness(deviceID: active.deviceID) + let machine = BLEStateMachine(centralManager: active.central) + _ = try await active.connect(machine) + let sender = Task { () -> Bool in + do { try await machine.send(Data([1])); return true } catch { return false } + } + try #require(await active.awaitCondition { active.writePayloads.count == 1 }) + let bridge = await machine.delegateHandler + let failure = NSError(domain: CBErrorDomain, code: CBError.connectionFailed.rawValue) + bridge.peripheral( + wrongCharacteristic ? active.peripheral : old.peripheral, + didWriteValueFor: wrongCharacteristic ? old.tx : active.tx, error: oldFails ? failure : nil + ) + bridge.peripheral(active.peripheral, didWriteValueFor: active.tx, error: oldFails ? nil : failure) + #expect(await sender.value == oldFails) + await machine.shutdown() + } + + @Test(arguments: [false, true], [false, true]) + func `restoration stands down after normal setup owns the machine`(discovering: Bool, sameRadio: Bool) async throws { + let active = BLETransportHarness() + let restored = BLETransportHarness(deviceID: sameRadio ? active.deviceID : UUID()) + let machine = BLEStateMachine(centralManager: active.central) + let pending = Task { try await machine.connect(to: active.deviceID) } + try #require(await active.awaitCondition { active.connectCount == 1 }) + let bridge = await machine.delegateHandler + if discovering { + bridge.centralManager(active.central, didConnect: active.peripheral) + try #require(await active.awaitCondition { active.serviceDiscoveryCount == 1 }) + } + let before = await machine.currentPhase + let continuation: CheckedContinuation + switch before { + case let .connecting(_, pending, _), let .discoveringServices(_, pending): continuation = pending + default: + await machine.shutdown() + _ = await pending.result + Issue.record("Expected active production setup") + return + } + let generation = await machine.currentConnectionGeneration + let delivery = try #require(bridge.restoreState(from: restored.peripheral)) + await delivery.value + let after = await machine.currentPhase + #expect(after.kind == before.kind) + #expect(after.peripheral === active.peripheral) + #expect(await machine.currentConnectionGeneration == generation) + #expect(active.cancellationCount == (sameRadio ? 0 : 1)) + // A displaced setup continuation still needs completion during failing-test cleanup. + if after.kind != before.kind { continuation.resume(throwing: CancellationError()) } + await machine.shutdown() + _ = await pending.result + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineDisconnectionMappingTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineDisconnectionMappingTests.swift index 39c1af16c8..b88cf9c727 100644 --- a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineDisconnectionMappingTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineDisconnectionMappingTests.swift @@ -4,11 +4,8 @@ import Foundation import ObjectiveC import Testing -/// Drives the callback handlers that route disconnection errors through -/// `ReconnectPolicy.makeConnectionError` before invoking `onDisconnection`, -/// proving each site surfaces a bond-invalidation CoreBluetooth error as the -/// typed `BLEError.authenticationFailed` and preserves `nil` for a clean -/// disconnect in the `.connected` branch. +/// Verifies callback handlers preserve bond-invalidation errors as authentication failures +/// and retain nil for a clean disconnect. @Suite("BLEStateMachine disconnection error mapping") struct BLEStateMachineDisconnectionMappingTests { /// A CoreBluetooth error every mapped site must surface as `.authenticationFailed`. @@ -25,12 +22,13 @@ struct BLEStateMachineDisconnectionMappingTests { ) } - /// Installs a recording `onDisconnection` handler and returns the box collecting + /// Installs a recording `BLELifecycleEvent.disconnected` handler and returns the box collecting /// every `(deviceID, error)` pair it receives. private func recordDisconnections(on sm: BLEStateMachine) async -> DisconnectionRecorder { let recorder = DisconnectionRecorder() - await sm.setDisconnectionHandler { deviceID, error in - recorder.append(deviceID: deviceID, error: error) + await sm.setLifecycleEventHandler { event, _ in + guard case let .disconnected(origin, error) = event else { return } + recorder.append(deviceID: origin.deviceID, error: error) } return recorder } @@ -160,9 +158,7 @@ struct BLEStateMachineDisconnectionMappingTests { // MARK: - Test doubles and seams -/// Collects `(deviceID, error)` pairs delivered to `onDisconnection`. -/// The handler is `@Sendable`; the state machine invokes it from its own -/// isolation, and each test awaits the driving call before reading `events`. +/// Records disconnected lifecycle events; tests await the actor callback before reading. private final class DisconnectionRecorder: @unchecked Sendable { private(set) var events: [(deviceID: UUID, error: Error?)] = [] diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineEmptyGATTHoldTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineEmptyGATTHoldTests.swift index 326cf2979e..094f244b4a 100644 --- a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineEmptyGATTHoldTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineEmptyGATTHoldTests.swift @@ -23,8 +23,9 @@ struct BLEStateMachineEmptyGATTHoldTests { await sm.injectCentralManager(central) let peripheral = makeLeakedHoldPeripheral() let recorder = HoldDisconnectionRecorder() - await sm.setDisconnectionHandler { deviceID, error in - recorder.append(deviceID: deviceID, error: error) + await sm.setLifecycleEventHandler { event, _ in + guard case let .disconnected(origin, error) = event else { return } + recorder.append(deviceID: origin.deviceID, error: error) } await sm.primeAutoReconnectingPhase(peripheral: peripheral) return (sm, central, peripheral, recorder) @@ -190,7 +191,7 @@ struct BLEStateMachineEmptyGATTHoldTests { await sm.disconnect() #expect(await sm.currentPhase.name == "idle") - #expect(recorder.events.isEmpty, "Explicit disconnect must never fire onDisconnection") + #expect(recorder.events.isEmpty, "Explicit disconnect must never emit a disconnected event") #expect(central.cancelledPeripherals.contains(peripheral.identifier), "Explicit disconnect must cancel the standing auto-reconnect") } @@ -198,7 +199,7 @@ struct BLEStateMachineEmptyGATTHoldTests { // MARK: - Test doubles and seams -/// Collects `(deviceID, error)` pairs delivered to `onDisconnection`. +/// Collects `(deviceID, error)` pairs delivered to `BLELifecycleEvent.disconnected`. private final class HoldDisconnectionRecorder: @unchecked Sendable { private(set) var events: [(deviceID: UUID, error: Error?)] = [] diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineFringeEncryptionGraceTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineFringeEncryptionGraceTests.swift index 85eb6c839b..c8b5bad722 100644 --- a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineFringeEncryptionGraceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineFringeEncryptionGraceTests.swift @@ -22,8 +22,9 @@ struct BLEStateMachineFringeEncryptionGraceTests { await sm.injectFringeCentralManager(FringeTestCentralManager(delegate: nil, queue: nil)) let peripheral = makeLeakedFringePeripheral() let recorder = FringeDisconnectionRecorder() - await sm.setDisconnectionHandler { deviceID, error in - recorder.append(deviceID: deviceID, error: error) + await sm.setLifecycleEventHandler { event, _ in + guard case let .disconnected(origin, error) = event else { return } + recorder.append(deviceID: origin.deviceID, error: error) } if let bondVerified { await sm.recordBondVerification(deviceID: FringeTestPeripheral.uuid, at: bondVerified) @@ -181,7 +182,7 @@ struct BLEStateMachineFringeEncryptionGraceTests { // MARK: - Test doubles and seams -/// Collects `(deviceID, error)` pairs delivered to `onDisconnection`. +/// Collects `(deviceID, error)` pairs delivered to `BLELifecycleEvent.disconnected`. private final class FringeDisconnectionRecorder: @unchecked Sendable { private(set) var events: [(deviceID: UUID, error: Error?)] = [] diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachinePeripheralEventAdmissionTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachinePeripheralEventAdmissionTests.swift new file mode 100644 index 0000000000..e271abe247 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachinePeripheralEventAdmissionTests.swift @@ -0,0 +1,116 @@ +@preconcurrency import CoreBluetooth +import Foundation +@testable import MC1Services +import Testing + +@Suite("BLE peripheral native object admission") +struct BLEStateMachinePeripheralEventAdmissionTests { + @Test + func `RSSI rejects replaced native objects with the same Device ID`() async throws { + let harness = BLETransportHarness() + let replaced = BLETransportHarness(deviceID: harness.deviceID) + let machine = BLEStateMachine(centralManager: harness.central) + _ = try await harness.connect(machine) + let stamp = Date().addingTimeInterval(-60) + await machine.recordBondVerification(deviceID: harness.deviceID, at: stamp) + await machine.setAppSessionLive(deviceID: harness.deviceID) + let bridge = await machine.delegateHandler + let failure = NSError(domain: CBErrorDomain, code: CBError.connectionFailed.rawValue) + if let rejected = bridge.readRSSI(from: replaced.peripheral, RSSI: -50, error: failure) { + await rejected.value + } + #expect(await machine.consecutiveRSSIFailures == 0) + if let rejected = bridge.readRSSI(from: replaced.peripheral, RSSI: -50, error: nil) { + await rejected.value + } + #expect(await machine.bondVerificationDate(for: harness.deviceID) == stamp) + let failed = try #require(bridge.readRSSI(from: harness.peripheral, RSSI: -50, error: failure)) + await failed.value + #expect(await machine.consecutiveRSSIFailures == 1) + let succeeded = try #require(bridge.readRSSI(from: harness.peripheral, RSSI: -50, error: nil)) + await succeeded.value + #expect(await machine.consecutiveRSSIFailures == 0) + #expect(try #require(await machine.bondVerificationDate(for: harness.deviceID)) > stamp) + await machine.shutdown() + } + + @Test + func `write readiness rejects replaced native objects with the same Device ID`() async throws { + let harness = BLETransportHarness(supportsWriteWithoutResponse: true) + let replaced = BLETransportHarness(deviceID: harness.deviceID) + let machine = BLEStateMachine(centralManager: harness.central) + _ = try await harness.connect(machine) + let sender = Task { () -> Bool in + do { try await machine.sendWithoutResponse(Data([1])); return true } catch { return false } + } + try #require(await harness.awaitCondition { await machine.isAwaitingWriteWithoutResponseReady }) + let bridge = await machine.delegateHandler + harness.isReadyToWrite = true + if let rejected = bridge.readyForWrite(from: replaced.peripheral) { await rejected.value } + #expect(await machine.isAwaitingWriteWithoutResponseReady) + #expect(harness.writePayloads.isEmpty) + let delivered = try #require(bridge.readyForWrite(from: harness.peripheral)) + await delivered.value + #expect(await sender.value) + #expect(harness.writePayloads == [Data([1])]) + await machine.shutdown() + } + + @Test + func `RSSI rejects an admitted callback from a prior physical generation`() async throws { + let harness = BLETransportHarness() + let machine = BLEStateMachine(centralManager: harness.central) + _ = try await harness.connect(machine) + let oldGeneration = await machine.currentConnectionGeneration + try await reconnect(machine, harness: harness) + let stamp = Date().addingTimeInterval(-60) + await machine.recordBondVerification(deviceID: harness.deviceID, at: stamp) + await machine.setAppSessionLive(deviceID: harness.deviceID) + let failure = NSError(domain: CBErrorDomain, code: CBError.connectionFailed.rawValue) + await machine.handleDidReadRSSI(harness.peripheral, RSSI: -50, error: nil, generation: oldGeneration) + await machine.handleDidReadRSSI(harness.peripheral, RSSI: -50, error: failure, generation: oldGeneration) + #expect(await machine.consecutiveRSSIFailures == 0) + #expect(await machine.bondVerificationDate(for: harness.deviceID) == stamp) + await machine.shutdown() + } + + @Test + func `write readiness rejects an admitted callback from a prior physical generation`() async throws { + let harness = BLETransportHarness(supportsWriteWithoutResponse: true) + let machine = BLEStateMachine(centralManager: harness.central) + _ = try await harness.connect(machine) + let oldGeneration = await machine.currentConnectionGeneration + try await reconnect(machine, harness: harness) + let sender = Task { () -> Bool in + do { try await machine.sendWithoutResponse(Data([1])); return true } catch { return false } + } + try #require(await harness.awaitCondition { await machine.isAwaitingWriteWithoutResponseReady }) + harness.isReadyToWrite = true + await machine.handlePeripheralReadyForWriteWithoutResponse(harness.peripheral, generation: oldGeneration) + #expect(await machine.isAwaitingWriteWithoutResponseReady) + #expect(harness.writePayloads.isEmpty) + let bridge = await machine.delegateHandler + let delivered = try #require(bridge.readyForWrite(from: harness.peripheral)) + await delivered.value + #expect(await sender.value) + #expect(harness.writePayloads == [Data([1])]) + await machine.shutdown() + } + + private func reconnect(_ machine: BLEStateMachine, harness: BLETransportHarness) async throws { + let bridge = await machine.delegateHandler + bridge.centralManager( + harness.central, didDisconnectPeripheral: harness.peripheral, + timestamp: CFAbsoluteTimeGetCurrent(), isReconnecting: true, error: nil + ) + try #require(await harness.awaitCondition { await machine.currentPhase.kind == .autoReconnecting }) + bridge.centralManager(harness.central, didConnect: harness.peripheral) + try #require(await harness.awaitCondition { harness.serviceDiscoveryCount == 2 }) + bridge.peripheral(harness.peripheral, didDiscoverServices: nil) + try #require(await harness.awaitCondition { harness.characteristicDiscoveryCount == 2 }) + bridge.peripheral(harness.peripheral, didDiscoverCharacteristicsFor: harness.service, error: nil) + try #require(await harness.awaitCondition { harness.subscriptionCount == 2 }) + bridge.peripheral(harness.peripheral, didUpdateNotificationStateFor: harness.rx, error: nil) + try #require(await harness.awaitCondition { await machine.isConnected }) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineReliabilityTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineReliabilityTests.swift new file mode 100644 index 0000000000..3fc93476c2 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineReliabilityTests.swift @@ -0,0 +1,229 @@ +@preconcurrency import CoreBluetooth +import Foundation +@testable import MC1Services +import Testing + +@Suite("BLEStateMachine production operation lifetimes") +struct BLEStateMachineReliabilityTests { + @Test(arguments: [false, true], [false, true]) + func `cancelled queued writer cannot strand its successor`(paced: Bool, firstTimesOut: Bool) async throws { + let harness = BLETransportHarness() + let clock = BLETestOperationClock() + let pacing: TimeInterval = paced ? 1 : 0 + let machine = BLEStateMachine(writePacingDelay: pacing, centralManager: harness.central, operationClock: clock.clock) + _ = try await harness.connect(machine) + + let first = Task { await result { try await machine.send(Data([1])) } } + try #require(await harness.awaitCondition { harness.writePayloads.count == 1 && clock.sleeperCount == 1 }) + let cancelled = Task { await result { try await machine.send(Data([2])) } } + try #require(await harness.awaitCondition { await machine.queuedWriteCount == 1 }) + let successor = Task { await result { try await machine.send(Data([3])) } } + try #require(await harness.awaitCondition { await machine.queuedWriteCount == 2 }) + cancelled.cancel() + + if firstTimesOut { + clock.advance(by: .seconds(5)) + } else { + await harness.acknowledge(machine) + } + let cancelledResult = await cancelled.value + #expect(cancelledResult.isCancellation) + if paced { + // The cancelled writer must hand its pacing obligation to the successor. + _ = await harness.awaitCondition { clock.sleeperCount == 1 } + clock.advance(by: .seconds(pacing)) + } + let issued = await harness.awaitCondition { harness.writePayloads == [Data([1]), Data([3])] } + #expect(issued, "The successor must issue without unrelated traffic or teardown") + if issued { + if firstTimesOut { await harness.acknowledge(machine) } + await harness.acknowledge(machine) + } + if !issued { await machine.shutdown() } + let firstResult = await first.value + let successorResult = await successor.value + await machine.shutdown() + #expect(firstTimesOut ? firstResult.isTimeout : firstResult.isSuccess) + #expect(successorResult.isSuccess) + #expect(await machine.queuedWriteCount == 0) + } + + @Test + func `powered-off callback before wait still gives the wait a deadline`() async throws { + let harness = BLETransportHarness() + let clock = BLETestOperationClock() + harness.power = .poweredOff + let machine = BLEStateMachine(centralManager: harness.central, operationClock: clock.clock) + await machine.handleCentralManagerDidUpdateState(.poweredOff) + let waiter = Task { await result { try await machine.waitForPoweredOn() } } + try #require(await harness.awaitCondition { await machine.currentPhase.kind == .waitingForBluetooth }) + let armed = await harness.awaitCondition { clock.sleeperCount == 1 } + #expect(armed, "Entering the wait after an off callback must arm the existing grace") + clock.advance(by: .seconds(1)) + let settled = await harness.awaitCondition { await machine.currentPhase.kind == .idle } + #expect(settled, "The settled-off wait must fail without another state callback") + await machine.shutdown() + #expect(await waiter.value.isPoweredOff) + } + + @Test(arguments: [false, true]) + func `off event after wait either expires or is rescued by power-on`(powersOn: Bool) async throws { + let harness = BLETransportHarness() + let clock = BLETestOperationClock() + harness.power = .unknown + let machine = BLEStateMachine(centralManager: harness.central, operationClock: clock.clock) + let waiter = Task { await result { try await machine.waitForPoweredOn() } } + try #require(await harness.awaitCondition { await machine.currentPhase.kind == .waitingForBluetooth }) + harness.power = .poweredOff + await machine.handleCentralManagerDidUpdateState(.poweredOff) + try #require(await harness.awaitCondition { clock.sleeperCount == 1 }) + if powersOn { + harness.power = .poweredOn + await machine.handleCentralManagerDidUpdateState(.poweredOn) + } + clock.advance(by: .seconds(1)) + let outcome = await waiter.value + #expect(powersOn ? outcome.isSuccess : outcome.isPoweredOff) + #expect(await machine.currentPhase.kind == .idle) + #expect(clock.sleeperCount == 0) + await machine.shutdown() + } + + @Test + func `cancelled power wait releases only its own wait lifetime`() async throws { + let harness = BLETransportHarness() + let clock = BLETestOperationClock() + harness.power = .unknown + let machine = BLEStateMachine(centralManager: harness.central, operationClock: clock.clock) + let observation = OutcomeObservation() + let old = Task { + let outcome = await result { try await machine.waitForPoweredOn() } + await observation.record(outcome) + return outcome + } + try #require(await harness.awaitCondition { await machine.currentPhase.kind == .waitingForBluetooth }) + harness.power = .poweredOff + await machine.handleCentralManagerDidUpdateState(.poweredOff) + try #require(await harness.awaitCondition { clock.sleeperCount == 1 }) + old.cancel() + let cancelled = await harness.awaitCondition { await observation.outcome != nil } + #expect(cancelled, "Cancellation must release the power wait without another native callback") + if !cancelled { await machine.shutdown() } + #expect(await old.value.isCancellation) + if !cancelled { return } + #expect(await machine.currentPhase.kind == .idle) + let successor = Task { await result { try await machine.waitForPoweredOn() } } + try #require(await harness.awaitCondition { clock.sleeperCount == 1 }) + harness.power = .poweredOn + await machine.handleCentralManagerDidUpdateState(.poweredOn) + #expect(await successor.value.isSuccess) + clock.advance(by: .seconds(1)) + #expect(await machine.currentPhase.kind == .idle) + await machine.shutdown() + } + + @Test + func `cancelled write-command sender cannot write when readiness arrives`() async throws { + let harness = BLETransportHarness(supportsWriteWithoutResponse: true) + let machine = BLEStateMachine(centralManager: harness.central) + _ = try await harness.connect(machine) + let observation = OutcomeObservation() + let sender = Task { + let outcome = await result { try await machine.sendWithoutResponse(Data([1])) } + await observation.record(outcome) + return outcome + } + try #require(await harness.awaitCondition { await machine.isAwaitingWriteWithoutResponseReady }) + sender.cancel() + harness.isReadyToWrite = true + let bridge = await machine.delegateHandler + bridge.peripheralIsReady(toSendWriteWithoutResponse: harness.peripheral) + let cancelled = await harness.awaitCondition { await observation.outcome != nil } + #expect(cancelled) + if !cancelled { await machine.shutdown() } + #expect(await sender.value.isCancellation) + #expect(harness.writePayloads.isEmpty) + await machine.shutdown() + } + + @Test + func `cancelled dequeued writer forwards pacing to the queued successor`() async throws { + let harness = BLETransportHarness() + let clock = BLETestOperationClock() + let machine = BLEStateMachine(writePacingDelay: 1, centralManager: harness.central, operationClock: clock.clock) + _ = try await harness.connect(machine) + let first = Task { await result { try await machine.send(Data([1])) } } + try #require(await harness.awaitCondition { harness.writePayloads.count == 1 && clock.sleeperCount == 1 }) + let cancelled = Task { await result { try await machine.send(Data([2])) } } + try #require(await harness.awaitCondition { await machine.queuedWriteCount == 1 }) + let successor = Task { await result { try await machine.send(Data([3])) } } + try #require(await harness.awaitCondition { await machine.queuedWriteCount == 2 }) + await harness.acknowledge(machine) + try #require(await harness.awaitCondition { await machine.queuedWriteCount == 1 && clock.sleeperCount == 1 }) + cancelled.cancel() + #expect(await cancelled.value.isCancellation) + let handedOff = await harness.awaitCondition { clock.sleeperCount == 1 } + #expect(handedOff) + if handedOff { clock.advance(by: .seconds(1)) } + let issued = await harness.awaitCondition { harness.writePayloads == [Data([1]), Data([3])] } + #expect(issued) + if issued { await harness.acknowledge(machine) } else { await machine.shutdown() } + #expect(await first.value.isSuccess) + #expect(await successor.value.isSuccess) + await machine.shutdown() + } + + @Test + func `already-cancelled power wait cannot succeed on a powered-on central`() async { + let harness = BLETransportHarness() + let machine = BLEStateMachine(centralManager: harness.central) + let cancelled = Task { + withUnsafeCurrentTask { $0?.cancel() } + return await result { try await machine.waitForPoweredOn() } + } + #expect(await cancelled.value.isCancellation) + #expect(harness.connectCount == 0) + await machine.shutdown() + } + + private actor OutcomeObservation { + var outcome: Outcome? + func record(_ outcome: Outcome) { + self.outcome = outcome + } + } + + private enum Outcome: Sendable { + case success + case cancellation + case timeout + case poweredOff + case failure + + var isSuccess: Bool { + if case .success = self { true } else { false } + } + + var isCancellation: Bool { + if case .cancellation = self { true } else { false } + } + + var isTimeout: Bool { + if case .timeout = self { true } else { false } + } + + var isPoweredOff: Bool { + if case .poweredOff = self { true } else { false } + } + } + + private func result(_ work: @Sendable () async throws -> Void) async -> Outcome { + do { try await work(); return .success } catch is CancellationError { return .cancellation } catch { + switch error as? BLEError { + case .operationTimeout: return .timeout + case .bluetoothPoweredOff: return .poweredOff + default: return .failure + } + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineRestorationAndTeardownTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineRestorationAndTeardownTests.swift index 1f54fdbddb..a82a5ee7e9 100644 --- a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineRestorationAndTeardownTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineRestorationAndTeardownTests.swift @@ -2,6 +2,7 @@ import CoreBluetooth import Foundation @testable import MC1Services import ObjectiveC +import os import Testing /// Covers phase-continuation safety around state restoration and teardown: @@ -255,7 +256,7 @@ private final class ContinuationBox: @unchecked Sendable { /// allocated instance never set up, so releasing one crashes; never freeing /// them keeps the doubles usable. private enum RestorationPeripheralStore { - nonisolated(unsafe) static var retained: [CBPeripheral] = [] + static let retained = OSAllocatedUnfairLock(uncheckedState: [CBPeripheral]()) } /// A `CBPeripheral` double with a stable identity and `.disconnected` state. @@ -287,7 +288,7 @@ private final class RestorationConnectedPeripheral: CBPeripheral, @unchecked Sen private func makeLeakedPeripheral(_ type: T.Type) -> T { // swiftlint:disable:next force_cast let peripheral = class_createInstance(type, 0) as! T - RestorationPeripheralStore.retained.append(peripheral) + RestorationPeripheralStore.retained.withLockUnchecked { $0.append(peripheral) } return peripheral } diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineTests.swift index c96f76e383..bcf40a7651 100644 --- a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineTests.swift @@ -74,15 +74,8 @@ struct BLEStateMachineTests { let sm = BLEStateMachine() let testData = Data([0x01, 0x02, 0x03]) - do { + await #expect(throws: MeshTransportError.notConnected) { try await sm.send(testData) - Issue.record("Expected notConnected error") - } catch let error as BLEError { - if case .notConnected = error { - // Expected - } else { - Issue.record("Expected notConnected error, got \(error)") - } } } diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineWriteSubmissionTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineWriteSubmissionTests.swift new file mode 100644 index 0000000000..cd24d3b943 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineWriteSubmissionTests.swift @@ -0,0 +1,38 @@ +@preconcurrency import CoreBluetooth +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("BLE write submission") +struct BLEStateMachineWriteSubmissionTests { + @Test + func `a disconnected slot throws before writeValue and a dropped link resumes the pending write`() async throws { + let harness = BLETransportHarness() + let machine = BLEStateMachine(centralManager: harness.central) + _ = try await harness.connect(machine) + defer { Task { await machine.shutdown() } } + + harness.peripheralState = .disconnected + await #expect(throws: MeshTransportError.notConnected) { + try await machine.send(Data([0x01])) + } + #expect(harness.writePayloads.isEmpty) + + harness.peripheralState = .connected + let pending = Task { + try await machine.send(Data([0x02])) + } + let wrote = await harness.awaitCondition { harness.writePayloads == [Data([0x02])] } + try #require(wrote) + await machine.disconnect() + + let error = await #expect(throws: BLEError.self) { + try await pending.value + } + guard case .notConnected? = error else { + Issue.record("Expected the pending write to resume notConnected, got \(String(describing: error))") + return + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineWriteWithoutResponseTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineWriteWithoutResponseTests.swift index b32c7d82ac..a1902fe2b0 100644 --- a/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineWriteWithoutResponseTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineWriteWithoutResponseTests.swift @@ -3,10 +3,8 @@ import Foundation @testable import MC1Services import Testing -/// Covers the `.withoutResponse` write path's backpressure continuation lifecycle and -/// capability capture. The full `sendWithoutResponse` round-trip needs a real `CBPeripheral` -/// (no public initializer) so it is verified on-device; these tests lock the concurrency- -/// critical parts that can hang or corrupt state if they regress. +/// Covers the `.withoutResponse` readiness continuation and capability capture. +/// Production send admission and native origins are exercised by the transport harness. @Suite("BLEStateMachine write-without-response path") struct BLEStateMachineWriteWithoutResponseTests { // MARK: - Helpers @@ -21,16 +19,93 @@ struct BLEStateMachineWriteWithoutResponseTests { return false } - /// Returns true if `work` finishes within `duration`; false if it is still running - /// (i.e. the awaited continuation never resumed — a hang). Converts a hang into a - /// fast assertion failure instead of stalling the whole suite. - private func completesWithin(_ duration: Duration, _ work: @escaping @Sendable () async -> Void) async -> Bool { - await withTaskGroup(of: Bool.self) { group in - group.addTask { await work(); return true } - group.addTask { try? await Task.sleep(for: duration); return false } - defer { group.cancelAll() } - return await group.next() ?? false + /// Reports the deadline without joining noncooperative work. The caller still owns + /// the operation and must release and join it during cleanup when the deadline wins. + private func completesWithin( + _ duration: Duration, + sleep: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }, + _ work: @escaping @Sendable () async -> Void + ) async -> Bool { + let race = CompletionRace() + let observer = Task { await work(); await race.resolve(true) } + let timer = Task { + do { try await sleep(duration) } catch { return } + await race.resolve(false) } + let result = await race.value() + observer.cancel() + timer.cancel() + return result + } + + private actor CompletionRace { + var result: Bool? + var continuation: CheckedContinuation? + + func resolve(_ value: Bool) { + guard result == nil else { return } + result = value + continuation?.resume(returning: value) + continuation = nil + } + + func value() async -> Bool { + if let result { return result } + return await withCheckedContinuation { continuation = $0 } + } + } + + private actor SuspendedWork { + var continuation: CheckedContinuation? + var isWaiting: Bool { + continuation != nil + } + + func wait() async { + await withCheckedContinuation { continuation = $0 } + } + + func release() { + continuation?.resume() + continuation = nil + } + } + + private actor DeadlineObservation { + var result: Bool? + func record(_ value: Bool) { + result = value + } + } + + @Test + func `deadline reports stalled work before its owner releases and joins it`() async { + let work = SuspendedWork() + let observation = DeadlineObservation() + let clock = BLETestOperationClock() + let parkedTask = Task { await work.wait() } + while await !work.isWaiting { + await Task.yield() + } + let detector = Task { + let result = await completesWithin(.seconds(1), sleep: clock.clock.sleep) { await parkedTask.value } + await observation.record(result) + } + + while clock.sleeperCount == 0 { + await Task.yield() + } + clock.advance(by: .seconds(1)) + // The deadline is controlled; this separate bound only allows the observer to run. + let observationDeadline = ContinuousClock.now.advanced(by: .seconds(1)) + while await observation.result == nil, ContinuousClock.now < observationDeadline { + await Task.yield() + } + #expect(await observation.result == false) + await work.release() + await parkedTask.value + await detector.value + #expect(await observation.result == false) } // MARK: - Readiness gating @@ -54,7 +129,7 @@ struct BLEStateMachineWriteWithoutResponseTests { let waiter = Task { _ = try? await sm.awaitWriteWithoutResponseReadiness(alreadyReady: false) } #expect(await waitUntilAwaiting(sm)) - await sm.handlePeripheralReadyForWriteWithoutResponse() + await sm.resumeWriteWithoutResponseReadiness() #expect(await completesWithin(.seconds(3)) { await waiter.value }) #expect(await sm.isAwaitingWriteWithoutResponseReady == false) @@ -98,7 +173,7 @@ struct BLEStateMachineWriteWithoutResponseTests { func `peripheral-ready callback with no pending waiter is a safe no-op`() async { let sm = BLEStateMachine() - await sm.handlePeripheralReadyForWriteWithoutResponse() + await sm.resumeWriteWithoutResponseReadiness() #expect(await sm.isAwaitingWriteWithoutResponseReady == false) } diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLETestOperationClock.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLETestOperationClock.swift new file mode 100644 index 0000000000..d8801f73b7 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLETestOperationClock.swift @@ -0,0 +1,57 @@ +import Foundation +@testable import MC1Services +import os + +final class BLETestOperationClock: Sendable { + private struct Sleeper { + let id: UUID + let deadline: ContinuousClock.Instant + let continuation: CheckedContinuation + } + + private struct State { + var now = ContinuousClock.now + var sleepers: [Sleeper] = [] + } + + private let state = OSAllocatedUnfairLock(initialState: State()) + + var clock: BLEOperationClock { + BLEOperationClock(now: { self.state.withLock { $0.now } }, sleep: { try await self.sleep(for: $0) }) + } + + var sleeperCount: Int { + state.withLock { $0.sleepers.count } + } + + func advance(by duration: Duration) { + let ready = state.withLock { state in + state.now = state.now.advanced(by: duration) + let ready = state.sleepers.filter { $0.deadline <= state.now } + state.sleepers.removeAll { $0.deadline <= state.now } + return ready + } + ready.forEach { $0.continuation.resume() } + } + + private func sleep(for duration: Duration) async throws { + guard duration > .zero else { return } + let id = UUID() + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + let cancelled = state.withLock { state in + guard !Task.isCancelled else { return true } + state.sleepers.append(Sleeper(id: id, deadline: state.now.advanced(by: duration), continuation: continuation)) + return false + } + if cancelled { continuation.resume(throwing: CancellationError()) } + } + } onCancel: { + let sleeper = self.state.withLock { state -> Sleeper? in + guard let index = state.sleepers.firstIndex(where: { $0.id == id }) else { return nil } + return state.sleepers.remove(at: index) + } + sleeper?.continuation.resume(throwing: CancellationError()) + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BLETransportHarness.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLETransportHarness.swift new file mode 100644 index 0000000000..9863eaead6 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLETransportHarness.swift @@ -0,0 +1,337 @@ +@preconcurrency import CoreBluetooth +import Foundation +@testable import MC1Services +import MeshCore +import ObjectiveC +import os + +/// Drives the production connect/discovery/write path without priming BLEPhase. +/// Native CB objects still need runtime allocation and process-lifetime retention. +final class BLETransportHarness: @unchecked Sendable { + let central: CBCentralManager + let peripheral: CBPeripheral + let service: CBMutableService + let tx: CBMutableCharacteristic + let rx: CBMutableCharacteristic + let deviceID: UUID + + private struct State { + var peripheralState: CBPeripheralState = .connected + var systemConnected = false + var writeHandler: (@Sendable (Data) -> Void)? + var power: CBManagerState = .poweredOn + var isReadyToWrite = false + var peripheralDelegate: (any CBPeripheralDelegate)? + var connects = 0 + var cancellations = 0 + var serviceDiscoveries = 0 + var characteristicDiscoveries = 0 + var subscriptions = 0 + var writes: [Data] = [] + var automaticBridge: BLEDelegateHandler? + var onWrite: (@Sendable (Data) -> [Data])? + var automaticAcknowledgements = 0 + var peers: [UUID: BLETransportHarness] = [:] + } + + private let state = OSAllocatedUnfairLock(initialState: State()) + + private final class Registration { + weak var harness: BLETransportHarness? + init(_ harness: BLETransportHarness) { + self.harness = harness + } + } + + /// The lock protects retention and lookup; native objects are used only by the harness. + private struct Registry: @unchecked Sendable { + var registrations: [ObjectIdentifier: Registration] = [:] + var retained: [NSObject] = [] + } + + private static let registry = OSAllocatedUnfairLock(initialState: Registry()) + + init(deviceID: UUID = UUID(), supportsWriteWithoutResponse: Bool = false) { + self.deviceID = deviceID + // swiftlint:disable:next force_cast + central = class_createInstance(Central.self, 0) as! Central + // swiftlint:disable:next force_cast + peripheral = class_createInstance(Peripheral.self, 0) as! Peripheral + tx = CBMutableCharacteristic( + type: CBUUID(string: BLEServiceUUID.txCharacteristic), properties: supportsWriteWithoutResponse ? [.write, .writeWithoutResponse] : [.write], + value: nil, permissions: [.writeable] + ) + rx = NotifyingCharacteristic( + type: CBUUID(string: BLEServiceUUID.rxCharacteristic), properties: [.notify], + value: nil, permissions: [.readable] + ) + service = CBMutableService(type: CBUUID(string: BLEServiceUUID.nordicUART), primary: true) + service.characteristics = [tx, rx] + Self.registry.withLock { + $0.registrations[ObjectIdentifier(central)] = Registration(self) + $0.registrations[ObjectIdentifier(peripheral)] = Registration(self) + $0.retained += [central, peripheral] + } + } + + var peripheralState: CBPeripheralState { + get { state.withLock { $0.peripheralState } } + set { state.withLock { $0.peripheralState = newValue } } + } + + var systemConnected: Bool { + get { state.withLock { $0.systemConnected } } + set { state.withLock { $0.systemConnected = newValue } } + } + + func setWriteHandler(_ handler: (@Sendable (Data) -> Void)?) { + state.withLock { $0.writeHandler = handler } + } + + var power: CBManagerState { + get { state.withLock { $0.power } } + set { state.withLock { $0.power = newValue } } + } + + var isReadyToWrite: Bool { + get { state.withLock { $0.isReadyToWrite } } + set { state.withLock { $0.isReadyToWrite = newValue } } + } + + var writePayloads: [Data] { + state.withLock { $0.writes } + } + + var connectCount: Int { + state.withLock { $0.connects } + } + + var cancellationCount: Int { + state.withLock { $0.cancellations } + } + + var serviceDiscoveryCount: Int { + state.withLock { $0.serviceDiscoveries } + } + + var characteristicDiscoveryCount: Int { + state.withLock { $0.characteristicDiscoveries } + } + + var subscriptionCount: Int { + state.withLock { $0.subscriptions } + } + + var automaticAcknowledgementCount: Int { + state.withLock { $0.automaticAcknowledgements } + } + + func enableAutomaticCallbacks(_ bridge: BLEDelegateHandler, onWrite: @escaping @Sendable (Data) -> [Data]) { + state.withLock { + $0.automaticBridge = bridge + $0.onWrite = onWrite + } + } + + private var automaticBridge: BLEDelegateHandler? { + state.withLock { $0.automaticBridge } + } + + func registerPeer(_ peer: BLETransportHarness) { + state.withLock { $0.peers[peer.deviceID] = peer } + } + + /// An empty radio with one unused channel slot and no queued messages. + static func emptyRadioFrames(for data: Data) -> [Data] { + switch data.first { + case CommandCode.appStart.rawValue: + var response = Data([ResponseCode.selfInfo.rawValue, 1, 22, 22]) + response.append(Data(repeating: 1, count: 32)) + response.append(Data(repeating: 0, count: 12)) + for value: UInt32 in [915_000, 125_000] { + response.append(withUnsafeBytes(of: value.littleEndian) { Data($0) }) + } + response.append(contentsOf: [7, 5]) + return [response] + case CommandCode.deviceQuery.rawValue: + var response = Data([ResponseCode.deviceInfo.rawValue, 14, 1, 1]) + response.append(Data(repeating: 0, count: 76)) + return [response] + case CommandCode.getAutoAddConfig.rawValue: + return [Data([ResponseCode.autoAddConfig.rawValue, 0])] + case CommandCode.getContacts.rawValue: + return [Data([ResponseCode.contactStart.rawValue, 0, 0, 0, 0]), Data([ResponseCode.contactEnd.rawValue, 0, 0, 0, 0])] + case CommandCode.getChannel.rawValue: + let index = data.count > 1 ? data[1] : 0 + return [Data([ResponseCode.channelInfo.rawValue, index]) + Data(repeating: 0, count: 48)] + case CommandCode.getMessage.rawValue: + return [Data([ResponseCode.noMoreMessages.rawValue])] + case CommandCode.getTime.rawValue: + var timestamp = UInt32(Date().timeIntervalSince1970).littleEndian + return [Data([ResponseCode.currentTime.rawValue]) + withUnsafeBytes(of: ×tamp) { Data($0) }] + case CommandCode.setTime.rawValue: + return [Data([ResponseCode.ok.rawValue])] + case CommandCode.getBattery.rawValue: + return [Data([ResponseCode.battery.rawValue, 0x74, 0x0E])] + case CommandCode.setFloodScope.rawValue: + return [Data([ResponseCode.ok.rawValue])] + default: + return [Data([ResponseCode.error.rawValue, 1])] + } + } + + private func issueWrite(_ data: Data, type: CBCharacteristicWriteType) { + let callback = state.withLock { current -> (@Sendable (Data) -> [Data])? in + current.writes.append(data) + return current.onWrite + } + state.withLock { $0.writeHandler }?(data) + guard let bridge = automaticBridge else { return } + if type == .withResponse { + state.withLock { $0.automaticAcknowledgements += 1 } + bridge.peripheral(peripheral, didWriteValueFor: tx, error: nil) + } + for frame in callback?(data) ?? [] { + rx.value = frame + bridge.peripheral(peripheral, didUpdateValueFor: rx, error: nil) + } + } + + func connect(_ machine: BLEStateMachine) async throws -> AsyncStream { + let pending = Task { try await machine.connect(to: deviceID) } + guard await awaitCondition({ self.connectCount == 1 }) else { + await machine.shutdown() + _ = try? await pending.value + throw BLEError.connectionFailed("Harness did not issue connect") + } + let bridge = await machine.delegateHandler + bridge.centralManager(central, didConnect: peripheral) + guard await awaitCondition({ self.serviceDiscoveryCount == 1 }) else { + await machine.shutdown() + _ = try? await pending.value + throw BLEError.connectionFailed("Harness did not discover services") + } + bridge.peripheral(peripheral, didDiscoverServices: nil) + guard await awaitCondition({ self.characteristicDiscoveryCount == 1 }) else { + await machine.shutdown() + _ = try? await pending.value + throw BLEError.connectionFailed("Harness did not discover characteristics") + } + bridge.peripheral(peripheral, didDiscoverCharacteristicsFor: service, error: nil) + guard await awaitCondition({ self.subscriptionCount == 1 }) else { + await machine.shutdown() + _ = try? await pending.value + throw BLEError.connectionFailed("Harness did not subscribe") + } + bridge.peripheral(peripheral, didUpdateNotificationStateFor: rx, error: nil) + return try await pending.value + } + + func acknowledge(_ machine: BLEStateMachine, error: Error? = nil) async { + let bridge = await machine.delegateHandler + bridge.peripheral(peripheral, didWriteValueFor: tx, error: error) + } + + func awaitCondition(_ condition: @escaping @Sendable () async -> Bool) async -> Bool { + do { + try await waitUntil { await condition() } + return true + } catch { + return false + } + } + + private static func harness(for object: NSObject) -> BLETransportHarness? { + let identity = ObjectIdentifier(object) + return registry.withLock { $0.registrations[identity]?.harness } + } + + private final class Central: CBCentralManager, @unchecked Sendable { + override var state: CBManagerState { + BLETransportHarness.harness(for: self)?.power ?? .unknown + } + + override func retrievePeripherals(withIdentifiers identifiers: [UUID]) -> [CBPeripheral] { + guard let harness = BLETransportHarness.harness(for: self) else { return [] } + return identifiers.compactMap { id in + if id == harness.deviceID { return harness.peripheral } + return harness.state.withLock { $0.peers[id]?.peripheral } + } + } + + override func retrieveConnectedPeripherals(withServices serviceUUIDs: [CBUUID]) -> [CBPeripheral] { + guard let harness = BLETransportHarness.harness(for: self), + harness.systemConnected, harness.peripheralState == .connected else { return [] } + return [harness.peripheral] + } + + override func connect(_ peripheral: CBPeripheral, options: [String: Any]? = nil) { + guard let harness = BLETransportHarness.harness(for: self) else { return } + harness.state.withLock { $0.connects += 1 } + harness.automaticBridge?.centralManager(self, didConnect: peripheral) + } + + override func cancelPeripheralConnection(_ peripheral: CBPeripheral) { + BLETransportHarness.harness(for: self)?.state.withLock { $0.cancellations += 1 } + } + + override func stopScan() {} + } + + private final class Peripheral: CBPeripheral, @unchecked Sendable { + override var identifier: UUID { + BLETransportHarness.harness(for: self)!.deviceID + } + + override var name: String? { + "Harness" + } + + override var state: CBPeripheralState { + BLETransportHarness.harness(for: self)?.peripheralState ?? .disconnected + } + + override var canSendWriteWithoutResponse: Bool { + BLETransportHarness.harness(for: self)?.isReadyToWrite ?? false + } + + override var services: [CBService]? { + BLETransportHarness.harness(for: self).map { [$0.service] } + } + + override var delegate: (any CBPeripheralDelegate)? { + get { BLETransportHarness.harness(for: self)?.state.withLock { $0.peripheralDelegate } } + set { BLETransportHarness.harness(for: self)?.state.withLock { $0.peripheralDelegate = newValue } } + } + + override func discoverServices(_ serviceUUIDs: [CBUUID]?) { + guard let harness = BLETransportHarness.harness(for: self) else { return } + harness.state.withLock { $0.serviceDiscoveries += 1 } + harness.automaticBridge?.peripheral(self, didDiscoverServices: nil) + } + + override func discoverCharacteristics(_ characteristicUUIDs: [CBUUID]?, for service: CBService) { + guard let harness = BLETransportHarness.harness(for: self) else { return } + harness.state.withLock { $0.characteristicDiscoveries += 1 } + harness.automaticBridge?.peripheral(self, didDiscoverCharacteristicsFor: service, error: nil) + } + + override func setNotifyValue(_ enabled: Bool, for characteristic: CBCharacteristic) { + guard let harness = BLETransportHarness.harness(for: self) else { return } + harness.state.withLock { $0.subscriptions += 1 } + harness.automaticBridge?.peripheral(self, didUpdateNotificationStateFor: characteristic, error: nil) + } + + override func writeValue(_ data: Data, for characteristic: CBCharacteristic, type: CBCharacteristicWriteType) { + BLETransportHarness.harness(for: self)?.issueWrite(data, type: type) + } + + override func readRSSI() {} + } + + private final class NotifyingCharacteristic: CBMutableCharacteristic { + override var isNotifying: Bool { + true + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/BondShieldRefreshTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BondShieldRefreshTests.swift index b3de21cc26..d7ed57c891 100644 --- a/MC1Services/Tests/MC1ServicesTests/Transport/BondShieldRefreshTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BondShieldRefreshTests.swift @@ -129,8 +129,9 @@ struct BondShieldRefreshTests { await sm.appDidBecomeActive() await sm.primeFringeAutoReconnectingForBondTests(peripheral: peripheral) let recorder = FringeDisconnectionRecorder() - await sm.setDisconnectionHandler { deviceID, error in - recorder.append(deviceID: deviceID, error: error) + await sm.setLifecycleEventHandler { event, _ in + guard case let .disconnected(origin, error) = event else { return } + recorder.append(deviceID: origin.deviceID, error: error) } let encryptionTimedOut = NSError( @@ -196,8 +197,9 @@ struct BondShieldRefreshTests { await sm.appDidBecomeActive() await sm.primeFringeAutoReconnectingForBondTests(peripheral: peripheral) let recorder = FringeDisconnectionRecorder() - await sm.setDisconnectionHandler { deviceID, error in - recorder.append(deviceID: deviceID, error: error) + await sm.setLifecycleEventHandler { event, _ in + guard case let .disconnected(origin, error) = event else { return } + recorder.append(deviceID: origin.deviceID, error: error) } let encryptionTimedOut = NSError( domain: CBErrorDomain, @@ -348,7 +350,7 @@ private final class BondRefreshCallbackBox: @unchecked Sendable { } } -/// Same shape as FringeDisconnectionRecorder — collect onDisconnection events. +/// Records disconnected lifecycle events for the callback assertions. private final class FringeDisconnectionRecorder: @unchecked Sendable { struct Event { let deviceID: UUID diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/ConnectionManagerBLERetirementTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/ConnectionManagerBLERetirementTests.swift new file mode 100644 index 0000000000..d17dc5d9b6 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Transport/ConnectionManagerBLERetirementTests.swift @@ -0,0 +1,70 @@ +@testable import MC1Services +@testable import MeshCore +import os +import Testing + +@Suite("Retirement manager BLE") +@MainActor +struct ConnectionManagerBLERetirementTests { + enum Action: CaseIterable, Sendable { case disconnect, wifiSwitch, preservedRebuild } + + @Test(arguments: Action.allCases) + func `actual manager retires its first unsent BLE pipeline`(action: Action) async throws { + let fixture = try await RetirementBLEManagerHarness.make() + let machine = fixture.ble.machine + let adapter = fixture.ble.adapter + var pipeline: Task<(received: [ChannelInfo], missing: [UInt8]), Error>? + var terminal: Task? + do { + try await fixture.connect() + let old = try #require(fixture.manager.currentConnection) + let session = try #require(fixture.manager.session) + let before = fixture.ble.native.writePayloads + let origin = try #require(await adapter.lifecycleOrigin) + fixture.ble.native.isReadyToWrite = false + pipeline = Task { try await session.getChannels(indices: [0, 1]) } + try await fixture.ble.awaitCondition { await machine.isAwaitingWriteWithoutResponseReady } + let pending = try #require(pipeline) + let completed = OSAllocatedUnfairLock(initialState: false) + terminal = Task { + switch action { + case .disconnect: + _ = await fixture.manager.disconnect(reason: .userInitiated) + case .wifiSwitch: + _ = try await fixture.manager.connectViaWiFi(host: "other.local", port: 4242) + case .preservedRebuild: + await fixture.manager.handleBLELifecycleEvent(.autoReconnecting(origin, errorInfo: "recovery")) + } + _ = await pending.result + #expect(fixture.ble.native.writePayloads.filter { $0.first == CommandCode.getChannel.rawValue } + == before.filter { $0.first == CommandCode.getChannel.rawValue }) + if action == .preservedRebuild { + fixture.ble.native.isReadyToWrite = true + await fixture.manager.handleBLELifecycleEvent(.reconnected(origin)) + } + completed.withLock { $0 = true } + } + let prompt = await fixture.ble.observedBeforeDeadline { completed.withLock { $0 } } + #expect(prompt, "Actual manager retirement cannot wait for unsent-frame readiness or its long watchdog") + guard prompt else { throw BLESetupRetirementHarness.WaitError.expired } + let retiring = try #require(terminal) + try await retiring.value + #expect(await session.subscriberCountForTest == 0) + if action == .disconnect { + _ = try await fixture.manager.connectViaWiFi(host: "other.local", port: 4242) + } + #expect(fixture.manager.connectionState == .ready) + #expect(fixture.manager.currentConnection?.generation != old.generation) + let successor = try #require(fixture.manager.session) + _ = try await successor.getTime() + } catch { + fixture.ble.native.isReadyToWrite = true + await machine.shutdown() + _ = await pipeline?.result + _ = await terminal?.result + await fixture.close() + throw error + } + await fixture.close() + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/IdentityImportRetirementTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/IdentityImportRetirementTests.swift new file mode 100644 index 0000000000..ca6249893b --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Transport/IdentityImportRetirementTests.swift @@ -0,0 +1,226 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("Retirement identity BLE admission") +@MainActor +struct IdentityImportRetirementTests { + @Test + func `pre key reservation releases only its first unsent pipeline`() async throws { + let fixture = try await RetirementBLEManagerHarness.make() + let gate = Gate() + var importing: Task? + var pipeline: Task? + do { + let canonicalRadioID = UUID() + let ghost = DeviceDTO.testDevice(radioID: canonicalRadioID, publicKey: CanonicalIdentityFixture.publicKey) + try await fixture.manager.persistenceStore.saveDevice(ghost) + try await fixture.manager.persistenceStore.demoteDeviceToGhost(id: ghost.id) + try await fixture.connect() + let source = try #require(fixture.manager.currentConnection) + let services = try #require(fixture.manager.services) + let manager = fixture.manager + await services.nodeConfigService.setIdentityImportHandler { [weak manager, weak services] key in + await gate.wait() + guard let manager, let services else { throw CancellationError() } + return try await manager.importIdentity(key, expectedServices: services, deviceID: source.device.id) + } + await fixture.wire.setPublicKey(CanonicalIdentityFixture.publicKey, for: fixture.ble.peripheral.identifier) + let receipt = Receipt() + importing = Task { + defer { receipt.importFinished = true } + try await services.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: source.device.radioID + ) + } + try await waitUntil("real config planning should reach the real manager dispatch boundary") { await gate.isWaiting } + let before = fixture.ble.native.writePayloads.count + fixture.ble.native.isReadyToWrite = false + pipeline = Task { + try await services.channelService.syncChannels( + radioID: source.device.radioID, maxChannels: 2, usePipelinedRead: true + ) + } + try await fixture.ble.awaitCondition { await fixture.ble.machine.isAwaitingWriteWithoutResponseReady } + await gate.release() + let prompt = await fixture.ble.observedBeforeDeadline { await receipt.importFinished } + #expect(prompt, "Pre-key retirement cannot wait for an unsent ordinary write's readiness watchdog") + guard prompt else { throw BLESetupRetirementHarness.WaitError.expired } + try await importing?.value + _ = await pipeline?.result + let tail = Array(fixture.ble.native.writePayloads.dropFirst(before)) + let keyOffset = try #require(tail.firstIndex { $0.first == CommandCode.importPrivateKey.rawValue }) + #expect(!tail.prefix(keyOffset).contains { $0.first == CommandCode.getChannel.rawValue }) + #expect(fixture.manager.connectedDevice?.radioID == canonicalRadioID) + #expect(fixture.manager.currentConnection?.generation != source.generation) + #expect(await !fixture.ble.machine.isAwaitingWriteWithoutResponseReady) + #expect(try await fixture.manager.session?.getTime() != nil) + } catch { + await gate.release() + fixture.ble.native.isReadyToWrite = true + await fixture.ble.machine.shutdown() + _ = await pipeline?.result + _ = await importing?.result + await fixture.close() + throw error + } + await fixture.close() + } + + @Test(arguments: [false, true]) + func `aborted pipeline prefix must be answered before identity`(answered: Bool) async throws { + let fixture = try await RetirementBLEManagerHarness.make(maxChannels: 2) + let gate = Gate() + var importing: Task? + var pipeline: Task? + do { + let canonicalRadioID = UUID() + let ghost = DeviceDTO.testDevice(radioID: canonicalRadioID, publicKey: CanonicalIdentityFixture.publicKey) + try await fixture.manager.persistenceStore.saveDevice(ghost) + try await fixture.manager.persistenceStore.demoteDeviceToGhost(id: ghost.id) + try await fixture.connect() + let sourceSnapshot = fixture.manager.currentConnection + let source = try #require(sourceSnapshot) + let services = source.services + let manager = fixture.manager + await services.nodeConfigService.setIdentityImportHandler { [weak manager, weak services] key in + await gate.wait() + guard let manager, let services else { throw CancellationError() } + return try await manager.importIdentity(key, expectedServices: services, deviceID: source.device.id) + } + await fixture.wire.setIdentityImportPublicKey(CanonicalIdentityFixture.publicKey) + let receipt = Receipt() + importing = Task { + defer { receipt.importFinished = true } + try await services.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: source.device.radioID + ) + } + try await waitUntil("normal config planning should reach the real identity dispatch") { await gate.isWaiting } + let before = fixture.ble.native.writePayloads.count + await fixture.wire.holdReplies(for: .getChannel) + fixture.installWriteHandler(backpressureAfterChannelIndex: 0) + pipeline = Task { + try await services.channelService.syncChannels(radioID: source.device.radioID, maxChannels: 2, usePipelinedRead: true) + } + try await fixture.ble.awaitCondition { await fixture.ble.machine.isAwaitingWriteWithoutResponseReady } + try await waitUntil("the first actual channel response should remain held") { + await fixture.wire.heldReplyCount(for: .getChannel) == 1 + } + let submitted = fixture.ble.native.writePayloads.dropFirst(before) + let firstOnly = submitted.filter { $0.first == CommandCode.getChannel.rawValue }.map { $0[1] } == [0] + #expect(firstOnly) + await gate.release() + try await fixture.ble.awaitCondition { await !fixture.ble.machine.isAwaitingWriteWithoutResponseReady } + let noKeyWhilePrefixHeld = !fixture.ble.native.writePayloads.contains { + $0.first == CommandCode.importPrivateKey.rawValue + } + #expect(noKeyWhilePrefixHeld) + if !answered { + try await waitUntil("unanswered prefix must refuse identity or expose an unsafe key submission") { + receipt.importFinished || fixture.ble.native.writePayloads.contains { + $0.first == CommandCode.importPrivateKey.rawValue + } + } + } + await fixture.wire.releaseReplies(for: .getChannel) + let importTask = try #require(importing) + let result = await importTask.result + _ = await pipeline?.result + let keyCount = fixture.ble.native.writePayloads + .filter { $0.first == CommandCode.importPrivateKey.rawValue }.count + let importSucceeded = if case .success = result { true } else { false } + let expectedOutcome = importSucceeded == answered + let expectedKeyCount = keyCount == (answered ? 1 : 0) + #expect(expectedOutcome) + #expect(expectedKeyCount) + if answered { + let canonicalReady = fixture.manager.connectedDevice?.radioID == canonicalRadioID && fixture.manager.connectionState == .ready + #expect(canonicalReady) + } else { + let original = try await fixture.manager.persistenceStore.fetchDevice(id: source.device.id) + let originalPreserved = original?.publicKey == source.device.publicKey && original?.radioID == source.device.radioID + let canonical = try await fixture.manager.persistenceStore.fetchDevice(publicKey: CanonicalIdentityFixture.publicKey) + let ghostPreserved = canonical?.radioID == canonicalRadioID && canonical?.connectionMethods.isEmpty == true + #expect(originalPreserved) + #expect(ghostPreserved) + try await fixture.connect() + } + let laterIOWorks = try await fixture.manager.session?.getTime() != nil + #expect(laterIOWorks) + } catch { + await gate.release() + await fixture.wire.releaseAllGates() + fixture.ble.native.isReadyToWrite = true + await fixture.ble.machine.shutdown() + _ = await pipeline?.result + _ = await importing?.result + await fixture.close() + throw error + } + await fixture.close() + } + + @Test + func `ordinary coalescing reconciles before later identity`() async throws { + let fixture = try await RetirementBLEManagerHarness.make(maxChannels: 2) + do { + await fixture.wire.setChannel(index: 0, name: "First", secret: Data(repeating: 0xC1, count: 16)) + await fixture.wire.setChannel(index: 1, name: "Second", secret: Data(repeating: 0xC2, count: 16)) + try await fixture.connect() + let sourceSnapshot = fixture.manager.currentConnection + let source = try #require(sourceSnapshot) + let before = fixture.ble.native.writePayloads.count + await fixture.wire.enqueueResponsePackets(for: .getChannel, packets: []) + let result = try await source.services.channelService.syncChannels( + radioID: source.device.radioID, maxChannels: 2, usePipelinedRead: true + ) + let reads = fixture.ble.native.writePayloads.dropFirst(before) + .filter { $0.first == CommandCode.getChannel.rawValue }.map { $0[1] } + // The empty reply belongs to whichever primed getChannel the radio handles first. + // The other can also miss the idle window. Reconcile then repeats the missed indexes in order. + #expect(reads == [0, 1, 0] || reads == [0, 1, 1] || reads == [0, 1, 0, 1]) + #expect(result.channelsSynced == 2) + #expect(result.errors.isEmpty) + await fixture.wire.setIdentityImportPublicKey(CanonicalIdentityFixture.publicKey) + try await source.services.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: CanonicalIdentityFixture.privateKeyHex), + sections: ConfigSections(nodeIdentity: true), radioID: source.device.radioID + ) + #expect(fixture.manager.connectedDevice?.publicKey == CanonicalIdentityFixture.publicKey) + #expect(fixture.manager.connectionState == .ready) + let keyWrites = fixture.ble.native.writePayloads.filter { $0.first == CommandCode.importPrivateKey.rawValue } + #expect(keyWrites.count == 1) + #expect(try await fixture.manager.session?.getTime() != nil) + } catch { + await fixture.wire.releaseAllGates() + await fixture.close() + throw error + } + await fixture.close() + } + + @MainActor + private final class Receipt { var importFinished = false } + + private actor Gate { + private var continuation: CheckedContinuation? + private var released = false + private(set) var isWaiting = false + func wait() async { + guard !released else { return } + isWaiting = true + await withCheckedContinuation { continuation = $0 } + isWaiting = false + } + + func release() { + released = true + continuation?.resume() + continuation = nil + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/NativeBLEOwnershipIntegrationTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/NativeBLEOwnershipIntegrationTests.swift new file mode 100644 index 0000000000..a4f842c521 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Transport/NativeBLEOwnershipIntegrationTests.swift @@ -0,0 +1,108 @@ +@preconcurrency import CoreBluetooth +import Foundation +@testable import MC1Services +@testable import MeshCore +import MeshCoreTestSupport +import Testing + +@Suite("Native BLE ownership integration") +@MainActor +struct NativeBLEOwnershipIntegrationTests { + @Test(.timeLimit(.minutes(1))) + func `native reconnect replaces the retired stack and resumes protocol IO`() async throws { + let run = try await NativeConnectionPortHarness() + let events = ValueTracker() + let stream = run.manager.connectionStateEvents.subscribe() + let observer = Task { for await state in stream { + events.record(state) + } } + let published = CallTracker() + let usable = CallTracker() + let synced = CallTracker() + run.manager.onConnectionReady = { _ in published.markCalled() } + run.manager.onConnectionBecameUsable = { _ in usable.markCalled() } + run.manager.onDeviceSynced = { _, _ in synced.markCalled() } + do { + let initial = try await run.manager.connectViaBluetooth(peripheralID: run.native.deviceID) + #expect(run.manager.isCurrent(initial)) + let first = try #require(run.manager.installedLink) + run.remember(first) + let firstStream = await run.adapter.receivedData + let firstOrigin = try #require(await run.adapter.lifecycleOrigin) + #expect(first.resource.binding.isActive) + #expect(first.services.isEventMonitoringActive) + #expect(await run.machine.currentAppSessionLiveDeviceID == first.device.id) + let bridge = await run.machine.delegateHandler + bridge.centralManager( + run.native.central, didDisconnectPeripheral: run.native.peripheral, + timestamp: CFAbsoluteTimeGetCurrent(), isReconnecting: true, error: nil + ) + try await waitUntil("native loss must retire the old stack before reconnect discovery") { + run.manager.reconnectionCoordinator.currentCycle != nil && run.manager.connectionTeardownCount == 0 + } + #expect(run.manager.connectionState == .connecting) + #expect(run.manager.installedLink == nil) + #expect(!first.resource.binding.isActive) + #expect(await first.resource.session.sessionIsRunning == false) + #expect(await first.resource.session.subscriberCountForTest == 0) + #expect(!first.services.isEventMonitoringActive) + #expect(await run.machine.currentAppSessionLiveDeviceID == nil) + #expect(await run.machine.isAutoReconnecting) + #expect(run.native.cancellationCount == 0) + var stoppedIterator = firstStream.makeAsyncIterator() + #expect(await stoppedIterator.next() == nil) + bridge.centralManager(run.native.central, didConnect: run.native.peripheral) + // `.ready` is set before `onDeviceSynced`. A session read in between can delay that callback. + try await waitUntil("real discovery, appStart, and onDeviceSynced must publish a replacement") { + run.manager.connectionState == .ready && synced.callCount == 2 + } + let next = try #require(run.manager.installedLink) + run.remember(next) + #expect(next !== first) + #expect(next.requestID == first.requestID) + #expect(next.resource !== first.resource) + #expect(next.resource.binding !== first.resource.binding) + #expect(next.resource.session !== first.resource.session) + #expect(next.services !== first.services) + #expect(next.services.dataStore === first.services.dataStore) + #expect(next.device.id == first.device.id) + #expect(next.device.radioID == first.device.radioID) + #expect(next.device.publicKey == first.device.publicKey) + #expect(next.services.chatSendQueueService.radioID == first.device.radioID) + #expect(next.resource.binding.isActive) + #expect(await next.resource.session.sessionIsRunning) + #expect(next.services.isEventMonitoringActive) + #expect(await run.machine.currentAppSessionLiveDeviceID == next.device.id) + #expect(try await next.resource.session.getBattery().level == 3700) + #expect(try await next.resource.session.getTime().timeIntervalSince1970 > 0) + #expect(run.native.connectCount == 1) + #expect(run.native.serviceDiscoveryCount == 2) + #expect(run.native.subscriptionCount == 2) + #expect(run.native.cancellationCount == 0) + #expect(run.native.writePayloads.filter { $0.first == CommandCode.appStart.rawValue }.count == 2) + #expect(run.native.automaticAcknowledgementCount == run.native.writePayloads.count) + #expect(published.callCount == 2) + #expect(usable.callCount == 2) + #expect(synced.callCount == 2) + #expect(try await run.manager.persistenceStore.fetchDevice(id: first.device.id)?.radioID == first.device.radioID) + let closes = run.native.cancellationCount + await run.manager.handleBLELifecycleEvent(.disconnected(firstOrigin, error: .authenticationFailed)) + #expect(run.manager.installedLink === next) + #expect(next.resource.binding.isActive) + #expect(run.native.cancellationCount == closes) + _ = await run.manager.disconnect(reason: .userInitiated) + #expect(await next.resource.session.subscriberCountForTest == 0) + #expect(run.native.cancellationCount == 1) + run.manager.connectionStateEvents.finish() + await observer.value + #expect(events.values == [.connecting, .connecting, .connected, .syncing, .ready, + .connecting, .connecting, .connected, .syncing, .ready, .disconnected]) + } catch { + observer.cancel() + await observer.value + await run.close() + throw error + } + await run.close() + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Transport/RetirementStaleReadinessTests.swift b/MC1Services/Tests/MC1ServicesTests/Transport/RetirementStaleReadinessTests.swift new file mode 100644 index 0000000000..0ca5a5fedb --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Transport/RetirementStaleReadinessTests.swift @@ -0,0 +1,163 @@ +@preconcurrency import CoreBluetooth +import Foundation +@testable import MC1Services +@testable import MeshCore +import os +import Testing + +@Suite("Retirement stale readiness") +@MainActor +struct RetirementStaleReadinessTests { + enum ReadinessCallback: CaseIterable, Sendable { + case stalePeripheral + case stillBackpressuredCurrentPeripheral + case stalePeripheralWhileCurrentReady + } + + @Test(arguments: ReadinessCallback.allCases) + func `only current ready callback can release bs pipeline`(_ callback: ReadinessCallback) async throws { + let harness = await BLESetupRetirementHarness.make() + let peripheral = harness.peripheral + let binding = SessionTransportBinding() + let view = try await harness.connect(binding: binding) + let session = MeshCoreSession(transport: view) + let seen = OSAllocatedUnfairLock(initialState: Set()) + let stale = BLETransportHarness() + stale.peripheralState = .disconnected + stale.isReadyToWrite = true + let oldPeripheral = stale.peripheral + let callbackPeripheral = callback == .stillBackpressuredCurrentPeripheral ? peripheral : oldPeripheral + let callbackDeviceID = callbackPeripheral.identifier + await harness.machine.observeReadinessCallbacksForContract { id in + seen.withLock { _ = $0.insert(id) } + } + let delegate = await harness.machine.delegateHandler + delegate.stateMachine = harness.machine + var pipeline: Task<(received: [ChannelInfo], missing: [UInt8]), Error>? + do { + try await harness.start(session) + let before = harness.native.writePayloads + harness.native.isReadyToWrite = false + pipeline = Task { try await session.getChannels(indices: [0]) } + try await harness.awaitCondition { await harness.machine.isAwaitingWriteWithoutResponseReady } + if callback == .stalePeripheralWhileCurrentReady { + harness.native.isReadyToWrite = true + } + delegate.peripheralIsReady(toSendWriteWithoutResponse: callbackPeripheral) + try await harness.awaitCondition { seen.withLock { $0.contains(callbackDeviceID) } } + #expect(await harness.machine.isAwaitingWriteWithoutResponseReady) + #expect(harness.native.writePayloads == before) + #expect(binding.isActive) + + harness.native.isReadyToWrite = true + delegate.peripheralIsReady(toSendWriteWithoutResponse: peripheral) + try await harness.awaitCondition { + harness.native.writePayloads.count == before.count + 1 + } + var reply = Data([ResponseCode.channelInfo.rawValue, 0]) + reply.append(Data(repeating: 0, count: 32 + 16)) + await harness.inject(reply) + let result = try await #require(pipeline).value + #expect(result.received.map(\.index) == [0]) + let probe = Task { try await session.factoryReset() } + do { + try await harness.awaitCondition { await harness.machine.setupWriteIsPending } + await harness.completeWrite() + await harness.inject(Data([ResponseCode.ok.rawValue])) + try await probe.value + } catch { + await harness.machine.shutdown() + _ = await probe.result + throw error + } + } catch { + await harness.machine.shutdown() + _ = await pipeline?.result + await session.stop(disconnectTransport: false) + await session.waitForQuiescence() + throw error + } + binding.revoke() + await session.stop(disconnectTransport: false, drainExchanges: true) + await session.waitForQuiescence() + await harness.adapter.disconnect(sessionBinding: binding) + await harness.machine.shutdown() + #expect(await session.subscriberCountForTest == 0) + } + + @Test + func `a retired resource cannot release bs readiness waiter`() async throws { + let harness = await BLESetupRetirementHarness.make() + let peripheral = harness.peripheral + let oldBinding = SessionTransportBinding() + let oldView = try await harness.connect(binding: oldBinding) + let oldSession = MeshCoreSession(transport: oldView) + let oldResource = ConnectionResource( + binding: oldBinding, transport: harness.adapter, session: oldSession, + wifi: nil, ble: harness.adapter + ) + var current: MeshCoreSession? + var pipeline: Task<(received: [ChannelInfo], missing: [UInt8]), Error>? + do { + try await harness.start(oldSession) + await oldResource.retire(closePhysical: false) + let currentBinding = SessionTransportBinding() + let currentView = await harness.adapter.makeSessionTransport( + deviceID: peripheral.identifier, binding: currentBinding + ) + await harness.adapter.refreshDataStream(sessionBinding: currentBinding) + let session = MeshCoreSession(transport: currentView) + current = session + try await harness.start(session) + let before = harness.native.writePayloads + harness.native.isReadyToWrite = false + pipeline = Task { try await session.getChannels(indices: [0]) } + try await harness.awaitCondition { await harness.machine.isAwaitingWriteWithoutResponseReady } + await oldResource.retire(closePhysical: true) + #expect(await harness.machine.isAwaitingWriteWithoutResponseReady) + #expect(harness.native.writePayloads == before) + #expect(currentBinding.isActive) + #expect(harness.native.cancellationCount == 0) + + harness.native.isReadyToWrite = true + let delegate = await harness.machine.delegateHandler + delegate.stateMachine = harness.machine + delegate.peripheralIsReady(toSendWriteWithoutResponse: peripheral) + try await harness.awaitCondition { harness.native.writePayloads.count == before.count + 1 } + var reply = Data([ResponseCode.channelInfo.rawValue, 0]) + reply.append(Data(repeating: 0, count: 32 + 16)) + await harness.inject(reply) + #expect(try await #require(pipeline).value.received.map(\.index) == [0]) + let probe = Task { try await session.factoryReset() } + do { + try await harness.awaitCondition { await harness.machine.setupWriteIsPending } + await harness.completeWrite() + await harness.inject(Data([ResponseCode.ok.rawValue])) + try await probe.value + } catch { + await harness.machine.shutdown() + _ = await probe.result + throw error + } + currentBinding.revoke() + await session.stop(disconnectTransport: false, drainExchanges: true) + await session.waitForQuiescence() + await harness.adapter.disconnect(sessionBinding: currentBinding) + } catch { + await harness.machine.shutdown() + _ = await pipeline?.result + await oldSession.stop(disconnectTransport: false) + await current?.stop(disconnectTransport: false) + await oldSession.waitForQuiescence() + await current?.waitForQuiescence() + throw error + } + await harness.machine.shutdown() + } +} + +private extension BLEStateMachine { + func observeReadinessCallbacksForContract(_ observer: @escaping @Sendable (UUID) -> Void) { + testWriteReadinessHandled = observer + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Utilities/VContactIdentityTests.swift b/MC1Services/Tests/MC1ServicesTests/Utilities/VContactIdentityTests.swift index e3f98e898a..d6ea4a37f4 100644 --- a/MC1Services/Tests/MC1ServicesTests/Utilities/VContactIdentityTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Utilities/VContactIdentityTests.swift @@ -62,4 +62,16 @@ struct VContactIdentityTests { #expect(!VContactIdentity.isVContact(publicKey: Self.expectedVA, selfPublicKey: Data())) #expect(!VContactIdentity.isVContact(publicKey: Data(), selfPublicKey: Self.selfKeyA)) } + + @Test + func `Hex V-contact matches any of the given self keys in either case`() { + let uppercaseA = Self.expectedVA.hexString.uppercased() + #expect(VContactIdentity.isVContact( + publicKeyHex: uppercaseA, selfPublicKeys: [Self.selfKeyB, Self.selfKeyA] + )) + #expect(!VContactIdentity.isVContact( + publicKeyHex: Self.expectedVA.hexString, selfPublicKeys: [Self.selfKeyB] + )) + #expect(!VContactIdentity.isVContact(publicKeyHex: "abcd", selfPublicKeys: [Self.selfKeyA])) + } } diff --git a/MC1Tests/AppState/AppConnectionOwnershipTests.swift b/MC1Tests/AppState/AppConnectionOwnershipTests.swift new file mode 100644 index 0000000000..d1ef2fd033 --- /dev/null +++ b/MC1Tests/AppState/AppConnectionOwnershipTests.swift @@ -0,0 +1,312 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@Suite("App connection callback ownership") +@MainActor +struct AppConnectionOwnershipTests { + @Test(arguments: [false, true]) + func `a retired Settings consumer cannot update a replacement radio`(sameRadio: Bool) async throws { + try await withHarness { harness in + let old = try harness.install() + await harness.appState.wireSettingsEventStream(snapshot: old) + let oldTask = try #require(harness.appState.settingsEventsTask) + let oldEvents = try #require(await old.services.settingsService.eventContinuation) + let next = try harness.install(replacing: sameRadio ? old.device : nil) + + oldEvents.yield(.clientRepeatUpdated(true)) + oldEvents.finish() + await oldTask.value + #expect(harness.manager.isCurrent(next)) + #expect(harness.manager.connectedDevice?.clientRepeat == false) + + await harness.appState.wireSettingsEventStream(snapshot: next) + let nextTask = try #require(harness.appState.settingsEventsTask) + let nextEvents = try #require(await next.services.settingsService.eventContinuation) + nextEvents.yield(.clientRepeatUpdated(true)) + nextEvents.finish() + await nextTask.value + #expect(harness.manager.connectedDevice?.clientRepeat == true) + } + } + + @Test + func `old sync and storage events cannot mutate replacement presentation`() async throws { + try await withHarness { harness in + let old = try harness.install() + await harness.appState.connectionUI.wireCallbacks(snapshot: old, connectionManager: harness.manager) + harness.appState.wireSyncDataEvents(snapshot: old) + let oldDataTask = try #require(harness.appState.syncDataEventsTask) + let next = try harness.install(replacing: old.device) + await harness.appState.connectionUI.wireCallbacks(snapshot: next, connectionManager: harness.manager) + harness.appState.connectionUI.isNodeStorageFull = true + let contactsVersion = harness.appState.contactsVersion + + await old.services.syncCoordinator.beginResyncActivity() + old.services.syncCoordinator.notifyContactsChanged() + old.services.syncCoordinator.finishDataEvents() + old.services.advertisementService.eventBroadcaster.yield(.nodeStorageFullChanged(isFull: false)) + old.services.advertisementService.finishEvents() + await oldDataTask.value + #expect(harness.appState.connectionUI.syncActivityCount == 0) + #expect(harness.appState.contactsVersion == contactsVersion) + #expect(harness.appState.connectionUI.isNodeStorageFull) + + await next.services.syncCoordinator.beginResyncActivity() + #expect(harness.appState.connectionUI.syncActivityCount == 1) + await next.services.syncCoordinator.endResyncActivity(succeeded: false) + #expect(harness.appState.connectionUI.syncActivityCount == 0) + } + } + + @Test + func `a held battery result cannot publish through a replacement callback`() async throws { + try await withHarness { harness in + let oldRadio = ConnectionTestRadioTransport() + harness.radios.append(oldRadio) + let oldSession = MeshCoreSession(transport: oldRadio) + try await oldSession.start() + let old = try harness.install(session: oldSession) + await oldRadio.holdReplies(for: .getBattery) + let read = harness.run { + await harness.appState.batteryMonitor.fetchDeviceBattery(services: old.services, device: old.device) + } + try await waitUntil("old battery read should be submitted") { + await oldRadio.sentData.contains { $0.first == CommandCode.getBattery.rawValue } + } + + let nextRadio = ConnectionTestRadioTransport() + harness.radios.append(nextRadio) + let nextSession = MeshCoreSession(transport: nextRadio) + try await nextSession.start() + let next = try harness.install(session: nextSession) + let monitor = harness.appState.batteryMonitor + monitor.deviceBattery = BatteryInfo(level: 4200) + var publications = 0 + monitor.onBatteryChanged = { _ in publications += 1 } + await oldRadio.releaseReplies(for: .getBattery) + await read.value + #expect(monitor.deviceBattery?.level == 4200) + #expect(publications == 0) + + await monitor.fetchDeviceBattery(services: next.services, device: next.device) + #expect(monitor.deviceBattery?.level == 3700) + #expect(publications == 1) + } + } + + @Test + func `a replacement connects while retired app wiring is held`() async throws { + try await withHarness { harness in + let gate = harness.makeGate() + var heldGeneration: UUID? + var oldWiringResumed = false + harness.appState.connectionWiringAfterCallbacks = { snapshot in + guard heldGeneration == nil else { return } + heldGeneration = snapshot.generation + await gate.wait() + oldWiringResumed = true + } + harness.run { + do { + _ = try await harness.manager.connect(to: UUID()) + } catch { + Issue.record(error) + } + } + try await waitUntil("the old app wiring should reach the held await") { heldGeneration != nil } + let old = try #require(harness.manager.currentConnection) + let versionBeforeReplacement = harness.appState.servicesVersion + var replacement: ConnectionSnapshot? + harness.run { + do { + let result = try await harness.appState.connectViaWiFi(host: "next.local", port: ConnectionMethod.defaultWiFiPort) + if case let .operational(snapshot) = result { replacement = snapshot } + } catch { Issue.record(error) } + } + try await waitUntil("replacement should become usable before old native wiring resumes") { replacement != nil } + let next = try #require(replacement) + #expect(!oldWiringResumed) + #expect(harness.manager.isCurrent(next)) + #expect(!harness.manager.isCurrent(old)) + #expect(harness.appState.servicesVersion == versionBeforeReplacement + 1) + + gate.release() + try await waitUntil("the retired app wiring should finish after its hold is released") { oldWiringResumed } + #expect(harness.manager.isCurrent(next)) + #expect(harness.appState.servicesVersion == versionBeforeReplacement + 1) + #expect(harness.appState.syncCoordinator === next.services.syncCoordinator) + } + } + + @Test + func `cancelling a wiring waiter leaves another caller joined to the shared job`() async throws { + try await withHarness { harness in + let gate = harness.makeGate() + var operationStarted = false + var operationFinished = false + var cancelledWaiterFinished = false + var joinedWaiterFinished = false + let job = AppConnectionWiringJob(id: UUID(), generation: UUID()) { + operationStarted = true + await gate.wait() + operationFinished = true + } + let cancelled = harness.run { + await job.wait() + cancelledWaiterFinished = true + } + let joined = harness.run { + await job.wait() + joinedWaiterFinished = true + } + try await waitUntil("both callers should join the shared wiring operation") { + operationStarted && job.waitingCallerCount == 2 + } + cancelled.cancel() + try await waitUntil("the cancelled waiter should be released") { cancelledWaiterFinished } + #expect(!operationFinished) + #expect(!joinedWaiterFinished) + gate.release() + await joined.value + #expect(operationFinished) + #expect(joinedWaiterFinished) + } + } + + @Test + func `finishing an older presentation job cannot clear a newer busy state`() { + let state = ConnectionUIState() + let old = state.beginConnectionAction() + let next = state.beginConnectionAction() + #expect(!state.finishConnectionAction(old)) + #expect(state.isBusy) + #expect(state.isCurrentConnectionAction(next)) + #expect(state.finishConnectionAction(next)) + #expect(!state.isBusy) + } + + @Test + func `the same radio can open a new failure episode`() { + let state = ConnectionUIState() + let deviceID = UUID() + state.presentPairingFailure(.connectionFailed(deviceID: deviceID, underlying: BLEError.authenticationFailed)) + let first = state.pairingFailureEpisodeID + state.presentPairingFailure(.connectionFailed(deviceID: deviceID, underlying: BLEError.authenticationFailed)) + #expect(state.failedPairingDeviceID == deviceID) + #expect(state.pairingFailureEpisodeID != first) + } + + @MainActor + private final class Harness { + let appState: AppState + let suiteName: String + var services: [ServiceContainer] = [] + var radios: [ConnectionTestRadioTransport] = [] + private var jobs: [Task] = [] + private var gates: [Gate] = [] + var manager: ConnectionManager { + appState.connectionManager + } + + init() throws { + suiteName = "test.app-connection-ownership.\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + let container = try PersistenceStore.createContainer(inMemory: true) + let bluetooth = ConnectionTestRadioTransport(publicKey: Data(repeating: 0xA1, count: ProtocolLimits.publicKeySize)) + let wifi = ConnectionTestRadioTransport(publicKey: Data(repeating: 0xB1, count: ProtocolLimits.publicKeySize)) + let pairing = MockAccessorySetupKitService() + pairing.isSessionActive = false + let manager = ConnectionManager( + modelContainer: container, defaults: defaults, stateMachine: MockBLEStateMachine(), transport: bluetooth, + pairing: AccessorySetupPairingService(accessorySetupKit: pairing), makeWiFiTransport: { wifi } + ) + radios = [bluetooth, wifi] + appState = AppState(modelContainer: container, isPlaceholder: true, defaults: defaults, injectedConnectionManager: manager) + } + + func install(replacing old: DeviceDTO? = nil, session: MeshCoreSession? = nil) throws -> ConnectionSnapshot { + let device = old ?? DeviceDTO(from: Device( + radioID: UUID(), publicKey: Data(repeating: 0xA1, count: ProtocolLimits.publicKeySize), nodeName: "Fixture" + )) + let session = session ?? MeshCoreSession(transport: MockTransport()) + let container = ServiceContainer(session: session, dataStore: manager.persistenceStore, radioID: device.radioID) + services.append(container) + manager.setTestState( + connectionState: .connected, + services: container, + session: session, + connectedDevice: device, + currentTransportType: .bluetooth, + connectionIntent: .wantsConnection() + ) + return try #require(manager.currentConnection) + } + + @discardableResult + func run(_ work: @escaping @MainActor () async -> Void) -> Task { + let task = Task { await work() } + jobs.append(task) + return task + } + + func makeGate() -> Gate { + let gate = Gate() + gates.append(gate) + return gate + } + + func cleanup() async { + gates.forEach { $0.release() } + for radio in radios { + await radio.releaseAllGates() + } + jobs.forEach { $0.cancel() } + for job in jobs { + await job.value + } + await manager.disconnect(reason: .userInitiated) + let events = appState.settingsEventsTask + let sync = appState.syncDataEventsTask + appState.tearDownAppStateSessionState() + await events?.value + await sync?.value + appState.shutdown() + for container in services { + await container.tearDown() + await container.session.stop() + } + UserDefaults().removePersistentDomain(forName: suiteName) + } + + @MainActor + final class Gate { + private var continuation: CheckedContinuation? + private var released = false + + func wait() async { + guard !released else { return } + await withCheckedContinuation { continuation = $0 } + } + + func release() { + released = true + continuation?.resume() + continuation = nil + } + } + } + + private func withHarness(_ body: @MainActor (Harness) async throws -> Void) async throws { + let harness = try Harness() + do { + try await body(harness) + } catch { + await harness.cleanup() + throw error + } + await harness.cleanup() + } +} diff --git a/MC1Tests/AppState/AppStateSwitchTransportTests.swift b/MC1Tests/AppState/AppStateSwitchTransportTests.swift index 5b53946c38..a6a9cca619 100644 --- a/MC1Tests/AppState/AppStateSwitchTransportTests.swift +++ b/MC1Tests/AppState/AppStateSwitchTransportTests.swift @@ -8,94 +8,29 @@ import Testing struct AppStateSwitchTransportTests { @Test func `a timeout shows the connection failed alert`() async throws { - let harness = try makeHarness() - defer { harness.appState.shutdown() } - harness.manager.testWiFiConnectHandler = { _, _ in - throw BLEError.connectionTimeout + try await ConnectionLinkSwitchHarness.withHarness { harness in + await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") + + #expect(harness.appState.connectionUI.showingConnectionFailedAlert) + #expect(harness.appState.connectionUI.failedPairingDeviceID == nil) + #expect(harness.appState.connectionLinkSwitch?.checked == .bluetooth) + #expect(harness.appState.connectionLinkSwitch?.target == nil) + #expect(await harness.wifi.connectCount == 1) + #expect(harness.manager.currentTransportType == nil) } - - await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") - - #expect(harness.appState.connectionUI.showingConnectionFailedAlert) - #expect(harness.appState.connectionUI.failedPairingDeviceID == nil) - #expect(harness.appState.connectionLinkSwitch?.checked == .bluetooth) - #expect(harness.appState.connectionLinkSwitch?.target == nil) } @Test func `an authentication failure records the passed device`() async throws { - let harness = try makeHarness() - defer { harness.appState.shutdown() } - harness.manager.testWiFiConnectHandler = { _, _ in - throw BLEError.authenticationFailed - } - - await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") + try await ConnectionLinkSwitchHarness.withHarness { harness in + await harness.wifi.setConnectError(BLEError.authenticationFailed) - #expect(harness.appState.connectionUI.failedPairingDeviceID == harness.device.id) - #expect(harness.appState.connectionLinkSwitch?.checked == .bluetooth) - #expect(harness.appState.connectionLinkSwitch?.target == nil) - } - - @MainActor - private struct Harness { - let appState: AppState - let device: DeviceDTO - var manager: ConnectionManager { - appState.connectionManager - } - } + await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") - private func makeHarness() throws -> Harness { - let suite = "test.switchtransport.\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: suite)) - defaults.removePersistentDomain(forName: suite) - let appState = try AppState( - modelContainer: PersistenceStore.createContainer(inMemory: true), - isPlaceholder: true, - defaults: defaults - ) - let peripheralID = UUID() - let device = DeviceDTO( - id: UUID(), - publicKey: Data(repeating: 0xB1, count: ProtocolLimits.publicKeySize), - nodeName: "Relay", - firmwareVersion: 11, - firmwareVersionString: "1.15.0", - manufacturerName: "Test", - buildDate: "2025-01-01", - maxContacts: 100, - maxChannels: 8, - frequency: 915_000, - bandwidth: 250_000, - spreadingFactor: 10, - codingRate: 5, - txPower: 20, - maxTxPower: 20, - latitude: 0, - longitude: 0, - blePin: 0, - manualAddContacts: false, - multiAcks: 2, - telemetryModeBase: 2, - telemetryModeLoc: 0, - telemetryModeEnv: 0, - advertLocationPolicy: 0, - lastConnected: Date(), - lastContactSync: 0, - isActive: true, - ocvPreset: nil, - customOCVArrayString: nil, - connectionMethods: [.bluetooth(peripheralUUID: peripheralID, displayName: nil)] - ) - appState.connectionManager.setTestState( - connectionState: .connected, - connectedDevice: .some(device), - currentTransportType: .bluetooth - ) - appState.connectionManager.testWiFiConnectHandler = { _, _ in - throw BLEError.connectionTimeout + #expect(harness.appState.connectionUI.failedPairingDeviceID == harness.device.id) + #expect(harness.appState.connectionLinkSwitch?.checked == .bluetooth) + #expect(harness.appState.connectionLinkSwitch?.target == nil) + #expect(await harness.wifi.connectCount == 1) } - return Harness(appState: appState, device: device) } } diff --git a/MC1Tests/AppState/CanonicalIdentityCallerTests.swift b/MC1Tests/AppState/CanonicalIdentityCallerTests.swift new file mode 100644 index 0000000000..92d045313d --- /dev/null +++ b/MC1Tests/AppState/CanonicalIdentityCallerTests.swift @@ -0,0 +1,164 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Canonical identity import caller") +@MainActor +struct CanonicalIdentityCallerTests { + @Test(arguments: [false, true]) + func `interrupted identity apply surfaces unknown outcome and retains source`(losesAcknowledgement: Bool) async throws { + let env = try await ConnectionLinkSwitchHarness.make() + let model = NodeConfigImportViewModel() + model.configure( + nodeConfigService: { env.manager.services?.nodeConfigService }, + settingsService: { env.manager.services?.settingsService }, + connectedDevice: { env.manager.connectedDevice }, + connectionManager: env.manager + ) + do { + let source = try #require(env.manager.currentConnection) + let settings = source.services.settingsService + _ = try await settings.runCliCommand("set wifi.enabled 0") + let config = MeshCoreNodeConfig( + privateKey: "7065e18fd9fabb70c1ed90dca19907de698c88b709ea146eafd93d9b830c7b60" + + "c4681193c79bbc39945ba8064104bb618f8fd7a84a0af6f57033d6e8ddcd6471" + ) + model.acceptInput(config, source: nil) + model.sections = ConfigSections(nodeIdentity: true) + model.prepareConfirmation() + try await waitUntil { model.showConfirmation || model.errorMessage != nil } + #expect(model.showConfirmation) + await env.bluetooth.enqueueResponsePackets( + for: losesAcknowledgement ? .importPrivateKey : .appStart, packets: [] + ) + + model.applyConfig() + try await waitUntil(timeout: .seconds(35)) { !model.isApplying } + + #expect(!model.importComplete) + #expect(model.applyProgress == (losesAcknowledgement ? 0 : 1)) + #expect(model.errorMessage == L10n.Settings.ConfigImport.identityOutcomeUnknown(source.device.nodeName)) + let servicesUnavailable = env.manager.services == nil + #expect(servicesUnavailable) + #expect(settings.radioWiFiState.rebootPending) + let saved = try #require(try await env.manager.persistenceStore.fetchDevice(id: source.device.id)) + #expect(saved.id == source.device.id) + #expect(saved.radioID == source.device.radioID) + #expect(saved.publicKey == source.device.publicKey) + + env.appState.navigation.clearPerDeviceSelection() + model.handleDismissal() + let retainedOriginalInput = model.importedConfig == config + #expect(retainedOriginalInput) + #expect(model.errorMessage == L10n.Settings.ConfigImport.identityOutcomeUnknown(source.device.nodeName)) + } catch { + model.cancelImport() + await env.bluetooth.releaseAllGates() + await env.close() + throw error + } + model.cancelImport() + await env.close() + } + + @Test + func `actual import caller rewires canonical partition and wi fi evidence`() async throws { + let env = try await ConnectionLinkSwitchHarness.make() + let model = NodeConfigImportViewModel() + model.configure( + nodeConfigService: { env.manager.services?.nodeConfigService }, + settingsService: { env.manager.services?.settingsService }, + connectedDevice: { env.manager.connectedDevice }, + connectionManager: env.manager + ) + do { + let canonicalKey = Data([ + 0x1E, 0xC7, 0x71, 0x75, 0xB0, 0x91, 0x8E, 0xD2, 0x06, 0xF9, 0xAE, 0x04, 0xEC, 0x13, 0x6D, 0x6D, + 0x5D, 0x43, 0x15, 0xBB, 0x26, 0x30, 0x54, 0x27, 0xF6, 0x45, 0xB4, 0x92, 0xE9, 0x35, 0x0C, 0x10 + ]) + let ghost = env.device.copy { + $0.id = UUID() + $0.radioID = UUID() + $0.publicKey = canonicalKey + $0.isActive = false + $0.connectionMethods = [] + } + try await env.manager.persistenceStore.saveDevice(ghost) + let source = try #require(env.manager.currentConnection) + let settings = source.services.settingsService + let originalState = settings.radioWiFiState + let originalContext = settings.radioWiFiContextID + _ = try await settings.runCliCommand("set wifi.enabled 0") + await env.bluetooth.setPublicKey(canonicalKey, for: env.device.id) + let contactKey = Data(repeating: 0xC9, count: ProtocolLimits.publicKeySize) + model.acceptInput(MeshCoreNodeConfig( + privateKey: "7065e18fd9fabb70c1ed90dca19907de698c88b709ea146eafd93d9b830c7b60" + + "c4681193c79bbc39945ba8064104bb618f8fd7a84a0af6f57033d6e8ddcd6471", + channels: [.init(name: "Canonical", secret: String(repeating: "CD", count: 16))], + contacts: [.init(type: 1, name: "Imported", publicKey: contactKey.hexString, flags: 0, + latitude: "0", longitude: "0", lastAdvert: 0, lastModified: 0)] + ), source: nil) + model.sections = ConfigSections(nodeIdentity: true, channels: true, contacts: true) + model.prepareConfirmation() + try await waitUntil { model.showConfirmation || model.errorMessage != nil } + #expect(model.showConfirmation) + model.applyConfig() + try await waitUntil { !model.isApplying } + #expect(model.importComplete) + #expect(model.errorMessage == nil) + try await waitUntil { + env.manager.connectionState == .ready && env.manager.services?.notificationService.getBadgeCount != nil + } + #expect(env.manager.connectedDevice?.radioID == ghost.radioID) + let canonicalSettings = try #require(env.manager.services?.settingsService) + #expect(canonicalSettings !== settings) + #expect(settings.radioWiFiState === originalState) + #expect(settings.radioWiFiContextID == originalContext) + #expect(settings.radioWiFiState.radioID == source.device.radioID) + #expect(settings.radioWiFiState.rebootPending) + #expect(canonicalSettings.radioWiFiState === env.manager.radioWiFiState(for: ghost.radioID)) + #expect(canonicalSettings.radioWiFiContextID != originalContext) + #expect(canonicalSettings.radioWiFiState.radioID == ghost.radioID) + #expect(canonicalSettings.radioWiFiState.rebootPending) + let cliFramesBefore = await env.bluetooth.sentData.filter { $0.first == CommandCode.runCliCommand.rawValue }.count + await #expect { + try await settings.runCliCommand("get wifi.enabled") + } throws: { $0 is CancellationError } + let cliFramesAfter = await env.bluetooth.sentData.filter { $0.first == CommandCode.runCliCommand.rawValue }.count + #expect(cliFramesAfter == cliFramesBefore) + let settingsTime = try await canonicalSettings.getTime() + #expect(settingsTime.timeIntervalSince1970 > 0) + let contact = try #require(try await env.manager.persistenceStore.fetchContacts(radioID: ghost.radioID) + .first { $0.publicKey == contactKey }) + let channels = try await env.manager.persistenceStore.fetchChannels(radioID: ghost.radioID) + #expect(channels.contains { $0.name == "Canonical" }) + var incoming = Data([ResponseCode.contactMessageReceived.rawValue]) + Data(contactKey.prefix(6)) + incoming.append(contentsOf: [0, TextType.plain.rawValue]) + incoming.append(withUnsafeBytes(of: UInt32(1_700_000_001).littleEndian) { Data($0) }) + incoming.append(Data("Unread canonical message".utf8)) + await env.bluetooth.inject(incoming) + try await waitUntil { + await (try? env.manager.persistenceStore.fetchMessages(contactID: contact.id).contains { + $0.text == "Unread canonical message" + }) == true + } + try await waitUntil { + await (try? env.manager.persistenceStore.getUnreadCount(contactID: contact.id)) == 1 + } + let badgeReader = try #require(env.manager.services?.notificationService.getBadgeCount) + let badge = await badgeReader() + #expect(badge.contacts == 1) + let observedTime = try await #require(env.manager.session).getTime() + #expect(observedTime.timeIntervalSince1970 > 0) + } catch { + model.cancelImport() + await env.bluetooth.releaseAllGates() + await env.close() + throw error + } + model.cancelImport() + await env.close() + } +} diff --git a/MC1Tests/AppState/ChatCoordinatorRegistrySurvivalTests.swift b/MC1Tests/AppState/ChatCoordinatorRegistrySurvivalTests.swift index 265d02e9be..89d9d3dc0d 100644 --- a/MC1Tests/AppState/ChatCoordinatorRegistrySurvivalTests.swift +++ b/MC1Tests/AppState/ChatCoordinatorRegistrySurvivalTests.swift @@ -19,8 +19,7 @@ struct ChatCoordinatorRegistrySurvivalTests { let conversationID = ChatConversationID.dm(radioID: UUID(), contactID: UUID()) let original = registry.coordinator(for: conversationID) - appState.connectionManager.setTestState(services: .some(nil)) - await appState.wireServicesIfConnected() + await appState.disconnect() #expect(appState.chatCoordinatorRegistry === registry) #expect(appState.chatCoordinatorRegistry?.existingCoordinator(for: conversationID) === original) @@ -30,7 +29,11 @@ struct ChatCoordinatorRegistrySurvivalTests { ) appState.connectionManager.setTestState( connectionState: .ready, - services: services + services: services, + session: services.session, + connectedDevice: DeviceDTO(from: Device( + radioID: UUID(), publicKey: Data(repeating: 1, count: ProtocolLimits.publicKeySize), nodeName: "Fixture" + )) ) await appState.wireServicesIfConnected() @@ -39,13 +42,76 @@ struct ChatCoordinatorRegistrySurvivalTests { } @Test - func `notifyDataRestored bumps servicesVersion and the next load binds a fresh coordinator`() async throws { - let appState = AppState() + func `connection loss refreshes an open channel timeline to the committed send`() async throws { + let suiteName = "test.loss-timeline.\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + let appState = AppState(defaults: defaults) defer { appState.shutdown() } - appState.connectionManager.testLastConnectedDeviceID = UUID() + let radioID = UUID() + appState.connectionManager.persistConnection(deviceID: UUID(), radioID: radioID, deviceName: "Fixture") let store = try #require(appState.offlineDataStore) + let channel = ChannelDTO( + id: UUID(), radioID: radioID, index: 2, name: "Ops", + secret: Data(repeating: 0x5A, count: 16), isEnabled: true, + lastMessageDate: nil, unreadCount: 0 + ) + let message = MessageDTO( + id: UUID(), radioID: radioID, contactID: nil, channelIndex: channel.index, + text: "kept", timestamp: 1_700_000_000, + createdAt: Date(timeIntervalSince1970: 1_700_000_000), + direction: .outgoing, status: .pending, textType: .plain, ackCode: nil, + pathLength: 0, snr: nil, senderKeyPrefix: nil, senderNodeName: nil, + isRead: true, replyToID: nil, roundTripTime: nil, heardRepeats: 0, + retryAttempt: 0, maxRetryAttempts: 0 + ) + try await store.saveChannel(channel) + try await store.saveMessage(message) + + let registry = try #require(appState.ensureChatCoordinatorRegistry()) + let viewModel = ChatViewModel() + viewModel.configure( + dependencies: appState.makeChatViewModelDependencies(radioID: radioID), + onNavigateToMap: nil, linkPreviewCache: nil, + chatCoordinatorRegistry: registry, conversation: .channel(channel) + ) + viewModel.applyEnvInputs(.default) + #expect(await viewModel.primeInitialChannelMessages(for: channel, populateMode: .replace)) + #expect(viewModel.messagesByID[message.id]?.status == .pending) + try await store.updateMessageStatus(id: message.id, status: .sent) + #expect(viewModel.messagesByID[message.id]?.status == .pending) + + let versionBeforeLoss = appState.servicesVersion + await appState.disconnect() + #expect(appState.servicesVersion == versionBeforeLoss + 1) + #expect(appState.services == nil) + viewModel.configure( + dependencies: appState.makeChatViewModelDependencies(radioID: radioID), + onNavigateToMap: nil, linkPreviewCache: nil, + chatCoordinatorRegistry: registry, conversation: .channel(channel) + ) + await viewModel.loadChannelMessages(for: channel, populateMode: .refreshWindow) + await viewModel.coordinator?.buildItemsTask?.value + #expect(viewModel.messagesByID[message.id]?.status == .sent) + + let versionAfterRefresh = appState.servicesVersion + await appState.handleConnectionLoss(ConnectionLossReceipt(requestID: UUID(), retiredGeneration: UUID())) + #expect(appState.servicesVersion == versionAfterRefresh) + #expect(viewModel.messagesByID[message.id]?.status == .sent) + } + + @Test + func `notifyDataRestored bumps servicesVersion and the next load binds a fresh coordinator`() async throws { + let suiteName = "test.registry-source.\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + let appState = AppState(defaults: defaults) + defer { appState.shutdown() } let radioID = UUID() + appState.connectionManager.persistConnection(deviceID: UUID(), radioID: radioID, deviceName: "Fixture") + let store = try #require(appState.offlineDataStore) + let contact = makeForgetTestContact(radioID: radioID) try await store.saveContact(contact) try await store.saveMessage(makeForgetTestMessage( @@ -57,7 +123,7 @@ struct ChatCoordinatorRegistrySurvivalTests { let registry = try #require(appState.ensureChatCoordinatorRegistry()) let viewModel = ChatViewModel() viewModel.configure( - dependencies: appState.makeChatViewModelDependencies(), + dependencies: appState.makeChatViewModelDependencies(radioID: contact.radioID), onNavigateToMap: nil, linkPreviewCache: nil, chatCoordinatorRegistry: registry, @@ -70,11 +136,12 @@ struct ChatCoordinatorRegistrySurvivalTests { appState.notifyDataRestored() + #expect(appState.chatCoordinatorRegistry === registry) #expect(appState.servicesVersion == versionBefore + 1) #expect(registry.existingCoordinator(for: original.conversationID) == nil) viewModel.configure( - dependencies: appState.makeChatViewModelDependencies(), + dependencies: appState.makeChatViewModelDependencies(radioID: contact.radioID), onNavigateToMap: nil, linkPreviewCache: nil, chatCoordinatorRegistry: registry, @@ -85,24 +152,6 @@ struct ChatCoordinatorRegistrySurvivalTests { #expect(rebound !== original) } - @Test - func `notifyDataRestored drops registry entries`() throws { - let appState = AppState() - defer { appState.shutdown() } - appState.connectionManager.testLastConnectedDeviceID = UUID() - - let registry = try #require(appState.ensureChatCoordinatorRegistry()) - let conversationID = ChatConversationID.dm(radioID: UUID(), contactID: UUID()) - let original = registry.coordinator(for: conversationID) - - appState.notifyDataRestored() - - #expect(appState.chatCoordinatorRegistry === registry) - #expect(registry.existingCoordinator(for: conversationID) == nil) - let afterRestore = registry.coordinator(for: conversationID) - #expect(afterRestore !== original) - } - @Test func `forgetting the last-connected device empties the registry and reloads unavailable`() async throws { let suiteName = "test.forget-registry.\(UUID().uuidString)" @@ -132,7 +181,7 @@ struct ChatCoordinatorRegistrySurvivalTests { let conversationID = ChatConversationID.dm(radioID: radioID, contactID: contact.id) let viewModel = ChatViewModel() viewModel.configure( - dependencies: appState.makeChatViewModelDependencies(), + dependencies: appState.makeChatViewModelDependencies(radioID: contact.radioID), onNavigateToMap: nil, linkPreviewCache: nil, chatCoordinatorRegistry: registry, @@ -151,7 +200,7 @@ struct ChatCoordinatorRegistrySurvivalTests { #expect(appState.offlineDataStore == nil) viewModel.configure( - dependencies: appState.makeChatViewModelDependencies(), + dependencies: appState.makeChatViewModelDependencies(radioID: contact.radioID), onNavigateToMap: nil, linkPreviewCache: nil, chatCoordinatorRegistry: registry, diff --git a/MC1Tests/AppState/CommittedChannelSlotCleanupTests.swift b/MC1Tests/AppState/CommittedChannelSlotCleanupTests.swift new file mode 100644 index 0000000000..29220b25a3 --- /dev/null +++ b/MC1Tests/AppState/CommittedChannelSlotCleanupTests.swift @@ -0,0 +1,187 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Committed channel slot cleanup", .serialized) +@MainActor +struct CommittedChannelSlotCleanupTests { + @Test(arguments: [false, true]) + func `a committed channel reassignment retires cached state after its link retires`(replacementRadio: Bool) async throws { + let harness = try Harness() + do { + try await checkCommittedCleanup(in: harness, replacementRadio: replacementRadio) + } catch { + await harness.close() + throw error + } + await harness.close() + } + + private func checkCommittedCleanup(in harness: Harness, replacementRadio: Bool) async throws { + let app = harness.app + let manager = app.connectionManager + let store = manager.persistenceStore + await harness.radio.setChannel(index: 0, name: "Prior", secret: harness.priorSecret) + _ = try await manager.connect(to: harness.deviceID) + let old = try #require(manager.currentConnection) + harness.trackLogBuffer(old.services) + let channel = try #require(try await store.fetchChannel(radioID: old.device.radioID, index: 0)) + let id = ChatConversationID.channel(radioID: old.device.radioID, channelIndex: 0) + let editor = app.chatDraftEditor(for: id) + editor.setText("private draft") + editor.flush() + let registry = try #require(app.ensureChatCoordinatorRegistry()) + let coordinator = registry.coordinator(for: id) + app.navigation.navigateToChannel(with: channel, scrollToMessageID: UUID()) + + let other = try await harness.prepareReplacement() + let otherID = ChatConversationID.channel(radioID: other.radioID, channelIndex: 0) + let otherChannel = try #require(try await store.fetchChannel(radioID: other.radioID, index: 0)) + let otherEditor = app.chatDraftEditor(for: otherID) + otherEditor.setText("other draft") + otherEditor.flush() + let otherCoordinator = registry.coordinator(for: otherID) + + await harness.radio.setChannel(index: 0, name: "Replacement", secret: harness.replacementSecret) + await store.setBatchSaveChannelsFaultInjection { + DispatchQueue.main.sync { + MainActor.assumeIsolated { + harness.retireLink(replacingWith: replacementRadio ? other : nil) + if replacementRadio { + app.navigation.navigateToChannel(with: otherChannel, scrollToMessageID: harness.otherScrollTarget) + } + } + } + } + let result = try await old.services.channelService.syncChannels( + radioID: old.device.radioID, maxChannels: 1, usePipelinedRead: false + ) + await store.setBatchSaveChannelsFaultInjection(nil) + await harness.retirement?.value + + #expect(result.channelsSynced == 1) + #expect(result.errors.isEmpty) + #expect(!manager.isCurrent(old)) + #expect(try await store.fetchChannel(radioID: old.device.radioID, index: 0)?.secret == harness.replacementSecret) + #expect(DraftStore(defaults: harness.defaults).draft(for: id) == nil) + #expect(registry.existingCoordinator(for: id) == nil) + #expect(app.channelSlotGenerations[id] == 1) + let nextEditor = app.chatDraftEditor(for: id) + #expect(nextEditor !== editor) + #expect(nextEditor.text.isEmpty) + #expect(registry.coordinator(for: id) !== coordinator) + nextEditor.setText("replacement draft") + nextEditor.flush() + editor.setText("stale write") + editor.flush() + #expect(editor.text == "private draft") + #expect(DraftStore(defaults: harness.defaults).draft(for: id) == "replacement draft") + + #expect(app.chatDraftEditor(for: otherID) === otherEditor) + #expect(otherEditor.text == "other draft") + #expect(DraftStore(defaults: harness.defaults).draft(for: otherID) == "other draft") + #expect(registry.existingCoordinator(for: otherID) === otherCoordinator) + #expect(app.channelSlotGenerations[otherID] == nil) + if replacementRadio { + #expect(manager.currentConnection?.device.radioID == other.radioID) + #expect(app.navigation.chatsSelectedRoute == .channel(otherChannel)) + #expect(app.navigation.pendingScrollTarget?.messageID == harness.otherScrollTarget) + } else { + #expect(app.navigation.chatsSelectedRoute == nil) + #expect(app.navigation.pendingScrollTarget == nil) + _ = try await manager.connect(to: harness.deviceID) + try harness.trackLogBuffer(#require(manager.services)) + #expect(manager.currentConnection?.device.radioID == old.device.radioID) + #expect(app.channelSlotGenerations[id] == 1) + #expect(app.chatDraftEditor(for: id) === nextEditor) + #expect(DraftStore(defaults: harness.defaults).draft(for: id) == "replacement draft") + } + } + + @MainActor + private final class Harness { + let app: AppState + let defaults: UserDefaults + let radio = ConnectionTestRadioTransport(publicKey: Data(repeating: 0xA1, count: ProtocolLimits.publicKeySize)) + let otherRadio = ConnectionTestRadioTransport(publicKey: Data(repeating: 0xB1, count: ProtocolLimits.publicKeySize)) + let deviceID = UUID() + let otherScrollTarget = UUID() + let priorSecret = Data(repeating: 0x11, count: ProtocolLimits.channelSecretSize) + let replacementSecret = Data(repeating: 0x22, count: ProtocolLimits.channelSecretSize) + var retirement: ConnectionRetirement? + private let suiteName = "test.committed-channel-cleanup.\(UUID())" + private var otherSession: MeshCoreSession? + private var otherServices: ServiceContainer? + private let previousDebugLogBuffer = DebugLogBuffer.shared + private var ownedDebugLogBuffers: [DebugLogBuffer] = [] + + init() throws { + defaults = try #require(UserDefaults(suiteName: suiteName)) + let container = try PersistenceStore.createContainer(inMemory: true) + let pairing = MockAccessorySetupKitService() + pairing.isSessionActive = false + let otherRadio = otherRadio + let manager = ConnectionManager( + modelContainer: container, defaults: defaults, stateMachine: MockBLEStateMachine(), transport: radio, + pairing: AccessorySetupPairingService(accessorySetupKit: pairing), makeWiFiTransport: { otherRadio } + ) + manager.otherAppWaitStrategyOverride = { _ in false } + app = AppState(modelContainer: container, isPlaceholder: true, defaults: defaults, injectedConnectionManager: manager) + } + + func prepareReplacement() async throws -> DeviceDTO { + try await otherRadio.connect() + let session = MeshCoreSession(transport: otherRadio) + try await session.start() + otherSession = session + let device = DeviceDTO(from: Device( + radioID: UUID(), publicKey: Data(repeating: 0xB1, count: ProtocolLimits.publicKeySize), nodeName: "Other" + )) + let services = ServiceContainer(session: session, dataStore: app.connectionManager.persistenceStore, radioID: device.radioID) + otherServices = services + trackLogBuffer(services) + try await app.connectionManager.persistenceStore.saveDevice(device) + _ = try await app.connectionManager.persistenceStore.saveChannel( + radioID: device.radioID, from: ChannelInfo(index: 0, name: "Other", secret: priorSecret) + ) + return device + } + + func trackLogBuffer(_ services: ServiceContainer) { + ownedDebugLogBuffers.append(services.debugLogBuffer) + } + + func retireLink(replacingWith replacement: DeviceDTO?) { + retirement = app.connectionManager.beginDisconnect(reason: .userInitiated).barrier + guard let replacement, let services = otherServices else { return } + app.connectionManager.setTestState( + connectionState: .ready, services: services, session: services.session, + connectedDevice: replacement, currentTransportType: .wifi, wifiTransport: otherRadio, + connectionIntent: .wantsConnection() + ) + } + + func close() async { + await app.connectionManager.persistenceStore.setBatchSaveChannelsFaultInjection(nil) + await radio.releaseAllGates() + await otherRadio.releaseAllGates() + await retirement?.value + await app.connectionManager.disconnect(reason: .userInitiated) + let settings = app.settingsEventsTask + let sync = app.syncDataEventsTask + app.tearDownAppStateSessionState() + await settings?.value + await sync?.value + app.shutdown() + await otherServices?.tearDown() + await otherSession?.stop() + await otherRadio.disconnect() + defaults.removePersistentDomain(forName: suiteName) + if let current = DebugLogBuffer.shared, ownedDebugLogBuffers.contains(where: { $0 === current }) { + DebugLogBuffer.shared = previousDebugLogBuffer + } + } + } +} diff --git a/MC1Tests/AppState/ConnectionLinkSwitchTests.swift b/MC1Tests/AppState/ConnectionLinkSwitchTests.swift index d3749eb7a5..ae2a511445 100644 --- a/MC1Tests/AppState/ConnectionLinkSwitchTests.swift +++ b/MC1Tests/AppState/ConnectionLinkSwitchTests.swift @@ -8,112 +8,85 @@ import Testing struct ConnectionLinkSwitchTests { @Test func `the live link does not start an attempt`() async throws { - let harness = try makeHarness(live: .bluetooth, peripheralID: UUID(), wifiHost: nil) - defer { harness.appState.shutdown() } + try await ConnectionLinkSwitchHarness.withHarness { harness in + await harness.appState.beginLinkSwitch(to: .bluetooth, snapshotWiFiHost: "10.0.0.8") - await harness.appState.beginLinkSwitch(to: .bluetooth, snapshotWiFiHost: "10.0.0.8") - - #expect(harness.appState.connectionLinkSwitch == nil) - #expect(harness.manager.testWiFiConnectAttempts.isEmpty) - #expect(harness.manager.testBluetoothConnectAttempts.isEmpty) + #expect(harness.appState.connectionLinkSwitch == nil) + #expect(await harness.wifi.connectCount == 0) + #expect(await harness.bluetooth.connectCount == harness.initialBluetoothAttempts) + #expect(harness.manager.connectionState == .ready) + } } @Test func `the other link starts one attempt and keeps the check`() async throws { let peripheralID = UUID() - let harness = try makeHarness(live: .bluetooth, peripheralID: peripheralID, wifiHost: nil) - defer { harness.appState.shutdown() } - let gate = LinkSwitchGate() - harness.manager.testWiFiConnectHandler = { _, _ in - await gate.enter() - throw BLEError.connectionTimeout - } - - let task = Task { - await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") + try await ConnectionLinkSwitchHarness.withHarness(peripheralID: peripheralID) { harness in + await harness.wifi.holdConnect() + let task = harness.startSwitch(to: .wifi) + try await waitUntil("WiFi physical connect held") { await harness.wifi.connectIsHeld } + + let record = try #require(harness.appState.connectionLinkSwitch) + #expect(record.checked == .bluetooth) + #expect(record.target == .wifi) + #expect(record.bluetoothPeripheralID == peripheralID) + #expect(record.wifi == ConnectionLinkWiFiDial(host: "10.0.0.8", port: ConnectionMethod.defaultWiFiPort)) + #expect(record.deviceID == harness.device.id) + #expect(await harness.wifi.connectCount == 1) + #expect(await harness.wifi.connectionInfo?.host == "10.0.0.8") + #expect(await harness.wifi.connectionInfo?.port == ConnectionMethod.defaultWiFiPort) + #expect(await harness.bluetooth.connectCount == harness.initialBluetoothAttempts) + + await harness.wifi.releaseConnect() + await task.value } - await gate.waitUntilEntered() - - let record = try #require(harness.appState.connectionLinkSwitch) - #expect(record.checked == .bluetooth) - #expect(record.target == .wifi) - #expect(record.bluetoothPeripheralID == peripheralID) - #expect(record.wifi == ConnectionLinkWiFiDial(host: "10.0.0.8", port: ConnectionMethod.defaultWiFiPort)) - #expect(record.deviceID == harness.device.id) - let attempt = try #require(harness.manager.testWiFiConnectAttempts.first) - #expect(harness.manager.testWiFiConnectAttempts.count == 1) - #expect(attempt.host == "10.0.0.8") - #expect(attempt.port == ConnectionMethod.defaultWiFiPort) - #expect(harness.manager.testBluetoothConnectAttempts.isEmpty) - - gate.release() - await task.value } @Test func `a second start does not replace the current attempt`() async throws { - let harness = try makeHarness(live: .bluetooth, peripheralID: UUID(), wifiHost: nil) - defer { harness.appState.shutdown() } - let gate = LinkSwitchGate() - harness.manager.testWiFiConnectHandler = { _, _ in - await gate.enter() - throw BLEError.connectionTimeout - } + try await ConnectionLinkSwitchHarness.withHarness { harness in + await harness.wifi.holdConnect() + let task = harness.startSwitch(to: .wifi) + try await waitUntil("WiFi physical connect held") { await harness.wifi.connectIsHeld } + let token = try #require(harness.appState.connectionLinkSwitch).token - let task = Task { - await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") + await harness.appState.beginLinkSwitch(to: .bluetooth, snapshotWiFiHost: "10.9.9.9") + await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.9.9.9") + + let record = try #require(harness.appState.connectionLinkSwitch) + #expect(record.token == token) + #expect(record.target == .wifi) + #expect(record.wifi?.host == "10.0.0.8") + #expect(await harness.wifi.connectCount == 1) + #expect(await harness.bluetooth.connectCount == harness.initialBluetoothAttempts) + await harness.wifi.releaseConnect() + await task.value } - await gate.waitUntilEntered() - let token = try #require(harness.appState.connectionLinkSwitch).token - - await harness.appState.beginLinkSwitch(to: .bluetooth, snapshotWiFiHost: "10.9.9.9") - await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.9.9.9") - - let record = try #require(harness.appState.connectionLinkSwitch) - #expect(record.token == token) - #expect(record.target == .wifi) - #expect(record.wifi?.host == "10.0.0.8") - #expect(harness.manager.testWiFiConnectAttempts.count == 1) - #expect(harness.manager.testBluetoothConnectAttempts.isEmpty) - - gate.release() - await task.value } @Test func `a missing dial fact does not start`() async throws { - let peripheralID = UUID() - let wifiOnly = try makeHarness(live: .wifi, peripheralID: nil, wifiHost: "10.0.0.4", wifiPort: 4242) - defer { wifiOnly.appState.shutdown() } - await wifiOnly.appState.beginLinkSwitch(to: .bluetooth, snapshotWiFiHost: nil) - #expect(wifiOnly.appState.connectionLinkSwitch == nil) - #expect(wifiOnly.manager.testBluetoothConnectAttempts.isEmpty) - - let bluetoothOnly = try makeHarness(live: .bluetooth, peripheralID: peripheralID, wifiHost: nil) - defer { bluetoothOnly.appState.shutdown() } - await bluetoothOnly.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: nil) - await bluetoothOnly.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: " ") - #expect(bluetoothOnly.appState.connectionLinkSwitch == nil) - #expect(bluetoothOnly.manager.testWiFiConnectAttempts.isEmpty) - + try await ConnectionLinkSwitchHarness.withHarness( + live: .wifi, peripheralID: nil, wifiHost: "10.0.0.4", wifiPort: 4242 + ) { harness in + await harness.appState.beginLinkSwitch(to: .bluetooth, snapshotWiFiHost: nil) + #expect(harness.appState.connectionLinkSwitch == nil) + #expect(await harness.bluetooth.connectCount == 0) + } + try await ConnectionLinkSwitchHarness.withHarness { harness in + await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: nil) + await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: " ") + #expect(harness.appState.connectionLinkSwitch == nil) + #expect(await harness.wifi.connectCount == 0) + } let held = ConnectionLinkSwitch( - radioID: UUID(), - deviceID: UUID(), - checked: .wifi, - target: nil, - token: UUID(), - bluetoothPeripheralID: peripheralID, - wifi: ConnectionLinkWiFiDial(host: "", port: ConnectionMethod.defaultWiFiPort) + radioID: UUID(), deviceID: UUID(), checked: .wifi, target: nil, token: UUID(), + bluetoothPeripheralID: UUID(), wifi: ConnectionLinkWiFiDial(host: "", port: ConnectionMethod.defaultWiFiPort) ) let declined = ConnectionLinkSwitch.start( - existing: held, - target: .wifi, - liveTransport: nil, - radioID: nil, - deviceID: nil, + existing: held, target: .wifi, liveTransport: nil, radioID: nil, deviceID: nil, bluetoothPeripheralID: nil, - wifi: ConnectionLinkWiFiDial(host: "10.9.9.9", port: ConnectionMethod.defaultWiFiPort), - token: UUID() + wifi: ConnectionLinkWiFiDial(host: "10.9.9.9", port: ConnectionMethod.defaultWiFiPort), token: UUID() ) #expect(declined == nil) #expect(held.wifi?.displayHost == nil) @@ -121,545 +94,255 @@ struct ConnectionLinkSwitchTests { @Test func `success for the current attempt on the same radio clears the record`() async throws { - let harness = try makeHarness(live: .bluetooth, peripheralID: UUID(), wifiHost: nil) - defer { harness.appState.shutdown() } - harness.manager.testWiFiConnectHandler = { _, _ in - harness.manager.setTestState( - connectedDevice: .some(harness.device), - currentTransportType: .wifi - ) - } + try await ConnectionLinkSwitchHarness.withHarness { harness in + await harness.wifi.setConnectError(nil) - await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") + await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") - #expect(harness.appState.connectionLinkSwitch == nil) - await harness.appState.disconnect(reason: .userInitiated) - #expect(harness.appState.connectionLinkSwitch == nil) + #expect(harness.appState.connectionLinkSwitch == nil) + #expect(harness.manager.currentTransportType == .wifi) + #expect(harness.manager.connectionState == .ready) + #expect(harness.manager.connectedDevice?.radioID == harness.device.radioID) + #expect(harness.manager.services != nil) + await harness.appState.disconnect(reason: .userInitiated) + #expect(harness.appState.connectionLinkSwitch == nil) + } } @Test func `a throw keeps the check and keeps the record`() async throws { let peripheralID = UUID() - let harness = try makeHarness( - live: .wifi, - peripheralID: peripheralID, - wifiHost: "radio.local", - wifiPort: 4242 - ) - defer { harness.appState.shutdown() } - - await harness.appState.beginLinkSwitch(to: .bluetooth, snapshotWiFiHost: "10.9.9.9") - - let record = try #require(harness.appState.connectionLinkSwitch) - #expect(record.checked == .wifi) - #expect(record.target == nil) - #expect(record.wifi == ConnectionLinkWiFiDial(host: "radio.local", port: 4242)) - #expect(record.displayHost == "radio.local") - #expect(harness.manager.testBluetoothConnectAttempts == [peripheralID]) - #expect(harness.manager.testWiFiConnectAttempts.isEmpty) - #expect(harness.appState.connectionUI.showingConnectionFailedAlert) - - await harness.appState.disconnect(reason: .userInitiated) - #expect(harness.appState.connectionLinkSwitch == nil) - } + try await ConnectionLinkSwitchHarness.withHarness( + live: .wifi, peripheralID: peripheralID, wifiHost: "radio.local", wifiPort: 4242 + ) { harness in + await harness.appState.beginLinkSwitch(to: .bluetooth, snapshotWiFiHost: "10.9.9.9") - @Test - func `a retry dials the captured wifi host and non-default port`() async throws { - let harness = try makeHarness( - live: .wifi, - peripheralID: UUID(), - wifiHost: "radio.local", - wifiPort: 4242 - ) - defer { harness.appState.shutdown() } - harness.manager.testBluetoothConnectHandler = { _ in - harness.manager.setTestState( - connectedDevice: .some(nil), - currentTransportType: .some(nil) - ) - throw BLEError.connectionTimeout + let record = try #require(harness.appState.connectionLinkSwitch) + #expect(record.checked == .wifi) + #expect(record.target == nil) + #expect(record.wifi == ConnectionLinkWiFiDial(host: "radio.local", port: 4242)) + #expect(record.displayHost == "radio.local") + #expect(await harness.bluetooth.connectCount == 1) + #expect(await harness.wifi.connectCount == harness.initialWiFiAttempts) + #expect(harness.appState.connectionUI.showingConnectionFailedAlert) + #expect(harness.manager.currentTransportType == nil) } - - await harness.appState.beginLinkSwitch(to: .bluetooth, snapshotWiFiHost: "10.9.9.9") - await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.8.8.8") - - let attempt = try #require(harness.manager.testWiFiConnectAttempts.first) - #expect(harness.manager.testWiFiConnectAttempts.count == 1) - #expect(attempt.host == "radio.local") - #expect(attempt.port == 4242) } @Test - func `a stale completion writes nothing`() async throws { - let harness = try makeHarness(live: .bluetooth, peripheralID: UUID(), wifiHost: nil) - defer { harness.appState.shutdown() } - let gate = LinkSwitchGate() - harness.manager.testWiFiConnectHandler = { _, _ in - await gate.enter() - harness.manager.setTestState( - connectedDevice: .some(harness.device), - currentTransportType: .wifi - ) - } - - let task = Task { - await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") + func `a stale completion does not finish a newer token`() async throws { + try await ConnectionLinkSwitchHarness.withHarness { harness in + await harness.wifi.holdConnect() + let task = harness.startSwitch(to: .wifi) + try await waitUntil("WiFi physical connect held") { await harness.wifi.connectIsHeld } + var replaced = try #require(harness.appState.connectionLinkSwitch) + replaced.token = UUID() + harness.appState.connectionLinkSwitch = replaced + + await harness.wifi.releaseConnect() + await task.value + + #expect(harness.appState.connectionLinkSwitch == replaced) } - await gate.waitUntilEntered() - var replaced = try #require(harness.appState.connectionLinkSwitch) - replaced.token = UUID() - harness.appState.connectionLinkSwitch = replaced - - gate.release() - await task.value - - let record = try #require(harness.appState.connectionLinkSwitch) - #expect(record == replaced) } @Test func `a different radio drops the record`() async throws { - let harness = try makeHarness(live: .bluetooth, peripheralID: UUID(), wifiHost: nil) - defer { harness.appState.shutdown() } - harness.manager.testWiFiConnectHandler = { _, _ in - var other = harness.device - other.radioID = UUID() - harness.manager.setTestState( - connectedDevice: .some(other), - currentTransportType: .wifi - ) - throw BLEError.connectionTimeout - } + try await ConnectionLinkSwitchHarness.withHarness(foreignWiFiRadio: true) { harness in + await harness.wifi.setConnectError(nil) - await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") + await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") - #expect(harness.appState.connectionLinkSwitch == nil) + #expect(harness.appState.connectionLinkSwitch == nil) + #expect(harness.manager.currentTransportType == .wifi) + #expect(harness.manager.connectedDevice?.radioID != harness.device.radioID) + #expect(harness.manager.connectionState == .ready) + } } @Test func `disconnect before the completion leaves the record clear`() async throws { - let harness = try makeHarness(live: .bluetooth, peripheralID: UUID(), wifiHost: nil) - defer { harness.appState.shutdown() } - let gate = LinkSwitchGate() - harness.manager.testWiFiConnectHandler = { _, _ in - await gate.enter() - harness.manager.setTestState( - connectedDevice: .some(harness.device), - currentTransportType: .wifi - ) - } - - let task = Task { - await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") - } - await gate.waitUntilEntered() - let disconnect = Task { - await harness.appState.disconnect(reason: .userInitiated) + try await ConnectionLinkSwitchHarness.withHarness { harness in + await harness.wifi.setConnectError(nil) + await harness.wifi.holdConnect() + let task = harness.startSwitch(to: .wifi) + try await waitUntil("WiFi physical connect held") { await harness.wifi.connectIsHeld } + let disconnect = harness.startDisconnect() + try await waitUntil("disconnect clears switch presentation") { harness.appState.connectionLinkSwitch == nil } + + await harness.wifi.releaseConnect() + await task.value + await disconnect.value + + #expect(harness.appState.connectionLinkSwitch == nil) + #expect(harness.manager.connectionState == .disconnected) + #expect(harness.manager.currentTransportType == nil) + #expect(!harness.appState.connectionUI.showingConnectionFailedAlert) } - await Task.yield() - #expect(harness.appState.connectionLinkSwitch == nil) - - gate.release() - await task.value - await disconnect.value - #expect(harness.appState.connectionLinkSwitch == nil) } @Test func `a nil live transport can start the checked link`() async throws { let peripheralID = UUID() - let harness = try makeHarness(live: .bluetooth, peripheralID: peripheralID, wifiHost: nil) - defer { harness.appState.shutdown() } - harness.manager.testWiFiConnectHandler = { _, _ in - throw BLEError.connectionTimeout - } - await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") - #expect(harness.appState.connectionLinkSwitch?.checked == .bluetooth) - #expect(harness.appState.connectionLinkSwitch?.target == nil) - - harness.manager.setTestState( - connectedDevice: .some(nil), - currentTransportType: .some(nil) - ) - let gate = LinkSwitchGate() - harness.manager.testBluetoothConnectHandler = { _ in - await gate.enter() - throw BLEError.connectionTimeout - } - - let task = Task { - await harness.appState.beginLinkSwitch(to: .bluetooth, snapshotWiFiHost: "10.9.9.9") + try await ConnectionLinkSwitchHarness.withHarness(peripheralID: peripheralID) { harness in + await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") + #expect(harness.manager.currentTransportType == nil) + await harness.bluetooth.holdConnect() + let task = harness.startSwitch(to: .bluetooth, host: "10.9.9.9") + try await waitUntil("Bluetooth physical connect held") { await harness.bluetooth.connectIsHeld } + + let record = try #require(harness.appState.connectionLinkSwitch) + #expect(record.checked == .bluetooth) + #expect(record.target == .bluetooth) + #expect(record.wifi?.host == "10.0.0.8") + #expect(record.bluetoothPeripheralID == peripheralID) + #expect(await harness.bluetooth.connectCount == harness.initialBluetoothAttempts + 1) + await harness.bluetooth.releaseConnect() + await task.value + #expect(harness.appState.connectionLinkSwitch?.target == nil) } - await gate.waitUntilEntered() - - let record = try #require(harness.appState.connectionLinkSwitch) - #expect(record.checked == .bluetooth) - #expect(record.target == .bluetooth) - #expect(record.wifi?.host == "10.0.0.8") - #expect(harness.manager.testBluetoothConnectAttempts == [peripheralID]) - - gate.release() - await task.value - #expect(harness.appState.connectionLinkSwitch?.checked == .bluetooth) - #expect(harness.appState.connectionLinkSwitch?.target == nil) } @Test func `a finished record clears once the radio is connected`() async throws { - let harness = try makeHarness(live: .bluetooth, peripheralID: UUID(), wifiHost: nil) - defer { harness.appState.shutdown() } - harness.appState.connectionLinkSwitch = ConnectionLinkSwitch( - radioID: harness.device.radioID, - deviceID: harness.device.id, - checked: .bluetooth, - target: nil, - token: UUID(), - bluetoothPeripheralID: harness.device.bluetoothPeripheralID, - wifi: ConnectionLinkWiFiDial(host: "10.0.0.8", port: ConnectionMethod.defaultWiFiPort) - ) + try await ConnectionLinkSwitchHarness.withHarness { harness in + harness.appState.connectionLinkSwitch = ConnectionLinkSwitch( + radioID: harness.device.radioID, deviceID: harness.device.id, checked: .bluetooth, + target: nil, token: UUID(), bluetoothPeripheralID: harness.device.bluetoothPeripheralID, + wifi: ConnectionLinkWiFiDial(host: "10.0.0.8", port: ConnectionMethod.defaultWiFiPort) + ) - await harness.appState.wireServicesIfConnected() + harness.appState.reconcileConnectionLinkSwitch() - #expect(harness.appState.connectionLinkSwitch == nil) + #expect(harness.appState.connectionLinkSwitch == nil) + } } @Test func `an in-progress attempt keeps the record for the same radio`() async throws { - let harness = try makeHarness(live: .bluetooth, peripheralID: UUID(), wifiHost: nil) - defer { harness.appState.shutdown() } - let record = ConnectionLinkSwitch( - radioID: harness.device.radioID, - deviceID: harness.device.id, - checked: .bluetooth, - target: .wifi, - token: UUID(), - bluetoothPeripheralID: harness.device.bluetoothPeripheralID, - wifi: ConnectionLinkWiFiDial(host: "10.0.0.8", port: ConnectionMethod.defaultWiFiPort) - ) - harness.appState.connectionLinkSwitch = record - - await harness.appState.wireServicesIfConnected() - #expect(harness.appState.connectionLinkSwitch == record) - - var other = harness.device - other.radioID = UUID() - harness.manager.setTestState(connectedDevice: .some(other)) - await harness.appState.wireServicesIfConnected() - #expect(harness.appState.connectionLinkSwitch == nil) + try await ConnectionLinkSwitchHarness.withHarness(foreignWiFiRadio: true) { harness in + let record = ConnectionLinkSwitch( + radioID: harness.device.radioID, deviceID: harness.device.id, checked: .bluetooth, + target: .wifi, token: UUID(), bluetoothPeripheralID: harness.device.bluetoothPeripheralID, + wifi: ConnectionLinkWiFiDial(host: "10.0.0.8", port: ConnectionMethod.defaultWiFiPort) + ) + harness.appState.connectionLinkSwitch = record + harness.appState.reconcileConnectionLinkSwitch() + #expect(harness.appState.connectionLinkSwitch == record) + + await harness.wifi.setConnectError(nil) + _ = try await harness.manager.connectViaWiFi(host: "10.0.0.8", port: ConnectionMethod.defaultWiFiPort) + harness.appState.reconcileConnectionLinkSwitch() + #expect(harness.appState.connectionLinkSwitch == nil) + } } @Test func `a completed wifi session returns to its saved host and port`() async throws { - let harness = try makeHarness( - live: .wifi, - peripheralID: UUID(), - wifiHost: "radio.local", - wifiPort: 4242 - ) - defer { harness.appState.shutdown() } - harness.manager.testBluetoothConnectHandler = { _ in - harness.manager.setTestState( - connectedDevice: .some(harness.device), - currentTransportType: .bluetooth - ) - } - - await harness.appState.beginLinkSwitch(to: .bluetooth, snapshotWiFiHost: "10.9.9.9") - #expect(harness.appState.connectionLinkSwitch == nil) + try await ConnectionLinkSwitchHarness.withHarness( + live: .wifi, wifiHost: "radio.local", wifiPort: 4242 + ) { harness in + await harness.bluetooth.setConnectError(nil) + await harness.appState.beginLinkSwitch(to: .bluetooth, snapshotWiFiHost: "10.9.9.9") + #expect(harness.appState.connectionLinkSwitch == nil) + #expect(harness.manager.currentTransportType == .bluetooth) - await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.1.2.3") + await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.1.2.3") - let attempt = try #require(harness.manager.testWiFiConnectAttempts.first) - #expect(harness.manager.testWiFiConnectAttempts.count == 1) - #expect(attempt.host == "radio.local") - #expect(attempt.port == 4242) - #expect(harness.appState.connectionUI.showingConnectionFailedAlert) + #expect(await harness.wifi.connectCount == harness.initialWiFiAttempts + 1) + #expect(await harness.wifi.connectionInfo?.host == "radio.local") + #expect(await harness.wifi.connectionInfo?.port == 4242) + #expect(harness.appState.connectionUI.showingConnectionFailedAlert) + } } @Test func `a failed saved dial does not try the reported address`() async throws { - let harness = try makeHarness( - live: .bluetooth, - peripheralID: UUID(), - wifiHost: "radio.example", - wifiPort: 4242 - ) - defer { harness.appState.shutdown() } - - await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") + try await ConnectionLinkSwitchHarness.withHarness(wifiHost: "radio.example", wifiPort: 4242) { harness in + await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") - let attempt = try #require(harness.manager.testWiFiConnectAttempts.first) - #expect(harness.manager.testWiFiConnectAttempts.count == 1) - #expect(attempt.host == "radio.example") - #expect(attempt.port == 4242) - #expect(harness.manager.testBluetoothConnectAttempts.isEmpty) - #expect(harness.appState.connectionUI.showingConnectionFailedAlert) - #expect(harness.appState.connectionLinkSwitch?.wifi == ConnectionLinkWiFiDial(host: "radio.example", port: 4242)) + #expect(await harness.wifi.connectCount == 1) + #expect(await harness.wifi.connectionInfo?.host == "radio.example") + #expect(await harness.wifi.connectionInfo?.port == 4242) + #expect(await harness.bluetooth.connectCount == harness.initialBluetoothAttempts) + #expect(harness.appState.connectionUI.showingConnectionFailedAlert) + #expect(harness.appState.connectionLinkSwitch?.wifi == ConnectionLinkWiFiDial(host: "radio.example", port: 4242)) + } } @Test func `an unusable saved endpoint uses the reported address on the default port`() async throws { - let harness = try makeHarness(live: .bluetooth, peripheralID: UUID(), wifiHost: "bad host", wifiPort: 4242) - defer { harness.appState.shutdown() } - - await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") + try await ConnectionLinkSwitchHarness.withHarness(wifiHost: "bad host", wifiPort: 4242) { harness in + await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") - let attempt = try #require(harness.manager.testWiFiConnectAttempts.first) - #expect(harness.manager.testWiFiConnectAttempts.count == 1) - #expect(attempt.host == "10.0.0.8") - #expect(attempt.port == ConnectionMethod.defaultWiFiPort) + #expect(await harness.wifi.connectCount == 1) + #expect(await harness.wifi.connectionInfo?.host == "10.0.0.8") + #expect(await harness.wifi.connectionInfo?.port == ConnectionMethod.defaultWiFiPort) + } } @Test func `no usable wifi source does not dial`() async throws { - let harness = try makeHarness(live: .bluetooth, peripheralID: UUID(), wifiHost: "bad host", wifiPort: 4242) - defer { harness.appState.shutdown() } + try await ConnectionLinkSwitchHarness.withHarness(wifiHost: "bad host", wifiPort: 4242) { harness in + await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "999.1.1.1") - await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "999.1.1.1") - - #expect(harness.appState.connectionLinkSwitch == nil) - #expect(harness.manager.testWiFiConnectAttempts.isEmpty) - #expect(!harness.appState.connectionUI.showingConnectionFailedAlert) + #expect(harness.appState.connectionLinkSwitch == nil) + #expect(await harness.wifi.connectCount == 0) + #expect(!harness.appState.connectionUI.showingConnectionFailedAlert) + } } @Test(arguments: [TransportType.bluetooth, .wifi]) func `a failed switch can recover through either captured link`(_ source: TransportType) async throws { let peripheralID = UUID() - let capturedPort: UInt16 = 4242 - let harness = try makeHarness( - live: source, - peripheralID: peripheralID, - wifiHost: "radio.local", - wifiPort: capturedPort - ) - defer { harness.appState.shutdown() } - let target: TransportType = source == .bluetooth ? .wifi : .bluetooth - let clearLive = { - harness.manager.setTestState( - connectedDevice: .some(nil), - currentTransportType: .some(nil) - ) - } - harness.manager.testWiFiConnectHandler = { _, _ in - clearLive() - throw BLEError.connectionTimeout - } - harness.manager.testBluetoothConnectHandler = { _ in - clearLive() - throw BLEError.connectionTimeout - } - - await harness.appState.beginLinkSwitch(to: target, snapshotWiFiHost: "10.9.9.9") - - var replaced = harness.device - replaced.connectionMethods = [ - .bluetooth(peripheralUUID: UUID(), displayName: nil), - .wifi(host: "other.example", port: 9, displayName: nil) - ] - harness.manager.setTestState( - connectedDevice: .some(replaced), - currentTransportType: .some(nil) - ) - - try expectRecoveryRow(harness, link: source, peripheralID: peripheralID, port: capturedPort) - await harness.appState.beginLinkSwitch(to: source, snapshotWiFiHost: "10.8.8.8") - try expectRecoveryRow(harness, link: target, peripheralID: peripheralID, port: capturedPort) - await harness.appState.beginLinkSwitch(to: target, snapshotWiFiHost: "10.1.2.3") - - let record = try #require(harness.appState.connectionLinkSwitch) - #expect(record.checked == source) - #expect(record.bluetoothPeripheralID == peripheralID) - #expect(record.wifi == ConnectionLinkWiFiDial(host: "radio.local", port: capturedPort)) - if source == .bluetooth { - #expect(harness.manager.testBluetoothConnectAttempts == [peripheralID]) - #expect(harness.manager.testWiFiConnectAttempts.map(\.host) == ["radio.local", "radio.local"]) - #expect(harness.manager.testWiFiConnectAttempts.map(\.port) == [capturedPort, capturedPort]) - } else { - #expect(harness.manager.testBluetoothConnectAttempts == [peripheralID, peripheralID]) - #expect(harness.manager.testWiFiConnectAttempts.map(\.host) == ["radio.local"]) - #expect(harness.manager.testWiFiConnectAttempts.map(\.port) == [capturedPort]) + let port: UInt16 = 4242 + try await ConnectionLinkSwitchHarness.withHarness( + live: source, peripheralID: peripheralID, wifiHost: "radio.local", wifiPort: port + ) { harness in + let target: TransportType = source == .bluetooth ? .wifi : .bluetooth + await harness.appState.beginLinkSwitch(to: target, snapshotWiFiHost: "10.9.9.9") + var replaced = try #require(try await harness.manager.persistenceStore.fetchDevice(id: harness.device.id)) + replaced.connectionMethods = [ + .bluetooth(peripheralUUID: UUID(), displayName: nil), + .wifi(host: "other.example", port: 9, displayName: nil) + ] + try await harness.manager.persistenceStore.saveDevice(replaced) + + try harness.expectRecoveryRow(source, peripheralID: peripheralID, port: port) + await harness.appState.beginLinkSwitch(to: source, snapshotWiFiHost: "10.8.8.8") + try harness.expectRecoveryRow(target, peripheralID: peripheralID, port: port) + await harness.appState.beginLinkSwitch(to: target, snapshotWiFiHost: "10.1.2.3") + + let record = try #require(harness.appState.connectionLinkSwitch) + #expect(record.checked == source) + #expect(record.bluetoothPeripheralID == peripheralID) + #expect(record.wifi == ConnectionLinkWiFiDial(host: "radio.local", port: port)) + #expect(await harness.bluetooth.connectCount == harness.initialBluetoothAttempts + (source == .bluetooth ? 1 : 2)) + #expect(await harness.wifi.connectCount == harness.initialWiFiAttempts + (source == .bluetooth ? 2 : 1)) + #expect(await harness.wifi.connectionInfo?.host == "radio.local") + #expect(await harness.wifi.connectionInfo?.port == port) } } @Test func `a held attempt keeps its endpoint when saved data and the snapshot change`() async throws { - let harness = try makeHarness( - live: .bluetooth, - peripheralID: UUID(), - wifiHost: " radio.local ", - wifiPort: 4242 - ) - defer { harness.appState.shutdown() } - let gate = LinkSwitchGate() - harness.manager.testWiFiConnectHandler = { _, _ in - await gate.enter() - throw BLEError.connectionTimeout + try await ConnectionLinkSwitchHarness.withHarness(wifiHost: " radio.local ", wifiPort: 4242) { harness in + await harness.wifi.holdConnect() + let task = harness.startSwitch(to: .wifi) + try await waitUntil("WiFi physical connect held") { await harness.wifi.connectIsHeld } + var replaced = try #require(try await harness.manager.persistenceStore.fetchDevice(id: harness.device.id)) + replaced.connectionMethods = [.wifi(host: "other.example", port: 9, displayName: nil)] + try await harness.manager.persistenceStore.saveDevice(replaced) + await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.9.9.9") + + #expect(harness.appState.connectionLinkSwitch?.wifi == ConnectionLinkWiFiDial(host: "radio.local", port: 4242)) + #expect(await harness.wifi.connectCount == 1) + await harness.wifi.releaseConnect() + await task.value + await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.8.8.8") + #expect(await harness.wifi.connectCount == 2) + #expect(await harness.wifi.connectionInfo?.host == "radio.local") + #expect(await harness.wifi.connectionInfo?.port == 4242) } - - let task = Task { - await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.0.0.8") - } - await gate.waitUntilEntered() - - var replaced = harness.device - replaced.connectionMethods = [ - .wifi(host: "other.example", port: 9, displayName: nil) - ] - harness.manager.setTestState(connectedDevice: .some(replaced)) - await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.9.9.9") - - let running = try #require(harness.appState.connectionLinkSwitch) - #expect(running.wifi == ConnectionLinkWiFiDial(host: "radio.local", port: 4242)) - #expect(harness.manager.testWiFiConnectAttempts.count == 1) - - gate.release() - await task.value - - harness.manager.testWiFiConnectHandler = { _, _ in - throw BLEError.connectionTimeout - } - await harness.appState.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "10.8.8.8") - #expect(harness.manager.testWiFiConnectAttempts.count == 2) - #expect(harness.manager.testWiFiConnectAttempts.last?.host == "radio.local") - #expect(harness.manager.testWiFiConnectAttempts.last?.port == 4242) - } -} - -@MainActor -private final class LinkSwitchGate { - private var entered = false - private var enteredWaiter: CheckedContinuation? - private var releaseWaiter: CheckedContinuation? - - func enter() async { - entered = true - enteredWaiter?.resume() - enteredWaiter = nil - await withCheckedContinuation { (continuation: CheckedContinuation) in - releaseWaiter = continuation - } - } - - func waitUntilEntered() async { - if entered { return } - await withCheckedContinuation { (continuation: CheckedContinuation) in - if entered { - continuation.resume() - return - } - enteredWaiter = continuation - } - } - - func release() { - releaseWaiter?.resume() - releaseWaiter = nil - } -} - -@MainActor -private struct LinkSwitchHarness { - let appState: AppState - let device: DeviceDTO - - var manager: ConnectionManager { - appState.connectionManager } } - -@MainActor -private func expectRecoveryRow( - _ harness: LinkSwitchHarness, - link: TransportType, - peripheralID: UUID, - port: UInt16 -) throws { - let record = try #require(harness.appState.connectionLinkSwitch) - let device = harness.appState.connectedDevice - let snapshot = ConnectionLinkRows.make( - liveTransport: harness.manager.currentTransportType, - savedPeripheralID: device?.bluetoothPeripheralID, - wifiSupport: .supported, - wifiAssociated: true, - wifiDial: ConnectionLinkWiFiDial(host: "other.example", port: 9), - activeSwitch: record - ) - let row = try #require(snapshot.rows.first { $0.link == link }) - #expect(row.canSwitch) - #expect(snapshot.checked == record.checked) - #expect(snapshot.rows.first { $0.link == .wifi }?.address == "radio.local") - #expect(record.bluetoothPeripheralID == peripheralID) - #expect(record.wifi == ConnectionLinkWiFiDial(host: "radio.local", port: port)) -} - -@MainActor -private func makeHarness( - live: TransportType, - peripheralID: UUID?, - wifiHost: String?, - wifiPort: UInt16 = ConnectionMethod.defaultWiFiPort -) throws -> LinkSwitchHarness { - let suite = "test.linkswitch.\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: suite)) - defaults.removePersistentDomain(forName: suite) - let appState = try AppState( - modelContainer: PersistenceStore.createContainer(inMemory: true), - isPlaceholder: true, - defaults: defaults - ) - var methods: [ConnectionMethod] = [] - if let peripheralID { - methods.append(.bluetooth(peripheralUUID: peripheralID, displayName: nil)) - } - if let wifiHost { - methods.append(.wifi(host: wifiHost, port: wifiPort, displayName: nil)) - } - let device = makeLinkDevice(methods: methods) - appState.connectionManager.setTestState( - connectionState: .connected, - connectedDevice: .some(device), - currentTransportType: live - ) - appState.connectionManager.testWiFiConnectHandler = { _, _ in - throw BLEError.connectionTimeout - } - appState.connectionManager.testBluetoothConnectHandler = { _ in - throw BLEError.connectionTimeout - } - return LinkSwitchHarness(appState: appState, device: device) -} - -private func makeLinkDevice(methods: [ConnectionMethod]) -> DeviceDTO { - DeviceDTO( - id: UUID(), - publicKey: Data(repeating: 0xB1, count: ProtocolLimits.publicKeySize), - nodeName: "Relay", - firmwareVersion: 11, - firmwareVersionString: "1.15.0", - manufacturerName: "Test", - buildDate: "2025-01-01", - maxContacts: 100, - maxChannels: 8, - frequency: 915_000, - bandwidth: 250_000, - spreadingFactor: 10, - codingRate: 5, - txPower: 20, - maxTxPower: 20, - latitude: 0, - longitude: 0, - blePin: 0, - manualAddContacts: false, - multiAcks: 2, - telemetryModeBase: 2, - telemetryModeLoc: 0, - telemetryModeEnv: 0, - advertLocationPolicy: 0, - lastConnected: Date(), - lastContactSync: 0, - isActive: true, - ocvPreset: nil, - customOCVArrayString: nil, - connectionMethods: methods - ) -} diff --git a/MC1Tests/AppState/ConnectionRecoveryCallerBoundaryTests.swift b/MC1Tests/AppState/ConnectionRecoveryCallerBoundaryTests.swift new file mode 100644 index 0000000000..b26ad7f893 --- /dev/null +++ b/MC1Tests/AppState/ConnectionRecoveryCallerBoundaryTests.swift @@ -0,0 +1,306 @@ +import AccessorySetupKit +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Connection recovery caller boundaries") +@MainActor +struct ConnectionRecoveryCallerBoundaryTests { + @Test(arguments: [false, true]) + func `owned BLE rebuild settles actual pairing and settings switch`(pairing: Bool) async throws { + let env = try Harness(paired: !pairing) + if pairing { #expect(!env.app.onboarding.hasCompletedOnboarding) } + var switchWorker: Task? + do { + if !pairing { + _ = try await env.manager.connect(to: env.deviceID) + _ = try await env.manager.connectViaWiFi(host: "radio.local", port: 4242) + } + let previousTimeReads = await env.ble.timeReads + await env.ble.holdReplies(for: .getTime) + if pairing { + env.app.startDeviceScan() + } else { + switchWorker = Task { await env.app.beginLinkSwitch(to: .bluetooth, snapshotWiFiHost: "radio.local") } + } + try await waitUntil("the app caller must publish BLE and reach its real clock tail") { + await env.ble.timeReads == previousTimeReads + 1 + } + let first = try #require(env.manager.currentConnection) + if !pairing { #expect(env.app.connectionLinkSwitch?.target == .bluetooth) } + await env.ble.simulateAutoReconnecting(deviceID: env.deviceID) + try await waitUntil("post-publication physical loss must retire the Link") { env.manager.currentConnection == nil } + await env.ble.releaseReplies(for: .getTime) + try await waitUntil("the retired setup must release its barrier") { env.manager.connectionTeardownCount == 0 } + await env.ble.simulateReconnected() + try await waitUntil("OS recovery must rebuild the same request") { + env.manager.connectionState == .ready && env.manager.currentConnection?.generation != first.generation + } + await switchWorker?.value + #expect(env.manager.connectionRequestID == first.requestID) + if pairing { + try await waitUntil(timeout: .seconds(3), "fresh pairing must automatically advance after owned recovery") { + env.app.onboarding.onboardingPath.contains(.region) + } + #expect(!env.app.connectionUI.isBusy) + } else { + #expect(env.app.connectionLinkSwitch?.target == nil, "same-radio Settings switch must settle after owned recovery") + } + #expect(!env.app.connectionUI.showingConnectionFailedAlert) + #expect(try await env.manager.session?.getTime() != nil) + } catch { + await env.ble.releaseAllGates() + switchWorker?.cancel() + await switchWorker?.value + await env.close() + throw error + } + await env.close() + } + + @Test + func `genuinely superseded pairing does not advance onboarding`() async throws { + let env = try Harness() + var next: Task? + do { + await env.ble.holdReplies(for: .getTime) + env.app.startDeviceScan() + try await waitUntil("pairing must reach the published clock tail") { await env.ble.timeReads == 1 } + let first = try #require(env.manager.currentConnection) + next = Task { try await env.manager.connectViaWiFi(host: "replacement.local", port: 4242) } + try await waitUntil("replacement must supersede the pairing request") { env.manager.connectionRequestID != first.requestID } + await env.ble.releaseAllGates() + #expect(try await env.manager.isCurrent(#require(next).value)) + try await waitUntil("superseded pairing caller must settle") { !env.app.connectionUI.isBusy } + #expect(!env.app.onboarding.onboardingPath.contains(.region)) + #expect(!env.app.connectionUI.showingConnectionFailedAlert) + } catch { + await env.ble.releaseAllGates() + next?.cancel() + _ = await next?.result + await env.close() + throw error + } + await env.close() + } + + @Test(arguments: [false, true]) + func `stale recovery controls preserve a same or different radio successor`(sameRadio: Bool) async throws { + try await withHarness(foreignWiFiRadio: !sameRadio) { env in + _ = try await env.manager.connect(to: env.deviceID) + let first = try #require(env.manager.currentConnection) + await env.ble.simulateAutoReconnecting(deviceID: env.deviceID) + try await waitUntil("recovery must retire the old Link") { env.manager.currentConnection == nil } + let captured = try #require(env.manager.connectionActivity) + #expect(captured.requestID == first.requestID) + #expect(captured.phase == .reconnecting) + try await waitUntil("old cleanup must finish before physical recovery") { env.manager.connectionTeardownCount == 0 } + await env.ble.simulateReconnected() + try await waitUntil("the original request must recover before choosing another link") { + env.manager.connectionState == .ready && env.manager.currentConnection?.generation != first.generation + } + + await env.wifi.holdConnect() + env.startWiFiSwitch() + try await waitUntil("the successor switch must reach its physical connect") { await env.wifi.connectIsHeld } + let successorID = try #require(env.manager.connectionRequestID) + let record = try #require(env.app.connectionLinkSwitch) + let pendingPill = env.app.statusPillState + let disconnects = await env.wifi.disconnectCount + #expect(successorID != captured.requestID) + #expect(record.target == .wifi) + + await env.app.disconnect(requestID: captured.requestID) + + #expect(env.manager.connectionRequestID == successorID) + #expect(env.app.connectionLinkSwitch == record) + #expect(env.app.statusPillState == pendingPill) + #expect(env.app.connectionState == .connecting) + #expect(env.manager.connectionActivity?.requestID == successorID) + #expect(env.manager.connectionIntent.wantsConnection) + #expect(await env.wifi.disconnectCount == disconnects) + await env.wifi.releaseConnect() + await env.finishWorkers() + let successor = try #require(env.manager.currentConnection) + let session = try #require(env.manager.session) + #expect(successor.requestID == successorID) + #expect((successor.device.radioID == first.device.radioID) == sameRadio) + #expect(env.app.connectionState == .ready) + + await env.app.disconnect(requestID: captured.requestID) + + #expect(env.manager.currentConnection?.generation == successor.generation) + #expect(env.manager.connectionRequestID == successorID) + #expect(env.app.services === successor.services) + #expect(env.manager.session === session) + #expect(env.app.connectedDevice?.radioID == successor.device.radioID) + #expect(env.app.connectionState == .ready) + #expect(env.manager.connectionActivity?.phase == .ready) + #expect(!env.defaults.bool(forKey: PersistenceKeys.userExplicitlyDisconnected)) + #expect(await env.wifi.disconnectCount == disconnects) + let expectedTime = Date(timeIntervalSince1970: 1_800_000_000) + await env.wifi.setRadioTime(expectedTime) + #expect(try await session.getTime() == expectedTime) + } + } + + @Test + func `a captured recovery control stops its request after Ready and persists the choice`() async throws { + try await withHarness { env in + _ = try await env.manager.connect(to: env.deviceID) + let first = try #require(env.manager.currentConnection) + await env.ble.simulateAutoReconnecting(deviceID: env.deviceID) + try await waitUntil("recovery must retire the old Link") { env.manager.currentConnection == nil } + let captured = try #require(env.manager.connectionActivity) + #expect(captured.requestID == first.requestID) + #expect(captured.phase == .reconnecting) + #expect(captured.statusTitle == L10n.Settings.BleStatus.Status.reconnecting) + #expect(captured.stopTitle == L10n.Settings.BleStatus.stopReconnecting) + let name = try #require(captured.targetName) + #expect(captured.accessibilityValue == L10n.Settings.BleStatus.accessibilityValue(name, captured.statusTitle)) + #expect(env.app.statusPillState == .reconnecting) + try await waitUntil("old cleanup must finish before physical recovery") { env.manager.connectionTeardownCount == 0 } + await env.ble.simulateReconnected() + try await waitUntil("the captured request must recover before the user taps Stop") { + env.manager.connectionState == .ready && env.manager.currentConnection?.generation != first.generation + } + #expect(env.manager.connectionActivity?.requestID == captured.requestID) + #expect(env.manager.connectionActivity?.stopTitle == L10n.Settings.BleStatus.disconnect) + + await env.app.disconnect(requestID: captured.requestID) + + #expect(env.app.connectionState == .disconnected) + #expect(env.app.connectedDevice == nil) + #expect(env.app.services == nil) + #expect(env.manager.session == nil) + #expect(env.manager.connectionActivity == nil) + #expect(env.manager.connectionIntent == .userDisconnected) + #expect(env.defaults.bool(forKey: PersistenceKeys.userExplicitlyDisconnected)) + #expect(env.app.statusPillState == .hidden) + #expect(await env.ble.isConnected == false) + } + } + + @Test + func `dismissing device selection leaves active recovery and its Stop control intact`() async throws { + try await withHarness { env in + _ = try await env.manager.connect(to: env.deviceID) + await env.ble.simulateAutoReconnecting(deviceID: env.deviceID) + try await waitUntil("recovery must retire the old Link") { env.manager.currentConnection == nil } + let captured = try #require(env.manager.connectionActivity) + let connects = await env.ble.connectCount + let disconnects = await env.ble.disconnectCount + + env.app.handleDeviceSelectionSheetDismissed() + + #expect(env.manager.connectionActivity == captured) + #expect(env.manager.connectionIntent.wantsConnection) + #expect(env.app.statusPillState == .reconnecting) + #expect(env.app.connectionUI.queuedSavedDeviceConnection == nil) + #expect(!env.defaults.bool(forKey: PersistenceKeys.userExplicitlyDisconnected)) + #expect(await env.ble.connectCount == connects) + #expect(await env.ble.disconnectCount == disconnects) + } + } + + @Test + func `recovery status takes precedence over retired sync activity`() async throws { + try await withHarness { env in + _ = try await env.manager.connect(to: env.deviceID) + await env.app.wireServicesIfConnected() + let snapshot = try #require(env.manager.currentConnection) + let coordinator = snapshot.services.syncCoordinator + env.app.connectionUI.hideReadyToast() + await coordinator.beginResyncActivity() + #expect(env.app.connectionUI.syncActivityCount == 1) + #expect(env.app.statusPillState == .syncing) + + await env.ble.simulateAutoReconnecting(deviceID: env.deviceID) + try await waitUntil("physical loss must retire the syncing Link") { + env.manager.currentConnection == nil && env.manager.connectionTeardownCount == 0 + } + #expect(env.manager.connectionActivity?.requestID == snapshot.requestID) + #expect(env.manager.connectionActivity?.phase == .reconnecting) + #expect(env.app.statusPillState == .reconnecting) + await coordinator.endResyncActivity(succeeded: false) + + #expect(env.app.connectionUI.syncActivityCount == 1) + #expect(env.manager.connectionActivity?.phase == .reconnecting) + #expect(env.app.statusPillState == .reconnecting) + } + } + + private func withHarness( + foreignWiFiRadio: Bool = false, operation: (Harness) async throws -> Void + ) async throws { + let env = try Harness(paired: true, foreignWiFiRadio: foreignWiFiRadio) + do { + try await operation(env) + } catch { + await env.close() + throw error + } + await env.close() + } + + @MainActor + private final class Harness { + let app: AppState + let manager: ConnectionManager + let ble = ConnectionTestRadioTransport(publicKey: Data(repeating: 0xA1, count: ProtocolLimits.publicKeySize)) + let wifi: ConnectionTestRadioTransport + let defaults: UserDefaults + private var workers: [Task] = [] + let deviceID = UUID() + private let suite = "test.recovery-callers.\(UUID())" + + init(paired: Bool = false, foreignWiFiRadio: Bool = false) throws { + let defaults = try #require(UserDefaults(suiteName: suite)) + self.defaults = defaults + wifi = ConnectionTestRadioTransport( + publicKey: Data(repeating: foreignWiFiRadio ? 0xA2 : 0xA1, count: ProtocolLimits.publicKeySize) + ) + defaults.set(false, forKey: AppStorageKey.hasCompletedOnboarding.rawValue) + let container = try PersistenceStore.createContainer(inMemory: true) + let picker = MockAccessorySetupKitService() + let accessory = ASAccessory(bluetoothIdentifier: deviceID, displayName: "Radio") + if paired { picker.setPairedAccessories([accessory]) } + picker.beforePickerResult = { [weak picker] in picker?.setPairedAccessories([accessory]) } + picker.setPickerResult(.success(deviceID)) + picker.isSessionActive = false + let ble = ble + let wifi = wifi + manager = ConnectionManager( + modelContainer: container, defaults: defaults, stateMachine: MockBLEStateMachine(), transport: ble, + pairing: AccessorySetupPairingService(accessorySetupKit: picker), makeWiFiTransport: { wifi } + ) + manager.otherAppWaitStrategyOverride = { _ in false } + app = AppState(modelContainer: container, isPlaceholder: true, defaults: defaults, injectedConnectionManager: manager) + } + + func startWiFiSwitch() { + workers.append(Task { await app.beginLinkSwitch(to: .wifi, snapshotWiFiHost: "replacement.local") }) + } + + func finishWorkers() async { + for worker in workers { + await worker.value + } + workers.removeAll() + } + + func close() async { + await ble.releaseAllGates() + await wifi.releaseAllGates() + await finishWorkers() + _ = await app.disconnect(reason: .userInitiated) + try? await waitUntil("app pairing action should settle during cleanup") { !self.app.connectionUI.isBusy } + app.tearDownAppStateSessionState() + app.shutdown() + await manager.retirementTask?.value + UserDefaults().removePersistentDomain(forName: suite) + } + } +} diff --git a/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift b/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift index eef0e17410..08a24f9ba9 100644 --- a/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift +++ b/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift @@ -8,18 +8,26 @@ import Testing @MainActor struct ConnectionStatusLifecycleTests { private func makeAppState(clock: TestClock? = nil) throws -> AppState { - try AppState( + let appState = try AppState( modelContainer: PersistenceStore.createContainer(inMemory: true), isPlaceholder: true, injectedConnectionUI: ConnectionUIState(clock: clock) ) + appState.connectionManager.testForceNeverPaired = true + return appState } private func wireConnection(_ appState: AppState) async throws -> ServiceContainer { + let radioID = UUID() let services = try await ServiceContainer.forTesting( - session: MeshCoreSession(transport: MockTransport()) + session: MeshCoreSession(transport: MockTransport()), radioID: radioID + ) + let device = DeviceDTO(from: Device( + radioID: radioID, publicKey: Data(repeating: 1, count: ProtocolLimits.publicKeySize), nodeName: "Fixture" + )) + appState.connectionManager.setTestState( + connectionState: .connected, services: services, session: services.session, connectedDevice: device ) - appState.connectionManager.setTestState(connectionState: .connected, services: services) await appState.wireServicesIfConnected() return services } @@ -147,7 +155,7 @@ struct ConnectionStatusLifecycleTests { clock.advance(by: .milliseconds(500)) try await waitUntil("message label should reveal") { appState.connectionUI.showMessageSyncPill } #expect(appState.statusPillState == .syncingMessages) - appState.connectionManager.onResyncFailed?() + try appState.connectionManager.onResyncFailed?(#require(appState.connectionManager.currentConnection)) #expect(!appState.connectionUI.showMessageSyncPill) #expect(appState.statusPillState == .failed(message: L10n.Localizable.StatusPill.syncFailed)) appState.connectionUI.hideSyncFailedPill() @@ -205,8 +213,7 @@ struct ConnectionStatusLifecycleTests { await services.syncCoordinator.beginResyncActivity() services.syncCoordinator.setState(.syncing(progress: SyncProgress(phase: .messages, current: 0, total: 0))) try await waitUntil("message label timer should park") { clock.sleeperCount == 1 } - appState.connectionManager.setTestState(connectionState: .disconnected, services: .some(nil)) - await appState.wireServicesIfConnected() + await appState.disconnect() await services.syncCoordinator.endResyncActivity(succeeded: true) await services.syncCoordinator.beginResyncActivity() services.syncCoordinator.setState(.syncing(progress: SyncProgress(phase: .messages, current: 0, total: 0))) @@ -263,9 +270,9 @@ struct ConnectionStatusLifecycleTests { func startAutoFetch(radioID: UUID) async {} func pauseAutoFetch() async {} func resumeAutoFetch() async {} - func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext) async -> Void) {} - func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext) async -> Void) {} - func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) {} + func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void) {} + func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void) {} + func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ReceiveScope) async -> Void) {} func setCLIMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) {} } } diff --git a/MC1Tests/AppState/ConversationUnreadMutationTests+Fixture.swift b/MC1Tests/AppState/ConversationUnreadMutationTests+Fixture.swift index eb9f45e4b2..ede1fef0c7 100644 --- a/MC1Tests/AppState/ConversationUnreadMutationTests+Fixture.swift +++ b/MC1Tests/AppState/ConversationUnreadMutationTests+Fixture.swift @@ -105,8 +105,9 @@ extension ConversationUnreadMutationTests { currentRadioID: { self.currentRadioID } )) appState.connectionManager.persistConnection(deviceID: UUID(), radioID: radioID, deviceName: "Radio") - appState.connectionManager.setTestState(services: services) - appState.wireSyncDataEvents(services: services) + let device = DeviceDTO(from: Device(radioID: radioID, publicKey: Data(repeating: 0xA1, count: 32), nodeName: "Radio")) + appState.connectionManager.setTestState(connectionState: .ready, services: services, session: services.session, connectedDevice: device) + try appState.wireSyncDataEvents(snapshot: #require(appState.connectionManager.currentConnection)) await appState.refreshConversations().value await viewModel.requestConversationReload()?.value try #require(await recorder.publications == [total()]) @@ -121,8 +122,10 @@ extension ConversationUnreadMutationTests { session: MeshCoreSession(transport: MockTransport()), dataStore: store, radioID: radioID ) containers.append(services) - appState.connectionManager.setTestState(services: services) - appState.wireSyncDataEvents(services: services) + guard let device = appState.connectedDevice else { return } + appState.connectionManager.setTestState(connectionState: .ready, services: services, session: services.session, connectedDevice: device) + guard let snapshot = appState.connectionManager.currentConnection else { return } + appState.wireSyncDataEvents(snapshot: snapshot) } func finishEvents() async { diff --git a/MC1Tests/AppState/MacOSPairingRecoveryTests.swift b/MC1Tests/AppState/MacOSPairingRecoveryTests.swift index d217b43074..c52aaa8ccf 100644 --- a/MC1Tests/AppState/MacOSPairingRecoveryTests.swift +++ b/MC1Tests/AppState/MacOSPairingRecoveryTests.swift @@ -6,63 +6,84 @@ import Foundation @testable import MC1Services import Testing -/// Without a pairing registry, Remove and Try Again must present the scanner -/// immediately; with a registry it still waits for `.active`. +/// Remove and Try Again continues into the platform picker after confirmed removal. @Suite("macOS pairing recovery") @MainActor struct MacOSPairingRecoveryTests { @Test func `remove and retry on macOS starts the scanner without waiting for foreground`() async throws { let pairing = BluetoothScanPairingService() - let harness = try makeHarness(pairing: pairing) - defer { harness.cleanup() } - harness.appState.connectionUI.failedPairingDeviceID = UUID() + let harness = try await makeHarness(pairing: pairing, deviceID: UUID()) + do { + let removal = try #require(harness.appState.removeFailedPairingAndRetry()) + try await waitUntil(timeout: .seconds(2), "macOS scanner should present") { + pairing.isPresenting + } - harness.appState.removeFailedPairingAndRetry() - try await waitUntil(timeout: .seconds(2), "macOS scanner should present") { - pairing.isPresenting - } - - #expect(harness.appState.connectionUI.shouldShowPickerOnForeground == false) - #expect(harness.appState.connectionUI.failedPairingDeviceID == nil) - pairing.cancel() - try await waitUntil(timeout: .seconds(2), "pairing task should finish after cancel") { - !harness.appState.connectionUI.isBusy + #expect(harness.appState.isRecoveringPairing) + #expect(harness.appState.connectionUI.failedPairingDeviceID == nil) + pairing.cancel() + await removal.value + try await waitUntil(timeout: .seconds(2), "pairing task should finish after cancel") { + !harness.appState.connectionUI.isBusy + } + } catch { + pairing.cancel() + await harness.cleanup() + throw error } + await harness.cleanup() } @Test - func `remove and retry on iOS still waits for foreground`() async throws { + func `remove and retry on iOS opens the picker without another foreground event`() async throws { let mockASK = MockAccessorySetupKitService() - let harness = try makeHarness(pairing: AccessorySetupPairingService(accessorySetupKit: mockASK)) - defer { harness.cleanup() } - harness.appState.connectionUI.failedPairingDeviceID = UUID() + let deviceID = UUID() + mockASK.setPickerResult(.failure(AccessorySetupKitError.pickerDismissed)) + mockASK.setPairedAccessories([ASAccessory(bluetoothIdentifier: deviceID, displayName: "Radio")]) + let harness = try await makeHarness( + pairing: AccessorySetupPairingService(accessorySetupKit: mockASK), deviceID: deviceID + ) - harness.appState.removeFailedPairingAndRetry() - try await waitUntil(timeout: .seconds(2), "iOS remove should finish") { - harness.appState.connectionUI.failedPairingDeviceID == nil - && !harness.appState.connectionUI.isBusy + do { + let removal = try #require(harness.appState.removeFailedPairingAndRetry()) + await removal.value + #expect(harness.appState.connectionUI.failedPairingDeviceID == nil) + #expect(!harness.appState.connectionUI.isBusy) + #expect(!harness.appState.isRecoveringPairing) + #expect(mockASK.showPickerCallCount == 1) + } catch { + await harness.cleanup() + throw error } - - #expect(harness.appState.connectionUI.shouldShowPickerOnForeground == true) - #expect(mockASK.showPickerCallCount == 0) + await harness.cleanup() } } @MainActor private struct MacOSPairingRecoveryHarness { let appState: AppState - let cleanup: () -> Void + let suite: String + + func cleanup() async { + await appState.disconnect(reason: .userInitiated) + appState.shutdown() + UserDefaults().removePersistentDomain(forName: suite) + } } @MainActor -private func makeHarness(pairing: any DevicePairingService) throws -> MacOSPairingRecoveryHarness { +private func makeHarness(pairing: any DevicePairingService, deviceID: UUID) async throws -> MacOSPairingRecoveryHarness { let container = try PersistenceStore.createContainer(inMemory: true) let suite = "test.\(UUID().uuidString)" let defaults = UserDefaults(suiteName: suite)! + let transport = MockMeshTransport() + await transport.setConnectError(BLEError.authenticationFailed) let manager = ConnectionManager( modelContainer: container, defaults: defaults, + stateMachine: MockBLEStateMachine(), + transport: transport, pairing: pairing ) let appState = AppState( @@ -71,8 +92,22 @@ private func makeHarness(pairing: any DevicePairingService) throws -> MacOSPairi defaults: defaults, injectedConnectionManager: manager ) - return MacOSPairingRecoveryHarness( - appState: appState, - cleanup: { UserDefaults().removePersistentDomain(forName: suite) } - ) + let harness = MacOSPairingRecoveryHarness(appState: appState, suite: suite) + do { + do { + _ = try await appState.connectViaBluetooth(peripheralID: deviceID) + Issue.record("Physical authentication failure must establish the failed request") + } catch let failure as ConnectionRequestFailure { + #expect(manager.isCurrent(failure)) + guard case BLEError.authenticationFailed = failure.underlying else { throw failure } + appState.connectionUI.presentPairingFailure( + .connectionFailed(deviceID: deviceID, underlying: failure.underlying) + ) + } + #expect(await transport.connectInvocations.count == 1) + return harness + } catch { + await harness.cleanup() + throw error + } } diff --git a/MC1Tests/AppState/NodesContactInvalidationTests.swift b/MC1Tests/AppState/NodesContactInvalidationTests.swift index cf2dff6fde..822b031e3d 100644 --- a/MC1Tests/AppState/NodesContactInvalidationTests.swift +++ b/MC1Tests/AppState/NodesContactInvalidationTests.swift @@ -50,7 +50,7 @@ struct NodesContactInvalidationTests { break } let revision = navigation.nodesPresentationRevision - await fixture.appState.wireDeviceUpdateCallbacks(services: fixture.services) + try await fixture.appState.wireDeviceUpdateCallbacks(snapshot: #require(fixture.appState.connectionManager.currentConnection)) let listener = try #require(fixture.appState.advertisementEventsTask) fixture.services.advertisementService.eventBroadcaster.yield( .contactDeletedCleanup(contactIDs: selection == .emptyBatch ? [] : [contact.id]) @@ -85,7 +85,7 @@ struct NodesContactInvalidationTests { let oldBinding = try openHistory(contact, appState: fixture.appState, routes: routes) let oldPath = oldBinding.wrappedValue fixture.appState.navigation.selectedTab = AppTab.map.rawValue - fixture.appState.wireSyncDataEvents(services: fixture.services) + try fixture.appState.wireSyncDataEvents(snapshot: #require(fixture.appState.connectionManager.currentConnection)) let listener = try #require(fixture.appState.syncDataEventsTask) try await store.deleteContact(id: contact.id) @@ -111,7 +111,7 @@ struct NodesContactInvalidationTests { let contact = makeContact(radioID: fixture.radioID) try await fixture.appState.connectionManager.persistenceStore.saveContact(contact) fixture.appState.navigation.navigateToContactDetail(contact) - fixture.appState.wireSyncDataEvents(services: fixture.services) + try fixture.appState.wireSyncDataEvents(snapshot: #require(fixture.appState.connectionManager.currentConnection)) let listener = try #require(fixture.appState.syncDataEventsTask) if disconnected { fixture.appState.connectionManager.setTestState( @@ -130,7 +130,7 @@ struct NodesContactInvalidationTests { defer { fixture.stop() } let contact = makeContact(radioID: fixture.radioID) fixture.appState.navigation.navigateToContactDetail(contact) - fixture.appState.wireSyncDataEvents(services: fixture.services, nodesContactExists: { _ in + try fixture.appState.wireSyncDataEvents(snapshot: #require(fixture.appState.connectionManager.currentConnection), nodesContactExists: { _ in throw LookupError.unavailable }) let listener = try #require(fixture.appState.syncDataEventsTask) @@ -154,7 +154,7 @@ struct NodesContactInvalidationTests { let entered = Gate() let resume = Gate() let store = appState.connectionManager.persistenceStore - appState.wireSyncDataEvents(services: fixture.services, nodesContactExists: { id in + try appState.wireSyncDataEvents(snapshot: #require(fixture.appState.connectionManager.currentConnection), nodesContactExists: { id in let exists = try await store.fetchContact(id: id) != nil await entered.open() await resume.wait() @@ -228,7 +228,7 @@ struct NodesContactInvalidationTests { session: MeshCoreSession(transport: MockTransport()), dataStore: appState.connectionManager.persistenceStore, radioID: radioID ) - appState.connectionManager.setTestState(connectionState: .ready, services: services, connectedDevice: device) + appState.connectionManager.setTestState(connectionState: .ready, services: services, session: services.session, connectedDevice: device) return Fixture(appState: appState, services: services, radioID: radioID, defaults: defaults, suite: suite) } diff --git a/MC1Tests/AppState/PairingRecoveryOwnershipTests.swift b/MC1Tests/AppState/PairingRecoveryOwnershipTests.swift new file mode 100644 index 0000000000..9a7a31daf0 --- /dev/null +++ b/MC1Tests/AppState/PairingRecoveryOwnershipTests.swift @@ -0,0 +1,338 @@ +import AccessorySetupKit +import Foundation +@testable import MC1 +@testable import MC1Services +import SwiftUI +import Testing +import UIKit + +@Suite("Pairing recovery ownership", .serialized, .timeLimit(.minutes(1))) +@MainActor +struct PairingRecoveryOwnershipTests { + @Test(arguments: [false, true]) + func `confirmed removal opens the picker without another foreground event`(hasWiFi: Bool) async throws { + try await withHarness(hasWiFi: hasWiFi) { env in + let operation = try #require(env.app.removeFailedPairingAndRetry()) + await operation.value + + #expect(env.picker.showPickerCallCount == 1) + #expect(!env.app.connectionUI.isBusy) + #expect(!env.manager.isPairingFlowActive) + #expect(!env.app.connectionUI.showingConnectionFailedAlert) + let saved = try #require(await env.manager.persistenceStore.fetchDevice(publicKey: env.device.publicKey)) + #expect(saved.radioID == env.device.radioID) + #expect(saved.connectionMethods == env.device.connectionMethods.filter(\.isWiFi)) + } + } + + @Test + func `a system removal error preserves the failure episode and shows the error`() async throws { + try await withHarness { env in + let episode = env.app.connectionUI.pairingFailureEpisodeID + let previous = try #require(env.manager.currentConnection) + env.picker.removeAccessoryError = NSError(domain: "RemovalFailure", code: 1) + let operation = try #require(env.app.removeFailedPairingAndRetry()) + await operation.value + + #expect(env.app.connectionUI.showingConnectionFailedAlert) + #expect(env.app.connectionUI.failedPairingDeviceID == env.device.id) + #expect(env.app.connectionUI.pairingFailureEpisodeID == episode) + #expect(env.picker.showPickerCallCount == 0) + #expect(env.manager.isCurrent(previous)) + #expect(!env.app.isRecoveringPairing) + #expect(!env.manager.isPairingFlowActive) + } + } + + @Test + func `re-pairing presentation outlives busy work and clears for a live successor`() async throws { + try await withHarness { env in + env.picker.setPickerResult(.failure(AccessorySetupKitError.pickerRestricted)) + let operation = try #require(env.app.removeFailedPairingAndRetry()) + await operation.value + #expect(env.app.shouldCompleteFreshPairingOnForeground) + #expect(!env.app.connectionUI.isBusy) + #expect(env.app.isRecoveringPairing) + #expect(env.manager.isPairingFlowActive) + env.app.startDeviceScan() + #expect(env.app.isRecoveringPairing) + #expect(env.picker.showPickerCallCount == 1) + + let result = try await env.manager.connectViaWiFi(host: "successor.local", port: 4242) + #expect(env.manager.isCurrent(result)) + env.app.handleBecameActive() + #expect(!env.app.isRecoveringPairing) + #expect(!env.manager.isPairingFlowActive) + #expect(!env.app.connectionUI.isBusy) + #expect(!env.app.shouldCompleteFreshPairingOnForeground) + #expect(env.picker.showPickerCallCount == 1) + #expect(env.manager.isCurrent(result)) + } + } + + @Test + func `scan during removal keeps the failure episode and admits one picker`() async throws { + try await withHarness { env in + let gate = AsyncStream.makeStream() + defer { gate.continuation.finish() } + env.picker.beforeRemovalResult = { + for await _ in gate.stream { + break + } + } + let episode = env.app.connectionUI.pairingFailureEpisodeID + let operation = try #require(env.app.removeFailedPairingAndRetry()) + try await waitUntil("system removal must own its confirmation") { env.picker.removeAccessoryCallCount == 1 } + + env.app.startDeviceScan() + #expect(env.app.connectionUI.failedPairingDeviceID == env.device.id) + #expect(env.app.connectionUI.pairingFailureEpisodeID == episode) + #expect(env.picker.showPickerCallCount == 0) + gate.continuation.finish() + await operation.value + #expect(env.picker.showPickerCallCount == 1) + #expect(!env.app.connectionUI.isBusy) + #expect(!env.manager.isPairingFlowActive) + } + } + + @Test + func `a real successor discards a pending foreground picker retry`() async throws { + try await withHarness(connected: false) { env in + env.picker.setPickerResult(.failure(AccessorySetupKitError.pickerRestricted)) + env.app.startDeviceScan() + try await waitUntil("picker rejection must arm its scoped retry") { + env.app.shouldCompleteFreshPairingOnForeground && !env.app.connectionUI.isBusy + } + let result = try await env.manager.connectViaWiFi(host: "successor.local", port: 4242) + guard case let .operational(successor) = result else { + Issue.record("the replacement must install a real operational connection") + return + } + env.app.handleBecameActive() + try await waitUntil("the obsolete foreground flow must settle") { + !env.app.shouldCompleteFreshPairingOnForeground && !env.app.connectionUI.isBusy + } + + #expect(env.picker.showPickerCallCount == 1) + #expect(env.manager.isCurrent(successor)) + #expect(!env.manager.isPairingFlowActive) + #expect(!env.app.connectionUI.showingConnectionFailedAlert) + #expect(try await env.manager.session?.getTime() != nil) + } + } + + @Test + func `a replacement scan joins the previous picker before presenting another`() async throws { + try await withHarness(connected: false) { env in + let gate = AsyncStream.makeStream() + defer { gate.continuation.finish() } + env.picker.beforePickerResultAsync = { + if env.picker.showPickerCallCount == 1 { + for await _ in gate.stream { + break + } + } + } + env.app.startDeviceScan() + try await waitUntil("the first scan must enter the actual picker") { env.picker.showPickerCallCount == 1 } + env.app.startDeviceScan() + gate.continuation.finish() + try await waitUntil("the new scan must present after the first unwinds") { + env.picker.showPickerCallCount == 2 && !env.app.connectionUI.isBusy + } + #expect(!env.manager.isPairingFlowActive) + #expect(!env.app.connectionUI.showingConnectionFailedAlert) + } + } + + @Test + func `cancelling an explicit switch keeps the previous operational connection`() async throws { + try await withHarness { env in + let previous = try #require(env.manager.currentConnection) + env.app.startDeviceScan() + try await waitUntil("the cancelled picker must settle") { + env.picker.showPickerCallCount == 1 && !env.app.connectionUI.isBusy + } + #expect(env.manager.isCurrent(previous)) + #expect(env.manager.connectedDevice?.radioID == env.device.radioID) + #expect(!env.manager.isPairingFlowActive) + #expect(!env.app.connectionUI.showingConnectionFailedAlert) + #expect(try await env.manager.session?.getTime() != nil) + } + } + + @Test + func `an obsolete delayed retry releases its claim without clearing newer busy state`() async throws { + try await withHarness(connected: false) { env in + env.picker.setPickerResult(.failure(AccessorySetupKitError.pickerRestricted)) + env.app.startDeviceScan() + try await waitUntil("the first picker must leave a pending retry") { + env.app.shouldCompleteFreshPairingOnForeground && !env.app.connectionUI.isBusy + } + let next = env.app.connectionUI.beginConnectionAction() + defer { env.app.connectionUI.finishConnectionAction(next) } + try await waitUntil("the delayed retry must release the obsolete pairing claim") { + !env.manager.isPairingFlowActive + } + #expect(env.app.connectionUI.isCurrentConnectionAction(next)) + #expect(env.app.connectionUI.isBusy) + #expect(!env.app.shouldCompleteFreshPairingOnForeground) + #expect(env.picker.showPickerCallCount == 1) + } + } + + @Test(arguments: PresentationSurface.allCases) + func `recovery replaces the scan control on each real presentation`(surface: PresentationSurface) async throws { + try await withHarness(hasWiFi: surface == .savedSelection) { env in + let gate = AsyncStream.makeStream() + defer { gate.continuation.finish() } + env.picker.setPickerResult(.failure(AccessorySetupKitError.pickerRestricted)) + env.picker.beforePickerResultAsync = { + if env.picker.showPickerCallCount > 1 { + for await _ in gate.stream { + break + } + } + } + let operation = try #require(env.app.removeFailedPairingAndRetry()) + await operation.value + #expect(env.app.isRecoveringPairing) + let host = try SettingsTabHarness.make(connected: false, injectedAppState: env.app) + defer { host.tearDown() } + let content: AnyView = surface == .onboarding ? AnyView(DeviceScanView()) : AnyView(DeviceSelectionSheet()) + host.window.rootViewController = UIHostingController(rootView: content.environment(\.appState, env.app)) + host.window.makeKeyAndVisible() + host.window.layoutIfNeeded() + let status = L10n.Settings.DeviceSelection.rePairing + let showedRecovery = try await host.waitUntil { + let labels = host.labels(in: host.window) + guard labels.contains(status) else { return false } + switch surface { + case .onboarding: return true + case .emptySelection: return labels.contains { $0.contains(L10n.Settings.DeviceSelection.noPairedDevices) } + case .savedSelection: return labels.contains { $0.contains(env.device.nodeName) } + } + } + try #require(showedRecovery, "The rendered recovery control must carry its localized label") + let labels = host.labels(in: host.window) + #expect(!labels.contains(L10n.Onboarding.DeviceScan.addDevice)) + #expect(!labels.contains(L10n.Settings.DeviceSelection.scanForDevices)) + #expect(!labels.contains(L10n.Settings.DeviceSelection.scanBluetooth)) + + env.app.cancelFreshPairingOperation() + gate.continuation.finish() + let clearedRecovery = try await host.waitUntil { !host.labels(in: host.window).contains(status) } + #expect(clearedRecovery) + #expect(!env.manager.isPairingFlowActive) + #expect(!env.app.connectionUI.isBusy) + } + } + + @Test + func `cancelling an admitted pairing lets the next scan start`() async throws { + try await withHarness(connected: false) { env in + let deviceID = UUID() + env.picker.setPickerResult(.success(deviceID)) + await env.ble.holdConnect() + env.app.startDeviceScan() + try await waitUntil("pairing must reach the held connect") { + env.manager.isPairingInProgress && env.manager.connectionState == .connecting + && env.manager.admittedPairingRequestID != nil + } + try await waitUntil("the transport connect must be held") { await env.ble.connectIsHeld } + + env.app.cancelDeviceScanAttempt() + try await waitUntil("cancel must disconnect the admitted pairing") { + env.manager.connectionIntent == .userDisconnected + } + await env.ble.releaseConnect() + try await waitUntil("the cancelled pairing must leave the in-progress latch") { + !env.manager.isPairingInProgress && !env.app.connectionUI.isBusy + && env.manager.connectionState == .disconnected + && !env.app.connectionUI.showingConnectionFailedAlert + } + + env.picker.setPickerResult(.failure(AccessorySetupKitError.pickerDismissed)) + env.app.startDeviceScan() + try await waitUntil("the next scan must present instead of reporting pairing in progress") { + env.picker.showPickerCallCount == 2 && !env.app.connectionUI.isBusy + && !env.manager.isPairingInProgress && !env.app.connectionUI.showingConnectionFailedAlert + } + } + } + + enum PresentationSurface: CaseIterable, Sendable { + case onboarding + case emptySelection + case savedSelection + } + + private func withHarness( + connected: Bool = true, + hasWiFi: Bool = false, + _ body: @MainActor (Harness) async throws -> Void + ) async throws { + let env = try await Harness(connected: connected, hasWiFi: hasWiFi) + do { + try await body(env) + } catch { + await env.close() + throw error + } + await env.close() + } + + @MainActor + private final class Harness { + let app: AppState + let manager: ConnectionManager + let picker = MockAccessorySetupKitService() + let ble = ConnectionTestRadioTransport(publicKey: Data(repeating: 0xA1, count: ProtocolLimits.publicKeySize)) + let wifi = ConnectionTestRadioTransport(publicKey: Data(repeating: 0xB2, count: ProtocolLimits.publicKeySize)) + let device: DeviceDTO + private let suite = "test.pairing-recovery.\(UUID())" + + init(connected: Bool, hasWiFi: Bool) async throws { + let defaults = try #require(UserDefaults(suiteName: suite)) + defaults.set(false, forKey: AppStorageKey.hasCompletedOnboarding.rawValue) + let container = try PersistenceStore.createContainer(inMemory: true) + let deviceID = UUID() + var methods: [ConnectionMethod] = [.bluetooth(peripheralUUID: deviceID, displayName: "Radio")] + if hasWiFi { methods.append(.wifi(host: "radio.local", port: 4242, displayName: nil)) } + device = DeviceDTO(from: Device( + id: deviceID, radioID: UUID(), publicKey: ble.publicKey, nodeName: "Radio", connectionMethods: methods + )) + if connected { + picker.setPairedAccessories([ASAccessory(bluetoothIdentifier: deviceID, displayName: "Radio")]) + } + picker.isSessionActive = false + picker.setPickerResult(.failure(AccessorySetupKitError.pickerDismissed)) + let wifi = wifi + manager = ConnectionManager( + modelContainer: container, defaults: defaults, stateMachine: MockBLEStateMachine(), transport: ble, + pairing: AccessorySetupPairingService(accessorySetupKit: picker), makeWiFiTransport: { wifi } + ) + manager.otherAppWaitStrategyOverride = { _ in false } + app = AppState(modelContainer: container, isPlaceholder: true, defaults: defaults, injectedConnectionManager: manager) + if connected { + try await manager.persistenceStore.saveDevice(device) + let result = try await manager.connect(to: deviceID) + #expect(manager.isCurrent(result)) + app.connectionUI.failedPairingDeviceID = deviceID + } + } + + func close() async { + picker.beforePickerResultAsync = nil + picker.beforeRemovalResult = nil + await ble.releaseAllGates() + await wifi.releaseAllGates() + _ = await app.disconnect(reason: .userInitiated) + app.tearDownAppStateSessionState() + app.shutdown() + await manager.retirementTask?.value + UserDefaults().removePersistentDomain(forName: suite) + } + } +} diff --git a/MC1Tests/AppState/RadioEraseDiskTests.swift b/MC1Tests/AppState/RadioEraseDiskTests.swift new file mode 100644 index 0000000000..0bf4c8d860 --- /dev/null +++ b/MC1Tests/AppState/RadioEraseDiskTests.swift @@ -0,0 +1,82 @@ +import Foundation +@testable import MC1Services +import SwiftData +import Testing + +@MainActor +struct RadioEraseDiskTests { + private enum InjectedFailure: Error { + case save + } + + @Test + func `pending target survives partial cleanup and reopens without A device row`() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("cleanup.store") + let radio = DeviceDTO(from: Device(publicKey: Data(repeating: 1, count: 32), nodeName: "Target")) + let other = DeviceDTO(from: Device(publicKey: Data(repeating: 2, count: 32), nodeName: "Other")) + let lifetime = ReceiveScope.Lifetime() + let scope: ReceiveScope + + do { + let store = try openStore(url) + try await store.saveDevice(radio) + try await store.saveDevice(other) + try await store.recordRecentlyBlockedMessage(makeDrop(radio)) + try await store.recordRecentlyBlockedMessage(makeDrop(other)) + scope = try #require(await store.captureReceiveScope(radioID: radio.radioID, link: lifetime)) + + await store.setRadioEraseFaults(begin: { throw InjectedFailure.save }, complete: nil) + await #expect(throws: InjectedFailure.save) { + _ = try await store.beginRadioErase(radio) + } + #expect(scope.isCurrent) + #expect(try await store.fetchPendingRadioErases().isEmpty) + #expect(try await store.fetchDevice(id: radio.id) != nil) + #expect(try await store.recentlyBlockedCount() == 2) + + await store.setRadioEraseFaults(begin: nil, complete: { throw InjectedFailure.save }) + _ = try await store.beginRadioErase(radio, isFactoryReset: true) + #expect(!scope.isCurrent) + #expect(try await store.captureReceiveScope(radioID: radio.radioID, link: lifetime) == nil) + await #expect(throws: InjectedFailure.save) { + try await store.completeRadioErase(radioID: radio.radioID) + } + try await store.deleteDevice(id: radio.id) + } + + let reopened = try openStore(url) + let target = try #require(await reopened.fetchPendingRadioErases().first) + #expect(target.radioID == radio.radioID) + #expect(target.radioName == radio.nodeName) + #expect(target.isFactoryReset == true) + #expect(try await reopened.captureReceiveScope(radioID: radio.radioID, link: .init()) == nil) + try await reopened.completeRadioErase(radioID: target.radioID) + #expect(try await reopened.fetchPendingRadioErases().isEmpty) + #expect(try await reopened.recentlyBlockedMessages().map(\.identity.radioID) == [other.radioID]) + #expect(try await reopened.fetchDevice(id: other.id) != nil) + #expect(!scope.isCurrent) + } + + private func openStore(_ url: URL) throws -> PersistenceStore { + let schema = PersistenceStore.schema + let configuration = ModelConfiguration(schema: schema, url: url) + return try PersistenceStore(modelContainer: ModelContainer(for: schema, configurations: configuration)) + } + + private func makeDrop(_ radio: DeviceDTO) throws -> RecentlyBlockedMessageDTO { + let body = "Hidden body" + var preference = TextRulesPreference() + preference.append(.init(phrase: "hidden", lookIn: .message, match: .contains)) + return try RecentlyBlockedMessageDTO( + identity: .init( + radioID: radio.radioID, conversationID: nil, senderPrefix: nil, + senderTimestamp: 1, textType: 0, wireText: Data(body.utf8) + ), + arrivedAt: Date(), body: body, sender: nil, conversationName: nil, radioName: radio.nodeName, + match: #require(preference.firstMatch(body: body, sender: nil)) + ) + } +} diff --git a/MC1Tests/AppState/RecentlyBlockedPersistenceTests.swift b/MC1Tests/AppState/RecentlyBlockedPersistenceTests.swift new file mode 100644 index 0000000000..81e9a4f1e5 --- /dev/null +++ b/MC1Tests/AppState/RecentlyBlockedPersistenceTests.swift @@ -0,0 +1,156 @@ +import Foundation +@testable import MC1Services +import SwiftData +import Testing + +@Suite("Recently Blocked persistence") +struct RecentlyBlockedPersistenceTests { + private struct InjectedSaveFailure: Error {} + + @Test + func `retained drops are capped across radios and rollback preserves the committed archive`() async throws { + let directory = URL.temporaryDirectory.appending(path: UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let configuration = ModelConfiguration( + schema: PersistenceStore.schema, + url: directory.appending(path: "recently-blocked.store") + ) + let radios = [UUID(), UUID()] + let limit = PersistenceStore.recentlyBlockedRetentionLimit + let drops = try (0...limit + 1).map { index in + try makeDrop(index: index, radioID: radios[index % radios.count]) + } + + do { + let container = try ModelContainer(for: PersistenceStore.schema, configurations: [configuration]) + let store = PersistenceStore(modelContainer: container) + for drop in drops.dropLast() { + try await store.recordRecentlyBlockedMessage(drop) + } + let lastDrop = drops[limit] + try await store.recordRecentlyBlockedMessage(lastDrop) + let committed = try await store.recentlyBlockedMessages() + #expect(committed == Array(drops[1...limit].reversed())) + + await store.setRecordRecentlyBlockedFaultInjection { throw InjectedSaveFailure() } + await #expect(throws: InjectedSaveFailure.self) { + try await store.recordRecentlyBlockedMessage(drops[limit + 1]) + } + #expect(try await store.recentlyBlockedMessages() == committed) + } + + let reopened = try ModelContainer(for: PersistenceStore.schema, configurations: [configuration]) + let store = PersistenceStore(modelContainer: reopened) + #expect(try await store.recentlyBlockedMessages() == Array(drops[1...limit].reversed())) + let exported = try await AppBackupService().export(persistenceStore: store) + let envelope = try parseBackup(data: exported.data) + #expect(envelope.messages.isEmpty) + #expect(envelope.roomMessages.isEmpty) + let encoded = try JSONEncoder().encode(envelope) + #expect(!String(decoding: encoded, as: UTF8.self).contains("Archive-only body")) + } + + @Test(arguments: [false, true]) + func `restored DM wins over retained drop after reopening the store`(corrected: Bool) async throws { + let directory = URL.temporaryDirectory.appending(path: UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let configuration = ModelConfiguration( + schema: PersistenceStore.schema, + url: directory.appending(path: "dm-replay.store") + ) + let radioID = UUID() + let radioKey = Data(repeating: 0x17, count: 32) + let contactKey = Data(repeating: 0x48, count: 32) + let contact = ContactDTO(from: Contact( + radioID: radioID, publicKey: contactKey, name: "Peer", lastHeardTimestamp: 0 + )) + let arrival = MessageDTO(from: Message( + radioID: radioID, contactID: contact.id, text: "Field alert ", timestamp: 1_700_000_100, + directionRawValue: MessageDirection.incoming.rawValue, statusRawValue: MessageStatus.delivered.rawValue, + senderKeyPrefix: Data(contactKey.prefix(6)), deduplicationKey: "live-contact-key", + timestampCorrected: corrected, senderTimestamp: corrected ? 50 : nil + )) + var preference = TextRulesPreference() + preference.setSelection(.all, for: .directMessage) + preference.append(.init(phrase: "alert", lookIn: .message, match: .contains)) + + do { + let store = try PersistenceStore(modelContainer: ModelContainer( + for: PersistenceStore.schema, configurations: [configuration] + )) + try await store.saveDevice(DeviceDTO(from: Device(radioID: radioID, publicKey: radioKey, nodeName: "Local"))) + try await store.saveContact(contact) + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) + let captured = try #require(await store.fetchContact(id: contact.id)) + let admission = try await store.admitDirectMessage( + arrival, wireTextType: arrival.textType.rawValue, contact: captured, scope: scope, preference: preference + ) + guard case .discarded = admission else { + Issue.record("Expected rule to drop the initial arrival") + return + } + #expect(try await store.recentlyBlockedCount() == 1) + } + + let store = try PersistenceStore(modelContainer: ModelContainer( + for: PersistenceStore.schema, configurations: [configuration] + )) + let foreignRadioID = UUID() + let foreignContact = ContactDTO(from: Contact( + radioID: foreignRadioID, publicKey: contactKey, name: "Peer", lastHeardTimestamp: 0 + )) + let foreignMessage = arrival.copy { + $0.id = UUID() + $0.radioID = foreignRadioID + $0.contactID = foreignContact.id + $0.deduplicationKey = "foreign-contact-key" + } + let backup = AppBackupEnvelope( + appVersion: "1", appBuild: "1", + devices: [DeviceDTO(from: Device(radioID: foreignRadioID, publicKey: radioKey, nodeName: "Foreign"))], + contacts: [foreignContact], + messages: [foreignMessage] + ) + _ = try await AppBackupService().importBackup(envelope: backup, into: store) + let scope = try #require(await store.captureReceiveScope(radioID: radioID, link: .init())) + let captured = try #require(await store.fetchContact(id: contact.id)) + let admission = try await store.admitDirectMessage( + arrival, wireTextType: arrival.textType.rawValue, contact: captured, scope: scope, preference: preference + ) + guard case let .replay(saved) = admission else { + Issue.record("Expected exact saved DM to win over the retained drop") + return + } + #expect(saved.id == foreignMessage.id) + #expect(saved.radioID == radioID) + #expect(saved.contactID == contact.id) + #expect(try await store.recentlyBlockedCount() == 1) + #expect(try await store.fetchMessages(contactID: contact.id).count == 1) + } + + private func makeDrop(index: Int, radioID: UUID) throws -> RecentlyBlockedMessageDTO { + var preference = TextRulesPreference() + preference.append(.init(phrase: "archive", lookIn: .messageOrSender, match: .contains)) + let body = "Archive-only body \(index) " + let sender = "Archive Sender" + let match = try #require(preference.firstMatch(body: body, sender: sender)) + return RecentlyBlockedMessageDTO( + identity: .init( + radioID: radioID, + conversationID: UUID(), + senderPrefix: nil, + senderTimestamp: UInt32(index), + textType: 0, + wireText: Data(body.utf8) + ), + arrivedAt: Date(timeIntervalSince1970: Double(index)), + body: body, + sender: sender, + conversationName: "#test", + radioName: "Radio \(radioID)", + match: match + ) + } +} diff --git a/MC1Tests/AppState/RecipientPublicationWiringTests.swift b/MC1Tests/AppState/RecipientPublicationWiringTests.swift index 99803410b0..dacbb21bbb 100644 --- a/MC1Tests/AppState/RecipientPublicationWiringTests.swift +++ b/MC1Tests/AppState/RecipientPublicationWiringTests.swift @@ -42,7 +42,8 @@ struct RecipientPublicationWiringTests { await session.stop() } } - appState.connectionManager.setTestState(connectionState: .connected, services: services) + try await installDevice(store: services.dataStore, appState: appState) + appState.connectionManager.setTestState(connectionState: .connected, services: services, session: session) await appState.wireServicesIfConnected() @@ -55,7 +56,7 @@ struct RecipientPublicationWiringTests { let run = try await prepareRadio() defer { run.finish() } try await saveChannel(store: run.store, index: 0, name: "Ops", secret: Self.secret) - let callback = try #require(run.appState.connectionManager.onDeviceSynced) + let callback = try syncCallback(for: run.appState) await callback(true) await callback(true) @@ -68,7 +69,7 @@ struct RecipientPublicationWiringTests { @Test func `an empty read publishes once and records the empty set`() async throws { let run = try await prepareRadio() defer { run.finish() } - let callback = try #require(run.appState.connectionManager.onDeviceSynced) + let callback = try syncCallback(for: run.appState) await callback(true) await callback(true) @@ -83,7 +84,7 @@ struct RecipientPublicationWiringTests { let run = try await prepareRadio() defer { run.finish() } try await saveChannel(store: run.store, index: 0, name: "Ops", secret: Self.secret) - let callback = try #require(run.appState.connectionManager.onDeviceSynced) + let callback = try syncCallback(for: run.appState) await callback(true) #expect(run.counter.count == 1) let published = try #require(run.appState.lastPublishedRecipientIDs) @@ -132,7 +133,7 @@ struct RecipientPublicationWiringTests { (1, "Copy", Self.secret) ]) defer { run.finish() } - let callback = try #require(run.appState.connectionManager.onDeviceSynced) + let callback = try syncCallback(for: run.appState) await callback(false) let task = try #require(run.appState.staleNodeCleanupTask) @@ -161,7 +162,7 @@ struct RecipientPublicationWiringTests { let run = try await prepareCleanup(channels: [(0, "Ops", Self.secret)]) defer { run.finish() } let before = try await offeredIDs(store: run.store) - let callback = try #require(run.appState.connectionManager.onDeviceSynced) + let callback = try syncCallback(for: run.appState) await callback(true) let task = try #require(run.appState.staleNodeCleanupTask) @@ -181,7 +182,7 @@ struct RecipientPublicationWiringTests { @Test func `a cancelled cleanup does not publish`() async throws { let run = try await prepareCleanup(channels: [(0, "Ops", Self.secret)]) defer { run.finish() } - let callback = try #require(run.appState.connectionManager.onDeviceSynced) + let callback = try syncCallback(for: run.appState) await callback(true) let task = try #require(run.appState.staleNodeCleanupTask) @@ -197,7 +198,7 @@ struct RecipientPublicationWiringTests { @Test func `replaced services do not publish after cleanup`() async throws { let run = try await prepareCleanup(channels: [(0, "Ops", Self.secret)]) defer { run.finish() } - let callback = try #require(run.appState.connectionManager.onDeviceSynced) + let callback = try syncCallback(for: run.appState) await callback(true) let task = try #require(run.appState.staleNodeCleanupTask) @@ -221,7 +222,7 @@ struct RecipientPublicationWiringTests { @Test func `a second callback publishes once after the same cleanup`() async throws { let run = try await prepareCleanup(channels: [(0, "Ops", Self.secret)]) defer { run.finish() } - let callback = try #require(run.appState.connectionManager.onDeviceSynced) + let callback = try syncCallback(for: run.appState) await callback(true) let task = try #require(run.appState.staleNodeCleanupTask) @@ -250,9 +251,14 @@ struct RecipientPublicationWiringTests { let run = try await prepareRadio() defer { run.finish() } try await saveChannel(store: run.store, index: 0, name: "Ops", secret: Self.secret) - let callback = try #require(run.appState.connectionManager.onDeviceSynced) + let callback = try syncCallback(for: run.appState) await callback(true) #expect(run.counter.count == 1) + let device = try #require(run.appState.connectedDevice) + run.appState.connectionManager.persistConnection( + deviceID: device.id, radioID: device.radioID, deviceName: device.nodeName + ) + await run.appState.disconnect(reason: .userInitiated) await run.appState.notifyDataRestored().value #expect(run.counter.count == 1) @@ -274,7 +280,7 @@ struct RecipientPublicationWiringTests { run.appState.beforeShortcutRecipientRereadForTesting = { [weak appState = run.appState] in appState?.connectionManager.setTestState(connectedDevice: .some(nil)) } - let callback = try #require(run.appState.connectionManager.onDeviceSynced) + let callback = try syncCallback(for: run.appState) await callback(true) @@ -306,7 +312,7 @@ struct RecipientPublicationWiringTests { appState.cancelStaleNodeCleanup() } } - let callback = try #require(run.appState.connectionManager.onDeviceSynced) + let callback = try syncCallback(for: run.appState) await callback(true) let task = try #require(run.appState.staleNodeCleanupTask) try await waitForCommands(1, transport: run.transport) @@ -359,10 +365,10 @@ struct RecipientPublicationWiringTests { let cleanup = Task { await cleanupRelease.wait() } appState.staleNodeCleanupTask = cleanup appState.staleNodeCleanupServiceID = ObjectIdentifier(attached.services) - manager.onDeviceSynced = { eligible in + manager.onDeviceSynced = { snapshot, eligible in callbackEntered = true callbackSignal.open() - await originalCallback(eligible) + await originalCallback(snapshot, eligible) } defer { cleanupRelease.open() @@ -373,12 +379,11 @@ struct RecipientPublicationWiringTests { await attached.session.stop() } } + let link = try #require(manager.installedLink) let promotion = Task { defer { callbackSignal.open() } - let result = await manager.promoteToReady( - syncResult: FullSyncResult(contacts: .clean, channels: .clean, messages: .clean), - expectedServices: attached.services, - transportType: .bluetooth + let result = await manager.completeSync( + link, syncResult: FullSyncResult(contacts: .clean, channels: .clean, messages: .clean) ) promotionReturned = true return result @@ -387,13 +392,14 @@ struct RecipientPublicationWiringTests { try #require(callbackEntered) #expect(!promotionReturned) #expect(manager.connectionState == .ready) - await manager.handleConnectionLoss(deviceID: deviceID, error: nil) - #expect(manager.connectionState == .disconnected) + let origin = BLELifecycleOrigin(deviceID: deviceID, generation: 1, eventTime: CFAbsoluteTimeGetCurrent()) + let loss = Task { await manager.handleBLELifecycleEvent(.disconnected(origin, error: nil)) } + try await waitUntil("connection loss should detach the retiring stack") { manager.connectionState == .disconnected } #expect(manager.services == nil) - #expect(manager.isReconnectionWatchdogRunning) #expect(!promotionReturned) cleanupRelease.open() let promoted = await promotion.value + await loss.value #expect(!promoted) #expect(manager.connectionState == .disconnected) #expect(manager.services == nil) @@ -455,6 +461,7 @@ extension RecipientPublicationWiringTests { let appState = try makeAppState() let store = appState.connectionManager.persistenceStore try await installDevice(store: store, appState: appState) + _ = attachIdleServices(appState: appState, store: store) let counter = installCounter(on: appState) return RadioRun(appState: appState, store: store, counter: counter) } @@ -510,6 +517,12 @@ extension RecipientPublicationWiringTests { appState.connectionManager.setTestState(connectionState: .ready, connectedDevice: device) } + private func syncCallback(for appState: AppState) throws -> (Bool) async -> Void { + let callback = try #require(appState.connectionManager.onDeviceSynced) + let snapshot = try #require(appState.connectionManager.currentConnection) + return { eligible in await callback(snapshot, eligible) } + } + private func saveChannel(store: PersistenceStore, index: UInt8, name: String, secret: Data) async throws { try await store.saveChannel(ChannelDTO( id: UUID(), diff --git a/MC1Tests/AppState/RemoveFailedPairingTests.swift b/MC1Tests/AppState/RemoveFailedPairingTests.swift new file mode 100644 index 0000000000..51f61c2a33 --- /dev/null +++ b/MC1Tests/AppState/RemoveFailedPairingTests.swift @@ -0,0 +1,178 @@ +#if canImport(UIKit) + import AccessorySetupKit +#endif +import Foundation +@testable import MC1 +@testable import MC1Services +import Testing + +#if canImport(UIKit) + @Suite("AppState Remove and Retry") + @MainActor + struct RemoveFailedPairingTests { + @Test(arguments: [false, true]) + func `declining removal preserves the current radio and failure episode`(hasWiFi: Bool) async throws { + try await withHarness(hasWiFi: hasWiFi) { harness in + harness.pairing.removeAccessoryError = NSError( + domain: ASError.errorDomain, + code: ASError.Code.userCancelled.rawValue + ) + + let operation = try #require(harness.appState.removeFailedPairingAndRetry()) + await operation.value + + #expect(harness.pairing.removeAccessoryCallCount == 1) + #expect(harness.pairing.accessory(for: harness.device.id) != nil) + #expect(await harness.transport.disconnectCount == 0) + let saved = try #require(await harness.manager.persistenceStore.fetchDevice(id: harness.device.id)) + #expect(saved.radioID == harness.device.radioID) + #expect(saved.connectionMethods == harness.device.connectionMethods) + #expect(harness.manager.connectedDevice?.id == harness.device.id) + #expect(harness.manager.connectedDevice?.connectionMethods == harness.device.connectionMethods) + #expect(harness.manager.lastConnectedDeviceID == harness.device.id) + #expect(harness.manager.lastConnectedRadioID == harness.device.radioID) + #expect(harness.manager.connectionIntent.wantsConnection) + #expect(harness.appState.connectionUI.failedPairingDeviceID == harness.device.id) + #expect(!harness.appState.isRecoveringPairing) + #expect(harness.pairing.showPickerCallCount == 0) + } + } + + @Test(arguments: [false, true]) + func `confirmed removal preserves the radio partition and opens the picker`(hasWiFi: Bool) async throws { + try await withHarness(hasWiFi: hasWiFi) { harness in + harness.pairing.setPickerResult(.failure(AccessorySetupKitError.pickerDismissed)) + let operation = try #require(harness.appState.removeFailedPairingAndRetry()) + await operation.value + + #expect(harness.pairing.removeAccessoryCallCount == 1) + #expect(harness.pairing.accessory(for: harness.device.id) == nil) + #expect(await harness.transport.disconnectCount == 1) + let saved = try #require(await harness.manager.persistenceStore.fetchDevice(publicKey: harness.device.publicKey)) + #expect(saved.radioID == harness.device.radioID) + if hasWiFi { + #expect(saved.id == harness.device.id) + #expect(saved.connectionMethods == harness.device.connectionMethods.filter(\.isWiFi)) + } else { + #expect(saved.id != harness.device.id) + #expect(saved.connectionMethods.isEmpty) + #expect(harness.manager.lastConnectedDeviceID == nil) + } + #expect(harness.appState.connectionUI.failedPairingDeviceID == nil) + #expect(!harness.appState.isRecoveringPairing) + #expect(harness.pairing.showPickerCallCount == 1) + } + } + + @Test + func `a new same-device failure episode survives an older successful removal`() async throws { + try await withHarness(hasWiFi: false) { harness in + let gate = AsyncStream.makeStream() + defer { gate.continuation.finish() } + harness.pairing.beforeRemovalResult = { + for await _ in gate.stream { + break + } + } + let operation = try #require(harness.appState.removeFailedPairingAndRetry()) + do { + try await waitUntil("removal confirmation should be pending") { + harness.pairing.removeAccessoryCallCount == 1 + } + } catch { + gate.continuation.finish() + await operation.value + throw error + } + harness.appState.connectionUI.presentPairingFailure( + .connectionFailed(deviceID: harness.device.id, underlying: BLEError.authenticationFailed) + ) + let episodeID = harness.appState.connectionUI.pairingFailureEpisodeID + gate.continuation.finish() + await operation.value + #expect(harness.appState.connectionUI.pairingFailureEpisodeID == episodeID) + #expect(harness.appState.connectionUI.failedPairingDeviceID == harness.device.id) + #expect(!harness.appState.isRecoveringPairing) + #expect(harness.pairing.showPickerCallCount == 0) + } + } + + @MainActor + private struct Harness { + let appState: AppState + let device: DeviceDTO + let transport: ConnectionTestRadioTransport + let pairing: MockAccessorySetupKitService + let suiteName: String + + var manager: ConnectionManager { + appState.connectionManager + } + + func cleanup() async { + await appState.disconnect(reason: .userInitiated) + appState.shutdown() + UserDefaults().removePersistentDomain(forName: suiteName) + } + } + + private func withHarness(hasWiFi: Bool, _ body: @MainActor (Harness) async throws -> Void) async throws { + let harness = try await makeHarness(hasWiFi: hasWiFi) + do { + try await body(harness) + } catch { + await harness.cleanup() + throw error + } + await harness.cleanup() + } + + private func makeHarness(hasWiFi: Bool) async throws -> Harness { + let suiteName = "test.remove-retry.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + let container = try PersistenceStore.createContainer(inMemory: true) + let pairing = MockAccessorySetupKitService() + let deviceID = UUID() + var methods: [ConnectionMethod] = [.bluetooth(peripheralUUID: deviceID, displayName: "Radio")] + if hasWiFi { + methods.append(.wifi(host: "radio.test", port: 5678, displayName: "Radio")) + } + let device = DeviceDTO(from: Device( + id: deviceID, + radioID: UUID(), + publicKey: Data(repeating: 0xA1, count: ProtocolLimits.publicKeySize), + nodeName: "Radio", + isActive: true, + connectionMethods: methods + )) + let transport = ConnectionTestRadioTransport(publicKey: device.publicKey) + let manager = ConnectionManager( + modelContainer: container, + defaults: defaults, + stateMachine: MockBLEStateMachine(), + transport: transport, + pairing: AccessorySetupPairingService(accessorySetupKit: pairing) + ) + try await manager.persistenceStore.saveDevice(device) + pairing.setPairedAccessories([ASAccessory(bluetoothIdentifier: device.id, displayName: device.nodeName)]) + let appState = AppState( + modelContainer: container, + isPlaceholder: true, + defaults: defaults, + injectedConnectionManager: manager + ) + do { + _ = try await manager.connect(to: device.id) + let connected = try #require(manager.connectedDevice) + #expect(connected.radioID == device.radioID) + appState.connectionUI.failedPairingDeviceID = connected.id + return Harness(appState: appState, device: connected, transport: transport, pairing: pairing, suiteName: suiteName) + } catch { + await appState.disconnect(reason: .userInitiated) + appState.shutdown() + defaults.removePersistentDomain(forName: suiteName) + throw error + } + } + } +#endif diff --git a/MC1Tests/AppState/RetirementContractCallerTests.swift b/MC1Tests/AppState/RetirementContractCallerTests.swift new file mode 100644 index 0000000000..21e50503c7 --- /dev/null +++ b/MC1Tests/AppState/RetirementContractCallerTests.swift @@ -0,0 +1,210 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Synchronization +import Testing +import UserNotifications + +@Suite("Retirement contract callers") +@MainActor +struct RetirementContractCallerTests { + enum Trigger: CaseIterable, Sendable { case disconnect, replacement, wifiLoss, bleLoss } + @Test(arguments: Trigger.allCases) + func `captured cleanup survives each terminal caller`(trigger: Trigger) async throws { + let fixture = try Fixture(bluetoothSource: trigger == .bleLoss) + var disconnect: Task? + var replacement: Task? + do { + if trigger == .bleLoss { + _ = try await fixture.manager.connect(to: fixture.deviceID, forceFullSync: true, forceReconnect: true) + } else { + _ = try await fixture.app.connectViaWiFi(host: "first.local", port: 4242) + } + let source = try #require(fixture.manager.currentConnection) + let sourceServices = try #require(fixture.manager.services) + let frame = ContactFrame( + publicKey: Data(repeating: 41, count: ProtocolLimits.publicKeySize), type: .chat, + flags: 0, outPathLength: 0, outPath: Data(), name: "Deleted", lastAdvertTimestamp: 0, + latitude: 0, longitude: 0, lastModified: 0 + ) + let saved = try await fixture.manager.persistenceStore.saveContact(radioID: source.device.radioID, from: frame) + fixture.firstNotifications.add(contactID: saved.id, prefix: "source") + fixture.secondNotifications.add(contactID: UUID(), prefix: "successor") + fixture.firstNotifications.holdNextSnapshot = true + fixture.app.advertisementEventsTask?.cancel() + await fixture.app.advertisementEventsTask?.value + fixture.app.advertisementEventsTask = nil + await fixture.first.inject(Data([ResponseCode.contactDeleted.rawValue]) + frame.publicKey) + try await waitUntil("background deletion should be admitted before retirement") { + await sourceServices.advertisementService.pendingDeletedKeys.contains(frame.publicKey) + } + let sourceBadges = fixture.firstNotifications.badges + fixture.manager.testNotificationSystemOperations = fixture.secondNotifications.operations + switch trigger { + case .disconnect: + disconnect = Task { await fixture.app.disconnect(reason: .userInitiated) } + try await waitUntil("disconnect should enter captured system cleanup") { + fixture.firstNotifications.snapshotIsHeld + } + replacement = Task { try await fixture.app.connectViaWiFi(host: "second.local", port: 4242) } + case .replacement: + replacement = Task { try await fixture.app.connectViaWiFi(host: "second.local", port: 4242) } + case .wifiLoss: + await fixture.first.simulateRemoteLoss() + case .bleLoss: + await fixture.first.simulateRemoteLoss() + try await waitUntil("BLE loss should enter captured system cleanup") { + fixture.firstNotifications.snapshotIsHeld + } + replacement = Task { try await fixture.app.connectViaWiFi(host: "second.local", port: 4242) } + } + try await waitUntil("retirement should await captured notification cleanup") { + fixture.firstNotifications.snapshotIsHeld + } + #expect(try await fixture.manager.persistenceStore.fetchContact(id: saved.id) == nil) + #expect(await fixture.second.connectCount == 0) + #expect(fixture.manager.currentConnection == nil) + #expect(fixture.firstNotifications.removed.isEmpty) + #expect(fixture.app.advertisementEventsTask == nil) + fixture.app.navigation.selectedTool = .lineOfSight + + fixture.firstNotifications.releaseSnapshot() + await disconnect?.value + if let replacement { + let result = try await replacement.value + #expect(fixture.manager.isCurrent(result)) + } else { + try await waitUntil("same-request recovery should establish B after A cleanup") { + fixture.manager.connectionState == .ready && fixture.manager.connectedDevice?.publicKey == fixture.second.publicKey + } + } + #expect(fixture.manager.connectionState == .ready) + #expect(fixture.manager.connectedDevice?.publicKey == fixture.second.publicKey) + #expect(Set(fixture.firstNotifications.removed) == ["source-dm", "source-reaction"]) + #expect(fixture.firstNotifications.badges == sourceBadges) + #expect(fixture.secondNotifications.removed.isEmpty) + #expect(fixture.secondNotifications.requests.count == 2) + #expect(fixture.app.navigation.selectedTool == .lineOfSight) + #expect(!fixture.app.connectionUI.isBusy) + let successor = try #require(fixture.manager.session) + _ = try await successor.getTime() + } catch { + fixture.firstNotifications.releaseSnapshot() + fixture.secondNotifications.releaseSnapshot() + await disconnect?.value + _ = await replacement?.result + await fixture.close() + throw error + } + await fixture.close() + } + + @MainActor + private final class Fixture { + let deviceID = UUID() + let app: AppState + let manager: ConnectionManager + let first = ConnectionTestRadioTransport(publicKey: Data(repeating: 0xA1, count: ProtocolLimits.publicKeySize)) + let second = ConnectionTestRadioTransport(publicKey: Data(repeating: 0xB2, count: ProtocolLimits.publicKeySize)) + let firstNotifications = Recorder() + let secondNotifications = Recorder() + let sockets: Sockets + private let suite = "test.retirement-callers.\(UUID())" + + init(bluetoothSource: Bool) throws { + let defaults = try #require(UserDefaults(suiteName: suite)) + let container = try PersistenceStore.createContainer(inMemory: true) + sockets = Sockets(first: bluetoothSource ? second : first, second: second) + let sockets = sockets + let pairing = MockAccessorySetupKitService() + pairing.isSessionActive = false + manager = ConnectionManager( + modelContainer: container, defaults: defaults, stateMachine: MockBLEStateMachine(), + transport: first, pairing: AccessorySetupPairingService(accessorySetupKit: pairing), + makeWiFiTransport: { sockets.take() } + ) + manager.testNotificationSystemOperations = firstNotifications.operations + app = AppState(modelContainer: container, isPlaceholder: true, defaults: defaults, injectedConnectionManager: manager) + manager.appStateProvider = Background() + } + + func close() async { + firstNotifications.releaseSnapshot() + secondNotifications.releaseSnapshot() + await first.releaseAllGates() + await second.releaseAllGates() + await app.disconnect(reason: .userInitiated) + app.tearDownAppStateSessionState() + app.shutdown() + await manager.retirementTask?.value + UserDefaults().removePersistentDomain(forName: suite) + } + } + + private struct Background: AppStateProvider { + let isInForeground = false + } + + private final class Sockets: Sendable { + private let first: ConnectionTestRadioTransport + private let second: ConnectionTestRadioTransport + private let count = Mutex(0) + + init(first: ConnectionTestRadioTransport, second: ConnectionTestRadioTransport) { + self.first = first + self.second = second + } + + func take() -> ConnectionTestRadioTransport { + count.withLock { count in + defer { count += 1 } + return count == 0 ? first : second + } + } + } + + @MainActor + private final class Recorder { + var requests: [UNNotificationRequest] = [] + var removed: [String] = [] + var badges: [Int] = [] + var holdNextSnapshot = false + var snapshotIsHeld = false + var waiter: CheckedContinuation? + + func add(contactID: UUID, prefix: String) { + for type in ["dm", "reaction"] { + let content = UNMutableNotificationContent() + content.userInfo = ["contactID": contactID.uuidString, "type": type] + requests.append(UNNotificationRequest(identifier: "\(prefix)-\(type)", content: content, trigger: nil)) + } + } + + func releaseSnapshot() { + waiter?.resume() + waiter = nil + snapshotIsHeld = false + holdNextSnapshot = false + } + + var operations: NotificationService.SystemOperations { + .init( + setBadgeCount: { self.badges.append($0) }, + deliveredRequests: { + if self.holdNextSnapshot { + self.holdNextSnapshot = false + self.snapshotIsHeld = true + await withCheckedContinuation { self.waiter = $0 } + self.snapshotIsHeld = false + } + return self.requests + }, + removeDeliveredNotifications: { identifiers in + self.removed.append(contentsOf: identifiers) + self.requests.removeAll { identifiers.contains($0.identifier) } + } + ) + } + } +} diff --git a/MC1Tests/Helpers/ConnectionLinkSwitchHarness.swift b/MC1Tests/Helpers/ConnectionLinkSwitchHarness.swift new file mode 100644 index 0000000000..3b49e62bf6 --- /dev/null +++ b/MC1Tests/Helpers/ConnectionLinkSwitchHarness.swift @@ -0,0 +1,172 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import Testing + +@MainActor +final class ConnectionLinkSwitchHarness { + let appState: AppState + let device: DeviceDTO + let bluetooth: ConnectionTestRadioTransport + let wifi: ConnectionTestRadioTransport + let pairing: MockAccessorySetupKitService + let initialBluetoothAttempts: Int + let initialWiFiAttempts: Int + private let defaults: UserDefaults + private let suite: String + private var workers: [Task] = [] + + var manager: ConnectionManager { + appState.connectionManager + } + + private init( + appState: AppState, device: DeviceDTO, bluetooth: ConnectionTestRadioTransport, + wifi: ConnectionTestRadioTransport, pairing: MockAccessorySetupKitService, + initialBluetoothAttempts: Int, initialWiFiAttempts: Int, + defaults: UserDefaults, suite: String + ) { + self.appState = appState + self.device = device + self.bluetooth = bluetooth + self.wifi = wifi + self.pairing = pairing + self.initialBluetoothAttempts = initialBluetoothAttempts + self.initialWiFiAttempts = initialWiFiAttempts + self.defaults = defaults + self.suite = suite + } + + static func make( + live: TransportType = .bluetooth, + peripheralID: UUID? = UUID(), + wifiHost: String? = nil, + wifiPort: UInt16 = ConnectionMethod.defaultWiFiPort, + foreignWiFiRadio: Bool = false + ) async throws -> ConnectionLinkSwitchHarness { + let suite = "test.linkswitch.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suite)) + let container = try PersistenceStore.createContainer(inMemory: true) + let publicKey = Data(repeating: 0xB1, count: ProtocolLimits.publicKeySize) + let bluetooth = ConnectionTestRadioTransport(publicKey: publicKey) + let wifi = ConnectionTestRadioTransport( + publicKey: foreignWiFiRadio ? Data(repeating: 0xB2, count: ProtocolLimits.publicKeySize) : publicKey + ) + let pairing = MockAccessorySetupKitService() + pairing.isSessionActive = false + let manager = ConnectionManager( + modelContainer: container, defaults: defaults, stateMachine: MockBLEStateMachine(), + transport: bluetooth, pairing: AccessorySetupPairingService(accessorySetupKit: pairing), + makeWiFiTransport: { wifi } + ) + var methods: [ConnectionMethod] = [] + if let peripheralID { methods.append(.bluetooth(peripheralUUID: peripheralID, displayName: nil)) } + if let wifiHost { methods.append(.wifi(host: wifiHost, port: wifiPort, displayName: nil)) } + let seed = makeDevice(id: peripheralID ?? UUID(), publicKey: publicKey, methods: methods) + try await manager.persistenceStore.saveDevice(seed) + let appState = AppState( + modelContainer: container, isPlaceholder: true, defaults: defaults, injectedConnectionManager: manager + ) + do { + switch live { + case .bluetooth: + let id = try #require(peripheralID) + _ = try await manager.connect(to: id) + case .wifi: + _ = try await manager.connectViaWiFi(host: wifiHost ?? "10.0.0.4", port: wifiPort) + } + let device = try #require(manager.connectedDevice) + #expect(manager.connectionState == .ready) + #expect(manager.services != nil) + await bluetooth.setConnectError(BLEError.bluetoothUnavailable) + await wifi.setConnectError(BLEError.connectionTimeout) + return await ConnectionLinkSwitchHarness( + appState: appState, device: device, bluetooth: bluetooth, wifi: wifi, pairing: pairing, + initialBluetoothAttempts: bluetooth.connectCount, + initialWiFiAttempts: wifi.connectCount, defaults: defaults, suite: suite + ) + } catch { + await bluetooth.releaseAllGates() + await wifi.releaseAllGates() + await manager.disconnect(reason: .userInitiated) + appState.shutdown() + defaults.removePersistentDomain(forName: suite) + throw error + } + } + + func startSwitch(to target: TransportType, host: String? = "10.0.0.8") -> Task { + let worker = Task { await self.appState.beginLinkSwitch(to: target, snapshotWiFiHost: host) } + workers.append(worker) + return worker + } + + func startDisconnect() -> Task { + let worker = Task { await self.appState.disconnect(reason: .userInitiated) } + workers.append(worker) + return worker + } + + func close() async { + await bluetooth.releaseAllGates() + await wifi.releaseAllGates() + for worker in workers { + await worker.value + } + workers.removeAll() + await appState.disconnect(reason: .userInitiated) + appState.shutdown() + defaults.removePersistentDomain(forName: suite) + #expect(manager.services == nil) + #expect(await bluetooth.isConnected == false) + #expect(await wifi.isConnected == false) + } + + func expectRecoveryRow(_ link: TransportType, peripheralID: UUID, port: UInt16) throws { + let record = try #require(appState.connectionLinkSwitch) + let snapshot = ConnectionLinkRows.make( + liveTransport: manager.currentTransportType, + savedPeripheralID: appState.connectedDevice?.bluetoothPeripheralID, + wifiSupport: .supported, wifiAssociated: true, + wifiDial: ConnectionLinkWiFiDial(host: "other.example", port: 9), activeSwitch: record + ) + #expect(try #require(snapshot.rows.first { $0.link == link }).canSwitch) + #expect(snapshot.checked == record.checked) + #expect(snapshot.rows.first { $0.link == .wifi }?.address == "radio.local") + #expect(record.bluetoothPeripheralID == peripheralID) + #expect(record.wifi == ConnectionLinkWiFiDial(host: "radio.local", port: port)) + } + + static func withHarness( + live: TransportType = .bluetooth, + peripheralID: UUID? = UUID(), + wifiHost: String? = nil, + wifiPort: UInt16 = ConnectionMethod.defaultWiFiPort, + foreignWiFiRadio: Bool = false, + body: (ConnectionLinkSwitchHarness) async throws -> Void + ) async throws { + let harness = try await make( + live: live, peripheralID: peripheralID, wifiHost: wifiHost, + wifiPort: wifiPort, foreignWiFiRadio: foreignWiFiRadio + ) + do { + try await body(harness) + await harness.close() + } catch { + await harness.close() + throw error + } + } + + private static func makeDevice(id: UUID, publicKey: Data, methods: [ConnectionMethod]) -> DeviceDTO { + DeviceDTO( + id: id, radioID: UUID(), publicKey: publicKey, nodeName: "Relay", firmwareVersion: 14, + firmwareVersionString: "1.18.0", manufacturerName: "Test", buildDate: "2025-01-01", + maxContacts: 100, maxChannels: 1, frequency: 915_000, bandwidth: 250_000, + spreadingFactor: 10, codingRate: 5, txPower: 20, maxTxPower: 20, latitude: 0, longitude: 0, + blePin: 0, manualAddContacts: false, multiAcks: 2, telemetryModeBase: 2, telemetryModeLoc: 0, + telemetryModeEnv: 0, advertLocationPolicy: 0, lastConnected: Date(), lastContactSync: 0, + isActive: true, ocvPreset: nil, customOCVArrayString: nil, connectionMethods: methods + ) + } +} diff --git a/MC1Tests/Helpers/MockAccessorySetupKitService.swift b/MC1Tests/Helpers/MockAccessorySetupKitService.swift index eceff873f4..d519fa2849 100644 --- a/MC1Tests/Helpers/MockAccessorySetupKitService.swift +++ b/MC1Tests/Helpers/MockAccessorySetupKitService.swift @@ -25,6 +25,9 @@ final class MockAccessorySetupKitService: AccessorySetupKitServicing { var pickerResult: Result = .failure(AccessorySetupKitError.sessionNotActive) var removeAccessoryError: Error? + var beforeRemovalResult: (@MainActor () async -> Void)? + var beforePickerResult: (@MainActor () -> Void)? + var beforePickerResultAsync: (@MainActor () async -> Void)? func setPickerResult(_ result: Result) { pickerResult = result @@ -41,6 +44,8 @@ final class MockAccessorySetupKitService: AccessorySetupKitServicing { func showPicker() async throws -> UUID { showPickerCallCount += 1 + beforePickerResult?() + await beforePickerResultAsync?() switch pickerResult { case let .success(id): return id @@ -52,6 +57,7 @@ final class MockAccessorySetupKitService: AccessorySetupKitServicing { func removeAccessory(_ accessory: ASAccessory) async throws { removeAccessoryCallCount += 1 lastRemovedDeviceID = accessory.bluetoothIdentifier + await beforeRemovalResult?() if let removeAccessoryError { throw removeAccessoryError } diff --git a/MC1Tests/Helpers/MockMeshTransport.swift b/MC1Tests/Helpers/MockMeshTransport.swift index 9fdfc14215..4b0f6248d8 100644 --- a/MC1Tests/Helpers/MockMeshTransport.swift +++ b/MC1Tests/Helpers/MockMeshTransport.swift @@ -2,7 +2,7 @@ import Foundation @testable import MC1Services @testable import MeshCore -/// In-memory transport for app-layer pairing tests. Mirrors the MC1Services test mock. +/// Records pairing dispatch and source lifecycle events; session bytes are injected explicitly. public actor MockMeshTransport: iOSMeshTransport { public struct ConnectInvocation: Sendable, Equatable { public let deviceID: UUID? @@ -11,11 +11,16 @@ public actor MockMeshTransport: iOSMeshTransport { public private(set) var connectInvocations: [ConnectInvocation] = [] public private(set) var disconnectInvocations = 0 + public private(set) var sentData: [Data] = [] private var currentDeviceID: UUID? - private var disconnectionHandler: (@Sendable (UUID, Error?) -> Void)? - private var reconnectionHandler: (@Sendable (UUID) -> Void)? - private let dataStream: AsyncStream - private let dataContinuation: AsyncStream.Continuation + private var currentBinding: SessionTransportBinding? + private var lifecycleHandler: (@Sendable (BLELifecycleEvent) -> Void)? + private var lifecycleGeneration: UInt64 = 0 + private var lifecycleEventTime = CFAbsoluteTimeGetCurrent() + private var recovering = false + private var dataStream: AsyncStream + /// Keeps the physical stream open until the test injects a reply or renews it. + private var dataContinuation: AsyncStream.Continuation private var connected = false private var connectError: Error? @@ -25,6 +30,8 @@ public actor MockMeshTransport: iOSMeshTransport { dataContinuation = continuation } + // MARK: - MeshTransport + public var receivedData: AsyncStream { dataStream } @@ -36,36 +43,137 @@ public actor MockMeshTransport: iOSMeshTransport { public func connect() async throws { connectInvocations.append(ConnectInvocation(deviceID: currentDeviceID, timestamp: Date())) if let connectError { throw connectError } + lifecycleGeneration += 1 + lifecycleEventTime = CFAbsoluteTimeGetCurrent() + recovering = false connected = true } public func disconnect() async { disconnectInvocations += 1 connected = false + recovering = false + } + + public func makeSessionTransport(deviceID: UUID, binding: SessionTransportBinding) -> SessionBoundTransport { + try? binding.performIfActive { + if currentBinding !== binding { currentBinding?.revoke() } + currentDeviceID = deviceID + currentBinding = binding + } + return SessionBoundTransport(transport: self, binding: binding) + } + + public func disconnect(sessionBinding: SessionTransportBinding) async { + guard currentBinding === sessionBinding else { return } + await disconnect() + } + + // Connect completes in one actor turn, so this fixture has no pending setup to cancel. + public func cancelPendingEstablishment(sessionBinding: SessionTransportBinding) {} + public func cancelUnsubmittedWrites(sessionBinding: SessionTransportBinding) {} + + public func connect(sessionBinding: SessionTransportBinding) async throws { + guard currentBinding === sessionBinding else { throw CancellationError() } + try sessionBinding.performIfActive { + connectInvocations.append(ConnectInvocation(deviceID: currentDeviceID, timestamp: Date())) + if let connectError { throw connectError } + lifecycleGeneration += 1 + lifecycleEventTime = CFAbsoluteTimeGetCurrent() + recovering = false + connected = true + } + } + + public func send(_ data: Data, sessionBinding: SessionTransportBinding) throws { + guard currentBinding === sessionBinding else { throw CancellationError() } + try sessionBinding.performIfActive { sentData.append(data) } } - public func send(_ data: Data) async throws {} + public func receivedData(sessionBinding: SessionTransportBinding) -> AsyncStream { + guard currentBinding === sessionBinding, sessionBinding.isActive else { return AsyncStream { $0.finish() } } + return dataStream + } + + public func refreshDataStream(sessionBinding: SessionTransportBinding) { + guard currentBinding === sessionBinding, sessionBinding.isActive else { return } + refreshDataStream() + } + + public var lifecycleOrigin: BLELifecycleOrigin? { + guard let currentDeviceID, connected || recovering else { return nil } + return BLELifecycleOrigin(deviceID: currentDeviceID, generation: lifecycleGeneration, eventTime: lifecycleEventTime) + } + + public var hasLifecycleHandler: Bool { + lifecycleHandler != nil + } + + public func setLifecycleHandler(_ handler: @escaping @Sendable (BLELifecycleEvent) -> Void) { + lifecycleHandler = handler + } + + public func send(_ data: Data) async throws { + sentData.append(data) + } + + // MARK: - iOSMeshTransport public func setDeviceID(_ id: UUID) { currentDeviceID = id } - public func switchDevice(to deviceID: UUID) async throws { - connectInvocations.append(ConnectInvocation(deviceID: deviceID, timestamp: Date())) - currentDeviceID = deviceID + public func refreshDataStream() { + dataContinuation.finish() + (dataStream, dataContinuation) = AsyncStream.makeStream(of: Data.self) } - public func setDisconnectionHandler(_ handler: @escaping @Sendable (UUID, Error?) -> Void) { - disconnectionHandler = handler + public func primePhysicalLink(deviceID: UUID, generation: UInt64 = 1, recovering: Bool = false) { + currentDeviceID = deviceID + lifecycleGeneration = generation + lifecycleEventTime = CFAbsoluteTimeGetCurrent() + self.recovering = recovering + connected = !recovering } - public func setReconnectionHandler(_ handler: @escaping @Sendable (UUID) -> Void) { - reconnectionHandler = handler + public func simulateReceive(_ data: Data) { + dataContinuation.yield(data) } - public func refreshDataStream() {} + // MARK: - Test Helpers + /// Makes every recorded connection attempt fail before establishing a BLE link. public func setConnectError(_ error: Error?) { connectError = error } + + /// Emits a reconnected lifecycle event as if iOS auto-reconnect completed + /// for `deviceID`, including synchronous renewed-stream capture. + public func simulateReconnection(deviceID: UUID) { + currentDeviceID = deviceID + connected = true + recovering = false + refreshDataStream() + let origin = BLELifecycleOrigin(deviceID: deviceID, generation: lifecycleGeneration, eventTime: CFAbsoluteTimeGetCurrent()) + lifecycleHandler?(.reconnected(origin)) + } + + public func simulateAutoReconnecting(deviceID: UUID, errorInfo: String = "none") { + currentBinding?.revoke() + currentDeviceID = deviceID + lifecycleGeneration += 1 + lifecycleEventTime = CFAbsoluteTimeGetCurrent() + connected = false + recovering = true + let origin = BLELifecycleOrigin(deviceID: deviceID, generation: lifecycleGeneration, eventTime: lifecycleEventTime) + lifecycleHandler?(.autoReconnecting(origin, errorInfo: errorInfo)) + } + + public func simulateDisconnection(deviceID: UUID, error: BLEError? = nil) { + currentBinding?.revoke() + connected = false + recovering = false + let origin = BLELifecycleOrigin(deviceID: deviceID, generation: lifecycleGeneration, eventTime: CFAbsoluteTimeGetCurrent()) + lifecycleHandler?(.disconnected(origin, error: error)) + } } diff --git a/MC1Tests/Helpers/RetainedAdminPartitionSurface.swift b/MC1Tests/Helpers/RetainedAdminPartitionSurface.swift new file mode 100644 index 0000000000..3e9b42a646 --- /dev/null +++ b/MC1Tests/Helpers/RetainedAdminPartitionSurface.swift @@ -0,0 +1,125 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import Testing + +@MainActor +struct RetainedAdminPartitionSurface { + let session: RemoteNodeSessionDTO + let settings: NodeSettingsViewModel + let cli: NodeCLIViewModel + let requestStatus: @MainActor () async -> Void + let canMakeCLISend: @MainActor () -> Bool + private let cliObservation: CLIObservation + + static func make( + harness: RetainedConversationPartitionHarness, radioID: UUID, role: RemoteNodeRole + ) async throws -> RetainedAdminPartitionSurface { + let appState = harness.environment.appState + let cliObservation = CLIObservation() + let session = RemoteNodeSessionDTO( + radioID: radioID, publicKey: harness.room.publicKey, name: "Retained admin", + role: role, isConnected: true, permissionLevel: .admin + ) + try await harness.store.saveRemoteNodeSessionDTO(session) + switch role { + case .roomServer: + let models = appState.remoteAdminWorkspaces.room(for: session) + preloadMetadata(models.settings.helper) + await models.settings.configure( + roomAdminService: { appState.connectionSnapshot(for: radioID)?.services.roomAdminService }, session: session + ) + models.status.configure( + roomAdminService: { appState.connectionSnapshot(for: radioID)?.services.roomAdminService }, + contactService: { appState.connectionSnapshot(for: radioID)?.services.contactService }, + nodeSnapshotService: { appState.connectionSnapshot(for: radioID)?.services.nodeSnapshotService } + ) + if let send = models.settings.makeNodeCLISendClosure(session: session) { + models.cli.configure(sessionName: session.name, remoteTarget: .room, sendRawCommand: { command, timeout in + try await cliObservation.send(command: command, timeout: timeout, using: send) + }) + } + return RetainedAdminPartitionSurface( + session: session, settings: models.settings.helper, cli: models.cli, + requestStatus: { await models.status.requestStatus(for: session) }, + canMakeCLISend: { models.settings.makeNodeCLISendClosure(session: session) != nil }, + cliObservation: cliObservation + ) + case .repeater: + let models = appState.remoteAdminWorkspaces.repeater(for: session) + preloadMetadata(models.settings.helper) + await models.settings.configure( + repeaterAdminService: { appState.connectionSnapshot(for: radioID)?.services.repeaterAdminService }, session: session + ) + models.status.configure( + repeaterAdminService: { appState.connectionSnapshot(for: radioID)?.services.repeaterAdminService }, + contactService: { appState.connectionSnapshot(for: radioID)?.services.contactService }, + nodeSnapshotService: { appState.connectionSnapshot(for: radioID)?.services.nodeSnapshotService }, + deviceHashSize: { appState.connectionSnapshot(for: radioID)?.device.hashSize } + ) + if let send = models.settings.makeNodeCLISendClosure(session: session) { + models.cli.configure(sessionName: session.name, remoteTarget: .repeater, sendRawCommand: { command, timeout in + try await cliObservation.send(command: command, timeout: timeout, using: send) + }) + } + return RetainedAdminPartitionSurface( + session: session, settings: models.settings.helper, cli: models.cli, + requestStatus: { await models.status.requestStatus(for: session) }, + canMakeCLISend: { models.settings.makeNodeCLISendClosure(session: session) != nil }, + cliObservation: cliObservation + ) + case .sensor: + preconditionFailure("Sensors use a separate settings workspace") + } + } + + func sendSettingsCommand() async -> Bool { + do { + _ = try await settings.sendAndWait(Self.command, rawMatching: true) + return false + } catch { + return true + } + } + + func executeCLI(harness: RetainedConversationPartitionHarness) async throws { + let completionsBefore = cliObservation.completedCount + let failuresBefore = cliObservation.failedCount + cli.executeCommand(Self.command) + try await harness.waitUntil { + !cli.isWaitingForResponse && cliObservation.completedCount > completionsBefore + } + let actualSendFailed = cliObservation.failedCount > failuresBefore + #expect(actualSendFailed) + } + + func close() { + cli.cancelCurrentCommand() + } + + private static func preloadMetadata(_ helper: NodeSettingsViewModel) { + helper.firmwareVersion = "1.18.0" + helper.applyDeviceTime("06:40 - 18/4/2025 UTC") + } + + private static let command = "ver" + + @MainActor + private final class CLIObservation { + var completedCount = 0 + var failedCount = 0 + + func send( + command: String, timeout: Duration, + using operation: @MainActor (String, Duration) async throws -> String + ) async throws -> String { + defer { completedCount += 1 } + do { + return try await operation(command, timeout) + } catch { + failedCount += 1 + throw error + } + } + } +} diff --git a/MC1Tests/Helpers/RetainedConversationPartitionHarness.swift b/MC1Tests/Helpers/RetainedConversationPartitionHarness.swift new file mode 100644 index 0000000000..50a490dad6 --- /dev/null +++ b/MC1Tests/Helpers/RetainedConversationPartitionHarness.swift @@ -0,0 +1,228 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@MainActor +final class RetainedConversationPartitionHarness { + let environment: ConnectionLinkSwitchHarness + let canonicalRadioID: UUID + let contact: ContactDTO + let channel: ChannelDTO + let room: RemoteNodeSessionDTO + let directMessage: MessageDTO + let channelMessage: MessageDTO + let roomMessage: RoomMessageDTO + let directModel: ChatViewModel + let channelModel: ChatViewModel + let roomModel: RoomConversationViewModel + let radio: ConnectionTestRadioTransport + + var manager: ConnectionManager { + environment.manager + } + + var store: PersistenceStore { + manager.persistenceStore + } + + private init( + environment: ConnectionLinkSwitchHarness, canonicalRadioID: UUID, contact: ContactDTO, + channel: ChannelDTO, room: RemoteNodeSessionDTO, directMessage: MessageDTO, + channelMessage: MessageDTO, roomMessage: RoomMessageDTO, + directModel: ChatViewModel, channelModel: ChatViewModel, roomModel: RoomConversationViewModel, + radio: ConnectionTestRadioTransport + ) { + self.environment = environment + self.canonicalRadioID = canonicalRadioID + self.contact = contact + self.channel = channel + self.room = room + self.directMessage = directMessage + self.channelMessage = channelMessage + self.roomMessage = roomMessage + self.directModel = directModel + self.channelModel = channelModel + self.roomModel = roomModel + self.radio = radio + } + + static func make(live: TransportType = .bluetooth) async throws -> RetainedConversationPartitionHarness { + let env = try await ConnectionLinkSwitchHarness.make(live: live, wifiHost: live == .wifi ? "radio.local" : nil) + do { + let radio = live == .bluetooth ? env.bluetooth : env.wifi + await radio.setConnectError(nil) + let source = env.manager.currentConnection + let sourceAvailable = source != nil + try #require(sourceAvailable) + guard let source else { throw HarnessError.sourceUnavailable } + let store = env.manager.persistenceStore + let ghost = env.device.copy { + $0.id = UUID() + $0.radioID = UUID() + $0.publicKey = canonicalPublicKey + $0.isActive = false + $0.connectionMethods = [] + } + try await store.saveDevice(ghost) + let contact = makeContact(radioID: env.device.radioID, type: .chat, keyByte: 0xD1) + let roomContact = makeContact(radioID: env.device.radioID, type: .room, keyByte: 0xD2) + try await store.saveContact(contact) + try await store.saveContact(roomContact) + let channel = ChannelDTO( + id: UUID(), radioID: env.device.radioID, index: channelIndex, name: "Retained A", + secret: channelSecret, isEnabled: true, lastMessageDate: nil, unreadCount: 0 + ) + try await store.saveChannel(channel) + await radio.setChannel(index: channelIndex, name: "Retained A", secret: channelSecret) + let room = RemoteNodeSessionDTO( + radioID: env.device.radioID, publicKey: roomContact.publicKey, name: "Retained A room", + role: .roomServer, isConnected: true, permissionLevel: .readWrite + ) + try await store.saveRemoteNodeSessionDTO(room) + let directMessage = try await source.services.messageService.createPendingMessage(text: "Retained A DM", to: contact) + .copy { $0.status = .failed; $0.timestamp = originalTimestamp } + let channelMessage = try await source.services.messageService.createPendingChannelMessage( + text: "Retained A channel", channelIndex: channelIndex, radioID: env.device.radioID + ).copy { $0.status = .failed; $0.timestamp = originalTimestamp } + try await store.saveMessage(directMessage) + try await store.saveMessage(channelMessage) + let roomMessage = RoomMessageDTO( + sessionID: room.id, authorKeyPrefix: Data(env.device.publicKey.prefix(4)), text: "Retained A room retry", + timestamp: originalTimestamp, isFromSelf: true, status: .failed + ) + try await store.saveRoomMessage(roomMessage) + let directModel = configureChat(environment: env, conversation: .dm(contact)) + let channelModel = configureChat(environment: env, conversation: .channel(channel)) + _ = await directModel.primeInitialMessages(for: contact, populateMode: .refreshWindow) + _ = await channelModel.primeInitialChannelMessages(for: channel, populateMode: .refreshWindow) + let roomModel = RoomConversationViewModel() + roomModel.configure( + roomServerService: { env.appState.connectionSnapshot(for: room.radioID)?.services.roomServerService }, + dataStore: { env.appState.connectionSnapshot(for: room.radioID)?.services.dataStore }, + syncCoordinator: { env.appState.connectionSnapshot(for: room.radioID)?.services.syncCoordinator }, + notificationService: { env.appState.connectionSnapshot(for: room.radioID)?.services.notificationService } + ) + await roomModel.loadMessages(for: room) + return RetainedConversationPartitionHarness( + environment: env, canonicalRadioID: ghost.radioID, contact: contact, channel: channel, + room: room, directMessage: directMessage, channelMessage: channelMessage, roomMessage: roomMessage, + directModel: directModel, channelModel: channelModel, roomModel: roomModel, radio: radio + ) + } catch { + await env.close() + throw error + } + } + + func importCanonicalIdentity(includeSelectedTail: Bool = false) async throws { + let source = manager.currentConnection + let sourceAvailable = source != nil + try #require(sourceAvailable) + guard let source else { throw HarnessError.sourceUnavailable } + await radio.setIdentityImportPublicKey(Self.canonicalPublicKey) + try await source.services.nodeConfigService.importConfig( + MeshCoreNodeConfig( + privateKey: Self.privateKey, + otherSettings: includeSelectedTail ? .init(multiAcks: Self.selectedTailMultiAcks) : nil + ), sections: ConfigSections(nodeIdentity: true, otherSettings: includeSelectedTail), + radioID: environment.device.radioID + ) + try await waitUntil { + self.manager.connectionState == .ready && self.manager.connectedDevice?.radioID == self.canonicalRadioID + } + let handlePreserved = manager.connectedDevice?.id == environment.device.id + let partitionChanged = manager.connectedDevice?.radioID != environment.device.radioID + try #require(handlePreserved) + try #require(partitionChanged) + } + + func seedDirectPending() async throws -> PendingSendDTO { + await joinCurrentChatDrain() + let pending = PendingSendDTO( + id: UUID(), radioID: contact.radioID, messageID: directMessage.id, kind: .dm, + contactID: contact.id, channelIndex: nil, isResend: true, messageText: "Retained prior pending text", + messageTimestamp: Self.originalTimestamp, localNodeName: "Retained prior owner", sequence: Self.pendingSequence, + enqueuedAt: Date(timeIntervalSince1970: TimeInterval(Self.originalTimestamp)), attemptCount: Self.pendingAttempts + ) + try await store.upsertPendingSend(pending) + return pending + } + + func messageFrameCount() async -> Int { + await radio.sentData.filter { + $0.first == CommandCode.sendMessage.rawValue || $0.first == CommandCode.sendChannelMessage.rawValue + }.count + } + + func joinCurrentChatDrain() async { + await manager.services?.chatSendQueueService.awaitDrainCompletion() + } + + func proveLaterIO() async throws { + let time = try await manager.session?.getTime() + let exchangeCompleted = (time?.timeIntervalSince1970 ?? 0) > 0 + #expect(exchangeCompleted) + let info = try await manager.session?.sendAppStart() + let currentRadioAnswered = info != nil && info?.publicKey == manager.connectedDevice?.publicKey + #expect(currentRadioAnswered) + } + + func waitUntil(_ predicate: @escaping @MainActor () async -> Bool) async throws { + let deadline = ContinuousClock.now + Timing.timeout + while await !predicate() { + guard ContinuousClock.now < deadline else { throw HarnessError.timedOut } + try await Task.sleep(for: Timing.pollInterval) + } + } + + static func withHarness( + live: TransportType = .bluetooth, _ body: (RetainedConversationPartitionHarness) async throws -> Void + ) async throws { + let harness = try await make(live: live) + do { + try await body(harness) + await harness.environment.close() + } catch { + await harness.environment.close() + throw error + } + } + + private static func configureChat( + environment env: ConnectionLinkSwitchHarness, conversation: ChatConversationType + ) -> ChatViewModel { + let model = ChatViewModel() + model.configure( + dependencies: env.appState.makeChatViewModelDependencies(radioID: conversation.radioID), onNavigateToMap: nil, + linkPreviewCache: nil, chatCoordinatorRegistry: env.appState.ensureChatCoordinatorRegistry(), conversation: conversation + ) + return model + } + + private static func makeContact(radioID: UUID, type: ContactType, keyByte: UInt8) -> ContactDTO { + ContactDTO( + id: UUID(), radioID: radioID, publicKey: Data(repeating: keyByte, count: ProtocolLimits.publicKeySize), + name: "Retained A contact", typeRawValue: type.rawValue, flags: 0, outPathLength: 0, outPath: Data(), + lastAdvertTimestamp: 0, latitude: 0, longitude: 0, lastModified: 0, lastHeardTimestamp: nil, + nickname: nil, isBlocked: false, isMuted: false, isFavorite: false, lastMessageDate: nil, unreadCount: 0 + ) + } + + private enum HarnessError: Error { case sourceUnavailable, timedOut } + private enum Timing { + static let timeout: Duration = .seconds(10) + static let pollInterval: Duration = .milliseconds(1) + } + + private static let channelIndex: UInt8 = 0 + private static let channelSecret = Data(repeating: 0xCD, count: 16) + private static let originalTimestamp: UInt32 = 1_700_000_000 + private static let pendingSequence = 17 + private static let pendingAttempts = 3 + private static let selectedTailMultiAcks: UInt8 = 1 + private static let canonicalPublicKey = Data(repeating: 0xD5, count: ProtocolLimits.publicKeySize) + private static let privateKey = "7065e18fd9fabb70c1ed90dca19907de698c88b709ea146eafd93d9b830c7b60" + + "c4681193c79bbc39945ba8064104bb618f8fd7a84a0af6f57033d6e8ddcd6471" +} diff --git a/MC1Tests/Helpers/TestClock.swift b/MC1Tests/Helpers/TestClock.swift index a48b8e9253..957e937f5d 100644 --- a/MC1Tests/Helpers/TestClock.swift +++ b/MC1Tests/Helpers/TestClock.swift @@ -54,6 +54,14 @@ final class TestClock: Clock, @unchecked Sendable { return sleepers.count } + /// Time until the earliest parked deadline. `nil` when nobody is parked. + var nextSleepDuration: Duration? { + lock.lock() + defer { lock.unlock() } + guard let deadline = sleepers.map(\.deadline).min() else { return nil } + return _now.duration(to: deadline) + } + func sleep(until deadline: Instant, tolerance: Duration? = nil) async throws { let id = UUID() try await withTaskCancellationHandler { @@ -84,6 +92,22 @@ final class TestClock: Clock, @unchecked Sendable { } } + /// Moves virtual time to the earliest parked deadline and resumes those sleepers. + func advanceToNextSleep() { + lock.lock() + guard let next = sleepers.map(\.deadline).min() else { + lock.unlock() + return + } + _now = next + let due = sleepers.filter { $0.deadline <= _now } + sleepers.removeAll { $0.deadline <= _now } + lock.unlock() + for sleeper in due { + sleeper.continuation.resume() + } + } + /// Advances virtual time, resuming every sleeper whose deadline has passed. func advance(by duration: Duration = .zero) { lock.lock() diff --git a/MC1Tests/Intents/SendMessageIntentTests.swift b/MC1Tests/Intents/SendMessageIntentTests.swift index 6658c35b36..47a51bbbe0 100644 --- a/MC1Tests/Intents/SendMessageIntentTests.swift +++ b/MC1Tests/Intents/SendMessageIntentTests.swift @@ -330,35 +330,40 @@ struct SendMessageIntentTests { #expect(pending.isEmpty) } - // MARK: - enqueue-failure orphan recovery primitive - - /// `performSend`'s catch marks a persisted-but-unenqueued row `.failed` via - /// `updateMessageStatusUnlessDelivered` so an enqueue-write failure surfaces a - /// retry instead of hanging `.pending`. Forcing the enqueue itself to throw is - /// not reachable through any existing test seam (the queue persists through the - /// concrete in-memory `PersistenceStore`, which does not fail), so this pins - /// the recovery primitive on a real row built by production `createPendingMessage`: - /// a `.pending` row flips to `.failed`, while a `.delivered` row is left intact - /// so the recovery can never downgrade a delivered send. - @Test func `update message status unless delivered fails pending but spares delivered`() async throws { + // MARK: - Enqueue failure + + @Test(arguments: [false, true]) + func `enqueue failure retains one failed Message and reports send failed`(isChannel: Bool) async throws { let appState = AppState() + defer { appState.shutdown() } let services = try seedReady(appState, state: .ready) let contact = Self.makeContact() + let channel = Self.makeChannel() try await services.dataStore.saveContact(contact) + try await services.dataStore.saveChannel(channel) + await services.dataStore.setPendingSendInsertHandler { throw CocoaError(.fileWriteUnknown) } + let recipient: MessageRecipient = isChannel ? .channel(channel) : .contact(contact) + let text = "Keep one failed Message" - let pending = try await services.messageService.createPendingMessage(text: "queued", to: contact) - #expect(try await services.dataStore.fetchMessage(id: pending.id)?.status == .pending) - - let flipped = try await services.dataStore.updateMessageStatusUnlessDelivered(id: pending.id, status: .failed) - #expect(flipped) - #expect(try await services.dataStore.fetchMessage(id: pending.id)?.status == .failed) - - let delivered = try await services.messageService.createPendingMessage(text: "acked", to: contact) - try await services.dataStore.updateMessageAck(id: delivered.id, ackCode: 0x1234_5678, status: .delivered) + let thrown = await #expect(throws: IntentError.self) { + try await SendMessageIntent.performSend(message: text, recipient: recipient, in: appState) + } - let spared = try await services.dataStore.updateMessageStatusUnlessDelivered(id: delivered.id, status: .failed) - #expect(!spared) - #expect(try await services.dataStore.fetchMessage(id: delivered.id)?.status == .delivered) + #expect(try isCase(#require(thrown), .sendFailed)) + let messages = if isChannel { + try await services.dataStore.fetchMessages(radioID: Self.radioID, channelIndex: channel.index) + } else { + try await services.dataStore.fetchMessages(contactID: contact.id) + } + #expect(messages.count == 1) + let message = try #require(messages.first) + #expect(message.text == text) + #expect(message.status == .failed) + #expect(!message.failureSeen) + #expect(try await services.dataStore.fetchPendingSends(radioID: Self.radioID).isEmpty) + if !isChannel { + #expect(try await services.dataStore.fetchContact(id: contact.id)?.lastMessageDate == message.date) + } } // MARK: - .syncing takes the queue diff --git a/MC1Tests/MECP/MECPQuantityLineTests.swift b/MC1Tests/MECP/MECPQuantityLineTests.swift new file mode 100644 index 0000000000..32e5eab9d9 --- /dev/null +++ b/MC1Tests/MECP/MECPQuantityLineTests.swift @@ -0,0 +1,48 @@ +@testable import MC1Services +import Testing + +@Suite("MECP quantity line") +struct MECPQuantityLineTests { + @Test + func `each locale formats the person count with its plural rules`() { + let lines: [(Int, String, String)] = [ + (1, "en", "1 person"), + (3, "en", "3 people"), + (1, "de", "1 Person"), + (3, "de", "3 Personen"), + (1, "es", "1 persona"), + (3, "es", "3 personas"), + (1, "fr", "1 personne"), + (3, "fr", "3 personnes"), + (1, "it", "1 persona"), + (3, "it", "3 persone"), + (1, "nl", "1 persoon"), + (3, "nl", "3 personen"), + (1, "pt", "1 pessoa"), + (3, "pt", "3 pessoas"), + (1, "zh-Hans", "1 人"), + (3, "zh-Hans", "3 人"), + (1, "pl", "1 osoba"), + (2, "pl", "2 osoby"), + (5, "pl", "5 osób"), + (21, "pl", "21 osób"), + (22, "pl", "22 osoby"), + (1, "ru", "1 человек"), + (2, "ru", "2 человека"), + (5, "ru", "5 человек"), + (21, "ru", "21 человек"), + (22, "ru", "22 человека"), + (1, "uk", "1 людина"), + (2, "uk", "2 людини"), + (5, "uk", "5 людей"), + (21, "uk", "21 людина"), + (22, "uk", "22 людини"), + (1, "ko", "1 person"), + (3, "ko", "3 people"), + ] + for (count, localization, expected) in lines { + let line = MECPCatalog.quantityLine(count: count, preferredLocalization: localization, bundle: .main) + #expect(line == expected) + } + } +} diff --git a/MC1Tests/MECP/MessageVisibleBodyTests.swift b/MC1Tests/MECP/MessageVisibleBodyTests.swift new file mode 100644 index 0000000000..ff2b69826a --- /dev/null +++ b/MC1Tests/MECP/MessageVisibleBodyTests.swift @@ -0,0 +1,36 @@ +@testable import MC1 +@testable import MC1Services +import Testing + +@Suite("Message visible body") +struct MessageVisibleBodyTests { + @Test + func `a reading replaces the stored text and drops translation chrome`() throws { + let stored = "MECP/0/M01" + let offer = MessageTranslationChrome(phase: .offer, sourceLanguageCode: "de") + let visible = MessageVisibleBody(stored: stored, translation: offer) + let reading = try #require(MECPCatalog.reading(stored)) + + #expect(visible.plainText == reading) + #expect(visible.translation == nil) + #expect(visible.spokenText == L10n.Chats.Chats.Message.readingAccessibility( + reading.replacingOccurrences(of: "\n", with: " ") + )) + #expect(MessageVisibleBody.detailLine(storedText: stored) == L10n.Chats.Chats.Message.Info.mecp(stored)) + } + + @Test + func `ordinary text keeps a showing translation and has no detail line`() { + let showing = MessageTranslationChrome.Phase.showing( + translatedText: "Hello", + targetLanguageCode: "en" + ) + let chrome = MessageTranslationChrome(phase: showing, sourceLanguageCode: "de") + let visible = MessageVisibleBody(stored: "Guten Morgen", translation: chrome) + + #expect(visible.plainText == "Hello") + #expect(visible.translation == chrome) + #expect(visible.spokenText == L10n.Chats.Chats.Message.translatedAccessibility("Hello")) + #expect(MessageVisibleBody.detailLine(storedText: "Guten Morgen") == nil) + } +} diff --git a/MC1Tests/Models/WhatsNewVersionTests.swift b/MC1Tests/Models/WhatsNewVersionTests.swift index f4999dd110..55bf56a4e7 100644 --- a/MC1Tests/Models/WhatsNewVersionTests.swift +++ b/MC1Tests/Models/WhatsNewVersionTests.swift @@ -31,7 +31,7 @@ struct WhatsNewVersionTests { let lhs = WhatsNewVersion(marketingVersion: current) let rhs = WhatsNewVersion(marketingVersion: baseline) #expect(lhs == rhs) - #expect(try !(#require(lhs) > rhs!)) + #expect(try !(#require(lhs) > #require(rhs))) } @Test(arguments: [ diff --git a/MC1Tests/Protocol/LPPDataPointDisplayTests.swift b/MC1Tests/Protocol/LPPDataPointDisplayTests.swift index 090908035f..3390bb74c7 100644 --- a/MC1Tests/Protocol/LPPDataPointDisplayTests.swift +++ b/MC1Tests/Protocol/LPPDataPointDisplayTests.swift @@ -92,15 +92,49 @@ struct LPPDataPointDisplayTests { // MARK: - Locale Conversion Tests - @Test - func `Temperature conversion from Celsius to Fahrenheit`() { - let celsius = 25.0 - let converted = LPPSensorType.temperature.convertedValue(celsius) - if Locale.current.measurementSystem == .metric { - #expect(converted == celsius) - } else { - #expect(abs(converted - 77.0) < 0.01) - } + @Test(arguments: [ + (identifier: "en_US", expected: 77.0, symbol: "°F"), + (identifier: "en_GB", expected: 25.0, symbol: "°C"), + (identifier: "en_LR", expected: 25.0, symbol: "°C"), + (identifier: "de_DE", expected: 25.0, symbol: "°C"), + ]) + func `temperature uses the locale temperature unit`( + identifier: String, + expected: Double, + symbol: String + ) { + let locale = Locale(identifier: identifier) + let converted = LPPSensorType.temperature.convertedValue(25.0, locale: locale) + #expect(abs(converted - expected) < 0.01) + #expect(LPPSensorType.temperature.localizedUnitSymbol(for: locale) == symbol) + } + + @Test(arguments: [ + (identifier: "en_US", text: "29.92 inHg"), + (identifier: "en_GB", text: "1,013.2 mbar"), + (identifier: "en_LR", text: "1,013.2 hPa"), + (identifier: "de_DE", text: "1.013,2 hPa"), + (identifier: "ru_RU", text: "760 mmHg"), + ]) + func `barometer reading uses the locale pressure unit`(identifier: String, text: String) { + let locale = Locale(identifier: identifier) + let sample = 1013.2 + let value = LPPSensorType.barometer.convertedValue(sample, locale: locale) + let digits = LPPSensorType.barometer.convertedFractionLength(for: locale) + let symbol = LPPSensorType.barometer.localizedUnitSymbol(for: locale) + let formatted = value.formatted(.number.precision(.fractionLength(digits)).locale(locale)) + #expect(text == "\(formatted) \(symbol)") + } + + @Test(arguments: [ + (identifier: "en_US", symbol: "ft"), + (identifier: "en_GB", symbol: "ft"), + (identifier: "en_LR", symbol: "m"), + (identifier: "de_DE", symbol: "m"), + ]) + func `altitude uses the locale length unit`(identifier: String, symbol: String) { + let locale = Locale(identifier: identifier) + #expect(LPPSensorType.altitude.localizedUnitSymbol(for: locale) == symbol) } @Test @@ -110,14 +144,4 @@ struct LPPDataPointDisplayTests { #expect(converted == volts) #expect(LPPSensorType.voltage.localizedUnitSymbol == "V") } - - @Test - func `Altitude uses locale-appropriate unit symbol`() { - let symbol = LPPSensorType.altitude.localizedUnitSymbol - if Locale.current.measurementSystem == .metric { - #expect(symbol == "m") - } else { - #expect(symbol == "ft") - } - } } diff --git a/MC1Tests/RemoteNodes/SignInPathFooterTests.swift b/MC1Tests/RemoteNodes/SignInPathFooterTests.swift new file mode 100644 index 0000000000..aab5e29c47 --- /dev/null +++ b/MC1Tests/RemoteNodes/SignInPathFooterTests.swift @@ -0,0 +1,124 @@ +@testable import MC1 +import Testing + +@Suite("Sign-in path footer") +struct SignInPathFooterTests { + @Test + func `a cleared route stays cleared when the contact has no stored route`() { + let choice = signInPathFooter( + hasStoredRoute: false, + floodRouting: true, + routeCleared: true, + fallbackEnabled: false, + isAuthenticating: false + ) + + #expect(choice.message == L10n.RemoteNodes.RemoteNodes.Auth.floodFooterCleared) + #expect(choice.showsSavedHops == false) + #expect(choice.showsNoRouteLabel == false) + #expect(choice.showsFloodRoutingOn) + #expect(choice.canChangeFloodRouting == false) + } + + @Test + func `a cleared route stays cleared when flood routing is on`() { + let choice = signInPathFooter( + hasStoredRoute: true, + floodRouting: true, + routeCleared: true, + fallbackEnabled: false, + isAuthenticating: false + ) + + #expect(choice.message == L10n.RemoteNodes.RemoteNodes.Auth.floodFooterCleared) + #expect(choice.showsSavedHops == false) + #expect(choice.showsNoRouteLabel == false) + #expect(choice.showsFloodRoutingOn) + #expect(choice.canChangeFloodRouting == false) + } + + @Test(arguments: [false, true]) + func `no stored route shows flood routing and locks it`(floodRouting: Bool) { + let choice = signInPathFooter( + hasStoredRoute: false, + floodRouting: floodRouting, + routeCleared: false, + fallbackEnabled: !floodRouting, + isAuthenticating: false + ) + + #expect(choice.message == L10n.RemoteNodes.RemoteNodes.Auth.noRouteFooter) + #expect(choice.showsSavedHops == false) + #expect(choice.showsNoRouteLabel) + #expect(choice.showsFloodRoutingOn == floodRouting) + #expect(choice.canChangeFloodRouting == false) + } + + @Test + func `flood routing on a stored route uses the flood footer`() { + let choice = signInPathFooter( + hasStoredRoute: true, + floodRouting: true, + routeCleared: false, + fallbackEnabled: false, + isAuthenticating: false + ) + + #expect(choice.message == L10n.RemoteNodes.RemoteNodes.Auth.floodFooter) + #expect(choice.showsSavedHops == false) + #expect(choice.showsNoRouteLabel == false) + #expect(choice.showsFloodRoutingOn) + #expect(choice.canChangeFloodRouting) + } + + @Test(arguments: [false, true]) + func `a stored route with flood routing off follows path fallback`(fallbackEnabled: Bool) { + let choice = signInPathFooter( + hasStoredRoute: true, + floodRouting: false, + routeCleared: false, + fallbackEnabled: fallbackEnabled, + isAuthenticating: false + ) + + #expect( + choice.message == ( + fallbackEnabled + ? L10n.RemoteNodes.RemoteNodes.Auth.pathFooter + : L10n.RemoteNodes.RemoteNodes.Auth.pathFooterKept + ) + ) + #expect(choice.showsSavedHops) + #expect(choice.showsNoRouteLabel == false) + #expect(choice.showsFloodRoutingOn == false) + #expect(choice.canChangeFloodRouting) + } + + @Test(arguments: [false, true], [false, true]) + private func `an in-flight attempt on a stored route locks flood routing`( + floodRouting: Bool, + fallbackEnabled: Bool + ) { + let resting = signInPathFooter( + hasStoredRoute: true, + floodRouting: floodRouting, + routeCleared: false, + fallbackEnabled: fallbackEnabled, + isAuthenticating: false + ) + let waiting = signInPathFooter( + hasStoredRoute: true, + floodRouting: floodRouting, + routeCleared: false, + fallbackEnabled: fallbackEnabled, + isAuthenticating: true + ) + + #expect(resting.canChangeFloodRouting) + #expect(waiting.message == resting.message) + #expect(waiting.showsSavedHops == resting.showsSavedHops) + #expect(waiting.showsNoRouteLabel == resting.showsNoRouteLabel) + #expect(waiting.showsFloodRoutingOn == resting.showsFloodRoutingOn) + #expect(!waiting.canChangeFloodRouting) + } +} diff --git a/MC1Tests/Services/InlineImagePrefetcherTests.swift b/MC1Tests/Services/InlineImagePrefetcherTests.swift index 530eb216bf..4c3534c868 100644 --- a/MC1Tests/Services/InlineImagePrefetcherTests.swift +++ b/MC1Tests/Services/InlineImagePrefetcherTests.swift @@ -320,7 +320,6 @@ private actor StubDataStore: PersistenceStoreProtocol { func updateMessageStatus(id: UUID, status: MessageStatus) async throws {} func updateMessageAck(id: UUID, ackCode: UInt32, status: MessageStatus, roundTripTime: UInt32?) async throws {} func updateMessageRetryStatus(id: UUID, status: MessageStatus, retryAttempt: Int, maxRetryAttempts: Int) async throws {} - func updateMessageHeardRepeats(id: UUID, heardRepeats: Int) async throws {} func updateMessageLinkPreview(id: UUID, url: String?, title: String?, imageData: Data?, iconData: Data?, fetched: Bool) throws {} func fetchContacts(radioID: UUID) async throws -> [ContactDTO] { @@ -507,6 +506,7 @@ private actor StubDataStore: PersistenceStoreProtocol { func admitSentEcho( messageID: UUID, + expectedTimestamp: UInt32, receivedAt: Date, pathNodes: Data, pathLength: UInt8, @@ -517,12 +517,20 @@ private actor StubDataStore: PersistenceStoreProtocol { nil } - func deleteMessageRepeats(messageID: UUID) async throws {} func incrementMessageSendCount(id: UUID) async throws -> Int { 0 } func updateMessageTimestamp(id: UUID, timestamp: UInt32) async throws {} + func commitOutgoingDirectMessageTimestamp(id: UUID, timestamp: UInt32) async throws -> UInt32? { + nil + } + + func setPendingSendWireAttempt(id: UUID, to next: UInt8) async throws -> Bool { + false + } + + func prepareChannelMessageResend(id: UUID, timestamp: UInt32) async throws {} func saveDebugLogEntries(_ dtos: [DebugLogEntryDTO]) async throws {} func fetchDebugLogEntries(since date: Date, limit: Int) async throws -> [DebugLogEntryDTO] { @@ -656,28 +664,23 @@ private actor StubDataStore: PersistenceStoreProtocol { } func markMessageAsRead(id: UUID) async throws {} - func incrementPendingSendAttemptCount(messageID: UUID) async throws -> Int? { + func savePendingAcknowledgement(_ dto: PendingSendDTO, replacingPendingSendID: UUID?, markSent _: Bool) async throws -> Bool { + false + } + + func resolvePendingAcknowledgement(id: UUID, expectedDeadline: Date?, status: MessageStatus, ackCode: UInt32?, roundTripTime: UInt32?) async throws -> Bool { + false + } + + func preparePendingSendAttempt(messageID: UUID) async throws -> (pendingSendID: UUID, attemptCount: Int)? { nil } func saveDevice(_ dto: DeviceDTO) async throws {} - func updateDeviceNodeName(radioID: UUID, name: String) async throws {} - func updateDeviceCoordinates(radioID: UUID, latitude: Double, longitude: Double) async throws {} - func updateDeviceRadio( - radioID: UUID, - frequency: UInt32, - bandwidth: UInt32, - spreadingFactor: UInt8, - codingRate: UInt8, - appliedRadioPresetID: String? - ) async throws {} - func updateDeviceTxPower(radioID: UUID, txPower: Int8) async throws {} - func updateDeviceObservation(radioID: UUID, mapped: DeviceDTO) async throws {} - func updateDeviceOtherParams(radioID: UUID, intent: OtherParamsIntent) async throws {} - func updateDeviceClientRepeat(radioID: UUID, enabled: Bool) async throws {} - func updateDevicePathHashMode(radioID: UUID, mode: UInt8) async throws {} - func updateDeviceAutoAdd(radioID: UUID, config: UInt8, maxHops: UInt8) async throws {} - func updateDeviceDefaultFloodScopeName(radioID: UUID, name: String?) async throws {} + func updateDeviceOCVSettings(id: UUID, preset: String, customArray: String?) async throws -> DeviceDTO? { + nil + } + func fetchRemoteNodeSessionByPrefix(_ prefix: Data) async throws -> RemoteNodeSessionDTO? { nil } @@ -783,6 +786,23 @@ private actor StubDataStore: PersistenceStoreProtocol { func deleteOldNodeStatusSnapshots(olderThan date: Date) async throws {} + func recordSelfTelemetrySnapshot( + deviceID: UUID, + radioID: UUID, + nodePublicKey: Data, + telemetry: [TelemetrySnapshotEntry]?, + location: NodeLocationFix? + ) async throws -> UUID? { + nil + } + + func fetchSelfTelemetrySnapshots( + radioID: UUID, + nodePublicKey: Data + ) async throws -> [NodeStatusSnapshotDTO] { + [] + } + func upsertPendingSend(_ dto: PendingSendDTO) async throws {} func insertPendingSendAssigningSequence(_ dto: PendingSendDTO) async throws -> Int { 0 diff --git a/MC1Tests/Services/LinkPreviewCacheTests.swift b/MC1Tests/Services/LinkPreviewCacheTests.swift index 16e0eae079..5520645046 100644 --- a/MC1Tests/Services/LinkPreviewCacheTests.swift +++ b/MC1Tests/Services/LinkPreviewCacheTests.swift @@ -270,7 +270,6 @@ private actor MockPreviewDataStore: PersistenceStoreProtocol { func updateMessageStatus(id: UUID, status: MessageStatus) async throws {} func updateMessageAck(id: UUID, ackCode: UInt32, status: MessageStatus, roundTripTime: UInt32?) async throws {} func updateMessageRetryStatus(id: UUID, status: MessageStatus, retryAttempt: Int, maxRetryAttempts: Int) async throws {} - func updateMessageHeardRepeats(id: UUID, heardRepeats: Int) async throws {} func updateMessageLinkPreview(id: UUID, url: String?, title: String?, imageData: Data?, iconData: Data?, fetched: Bool) throws {} /// Contact Operations @@ -463,6 +462,7 @@ private actor MockPreviewDataStore: PersistenceStoreProtocol { func admitSentEcho( messageID: UUID, + expectedTimestamp: UInt32, receivedAt: Date, pathNodes: Data, pathLength: UInt8, @@ -473,12 +473,20 @@ private actor MockPreviewDataStore: PersistenceStoreProtocol { nil } - func deleteMessageRepeats(messageID: UUID) async throws {} func incrementMessageSendCount(id: UUID) async throws -> Int { 0 } func updateMessageTimestamp(id: UUID, timestamp: UInt32) async throws {} + func commitOutgoingDirectMessageTimestamp(id: UUID, timestamp: UInt32) async throws -> UInt32? { + nil + } + + func setPendingSendWireAttempt(id: UUID, to next: UInt8) async throws -> Bool { + false + } + + func prepareChannelMessageResend(id: UUID, timestamp: UInt32) async throws {} // Debug Log Entries func saveDebugLogEntries(_ dtos: [DebugLogEntryDTO]) async throws {} @@ -627,28 +635,23 @@ private actor MockPreviewDataStore: PersistenceStoreProtocol { } func markMessageAsRead(id: UUID) async throws {} - func incrementPendingSendAttemptCount(messageID: UUID) async throws -> Int? { + func savePendingAcknowledgement(_ dto: PendingSendDTO, replacingPendingSendID: UUID?, markSent _: Bool) async throws -> Bool { + false + } + + func resolvePendingAcknowledgement(id: UUID, expectedDeadline: Date?, status: MessageStatus, ackCode: UInt32?, roundTripTime: UInt32?) async throws -> Bool { + false + } + + func preparePendingSendAttempt(messageID: UUID) async throws -> (pendingSendID: UUID, attemptCount: Int)? { nil } func saveDevice(_ dto: DeviceDTO) async throws {} - func updateDeviceNodeName(radioID: UUID, name: String) async throws {} - func updateDeviceCoordinates(radioID: UUID, latitude: Double, longitude: Double) async throws {} - func updateDeviceRadio( - radioID: UUID, - frequency: UInt32, - bandwidth: UInt32, - spreadingFactor: UInt8, - codingRate: UInt8, - appliedRadioPresetID: String? - ) async throws {} - func updateDeviceTxPower(radioID: UUID, txPower: Int8) async throws {} - func updateDeviceObservation(radioID: UUID, mapped: DeviceDTO) async throws {} - func updateDeviceOtherParams(radioID: UUID, intent: OtherParamsIntent) async throws {} - func updateDeviceClientRepeat(radioID: UUID, enabled: Bool) async throws {} - func updateDevicePathHashMode(radioID: UUID, mode: UInt8) async throws {} - func updateDeviceAutoAdd(radioID: UUID, config: UInt8, maxHops: UInt8) async throws {} - func updateDeviceDefaultFloodScopeName(radioID: UUID, name: String?) async throws {} + func updateDeviceOCVSettings(id: UUID, preset: String, customArray: String?) async throws -> DeviceDTO? { + nil + } + func fetchRemoteNodeSessionByPrefix(_ prefix: Data) async throws -> RemoteNodeSessionDTO? { nil } @@ -756,6 +759,23 @@ private actor MockPreviewDataStore: PersistenceStoreProtocol { func deleteOldNodeStatusSnapshots(olderThan date: Date) async throws {} + func recordSelfTelemetrySnapshot( + deviceID: UUID, + radioID: UUID, + nodePublicKey: Data, + telemetry: [TelemetrySnapshotEntry]?, + location: NodeLocationFix? + ) async throws -> UUID? { + nil + } + + func fetchSelfTelemetrySnapshots( + radioID: UUID, + nodePublicKey: Data + ) async throws -> [NodeStatusSnapshotDTO] { + [] + } + // Pending Sends func upsertPendingSend(_ dto: PendingSendDTO) async throws {} func insertPendingSendAssigningSequence(_ dto: PendingSendDTO) async throws -> Int { diff --git a/MC1Tests/Services/LogExportLifecycleTests.swift b/MC1Tests/Services/LogExportLifecycleTests.swift new file mode 100644 index 0000000000..7bc31f6dae --- /dev/null +++ b/MC1Tests/Services/LogExportLifecycleTests.swift @@ -0,0 +1,250 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Lifecycle diagnostic export", .serialized, .timeLimit(.minutes(1))) +@MainActor +struct LogExportLifecycleTests { + @Test + func `real disconnect export retains the retired Link and request without payload fields`() async throws { + let run = try Harness() + do { + await run.manager.wireTransportHandlers() + _ = try await run.manager.connect(to: run.deviceID, forceFullSync: true, forceReconnect: true) + let link = try #require(run.manager.installedLink) + let request = try #require(run.manager.desiredRequest) + let attempt = try #require(request.attempt) + let origin = try #require(request.physicalOrigin) + run.trackBuffer(link.services.debugLogBuffer) + #expect(run.manager.connectionState == .ready) + #expect(try await link.resource.session.getBattery().level == 3700) + let appWorkers = run.trackAppWorkers() + run.reclaimLogs() + + _ = await run.manager.disconnect(reason: .userInitiated) + for worker in appWorkers { + await worker.value + } + + let currentRequestID = try #require(run.manager.connectionRequestID) + let fields = [ + "request=\(request.id)", "attempt=\(ObjectIdentifier(attempt))", "link=\(link.generation)", + "binding=\(ObjectIdentifier(link.resource.binding))", "session=\(ObjectIdentifier(link.resource.session))", + "physicalGeneration=\(origin.generation)", "device=\(link.device.id.uuidString.prefix(8))" + ] + let records = [ + ["event=disconnectAdmitted,", "request=\(currentRequestID)", "currentLink=\(link.generation)", + "currentBinding=\(ObjectIdentifier(link.resource.binding))", "reason=\(DisconnectReason.userInitiated.rawValue)"], + ["event=dispose,", "currentRequest=\(currentRequestID)"] + fields, + ["event=state,", "request=\(currentRequestID)", "currentRequest=\(currentRequestID)", + "state=disconnected", "link=none"] + ] + let exported = try await run.exportedLogs(until: records, containing: ["Intent: userDisconnected"]) + Attachment.record(exported, named: "connection-lifecycle-export.txt") + let lines = exported.split(separator: "\n").map(String.init).filter { $0.contains("[ConnectionLifecycle]") } + for fields in records { + #expect(lines.contains { line in fields.allSatisfy(line.contains) }, + "Export must retain each exact owner and terminal record") + } + #expect(exported.contains("Intent: userDisconnected")) + #expect(run.manager.currentConnection == nil) + #expect(await run.radio.disconnectCount == 1) + for line in lines { + for forbidden in ["payload=", "password=", "pin=", "secret=", "publicKey=", "host=", "ssid="] { + #expect(!line.localizedCaseInsensitiveContains(forbidden)) + } + } + } catch { await run.close(); throw error } + await run.close() + } + + @Test + func `real same-radio recovery export retains the request and replacement stack`() async throws { + let run = try Harness() + do { + await run.manager.wireTransportHandlers() + _ = try await run.manager.connect(to: run.deviceID, forceFullSync: true, forceReconnect: true) + let first = try #require(run.manager.installedLink) + let request = try #require(run.manager.desiredRequest) + let firstAttempt = try #require(request.attempt) + run.trackBuffer(first.services.debugLogBuffer) + let firstWorkers = run.trackAppWorkers() + run.reclaimLogs() + #expect(try await first.resource.session.getBattery().level == 3700) + + await run.radio.simulateAutoReconnecting(deviceID: run.deviceID) + try await waitUntil("loss handling must join retirement") { run.handledEvents.count == 1 } + guard case .autoReconnecting = run.handledEvents.first else { + Issue.record("The first completed lifecycle event must be auto-reconnecting") + await run.close() + return + } + let cycle = try #require(run.manager.reconnectionCoordinator.currentCycle) + let lossOrigin = try #require(request.physicalOrigin) + #expect(run.manager.connectionState == .connecting) + #expect(run.manager.installedLink == nil) + #expect(run.manager.desiredRequest === request) + #expect(!first.resource.binding.isActive) + await #expect(throws: CancellationError.self) { try await first.resource.session.start() } + #expect(run.manager.connectionTeardownCount == 0) + #expect(await run.radio.disconnectCount == 0) + + await run.radio.simulateReconnected() + try await waitUntil("reconnection handling must join the rebuilt stack") { run.handledEvents.count == 2 } + guard case .reconnected = run.handledEvents.last else { + Issue.record("The second completed lifecycle event must be reconnected") + await run.close() + return + } + let next = try #require(run.manager.installedLink) + let nextAttempt = try #require(request.attempt) + run.trackBuffer(next.services.debugLogBuffer) + _ = run.trackAppWorkers() + for worker in firstWorkers { + await worker.value + } + run.reclaimLogs() + #expect(run.manager.connectionState == .ready) + #expect(run.manager.desiredRequest === request) + #expect(run.manager.reconnectionCoordinator.currentCycle == nil) + #expect(next.generation != first.generation) + #expect(next.resource !== first.resource) + #expect(next.resource.binding !== first.resource.binding) + #expect(next.resource.session !== first.resource.session) + #expect(next.resource.binding.isActive) + #expect(next.device.id == first.device.id) + #expect(next.device.radioID == first.device.radioID) + #expect(try await next.resource.session.getBattery().level == 3700) + #expect(await run.radio.connectCount == 1) + #expect(await run.radio.disconnectCount == 0) + + let nextOwner = "request=\(request.id), attempt=\(ObjectIdentifier(nextAttempt)), link=\(next.generation)" + let common = ["request=\(request.id)", "reconnectCycle=\(cycle.id)", "reconnectGeneration=\(cycle.generation)"] + let retired = common + [ + "attempt=\(ObjectIdentifier(firstAttempt))", "link=\(first.generation)", + "binding=\(ObjectIdentifier(first.resource.binding))", "session=\(ObjectIdentifier(first.resource.session))", + "physicalGeneration=\(lossOrigin.generation)", "reason=preservePhysical" + ] + let successor = common + [ + "binding=\(ObjectIdentifier(next.resource.binding))", "session=\(ObjectIdentifier(next.resource.session))" + ] + let records = [ + ["event=dispose,"] + retired, + ["event=retired,"] + retired, + ["event=attemptStarted,", "attempt=\(ObjectIdentifier(nextAttempt))", + "binding=\(ObjectIdentifier(next.resource.binding))"] + common, + ["event=published, \(nextOwner)", "state=syncing"] + successor, + ["event=state, \(nextOwner)", "state=ready"] + successor + ] + let diagnostic = try #require(run.manager.lastDisconnectDiagnostic) + #expect(diagnostic.contains("source=ble.autoReconnecting, device=\(run.deviceID.uuidString.prefix(8)),")) + let diagnosticHeader = "Last Disconnect Diagnostic: \(diagnostic)" + let exported = try await run.exportedLogs(until: records, containing: [diagnosticHeader, "State: ready"]) + Attachment.record(exported, named: "recovery-lifecycle-export.txt") + let lines = exported.split(separator: "\n").map(String.init).filter { $0.contains("[ConnectionLifecycle]") } + for fields in records { + #expect(lines.contains { line in fields.allSatisfy(line.contains) }, + "Export must retain each exact request, Cycle and stack boundary") + } + #expect(exported.contains(diagnosticHeader)) + #expect(exported.contains("State: ready")) + } catch { await run.close(); throw error } + await run.close() + } + + @MainActor + private final class Harness { + let app: AppState + let manager: ConnectionManager + let radio = ConnectionTestRadioTransport() + let deviceID = UUID() + private let defaults: UserDefaults + private let suite = "test.lifecycle-export.\(UUID().uuidString)" + private let previousBuffer = DebugLogBuffer.shared + private let previousCollectionValue = UserDefaults.standard.object(forKey: AppStorageKey.collectDebugLogs.rawValue) + private let bootstrap: DebugLogBuffer + private var ownedBuffers: [DebugLogBuffer] + private var appWorkers: [Task] = [] + var handledEvents: [BLELifecycleEvent] = [] + private static let settleTimeout: Duration = .seconds(2) + private static let pollInterval: Duration = .milliseconds(10) + + init() throws { + defaults = try #require(UserDefaults(suiteName: suite)) + let container = try PersistenceStore.createContainer(inMemory: true) + let pairing = MockAccessorySetupKitService() + pairing.isSessionActive = false + manager = ConnectionManager( + modelContainer: container, defaults: defaults, stateMachine: MockBLEStateMachine(), transport: radio, + pairing: AccessorySetupPairingService(accessorySetupKit: pairing) + ) + app = AppState(modelContainer: container, isPlaceholder: true, defaults: defaults, injectedConnectionManager: manager) + bootstrap = DebugLogBuffer(dataStore: manager.persistenceStore) + ownedBuffers = [bootstrap] + DebugLogBuffer.shared = bootstrap + manager.testBLELifecycleEventHandled = { [weak self] event in self?.handledEvents.append(event) } + UserDefaults.standard.set(true, forKey: AppStorageKey.collectDebugLogs.rawValue) + } + + func trackAppWorkers() -> [Task] { + let workers = [app.settingsEventsTask, app.syncDataEventsTask, + app.advertisementEventsTask, app.rxLogEventsTask].compactMap(\.self) + appWorkers.append(contentsOf: workers) + return workers + } + + func trackBuffer(_ buffer: DebugLogBuffer) { + ownedBuffers.append(buffer) + } + + func reclaimLogs() { + DebugLogBuffer.shared = bootstrap + } + + func exportedLogs(until records: [[String]], containing markers: [String]) async throws -> String { + let deadline = ContinuousClock.now + Self.settleTimeout + var exported = "" + repeat { + for buffer in ownedBuffers { + await buffer.flush() + } + exported = await LogExportService.generateExport(appState: app, persistenceStore: manager.persistenceStore) + let lines = exported.split(separator: "\n").map(String.init).filter { $0.contains("[ConnectionLifecycle]") } + let hasRecords = records.allSatisfy { fields in + lines.contains { line in fields.allSatisfy(line.contains) } + } + if hasRecords, markers.allSatisfy(exported.contains) { break } + try await Task.sleep(for: Self.pollInterval) + } while ContinuousClock.now < deadline + return exported + } + + func close() async { + manager.testBLELifecycleEventHandled = nil + await radio.releaseAllGates() + _ = trackAppWorkers() + _ = await manager.disconnect(reason: .userInitiated) + await manager.retirementTask?.value + await manager.metadataCommitTask?.value + app.tearDownAppStateSessionState() + for worker in appWorkers { + await worker.value + } + app.shutdown() + for buffer in ownedBuffers { + await buffer.shutdown() + } + defaults.removePersistentDomain(forName: suite) + if let current = DebugLogBuffer.shared, ownedBuffers.contains(where: { $0 === current }) { + DebugLogBuffer.shared = previousBuffer + } + if let previousCollectionValue { + UserDefaults.standard.set(previousCollectionValue, forKey: AppStorageKey.collectDebugLogs.rawValue) + } else { + UserDefaults.standard.removeObject(forKey: AppStorageKey.collectDebugLogs.rawValue) + } + } + } +} diff --git a/MC1Tests/State/ChatPrewarmRefresherTests.swift b/MC1Tests/State/ChatPrewarmRefresherTests.swift index 8ed2579ff2..67e11e3957 100644 --- a/MC1Tests/State/ChatPrewarmRefresherTests.swift +++ b/MC1Tests/State/ChatPrewarmRefresherTests.swift @@ -31,7 +31,6 @@ struct ChatPrewarmRefresherTests { connectionState: { .disconnected }, connectedDevice: { nil }, currentRadioID: { nil }, - session: { nil }, reactionService: { nil }, chatSendQueueService: { nil }, inlineImageDimensionsStore: { nil }, diff --git a/MC1Tests/State/ChatTimelineFreshnessTests.swift b/MC1Tests/State/ChatTimelineFreshnessTests.swift index f4e07b09ca..42535694e0 100644 --- a/MC1Tests/State/ChatTimelineFreshnessTests.swift +++ b/MC1Tests/State/ChatTimelineFreshnessTests.swift @@ -157,7 +157,8 @@ struct ChatTimelineFreshnessTests { envInputs: .default, senderTables: { .empty }, postApply: nil, - anchorSortDate: nil + anchorSortDate: nil, + isCurrent: { writer.isCurrent } ) guard case .loaded = outcome else { Issue.record("populate outcome was \(outcome), expected .loaded") @@ -224,7 +225,8 @@ struct ChatTimelineFreshnessTests { envInputs: .default, senderTables: { tables }, postApply: nil, - anchorSortDate: nil + anchorSortDate: nil, + isCurrent: { writer.isCurrent } ) guard case .loaded = outcome else { Issue.record("populate outcome was \(outcome), expected .loaded") @@ -333,11 +335,15 @@ struct ChatTimelineFreshnessTests { @Test func `a still-alive interactive owner cannot starve the arrival refresh after close`() async throws { - let appState = AppState() - appState.connectionManager.testLastConnectedDeviceID = UUID() + let suiteName = "test.timeline-source.\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + let appState = AppState(defaults: defaults) + defer { appState.shutdown() } + let radioID = UUID() + appState.connectionManager.persistConnection(deviceID: UUID(), radioID: radioID, deviceName: "Fixture") let store = try #require(appState.offlineDataStore) - let radioID = UUID() let contact = makeContact(radioID: radioID) try await store.saveContact(contact) try await store.saveMessage(makeDirectMessage(radioID: radioID, contactID: contact.id, timestamp: 1000, text: "old")) @@ -355,7 +361,7 @@ struct ChatTimelineFreshnessTests { // A live open: the interactive view model binds the writer and populates. let viewModel = ChatViewModel() viewModel.configure( - dependencies: appState.makeChatViewModelDependencies(), + dependencies: appState.makeChatViewModelDependencies(radioID: contact.radioID), onNavigateToMap: nil, linkPreviewCache: nil, chatCoordinatorRegistry: registry, diff --git a/MC1Tests/State/ConnectionManagerDeleteDeviceTests.swift b/MC1Tests/State/ConnectionManagerDeleteDeviceTests.swift index fc7ae3ec72..b1de563251 100644 --- a/MC1Tests/State/ConnectionManagerDeleteDeviceTests.swift +++ b/MC1Tests/State/ConnectionManagerDeleteDeviceTests.swift @@ -169,7 +169,7 @@ import Testing try await env.manager.deleteDevice(id: deviceID) - #expect(env.manager.connectingDeviceID == nil) + #expect(env.manager.activeConnectionAttemptDeviceID == nil) #expect(env.manager.connectionState == .disconnected) #expect(env.manager.connectionIntent.isUserDisconnected) #expect(env.mockASK.accessory(for: deviceID) == nil) diff --git a/MC1Tests/State/DeviceSelectionConnectionTests.swift b/MC1Tests/State/DeviceSelectionConnectionTests.swift index db4900e518..7e2b5df42a 100644 --- a/MC1Tests/State/DeviceSelectionConnectionTests.swift +++ b/MC1Tests/State/DeviceSelectionConnectionTests.swift @@ -22,62 +22,52 @@ struct DeviceSelectionConnectionTests { @Test func `the default dismissal handler dials the captured wifi endpoint`() async throws { - let harness = try makeHarness() + let wifi = ConnectionTestRadioTransport() + await wifi.setConnectError(BLEError.connectionTimeout) + let harness = try makeHarness(wifi: wifi) defer { harness.cleanup() } - harness.appState.connectionManager.testWiFiConnectHandler = { _, _ in - throw BLEError.connectionTimeout - } harness.appState.connectionUI.queueSavedDeviceConnection( makeDevice(), target: .wifi(host: "radio.local", port: 4242) ) - #expect(harness.appState.connectionManager.testWiFiConnectAttempts.isEmpty) + #expect(await wifi.connectCount == 0) harness.appState.handleDeviceSelectionSheetDismissed() try await waitUntil("wifi should be attempted after dismissal") { harness.appState.connectionUI.showingConnectionFailedAlert } - let attempts = harness.appState.connectionManager.testWiFiConnectAttempts - #expect(attempts.count == 1) - #expect(attempts.first?.host == "radio.local") - #expect(attempts.first?.port == 4242) + #expect(await wifi.connectCount == 1) + let endpoint = await wifi.connectionInfo + #expect(endpoint?.host == "radio.local") + #expect(endpoint?.port == 4242) } @Test func `choosing bluetooth while the same radio is connected over wifi starts a transport switch`() async throws { - let transport = MockMeshTransport() - await transport.setConnectError(BLEError.authenticationFailed) - let harness = try makeHarness(transport: transport) - defer { harness.cleanup() } - var device = makeDevice() - let peripheralID = try #require(device.bluetoothPeripheralID) - device.id = peripheralID - device.connectionMethods.reverse() - harness.appState.connectionManager.setTestState( - connectionState: .ready, - connectedDevice: device, - currentTransportType: .wifi, - connectionIntent: .wantsConnection() - ) - harness.appState.connectionManager.wifiTransport = WiFiTransport() - harness.appState.connectionUI.queueSavedDeviceConnection(device, target: .bluetooth(peripheralID: peripheralID)) - #expect(await transport.connectInvocations.isEmpty) - #expect(!harness.appState.connectionUI.showingConnectionFailedAlert) + try await ConnectionLinkSwitchHarness.withHarness(live: .wifi, wifiHost: "radio.local", wifiPort: 4242) { harness in + await harness.bluetooth.setConnectError(BLEError.authenticationFailed) + let device = harness.device + let peripheralID = try #require(device.bluetoothPeripheralID) + harness.appState.connectionUI.queueSavedDeviceConnection(device, target: .bluetooth(peripheralID: peripheralID)) + #expect(await harness.bluetooth.connectCount == harness.initialBluetoothAttempts) + #expect(!harness.appState.connectionUI.showingConnectionFailedAlert) - harness.appState.handleDeviceSelectionSheetDismissed() - try await waitUntil(timeout: .seconds(2), "the selected Bluetooth transport should be dialed") { - harness.appState.connectionUI.showingConnectionFailedAlert - } - harness.appState.handleDeviceSelectionSheetDismissed() + harness.appState.handleDeviceSelectionSheetDismissed() + try await waitUntil("the selected Bluetooth transport should be dialed") { + harness.appState.connectionUI.showingConnectionFailedAlert + } + harness.appState.handleDeviceSelectionSheetDismissed() - #expect(await transport.connectInvocations.compactMap(\.deviceID) == [peripheralID]) - #expect(harness.appState.connectionUI.queuedSavedDeviceConnection == nil) - #expect(harness.appState.connectionManager.wifiTransport == nil) - #expect(harness.appState.connectedDevice == nil) - #expect(harness.appState.connectionManager.connectionIntent == .wantsConnection(forceFullSync: true)) - #expect(harness.appState.connectionUI.failedPairingDeviceID == device.id) - #expect(harness.appState.connectionUI.pairingFailureKind == .authentication) + #expect(await harness.bluetooth.connectCount == harness.initialBluetoothAttempts + 1) + #expect(await harness.bluetooth.sessionDeviceIDs.last == peripheralID) + #expect(harness.appState.connectionUI.queuedSavedDeviceConnection == nil) + #expect(harness.manager.wifiTransport == nil) + #expect(harness.appState.connectedDevice == nil) + #expect(harness.manager.connectionIntent == .wantsConnection(forceFullSync: true)) + #expect(harness.appState.connectionUI.failedPairingDeviceID == device.id) + #expect(harness.appState.connectionUI.pairingFailureKind == .authentication) + } } private struct Harness { @@ -85,7 +75,7 @@ struct DeviceSelectionConnectionTests { let cleanup: () -> Void } - private func makeHarness(transport: MockMeshTransport? = nil) throws -> Harness { + private func makeHarness(wifi: ConnectionTestRadioTransport = ConnectionTestRadioTransport()) throws -> Harness { let suite = "test.deviceselection.\(UUID().uuidString)" let defaults = try #require(UserDefaults(suiteName: suite)) let container = try PersistenceStore.createContainer(inMemory: true) @@ -94,8 +84,10 @@ struct DeviceSelectionConnectionTests { let manager = ConnectionManager( modelContainer: container, defaults: defaults, - transport: transport, - pairing: AccessorySetupPairingService(accessorySetupKit: mockASK) + stateMachine: MockBLEStateMachine(), + transport: MockMeshTransport(), + pairing: AccessorySetupPairingService(accessorySetupKit: mockASK), + makeWiFiTransport: { wifi } ) let appState = AppState( modelContainer: container, diff --git a/MC1Tests/State/LiveActivityManagerTests.swift b/MC1Tests/State/LiveActivityManagerTests.swift index 5cd3c71bc8..a3dba56492 100644 --- a/MC1Tests/State/LiveActivityManagerTests.swift +++ b/MC1Tests/State/LiveActivityManagerTests.swift @@ -40,4 +40,33 @@ struct LiveActivityManagerTests { let timestamps = (1...3).map { now.addingTimeInterval(-Double($0)) } #expect(LiveActivityManager.packetsPerMinute(timestamps: timestamps, now: now, window: 15) == 12) } + + @Test + func `unchanged content waits until the stale date is close`() { + let state = sampleState(packetsPerMinute: 4) + #expect(!LiveActivityManager.shouldPublishUpdate( + current: state, + proposed: state, + currentStaleDate: now.addingTimeInterval(50), + now: now, + refreshLeadTime: 30 + )) + #expect(LiveActivityManager.shouldPublishUpdate( + current: state, + proposed: state, + currentStaleDate: now.addingTimeInterval(30), + now: now, + refreshLeadTime: 30 + )) + } + + private func sampleState(packetsPerMinute: Int) -> MeshStatusAttributes.ContentState { + MeshStatusAttributes.ContentState( + isConnected: true, + batteryPercent: nil, + packetsPerMinute: packetsPerMinute, + unreadCount: 0, + disconnectedDate: nil + ) + } } diff --git a/MC1Tests/State/SystemPairingSetupAppStateTests.swift b/MC1Tests/State/SystemPairingSetupAppStateTests.swift index 3f58311413..0722911d62 100644 --- a/MC1Tests/State/SystemPairingSetupAppStateTests.swift +++ b/MC1Tests/State/SystemPairingSetupAppStateTests.swift @@ -108,7 +108,7 @@ struct SystemPairingSetupAppStateTests { harness.appState.confirmSystemPairingSetup() try await waitUntil(timeout: .seconds(2), "first picker attempt should finish") { !harness.appState.connectionUI.isBusy - && harness.appState.connectionUI.shouldCompleteFreshPairingOnForeground + && harness.appState.shouldCompleteFreshPairingOnForeground } #expect(harness.appState.connectionUI.showingConnectionFailedAlert == false) @@ -123,10 +123,69 @@ struct SystemPairingSetupAppStateTests { } #expect(harness.appState.connectionUI.showingConnectionFailedAlert == false) - #expect(harness.appState.connectionUI.shouldCompleteFreshPairingOnForeground == false) + #expect(harness.appState.shouldCompleteFreshPairingOnForeground == false) #expect(!harness.appState.connectionManager.shouldDeferOpportunisticReconnect) } + @Test + func `a second restricted picker ends the foreground retry with an error`() async throws { + let harness = try makeHarness() + defer { harness.cleanup() } + harness.mockASK.setPickerResult(.failure(AccessorySetupKitError.pickerRestricted)) + + harness.appState.startDeviceScan() + await harness.appState.freshPairingTask?.value + #expect(harness.appState.shouldCompleteFreshPairingOnForeground) + + harness.appState.handleBecameActive() + await harness.appState.freshPairingTask?.value + + #expect(harness.mockASK.showPickerCallCount == 2) + #expect(harness.appState.connectionUI.showingConnectionFailedAlert) + #expect(harness.appState.connectionUI.connectionFailedMessage == L10n.Localizable.Error.AccessorySetup.pickerRestricted) + #expect(!harness.appState.shouldCompleteFreshPairingOnForeground) + #expect(!harness.appState.connectionUI.isBusy) + #expect(!harness.appState.connectionManager.shouldDeferOpportunisticReconnect) + harness.appState.handleBecameActive() + #expect(harness.mockASK.showPickerCallCount == 2) + harness.appState.shutdown() + } + + @Test + func `repeated foreground callbacks admit only one picker retry`() async throws { + let harness = try makeHarness() + defer { harness.cleanup() } + harness.mockASK.setPickerResult(.failure(AccessorySetupKitError.pickerRestricted)) + harness.appState.startDeviceScan() + await harness.appState.freshPairingTask?.value + #expect(harness.appState.shouldCompleteFreshPairingOnForeground) + + let gate = AsyncStream.makeStream() + defer { gate.continuation.finish() } + harness.mockASK.beforePickerResultAsync = { + for await _ in gate.stream { + break + } + } + harness.mockASK.setPickerResult(.failure(AccessorySetupKitError.pickerDismissed)) + harness.appState.handleBecameActive() + harness.appState.handleBecameActive() + try await waitUntil(timeout: .seconds(2), "the retry should enter the picker") { + harness.mockASK.showPickerCallCount == 2 + } + harness.appState.handleBecameActive() + + #expect(harness.appState.connectionUI.isBusy) + #expect(!harness.appState.shouldCompleteFreshPairingOnForeground) + gate.continuation.finish() + await harness.appState.freshPairingTask?.value + #expect(harness.mockASK.showPickerCallCount == 2) + #expect(!harness.appState.connectionUI.isBusy) + #expect(!harness.appState.connectionManager.shouldDeferOpportunisticReconnect) + #expect(!harness.appState.connectionUI.showingConnectionFailedAlert) + harness.appState.shutdown() + } + @Test func `auth failure after Forget routes through presentFreshPairingFailure`() async throws { let harness = try makeHarness(injectTransport: true) @@ -300,35 +359,26 @@ struct SystemPairingSetupAppStateTests { harness.appState.connectionUI.pendingSystemPairingSetup = SystemPairingSetupPrompt( accessories: [SystemPairedAccessory(id: id, name: "B")] ) - harness.appState.connectionUI.shouldShowPickerOnForeground = true harness.appState.connectionManager.isPairingFlowActive = true harness.appState.handleBecameActive() - #expect(harness.appState.connectionUI.shouldShowPickerOnForeground) #expect(harness.appState.connectionUI.pendingSystemPairingSetup?.accessories.map(\.id) == [id]) #expect(harness.appState.connectionUI.isBusy == false) #expect(harness.mockASK.showPickerCallCount == 0) } @Test - func `became-active picker retry still scans when no setup prompt is pending`() async throws { + func `became-active without a pairing operation does not open a picker`() throws { let harness = try makeHarness() defer { harness.cleanup() } let id = UUID() - harness.mockASK.setPairedAccessories([ - ASAccessory(bluetoothIdentifier: id, displayName: "B") - ]) - harness.appState.connectionUI.shouldShowPickerOnForeground = true + harness.mockASK.setPairedAccessories([ASAccessory(bluetoothIdentifier: id, displayName: "B")]) harness.appState.handleBecameActive() - try await waitUntil(timeout: .seconds(2), "foreground scan should set the prompt") { - harness.appState.connectionUI.pendingSystemPairingSetup != nil - && !harness.appState.connectionUI.isBusy - } - #expect(harness.appState.connectionUI.shouldShowPickerOnForeground == false) - #expect(harness.appState.connectionUI.pendingSystemPairingSetup?.accessories.map(\.id) == [id]) + #expect(harness.appState.connectionUI.pendingSystemPairingSetup == nil) + #expect(!harness.appState.connectionUI.isBusy) #expect(harness.mockASK.showPickerCallCount == 0) } @@ -347,6 +397,42 @@ struct SystemPairingSetupAppStateTests { #expect(!harness.appState.connectionManager.shouldDeferOpportunisticReconnect) } + @Test + func `setup-sheet dismissal after removal preserves the initial picker`() async throws { + let harness = try makeHarness() + defer { harness.cleanup() } + let id = UUID() + harness.mockASK.setPairedAccessories([ASAccessory(bluetoothIdentifier: id, displayName: "Radio")]) + harness.appState.connectionUI.pendingSystemPairingSetup = SystemPairingSetupPrompt( + accessories: [SystemPairedAccessory(id: id, name: "Radio")] + ) + let gate = AsyncStream.makeStream() + defer { gate.continuation.finish() } + harness.mockASK.beforePickerResultAsync = { + for await _ in gate.stream { + break + } + } + harness.mockASK.setPickerResult(.failure(AccessorySetupKitError.pickerDismissed)) + + harness.appState.confirmSystemPairingSetup() + try await waitUntil(timeout: .seconds(2), "removal should advance to the picker") { + harness.mockASK.showPickerCallCount == 1 + } + harness.appState.handleSystemPairingSetupSheetDismissed() + + #expect(harness.mockASK.removeAccessoryCallCount == 1) + #expect(harness.appState.connectionUI.isBusy) + #expect(harness.appState.connectionManager.shouldDeferOpportunisticReconnect) + let worker = try #require(harness.appState.freshPairingTask) + #expect(!worker.isCancelled) + gate.continuation.finish() + await worker.value + #expect(!harness.appState.connectionUI.isBusy) + #expect(!harness.appState.connectionManager.shouldDeferOpportunisticReconnect) + #expect(!harness.appState.connectionUI.showingConnectionFailedAlert) + } + @Test func `setup-sheet onDismiss during confirm does not end pairing-flow deferral`() async throws { let harness = try makeHarness() diff --git a/MC1Tests/Utilities/MacSuspendLockMarkerTests.swift b/MC1Tests/Utilities/MacSuspendLockMarkerTests.swift new file mode 100644 index 0000000000..e69635e35f --- /dev/null +++ b/MC1Tests/Utilities/MacSuspendLockMarkerTests.swift @@ -0,0 +1,50 @@ +import Darwin +import Foundation +@testable import MC1 +import Testing + +struct MacSuspendLockMarkerTests { + @Test + func `Lock path nests the bundle identifier under the sandbox cache`() { + let url = MacSuspendLockMarker.metalArchiveLockURL( + cacheDirectory: "/var/folders/C/io.pocketmesh.app/", + bundleIdentifier: "io.pocketmesh.app" + ) + #expect( + url.path == "/var/folders/C/io.pocketmesh.app/io.pocketmesh.app/com.apple.metal/archiveUsage.db/lock.mdb" + ) + } + + @Test + func `Marking a lock file sets the suspend attribute`() throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("mac-suspend-lock-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let file = directory.appendingPathComponent("lock.mdb") + #expect(FileManager.default.createFile(atPath: file.path, contents: Data())) + + MacSuspendLockMarker.markLockFile(at: file) + + #expect(attributeBytes(at: file) == [0xFF]) + } + + @Test + func `Marking a missing file leaves it missing`() { + let file = FileManager.default.temporaryDirectory + .appendingPathComponent("mac-suspend-missing-\(UUID().uuidString)") + + MacSuspendLockMarker.markLockFile(at: file) + + #expect(!FileManager.default.fileExists(atPath: file.path)) + } + + private func attributeBytes(at url: URL) -> [UInt8]? { + let size = getxattr(url.path, MacSuspendLockMarker.attributeName, nil, 0, 0, 0) + guard size > 0 else { return nil } + var buffer = [UInt8](repeating: 0, count: size) + let read = getxattr(url.path, MacSuspendLockMarker.attributeName, &buffer, buffer.count, 0, 0) + guard read == size else { return nil } + return buffer + } +} diff --git a/MC1Tests/Utilities/MalwareDomainFilterTests.swift b/MC1Tests/Utilities/MalwareDomainFilterTests.swift index 67500b598a..6101801cf2 100644 --- a/MC1Tests/Utilities/MalwareDomainFilterTests.swift +++ b/MC1Tests/Utilities/MalwareDomainFilterTests.swift @@ -10,10 +10,10 @@ struct MalwareDomainFilterTests { // Read a domain from the bundled list to test against. // The test host is the app, so Bundle.main contains app resources. guard let bundleURL = Bundle.main.url( - forResource: "urlhaus-filter-hosts-online", - withExtension: "txt" - ), - let text = try? String(contentsOf: bundleURL, encoding: .utf8) else { + forResource: "urlhaus-filter-hosts-online", + withExtension: "txt" + ), + let text = try? String(contentsOf: bundleURL, encoding: .utf8) else { Issue.record("Bundled malware domain list not found") return } diff --git a/MC1Tests/ViewModels/BatchTraceTests.swift b/MC1Tests/ViewModels/BatchTraceTests.swift index c8ba5885b0..05d933d1e4 100644 --- a/MC1Tests/ViewModels/BatchTraceTests.swift +++ b/MC1Tests/ViewModels/BatchTraceTests.swift @@ -264,7 +264,7 @@ struct BatchExecutionTests { viewModel.batchEnabled = true viewModel.isRunning = true viewModel.currentTraceIndex = 2 - viewModel.setPendingTagForTesting(12345) + viewModel.setPendingTraceForTesting(12345) viewModel.cancelBatchTrace() diff --git a/MC1Tests/ViewModels/ChatViewModelPaginationTests.swift b/MC1Tests/ViewModels/ChatViewModelPaginationTests.swift index 9f68f71bd3..22f5a7d871 100644 --- a/MC1Tests/ViewModels/ChatViewModelPaginationTests.swift +++ b/MC1Tests/ViewModels/ChatViewModelPaginationTests.swift @@ -438,7 +438,8 @@ struct ChatViewModelChannelPaginationTests { channelIndex: channelIndex, timestamp: 2000 ) - await viewModel.handle(.channelMessageReceived(message: channelMessage, channelIndex: channelIndex)) + let scope = ReceiveScope(radioID: radioID, link: .init(), partition: .init()) + await viewModel.handle(.channelMessageReceived(message: channelMessage, channelIndex: channelIndex, scope: scope)) #expect(viewModel.messages.count == baselineCount, "An incoming channel message must not be admitted into the open DM after the axis switch") diff --git a/MC1Tests/ViewModels/ChatViewModelPreviewSeedTests.swift b/MC1Tests/ViewModels/ChatViewModelPreviewSeedTests.swift index e8ab4ef590..3032e5bf33 100644 --- a/MC1Tests/ViewModels/ChatViewModelPreviewSeedTests.swift +++ b/MC1Tests/ViewModels/ChatViewModelPreviewSeedTests.swift @@ -101,7 +101,6 @@ struct ChatViewModelPreviewSeedTests { connectionState: { .disconnected }, connectedDevice: { nil }, currentRadioID: { nil }, - session: { nil }, reactionService: { nil }, chatSendQueueService: { nil }, inlineImageDimensionsStore: { dimensionsStore }, diff --git a/MC1Tests/ViewModels/ChatViewModelTranslationTests.swift b/MC1Tests/ViewModels/ChatViewModelTranslationTests.swift index 4133dc87cc..1d274ebfc7 100644 --- a/MC1Tests/ViewModels/ChatViewModelTranslationTests.swift +++ b/MC1Tests/ViewModels/ChatViewModelTranslationTests.swift @@ -311,6 +311,24 @@ struct ChatViewModelTranslationTests { #expect(viewModel.translation(for: second.id)?.phase == .inProgress) } + @Test + func `decoded message with a detected language keeps nil translation and the wire displayedText`() async { + let viewModel = ChatViewModel() + let coordinator = ChatCoordinator.makeForTesting() + viewModel.bindCoordinatorForTesting(coordinator) + let wire = "MECP/0/M01 \(german)" + let message = makeMessage(timestamp: 1000, text: wire) + viewModel.appendMessageIfNew(message) + await coordinator.buildItemsTask?.value + + viewModel.timeline.bake.detectedLanguages[message.id] = .identified(languageCode: "de") + viewModel.timeline.rebakeRow(message.id) + + #expect(viewModel.timeline.bake.detectedLanguages[message.id] == .identified(languageCode: "de")) + #expect(viewModel.translation(for: message.id) == nil) + #expect(viewModel.displayedText(for: message) == wire) + } + @discardableResult private func performCurrent( _ viewModel: ChatViewModel, diff --git a/MC1Tests/ViewModels/ContactsViewModelTests.swift b/MC1Tests/ViewModels/ContactsViewModelTests.swift index 171928df3c..6518521059 100644 --- a/MC1Tests/ViewModels/ContactsViewModelTests.swift +++ b/MC1Tests/ViewModels/ContactsViewModelTests.swift @@ -48,6 +48,22 @@ private func createContact( @Suite("ContactsViewModel Tests") @MainActor struct ContactsViewModelTests { + @Test + func `sensors have their own segment and remain searchable favorites`() { + let model = ContactsViewModel() + let sensor = createContact(name: "Sensor", type: .sensor, isFavorite: true) + model.contacts = [sensor, createContact(type: .chat), createContact(type: .repeater), createContact(type: .room)] + func filtered(_ segment: NodeSegment, search: String = "") -> [UUID] { + model.filteredContacts(searchText: search, segment: segment, sortOrder: .name, userLocation: nil).map(\.id) + } + #expect(filtered(.sensors) == [sensor.id]) + #expect(filtered(.favorites) == [sensor.id]) + #expect(!filtered(.contacts).contains(sensor.id)) + #expect(!filtered(.repeaters).contains(sensor.id)) + #expect(!filtered(.rooms).contains(sensor.id)) + #expect(filtered(.contacts, search: "Sensor") == [sensor.id]) + } + // MARK: - Initial State @Test diff --git a/MC1Tests/ViewModels/DeviceInfoTelemetryViewModelTests.swift b/MC1Tests/ViewModels/DeviceInfoTelemetryViewModelTests.swift new file mode 100644 index 0000000000..9748a9e2d0 --- /dev/null +++ b/MC1Tests/ViewModels/DeviceInfoTelemetryViewModelTests.swift @@ -0,0 +1,485 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Device Info self telemetry") +@MainActor +struct DeviceInfoTelemetryViewModelTests { + private let publicKey = Data(repeating: 0x01, count: ProtocolLimits.publicKeySize) + private let latitude = 37.7749 + private let longitude = -122.4194 + + @Test + func `a valid reply shows voltage and location and writes the service current at apply`() async throws { + let opened = try await openLink() + let otherStore = SelfTelemetryStore() + let task = Task { await opened.model.loadTelemetry() } + try await waitUntil("self telemetry command") { await self.commandCount(opened.transport) == 1 } + opened.box.snapshots = NodeSnapshotService(dataStore: otherStore) + await opened.transport.simulateReceive(telemetryFrame()) + await task.value + + #expect(opened.model.cachedDataPoints.allSatisfy { $0.channel != 0 }) + #expect(opened.model.cachedDataPoints.contains { $0.channel == 1 && $0.type == .voltage }) + #expect(opened.model.currentLocationFix?.latitude == latitude) + #expect(opened.model.currentLocationFix?.longitude == longitude) + #expect(opened.model.telemetryLoaded) + #expect(opened.model.telemetrySectionError == nil) + #expect(await opened.store.rows().isEmpty) + let saved = await otherStore.rows() + #expect(saved.count == 1) + #expect(saved.first?.latitude == latitude) + #expect(saved.first?.telemetryEntries?.count == 1) + #expect(saved.first?.telemetryEntries?.first?.channel == 1) + #expect(saved.first?.selfRadioID == opened.box.device?.radioID) + + let points = opened.model.cachedDataPoints + opened.box.device = opened.box.device?.copy { + $0.nodeName = "Renamed" + $0.ocvPreset = OCVPreset.liFePO4.rawValue + } + opened.model.synchronizePresentation() + #expect(opened.model.cachedDataPoints == points) + #expect(opened.model.displayName == "Renamed") + #expect(opened.model.ocvValues == OCVPreset.liFePO4.ocvArray) + #expect(opened.model.mapLabel == "Renamed") + } + + @Test + func `a held save keeps the spinner and the next read owns loading`() async throws { + let opened = try await openLink() + await opened.store.holdNextWrite() + let first = Task { await opened.model.loadTelemetry() } + try await waitUntil("first command") { await self.commandCount(opened.transport) == 1 } + await opened.transport.simulateReceive(telemetryFrame()) + try await waitUntil("first save held") { await opened.store.isHoldingWrite } + + let sentWhileHeld = await opened.transport.sentData.count + await opened.model.loadTelemetry() + #expect(await opened.transport.sentData.count == sentWhileHeld) + #expect(opened.model.isLoadingTelemetry) + + await opened.store.resumeWrite() + await first.value + #expect(opened.model.isLoadingTelemetry == false) + #expect(await opened.store.rows().count == 1) + + await opened.store.holdNextWrite() + let second = Task { await opened.model.loadTelemetry() } + try await waitUntil("second command") { await self.commandCount(opened.transport) == 2 } + await opened.transport.simulateReceive(telemetryFrame()) + try await waitUntil("second save held") { await opened.store.isHoldingWrite } + #expect(opened.model.isLoadingTelemetry) + await opened.store.resumeWrite() + await second.value + #expect(opened.model.isLoadingTelemetry == false) + #expect(await opened.store.rows().count == 2) + } + + @Test + func `a reply after leaving ready does not apply and the next expansion can load`() async throws { + let opened = try await openLink() + try await deliverStale(opened) { $0.ready = false } + opened.box.ready = true + opened.model.synchronizePresentation() + #expect(opened.model.telemetryExpanded == false) + #expect(opened.model.telemetryLoaded == false) + + let task = Task { await opened.model.loadTelemetry() } + try await waitUntil("reconnect command") { await self.commandCount(opened.transport) == 2 } + await opened.transport.simulateReceive(telemetryFrame()) + await task.value + #expect(opened.model.currentLocationFix?.latitude == latitude) + #expect(await opened.store.rows().count == 1) + } + + @Test + func `a replaced ready service cannot clear the newer spinner or write the old store`() async throws { + let opened = try await openLink() + let first = Task { await opened.model.loadTelemetry() } + try await waitUntil("original command") { await self.commandCount(opened.transport) == 1 } + + let replacement = try await startedService() + let replacementStore = SelfTelemetryStore() + opened.box.service = replacement.service + opened.box.snapshots = NodeSnapshotService(dataStore: replacementStore) + let second = Task { await opened.model.loadTelemetry() } + try await waitUntil("replacement command") { await self.commandCount(replacement.transport) == 1 } + + await opened.transport.simulateReceive(telemetryFrame()) + await first.value + #expect(opened.model.isLoadingTelemetry) + #expect(opened.model.telemetry == nil) + #expect(await opened.store.rows().isEmpty) + + await replacement.transport.simulateReceive(telemetryFrame()) + await second.value + #expect(opened.model.currentLocationFix?.latitude == latitude) + #expect(opened.model.isLoadingTelemetry == false) + #expect(await replacementStore.rows().count == 1) + #expect(await opened.store.rows().isEmpty) + } + + @Test + func `switching radios drops the in flight reply`() async throws { + let opened = try await openLink() + try await deliverStale(opened) { box in + box.device = box.device?.copy { + $0.id = UUID() + $0.radioID = UUID() + } + } + } + + @Test + func `leaving and reopening device info drops the in flight reply`() async throws { + let opened = try await openLink() + try await deliverStale(opened) { $0.presentationRevision += 1 } + try await deliverStale(opened) { $0.deviceInfoSelected = false } + } + + @Test + func `navigating to the selected device info root drops the in flight reply`() async throws { + let opened = try await openLink() + try await deliverStale(opened) { $0.rootGeneration += 1 } + } + + @Test + func `missing short and unready links send no command`() async throws { + let opened = try await openLink() + let sent = await opened.transport.sentData.count + + opened.box.device = nil + await opened.model.loadTelemetry() + opened.box.device = makeRadio(publicKey: Data([0x01])) + await opened.model.loadTelemetry() + opened.box.device = makeRadio(publicKey: publicKey) + opened.box.ready = false + await opened.model.loadTelemetry() + #expect(await opened.transport.sentData.count == sent) + + opened.box.ready = true + let task = Task { await opened.model.loadTelemetry() } + try await waitUntil("in-flight command") { await self.commandCount(opened.transport) == 1 } + let duringFlight = await opened.transport.sentData.count + await opened.model.loadTelemetry() + #expect(await opened.transport.sentData.count == duringFlight) + #expect(duringFlight == sent + 1) + await opened.transport.simulateReceive(telemetryFrame()) + await task.value + } + + @Test + func `first load and reload timeouts set the section error without a new snapshot`() async throws { + let opened = try await openLink(timeout: 0.4) + await opened.model.loadTelemetry() + #expect(opened.model.telemetrySectionError == L10n.Localizable.Error.MeshCore.timeout) + #expect(opened.model.telemetry == nil) + #expect(opened.model.telemetryLoaded == false) + #expect(await opened.store.rows().isEmpty) + #expect(opened.model.isLoadingTelemetry == false) + + let task = Task { await opened.model.loadTelemetry() } + try await waitUntil("timeout recovery command") { await self.commandCount(opened.transport) == 2 } + await opened.transport.simulateReceive(telemetryFrame()) + await task.value + let points = opened.model.cachedDataPoints + #expect(points.isEmpty == false) + + await opened.model.loadTelemetry() + #expect(opened.model.telemetrySectionError == L10n.Localizable.Error.MeshCore.timeout) + #expect(opened.model.cachedDataPoints == points) + #expect(opened.model.telemetryLoaded) + #expect(await opened.store.rows().count == 1) + #expect(opened.model.isLoadingTelemetry == false) + } + + private func deliverStale( + _ opened: OpenedLink, + mutate: (LinkBox) -> Void + ) async throws { + let task = Task { await opened.model.loadTelemetry() } + let expected = await commandCount(opened.transport) + 1 + try await waitUntil("stale command") { await self.commandCount(opened.transport) == expected } + mutate(opened.box) + await opened.transport.simulateReceive(telemetryFrame()) + await task.value + #expect(opened.model.telemetry == nil) + #expect(opened.model.isLoadingTelemetry) + #expect(await opened.store.rows().isEmpty) + opened.model.synchronizePresentation() + #expect(opened.model.isLoadingTelemetry == false) + #expect(opened.model.telemetryExpanded == false) + #expect(opened.model.telemetrySectionError == nil) + #expect(opened.model.cachedDataPoints.isEmpty) + } + + private func openLink(timeout: TimeInterval = 2) async throws -> OpenedLink { + let started = try await startedService(timeout: timeout) + let store = SelfTelemetryStore() + let box = LinkBox( + device: makeRadio(publicKey: publicKey), + service: started.service, + snapshots: NodeSnapshotService(dataStore: store) + ) + let model = DeviceInfoTelemetryViewModel() + box.bind(model) + return OpenedLink(transport: started.transport, store: store, model: model, box: box) + } + + private func startedService(timeout: TimeInterval = 2) async throws -> StartedService { + let transport = MockTransport() + let session = MeshCoreSession( + transport: transport, + configuration: SessionConfiguration(defaultTimeout: timeout) + ) + let start = Task { try await session.start() } + try await waitUntil("app start") { await transport.sentData.count == 1 } + await transport.simulateReceive(selfInfoPacket()) + try await start.value + let container = try await ServiceContainer.forTesting(session: session) + return StartedService(transport: transport, service: container.binaryProtocolService) + } + + private func telemetryFrame() -> Data { + var frame = Data([ResponseCode.telemetryResponse.rawValue, 0x00]) + frame.append(publicKey.prefix(6)) + frame.append(sampleLPP()) + return frame + } + + private func sampleLPP() -> Data { + func int24BE(_ scaled: Int32) -> [UInt8] { + [UInt8((scaled >> 16) & 0xFF), UInt8((scaled >> 8) & 0xFF), UInt8(scaled & 0xFF)] + } + var bytes: [UInt8] = [0x00, LPPSensorType.voltage.rawValue, 0x00, 0x64] + bytes += [0x01, LPPSensorType.voltage.rawValue, 0x01, 0x90] + bytes += [0x01, LPPSensorType.gps.rawValue] + bytes += int24BE(Int32((latitude * 10000).rounded())) + bytes += int24BE(Int32((longitude * 10000).rounded())) + bytes += int24BE(0) + return Data(bytes) + } + + private func selfInfoPacket() -> Data { + var payload = Data([ResponseCode.selfInfo.rawValue]) + payload.append(1) + payload.append(UInt8(bitPattern: 22)) + payload.append(UInt8(bitPattern: 22)) + payload.append(publicKey) + payload.append(contentsOf: withUnsafeBytes(of: Int32(0).littleEndian) { Array($0) }) + payload.append(contentsOf: withUnsafeBytes(of: Int32(0).littleEndian) { Array($0) }) + payload.append(0) + payload.append(0) + payload.append(0) + payload.append(0) + payload.append(contentsOf: withUnsafeBytes(of: UInt32(869_525).littleEndian) { Array($0) }) + payload.append(contentsOf: withUnsafeBytes(of: UInt32(250_000).littleEndian) { Array($0) }) + payload.append(11) + payload.append(5) + return payload + } + + private func commandCount(_ transport: MockTransport) async -> Int { + await transport.sentData.filter { $0.first == CommandCode.getSelfTelemetry.rawValue }.count + } + + private func waitUntil( + _ reason: String, + timeout: Duration = .seconds(2), + _ condition: @escaping @MainActor () async -> Bool + ) async throws { + let deadline = ContinuousClock.now.advanced(by: timeout) + while ContinuousClock.now < deadline { + if await condition() { return } + try await Task.sleep(for: .milliseconds(20)) + } + let matched = await condition() + #expect(matched, "Timed out waiting until \(reason)") + } + + private func makeRadio(publicKey: Data) -> DeviceDTO { + DeviceDTO( + id: UUID(), + radioID: UUID(), + publicKey: publicKey, + nodeName: "Field", + firmwareVersion: 11, + firmwareVersionString: "1.15.0", + manufacturerName: "Test", + buildDate: "2025-01-01", + maxContacts: 100, + maxChannels: 8, + frequency: 915_000, + bandwidth: 250_000, + spreadingFactor: 10, + codingRate: 5, + txPower: 20, + maxTxPower: 20, + latitude: 0, + longitude: 0, + blePin: 0, + clientRepeat: false, + manualAddContacts: false, + multiAcks: 2, + telemetryModeBase: 2, + telemetryModeLoc: 0, + telemetryModeEnv: 0, + advertLocationPolicy: 0, + lastConnected: Date(), + lastContactSync: 0, + isActive: true, + ocvPreset: nil, + customOCVArrayString: nil + ) + } +} + +private struct OpenedLink { + let transport: MockTransport + let store: SelfTelemetryStore + let model: DeviceInfoTelemetryViewModel + let box: LinkBox +} + +private struct StartedService { + let transport: MockTransport + let service: BinaryProtocolService +} + +@MainActor +private final class LinkBox { + var device: DeviceDTO? + var ready = true + var deviceInfoSelected = true + var presentationRevision = 0 + var rootGeneration = 0 + var service: BinaryProtocolService + var snapshots: NodeSnapshotService + + init(device: DeviceDTO, service: BinaryProtocolService, snapshots: NodeSnapshotService) { + self.device = device + self.service = service + self.snapshots = snapshots + } + + func bind(_ model: DeviceInfoTelemetryViewModel) { + model.configure( + device: { self.device }, + readyScope: { self.scope() }, + nodeSnapshotService: { self.snapshots } + ) + model.synchronizePresentation() + } + + func scope() -> DeviceInfoTelemetryViewModel.ReadyScope? { + guard ready, deviceInfoSelected else { return nil } + return DeviceInfoTelemetryViewModel.ReadyScope( + binaryProtocolService: service, + presentationRevision: presentationRevision, + rootNavigationGeneration: rootGeneration + ) + } +} + +private actor SelfTelemetryStore: NodeSnapshotPersisting { + private var snapshots: [NodeStatusSnapshotDTO] = [] + private var holdNext = false + private var continuation: CheckedContinuation? + private(set) var isHoldingWrite = false + + func holdNextWrite() { + holdNext = true + } + + func resumeWrite() { + isHoldingWrite = false + continuation?.resume() + continuation = nil + } + + func rows() -> [NodeStatusSnapshotDTO] { + snapshots + } + + func recordSelfTelemetrySnapshot( + deviceID: UUID, + radioID: UUID, + nodePublicKey: Data, + telemetry: [TelemetrySnapshotEntry]?, + location: NodeLocationFix? + ) async throws -> UUID? { + if holdNext { + holdNext = false + isHoldingWrite = true + await withCheckedContinuation { continuation = $0 } + } + let dto = NodeStatusSnapshotDTO( + nodePublicKey: nodePublicKey, + selfRadioID: radioID, + telemetryEntries: telemetry, + latitude: location?.latitude, + longitude: location?.longitude, + altitude: location?.altitude + ) + snapshots.append(dto) + _ = deviceID + return dto.id + } + + func fetchSelfTelemetrySnapshots( + radioID: UUID, + nodePublicKey: Data + ) async throws -> [NodeStatusSnapshotDTO] { + snapshots.filter { $0.selfRadioID == radioID && $0.nodePublicKey == nodePublicKey } + } + + func recordNodeStatusSnapshot( + nodePublicKey: Data, + status: NodeStatusMetrics?, + telemetry: [TelemetrySnapshotEntry]?, + neighbors: [NeighborSnapshotEntry]?, + location: NodeLocationFix? + ) async throws -> UUID { + UUID() + } + + func fetchNodeStatusSnapshots(nodePublicKey: Data, since: Date?) async throws -> [NodeStatusSnapshotDTO] { + [] + } + + func fetchLatestNodeStatusSnapshot(nodePublicKey: Data) async throws -> NodeStatusSnapshotDTO? { + nil + } + + // swiftlint:disable:next function_parameter_count + func saveNodeStatusSnapshot( + nodePublicKey: Data, + batteryMillivolts: UInt16?, + lastSNR: Double?, + lastRSSI: Int16?, + noiseFloor: Int16?, + uptimeSeconds: UInt32?, + rxAirtimeSeconds: UInt32?, + packetsSent: UInt32?, + packetsReceived: UInt32?, + receiveErrors: UInt32?, + postedCount: UInt16?, + postPushCount: UInt16? + ) async throws -> UUID { + UUID() + } + + func saveTelemetryOnlySnapshot( + nodePublicKey: Data, + telemetryEntries: [TelemetrySnapshotEntry] + ) async throws -> UUID { + UUID() + } + + func updateSnapshotNeighbors(id: UUID, neighbors: [NeighborSnapshotEntry]) async throws {} + func updateSnapshotTelemetry(id: UUID, telemetry: [TelemetrySnapshotEntry]) async throws {} + func deleteOldNodeStatusSnapshots(olderThan date: Date) async throws {} +} diff --git a/MC1Tests/ViewModels/DiscoveryViewModelTests.swift b/MC1Tests/ViewModels/DiscoveryViewModelTests.swift index 70020dbc4a..1f515a344a 100644 --- a/MC1Tests/ViewModels/DiscoveryViewModelTests.swift +++ b/MC1Tests/ViewModels/DiscoveryViewModelTests.swift @@ -47,6 +47,16 @@ private func makeNode( @Suite("DiscoveryViewModel Tests") @MainActor struct DiscoveryViewModelTests { + @Test + func `sensor discovery segment does not treat sensors as companions`() { + let model = DiscoveryViewModel() + let sensor = makeNode(name: "Sensor", type: .sensor) + model.discoveredNodes = [sensor, makeNode(type: .chat), makeNode(type: .repeater), makeNode(type: .room)] + #expect(model.filteredNodes(searchText: "", segment: .sensors, sortOrder: .name, userLocation: nil).map(\.id) == [sensor.id]) + #expect(!model.filteredNodes(searchText: "", segment: .contacts, sortOrder: .name, userLocation: nil).contains { $0.id == sensor.id }) + #expect(model.filteredNodes(searchText: "Sensor", segment: .contacts, sortOrder: .name, userLocation: nil).map(\.id) == [sensor.id]) + } + // MARK: - Name / Hex Search @Test diff --git a/MC1Tests/ViewModels/LineOfSightViewModelTests.swift b/MC1Tests/ViewModels/LineOfSightViewModelTests.swift index c175bfb6c4..674ba67925 100644 --- a/MC1Tests/ViewModels/LineOfSightViewModelTests.swift +++ b/MC1Tests/ViewModels/LineOfSightViewModelTests.swift @@ -134,7 +134,6 @@ actor MockPersistenceStore: PersistenceStoreProtocol { func updateMessageStatus(id: UUID, status: MessageStatus) async throws {} func updateMessageAck(id: UUID, ackCode: UInt32, status: MessageStatus, roundTripTime: UInt32?) async throws {} func updateMessageRetryStatus(id: UUID, status: MessageStatus, retryAttempt: Int, maxRetryAttempts: Int) async throws {} - func updateMessageHeardRepeats(id: UUID, heardRepeats: Int) async throws {} func updateMessageLinkPreview(id: UUID, url: String?, title: String?, imageData: Data?, iconData: Data?, fetched: Bool) throws {} func fetchConversations(radioID: UUID) async throws -> [ContactDTO] { [] @@ -315,6 +314,7 @@ actor MockPersistenceStore: PersistenceStoreProtocol { func admitSentEcho( messageID: UUID, + expectedTimestamp: UInt32, receivedAt: Date, pathNodes: Data, pathLength: UInt8, @@ -325,12 +325,20 @@ actor MockPersistenceStore: PersistenceStoreProtocol { nil } - func deleteMessageRepeats(messageID: UUID) async throws {} func incrementMessageSendCount(id: UUID) async throws -> Int { 0 } func updateMessageTimestamp(id: UUID, timestamp: UInt32) async throws {} + func commitOutgoingDirectMessageTimestamp(id: UUID, timestamp: UInt32) async throws -> UInt32? { + nil + } + + func setPendingSendWireAttempt(id: UUID, to next: UInt8) async throws -> Bool { + false + } + + func prepareChannelMessageResend(id: UUID, timestamp: UInt32) async throws {} // MARK: - Debug Log (stubs) @@ -494,28 +502,23 @@ actor MockPersistenceStore: PersistenceStoreProtocol { } func markMessageAsRead(id: UUID) async throws {} - func incrementPendingSendAttemptCount(messageID: UUID) async throws -> Int? { + func savePendingAcknowledgement(_ dto: PendingSendDTO, replacingPendingSendID: UUID?, markSent _: Bool) async throws -> Bool { + false + } + + func resolvePendingAcknowledgement(id: UUID, expectedDeadline: Date?, status: MessageStatus, ackCode: UInt32?, roundTripTime: UInt32?) async throws -> Bool { + false + } + + func preparePendingSendAttempt(messageID: UUID) async throws -> (pendingSendID: UUID, attemptCount: Int)? { nil } func saveDevice(_ dto: DeviceDTO) async throws {} - func updateDeviceNodeName(radioID: UUID, name: String) async throws {} - func updateDeviceCoordinates(radioID: UUID, latitude: Double, longitude: Double) async throws {} - func updateDeviceRadio( - radioID: UUID, - frequency: UInt32, - bandwidth: UInt32, - spreadingFactor: UInt8, - codingRate: UInt8, - appliedRadioPresetID: String? - ) async throws {} - func updateDeviceTxPower(radioID: UUID, txPower: Int8) async throws {} - func updateDeviceObservation(radioID: UUID, mapped: DeviceDTO) async throws {} - func updateDeviceOtherParams(radioID: UUID, intent: OtherParamsIntent) async throws {} - func updateDeviceClientRepeat(radioID: UUID, enabled: Bool) async throws {} - func updateDevicePathHashMode(radioID: UUID, mode: UInt8) async throws {} - func updateDeviceAutoAdd(radioID: UUID, config: UInt8, maxHops: UInt8) async throws {} - func updateDeviceDefaultFloodScopeName(radioID: UUID, name: String?) async throws {} + func updateDeviceOCVSettings(id: UUID, preset: String, customArray: String?) async throws -> DeviceDTO? { + nil + } + func fetchRemoteNodeSessionByPrefix(_ prefix: Data) async throws -> RemoteNodeSessionDTO? { nil } @@ -625,6 +628,23 @@ actor MockPersistenceStore: PersistenceStoreProtocol { func deleteOldNodeStatusSnapshots(olderThan date: Date) async throws {} + func recordSelfTelemetrySnapshot( + deviceID: UUID, + radioID: UUID, + nodePublicKey: Data, + telemetry: [TelemetrySnapshotEntry]?, + location: NodeLocationFix? + ) async throws -> UUID? { + nil + } + + func fetchSelfTelemetrySnapshots( + radioID: UUID, + nodePublicKey: Data + ) async throws -> [NodeStatusSnapshotDTO] { + [] + } + // MARK: - Pending Sends (stubs) func upsertPendingSend(_ dto: PendingSendDTO) async throws {} diff --git a/MC1Tests/ViewModels/NodeConfigImportNormalInputTests.swift b/MC1Tests/ViewModels/NodeConfigImportNormalInputTests.swift new file mode 100644 index 0000000000..a68b25d99e --- /dev/null +++ b/MC1Tests/ViewModels/NodeConfigImportNormalInputTests.swift @@ -0,0 +1,213 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Node config normal import input", .serialized) +@MainActor +struct NodeConfigImportNormalInputTests { + @Test(arguments: InterruptedSettlement.allCases) + func `first normal route after same device reconnect offers fresh file selection`( + settlement: InterruptedSettlement + ) async throws { + try await withImporter(hostNavigation: true) { env, model in + model.beginImport() + try await selectFile(Self.originalConfig, model: model) + let originalSource = model.inputSource + let inputWasBoundToLiveSource = originalSource != nil && originalSource == env.manager.currentConnection.map { + NodeConfigImportViewModel.ImportSource($0) + } + try #require(inputWasBoundToLiveSource) + try await prepareConfirmation(model) + await env.bluetooth.holdReplies(for: .setCoordinates) + await env.bluetooth.rejectNext(.setCoordinates) + + model.applyConfig() + try await waitUntil(timeout: .seconds(35)) { await self.positionWriteCount(env.bluetooth) == 1 } + let disconnect = env.startDisconnect() + try await waitUntil(timeout: .seconds(35)) { env.appState.navigation.selectedSetting == nil } + let detachedWhileApplying = env.manager.services == nil && model.isApplying + try #require(detachedWhileApplying) + + model.handleDismissal() + + let retainedWhileApplying = model.importedConfig == Self.originalConfig && model.isApplying + #expect(retainedWhileApplying) + if settlement == .cancel { model.cancelImport() } + await env.bluetooth.releaseReplies(for: .setCoordinates) + await model.importTask?.value + await disconnect.value + let failedImportSettled = !model.isApplying && !model.importComplete && model.errorMessage != nil + try #require(failedImportSettled) + let retainedAfterFailure = model.importedConfig == Self.originalConfig + try #require(retainedAfterFailure) + + await env.bluetooth.setConnectError(nil) + _ = try await env.appState.connectViaBluetooth(peripheralID: env.device.id) + let replacementSource = env.manager.currentConnection.map { NodeConfigImportViewModel.ImportSource($0) } + let sameDeviceReconnected = replacementSource?.deviceID == originalSource?.deviceID + && replacementSource?.radioID == originalSource?.radioID + let connectionIdentityChanged = replacementSource?.generation != originalSource?.generation + && replacementSource?.requestID != originalSource?.requestID + try #require(sameDeviceReconnected) + try #require(connectionIdentityChanged) + env.appState.navigation.navigateToSetting(.advanced) + + model.beginImport() + + let fileSelectionAvailable = model.importedConfig == nil && model.recovery == nil && !model.isApplying + #expect(fileSelectionAvailable, "The first reopened normal route must expose Select File") + let stalePreviewCleared = model.inputSource == nil && model.sections == ConfigSections() && model.errorMessage == nil + #expect(stalePreviewCleared) + + try await selectFile(Self.replacementConfig, model: model) + let deliberateInputUsesFreshSource = model.inputSource == replacementSource + try #require(deliberateInputUsesFreshSource) + try await prepareConfirmation(model) + model.applyConfig() + try await waitUntil(timeout: .seconds(35)) { !model.isApplying } + let selectedImportCompleted = model.importComplete && model.didApplyAnyWrite && model.errorMessage == nil + #expect(selectedImportCompleted) + let writesAfterSelection = await positionWriteCount(env.bluetooth) + #expect(writesAfterSelection == 2) + let replacementWasWritten = await env.bluetooth.sentData.contains( + PacketBuilder.setCoordinates(latitude: Self.replacementLatitude, longitude: Self.replacementLongitude) + ) + #expect(replacementWasWritten) + let identityWrites = await env.bluetooth.sentData.filter { $0.first == CommandCode.importPrivateKey.rawValue }.count + #expect(identityWrites == 0) + let laterTime = try await env.manager.session?.getTime() + let laterIOCompleted = (laterTime?.timeIntervalSince1970 ?? 0) > 0 + #expect(laterIOCompleted) + await model.importTask?.value + let successfulImportReleasedInput = model.importedConfig == nil + #expect(successfulImportReleasedInput) + } + } + + @Test + func `unchanged live source retains failed input and can retry`() async throws { + try await withImporter(hostNavigation: false) { env, model in + model.beginImport() + try await selectFile(Self.originalConfig, model: model) + let inputID = model.inputID + let source = model.inputSource + try await prepareConfirmation(model) + await env.bluetooth.rejectNext(.setCoordinates) + model.applyConfig() + await model.importTask?.value + let failedImportSettled = !model.isApplying && !model.importComplete && model.errorMessage != nil + try #require(failedImportSettled) + + model.beginImport() + + let failedInputRetained = model.importedConfig == Self.originalConfig + && model.inputID == inputID && model.inputSource == source + #expect(failedInputRetained) + try await prepareConfirmation(model) + model.applyConfig() + try await waitUntil(timeout: .seconds(35)) { !model.isApplying } + let retryCompleted = model.importComplete && model.didApplyAnyWrite && model.errorMessage == nil + #expect(retryCompleted) + let writesAfterRetry = await positionWriteCount(env.bluetooth) + #expect(writesAfterRetry == 2) + let laterTime = try await env.manager.session?.getTime() + let laterIOCompleted = (laterTime?.timeIntervalSince1970 ?? 0) > 0 + #expect(laterIOCompleted) + await model.importTask?.value + } + } + + @Test + func `idle normal dismissal releases parsed input and confirmation`() async throws { + try await withImporter(hostNavigation: false) { env, model in + model.beginImport() + try await selectFile(Self.originalConfig, model: model) + try await prepareConfirmation(model) + + model.handleDismissal() + + let inputReleased = model.importedConfig == nil && model.inputSource == nil && model.recovery == nil + let previewReleased = model.sections == ConfigSections() && !model.showConfirmation && model.confirmation == nil + #expect(inputReleased) + #expect(previewReleased) + let writesAfterDismissal = await positionWriteCount(env.bluetooth) + #expect(writesAfterDismissal == 0) + } + } + + private func withImporter( + hostNavigation: Bool, + body: (ConnectionLinkSwitchHarness, NodeConfigImportViewModel) async throws -> Void + ) async throws { + let env = try await ConnectionLinkSwitchHarness.make() + let model = NodeConfigImportViewModel() + model.configure( + nodeConfigService: { env.manager.services?.nodeConfigService }, + settingsService: { env.manager.services?.settingsService }, + connectedDevice: { env.manager.connectedDevice }, connectionManager: env.manager + ) + var host: SettingsTabHarness? + var bodyError: (any Error)? + do { + if hostNavigation { + let tabHost = try SettingsTabHarness.make(connected: false, injectedAppState: env.appState) + host = tabHost + let settingsVisible = try await tabHost.showSettingsList() + try #require(settingsVisible) + env.appState.navigation.navigateToSetting(.advanced) + let advancedSelected = try await tabHost.waitUntil { env.appState.navigation.selectedSetting == .advanced } + try #require(advancedSelected) + } + try await body(env, model) + } catch { + bodyError = error + } + model.cancelImport() + model.parseTask?.cancel() + model.previewTask?.cancel() + await env.bluetooth.releaseAllGates() + await env.wifi.releaseAllGates() + await model.importTask?.value + await model.parseTask?.value + await model.previewTask?.value + await env.close() + host?.tearDown() + if let bodyError { throw bodyError } + } + + private func selectFile(_ config: MeshCoreNodeConfig, model: NodeConfigImportViewModel) async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("config.json") + try JSONEncoder().encode(config).write(to: url) + model.parseFile(at: url) + await model.parseTask?.value + let parsedSelectedInput = model.importedConfig == config && !model.isParsing + try #require(parsedSelectedInput) + } + + private func prepareConfirmation(_ model: NodeConfigImportViewModel) async throws { + model.prepareConfirmation() + await model.previewTask?.value + let confirmationReady = model.showConfirmation && !model.isPreparingConfirmation && model.errorMessage == nil + try #require(confirmationReady) + } + + private func positionWriteCount(_ transport: ConnectionTestRadioTransport) async -> Int { + await transport.sentData.filter { $0.first == CommandCode.setCoordinates.rawValue }.count + } + + enum InterruptedSettlement: CaseIterable, Sendable { case failure, cancel } + + private static let originalConfig = MeshCoreNodeConfig( + positionSettings: .init(latitude: "37.5", longitude: "-122.5") + ) + private static let replacementLatitude = 38.5 + private static let replacementLongitude = -121.5 + private static let replacementConfig = MeshCoreNodeConfig( + positionSettings: .init(latitude: String(replacementLatitude), longitude: String(replacementLongitude)) + ) +} diff --git a/MC1Tests/ViewModels/NodeConfigImportOperationTests.swift b/MC1Tests/ViewModels/NodeConfigImportOperationTests.swift new file mode 100644 index 0000000000..8e01d107a9 --- /dev/null +++ b/MC1Tests/ViewModels/NodeConfigImportOperationTests.swift @@ -0,0 +1,198 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Node config import operation ownership", .serialized) +@MainActor +struct NodeConfigImportOperationTests { + @Test(arguments: PreviewReplacement.allCases, PreviewSettlement.allCases) + func `a retired preview cannot publish confirmation or failure`( + replacement: PreviewReplacement, settlement: PreviewSettlement + ) async throws { + try await withImporter { env, model in + try await selectFile(Self.originalConfig, model: model) + await env.bluetooth.holdReplies(for: .deviceQuery) + if settlement == .failure { await env.bluetooth.rejectNext(.deviceQuery) } + model.prepareConfirmation() + let preview = model.previewTask + try await waitUntil("the preview should hold its capability read") { + await env.bluetooth.heldReplyCount(for: .deviceQuery) == 1 + } + try #require(model.isPreparingConfirmation) + + switch replacement { + case .file: + try await selectFile(Self.replacementConfig, model: model) + case .dismissal: + model.handleDismissal() + } + await env.bluetooth.releaseReplies(for: .deviceQuery) + await preview?.value + + #expect(!model.isPreparingConfirmation) + #expect(!model.showConfirmation) + #expect(model.confirmation == nil) + #expect(model.errorMessage == nil) + model.applyConfig() + #expect(!model.isApplying) + #expect(await positionWriteCount(env.bluetooth) == 0) + switch replacement { + case .file: + #expect(model.importedConfig == Self.replacementConfig) + try await prepareConfirmation(model) + #expect(model.showConfirmation) + case .dismissal: + #expect(model.importedConfig == nil) + #expect(model.inputSource == nil) + } + } + } + + @Test(arguments: ConfirmationChange.allCases) + func `normal confirmation cannot authorize changed input sections or connection`( + change: ConfirmationChange + ) async throws { + try await withImporter { env, model in + try await selectFile(Self.originalConfig, model: model) + try await prepareConfirmation(model) + let source = try #require(env.manager.currentConnection) + + switch change { + case .sections: + model.sections.positionSettings = false + case .file: + try await selectFile(Self.replacementConfig, model: model) + case .connection: + await env.startDisconnect().value + await env.bluetooth.setConnectError(nil) + _ = try await env.appState.connectViaBluetooth(peripheralID: env.device.id) + let replacement = try #require(env.manager.currentConnection) + #expect(replacement.device.id == source.device.id) + #expect(replacement.device.radioID == source.device.radioID) + #expect(replacement.generation != source.generation) + #expect(replacement.requestID != source.requestID) + } + + model.applyConfig() + + #expect(!model.isApplying) + #expect(!model.importComplete) + #expect(!model.showConfirmation) + #expect(await positionWriteCount(env.bluetooth) == 0) + } + } + + @Test + func `confirmation presentation can dismiss before its apply action`() async throws { + try await withImporter { env, model in + try await selectFile(Self.originalConfig, model: model) + try await prepareConfirmation(model) + + model.showConfirmation = false + model.applyConfig() + + try await waitUntil("the confirmed import should complete") { !model.isApplying } + #expect(model.importComplete) + #expect(model.errorMessage == nil) + #expect(await positionWriteCount(env.bluetooth) == 1) + let selectedPositionWasWritten = await env.bluetooth.sentData.contains( + PacketBuilder.setCoordinates(latitude: 37.5, longitude: -122.5) + ) + #expect(selectedPositionWasWritten) + } + } + + @Test + func `success cleanup preserves a subsequently selected file`() async throws { + try await withImporter { env, model in + try await selectFile(Self.originalConfig, model: model) + try await prepareConfirmation(model) + model.applyConfig() + let completedImport = model.importTask + try await waitUntil("the import should display its completed result") { !model.isApplying } + try #require(model.importComplete) + try #require(model.errorMessage == nil) + #expect(await positionWriteCount(env.bluetooth) == 1) + + try await selectFile(Self.replacementConfig, model: model) + let replacementID = model.inputID + let replacementSource = model.inputSource + await completedImport?.value + + #expect(model.importedConfig == Self.replacementConfig) + #expect(model.inputID == replacementID) + #expect(model.inputSource == replacementSource) + #expect(model.sections.positionSettings) + #expect(!model.isApplying) + #expect(!model.importComplete) + #expect(model.errorMessage == nil) + #expect(await positionWriteCount(env.bluetooth) == 1) + } + } + + private func withImporter( + body: (ConnectionLinkSwitchHarness, NodeConfigImportViewModel) async throws -> Void + ) async throws { + let env = try await ConnectionLinkSwitchHarness.make() + let model = NodeConfigImportViewModel() + model.configure( + nodeConfigService: { env.manager.services?.nodeConfigService }, + settingsService: { env.manager.services?.settingsService }, + connectedDevice: { env.manager.connectedDevice }, connectionManager: env.manager + ) + var bodyError: (any Error)? + do { + model.beginImport() + try await body(env, model) + } catch { + bodyError = error + } + model.cancelImport() + model.parseTask?.cancel() + model.previewTask?.cancel() + await env.bluetooth.releaseAllGates() + await env.wifi.releaseAllGates() + await model.importTask?.value + await model.parseTask?.value + await model.previewTask?.value + await env.close() + if let bodyError { throw bodyError } + } + + private func selectFile(_ config: MeshCoreNodeConfig, model: NodeConfigImportViewModel) async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("config.json") + try JSONEncoder().encode(config).write(to: url) + model.parseFile(at: url) + await model.parseTask?.value + try #require(model.importedConfig == config) + try #require(!model.isParsing) + } + + private func prepareConfirmation(_ model: NodeConfigImportViewModel) async throws { + model.prepareConfirmation() + await model.previewTask?.value + try #require(model.showConfirmation) + try #require(!model.isPreparingConfirmation) + try #require(model.errorMessage == nil) + } + + private func positionWriteCount(_ transport: ConnectionTestRadioTransport) async -> Int { + await transport.sentData.filter { $0.first == CommandCode.setCoordinates.rawValue }.count + } + + enum PreviewReplacement: CaseIterable, Sendable { case file, dismissal } + enum PreviewSettlement: CaseIterable, Sendable { case success, failure } + enum ConfirmationChange: CaseIterable, Sendable { case sections, file, connection } + + private static let originalConfig = MeshCoreNodeConfig( + positionSettings: .init(latitude: "37.5", longitude: "-122.5") + ) + private static let replacementConfig = MeshCoreNodeConfig( + positionSettings: .init(latitude: "38.5", longitude: "-121.5") + ) +} diff --git a/MC1Tests/ViewModels/NodeConfigImportRecoveryTests.swift b/MC1Tests/ViewModels/NodeConfigImportRecoveryTests.swift new file mode 100644 index 0000000000..349e4da072 --- /dev/null +++ b/MC1Tests/ViewModels/NodeConfigImportRecoveryTests.swift @@ -0,0 +1,327 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import SwiftUI +import Testing + +@Suite("Node config explicit identity recovery") +@MainActor +struct NodeConfigImportRecoveryTests { + @Test + func `retry is identity only and releases input when its result is dismissed`() async throws { + try await withInterruptedImport { env, model, recovery in + let servicesUnavailable = env.manager.services == nil + #expect(servicesUnavailable) + env.appState.navigation.clearPerDeviceSelection() + #expect(env.appState.navigation.selectedSetting == nil) + #expect(model.beginRecovery(recovery)) + let retained = model.importedConfig != nil + #expect(retained) + model.prepareConfirmation() + #expect(model.showConfirmation) + #expect(model.confirmTitle == L10n.Settings.ConfigImport.confirmTitleIdentityRecovery) + #expect(model.confirmButtonRole == .destructive) + #expect(!model.recoverySheetDismissalDisabled) + #expect(model.confirmMessage.contains(recovery.targetDescription)) + let writesBefore = await identityWriteCount(env.bluetooth) + await env.bluetooth.setConnectError(nil) + await env.bluetooth.setPublicKey(Self.recoveredPublicKey, for: env.device.id) + + model.applyConfig() + #expect(model.recoverySheetDismissalDisabled) + try await waitUntil(timeout: .seconds(35)) { !model.isApplying } + + #expect(!model.recoverySheetDismissalDisabled) + #expect(model.identityRecoveryComplete) + #expect(!model.importComplete) + #expect(model.errorMessage == nil) + #expect(env.manager.identityImportRecoveries.isEmpty) + let writesAfterRetry = await identityWriteCount(env.bluetooth) + #expect(writesAfterRetry == writesBefore + 1) + let device = try #require(env.manager.connectedDevice) + #expect(device.radioID == env.device.radioID) + #expect(device.publicKey == Self.recoveredPublicKey) + let channels = try await env.manager.persistenceStore.fetchChannels(radioID: device.radioID) + #expect(!channels.contains { $0.name == Self.tailChannelName }) + let frames = await env.bluetooth.sentData + let tailWasNotWritten = !frames.contains { $0.first == CommandCode.setChannel.rawValue } + #expect(tailWasNotWritten) + #expect(try await #require(env.manager.session).getTime().timeIntervalSince1970 > 0) + + model.handleDismissal() + let released = model.importedConfig == nil + #expect(released) + #expect(model.recovery == nil) + + model.beginImport() + model.acceptInput(MeshCoreNodeConfig( + channels: [.init(name: Self.tailChannelName, secret: String(repeating: "CD", count: 16))] + ), source: nil) + model.sections = ConfigSections(channels: true) + model.prepareConfirmation() + try await waitUntil(timeout: .seconds(35)) { model.showConfirmation || model.errorMessage != nil } + #expect(model.showConfirmation) + #expect(model.confirmButtonRole == nil) + #expect(!model.recoverySheetDismissalDisabled) + model.applyConfig() + try await waitUntil(timeout: .seconds(35)) { !model.isApplying } + #expect(model.importComplete) + #expect(try await env.manager.persistenceStore.fetchChannels(radioID: device.radioID) + .contains { $0.name == Self.tailChannelName }) + } + } + + @Test(arguments: StaleAction.allCases) + func `stale or cancelled confirmation cannot start recovery`(action: StaleAction) async throws { + try await withInterruptedImport { env, model, recovery in + #expect(model.beginRecovery(recovery)) + model.prepareConfirmation() + #expect(model.showConfirmation) + let writesBefore = await identityWriteCount(env.bluetooth) + switch action { + case .cancel: + model.cancelConfirmation() + case .dismiss: + model.handleDismissal() + case .replaceInput: + try await selectFile(MeshCoreNodeConfig(privateKey: Self.replacementPrivateKey), model: model) + case .newRequest: + _ = try await connectOtherRadio(env) + } + + model.applyConfig() + await Task.yield() + + #expect(!model.isApplying) + #expect(!model.identityRecoveryComplete) + let writesAfterAction = await identityWriteCount(env.bluetooth) + #expect(writesAfterAction == writesBefore) + #expect(env.manager.identityImportRecoveries.contains { $0.receiptID == recovery.receiptID }) + if action == .newRequest { + #expect(env.manager.currentTransportType == .wifi) + #expect(try await #require(env.manager.session).getTime().timeIntervalSince1970 > 0) + } + } + } + + @Test + func `a new settings importer requests file and can confirm deliberately selected input`() async throws { + try await withInterruptedImport { env, _, recovery in + let reopened = NodeConfigImportViewModel() + configure(reopened, environment: env) + #expect(reopened.beginRecovery(recovery)) + reopened.prepareConfirmation() + #expect(reopened.showFilePicker) + #expect(!reopened.showConfirmation) + #expect(reopened.errorMessage == L10n.Settings.ConfigImport.identityRecoveryKeyRequired) + reopened.showFilePicker = false + try await selectFile(MeshCoreNodeConfig(privateKey: Self.replacementPrivateKey), model: reopened) + reopened.prepareConfirmation() + #expect(reopened.showConfirmation) + #expect(reopened.confirmTitle == L10n.Settings.ConfigImport.confirmTitleIdentityRecovery) + #expect(reopened.confirmButtonRole == .destructive) + #expect(reopened.confirmMessage == L10n.Settings.ConfigImport.confirmIdentityRecovery( + "\(recovery.sourceName) (\(recovery.targetDescription))" + )) + reopened.cancelConfirmation() + reopened.handleDismissal() + let retainedForReceipt = reopened.importedConfig != nil + #expect(retainedForReceipt) + #expect(reopened.beginRecovery(recovery)) + reopened.prepareConfirmation() + #expect(reopened.showConfirmation) + } + } + + @Test + func `reentering the same recovery retires parsing and preserves its prior input`() async throws { + try await withInterruptedImport { env, model, recovery in + try #require(model.beginRecovery(recovery)) + let retainedConfig = try #require(model.importedConfig) + let retainedInputID = model.inputID + let writesBefore = await identityWriteCount(env.bluetooth) + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("config.json") + try JSONEncoder().encode(MeshCoreNodeConfig(privateKey: Self.replacementPrivateKey)).write(to: url) + + model.parseFile(at: url) + let parser = model.parseTask + #expect(model.isParsing) + #expect(model.beginRecovery(recovery)) + #expect(!model.isParsing) + #expect(model.importedConfig == retainedConfig) + #expect(model.inputID == retainedInputID) + await parser?.value + + #expect(!model.isParsing) + #expect(model.importedConfig == retainedConfig) + #expect(model.inputID == retainedInputID) + #expect(model.inputReceiptID == recovery.receiptID) + model.prepareConfirmation() + #expect(model.showConfirmation) + #expect(model.confirmMessage.contains(recovery.targetDescription)) + #expect(await identityWriteCount(env.bluetooth) == writesBefore) + model.cancelConfirmation() + } + } + + @Test + func `input retained for another unresolved radio requires deliberate selection`() async throws { + try await withInterruptedImport { env, model, recoveryA in + _ = try await connectOtherRadio(env) + model.beginImport() + let configB = MeshCoreNodeConfig(privateKey: Self.replacementPrivateKey) + try await selectFile(configB, model: model) + model.prepareConfirmation() + try await waitUntil(timeout: .seconds(35)) { model.showConfirmation || model.errorMessage != nil } + #expect(model.showConfirmation) + await env.wifi.enqueueResponsePackets(for: .importPrivateKey, packets: []) + model.applyConfig() + try await waitUntil(timeout: .seconds(35)) { !model.isApplying } + let recoveryB = try #require(model.recovery) + #expect(recoveryB.receiptID != recoveryA.receiptID) + let retainedB = model.importedConfig == configB + #expect(retainedB) + + #expect(model.beginRecovery(recoveryA)) + let refusedAutomaticReuse = model.importedConfig == nil + #expect(refusedAutomaticReuse) + model.prepareConfirmation() + #expect(!model.showConfirmation) + #expect(model.showFilePicker) + model.showFilePicker = false + + try await selectFile(configB, model: model) + model.prepareConfirmation() + #expect(model.showConfirmation) + #expect(model.inputReceiptID == recoveryA.receiptID) + #expect(env.manager.identityImportRecoveries.count == 2) + model.cancelConfirmation() + } + } + + @Test + func `recovery required errors use localized copy through ordinary connection wrappers`() async throws { + try await withInterruptedImport { _, _, recovery in + let interrupted = IdentityImportRecoveryRequired(recovery: recovery) + let direct: any Error = interrupted + let wrapped: any Error = ConnectionRequestFailure(requestID: UUID(), underlying: interrupted) + let expected = L10n.Settings.ConfigImport.identityOutcomeUnknown(recovery.sourceName) + #expect(direct.userFacingMessage == expected) + #expect(wrapped.userFacingMessage == expected) + } + } + + @Test + func `ordinary app state connect surfaces current unknown outcome and rejects it after another choice`() async throws { + try await withInterruptedImport { env, _, recovery in + await env.bluetooth.setConnectError(nil) + await env.bluetooth.setPublicKey(Self.recoveredPublicKey, for: env.device.id) + var connectionFailure: (any Error)? + do { + _ = try await env.appState.connectViaBluetooth(peripheralID: env.device.id) + Issue.record("An ordinary connection must require explicit identity recovery") + } catch { + connectionFailure = error + } + let captured = try #require(connectionFailure) + let current = try #require(env.appState.currentConnectionFailure(captured)) + #expect(current is IdentityImportRecoveryRequired) + #expect(current.userFacingMessage == L10n.Settings.ConfigImport.identityOutcomeUnknown(recovery.sourceName)) + let servicesUnavailable = env.manager.services == nil + #expect(servicesUnavailable) + + _ = try await connectOtherRadio(env) + + #expect(env.appState.currentConnectionFailure(captured) == nil) + #expect(env.manager.currentTransportType == .wifi) + #expect(try await #require(env.manager.session).getTime().timeIntervalSince1970 > 0) + } + } + + private func withInterruptedImport( + _ body: (ConnectionLinkSwitchHarness, NodeConfigImportViewModel, IdentityImportRecovery) async throws -> Void + ) async throws { + let env = try await ConnectionLinkSwitchHarness.make() + let model = NodeConfigImportViewModel() + configure(model, environment: env) + do { + model.acceptInput(MeshCoreNodeConfig( + privateKey: Self.privateKey, + channels: [.init(name: Self.tailChannelName, secret: String(repeating: "CD", count: 16))] + ), source: nil) + model.sections = ConfigSections(nodeIdentity: true, channels: true, contacts: false) + model.prepareConfirmation() + try await waitUntil(timeout: .seconds(35)) { model.showConfirmation || model.errorMessage != nil } + #expect(model.showConfirmation) + await env.bluetooth.enqueueResponsePackets(for: .importPrivateKey, packets: []) + model.applyConfig() + try await waitUntil(timeout: .seconds(35)) { !model.isApplying } + let recovery = try #require(env.manager.identityImportRecoveries.first) + #expect(model.errorMessage == L10n.Settings.ConfigImport.identityOutcomeUnknown(recovery.sourceName)) + try await body(env, model, recovery) + } catch { + model.cancelImport() + await env.bluetooth.releaseAllGates() + await env.wifi.releaseAllGates() + await model.importTask?.value + await env.close() + throw error + } + model.cancelImport() + await model.importTask?.value + await env.close() + } + + private func configure(_ model: NodeConfigImportViewModel, environment env: ConnectionLinkSwitchHarness) { + model.configure( + nodeConfigService: { env.manager.services?.nodeConfigService }, + settingsService: { env.manager.services?.settingsService }, + connectedDevice: { env.manager.connectedDevice }, connectionManager: env.manager + ) + } + + private func connectOtherRadio(_ env: ConnectionLinkSwitchHarness) async throws -> DeviceDTO { + let other = env.device.copy { + $0.id = UUID() + $0.radioID = UUID() + $0.publicKey = Data(repeating: 0xB2, count: ProtocolLimits.publicKeySize) + $0.nodeName = "Other radio" + $0.connectionMethods = [.wifi(host: "other.local", port: 4242, displayName: nil)] + } + try await env.manager.persistenceStore.saveDevice(other) + await env.wifi.setDeviceID(other.id) + await env.wifi.setPublicKey(other.publicKey, for: other.id) + await env.wifi.setConnectError(nil) + _ = try await env.manager.connectViaWiFi(host: "other.local", port: 4242) + #expect(env.manager.connectedDevice?.radioID == other.radioID) + return other + } + + private func selectFile(_ config: MeshCoreNodeConfig, model: NodeConfigImportViewModel) async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("config.json") + try JSONEncoder().encode(config).write(to: url) + model.parseFile(at: url) + try await waitUntil(timeout: .seconds(35)) { !model.isParsing } + let parsed = model.importedConfig == config + #expect(parsed) + } + + private func identityWriteCount(_ transport: ConnectionTestRadioTransport) async -> Int { + await transport.sentData.filter { $0.first == CommandCode.importPrivateKey.rawValue }.count + } + + enum StaleAction: CaseIterable, Sendable { case cancel, dismiss, replaceInput, newRequest } + + private static let tailChannelName = "Must not import" + private static let privateKey = "7065e18fd9fabb70c1ed90dca19907de698c88b709ea146eafd93d9b830c7b60" + + "c4681193c79bbc39945ba8064104bb618f8fd7a84a0af6f57033d6e8ddcd6471" + private static let replacementPrivateKey = String(repeating: "AB", count: ProtocolLimits.privateKeySize) + private static let recoveredPublicKey = Data(repeating: 0xD5, count: ProtocolLimits.publicKeySize) +} diff --git a/MC1Tests/ViewModels/NodeConfigImportTailPresentationTests.swift b/MC1Tests/ViewModels/NodeConfigImportTailPresentationTests.swift new file mode 100644 index 0000000000..19048a217f --- /dev/null +++ b/MC1Tests/ViewModels/NodeConfigImportTailPresentationTests.swift @@ -0,0 +1,245 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Node config import private tail presentation", .serialized) +@MainActor +struct NodeConfigImportTailPresentationTests { + @Test(arguments: TailSettlement.allCases) + func `normal import survives hosted navigation clear without publishing its private tail`( + settlement: TailSettlement + ) async throws { + let env = try await ConnectionLinkSwitchHarness.make(live: .wifi, wifiHost: "source.local") + let model = NodeConfigImportViewModel() + model.configure( + nodeConfigService: { env.manager.services?.nodeConfigService }, + settingsService: { env.manager.services?.settingsService }, + connectedDevice: { env.manager.connectedDevice }, connectionManager: env.manager + ) + var host: SettingsTabHarness? + var callers: [Task] = [] + var bodyError: (any Error)? + do { + await env.bluetooth.setConnectError(nil) + await env.wifi.setConnectError(nil) + await env.wifi.setIdentityImportPublicKey(Self.importedPublicKey) + await env.wifi.setResponsePackets( + for: .getDefaultFloodScope, packets: [Data([ResponseCode.defaultFloodScope.rawValue])] + ) + guard let source = env.manager.currentConnection else { + throw NSError(domain: "NodeConfigImportTailPresentation", code: 2) + } + let hostedStartupScopeIsUnset = try await source.services.settingsService.getDefaultFloodScope() == nil + try #require(hostedStartupScopeIsUnset) + let store = env.manager.persistenceStore + let radioID = source.device.radioID + let retainedRecipient = ChannelDTO( + id: UUID(), radioID: radioID, index: 0, name: "Retained recipient", + secret: Self.channelSecret, isEnabled: true, lastMessageDate: nil, unreadCount: 0 + ) + try await store.saveChannel(retainedRecipient) + let settingsHost = try SettingsTabHarness.make(connected: false, injectedAppState: env.appState) + host = settingsHost + let settingsListIsVisible = try await settingsHost.showSettingsList() + try #require(settingsListIsVisible) + env.appState.navigation.navigateToSetting(.advanced) + try await waitUntil(timeout: .seconds(35), "the actual Settings host should select Advanced") { + env.appState.navigation.selectedSetting == .advanced + } + + model.beginImport() + try await selectFile(Self.config, model: model) + let inputID = model.inputID + model.prepareConfirmation() + await model.previewTask?.value + let confirmationReady = model.showConfirmation && model.confirmation != nil && model.errorMessage == nil + try #require(confirmationReady) + await env.wifi.holdReplies(for: .setCoordinates) + if settlement == .failure { await env.wifi.rejectNext(.setCoordinates) } + model.applyConfig() + try await waitUntil(timeout: .seconds(35), "the selected position stage should hold its actual post-key response") { + let positionIsHeld = await env.wifi.heldReplyCount(for: .setCoordinates) == 1 + return positionIsHeld || !model.isApplying + } + let heldPosition = await env.wifi.heldReplyCount(for: .setCoordinates) == 1 + let prerequisiteFrameCodes = await env.wifi.sentData.compactMap(\.first) + let prerequisiteError = model.errorMessage ?? "none" + try #require(heldPosition, "Import must reach its selected tail; error=\(prerequisiteError), frameCodes=\(prerequisiteFrameCodes)") + try await waitUntil(timeout: .seconds(35), "the importer should retain its actual private-key progress") { + model.didApplyAnyWrite + } + let heldFrames = await env.wifi.sentData + let keyIndex = heldFrames.firstIndex { $0.first == CommandCode.importPrivateKey.rawValue } + let importedFrameIndex = try #require(keyIndex) + let keyWriteCount = heldFrames.filter { $0.first == CommandCode.importPrivateKey.rawValue }.count + #expect(keyWriteCount == 1) + let acceptedIdentityIsSaved = try await store.fetchDevice(id: source.device.id)?.publicKey == Self.importedPublicKey + #expect(acceptedIdentityIsSaved) + let channelTailHasNotStarted = heldFrames.contains { $0.first == CommandCode.setChannel.rawValue } == false + #expect(channelTailHasNotStarted) + + let hasPublicSnapshot = env.manager.currentConnection != nil + let hasPublicServices = env.appState.services != nil + let hasPublicDevice = env.appState.connectedDevice != nil + let hasPublicSession = env.manager.session != nil + #expect(hasPublicSnapshot == false) + #expect(hasPublicServices == false) + #expect(hasPublicDevice == false) + #expect(hasPublicSession == false) + if !hasPublicDevice { + try await waitUntil(timeout: .seconds(35), "MainTabView should clear the device route during the private interval") { + env.appState.navigation.selectedSetting == nil + } + } + let routeWasCleared = env.appState.navigation.selectedSetting == nil + #expect(routeWasCleared) + settingsHost.selectTab(.chats) + // The real host clears navigation; the separately retained importer uses Settings' provider lifetime. + model.handleDismissal() + let applyingInputSurvivedDismissal = model.isApplying && model.importedConfig == Self.config + && model.inputID == inputID && model.recovery == nil && !model.importComplete + #expect(applyingInputSurvivedDismissal) + let exactHeldProgress = model.applyProgress == Self.privateKeyProgress + && model.applyStepDescription == L10n.Settings.ConfigImport.stepPrivateKey + #expect(exactHeldProgress) + + var foregroundEntered = false + var wiringEntered = false + callers.append(Task { + foregroundEntered = true + await env.appState.handleReturnToForeground() + }) + callers.append(Task { + wiringEntered = true + await env.appState.wireServicesIfConnected() + }) + try await waitUntil(timeout: .seconds(35), "actual foreground and direct wiring callers should enter") { + foregroundEntered && wiringEntered + } + let pendingBeforeIntent = try await store.fetchPendingSends(radioID: radioID).count + let intentOutcome = try await SendMessageIntent.performSend( + message: Self.heldIntentMessage, recipient: .channel(retainedRecipient), in: env.appState + ) + #expect(intentOutcome == .mustForeground) + let pendingAfterIntent = try await store.fetchPendingSends(radioID: radioID).count + #expect(pendingAfterIntent == pendingBeforeIntent) + let framesWhileHeld = await env.wifi.sentData + let postKeyCodes = framesWhileHeld.dropFirst(importedFrameIndex + 1).compactMap(\.first) + let earlyBatteryCount = postKeyCodes.filter { $0 == CommandCode.getBattery.rawValue }.count + let earlyQueueSendCount = postKeyCodes.filter { $0 == CommandCode.sendChannelMessage.rawValue }.count + #expect(earlyBatteryCount == 0) + #expect(earlyQueueSendCount == 0) + if settlement == .cancel { + model.cancelImport() + let cancellationWasRequested = model.importTask?.isCancelled == true + #expect(cancellationWasRequested) + } + let stillApplyingAtHeldResponse = model.isApplying && !model.importComplete + #expect(stillApplyingAtHeldResponse) + let stillNoPublishedSnapshot = env.manager.currentConnection == nil + #expect(stillNoPublishedSnapshot) + + await env.wifi.releaseReplies(for: .setCoordinates) + try await waitUntil(timeout: .seconds(35), "the original importer outcome must settle after its held exchange") { + !model.isApplying + } + let wholeImportSucceeded = model.importComplete + let outcomeError = model.errorMessage + switch settlement { + case .success: + #expect(wholeImportSucceeded) + #expect(outcomeError == nil) + case .failure: + #expect(wholeImportSucceeded == false) + let originalTailError = NodeConfigImportViewModel.failureMessage( + for: SettingsServiceError.sessionError(.deviceError(code: 1)), didApplyAnyWrite: true + ) + #expect(outcomeError == originalTailError) + case .cancel: + #expect(wholeImportSucceeded == false) + #expect(outcomeError == L10n.Settings.ConfigImport.cancelledPartial) + } + for caller in callers { + await caller.value + } + callers.removeAll() + try await waitUntil(timeout: .seconds(35), "the known accepted identity should activate after tail settlement") { + env.manager.connectionState == .ready && env.manager.currentConnection != nil + } + guard let live = env.manager.currentConnection else { + throw NSError(domain: "NodeConfigImportTailPresentation", code: 3) + } + let samePartitionIsLive = live.device.radioID == radioID && live.device.publicKey == Self.importedPublicKey + #expect(samePartitionIsLive) + let observedTime = try await live.services.settingsService.getTime() + #expect(observedTime.timeIntervalSince1970 > 0) + let tailChannelWriteCount = await env.wifi.sentData.filter { $0.first == CommandCode.setChannel.rawValue }.count + #expect(tailChannelWriteCount == (settlement == .success ? 1 : 0)) + if settlement == .success { + let restoredSecret = await env.wifi.channelMatches(index: 0, secret: Self.channelSecret) + #expect(restoredSecret) + let laterOutcome = try await SendMessageIntent.performSend( + message: Self.liveIntentMessage, recipient: .channel(retainedRecipient), in: env.appState + ) + #expect(laterOutcome == .queued) + try await waitUntil(timeout: .seconds(35), "a fresh activated queue should complete its actual frame") { + let hasLiveFrame = await env.wifi.sentData.contains { $0.range(of: Data(Self.liveIntentMessage.utf8)) != nil } + let pendingCount = await (try? store.fetchPendingSends(radioID: radioID).count) ?? 1 + return hasLiveFrame && pendingCount == 0 + } + } + await model.importTask?.value + let inputLifetimeIsCorrect = settlement == .success + ? model.importedConfig == nil + : model.importedConfig == Self.config && model.inputID == inputID + #expect(inputLifetimeIsCorrect) + } catch { + bodyError = error + } + model.cancelImport() + model.parseTask?.cancel() + model.previewTask?.cancel() + await env.bluetooth.releaseAllGates() + await env.wifi.releaseAllGates() + for caller in callers { + await caller.value + } + await model.importTask?.value + await model.parseTask?.value + await model.previewTask?.value + await env.close() + host?.tearDown() + if let bodyError { throw bodyError } + } + + private func selectFile(_ config: MeshCoreNodeConfig, model: NodeConfigImportViewModel) async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("config.json") + try JSONEncoder().encode(config).write(to: url) + model.parseFile(at: url) + await model.parseTask?.value + let selectedInputWasParsed = model.importedConfig == config && !model.isParsing + try #require(selectedInputWasParsed) + } + + enum TailSettlement: CaseIterable, Sendable { case success, failure, cancel } + + private static let privateKeyProgress = 1.0 / 3.0 + private static let heldIntentMessage = "Shortcut must wait for the private tail" + private static let liveIntentMessage = "Activated Shortcut queue is live" + private static let channelSecret = Data(repeating: 0xCD, count: 16) + private static let importedPublicKey = Data([ + 0x1E, 0xC7, 0x71, 0x75, 0xB0, 0x91, 0x8E, 0xD2, 0x06, 0xF9, 0xAE, 0x04, 0xEC, 0x13, 0x6D, 0x6D, + 0x5D, 0x43, 0x15, 0xBB, 0x26, 0x30, 0x54, 0x27, 0xF6, 0x45, 0xB4, 0x92, 0xE9, 0x35, 0x0C, 0x10 + ]) + private static let config = MeshCoreNodeConfig( + privateKey: "7065e18fd9fabb70c1ed90dca19907de698c88b709ea146eafd93d9b830c7b60" + + "c4681193c79bbc39945ba8064104bb618f8fd7a84a0af6f57033d6e8ddcd6471", + positionSettings: .init(latitude: "37.5", longitude: "-122.5"), + channels: [.init(name: "Restored selected tail", secret: String(repeating: "CD", count: 16))] + ) +} diff --git a/MC1Tests/ViewModels/NodeConfigImportViewModelTests.swift b/MC1Tests/ViewModels/NodeConfigImportViewModelTests.swift index 47106bde67..538bc87b0b 100644 --- a/MC1Tests/ViewModels/NodeConfigImportViewModelTests.swift +++ b/MC1Tests/ViewModels/NodeConfigImportViewModelTests.swift @@ -67,36 +67,6 @@ struct NodeConfigImportViewModelTests { #expect(NodeConfigImportViewModel.failureMessage(for: error, didApplyAnyWrite: false) == clean) } - @Test - func `Leaving the screen resets a loaded preview back to the file picker`() { - let viewModel = NodeConfigImportViewModel() - viewModel.importedConfig = MeshCoreNodeConfig(name: "Node", channels: []) - viewModel.errorMessage = "stale error" - viewModel.sections.channels = true - viewModel.showConfirmation = true - - viewModel.handleDismissal() - - #expect(viewModel.importedConfig == nil) - #expect(viewModel.errorMessage == nil) - #expect(viewModel.sections == ConfigSections()) - #expect(!viewModel.showConfirmation) - } - - @Test - func `Leaving the screen mid-import preserves the in-flight import state`() { - let viewModel = NodeConfigImportViewModel() - viewModel.importedConfig = MeshCoreNodeConfig(name: "Node", channels: []) - viewModel.isApplying = true - viewModel.applyProgress = 0.5 - - viewModel.handleDismissal() - - #expect(viewModel.importedConfig != nil) - #expect(viewModel.isApplying) - #expect(viewModel.applyProgress == 0.5) - } - @Test func `a dismissed import and a preset leave live and stored RF on the final operation`() async throws { let eu = try #require(RadioPresets.all.first { $0.id == "eu-narrow" }) @@ -124,9 +94,11 @@ struct NodeConfigImportViewModelTests { appState.connectionManager.setTestState( connectionState: .ready, services: services, + session: session, connectedDevice: device ) - await appState.wireSettingsEventStream(services: services) + let snapshot = try #require(appState.connectionManager.currentConnection) + await appState.wireSettingsEventStream(snapshot: snapshot) defer { appState.shutdown() Task { @@ -136,12 +108,13 @@ struct NodeConfigImportViewModelTests { } let gate = ImportSuspendGate() - await services.nodeConfigService.setOnPostIdentityImport { + await services.nodeConfigService.setIdentityImportHandler { key in + try await services.settingsService.importPrivateKey(key) await gate.park() return nil } let viewModel = NodeConfigImportViewModel() - viewModel.importedConfig = MeshCoreNodeConfig( + viewModel.acceptInput(MeshCoreNodeConfig( privateKey: String(repeating: "ab", count: 64), radioSettings: .init( frequency: eu.frequencyKHz, @@ -150,15 +123,17 @@ struct NodeConfigImportViewModelTests { codingRate: eu.codingRate, txPower: Device.Defaults.txPower ) - ) + ), source: nil) viewModel.sections.nodeIdentity = true viewModel.sections.radioSettings = true - viewModel.applyConfig( - nodeConfigService: services.nodeConfigService, - settingsService: services.settingsService, - radioID: radioID + viewModel.configure( + nodeConfigService: { services.nodeConfigService }, settingsService: { services.settingsService }, + connectedDevice: { appState.connectedDevice }, connectionManager: appState.connectionManager ) + viewModel.prepareConfirmation() + try await waitUntil("the import preview should be ready") { viewModel.showConfirmation || viewModel.errorMessage != nil } + viewModel.applyConfig() try await waitUntil("import should park after its early radio read") { gate.isParked && viewModel.isApplying } diff --git a/MC1Tests/ViewModels/NodeDiscoveryLifetimeTests.swift b/MC1Tests/ViewModels/NodeDiscoveryLifetimeTests.swift index 2d49ba6a39..265ce51eed 100644 --- a/MC1Tests/ViewModels/NodeDiscoveryLifetimeTests.swift +++ b/MC1Tests/ViewModels/NodeDiscoveryLifetimeTests.swift @@ -33,6 +33,77 @@ private final class AsyncGate { @Suite("Node Discovery lifetime") @MainActor struct NodeDiscoveryLifetimeTests { + @Test + func `reset before add task runs prevents dispatch`() async { + let (model, _) = makeViewModel() + var sends = 0 + model.addContactForTesting = { _ in sends += 1 } + model.addNode(result(publicKey: Data(repeating: 0xA4, count: 32))) + model.reset() + await Task.yield() + #expect(sends == 0) + #expect(model.addedPublicKeys.isEmpty) + } + + @Test + func `sensor add requires full key and matching modeled type`() async throws { + let (model, _) = makeViewModel() + var frames: [ContactFrame] = [] + model.addContactForTesting = { frames.append($0) } + func sensor(_ type: UInt8 = 4, size: Int = 32, filter: NodeDiscoveryFilter = .sensors) -> NodeDiscoveryResult { + NodeDiscoveryResult(name: "Sensor", publicKey: Data(repeating: 0xAA, count: size), nodeType: type, + snr: 1, snrIn: 1, rssi: -70, scanFilter: filter, receivedAt: Date()) + } + for invalid in [sensor(size: 8), sensor(size: 31), sensor(size: 33), sensor(0x7F), sensor(filter: .repeaters)] { + #expect(!model.canAdd(invalid)) + model.addNode(invalid) + } + #expect(frames.isEmpty) + model.addNode(sensor()) + model.addNode(sensor()) + try await waitUntil(timeout: .seconds(1), "sensor should be added once") { frames.count == 1 } + #expect(frames[0].typeRawValue == 4) + #expect(frames[0].type == .sensor) + } + + @Test + func `response before host acceptance is buffered and late response is ignored`() async throws { + let session = MeshCoreSession(transport: MockTransport()) + let (model, box) = makeViewModel(session: session) + let gate = AsyncGate() + model.sendDiscoverForTesting = { _ in try await gate.wait() } + model.scanDurationForTesting = 30 + model.scan() + try await waitUntil(timeout: .seconds(1), "host send should start") { gate.started } + let firstKey = Data(repeating: 0xAA, count: 32) + await session.dispatcher.dispatch(discover(tag: box.discoverTag, publicKey: firstKey)) + #expect(model.results.isEmpty) + gate.succeed(box.discoverTag) + try await waitUntil(timeout: .seconds(1), "early response should be published") { model.results.count == 1 } + model.setScanDeadlineForTesting(Date().addingTimeInterval(-1)) + model.expireScanIfDeadlinePassed() + await session.dispatcher.dispatch(discover(tag: box.discoverTag, publicKey: Data(repeating: 0xBB, count: 32))) + #expect(model.results.map(\.publicKey) == [firstKey]) + #expect(!model.isScanning) + await session.stop() + } + + @Test + func `early response followed by host failure never publishes`() async throws { + let session = MeshCoreSession(transport: MockTransport()) + let (model, box) = makeViewModel(session: session) + let gate = AsyncGate() + model.sendDiscoverForTesting = { _ in try await gate.wait() } + model.scan() + try await waitUntil(timeout: .seconds(1), "host send should start") { gate.started } + await session.dispatcher.dispatch(discover(tag: box.discoverTag, publicKey: Data(repeating: 0xAA, count: 32))) + gate.fail(MeshCoreError.timeout) + try await waitUntil(timeout: .seconds(1), "scan should fail") { !model.isScanning } + #expect(model.results.isEmpty) + #expect(model.errorMessage != nil) + await session.stop() + } + private let radioID = UUID() private func makeViewModel(session: MeshCoreSession? = nil) -> (NodeDiscoveryViewModel, Box) { diff --git a/MC1Tests/ViewModels/NodeLocationCaptureTests.swift b/MC1Tests/ViewModels/NodeLocationCaptureTests.swift index 46854ebbc3..4d5cf6e0d3 100644 --- a/MC1Tests/ViewModels/NodeLocationCaptureTests.swift +++ b/MC1Tests/ViewModels/NodeLocationCaptureTests.swift @@ -162,4 +162,21 @@ private actor StoringSnapshotPersister: NodeSnapshotPersisting { func updateSnapshotNeighbors(id: UUID, neighbors: [NeighborSnapshotEntry]) async throws {} func updateSnapshotTelemetry(id: UUID, telemetry: [TelemetrySnapshotEntry]) async throws {} func deleteOldNodeStatusSnapshots(olderThan date: Date) async throws {} + + func recordSelfTelemetrySnapshot( + deviceID: UUID, + radioID: UUID, + nodePublicKey: Data, + telemetry: [TelemetrySnapshotEntry]?, + location: NodeLocationFix? + ) async throws -> UUID? { + nil + } + + func fetchSelfTelemetrySnapshots( + radioID: UUID, + nodePublicKey: Data + ) async throws -> [NodeStatusSnapshotDTO] { + [] + } } diff --git a/MC1Tests/ViewModels/NodeSettingsLateRecoveryTests.swift b/MC1Tests/ViewModels/NodeSettingsLateRecoveryTests.swift index cdd163b079..0121a52b31 100644 --- a/MC1Tests/ViewModels/NodeSettingsLateRecoveryTests.swift +++ b/MC1Tests/ViewModels/NodeSettingsLateRecoveryTests.swift @@ -15,7 +15,7 @@ struct NodeSettingsLateRecoveryTests { let viewModel = NodeSettingsViewModel() let send: (UUID, String, Duration) async throws -> String = { _, command, _ in switch responses[command] { - case let .success(response): return response + case let .success(response): response case let .failure(error): throw error case nil: throw RemoteNodeError.timeout } diff --git a/MC1Tests/ViewModels/RemoteAdminLifetimeTests.swift b/MC1Tests/ViewModels/RemoteAdminLifetimeTests.swift index b2d7472e7a..da72aabd86 100644 --- a/MC1Tests/ViewModels/RemoteAdminLifetimeTests.swift +++ b/MC1Tests/ViewModels/RemoteAdminLifetimeTests.swift @@ -23,6 +23,22 @@ private final class ReplyGate { @Suite("Remote admin lifetime") @MainActor struct RemoteAdminLifetimeTests { + @Test + func `sensor workspaces are scoped to radio and public key`() { + let registry = RemoteAdminWorkspaces() + let first = RemoteNodeSessionDTO(radioID: UUID(), publicKey: Data(repeating: 4, count: 32), name: "Sensor", role: .sensor) + let second = RemoteNodeSessionDTO(radioID: UUID(), publicKey: first.publicKey, name: "Sensor", role: .sensor) + let a = registry.sensor(for: first) + let same = registry.sensor(for: first) + let b = registry.sensor(for: second) + #expect(a.settings === same.settings) + #expect(a.cli === same.cli) + #expect(a.settings !== b.settings) + #expect(a.cli !== b.cli) + registry.reset() + #expect(registry.sensor(for: first).settings !== a.settings) + } + private func session(radioID: UUID = UUID(), publicKey: Data, name: String) -> RemoteNodeSessionDTO { RemoteNodeSessionDTO( radioID: radioID, @@ -288,18 +304,13 @@ struct RemoteAdminLifetimeTests { #expect(first.discoverySecondsRemaining == 0) } - @Test + @Test(.timeLimit(.minutes(1))) func `session stop does not publish a timeout and the replacement reply applies`() async throws { let transport = MockTransport() - let mesh = MeshCoreSession( - transport: transport, - configuration: SessionConfiguration( - defaultTimeout: 0.4, - binaryRequestOverallTimeout: 0.4, - binaryRequestRetransmitInterval: 0.05 - ) - ) + let clock = TestClock() + let mesh = MeshCoreSession(transport: transport, clock: clock) try await startSession(mesh, transport: transport) + try #require(clock.sleeperCount == 0) let radioID = UUID() let services = try ServiceContainer( session: mesh, @@ -332,10 +343,10 @@ struct RemoteAdminLifetimeTests { } let sentAtStop = await transport.sentData.count await mesh.stop() - try await Task.sleep(for: .milliseconds(120)) - #expect(await transport.sentData.count == sentAtStop) await behavior.value await statusTask.value + #expect(await transport.sentData.count == sentAtStop) + #expect(clock.sleeperCount == 0) #expect(settings.behaviorError == false) #expect(settings.helper.errorMessage == nil) #expect(status.helper.statusSectionError == nil) diff --git a/MC1Tests/ViewModels/RetainedAdminPartitionTests.swift b/MC1Tests/ViewModels/RetainedAdminPartitionTests.swift new file mode 100644 index 0000000000..95d0b73d22 --- /dev/null +++ b/MC1Tests/ViewModels/RetainedAdminPartitionTests.swift @@ -0,0 +1,121 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Retained remote admin partition admission") +@MainActor +struct RetainedAdminPartitionTests { + @Test(arguments: [RemoteNodeRole.roomServer, .repeater]) + func `retained admin entry points cannot acquire canonical B`(role: RemoteNodeRole) async throws { + try await RetainedConversationPartitionHarness.withHarness { harness in + let appState = harness.environment.appState + await appState.wireServicesIfConnected() + let retained = try await RetainedAdminPartitionSurface.make( + harness: harness, radioID: harness.room.radioID, role: role + ) + defer { retained.close() } + let originallyConfigured = retained.canMakeCLISend() + try #require(originallyConfigured) + appState.navigation.navigateToRoom(with: harness.room) + appState.navigation.navigateToContactDetail(harness.contact) + try await harness.importCanonicalIdentity() + await appState.wireServicesIfConnected() + let perRadioNavigationCleared = appState.navigation.chatsSelectedRoute == nil + && appState.navigation.selectedContact == nil + #expect(perRadioNavigationCleared) + let previousWorkspaceReset = switch role { + case .roomServer: appState.remoteAdminWorkspaces.room(for: retained.session).settings.helper !== retained.settings + case .repeater: appState.remoteAdminWorkspaces.repeater(for: retained.session).settings.helper !== retained.settings + case .sensor: false + } + #expect(previousWorkspaceReset) + let framesBefore = await outgoingAdminFrameCount(harness) + await harness.radio.rejectNext(.sendStatusRequest) + await harness.radio.rejectNext(.sendMessage, count: Self.commandRejections) + + await retained.requestStatus() + let settingsRefused = await retained.sendSettingsCommand() + try await retained.executeCLI(harness: harness) + + #expect(settingsRefused) + let noForeignFrame = await outgoingAdminFrameCount(harness) == framesBefore + #expect(noForeignFrame) + let noFreshForeignCLI = !retained.canMakeCLISend() + #expect(noFreshForeignCLI) + try await harness.proveLaterIO() + } + } + + @Test(arguments: [RemoteNodeRole.roomServer, .repeater]) + func `cached foreign admin is not rebound to canonical B`(role: RemoteNodeRole) async throws { + try await RetainedConversationPartitionHarness.withHarness { harness in + let appState = harness.environment.appState + try await harness.importCanonicalIdentity() + await appState.wireServicesIfConnected() + let retained = try await RetainedAdminPartitionSurface.make( + harness: harness, radioID: harness.room.radioID, role: role + ) + defer { retained.close() } + let framesBefore = await outgoingAdminFrameCount(harness) + await harness.radio.rejectNext(.sendStatusRequest) + await harness.radio.rejectNext(.sendMessage, count: Self.commandRejections) + + await appState.remoteAdminWorkspaces.rebind( + radioID: harness.canonicalRadioID, + repeaterAdminService: { appState.services?.repeaterAdminService }, + roomAdminService: { appState.services?.roomAdminService }, + contactService: { appState.services?.contactService }, + nodeSnapshotService: { appState.services?.nodeSnapshotService }, + deviceHashSize: { appState.connectedDevice?.hashSize }, + remoteNodeService: { appState.connectionSnapshot(for: harness.canonicalRadioID)?.services.remoteNodeService }, + dataStore: { appState.offlineDataStore }, + connectionState: { appState.connectionState }, + isCurrent: { appState.connectionSnapshot(for: harness.canonicalRadioID) != nil } + ) + await retained.requestStatus() + let settingsRefused = await retained.sendSettingsCommand() + + #expect(settingsRefused) + let noForeignFrame = await outgoingAdminFrameCount(harness) == framesBefore + #expect(noForeignFrame) + let noForeignCLI = !retained.canMakeCLISend() + #expect(noForeignCLI) + try await harness.proveLaterIO() + } + } + + @Test(arguments: [RemoteNodeRole.roomServer, .repeater]) + func `current admin entry points still use real wire`(role: RemoteNodeRole) async throws { + try await RetainedConversationPartitionHarness.withHarness { harness in + try await harness.importCanonicalIdentity() + await harness.environment.appState.wireServicesIfConnected() + let current = try await RetainedAdminPartitionSurface.make( + harness: harness, radioID: harness.canonicalRadioID, role: role + ) + defer { current.close() } + let framesBefore = await outgoingAdminFrameCount(harness) + await harness.radio.rejectNext(.sendStatusRequest) + await harness.radio.rejectNext(.sendMessage, count: Self.commandRejections) + + await current.requestStatus() + let settingsSettled = await current.sendSettingsCommand() + try await current.executeCLI(harness: harness) + + #expect(settingsSettled) + let threeActualCommands = await outgoingAdminFrameCount(harness) == framesBefore + Self.currentCommandCount + #expect(threeActualCommands) + try await harness.proveLaterIO() + } + } + + private func outgoingAdminFrameCount(_ harness: RetainedConversationPartitionHarness) async -> Int { + await harness.radio.sentData.filter { + $0.first == CommandCode.sendStatusRequest.rawValue || $0.first == CommandCode.sendMessage.rawValue + }.count + } + + private static let commandRejections = 2 + private static let currentCommandCount = 3 +} diff --git a/MC1Tests/ViewModels/RetainedConversationDMPersistenceAdmissionTests.swift b/MC1Tests/ViewModels/RetainedConversationDMPersistenceAdmissionTests.swift new file mode 100644 index 0000000000..cd83801959 --- /dev/null +++ b/MC1Tests/ViewModels/RetainedConversationDMPersistenceAdmissionTests.swift @@ -0,0 +1,242 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Retained DM persistence admission") +@MainActor +struct RetainedConversationDMPersistenceAdmissionTests { + @Test(arguments: RetainedConversationPartitionTests.ChatAction.allCases, handoffCases) + func `identity handoff refuses new DM persistence`( + action: RetainedConversationPartitionTests.ChatAction, scenario: (window: HandoffWindow, live: TransportType) + ) async throws { + try await RetainedConversationPartitionHarness.withHarness(live: scenario.live) { harness in + let pending = try await harness.seedDirectPending() + let source = try #require(harness.manager.currentConnection) + let gate = Gate() + switch scenario.window { + case .installedTerminal: harness.manager.testIdentityBeforeCommit = { await gate.wait() } + case .selectedTail: await harness.radio.holdSubmissions(for: .setOtherParams) + case .finalSelection: harness.manager.testConnectionSelectionHandler = { _ in await gate.wait() } + } + let importing = Task { + try await harness.importCanonicalIdentity(includeSelectedTail: scenario.window != .installedTerminal) + } + do { + try await harness.waitUntil { + if scenario.window == .selectedTail { + return await harness.radio.submissionIsHeld(for: .setOtherParams) + } + return gate.arrived + } + let originalPartitionStillSelected = harness.environment.appState.currentRadioID == harness.contact.radioID + let sourceQueueRefused = harness.environment.appState.connectionSnapshot(for: harness.contact.radioID) == nil + let handoffIsConnected = harness.manager.connectionState == .connected + try #require(originalPartitionStillSelected) + try #require(sourceQueueRefused) + try #require(handoffIsConnected) + if scenario.window == .installedTerminal { + let installedSourceIsTerminal = harness.manager.isCurrent(source) && !source.services.isAcceptingRuntimeWork + try #require(installedSourceIsTerminal) + } else { + let candidate = try #require(harness.manager.desiredRequest?.attempt) + let canonicalCandidateIsPrivate = harness.manager.currentConnection == nil && harness.manager.services == nil + && candidate.identity.radioID == harness.canonicalRadioID && candidate.preparedServices != nil + && candidate.binding.isActive + try #require(canonicalCandidateIsPrivate) + } + let keyWriteCount = await harness.radio.sentData.filter { $0.first == CommandCode.importPrivateKey.rawValue }.count + try #require(keyWriteCount == 1) + let before = try await harness.store.fetchMessage(id: harness.directMessage.id) + let pendingBefore = try await harness.store.fetchPendingSendsForMessage(messageID: harness.directMessage.id) + let originalFailedMessageAndPending = before == harness.directMessage && pendingBefore == [pending] + try #require(originalFailedMessageAndPending) + let timelineBefore = harness.directModel.messages + let framesBefore = await harness.messageFrameCount() + try await expectLocalHistory(harness) + + await perform(action, in: harness) + + let after = try await harness.store.fetchMessage(id: harness.directMessage.id) + let pendingAfter = try await harness.store.fetchPendingSendsForMessage(messageID: harness.directMessage.id) + let messageUnchanged = after == before + let pendingIdentityAndContentsUnchanged = pendingAfter == pendingBefore + let timelineUnchanged = harness.directModel.messages == timelineBefore + let noMessageFrame = await harness.messageFrameCount() == framesBefore + let canonicalPending = try await harness.store.fetchPendingSends(radioID: harness.canonicalRadioID) + let noCanonicalPending = !canonicalPending.contains { $0.messageID == harness.directMessage.id } + #expect(messageUnchanged) + #expect(pendingIdentityAndContentsUnchanged) + #expect(timelineUnchanged) + #expect(noMessageFrame) + #expect(noCanonicalPending) + try await expectLocalHistory(harness) + + await releaseHandoff(harness, gate: gate) + try await importing.value + let canonicalBPublished = harness.manager.connectedDevice?.radioID == harness.canonicalRadioID + #expect(canonicalBPublished) + let sourcePendingAfterHandoff = try await harness.store.fetchPendingSendsForMessage(messageID: harness.directMessage.id) + let originalPendingPreservedAfterHandoff = sourcePendingAfterHandoff == pendingBefore + #expect(originalPendingPreservedAfterHandoff) + try await harness.proveLaterIO() + } catch { + await releaseHandoff(harness, gate: gate) + _ = await importing.result + throw error + } + } + } + + @Test(arguments: RetainedConversationPartitionTests.ChatAction.allCases, offlineCases) + func `disconnected DM persistence requires same partition`( + action: RetainedConversationPartitionTests.ChatAction, scenario: (canonicalB: Bool, live: TransportType) + ) async throws { + try await RetainedConversationPartitionHarness.withHarness(live: scenario.live) { harness in + let pending = try await harness.seedDirectPending() + if scenario.canonicalB { try await harness.importCanonicalIdentity() } + await harness.environment.appState.disconnect(reason: .userInitiated) + let before = try await harness.store.fetchMessage(id: harness.directMessage.id) + let pendingBefore = try await harness.store.fetchPendingSendsForMessage(messageID: harness.directMessage.id) + let seededOriginalWorkSurvives = before == harness.directMessage && pendingBefore == [pending] + try #require(seededOriginalWorkSurvives) + let fullyDisconnected = harness.manager.connectionState == .disconnected && harness.manager.currentConnection == nil + try #require(fullyDisconnected) + let framesBefore = await harness.messageFrameCount() + if !scenario.canonicalB { try await expectLocalHistory(harness) } + + await perform(action, in: harness) + + let after = try await harness.store.fetchMessage(id: harness.directMessage.id) + let pendingAfter = try await harness.store.fetchPendingSendsForMessage(messageID: harness.directMessage.id) + if scenario.canonicalB { + let foreignMessageUnchanged = after == before + let foreignPendingUnchanged = pendingAfter == pendingBefore + #expect(foreignMessageUnchanged) + #expect(foreignPendingUnchanged) + } else { + let expectedMessage = harness.directMessage.copy { $0.status = .pending } + let samePartitionMessagePending = after == expectedMessage + let replacement = try #require(pendingAfter.first) + let originalPendingReplacedInA = pendingAfter.count == 1 && replacement.id != pending.id + && replacement.radioID == harness.contact.radioID && replacement.messageID == harness.directMessage.id + && replacement.contactID == harness.contact.id && replacement.isResend == (action == .sendAgain) + #expect(samePartitionMessagePending) + #expect(originalPendingReplacedInA) + try await expectLocalHistory(harness) + } + let noOfflineMessageFrame = await harness.messageFrameCount() == framesBefore + let canonicalPending = try await harness.store.fetchPendingSends(radioID: harness.canonicalRadioID) + let noCanonicalPending = !canonicalPending.contains { $0.messageID == harness.directMessage.id } + #expect(noOfflineMessageFrame) + #expect(noCanonicalPending) + } + } + + @Test(arguments: RetainedConversationPartitionTests.ChatAction.allCases, liveCases) + func `current DM persistence reaches real queue`( + action: RetainedConversationPartitionTests.ChatAction, scenario: (phase: DeviceConnectionState, live: TransportType) + ) async throws { + try await RetainedConversationPartitionHarness.withHarness(live: scenario.live) { harness in + let pending = try await harness.seedDirectPending() + let link = try #require(harness.manager.installedLink) + harness.manager.transition(link, to: scenario.phase) + let currentSourceAdmitted = harness.environment.appState.connectionSnapshot(for: harness.contact.radioID) != nil + try #require(currentSourceAdmitted) + let framesBefore = await harness.messageFrameCount() + await harness.radio.rejectNext(.sendMessage) + await harness.radio.holdSubmissions(for: .sendMessage) + do { + await perform(action, in: harness) + try await harness.waitUntil { await harness.radio.submissionIsHeld(for: .sendMessage) } + let stored = try await harness.store.fetchMessage(id: harness.directMessage.id) + let pendingAtSend = try await harness.store.fetchPendingSendsForMessage(messageID: harness.directMessage.id) + let replacement = try #require(pendingAtSend.first) + let actualQueueEntered = pendingAtSend.count == 1 && replacement.id != pending.id + && replacement.radioID == harness.contact.radioID && replacement.messageID == harness.directMessage.id + && replacement.contactID == harness.contact.id && replacement.isResend == (action == .sendAgain) + && replacement.attemptCount == Self.firstDrainAttempt + let storedMessagePending = stored?.status == .pending + #expect(actualQueueEntered) + #expect(storedMessagePending) + await harness.radio.releaseSubmissions(for: .sendMessage) + await harness.joinCurrentChatDrain() + let actualMessageFrame = await harness.messageFrameCount() == framesBefore + 1 + let settledMessage = try await harness.store.fetchMessage(id: harness.directMessage.id) + let pendingAfter = try await harness.store.fetchPendingSendsForMessage(messageID: harness.directMessage.id) + let realRejectionSettled = settledMessage?.status == .failed && pendingAfter.isEmpty + #expect(actualMessageFrame) + #expect(realRejectionSettled) + harness.manager.transition(link, to: .ready) + try await harness.proveLaterIO() + } catch { + await harness.radio.releaseSubmissions(for: .sendMessage) + await harness.joinCurrentChatDrain() + throw error + } + } + } + + private func perform( + _ action: RetainedConversationPartitionTests.ChatAction, in harness: RetainedConversationPartitionHarness + ) async { + switch action { + case .retry: await harness.directModel.retryMessage(harness.directMessage) + case .sendAgain: await harness.directModel.sendAgain(harness.directMessage) + } + } + + private func expectLocalHistory( + _ harness: RetainedConversationPartitionHarness, sourceLocation: SourceLocation = #_sourceLocation + ) async throws { + let history = try await harness.directModel.dataStore?.fetchMessages(contactID: harness.contact.id) + let retainedLocalHistoryReadable = history?.contains { $0.id == harness.directMessage.id } == true + #expect(retainedLocalHistoryReadable, sourceLocation: sourceLocation) + } + + private func releaseHandoff(_ harness: RetainedConversationPartitionHarness, gate: Gate) async { + gate.open() + await harness.radio.releaseSubmissions(for: .setOtherParams) + harness.manager.testIdentityBeforeCommit = nil + harness.manager.testConnectionSelectionHandler = nil + } + + enum HandoffWindow: CaseIterable, Sendable { case installedTerminal, selectedTail, finalSelection } + + private nonisolated static let handoffCases: [(window: HandoffWindow, live: TransportType)] = + [TransportType.bluetooth, .wifi].flatMap { live in + HandoffWindow.allCases.map { (window: $0, live: live) } + } + + private nonisolated static let offlineCases: [(canonicalB: Bool, live: TransportType)] = + [TransportType.bluetooth, .wifi].flatMap { live in + [false, true].map { (canonicalB: $0, live: live) } + } + + private nonisolated static let liveCases: [(phase: DeviceConnectionState, live: TransportType)] = + [TransportType.bluetooth, .wifi].flatMap { live in + [DeviceConnectionState.connected, .syncing, .ready].map { (phase: $0, live: live) } + } + + private static let firstDrainAttempt = 1 + + @MainActor + private final class Gate { + private(set) var arrived = false + private var opened = false + private var continuation: CheckedContinuation? + + func wait() async { + arrived = true + guard !opened else { return } + await withCheckedContinuation { continuation = $0 } + } + + func open() { + opened = true + continuation?.resume() + continuation = nil + } + } +} diff --git a/MC1Tests/ViewModels/RetainedConversationPartitionTests.swift b/MC1Tests/ViewModels/RetainedConversationPartitionTests.swift new file mode 100644 index 0000000000..ab1efc4fef --- /dev/null +++ b/MC1Tests/ViewModels/RetainedConversationPartitionTests.swift @@ -0,0 +1,107 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Retained conversation partition admission") +@MainActor +struct RetainedConversationPartitionTests { + @Test(arguments: ChatAction.allCases, [false, true]) + func `retained chat action cannot acquire canonical B`(action: ChatAction, channel: Bool) async throws { + try await RetainedConversationPartitionHarness.withHarness { harness in + let model = channel ? harness.channelModel : harness.directModel + let message = channel ? harness.channelMessage : harness.directMessage + harness.environment.appState.navigation.setChatsRoute(channel ? .channel(harness.channel) : .direct(harness.contact)) + try await harness.importCanonicalIdentity() + let before = try await harness.store.fetchMessage(id: message.id) + let framesBefore = await harness.messageFrameCount() + await harness.radio.rejectNext(.sendMessage) + + switch (action, channel) { + case (.sendAgain, _): await model.sendAgain(message) + case (.retry, false): await model.retryMessage(message) + case (.retry, true): await model.retryChannelMessage(message) + } + await harness.joinCurrentChatDrain() + + let framesAfter = await harness.messageFrameCount() + let noForeignFrame = framesAfter == framesBefore + #expect(noForeignFrame) + let canonicalPending = try await harness.store.fetchPendingSends(radioID: harness.canonicalRadioID) + let noForeignPending = !canonicalPending.contains { $0.messageID == message.id } + #expect(noForeignPending) + let after = try await harness.store.fetchMessage(id: message.id) + let retainedHistoryUnchanged = after == before + #expect(retainedHistoryUnchanged) + let sourcePending = try await harness.store.fetchPendingSends(radioID: harness.environment.device.radioID) + let noNewSourcePending = !sourcePending.contains { $0.messageID == message.id } + #expect(noNewSourcePending) + try await harness.proveLaterIO() + } + } + + @Test(arguments: RoomAction.allCases) + func `retained room action cannot acquire canonical B`(action: RoomAction) async throws { + try await RetainedConversationPartitionHarness.withHarness { harness in + harness.environment.appState.navigation.navigateToRoom(with: harness.room) + try await harness.importCanonicalIdentity() + let before = try await harness.store.fetchRoomMessages(sessionID: harness.room.id) + let framesBefore = await harness.messageFrameCount() + await harness.radio.rejectNext(.sendMessage) + + switch action { + case .post: await harness.roomModel.sendMessage(text: Self.newRoomText) + case .retry: await harness.roomModel.retryMessage(id: harness.roomMessage.id) + } + if action == .post, + let admitted = try await harness.store.fetchRoomMessages(sessionID: harness.room.id).first(where: { $0.text == Self.newRoomText }) { + try await harness.waitUntil { + await (try? harness.store.fetchRoomMessage(id: admitted.id)?.status) == .failed + } + } + + let framesAfter = await harness.messageFrameCount() + let noForeignFrame = framesAfter == framesBefore + #expect(noForeignFrame) + let after = try await harness.store.fetchRoomMessages(sessionID: harness.room.id) + let retainedHistoryUnchanged = after == before + #expect(retainedHistoryUnchanged) + try await harness.proveLaterIO() + } + } + + @Test(arguments: [false, true]) + func `same partition chat send again still enters real queue`(channel: Bool) async throws { + try await RetainedConversationPartitionHarness.withHarness { harness in + let model = channel ? harness.channelModel : harness.directModel + let message = channel ? harness.channelMessage : harness.directMessage + let framesBefore = await harness.messageFrameCount() + await harness.radio.rejectNext(.sendMessage) + + await model.sendAgain(message) + await harness.joinCurrentChatDrain() + + let framesAfter = await harness.messageFrameCount() + let realSendEntered = framesAfter == framesBefore + 1 + #expect(realSendEntered) + try await harness.proveLaterIO() + } + } + + @Test + func `disconnected same partition store still reads history`() async throws { + try await RetainedConversationPartitionHarness.withHarness { harness in + await harness.environment.appState.disconnect(reason: .userInitiated) + + let messages = try await harness.directModel.dataStore?.fetchMessages(contactID: harness.contact.id) + + let retainedOfflineHistory = messages?.contains { $0.id == harness.directMessage.id } == true + #expect(retainedOfflineHistory) + } + } + + enum ChatAction: CaseIterable, Sendable { case sendAgain, retry } + enum RoomAction: CaseIterable, Sendable { case post, retry } + private static let newRoomText = "Refuse retained A room post" +} diff --git a/MC1Tests/ViewModels/RetainedConversationSourceSiblingTests.swift b/MC1Tests/ViewModels/RetainedConversationSourceSiblingTests.swift new file mode 100644 index 0000000000..0ef9f83528 --- /dev/null +++ b/MC1Tests/ViewModels/RetainedConversationSourceSiblingTests.swift @@ -0,0 +1,182 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Retained conversation source siblings") +@MainActor +struct RetainedConversationSourceSiblingTests { + @Test(arguments: RetainedConversationPartitionTests.RoomAction.allCases) + func `terminal installed source refuses room mutation`(action: RetainedConversationPartitionTests.RoomAction) async throws { + try await RetainedConversationPartitionHarness.withHarness { harness in + let gate = Gate() + harness.manager.testIdentityBeforeCommit = { await gate.wait() } + let transition = Task { try await harness.importCanonicalIdentity() } + do { + try await harness.waitUntil { await gate.arrived } + let source = harness.manager.currentConnection + let installedAIsTerminal = source?.device.radioID == harness.room.radioID + && source?.services.isAcceptingRuntimeWork == false + try #require(installedAIsTerminal) + let sourceStillManagerCurrent = source.map { harness.manager.isCurrent($0) } == true + try #require(sourceStillManagerCurrent) + let before = try await harness.store.fetchRoomMessages(sessionID: harness.room.id) + let framesBefore = await harness.messageFrameCount() + + switch action { + case .post: await harness.roomModel.sendMessage(text: Self.roomPost) + case .retry: await harness.roomModel.retryMessage(id: harness.roomMessage.id) + } + + let after = try await harness.store.fetchRoomMessages(sessionID: harness.room.id) + let historyUnchanged = before == after + let noTerminalFrame = await harness.messageFrameCount() == framesBefore + #expect(historyUnchanged) + #expect(noTerminalFrame) + await gate.open() + try await transition.value + harness.manager.testIdentityBeforeCommit = nil + try await harness.proveLaterIO() + } catch { + await gate.open() + _ = try? await transition.value + harness.manager.testIdentityBeforeCommit = nil + throw error + } + } + } + + @Test(arguments: [DeviceConnectionState.connected, .syncing, .ready]) + func `ordinary installed source can load room history`(phase: DeviceConnectionState) async throws { + try await RetainedConversationPartitionHarness.withHarness { harness in + let link = harness.manager.installedLink + let installed = link != nil + try #require(installed) + guard let link else { return } + harness.manager.transition(link, to: phase) + let appState = harness.environment.appState + let radioID = harness.room.radioID + let model = RoomConversationViewModel() + model.configure( + roomServerService: { appState.connectionSnapshot(for: radioID)?.services.roomServerService }, + dataStore: { appState.connectionSnapshot(for: radioID)?.services.dataStore }, + syncCoordinator: { appState.connectionSnapshot(for: radioID)?.services.syncCoordinator }, + notificationService: { appState.connectionSnapshot(for: radioID)?.services.notificationService } + ) + + await model.loadMessages(for: harness.room) + + let loadedStoredHistory = model.messages.contains { $0.id == harness.roomMessage.id } + #expect(loadedStoredHistory) + harness.manager.transition(link, to: .ready) + try await harness.proveLaterIO() + } + } + + @Test(arguments: RetainedConversationPartitionTests.RoomAction.allCases) + func `same partition room actions still reach real wire`(action: RetainedConversationPartitionTests.RoomAction) async throws { + try await RetainedConversationPartitionHarness.withHarness { harness in + let framesBefore = await harness.messageFrameCount() + await harness.radio.rejectNext(.sendMessage) + + switch action { + case .post: + await harness.roomModel.sendMessage(text: Self.roomPost) + try await harness.waitUntil { + await (try? harness.store.fetchRoomMessages(sessionID: harness.room.id).contains { + $0.text == Self.roomPost && $0.status == .failed + }) == true + } + case .retry: + await harness.roomModel.retryMessage(id: harness.roomMessage.id) + let updated = try await harness.store.fetchRoomMessage(id: harness.roomMessage.id) + let actualRetryRecorded = updated?.retryAttempt == harness.roomMessage.retryAttempt + 1 + #expect(actualRetryRecorded) + } + + let actualSendEntered = await harness.messageFrameCount() == framesBefore + 1 + #expect(actualSendEntered) + try await harness.proveLaterIO() + } + } + + @Test(arguments: [false, true]) + func `offline retry only mutates current partition`(canonicalB: Bool) async throws { + try await RetainedConversationPartitionHarness.withHarness { harness in + if canonicalB { try await harness.importCanonicalIdentity() } + await harness.environment.appState.disconnect(reason: .userInitiated) + let before = try await harness.store.fetchMessage(id: harness.directMessage.id) + let framesBefore = await harness.messageFrameCount() + + await harness.directModel.retryMessage(harness.directMessage) + + let sourcePending = try await harness.store.fetchPendingSends(radioID: harness.contact.radioID) + let pendingMatchesAdmission = sourcePending.contains { $0.messageID == harness.directMessage.id } == !canonicalB + #expect(pendingMatchesAdmission) + let after = try await harness.store.fetchMessage(id: harness.directMessage.id) + let statusMatchesAdmission = canonicalB ? after == before : after?.status == .pending + #expect(statusMatchesAdmission) + let noOfflineFrame = await harness.messageFrameCount() == framesBefore + #expect(noOfflineFrame) + let foreignPending = try await harness.store.fetchPendingSends(radioID: harness.canonicalRadioID) + let noForeignPending = !foreignPending.contains { $0.messageID == harness.directMessage.id } + #expect(noForeignPending) + } + } + + @Test + func `Persist-to-signal split-boundary equivalence preserves accepted A work`() async throws { + try await RetainedConversationPartitionHarness.withHarness { harness in + let envelope = DirectMessageEnvelope( + messageID: harness.directMessage.id, contactID: harness.contact.id, isResend: true + ) + let pending = PendingSendDTO(envelope: envelope, radioID: harness.contact.radioID) + _ = try await harness.store.replacePendingSendForRetry(messageID: harness.directMessage.id, dto: pending) + try await harness.importCanonicalIdentity() + let acceptedBefore = try await harness.store.fetchPendingSends(radioID: harness.contact.radioID) + let acceptedAExists = acceptedBefore.contains { $0.id == pending.id } + try #require(acceptedAExists) + let framesBefore = await harness.messageFrameCount() + var refusedNewQueue = false + + do { + try await harness.directModel.signalDMEnqueued(envelope) + } catch ChatSendQueueServiceError.notConnected { + refusedNewQueue = true + } + await harness.joinCurrentChatDrain() + + #expect(refusedNewQueue) + let noForeignFrame = await harness.messageFrameCount() == framesBefore + #expect(noForeignFrame) + let acceptedAfter = try await harness.store.fetchPendingSends(radioID: harness.contact.radioID) + let acceptedWorkPreserved = acceptedAfter == acceptedBefore + #expect(acceptedWorkPreserved) + let foreignPending = try await harness.store.fetchPendingSends(radioID: harness.canonicalRadioID) + let noForeignPending = !foreignPending.contains { $0.messageID == harness.directMessage.id } + #expect(noForeignPending) + try await harness.proveLaterIO() + } + } + + private actor Gate { + private(set) var arrived = false + private var opened = false + private var continuation: CheckedContinuation? + + func wait() async { + arrived = true + guard !opened else { return } + await withCheckedContinuation { continuation = $0 } + } + + func open() { + opened = true + continuation?.resume() + continuation = nil + } + } + + private static let roomPost = "Refuse terminal A post" +} diff --git a/MC1Tests/ViewModels/RoomConversationViewModelTranslationTests.swift b/MC1Tests/ViewModels/RoomConversationViewModelTranslationTests.swift index a887e97d2b..3e293cff9b 100644 --- a/MC1Tests/ViewModels/RoomConversationViewModelTranslationTests.swift +++ b/MC1Tests/ViewModels/RoomConversationViewModelTranslationTests.swift @@ -45,6 +45,21 @@ struct RoomConversationViewModelTranslationTests { #expect(viewModel.detectedLanguages[message.id] == nil) } + @Test + func `incoming reading keeps nil translation and the wire displayedText`() throws { + let viewModel = RoomConversationViewModel() + viewModel.preferredLanguageCode = "en" + let text = "MECP/0/M01 \(german)" + let message = roomMessage(text: text) + viewModel.detectedLanguages[message.id] = .identified(languageCode: "de") + viewModel.appendMessageIfNew(message) + + let row = try #require(viewModel.tiledRows.first) + #expect(viewModel.detectedLanguages[message.id] == .identified(languageCode: "de")) + #expect(row.translation == nil) + #expect(viewModel.displayedText(for: row.message) == text) + } + @Test func `detector maps land chrome on the materialized row`() throws { let viewModel = RoomConversationViewModel() diff --git a/MC1Tests/ViewModels/SensorSettingsViewModelTests.swift b/MC1Tests/ViewModels/SensorSettingsViewModelTests.swift new file mode 100644 index 0000000000..7e1c530f85 --- /dev/null +++ b/MC1Tests/ViewModels/SensorSettingsViewModelTests.swift @@ -0,0 +1,275 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("Sensor settings workspace", .timeLimit(.minutes(1))) +@MainActor +struct SensorSettingsViewModelTests { + private static let commandTimeout: TimeInterval = 10 + /// A CLI poll sleeps at most half a second. A command wait uses `commandTimeout`. + private static let pollSleepCeiling: Duration = .seconds(1) + private static let pollReleaseSettle: Duration = .milliseconds(100) + + @MainActor + private final class Harness { + let transport = MockTransport() + let clock: TestClock + let session: MeshCoreSession + let store: PersistenceStore + let remote: RemoteNodeService + let descriptor: RemoteNodeSessionDTO + let workspaces = RemoteAdminWorkspaces() + var currentRemote: RemoteNodeService? + var model: SensorSettingsViewModel { + workspaces.sensor(for: descriptor).settings + } + + init() async throws { + clock = TestClock() + session = MeshCoreSession( + transport: transport, + configuration: SessionConfiguration(defaultTimeout: SensorSettingsViewModelTests.commandTimeout, clientIdentifier: "Test"), + clock: clock + ) + store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + descriptor = RemoteNodeSessionDTO(radioID: UUID(), publicKey: Data(repeating: 0xA4, count: 32), + name: "Sensor", role: .sensor, isConnected: true, permissionLevel: .admin) + remote = RemoteNodeService(session: session, dataStore: store, keychainService: KeychainService()) + currentRemote = remote + try await store.saveRemoteNodeSessionDTO(descriptor) + let start = Task { try await session.start() } + try await waitUntil("app start should send") { await self.transport.sentData.count == 1 } + var info = Data([ResponseCode.selfInfo.rawValue, 1, 22, 22]) + info.append(Data(repeating: 1, count: 32)) + info.append(Data(repeating: 0, count: 12)) + info.append(contentsOf: withUnsafeBytes(of: UInt32(915_000).littleEndian) { Array($0) }) + info.append(contentsOf: withUnsafeBytes(of: UInt32(250_000).littleEndian) { Array($0) }) + info.append(contentsOf: [7, 5]) + await transport.simulateReceive(info) + try await start.value + try #require(clock.sleeperCount == 0) + await transport.clearSentData() + await remote.startEventMonitoring() + configure() + try await waitUntil("persisted authorization should load") { self.model.isAuthorized } + } + + func configure() { + workspaces.configureSensor(for: descriptor, remoteNodeService: { [weak self] in self?.currentRemote }, + dataStore: { [weak self] in self?.store }, connectionState: { .ready }) + } + + var commands: [Data] { + get async { await transport.sentData.filter { $0.first == CommandCode.sendMessage.rawValue } } + } + + func reply(_ text: String, index: Int, hostFirst: Bool = true) async throws { + try await waitUntil("CLI command should send") { await self.commands.count > index } + let frame = await commands[index] + let headerSize = 13 + let command = String(decoding: frame.dropFirst(headerSize), as: UTF8.self) + let prefix = try #require(CLIResponse.splitEchoedPrefix(command)?.prefix) + if hostFirst { await acceptHost() } + await session.dispatcher.dispatch(.contactMessageReceived(ContactMessage( + senderPublicKeyPrefix: Data(descriptor.publicKey.prefix(6)), pathLength: 0, textType: 1, + senderTimestamp: Date(), signature: nil, text: prefix + text, snr: nil + ))) + if !hostFirst { await acceptHost() } + await session.dispatcher.dispatch(.noMoreMessages) + try await releaseCLIPoll() + } + + /// The CLI poll holds the serializer until its short sleep ends. Wake that sleep after the reply. + /// A follow-up command then parks on the full command timeout; leave that wait for the next reply. + private func releaseCLIPoll() async throws { + let sentAtRelease = await commands.count + var idleSince: ContinuousClock.Instant? + try await waitUntil(timeout: .seconds(2), "cli poll should release the session") { + if self.clock.sleeperCount > 0, + let parked = self.clock.nextSleepDuration, + parked < SensorSettingsViewModelTests.pollSleepCeiling { + self.clock.advanceToNextSleep() + idleSince = nil + return false + } + let callers = await self.session.getMessageCallerCountForTest + guard callers == 0 else { + idleSince = nil + return false + } + if self.clock.sleeperCount > 0 { + idleSince = nil + return await self.commands.count > sentAtRelease + } + let start = idleSince ?? ContinuousClock.now + if idleSince == nil { idleSince = start } + return ContinuousClock.now - start >= SensorSettingsViewModelTests.pollReleaseSettle + } + } + + func acceptHost() async { + await session.dispatcher.dispatch(.messageSent(MessageSentInfo(route: 0, expectedAck: Data(), suggestedTimeoutMs: 1))) + } + + func load(_ text: String = "1 vars\ngps=0") async throws { + let count = await commands.count + let task = Task { await model.reload() } + try await reply(text, index: count) + await task.value + #expect(model.hasLoaded) + } + + func close() async { + workspaces.reset() + await currentRemote?.retire() + await remote.retire() + await session.stop() + } + } + + @Test(arguments: [true, false]) + func `settings load in either reply order and empty is complete`(hostFirst: Bool) async throws { + let h = try await Harness() + let load = Task { await h.model.reload() } + try await h.reply("no custom var", index: 0, hostFirst: hostFirst) + await load.value + #expect(h.model.hasLoaded) + #expect(h.model.settings.isEmpty) + #expect(h.model.errorMessage == nil) + #expect(h.model.canSend) + await h.close() + } + + @Test + func `accepted save survives reopening and preserves A newer draft`() async throws { + let h = try await Harness() + try await h.load() + h.model[draft: "gps"] = "1" + h.model.save("gps") + h.model.save("gps") + try await waitUntil("one setter should send") { await h.commands.count == 2 } + let reopened = h.workspaces.sensor(for: h.descriptor).settings + #expect(reopened === h.model) + #expect(reopened.isMutating) + h.configure() + h.model[draft: "gps"] = "2" + try await h.reply("ok", index: 1) + try await h.reply("> 1", index: 2) + try await waitUntil("verification should finish") { !h.model.isMutating } + #expect(h.model.settings.first?.value == "1") + #expect(h.model[draft: "gps"] == "2") + #expect(h.model.canSave("gps")) + #expect(h.model.statusMessage == L10n.RemoteNodes.RemoteNodes.Sensor.saved) + #expect(await h.commands.count == 3) + await h.close() + } + + @Test + func `verification mismatch requires reload without discarding draft`() async throws { + let h = try await Harness() + try await h.load() + h.model[draft: "gps"] = "1" + h.model.save("gps") + try await h.reply("ok", index: 1) + try await h.reply("> 0", index: 2) + try await waitUntil("unknown outcome should be published") { h.model.requiresReload && !h.model.isMutating } + #expect(h.model[draft: "gps"] == "1") + #expect(h.model.errorMessage != nil) + #expect(!h.model.canSave("gps")) + h.model.save("gps") + #expect(await h.commands.count == 3) + try await h.load() + #expect(!h.model.requiresReload) + #expect(h.model[draft: "gps"] == "1") + #expect(h.model.canSave("gps")) + await h.close() + } + + @Test + func `reload keeps A draft edited while the read was pending`() async throws { + let h = try await Harness() + try await h.load() + let task = Task { await h.model.reload() } + try await waitUntil("reload should send") { await h.commands.count == 2 } + h.model[draft: "gps"] = "draft" + try await h.reply("1 vars\ngps=1", index: 1) + await task.value + #expect(h.model.settings.first?.value == "1") + #expect(h.model[draft: "gps"] == "draft") + await h.close() + } + + @Test + func `provider replacement cancels mutation and cannot replay it`() async throws { + let h = try await Harness() + try await h.load() + h.model[draft: "gps"] = "1" + h.model.save("gps") + try await waitUntil("setter should send") { await h.commands.count == 2 } + let replacement = RemoteNodeService(session: h.session, dataStore: h.store, keychainService: KeychainService()) + await replacement.startEventMonitoring() + h.currentRemote = replacement + h.configure() + #expect(!h.model.isMutating) + #expect(h.model.requiresReload) + try await h.reply("ok", index: 1) + #expect(h.model.settings.first?.value == "0") + #expect(h.model.statusMessage == nil) + #expect(h.model[draft: "gps"] == "1") + #expect(await h.commands.count == 2) + await h.close() + } + + @Test + func `rebind ignores a foreign radio and an obsolete connection`() async throws { + let h = try await Harness() + let replacement = RemoteNodeService(session: h.session, dataStore: h.store, keychainService: KeychainService()) + for (radioID, isCurrent) in [(UUID(), true), (h.descriptor.radioID, false)] { + await h.workspaces.rebind( + radioID: radioID, + repeaterAdminService: { nil }, + roomAdminService: { nil }, + contactService: { nil }, + nodeSnapshotService: { nil }, + deviceHashSize: { nil }, + remoteNodeService: { replacement }, + dataStore: { h.store }, + connectionState: { .ready }, + isCurrent: { isCurrent } + ) + #expect(h.model.isBound(to: h.remote)) + #expect(h.model.isAuthorized) + } + await h.close() + } + + @Test + func `reboot waits for host acceptance then disables further commands`() async throws { + let h = try await Harness() + h.model.reboot() + h.model.reboot() + try await waitUntil("one reboot should send") { await h.commands.count == 1 } + #expect(h.model.isMutating) + #expect(h.model.statusMessage == nil) + await h.acceptHost() + try await waitUntil("accepted reboot should finish") { !h.model.isMutating } + #expect(!h.model.isAuthorized) + #expect(h.model.statusMessage == L10n.RemoteNodes.RemoteNodes.Sensor.rebootSent) + h.model.reboot() + #expect(await h.commands.count == 1) + await h.close() + } + + @Test + func `session events disable controls without erasing outcomes`() async throws { + let h = try await Harness() + try await h.load() + await h.remote.disconnect(sessionID: h.descriptor.id) + try await waitUntil("session event should revoke controls") { !h.model.isAuthorized } + #expect(h.model.settings.first?.value == "0") + #expect(!h.model.canSave("gps")) + await h.close() + } +} diff --git a/MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests+DirectActions.swift b/MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests+DirectActions.swift new file mode 100644 index 0000000000..711318ea91 --- /dev/null +++ b/MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests+DirectActions.swift @@ -0,0 +1,170 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +extension SettingsIdentityMetadataProvenanceTests { + @Test(arguments: [DirectIdentityCase.bluetoothImport, .wifiImport, .bluetoothRegenerate, .wifiRegenerate], + [DirectOutcome.success, .rejected, .disabled]) + func `standalone identity actions keep their settings event persistence`( + entry: DirectIdentityCase, outcome: DirectOutcome + ) async throws { + let action = entry.action + try await ConnectionLinkSwitchHarness.withHarness(live: entry.transport, wifiHost: "source.local") { env in + let radio = entry.transport == .bluetooth ? env.bluetooth : env.wifi + await env.appState.wireServicesIfConnected() + guard let source = env.manager.currentConnection else { + throw NSError(domain: "SettingsIdentityMetadataProvenance", code: 3) + } + await radio.setIdentityImportPublicKey(Self.importedPublicKey) + switch outcome { + case .success: break + case .rejected: await radio.rejectNext(.importPrivateKey) + case .disabled: + await radio.setResponsePackets(for: .importPrivateKey, packets: [Data([ResponseCode.disabled.rawValue])]) + } + let importModel = ImportKeyViewModel() + importModel.configure(settingsService: { env.manager.services?.settingsService }) + let regenerateModel = RegenerateIdentityViewModel() + regenerateModel.configure(settingsService: { env.manager.services?.settingsService }) + let expandedKey = Data([ + 0x70, 0x65, 0xE1, 0x8F, 0xD9, 0xFA, 0xBB, 0x70, 0xC1, 0xED, 0x90, 0xDC, 0xA1, 0x99, 0x07, 0xDE, + 0x69, 0x8C, 0x88, 0xB7, 0x09, 0xEA, 0x14, 0x6E, 0xAF, 0xD9, 0x3D, 0x9B, 0x83, 0x0C, 0x7B, 0x60, + 0xC4, 0x68, 0x11, 0x93, 0xC7, 0x9B, 0xBC, 0x39, 0x94, 0x5B, 0xA8, 0x06, 0x41, 0x04, 0xBB, 0x61, + 0x8F, 0x8F, 0xD7, 0xA8, 0x4A, 0x0A, 0xF6, 0xF5, 0x70, 0x33, 0xD6, 0xE8, 0xDD, 0xCD, 0x64, 0x71 + ]) + let succeeded: Bool + switch action { + case .importKey: + importModel.hexInput = Self.expandedKeyHex + importModel.validateAndConfirm() + let confirmationIsReady = importModel.showingReplaceAlert && importModel.errorMessage == nil + try #require(confirmationIsReady) + succeeded = await importModel.importKey() + case .regenerate: + regenerateModel.generatedKey = .init( + expandedKey: expandedKey, publicKeyHex: Self.importedPublicKey.hexString, + privateKeyHex: Self.expandedKeyHex, accessibilityLabel: "Synthetic public key" + ) + succeeded = await regenerateModel.replaceIdentity() + } + let successCount = action == .importKey ? importModel.successTrigger : regenerateModel.successTrigger + let outcomeError = action == .importKey ? importModel.errorMessage : regenerateModel.errorMessage + let expectedKey = outcome == .success ? Self.importedPublicKey : source.device.publicKey + if outcome == .success { + try await waitUntil("the real direct action refresh must reach AppState") { + env.manager.connectedDevice?.publicKey == Self.importedPublicKey + } + } + await env.manager.metadataCommitTask?.value + let stored = try await env.manager.persistenceStore.fetchDevice(id: source.device.id) + let storedKeyIsExpected = stored?.publicKey == expectedKey + let publishedKeyIsExpected = env.manager.connectedDevice?.publicKey == expectedKey + let stableIdentityAxesAndMethods = stored?.id == source.device.id && stored?.radioID == source.device.radioID + && stored?.connectionMethods == source.device.connectionMethods + let oneKeyAttempt = await radio.sentData.filter { $0.first == CommandCode.importPrivateKey.rawValue }.count == 1 + #expect(succeeded == (outcome == .success)) + #expect(successCount == (outcome == .success ? 1 : 0)) + #expect(storedKeyIsExpected) + #expect(publishedKeyIsExpected) + #expect(stableIdentityAxesAndMethods) + #expect(oneKeyAttempt) + switch outcome { + case .success: #expect(outcomeError == nil) + case .rejected: #expect(outcomeError == L10n.Settings.RegenerateIdentity.Error.deviceRejected) + case .disabled: #expect(outcomeError == L10n.Settings.RegenerateIdentity.Error.featureDisabled) + } + let laterTime = try await source.services.settingsService.getTime() + #expect(laterTime.timeIntervalSince1970 > 0) + } + } + + @Test + func `accepted verified settings event merges before same radio replacement dials`() async throws { + let env = try await ConnectionLinkSwitchHarness.make(wifiHost: "source.local") + let gate = Gate() + var blocker: Task? + var setter: Task? + var successor: Task? + var bodyError: (any Error)? + do { + await env.appState.wireServicesIfConnected() + guard let source = env.manager.currentConnection else { + throw NSError(domain: "SettingsIdentityMetadataProvenance", code: 3) + } + await env.wifi.setConnectError(nil) + await env.wifi.holdConnect() + blocker = env.manager.enqueueMetadata { store in + await gate.wait() + try await store.addDeviceKnownRegion(radioID: source.device.radioID, region: "Accepted local region") + } + await env.bluetooth.enqueueResponsePackets( + for: .appStart, packets: [Self.telemetryPacket(publicKey: source.device.publicKey)] + ) + await env.bluetooth.enqueueResponsePackets( + for: .appStart, packets: [Self.telemetryPacket(publicKey: source.device.publicKey)] + ) + setter = Task { + _ = try await source.services.settingsService.setOtherParamsVerified( + autoAddContacts: !source.device.manualAddContacts, telemetryModes: Self.telemetryModes, + advertLocationPolicy: source.device.advertLocationPolicyMode, multiAcks: source.device.multiAcks + ) + } + try await setter?.value + try await waitUntil("the ordinary Settings event must be accepted before retirement") { + env.manager.connectedDevice?.telemetryModeBase == Self.telemetryMarker + } + successor = Task { try await env.manager.connectViaWiFi(host: "source.local", port: ConnectionMethod.defaultWiFiPort) } + try await waitUntil("the same-radio successor must retire the event's original request") { + env.manager.connectionRequestID != source.requestID + } + let noEarlySuccessorDial = await env.wifi.connectCount == env.initialWiFiAttempts + #expect(noEarlySuccessorDial) + gate.open() + try await blocker?.value + try await waitUntil("the actual successor dial must follow accepted metadata settlement") { await env.wifi.connectIsHeld } + let saved = try await env.manager.persistenceStore.fetchDevice(id: source.device.id) + let acceptedFieldIsSaved = saved?.telemetryModeBase == Self.telemetryMarker + let unrelatedFreshFieldSurvives = saved?.knownRegions == ["Accepted local region"] + let originalTupleSurvives = saved?.id == source.device.id && saved?.radioID == source.device.radioID + && saved?.publicKey == source.device.publicKey + #expect(acceptedFieldIsSaved) + #expect(unrelatedFreshFieldSurvives) + #expect(originalTupleSurvives) + await env.wifi.releaseConnect() + _ = try await successor?.value + let laterTime = try await env.manager.services?.settingsService.getTime() + #expect(laterTime != nil) + } catch { + bodyError = error + } + gate.open() + setter?.cancel() + successor?.cancel() + await env.bluetooth.releaseAllGates() + await env.wifi.releaseAllGates() + _ = await blocker?.result + _ = await setter?.result + _ = await successor?.result + await env.manager.metadataCommitTask?.value + await env.close() + await env.manager.retirementTask?.value + if let bodyError { throw bodyError } + } + + enum DirectAction: Sendable { case importKey, regenerate } + enum DirectOutcome: Sendable { case success, rejected, disabled } + + enum DirectIdentityCase: Sendable { + case bluetoothImport, wifiImport, bluetoothRegenerate, wifiRegenerate + + var action: DirectAction { + self == .bluetoothImport || self == .wifiImport ? .importKey : .regenerate + } + + var transport: TransportType { + self == .bluetoothImport || self == .bluetoothRegenerate ? .bluetooth : .wifi + } + } +} diff --git a/MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests+Fixture.swift b/MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests+Fixture.swift new file mode 100644 index 0000000000..2912b34c23 --- /dev/null +++ b/MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests+Fixture.swift @@ -0,0 +1,93 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +extension SettingsIdentityMetadataProvenanceTests { + static let telemetryMarker: UInt8 = 1 + static let authenticatedTelemetryBase: UInt8 = 0 + static let telemetryModes = TelemetryModes(base: telemetryMarker, location: 0, environment: 0) + static let importedPublicKey = Data([ + 0x1E, 0xC7, 0x71, 0x75, 0xB0, 0x91, 0x8E, 0xD2, 0x06, 0xF9, 0xAE, 0x04, 0xEC, 0x13, 0x6D, 0x6D, + 0x5D, 0x43, 0x15, 0xBB, 0x26, 0x30, 0x54, 0x27, 0xF6, 0x45, 0xB4, 0x92, 0xE9, 0x35, 0x0C, 0x10 + ]) + static let expandedKeyHex = "7065e18fd9fabb70c1ed90dca19907de698c88b709ea146eafd93d9b830c7b60" + + "c4681193c79bbc39945ba8064104bb618f8fd7a84a0af6f57033d6e8ddcd6471" + static let config = MeshCoreNodeConfig(privateKey: expandedKeyHex, otherSettings: .init(multiAcks: 1)) + static let selectedTailPacket = PacketBuilder.setOtherParams( + manualAddContacts: false, telemetryModeEnvironment: 0, telemetryModeLocation: 0, + telemetryModeBase: authenticatedTelemetryBase, advertisementLocationPolicy: 0, multiAcks: 1 + ) + static let streamFenceMarker: UInt8 = 1 + static let continuationPreset = RadioPreset( + id: "continuation-source", name: "Continuation source", region: .northAmerica, + frequencyMHz: 915, bandwidthKHz: 125, spreadingFactor: 7, codingRate: 5, + pathHashSize: 1, availability: .countries(["US"]) + ) + + static func telemetryPacket(publicKey: Data) -> Data { + var packet = Data([ResponseCode.selfInfo.rawValue, 1, 22, 22]) + packet.append(publicKey) + packet.append(Data(repeating: 0, count: 8)) + packet.append(contentsOf: [0, 0, telemetryMarker, 0]) + for value: UInt32 in [915_000, 125_000] { + packet.append(withUnsafeBytes(of: value.littleEndian) { Data($0) }) + } + packet.append(contentsOf: [7, 5]) + packet.append(contentsOf: "Test Radio".utf8) + return packet + } + + func selectFile(_ config: MeshCoreNodeConfig, model: NodeConfigImportViewModel) async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("config.json") + try JSONEncoder().encode(config).write(to: url) + model.parseFile(at: url) + await model.parseTask?.value + let selectedInputWasParsed = model.importedConfig != nil && !model.isParsing && model.errorMessage == nil + try #require(selectedInputWasParsed) + let onlyIdentityAndOtherSettingsAreSelected = model.sections.nodeIdentity && model.sections.otherSettings + && !model.sections.radioSettings && !model.sections.positionSettings && !model.sections.channels && !model.sections.contacts + try #require(onlyIdentityAndOtherSettingsAreSelected) + } + + func waitUntil(_ reason: String, _ predicate: @escaping @MainActor () async -> Bool) async throws { + let deadline = ContinuousClock.now + Timing.timeout + while await !predicate() { + guard ContinuousClock.now < deadline else { + throw NSError(domain: "SettingsIdentityMetadataProvenance", code: 1, userInfo: [NSLocalizedDescriptionKey: reason]) + } + try await Task.sleep(for: Timing.pollInterval) + } + } + + @MainActor + final class Gate { + private(set) var arrived = false + private var continuations: [CheckedContinuation] = [] + private var isOpen = false + + func wait() async { + arrived = true + guard !isOpen else { return } + await withCheckedContinuation { continuations.append($0) } + } + + func open() { + isOpen = true + let pending = continuations + continuations.removeAll() + for continuation in pending { + continuation.resume() + } + } + } + + private enum Timing { + static let timeout: Duration = .seconds(35) + static let pollInterval: Duration = .milliseconds(1) + } +} diff --git a/MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests+ImportWriters.swift b/MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests+ImportWriters.swift new file mode 100644 index 0000000000..b0900c79f5 --- /dev/null +++ b/MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests+ImportWriters.swift @@ -0,0 +1,328 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +extension SettingsIdentityMetadataProvenanceTests { + @Test(arguments: [TransportType.bluetooth, .wifi], [false, true]) + func `imported settings writers adopt private runtime`(transport: TransportType, hasGhost: Bool) async throws { + let env = try await ConnectionLinkSwitchHarness.make(live: transport, wifiHost: "source.local") + let radio = transport == .bluetooth ? env.bluetooth : env.wifi + let model = makeWriterImportModel(env) + let selection = Gate() + var bodyError: (any Error)? + do { + await env.bluetooth.setConnectError(nil) + await env.wifi.setConnectError(nil) + await radio.setIdentityImportPublicKey(Self.importedPublicKey) + await env.appState.wireServicesIfConnected() + let source = try #require(env.manager.currentConnection) + try #require(env.manager.connectionState == .ready && source.services.isAcceptingRuntimeWork) + let ghost = source.device.copy { + $0.id = UUID() + $0.radioID = UUID() + $0.publicKey = Self.importedPublicKey + $0.isActive = false + $0.connectionMethods = [] + } + if hasGhost { try await env.manager.persistenceStore.saveDevice(ghost) } + let expectedRadioID = hasGhost ? ghost.radioID : source.device.radioID + let originalChannel = ChannelDTO( + id: UUID(), radioID: source.device.radioID, index: 0, name: Writers.originalName, + secret: Writers.originalSecret, isEnabled: true, lastMessageDate: nil, unreadCount: 0 + ) + let originalContact = ContactDTO( + id: UUID(), radioID: source.device.radioID, publicKey: Writers.contactKey, name: Writers.originalName, + typeRawValue: ContactType.chat.rawValue, flags: 0, outPathLength: 0xFF, outPath: Data(), + lastAdvertTimestamp: 0, latitude: 0, longitude: 0, lastModified: 0, lastHeardTimestamp: 0, + nickname: nil, isBlocked: false, isMuted: false, isFavorite: false, lastMessageDate: nil, unreadCount: 0 + ) + try await env.manager.persistenceStore.saveChannel(originalChannel) + try await env.manager.persistenceStore.saveContact(originalContact) + try await prepareWriterImport(Writers.config, model: model) + for code in Writers.stages { + await radio.holdReplies(for: code) + } + env.manager.testConnectionSelectionHandler = { _ in await selection.wait() } + let start = await radio.sentData.count + model.applyConfig() + try await waitUntil("the changed name must use the adopted runtime before partition resolution") { + await radio.heldReplyCount(for: .setName) == 1 + } + let attempt = try #require(env.manager.desiredRequest?.attempt) + let candidate = try #require(attempt.preparedServices) + let adoptedSession = await candidate.settingsService.configurationSessionForRead() as? MeshCoreSession + let replacementOwnsSettings = candidate.settingsService !== source.services.settingsService + && candidate.session !== source.services.session && adoptedSession === candidate.session + try #require(replacementOwnsSettings) + try #require(!source.services.isAcceptingRuntimeWork) + let canonicalSave = try await env.manager.persistenceStore.fetchDevice(id: source.device.id) + let savedBeforeName = canonicalSave?.publicKey == Self.importedPublicKey && canonicalSave?.radioID == expectedRadioID + try #require(savedBeforeName) + _ = try await env.manager.persistenceStore.saveChannel( + radioID: expectedRadioID, from: ChannelInfo(index: 0, name: Writers.channelName, secret: Writers.secret) + ) + let occupant = try await env.manager.persistenceStore.fetchChannel(radioID: expectedRadioID, index: 0) + let pendingOccupantMatchesSelectedSlot = occupant?.name == Writers.channelName && occupant?.secret == Writers.secret + try #require(pendingOccupantMatchesSelectedSlot) + let pendingDate = Date() + let pending = MessageDTO( + id: UUID(), radioID: expectedRadioID, contactID: nil, channelIndex: 0, text: "Imported queued message", + timestamp: UInt32(pendingDate.timeIntervalSince1970), createdAt: pendingDate, direction: .outgoing, status: .pending, + textType: .plain, ackCode: nil, pathLength: 0, snr: nil, senderKeyPrefix: nil, senderNodeName: nil, + isRead: false, replyToID: nil, roundTripTime: nil, heardRepeats: 0, sendCount: 1, retryAttempt: 0, maxRetryAttempts: 0 + ) + try await env.manager.persistenceStore.saveMessage(pending) + let envelope = ChannelMessageEnvelope( + messageID: pending.id, channelIndex: 0, isResend: false, messageText: pending.text, + messageTimestamp: pending.timestamp, localNodeName: "Test Radio" + ) + _ = try await env.manager.persistenceStore.insertPendingSendAssigningSequence(PendingSendDTO(envelope: envelope, radioID: expectedRadioID)) + try await expectWriterPublicAdmissionRefused(source.services.nodeConfigService, radioID: source.device.radioID) + var oldSettingsRefused = false + do { _ = try await source.services.settingsService.getTime() } catch { oldSettingsRefused = true } + #expect(oldSettingsRefused) + + for (index, code) in Writers.stages.enumerated() { + try await waitUntil("each selected writer must submit on the private runtime in order") { + await radio.heldReplyCount(for: code) == 1 + } + let privateRuntime = env.manager.currentConnection == nil && env.manager.services == nil + && env.manager.session == nil && env.manager.connectedDevice == nil && env.appState.services == nil + && env.manager.connectionState == .connected && model.isApplying + && env.manager.desiredRequest?.attempt === attempt && attempt.binding.isActive + #expect(privateRuntime) + let frames = await Array(radio.sentData.dropFirst(start)) + let writesMatchSelectedPrefix = Writers.selectedWrites(frames) == Array(Writers.packets.prefix(index + 1)) + #expect(writesMatchSelectedPrefix) + expectNoOrdinaryWriterWork(frames) + if code == .setOtherParams { + let betweenPositionAndOther = frames.drop { $0.first != CommandCode.setCoordinates.rawValue }.dropFirst().dropLast() + let cachedAuthenticatedParams = betweenPositionAndOther.allSatisfy { $0.first != CommandCode.appStart.rawValue } + #expect(cachedAuthenticatedParams) + } + if code == .setChannel { + let afterOtherParams = frames.drop { $0.first != CommandCode.setOtherParams.rawValue }.dropFirst() + let refreshedAdoptedParams = afterOtherParams.filter { $0.first == CommandCode.appStart.rawValue }.count == 1 + #expect(refreshedAdoptedParams) + } + await radio.releaseReplies(for: code) + } + try await waitUntil("all selected writes must settle before the canonical selection") { selection.arrived } + let framesAtSelection = await Array(radio.sentData.dropFirst(start)) + let allSelectedFramesMatch = Writers.selectedWrites(framesAtSelection) == Writers.packets + let oneKeyFrame = framesAtSelection.filter { $0.first == CommandCode.importPrivateKey.rawValue }.count == 1 + let selectedCodes = framesAtSelection.compactMap(\.first).filter { + $0 == CommandCode.importPrivateKey.rawValue || Writers.stages.map(\.rawValue).contains($0) + } + let keyThenSelectedOrder = selectedCodes == [CommandCode.importPrivateKey.rawValue] + Writers.stages.map(\.rawValue) + #expect(allSelectedFramesMatch) + #expect(oneKeyFrame) + #expect(keyThenSelectedOrder) + expectNoOrdinaryWriterWork(framesAtSelection) + #expect(env.manager.currentConnection == nil && env.appState.services == nil) + try await expectWriterPublicAdmissionRefused(source.services.nodeConfigService, radioID: source.device.radioID) + try await expectWriterPartition(env, radioID: expectedRadioID) + let retainedPending = try await env.manager.persistenceStore.fetchMessage(id: pending.id) + let pendingSendRetained = try await env.manager.persistenceStore.hasPendingSend(messageID: pending.id) + let noPrematureQueueEffect = retainedPending == pending && pendingSendRetained + #expect(noPrematureQueueEffect) + if hasGhost { + let retainedChannel = try await env.manager.persistenceStore.fetchChannel(id: originalChannel.id) + let retainedContact = try await env.manager.persistenceStore.fetchContact(id: originalContact.id) + let originalPartitionIsUntouched = retainedChannel == originalChannel && retainedContact == originalContact + #expect(originalPartitionIsUntouched) + } + selection.open() + try await waitUntil("the complete normal import must report its result") { !model.isApplying } + #expect(model.importComplete && model.errorMessage == nil) + try await waitUntil("ordinary setup must publish the adopted runtime after the tail") { + env.manager.connectionState == .ready && env.manager.currentConnection != nil + } + await env.appState.wireServicesIfConnected() + await env.manager.metadataCommitTask?.value + let live = try #require(env.manager.currentConnection) + let saved = try await env.manager.persistenceStore.fetchDevice(id: source.device.id) + let finalCanonicalIdentity = saved?.publicKey == Self.importedPublicKey && saved?.radioID == expectedRadioID + && live.device.publicKey == Self.importedPublicKey && live.device.radioID == expectedRadioID + let exactRuntimeWasPublished = live.services === candidate && live.generation != source.generation + let originalHandleAndMethods = saved?.id == source.device.id && saved?.connectionMethods == source.device.connectionMethods + #expect(finalCanonicalIdentity) + #expect(exactRuntimeWasPublished) + #expect(originalHandleAndMethods) + #expect(env.manager.identityImportRecoveries.isEmpty) + if hasGhost { + let consumedGhost = try await env.manager.persistenceStore.fetchDevice(id: ghost.id) == nil + #expect(consumedGhost) + } + try await expectWriterPartition(env, radioID: expectedRadioID) + try await waitUntil("ordinary canonical hydration must send the preserved pending row after the tail") { + await (try? env.manager.persistenceStore.fetchMessage(id: pending.id))?.status == .sent + } + let noUnconfiguredSend = await radio.unconfiguredChannelSendCount == 0 + #expect(noUnconfiguredSend) + let time = try await live.services.settingsService.getTime() + let info = try await live.services.settingsService.getSelfInfo() + let laterIdentityIsAuthenticated = info.publicKey == Self.importedPublicKey + #expect(time.timeIntervalSince1970 > 0) + #expect(laterIdentityIsAuthenticated) + try await expectWriterPublicAdmissionRefused(source.services.nodeConfigService, radioID: source.device.radioID) + let finalKeyCount = await radio.sentData.filter { $0.first == CommandCode.importPrivateKey.rawValue }.count + #expect(finalKeyCount == 1) + } catch { bodyError = error } + selection.open() + env.manager.testConnectionSelectionHandler = nil + await closeWriterImport(model, env: env) + if let bodyError { throw bodyError } + } + + @Test(arguments: [TransportType.bluetooth, .wifi]) + func `key free settings import retains service and diff gates`(transport: TransportType) async throws { + let env = try await ConnectionLinkSwitchHarness.make(live: transport, wifiHost: "source.local") + let radio = transport == .bluetooth ? env.bluetooth : env.wifi + let model = makeWriterImportModel(env) + var bodyError: (any Error)? + do { + await env.appState.wireServicesIfConnected() + let source = try #require(env.manager.currentConnection) + var changed = Writers.config + changed.privateKey = nil + try await prepareWriterImport(changed, model: model) + let beforeChanged = await radio.sentData.count + model.applyConfig() + try await waitUntil("the key-free changed import must settle") { !model.isApplying } + try #require(model.importComplete && model.errorMessage == nil) + let changedFrames = await Array(radio.sentData.dropFirst(beforeChanged)) + let keyFreeWritesMatch = Writers.selectedWrites(changedFrames) == Writers.packets + let changedImportKeptOriginalService = env.manager.isCurrent(source) && env.manager.services?.settingsService === source.services.settingsService + #expect(keyFreeWritesMatch) + #expect(changedImportKeptOriginalService) + await model.importTask?.value + try await expectWriterPartition(env, radioID: source.device.radioID) + try await prepareWriterImport(changed, model: model) + let beforeUnchanged = await radio.sentData.count + model.applyConfig() + try await waitUntil("unchanged selected settings and resident channel/contact must be diff-gated") { !model.isApplying } + #expect(model.importComplete && model.errorMessage == nil) + let unchangedFrames = await Array(radio.sentData.dropFirst(beforeUnchanged)) + let noRedundantWrites = Writers.selectedWrites(unchangedFrames).isEmpty + let noKeyWrites = await radio.sentData.allSatisfy { $0.first != CommandCode.importPrivateKey.rawValue } + let originalRuntimeSurvives = env.manager.isCurrent(source) && env.manager.services === source.services + && env.manager.services?.settingsService === source.services.settingsService + #expect(noRedundantWrites) + #expect(noKeyWrites) + #expect(originalRuntimeSurvives) + await env.manager.metadataCommitTask?.value + let saved = try await env.manager.persistenceStore.fetchDevice(id: source.device.id) + let originalIdentitySurvives = saved?.publicKey == source.device.publicKey && saved?.radioID == source.device.radioID + #expect(originalIdentitySurvives) + try await expectWriterPartition(env, radioID: source.device.radioID) + let laterTime = try await source.services.settingsService.getTime() + #expect(laterTime.timeIntervalSince1970 > 0) + } catch { bodyError = error } + await closeWriterImport(model, env: env) + if let bodyError { throw bodyError } + } + + private func makeWriterImportModel(_ env: ConnectionLinkSwitchHarness) -> NodeConfigImportViewModel { + let model = NodeConfigImportViewModel() + model.configure( + nodeConfigService: { env.manager.services?.nodeConfigService }, settingsService: { env.manager.services?.settingsService }, + connectedDevice: { env.manager.connectedDevice }, connectionManager: env.manager + ) + return model + } + + private func prepareWriterImport(_ config: MeshCoreNodeConfig, model: NodeConfigImportViewModel) async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("settings-writers.json") + try JSONEncoder().encode(config).write(to: url) + model.beginImport() + model.parseFile(at: url) + await model.parseTask?.value + let allSectionsParsed = model.importedConfig != nil && !model.isParsing && model.errorMessage == nil && model.sections.allSelected + try #require(allSectionsParsed) + model.prepareConfirmation() + await model.previewTask?.value + try #require(model.showConfirmation && model.confirmation != nil && model.errorMessage == nil) + } + + private func expectWriterPublicAdmissionRefused(_ service: NodeConfigService, radioID: UUID) async throws { + var refusals = 0 + do { _ = try await service.exportConfig(sections: ConfigSections(nodeIdentity: true)) } catch is CancellationError { refusals += 1 } + do { _ = try await service.previewImport(Writers.config, sections: ConfigSections(nodeIdentity: true)) } catch is CancellationError { refusals += 1 } + do { try await service.importConfig(Writers.config, sections: ConfigSections(nodeIdentity: true), radioID: radioID) } catch is CancellationError { refusals += 1 } + #expect(refusals == 3) + } + + private func expectNoOrdinaryWriterWork(_ frames: [Data]) { + let afterKey = frames.drop { $0.first != CommandCode.importPrivateKey.rawValue } + let ordinaryWorkWasWithheld = afterKey.allSatisfy { !Writers.ordinaryCodes.contains($0.first ?? 0) } + #expect(ordinaryWorkWasWithheld) + } + + private func expectWriterPartition(_ env: ConnectionLinkSwitchHarness, radioID: UUID) async throws { + let channel = try await env.manager.persistenceStore.fetchChannel(radioID: radioID, index: 0) + let contact = try await env.manager.persistenceStore.fetchContact(radioID: radioID, publicKey: Writers.contactKey) + let selectedChannelIsCanonical = channel?.radioID == radioID && channel?.name == Writers.channelName && channel?.secret == Writers.secret + let selectedContactIsCanonical = contact?.radioID == radioID && contact?.name == Writers.contactName + #expect(selectedChannelIsCanonical) + #expect(selectedContactIsCanonical) + } + + private func closeWriterImport(_ model: NodeConfigImportViewModel, env: ConnectionLinkSwitchHarness) async { + model.cancelImport() + model.parseTask?.cancel() + model.previewTask?.cancel() + await env.bluetooth.releaseAllGates() + await env.wifi.releaseAllGates() + await model.importTask?.value + await model.parseTask?.value + await model.previewTask?.value + await env.manager.metadataCommitTask?.value + await env.close() + await env.manager.retirementTask?.value + } + + @MainActor + private enum Writers { + static let originalName = "Original partition" + static let originalSecret = Data(repeating: 0x4A, count: 16) + static let secret = Data(repeating: 0x5A, count: 16) + static let contactKey = Data(repeating: 0x6B, count: 32) + static let channelName = "Imported channel" + static let contactName = "Imported contact" + static let stages: [CommandCode] = [.setName, .setCoordinates, .setOtherParams, .setChannel, .updateContact, .setRadio, .setTxPower] + static let ordinaryCodes = Set([CommandCode.getChannel, .getContacts, .getMessage, .sendMessage, .sendChannelMessage].map(\.rawValue)) + static var config: MeshCoreNodeConfig { + MeshCoreNodeConfig( + name: "Imported Radio", privateKey: SettingsIdentityMetadataProvenanceTests.expandedKeyHex, + radioSettings: .init(frequency: 916_000, bandwidth: 250_000, spreadingFactor: 8, codingRate: 6, txPower: 20), + positionSettings: .init(latitude: "37.123456", longitude: "-122.654321"), otherSettings: .init(multiAcks: 1), + channels: [.init(name: channelName, secret: secret.hexString)], + contacts: [.init(type: 1, name: contactName, publicKey: contactKey.hexString, flags: 0, + latitude: "0", longitude: "0", lastAdvert: 1, lastModified: 1)] + ) + } + + static var packets: [Data] { + let contact = MeshContact( + id: contactKey.hexString, publicKey: contactKey, type: .chat, flags: [], outPathLength: 0xFF, outPath: Data(), + advertisedName: contactName, lastAdvertisement: Date(timeIntervalSince1970: 1), latitude: 0, longitude: 0, + lastModified: Date(timeIntervalSince1970: 1) + ) + return [PacketBuilder.setName("Imported Radio"), PacketBuilder.setCoordinates(latitude: 37.123456, longitude: -122.654321), + SettingsIdentityMetadataProvenanceTests.selectedTailPacket, + PacketBuilder.setChannel(index: 0, name: channelName, secret: secret), PacketBuilder.updateContact(contact), + PacketBuilder.setRadio(frequency: 916, bandwidth: 250, spreadingFactor: 8, codingRate: 6), PacketBuilder.setTxPower(20)] + } + + static func selectedWrites(_ frames: [Data]) -> [Data] { + let codes = Set(stages.map(\.rawValue)) + return frames.filter { codes.contains($0.first ?? 0) } + } + } +} diff --git a/MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests+LateContinuation.swift b/MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests+LateContinuation.swift new file mode 100644 index 0000000000..19e7ccf8cb --- /dev/null +++ b/MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests+LateContinuation.swift @@ -0,0 +1,245 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +extension SettingsIdentityMetadataProvenanceTests { + @Test( + arguments: [TransportType.bluetooth, .wifi], + [LateTail.noGhostCancelled, .ghostCancelled, .noGhostFailed, .ghostFailed] + ) + func `completed telemetry cannot enter canonical settings subscription`( + transport: TransportType, tail: LateTail + ) async throws { + try await exerciseLateSettingsContinuation(transport: transport, tail: tail, operation: .telemetry) + } + + @Test( + arguments: [TransportType.bluetooth, .wifi], + [LateTail.noGhostCancelled, .ghostCancelled] + ) + func `completed preset cannot issue next command through canonical runtime`( + transport: TransportType, tail: LateTail + ) async throws { + try await exerciseLateSettingsContinuation(transport: transport, tail: tail, operation: .preset) + } + + private func exerciseLateSettingsContinuation( + transport: TransportType, tail: LateTail, operation: LateOperation + ) async throws { + let env = try await ConnectionLinkSwitchHarness.make(live: transport, wifiHost: "source.local") + let radio = transport == .bluetooth ? env.bluetooth : env.wifi + let model = NodeConfigImportViewModel() + model.configure( + nodeConfigService: { env.manager.services?.nodeConfigService }, + settingsService: { env.manager.services?.settingsService }, + connectedDevice: { env.manager.connectedDevice }, connectionManager: env.manager + ) + let admission = Gate() + let commit = Gate() + let oldResult = Gate() + var oldSettings: SettingsService? + var oldOperation: Task? + var bodyError: (any Error)? + do { + await env.bluetooth.setConnectError(nil) + await env.wifi.setConnectError(nil) + await radio.setIdentityImportPublicKey(Self.importedPublicKey) + await env.appState.wireServicesIfConnected() + let source = try #require(env.manager.currentConnection) + let sourceIsOperational = env.manager.connectionState == .ready && source.services.isAcceptingRuntimeWork + try #require(sourceIsOperational) + let settings = source.services.settingsService + oldSettings = settings + let ghost = source.device.copy { + $0.id = UUID() + $0.radioID = UUID() + $0.publicKey = Self.importedPublicKey + $0.isActive = false + $0.connectionMethods = [] + } + if tail.hasGhost { try await env.manager.persistenceStore.saveDevice(ghost) } + let expectedRadioID = tail.hasGhost ? ghost.radioID : source.device.radioID + model.beginImport() + try await selectFile(Self.config, model: model) + model.prepareConfirmation() + await model.previewTask?.value + let confirmationIsReady = model.showConfirmation && model.confirmation != nil && model.errorMessage == nil + try #require(confirmationIsReady) + env.manager.testIdentityBeforeAdmission = { await admission.wait() } + env.manager.testIdentityBeforeCommit = { await commit.wait() } + model.applyConfig() + try await waitUntil("normal import must reach identity admission") { admission.arrived } + + await radio.enqueueResponsePackets( + for: .appStart, packets: [Self.telemetryPacket(publicKey: source.device.publicKey)] + ) + if operation == .telemetry { + await radio.enqueueResponsePackets( + for: .appStart, packets: [Self.telemetryPacket(publicKey: source.device.publicKey)] + ) + } + let framesBeforeOrdinaryOperation = await radio.sentData.count + await settings.setTestSelfInfoResultHandler { await oldResult.wait() } + oldOperation = Task { + switch operation { + case .telemetry: + let info = try await settings.setOtherParamsVerified(autoAddContacts: !source.device.manualAddContacts, telemetryModes: Self.telemetryModes, + advertLocationPolicy: source.device.advertLocationPolicyMode, multiAcks: source.device.multiAcks) + let returnedResultBelongsToSource = info.publicKey == source.device.publicKey + #expect(returnedResultBelongsToSource) + #expect(info.telemetryModeBase == Self.telemetryMarker) + case .preset: + _ = try await settings.applyRadioPresetVerified(Self.continuationPreset) + } + } + try await waitUntil("the ordinary Settings caller must hold its real completed SelfInfo result") { oldResult.arrived } + await settings.setTestSelfInfoResultHandler(nil) + await source.services.session.waitForQuiescence() + let ordinaryFrames = await radio.sentData.dropFirst(framesBeforeOrdinaryOperation) + let ordinaryReadWasSubmitted = ordinaryFrames.contains { $0.first == CommandCode.appStart.rawValue } + let ordinaryWriteWasSubmitted = ordinaryFrames.contains { + $0.first == (operation == .telemetry ? CommandCode.setOtherParams.rawValue : CommandCode.setRadio.rawValue) + } + try #require(ordinaryReadWasSubmitted) + try #require(ordinaryWriteWasSubmitted) + let oldResultPrecedesAdmission = env.manager.isCurrent(source) && env.manager.connectionState == .ready + try #require(oldResultPrecedesAdmission) + let keyWritesBeforeAdmission = await radio.sentData.filter { $0.first == CommandCode.importPrivateKey.rawValue }.count + try #require(keyWritesBeforeAdmission == 0) + await radio.holdReplies(for: .setOtherParams) + if !tail.isCancelled { await radio.rejectNext(.setOtherParams) } + // Keep the authenticated radio state distinct from the held source result. + await radio.setTelemetryModeBase(Self.authenticatedTelemetryBase) + admission.open() + try await waitUntil("the actual key OK and authenticated SelfInfo must reach canonical commit") { commit.arrived } + let oneKeyWrite = await radio.sentData.filter { $0.first == CommandCode.importPrivateKey.rawValue }.count == 1 + try #require(oneKeyWrite) + commit.open() + try await waitUntil("the actual importer must submit the private selected tail") { + await radio.heldReplyCount(for: .setOtherParams) == 1 + } + await env.manager.metadataCommitTask?.value + let canonicalBeforeTail = try await env.manager.persistenceStore.fetchDevice(id: source.device.id) + let canonicalSavePrecedesRelease = canonicalBeforeTail?.publicKey == Self.importedPublicKey + && canonicalBeforeTail?.radioID == expectedRadioID + let selectedTailIsPrivate = env.manager.currentConnection == nil && env.appState.services == nil + && env.manager.connectionState == .connected && model.isApplying && oldResult.arrived + try #require(canonicalSavePrecedesRelease) + try #require(selectedTailIsPrivate) + if tail.isCancelled { + model.cancelImport() + try #require(model.importTask?.isCancelled == true) + } + await radio.releaseReplies(for: .setOtherParams) + await model.importTask?.value + let expectedTailOutcome = !model.isApplying && !model.importComplete && model.errorMessage != nil + && (tail.isCancelled ? model.errorMessage == L10n.Settings.ConfigImport.cancelledPartial + : model.errorMessage != L10n.Settings.ConfigImport.cancelledPartial) + try #require(expectedTailOutcome) + try await waitUntil("accepted canonical runtime must publish after the failed or cancelled tail") { + env.manager.connectionState == .ready && env.manager.currentConnection != nil + } + await env.appState.wireServicesIfConnected() + let canonical = try #require(env.manager.currentConnection) + #expect(canonical.services.settingsService !== settings) + let replacementIsAuthenticated = canonical.generation != source.generation + && canonical.device.publicKey == Self.importedPublicKey && canonical.device.radioID == expectedRadioID + try #require(replacementIsAuthenticated) + try #require(canonical.device.autoAddConfig != Self.streamFenceMarker) + let framesBeforeOldContinuation = await radio.sentData.count + oldResult.open() + let worker = try #require(oldOperation) + let oldOutcome = await worker.result + switch (operation, oldOutcome) { + case (.telemetry, .success): break + case (.preset, .failure): break + default: Issue.record("The old Settings operation did not preserve its source-bound outcome") + } + let oldContinuationFrames = await radio.sentData.dropFirst(framesBeforeOldContinuation) + let noOldNextCommand = oldContinuationFrames.allSatisfy { + $0.first != CommandCode.deviceQuery.rawValue && $0.first != CommandCode.setPathHashMode.rawValue + } + #expect(noOldNextCommand) + + // This real later event fences the same stream without refreshing SelfInfo. + await radio.setResponsePackets( + for: .getAutoAddConfig, packets: [Data([ResponseCode.autoAddConfig.rawValue, Self.streamFenceMarker])] + ) + try await canonical.services.settingsService.refreshAutoAddConfig() + try await waitUntil("the real canonical Settings subscriber must consume the later FIFO event") { + env.manager.connectedDevice?.autoAddConfig == Self.streamFenceMarker + } + await env.manager.metadataCommitTask?.value + let saved = try await env.manager.persistenceStore.fetchDevice(id: source.device.id) + let storedKeyIsAuthenticated = saved?.publicKey == Self.importedPublicKey + let publishedKeyIsAuthenticated = env.manager.connectedDevice?.publicKey == Self.importedPublicKey + let canonicalPartitionSurvives = saved?.radioID == expectedRadioID + && env.manager.connectedDevice?.radioID == expectedRadioID + let oldTelemetryDidNotEnterNewSubscriber = saved?.telemetryModeBase == Self.authenticatedTelemetryBase + && env.manager.connectedDevice?.telemetryModeBase == Self.authenticatedTelemetryBase + let sourceHandleAndMethodsSurvive = saved?.id == source.device.id + && saved?.connectionMethods == source.device.connectionMethods + #expect(storedKeyIsAuthenticated) + #expect(publishedKeyIsAuthenticated) + #expect(canonicalPartitionSurvives) + #expect(oldTelemetryDidNotEnterNewSubscriber) + #expect(sourceHandleAndMethodsSurvive) + #expect(env.manager.identityImportRecoveries.isEmpty) + if tail.hasGhost { + let ghostWasConsumed = try await env.manager.persistenceStore.fetchDevice(id: ghost.id) == nil + #expect(ghostWasConsumed) + } + if operation == .preset { + _ = try await canonical.services.settingsService.applyRadioPresetVerified(Self.continuationPreset) + } + let laterTime = try await canonical.services.settingsService.getTime() + let laterInfo = try await canonical.services.settingsService.getSelfInfo() + let laterWireKeyIsAuthenticated = laterInfo.publicKey == Self.importedPublicKey + #expect(laterTime.timeIntervalSince1970 > 0) + #expect(laterWireKeyIsAuthenticated) + let frames = await radio.sentData + let keyCount = frames.filter { $0.first == CommandCode.importPrivateKey.rawValue }.count + let selectedTailWasSubmitted = frames.contains(Self.selectedTailPacket) + #expect(keyCount == 1) + #expect(selectedTailWasSubmitted) + } catch { + bodyError = error + } + admission.open() + commit.open() + oldResult.open() + await oldSettings?.setTestSelfInfoResultHandler(nil) + env.manager.testIdentityBeforeAdmission = nil + env.manager.testIdentityBeforeCommit = nil + model.cancelImport() + model.parseTask?.cancel() + model.previewTask?.cancel() + oldOperation?.cancel() + await env.bluetooth.releaseAllGates() + await env.wifi.releaseAllGates() + _ = await oldOperation?.result + await model.importTask?.value + await model.parseTask?.value + await model.previewTask?.value + await env.manager.metadataCommitTask?.value + await env.close() + await env.manager.retirementTask?.value + if let bodyError { throw bodyError } + } + + enum LateTail: Sendable { + case noGhostCancelled, ghostCancelled, noGhostFailed, ghostFailed + + var hasGhost: Bool { + self == .ghostCancelled || self == .ghostFailed + } + + var isCancelled: Bool { + self == .noGhostCancelled || self == .ghostCancelled + } + } + + private enum LateOperation: Sendable { case telemetry, preset } +} diff --git a/MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests.swift b/MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests.swift new file mode 100644 index 0000000000..1bc025841b --- /dev/null +++ b/MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests.swift @@ -0,0 +1,202 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Settings identity metadata provenance", .serialized) +@MainActor +struct SettingsIdentityMetadataProvenanceTests { + @Test( + arguments: [TransportType.bluetooth, .wifi], + [ImportCase.noGhostCancelled, .ghostCancelled, .noGhostSuccessful, .ghostSuccessful] + ) + func `verified settings observation cannot revert canonical import`( + transport: TransportType, outcome: ImportCase + ) async throws { + let env = try await ConnectionLinkSwitchHarness.make(live: transport, wifiHost: "source.local") + let radio = transport == .bluetooth ? env.bluetooth : env.wifi + let model = NodeConfigImportViewModel() + model.configure( + nodeConfigService: { env.manager.services?.nodeConfigService }, + settingsService: { env.manager.services?.settingsService }, + connectedDevice: { env.manager.connectedDevice }, connectionManager: env.manager + ) + let admission = Gate() + let commit = Gate() + let observation = Gate() + var setter: Task? + var bodyError: (any Error)? + do { + await env.bluetooth.setConnectError(nil) + await env.wifi.setConnectError(nil) + await radio.setIdentityImportPublicKey(Self.importedPublicKey) + await env.appState.wireServicesIfConnected() + guard let source = env.manager.currentConnection else { + throw NSError(domain: "SettingsIdentityMetadataProvenance", code: 3) + } + let operationalSource = env.manager.connectionState == .ready && source.services.isAcceptingRuntimeWork + try #require(operationalSource) + let originalID = source.device.id + let originalRadioID = source.device.radioID + let originalMethods = source.device.connectionMethods + let ghost = source.device.copy { + $0.id = UUID() + $0.radioID = UUID() + $0.publicKey = Self.importedPublicKey + $0.isActive = false + $0.connectionMethods = [] + } + if outcome.hasGhost { try await env.manager.persistenceStore.saveDevice(ghost) } + let expectedRadioID = outcome.hasGhost ? ghost.radioID : originalRadioID + model.beginImport() + try await selectFile(Self.config, model: model) + model.prepareConfirmation() + await model.previewTask?.value + let confirmationReady = model.showConfirmation && model.confirmation != nil && model.errorMessage == nil + try #require(confirmationReady) + + env.manager.testIdentityBeforeAdmission = { await admission.wait() } + env.manager.testIdentityBeforeCommit = { await commit.wait() } + model.applyConfig() + try await waitUntil("normal import must finish its plan and reach identity admission") { admission.arrived } + await radio.holdReplies(for: .setOtherParams) + await radio.enqueueResponsePackets( + for: .appStart, packets: [Self.telemetryPacket(publicKey: source.device.publicKey)] + ) + await radio.enqueueResponsePackets( + for: .appStart, packets: [Self.telemetryPacket(publicKey: source.device.publicKey)] + ) + await source.services.settingsService.setTestSelfInfoResultHandler { await observation.wait() } + setter = Task { + _ = try await source.services.settingsService.setOtherParamsVerified( + autoAddContacts: !source.device.manualAddContacts, telemetryModes: Self.telemetryModes, + advertLocationPolicy: source.device.advertLocationPolicyMode, multiAcks: source.device.multiAcks + ) + } + try await waitUntil("the real telemetry setter must submit its preference frame") { + await radio.heldReplyCount(for: .setOtherParams) == 1 + } + await radio.releaseReplies(for: .setOtherParams) + try await waitUntil("the verified Settings result must complete before admission closes") { observation.arrived } + await source.services.settingsService.setTestSelfInfoResultHandler(nil) + let originalSourceStillInstalled = env.manager.isCurrent(source) && env.manager.connectionState == .ready + try #require(originalSourceStillInstalled) + // Keep the authenticated radio state distinct from the held source result. + await radio.setTelemetryModeBase(Self.authenticatedTelemetryBase) + admission.open() + try await waitUntil("identity metadata must own the chain before the verified Settings event publishes") { + env.manager.connectionState == .connected + } + observation.open() + try await waitUntil("the actual import must acknowledge its key and verify new SelfInfo") { commit.arrived } + try await waitUntil("the AppState Settings consumer must accept the old telemetry observation") { + env.manager.isCurrent(source) && env.manager.connectedDevice?.telemetryModeBase == Self.telemetryMarker + } + try await setter?.value + let keyCountAtCommit = await radio.sentData.filter { $0.first == CommandCode.importPrivateKey.rawValue }.count + try #require(keyCountAtCommit == 1) + let sourceStillHasOriginalIdentity = env.manager.connectedDevice?.publicKey == source.device.publicKey + && env.manager.connectedDevice?.radioID == originalRadioID + try #require(sourceStillHasOriginalIdentity) + + await radio.holdReplies(for: .setOtherParams) + commit.open() + try await waitUntil("the normal importer must submit its selected post-identity tail") { + await radio.heldReplyCount(for: .setOtherParams) == 1 + } + await env.manager.metadataCommitTask?.value + let storedBeforeTail = try await env.manager.persistenceStore.fetchDevice(id: originalID) + let authenticatedKeySurvivesBeforeRefresh = storedBeforeTail?.publicKey == Self.importedPublicKey + let canonicalPartitionSurvivesBeforeRefresh = storedBeforeTail?.radioID == expectedRadioID + let staleTelemetryDoesNotCrossIdentity = storedBeforeTail?.telemetryModeBase == Self.authenticatedTelemetryBase + let privateTailIsUnpublished = env.manager.currentConnection == nil && env.appState.services == nil + #expect(authenticatedKeySurvivesBeforeRefresh) + #expect(canonicalPartitionSurvivesBeforeRefresh) + #expect(staleTelemetryDoesNotCrossIdentity) + #expect(privateTailIsUnpublished) + if outcome.isCancelled { + model.cancelImport() + let cancellationRequested = model.importTask?.isCancelled == true + #expect(cancellationRequested) + } + await radio.releaseReplies(for: .setOtherParams) + try await waitUntil("the normal import outcome must settle after its selected exchange") { !model.isApplying } + let expectedOutcome = outcome.isCancelled + ? !model.importComplete && model.errorMessage == L10n.Settings.ConfigImport.cancelledPartial + : model.importComplete && model.errorMessage == nil + #expect(expectedOutcome) + try await waitUntil("canonical runtime must activate after the selected tail settles") { + env.manager.connectionState == .ready && env.manager.currentConnection != nil + } + if !outcome.isCancelled { + try await waitUntil("the successful import's separate refresh must reach AppState") { + env.manager.connectedDevice?.publicKey == Self.importedPublicKey + } + } + await env.manager.metadataCommitTask?.value + let saved = try await env.manager.persistenceStore.fetchDevice(id: originalID) + let storedIdentityIsAuthenticated = saved?.publicKey == Self.importedPublicKey && saved?.radioID == expectedRadioID + let publishedIdentityIsAuthenticated = env.manager.connectedDevice?.publicKey == Self.importedPublicKey + && env.manager.connectedDevice?.radioID == expectedRadioID + let originalHandleAndMethodsSurvive = saved?.id == originalID && saved?.connectionMethods == originalMethods + let noUnknownOutcomeReceipt = env.manager.identityImportRecoveries.isEmpty + #expect(storedIdentityIsAuthenticated) + #expect(publishedIdentityIsAuthenticated) + #expect(originalHandleAndMethodsSurvive) + #expect(noUnknownOutcomeReceipt) + if outcome.hasGhost { + let consumedGhostIsGone = try await env.manager.persistenceStore.fetchDevice(id: ghost.id) == nil + #expect(consumedGhostIsGone) + } + let frames = await radio.sentData + let keyWriteCount = frames.filter { $0.first == CommandCode.importPrivateKey.rawValue }.count + let selectedTailWasSubmitted = frames.last { $0.first == CommandCode.setOtherParams.rawValue } + == Self.selectedTailPacket + #expect(keyWriteCount == 1) + #expect(selectedTailWasSubmitted) + guard let live = env.manager.currentConnection else { + throw NSError(domain: "SettingsIdentityMetadataProvenance", code: 3) + } + let laterTime = try await live.services.settingsService.getTime() + #expect(laterTime.timeIntervalSince1970 > 0) + let laterInfo = try await live.services.settingsService.getSelfInfo() + let laterWireIdentityIsAuthenticated = laterInfo.publicKey == Self.importedPublicKey + #expect(laterWireIdentityIsAuthenticated) + await model.importTask?.value + } catch { + bodyError = error + } + admission.open() + commit.open() + observation.open() + env.manager.testIdentityBeforeAdmission = nil + env.manager.testIdentityBeforeCommit = nil + model.cancelImport() + model.parseTask?.cancel() + model.previewTask?.cancel() + setter?.cancel() + await env.bluetooth.releaseAllGates() + await env.wifi.releaseAllGates() + _ = await setter?.result + await model.importTask?.value + await model.parseTask?.value + await model.previewTask?.value + await env.manager.metadataCommitTask?.value + await env.close() + await env.manager.retirementTask?.value + if let bodyError { throw bodyError } + } + + enum ImportCase: Sendable { + case noGhostCancelled, ghostCancelled, noGhostSuccessful, ghostSuccessful + + var hasGhost: Bool { + self == .ghostCancelled || self == .ghostSuccessful + } + + var isCancelled: Bool { + self == .noGhostCancelled || self == .ghostCancelled + } + } +} diff --git a/MC1Tests/ViewModels/SettingsRefreshPropagationTests.swift b/MC1Tests/ViewModels/SettingsRefreshPropagationTests.swift index 26b05e220c..3a48550577 100644 --- a/MC1Tests/ViewModels/SettingsRefreshPropagationTests.swift +++ b/MC1Tests/ViewModels/SettingsRefreshPropagationTests.swift @@ -230,47 +230,87 @@ struct SettingsRefreshPropagationTests { @Test func `config import completion publishes name RF and TX without a second reconciliation`() async throws { let eu = try #require(RadioPresets.all.first { $0.id == "eu-narrow" }) - let fixture = try await RefreshFixture.make(device: savedDevice(catalogID: "hu"), state: .init()) - defer { fixture.stop() } - let callbacks = CallbackCount() - let services = fixture.services - let manager = fixture.appState.connectionManager - let deviceID = fixture.device.id - await services.nodeConfigService.setOnPostIdentityImport { - await callbacks.increment() - return try await manager.reconcileIdentity(expectedServices: services, deviceID: deviceID) - } - let viewModel = configuredImport( - fixture: fixture, - name: "Imported", - radio: eu, - txPower: 10 - ) - - viewModel.applyConfig( - nodeConfigService: fixture.services.nodeConfigService, - settingsService: fixture.services.settingsService, - radioID: fixture.device.radioID - ) - try await waitUntil("the import refresh should publish name, RF, and TX") { - fixture.appState.connectedDevice?.nodeName == "Imported" - && fixture.appState.connectedDevice?.frequency == eu.frequencyKHz - && fixture.appState.connectedDevice?.txPower == 10 - && fixture.appState.connectedDevice?.publicKey == Data(repeating: 0x22, count: ProtocolLimits.publicKeySize) + let env = try await ConnectionLinkSwitchHarness.make() + let radio = env.bluetooth + let viewModel = NodeConfigImportViewModel() + var bodyError: (any Error)? + do { + await radio.setConnectError(nil) + let importedKey = Data(repeating: 0x22, count: ProtocolLimits.publicKeySize) + await radio.setIdentityImportPublicKey(importedKey) + await env.appState.wireServicesIfConnected() + let source = try #require(env.manager.currentConnection) + viewModel.acceptInput(MeshCoreNodeConfig( + name: "Imported", privateKey: String(repeating: "ab", count: 64), + radioSettings: .init( + frequency: eu.frequencyKHz, bandwidth: eu.bandwidthHz, + spreadingFactor: eu.spreadingFactor, codingRate: eu.codingRate, txPower: 10 + ) + ), source: nil) + viewModel.configure( + nodeConfigService: { env.manager.services?.nodeConfigService }, + settingsService: { env.manager.services?.settingsService }, + connectedDevice: { env.manager.connectedDevice }, connectionManager: env.manager + ) + viewModel.sections.nodeIdentity = true + viewModel.sections.radioSettings = true + viewModel.prepareConfirmation() + await viewModel.previewTask?.value + try #require(viewModel.showConfirmation && viewModel.errorMessage == nil) + await radio.holdReplies(for: .setTxPower) + viewModel.applyConfig() + try await waitUntil("the imported settings should reach the last selected write") { + await radio.heldReplyCount(for: .setTxPower) == 1 + } + var finalState = PropagationRadio.State() + finalState.publicKey = importedKey + finalState.nodeName = "Imported" + finalState.frequencyKHz = eu.frequencyKHz + finalState.bandwidthHz = eu.bandwidthHz + finalState.spreadingFactor = eu.spreadingFactor + finalState.codingRate = eu.codingRate + finalState.txPower = 10 + await radio.releaseReplies(for: .setTxPower) + try await waitUntil("the import refresh should publish name, RF, and TX") { + !viewModel.isApplying && env.manager.connectedDevice?.nodeName == finalState.nodeName + && env.manager.connectedDevice?.frequency == eu.frequencyKHz + && env.manager.connectedDevice?.txPower == finalState.txPower + } + let live = try #require(env.manager.currentConnection) + let stored = try #require(try await env.manager.persistenceStore.fetchDevice(id: source.device.id)) + for device in [live.device, stored] { + #expect(device.nodeName == finalState.nodeName) + #expect(device.frequency == eu.frequencyKHz) + #expect(device.bandwidth == eu.bandwidthHz) + #expect(device.spreadingFactor == eu.spreadingFactor) + #expect(device.codingRate == eu.codingRate) + #expect(device.txPower == finalState.txPower) + #expect(device.publicKey == importedKey) + #expect(device.radioID == source.device.radioID) + #expect(device.id == source.device.id) + } + #expect(viewModel.errorMessage == nil) + #expect(viewModel.importComplete) + #expect(live.generation != source.generation) + #expect(live.services !== source.services) + let frames = await radio.sentData + #expect(frames.filter { $0.first == CommandCode.importPrivateKey.rawValue }.count == 1) + #expect(frames.filter { $0.first == CommandCode.setName.rawValue } == [PacketBuilder.setName(finalState.nodeName)]) + #expect(frames.filter { $0.first == CommandCode.setRadio.rawValue } == [PacketBuilder.setRadio( + frequency: eu.frequencyMHz, bandwidth: eu.bandwidthKHz, + spreadingFactor: eu.spreadingFactor, codingRate: eu.codingRate + )]) + #expect(frames.filter { $0.first == CommandCode.setTxPower.rawValue } == [PacketBuilder.setTxPower(finalState.txPower)]) + } catch { + bodyError = error } - - #expect(viewModel.errorMessage == nil) - #expect(await callbacks.value == 1) - let stored = try #require(try await fixture.store.fetchDevice(radioID: fixture.device.radioID)) - #expect(stored.nodeName == "Imported") - #expect(stored.frequency == eu.frequencyKHz) - #expect(stored.bandwidth == eu.bandwidthHz) - #expect(stored.spreadingFactor == eu.spreadingFactor) - #expect(stored.codingRate == eu.codingRate) - #expect(stored.txPower == 10) - #expect(stored.publicKey == Data(repeating: 0x22, count: ProtocolLimits.publicKeySize)) - #expect(stored.radioID == fixture.device.radioID) - #expect(stored.id == fixture.device.id) + viewModel.cancelImport() + viewModel.previewTask?.cancel() + await radio.releaseAllGates() + await viewModel.importTask?.value + await viewModel.previewTask?.value + await env.close() + if let bodyError { throw bodyError } } @Test(arguments: [UInt8(0), 1, 2, 3, 4, 255]) @@ -445,18 +485,18 @@ struct SettingsRefreshPropagationTests { #expect(viewModel.importedConfig?.otherSettings?.telemetryModeLocation == 4) #expect(viewModel.importedConfig?.otherSettings?.telemetryModeEnvironment == 4) - viewModel.prepareConfirmation(nodeConfigService: fixture.services.nodeConfigService) + viewModel.configure( + nodeConfigService: { fixture.services.nodeConfigService }, settingsService: { fixture.services.settingsService }, + connectedDevice: { fixture.appState.connectedDevice }, connectionManager: fixture.appState.connectionManager + ) + viewModel.prepareConfirmation() try await waitUntil("preview should accept the config") { viewModel.showConfirmation || viewModel.errorMessage != nil } #expect(viewModel.errorMessage == nil) #expect(viewModel.showConfirmation) - viewModel.applyConfig( - nodeConfigService: fixture.services.nodeConfigService, - settingsService: fixture.services.settingsService, - radioID: fixture.device.radioID - ) + viewModel.applyConfig() try await waitUntil("imported telemetry mode 4 should persist as 0") { fixture.appState.connectedDevice?.telemetryModeBase == 0 && fixture.appState.connectedDevice?.telemetryModeLoc == 0 @@ -506,9 +546,12 @@ private struct RefreshFixture { appState.connectionManager.setTestState( connectionState: .ready, services: services, - connectedDevice: device + session: session, + connectedDevice: device, + connectionIntent: .wantsConnection() ) - await appState.wireSettingsEventStream(services: services) + let snapshot = try #require(appState.connectionManager.currentConnection) + await appState.wireSettingsEventStream(snapshot: snapshot) return RefreshFixture( preferences: preferences, appState: appState, @@ -568,37 +611,6 @@ private func expectPreservedMetadata(_ device: DeviceDTO, matches original: Devi #expect(device.clientRepeat == original.clientRepeat) } -@MainActor -private func configuredImport( - fixture: RefreshFixture, - name: String, - radio: RadioPreset, - txPower: Int8 -) -> NodeConfigImportViewModel { - let viewModel = NodeConfigImportViewModel() - viewModel.importedConfig = MeshCoreNodeConfig( - name: name, - privateKey: String(repeating: "ab", count: 64), - radioSettings: .init( - frequency: radio.frequencyKHz, - bandwidth: radio.bandwidthHz, - spreadingFactor: radio.spreadingFactor, - codingRate: radio.codingRate, - txPower: txPower - ) - ) - viewModel.sections.nodeIdentity = true - viewModel.sections.radioSettings = true - return viewModel -} - -private actor CallbackCount { - private(set) var value = 0 - func increment() { - value += 1 - } -} - private actor PropagationRadio: MeshTransport { struct State: Sendable { var publicKey = Data(repeating: 0x11, count: 32) diff --git a/MC1Tests/ViewModels/TracePathExecutionCancellationTests.swift b/MC1Tests/ViewModels/TracePathExecutionCancellationTests.swift index 4fb1cb7d28..e790aadd96 100644 --- a/MC1Tests/ViewModels/TracePathExecutionCancellationTests.swift +++ b/MC1Tests/ViewModels/TracePathExecutionCancellationTests.swift @@ -125,6 +125,158 @@ struct TracePathExecutionCancellationTests { try #require(clock.sleeperCount == 0) } + @Test(arguments: [false, true], [false, true]) + func `a response during send wins once over its later completion`(isBatch: Bool, sendFails: Bool) async throws { + let send = ControllableTraceSend() + let clock = TestClock() + let viewModel = makeViewModel(send: send, clock: clock) + defer { + viewModel.reset() + send.completeAll() + } + viewModel.batchEnabled = isBatch + viewModel.batchSize = 1 + viewModel.startTrace() + let execution = try #require(viewModel.executionTaskForTesting) + + try await waitUntil("send should start") { send.sendCount == 1 } + let tag = try #require(viewModel.pendingTagForTesting) + viewModel.handleTraceResponse(traceInfo(tag: tag), radioID: nil) + viewModel.handleTraceResponse(traceInfo(tag: tag), radioID: nil) + #expect(viewModel.result?.success == true) + + if sendFails { + send.failOldest(MeshCoreError.timeout) + } else { + send.completeOldest() + } + await execution.value + + #expect(viewModel.result?.success == true) + #expect(viewModel.errorMessage == nil) + #expect(viewModel.completedResults.count == (isBatch ? 1 : 0)) + #expect(viewModel.isRunning == false) + #expect(viewModel.pendingTagForTesting == nil) + #expect(viewModel.hasActiveTimeoutTaskForTesting == false) + #expect(clock.sleeperCount == 0) + } + + @Test(arguments: [false, true]) + func `a retired preflight cannot send or replace a newer request`(replace: Bool) async throws { + let send = ControllableTraceSend() + send.hangUntilComplete = false + let clock = TestClock() + let gate = AppendGate() + let viewModel = makeViewModel(send: send, clock: clock) + defer { + gate.release() + viewModel.reset() + send.completeAll() + } + viewModel.responseTimeoutSecondsForTesting = 30 + viewModel.throwBeforeTagForTesting = { await gate.wait() } + viewModel.startTrace() + let oldExecution = try #require(viewModel.executionTaskForTesting) + try await waitUntil("preflight should suspend") { gate.started } + + var replacementTag: UInt32? + if replace { + viewModel.throwBeforeTagForTesting = nil + viewModel.startTrace() + try await waitUntil("replacement should wait for its response") { clock.sleeperCount == 1 } + let tag = try #require(viewModel.pendingTagForTesting) + replacementTag = tag + } else { + viewModel.cancelExecution() + } + gate.release() + await oldExecution.value + + #expect(send.sendCount == (replace ? 1 : 0)) + #expect(viewModel.pendingTagForTesting == replacementTag) + #expect(viewModel.errorMessage == nil) + #expect(viewModel.result == nil) + #expect(viewModel.isRunning == replace) + if let replacementTag { + viewModel.handleTraceResponse(traceInfo(tag: replacementTag), radioID: nil) + #expect(viewModel.result?.success == true) + } + } + + @Test(arguments: [false, true]) + func `a response after a send error completes the request once`(isBatch: Bool) async throws { + let send = ControllableTraceSend() + let clock = TestClock() + let viewModel = makeViewModel(send: send, clock: clock) + defer { + viewModel.reset() + send.completeAll() + } + viewModel.batchEnabled = isBatch + viewModel.batchSize = 1 + viewModel.unackedTimeoutSecondsForTesting = 5 + viewModel.startTrace() + let execution = try #require(viewModel.executionTaskForTesting) + + try await waitUntil("send should start") { send.sendCount == 1 } + let tag = try #require(viewModel.pendingTagForTesting) + send.failOldest(MeshCoreError.timeout) + try await waitUntil("unacked response deadline should park") { clock.sleeperCount == 1 } + let timeout = try #require(viewModel.timeoutTaskForTesting) + viewModel.handleTraceResponse(traceInfo(tag: tag), radioID: nil) + viewModel.handleTraceResponse(traceInfo(tag: tag), radioID: nil) + await execution.value + await timeout.value + clock.advance(by: .seconds(5)) + + #expect(viewModel.result?.success == true) + #expect(viewModel.errorMessage == nil) + #expect(viewModel.completedResults.count == (isBatch ? 1 : 0)) + #expect(viewModel.isRunning == false) + #expect(viewModel.pendingTagForTesting == nil) + } + + @Test + func `a timeout retains the submitted path and hash size`() async throws { + let send = ControllableTraceSend() + let clock = TestClock() + let viewModel = makeViewModel(send: send, clock: clock) + defer { + viewModel.reset() + send.completeAll() + } + var submittedPath: Data? + var submittedFlags: UInt8? + viewModel.sendTraceForTesting = { tag, flags, path in + submittedPath = path + submittedFlags = flags + return try await send.send(tag: tag, flags: flags, path: path) + } + viewModel.batchEnabled = true + viewModel.batchSize = 1 + viewModel.responseTimeoutSecondsForTesting = 5 + viewModel.startTrace() + let execution = try #require(viewModel.executionTaskForTesting) + try await waitUntil("send should start") { send.sendCount == 1 } + let path = try #require(submittedPath) + let flags = try #require(submittedFlags) + + viewModel.setTraceHashMode(1) + viewModel.addNode(makeContact()) + send.completeOldest() + try await waitUntil("response deadline should park") { clock.sleeperCount == 1 } + clock.advance(by: .seconds(5)) + await execution.value + + let result = try #require(viewModel.completedResults.first) + #expect(viewModel.completedResults.count == 1) + #expect(result.success == false) + #expect(result.tracedPathBytes == Array(path)) + #expect(result.hashSize == 1 << Int(flags)) + #expect(viewModel.fullPathData != path) + #expect(viewModel.hashSize != result.hashSize) + } + @Test func `hiding during the response wait still accepts the response`() async throws { let send = ControllableTraceSend() @@ -357,7 +509,7 @@ struct TracePathExecutionCancellationTests { connectedDevice: { nil }, bestAvailableLocation: { nil } )) - viewModel.setPendingTagForTesting(0x00C0_FFEE) + viewModel.setPendingTraceForTesting(0x00C0_FFEE) viewModel.isRunning = true viewModel.startListening() @@ -390,7 +542,7 @@ struct TracePathExecutionCancellationTests { bestAvailableLocation: { nil } )) viewModel.addNode(makeContact()) - viewModel.setPendingTagForTesting(0x00C0_FFEE) + viewModel.setPendingTraceForTesting(0x00C0_FFEE) viewModel.startListening() let listener = try #require(viewModel.traceEventsTaskForTesting) viewModel.reset() @@ -422,7 +574,7 @@ struct TracePathExecutionCancellationTests { connectedDevice: { nil }, bestAvailableLocation: { nil } )) - viewModel.setPendingTagForTesting(0x00C0_FFEE) + viewModel.setPendingTraceForTesting(0x00C0_FFEE) viewModel.isRunning = true viewModel.startListening() let listener = try #require(viewModel.traceEventsTaskForTesting) diff --git a/MC1Tests/ViewModels/TracePathListenerTests.swift b/MC1Tests/ViewModels/TracePathListenerTests.swift index 07d66589f2..fab62f64be 100644 --- a/MC1Tests/ViewModels/TracePathListenerTests.swift +++ b/MC1Tests/ViewModels/TracePathListenerTests.swift @@ -67,7 +67,7 @@ struct TracePathListenerTests { currentServices = services viewModel.startListening() - viewModel.setPendingTagForTesting(Self.testTag) + viewModel.setPendingTraceForTesting(Self.testTag) services.advertisementService.eventBroadcaster.yield( .traceResponse(traceInfo: makeTraceInfo(tag: Self.testTag), radioID: UUID()) ) @@ -98,7 +98,7 @@ struct TracePathListenerTests { currentServices = newServices viewModel.startListening() - viewModel.setPendingTagForTesting(Self.testTag) + viewModel.setPendingTraceForTesting(Self.testTag) newServices.advertisementService.eventBroadcaster.yield( .traceResponse(traceInfo: makeTraceInfo(tag: Self.testTag), radioID: UUID()) ) diff --git a/MC1Tests/ViewModels/TracePathSaveSnapshotTests.swift b/MC1Tests/ViewModels/TracePathSaveSnapshotTests.swift new file mode 100644 index 0000000000..c1baf1cce6 --- /dev/null +++ b/MC1Tests/ViewModels/TracePathSaveSnapshotTests.swift @@ -0,0 +1,106 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Trace Path saved request snapshot", .timeLimit(.minutes(1))) +@MainActor +struct TracePathSaveSnapshotTests { + @Test(arguments: [false, true]) + func `equal path bytes with different hop widths cannot change the saved trace`(isBatch: Bool) async throws { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radioID = UUID() + let device = DeviceDTO(from: Device( + radioID: radioID, + publicKey: Data(repeating: 0x01, count: 32), + nodeName: "Local radio", + firmwareVersion: 9 + )) + let originalPath = Data([0xAB, 0xCD]) + let original = makeContact(prefix: [0xAB, 0xCD], radioID: radioID) + let additional = makeContact(prefix: [0xCD], radioID: radioID) + let clock = TestClock() + let viewModel = TracePathViewModel(clock: clock) + defer { viewModel.reset() } + viewModel.configure(dependencies: .init( + dataStore: { store }, + session: { nil }, + advertisementService: { nil }, + connectedDevice: { device }, + bestAvailableLocation: { nil } + )) + viewModel.setContactsForTesting([original, additional]) + viewModel.setTraceHashMode(1) + viewModel.addNode(original) + viewModel.batchEnabled = isBatch + viewModel.batchSize = 1 + viewModel.responseTimeoutSecondsForTesting = 30 + + var submissions: [(tag: UInt32, flags: UInt8, path: Data)] = [] + viewModel.sendTraceForTesting = { tag, flags, path in + submissions.append((tag, flags, path)) + return MessageSentInfo(route: 1, expectedAck: Data(), suggestedTimeoutMs: 1000) + } + viewModel.startTrace() + let execution = try #require(viewModel.executionTaskForTesting) + try await waitUntil("the original trace should be waiting") { clock.sleeperCount == 1 } + let submitted = try #require(submissions.first) + #expect(submitted.flags == 1) + #expect(submitted.path == originalPath) + + viewModel.setTraceHashMode(0) + viewModel.autoReturnPath = false + viewModel.addNode(additional) + #expect(viewModel.fullPathData == originalPath) + #expect(viewModel.outboundPath.map(\.hashBytes) == [Data([0xAB]), Data([0xCD])]) + + viewModel.handleTraceResponse(response(tag: submitted.tag), radioID: radioID) + await execution.value + let result = try #require(viewModel.result) + #expect(result.success) + #expect(result.tracedPathBytes == Array(originalPath)) + #expect(result.hashSize == 2) + #expect(viewModel.hashSize == 1) + #expect(viewModel.canSavePath == false) + + // Exercise persistence independently of the UI's save-availability guard. + #expect(await viewModel.savePath(name: "Original trace")) + let savedPaths = try await store.fetchSavedTracePaths(radioID: radioID) + #expect(savedPaths.count == 1) + let saved = try #require(savedPaths.first) + #expect(saved.pathBytes == originalPath) + #expect(saved.hashSize == 2) + #expect(saved.runs.count == 1) + #expect(saved.runs.first?.success == true) + + viewModel.loadSavedPath(saved) + #expect(viewModel.fullPathData == originalPath) + #expect(viewModel.outboundPath.map(\.hashBytes) == [originalPath]) + #expect(viewModel.hashSize == 2) + #expect(viewModel.effectiveTraceMode == 1) + } + + private func makeContact(prefix: [UInt8], radioID: UUID) -> ContactDTO { + ContactDTO(from: Contact( + radioID: radioID, + publicKey: Data(prefix + Array(repeating: 0, count: 32 - prefix.count)), + name: "Repeater", + typeRawValue: ContactType.repeater.rawValue, + lastHeardTimestamp: 0 + )) + } + + private func response(tag: UInt32) -> TraceInfo { + TraceInfo( + tag: tag, + authCode: 0, + flags: 1, + pathLength: 1, + path: [ + TraceNode(hashBytes: Data([0xAB, 0xCD]), snr: 5), + TraceNode(hashBytes: nil, snr: 3) + ] + ) + } +} diff --git a/MC1Tests/ViewModels/TracePathViewModelTests.swift b/MC1Tests/ViewModels/TracePathViewModelTests.swift index c8dcfc3c14..ca6ac4a61c 100644 --- a/MC1Tests/ViewModels/TracePathViewModelTests.swift +++ b/MC1Tests/ViewModels/TracePathViewModelTests.swift @@ -271,7 +271,7 @@ struct TraceResponseHopParsingTests { ) // Set up pending tag to match - viewModel.setPendingTagForTesting(12345) + viewModel.setPendingTraceForTesting(12345) viewModel.handleTraceResponse(traceInfo, radioID: nil) guard let result = viewModel.result else { @@ -318,7 +318,7 @@ struct TraceResponseHopParsingTests { ] ) - viewModel.setPendingTagForTesting(12345) + viewModel.setPendingTraceForTesting(12345) viewModel.handleTraceResponse(traceInfo, radioID: nil) guard let result = viewModel.result else { @@ -356,7 +356,7 @@ struct TraceResponseHopParsingTests { ] ) - viewModel.setPendingTagForTesting(12345) // Different from traceInfo.tag + viewModel.setPendingTraceForTesting(12345) // Different from traceInfo.tag viewModel.handleTraceResponse(traceInfo, radioID: nil) #expect(viewModel.result == nil) @@ -384,7 +384,7 @@ struct ResultIDBehaviorTests { ] ) - viewModel.setPendingTagForTesting(12345) + viewModel.setPendingTraceForTesting(12345) #expect(viewModel.resultID == nil) viewModel.handleTraceResponse(traceInfo, radioID: nil) @@ -407,12 +407,12 @@ struct ResultIDBehaviorTests { ] ) - viewModel.setPendingTagForTesting(12345) + viewModel.setPendingTraceForTesting(12345) viewModel.handleTraceResponse(traceInfo, radioID: nil) let firstID = viewModel.resultID // Run another trace - viewModel.setPendingTagForTesting(12346) + viewModel.setPendingTraceForTesting(12346) let traceInfo2 = TraceInfo( tag: 12346, authCode: 0, @@ -605,7 +605,7 @@ struct MultiByteHashTests { ] ) - viewModel.setPendingTagForTesting(12345) + viewModel.setPendingTraceForTesting(12345) viewModel.handleTraceResponse(traceInfo, radioID: nil) guard let result = viewModel.result else { @@ -636,7 +636,7 @@ struct MultiByteHashTests { ] ) - viewModel.setPendingTagForTesting(12345) + viewModel.setPendingTraceForTesting(12345) viewModel.handleTraceResponse(traceInfo, radioID: nil) guard let result = viewModel.result else { @@ -789,8 +789,7 @@ struct DeviceIDValidationTests { ] ) - viewModel.setPendingTagForTesting(12345) - viewModel.setPendingDeviceIDForTesting(pendingDevice) + viewModel.setPendingTraceForTesting(12345, radioID: pendingDevice) viewModel.handleTraceResponse(traceInfo, radioID: differentDevice) // Result should be nil - response was ignored @@ -813,8 +812,7 @@ struct DeviceIDValidationTests { ] ) - viewModel.setPendingTagForTesting(12345) - viewModel.setPendingDeviceIDForTesting(deviceID) + viewModel.setPendingTraceForTesting(12345, radioID: deviceID) viewModel.handleTraceResponse(traceInfo, radioID: deviceID) #expect(viewModel.result != nil) @@ -836,8 +834,7 @@ struct DeviceIDValidationTests { ] ) - viewModel.setPendingTagForTesting(12345) - viewModel.setPendingDeviceIDForTesting(nil) + viewModel.setPendingTraceForTesting(12345, radioID: nil) viewModel.handleTraceResponse(traceInfo, radioID: UUID()) // Should accept - pendingDeviceID is nil so skip device check @@ -859,8 +856,7 @@ struct DeviceIDValidationTests { ] ) - viewModel.setPendingTagForTesting(12345) - viewModel.setPendingDeviceIDForTesting(UUID()) + viewModel.setPendingTraceForTesting(12345, radioID: UUID()) viewModel.handleTraceResponse(traceInfo, radioID: nil) // Should accept - received deviceID is nil so skip device check @@ -879,8 +875,7 @@ struct PathCaptureTests { // Set up pending path hash (simulating what runTrace does) let originalPath: [UInt8] = [0xAA, 0xBB, 0xAA] - viewModel.setPendingPathHashForTesting(originalPath) - viewModel.setPendingTagForTesting(12345) + viewModel.setPendingTraceForTesting(12345, path: originalPath) let traceInfo = TraceInfo( tag: 12345, @@ -911,8 +906,7 @@ struct PathCaptureTests { // Simulate a completed trace with path [0xAA, 0xAA] let originalPath: [UInt8] = [0xAA, 0xAA] - viewModel.setPendingPathHashForTesting(originalPath) - viewModel.setPendingTagForTesting(12345) + viewModel.setPendingTraceForTesting(12345, path: originalPath) let traceInfo = TraceInfo( tag: 12345, @@ -979,8 +973,7 @@ struct PathCaptureTests { let currentPath = viewModel.fullPathBytes // Simulate trace with same path - viewModel.setPendingPathHashForTesting(currentPath) - viewModel.setPendingTagForTesting(12345) + viewModel.setPendingTraceForTesting(12345, path: currentPath) let traceInfo = TraceInfo( tag: 12345, @@ -1652,7 +1645,7 @@ struct OutboundPathNameResolutionTests { ] ) - viewModel.setPendingTagForTesting(12345) + viewModel.setPendingTraceForTesting(12345) viewModel.handleTraceResponse(traceInfo, radioID: nil) guard let result = viewModel.result else { @@ -1740,7 +1733,7 @@ struct OutboundPathNameResolutionTests { ] ) - viewModel.setPendingTagForTesting(42) + viewModel.setPendingTraceForTesting(42) viewModel.handleTraceResponse(traceInfo, radioID: nil) guard let result = viewModel.result else { @@ -1774,7 +1767,7 @@ struct OutboundPathNameResolutionTests { ] ) - viewModel.setPendingTagForTesting(12345) + viewModel.setPendingTraceForTesting(12345) viewModel.handleTraceResponse(traceInfo, radioID: nil) guard let result = viewModel.result else { diff --git a/MC1Tests/Views/AdaptiveNavigationTests.swift b/MC1Tests/Views/AdaptiveNavigationTests.swift index 53a4d97a4d..b775e84677 100644 --- a/MC1Tests/Views/AdaptiveNavigationTests.swift +++ b/MC1Tests/Views/AdaptiveNavigationTests.swift @@ -653,7 +653,7 @@ struct AdaptiveNavigationTests { private func contactDetailIsVisible(in host: Host, contact: ContactDTO) -> Bool { guard host.renderedContact.id == contact.id, let navigation = navigationControllers(from: host.window.rootViewController) - .first(where: { viewIsVisible($0.view, in: host.window) }), + .first(where: { viewIsVisible($0.view, in: host.window) }), let root = navigation.topViewController?.view, let list = descendantViews(in: root, of: UICollectionView.self).first else { return false } return viewIsVisible(list, in: host.window) diff --git a/MC1Tests/Views/Chats/ChatChannelInfoPresentationTests.swift b/MC1Tests/Views/Chats/ChatChannelInfoPresentationTests.swift index 9c3e17a5a3..b0f562eb12 100644 --- a/MC1Tests/Views/Chats/ChatChannelInfoPresentationTests.swift +++ b/MC1Tests/Views/Chats/ChatChannelInfoPresentationTests.swift @@ -36,6 +36,28 @@ struct ChatChannelInfoPresentationTests { try await host.expectPin(initialPin) } + @Test + func `opening Channel Info offline initializes a legacy Text Rules identity`() async throws { + let host = try Host(initialPin: false, legacyChannel: true) + defer { host.tearDown() } + let store = host.appState.connectionManager.persistenceStore + host.appState.connectionManager.setTestState(connectionState: .disconnected, connectedDevice: .some(nil)) + #expect(try await store.fetchChannel(id: host.channel.id)?.textRulesID == nil) + + host.mount() + try await host.openInfo() + + let conversationID = try #require(try await store.fetchChannel(id: host.channel.id)?.textRulesID) + try await store.setTextRulesOverride( + .on, kind: .privateChannel, key: .init(radioID: host.channel.radioID, conversationID: conversationID) + ) + try await host.closeInfo() + try await host.openInfo() + let reopened = try #require(try await store.fetchChannel(id: host.channel.id)) + #expect(reopened.textRulesID == conversationID) + #expect(reopened.textRulesOverride == .on) + } + @MainActor private final class Host { let preferences = IsolatedUserDefaults() @@ -44,16 +66,25 @@ struct ChatChannelInfoPresentationTests { let window: UIWindow private(set) var controller: UIViewController = .init() - init(initialPin: Bool) throws { + init(initialPin: Bool, legacyChannel: Bool = false) throws { let container = try PersistenceStore.createContainer(inMemory: true) - appState = AppState(modelContainer: container, isPlaceholder: true, defaults: preferences.defaults) - let device = DeviceDTO(from: Device(publicKey: Data(repeating: 1, count: ProtocolLimits.publicKeySize), nodeName: "Radio")) - appState.connectionManager.setTestState(connectionState: .ready, connectedDevice: .some(device)) - appState.connectionManager.persistConnection(deviceID: device.id, radioID: device.radioID, deviceName: device.nodeName) - channel = ChannelDTO(from: Channel( + let device = Device(publicKey: Data(repeating: 1, count: ProtocolLimits.publicKeySize), nodeName: "Radio") + let model = Channel( radioID: device.radioID, index: 1, name: "General", secret: Data(repeating: 1, count: ProtocolLimits.channelSecretSize), isPinned: initialPin - )) + ) + if legacyChannel { + model.textRulesID = nil + let context = ModelContext(container) + context.insert(device) + context.insert(model) + try context.save() + } + let deviceDTO = DeviceDTO(from: device) + channel = ChannelDTO(from: model) + appState = AppState(modelContainer: container, isPlaceholder: true, defaults: preferences.defaults) + appState.connectionManager.setTestState(connectionState: .ready, connectedDevice: .some(deviceDTO)) + appState.connectionManager.persistConnection(deviceID: deviceDTO.id, radioID: deviceDTO.radioID, deviceName: deviceDTO.nodeName) let scene = try #require(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) window = UIWindow(windowScene: scene) window.frame = ChatChannelInfoPresentationTests.viewport diff --git a/MC1Tests/Views/Chats/ChatOpenAnchorStateTests.swift b/MC1Tests/Views/Chats/ChatOpenAnchorStateTests.swift new file mode 100644 index 0000000000..8f5f4d697d --- /dev/null +++ b/MC1Tests/Views/Chats/ChatOpenAnchorStateTests.swift @@ -0,0 +1,81 @@ +import Foundation +@testable import MC1 +import Testing + +@Suite("ChatOpenAnchorState") +@MainActor +struct ChatOpenAnchorStateTests { + private static let unreadCount = 3 + + private enum FetchError: Error { + case failed + } + + @Test + func `a baked divider presents before and after Populate settles`() { + let divider = UUID() + var state = ChatOpenAnchorState(unreadCount: Self.unreadCount) + + #expect(state.firstSnapshot(dividerMessageID: divider, dividerRowOnScreen: true) == .present(target: divider)) + state.completePopulate(.loaded) + #expect(state.firstSnapshot(dividerMessageID: divider, dividerRowOnScreen: true) == .present(target: divider)) + } + + @Test + func `an unbaked divider withholds before and after Populate settles`() { + let divider = UUID() + var state = ChatOpenAnchorState(unreadCount: Self.unreadCount) + + #expect(state.firstSnapshot(dividerMessageID: divider, dividerRowOnScreen: false) == .withhold) + state.completePopulate(.loaded) + #expect(state.firstSnapshot(dividerMessageID: divider, dividerRowOnScreen: false) == .withhold) + } + + @Test + func `terminal Populate without a divider presents at the bottom`() { + let outcomes: [ChatTimelinePopulator.Outcome] = [.loaded, .unavailable, .failed(FetchError.failed)] + for outcome in outcomes { + var state = ChatOpenAnchorState(unreadCount: Self.unreadCount) + #expect(state.firstSnapshot(dividerMessageID: nil, dividerRowOnScreen: false) == .withhold) + + state.completePopulate(outcome) + + #expect(state.firstSnapshot(dividerMessageID: nil, dividerRowOnScreen: false) == .present(target: nil)) + } + } + + @Test + func `cancelled Populate preserves readiness before and after a terminal retry`() { + var state = ChatOpenAnchorState(unreadCount: Self.unreadCount) + state.completePopulate(.cancelled) + #expect(state.firstSnapshot(dividerMessageID: nil, dividerRowOnScreen: false) == .withhold) + + state.completePopulate(.loaded) + state.completePopulate(.cancelled) + #expect(state.firstSnapshot(dividerMessageID: nil, dividerRowOnScreen: false) == .present(target: nil)) + } + + @Test(arguments: [false, true]) + func `consumption retires the Anchor across later Populate outcomes`(settledBeforeConsumption: Bool) { + let divider = UUID() + var state = ChatOpenAnchorState(unreadCount: Self.unreadCount) + if settledBeforeConsumption { + state.completePopulate(.loaded) + } + #expect(state.firstSnapshot(dividerMessageID: divider, dividerRowOnScreen: true) == .present(target: divider)) + + state.consumeAnchor() + #expect(state.firstSnapshot(dividerMessageID: divider, dividerRowOnScreen: true) == .present(target: nil)) + state.completePopulate(.cancelled) + #expect(state.firstSnapshot(dividerMessageID: divider, dividerRowOnScreen: true) == .present(target: nil)) + state.completePopulate(.loaded) + #expect(state.firstSnapshot(dividerMessageID: divider, dividerRowOnScreen: true) == .present(target: nil)) + } + + @Test + func `no unread backlog presents immediately with no target`() { + let state = ChatOpenAnchorState(unreadCount: 0) + + #expect(state.firstSnapshot(dividerMessageID: UUID(), dividerRowOnScreen: true) == .present(target: nil)) + } +} diff --git a/MC1Tests/Views/Chats/ChatOpenAtDividerCompositionTests.swift b/MC1Tests/Views/Chats/ChatOpenAtDividerCompositionTests.swift index 845e6426a1..7ba3439efa 100644 --- a/MC1Tests/Views/Chats/ChatOpenAtDividerCompositionTests.swift +++ b/MC1Tests/Views/Chats/ChatOpenAtDividerCompositionTests.swift @@ -3,55 +3,39 @@ import Foundation @testable import MC1Services import Testing -/// Composition tests for the open-at-divider first-snapshot decision on a warm -/// coordinator. -/// -/// A `ChatCoordinator` outlives the push, so on reopen a fresh `ChatViewModel` -/// reads state baked by the previous session. The open target must come from -/// the current session's unread position — never a divider the previous -/// session baked — and the timeline must stay withheld until the flag-bearing -/// divider item is among the items actually on screen. +/// A shared coordinator can retain a previous open's Bake, so readiness must +/// use this open's divider and the current flag-bearing row together. @Suite("Open-at-divider composition") @MainActor struct ChatOpenAtDividerCompositionTests { - @Test(arguments: [1, 18]) - func `reopen on a warm coordinator never presents the previous session's divider`( - currentUnreadCount: Int - ) async { + @Test + func `reopen on a warm coordinator never presents the previous session's divider`() async { let staleMessages = (0..<50).map { makeMessage(index: $0) } let coordinator = await makeWarmCoordinator(staleMessages: staleMessages, staleUnreadCount: 20) let staleDividerID = staleMessages[30].id let bakedDividerItemID = coordinator.renderState.items.first { $0.grouping.showNewMessagesDivider }?.id #expect(bakedDividerItemID == staleDividerID) - // Reopen: `currentUnreadCount` messages arrived while the chat was closed. - // The coordinator still holds the previous session's page; the fresh - // fetch has not landed. Mirrors `ChatConversationView.init`, which only - // attaches the shared coordinator before `configure` runs. + // Attach without populating so the previous open's page remains cached. let reopenedViewModel = ChatViewModel() reopenedViewModel.attachCoordinator(coordinator) + reopenedViewModel.timeline.stageOpen(makeConversation(unreadCount: 1)) - let decision = firstSnapshotDecision(for: reopenedViewModel, unreadCount: currentUnreadCount) - - // The first unread message of this session is not on screen yet, so the - // only correct decision is to withhold: presenting spends the one-shot - // positioning on the previous session's page. - #expect(decision == .withhold) + #expect(reopenedViewModel.timeline.firstSnapshot == .withhold) } @Test - func `fresh divider computed but not yet applied to items keeps withholding`() async { + func `a fresh divider presents only after its baked row is applied`() async { let staleMessages = (0..<50).map { makeMessage(index: $0) } let coordinator = await makeWarmCoordinator(staleMessages: staleMessages, staleUnreadCount: 20) let newMessages = (50..<68).map { makeMessage(index: $0) } let currentMessages = staleMessages + newMessages - // Populate has computed this session's divider synchronously, but the - // rebuilt items apply later from the off-main build: the coordinator's - // items are still the previous session's page in this window. + // The divider is computed while the coordinator still holds the previous Bake. let reopenedViewModel = ChatViewModel() reopenedViewModel.attachCoordinator(coordinator) + reopenedViewModel.timeline.stageOpen(makeConversation(unreadCount: newMessages.count)) reopenedViewModel.bake.computeDividerPosition( from: currentMessages, unreadCount: newMessages.count, @@ -59,44 +43,15 @@ struct ChatOpenAtDividerCompositionTests { ) #expect(reopenedViewModel.bake.newMessagesDividerMessageID == newMessages[0].id) - let decision = firstSnapshotDecision( - for: reopenedViewModel, - unreadCount: newMessages.count, - initialLoadSettled: true - ) - - #expect(decision == .withhold) - } - - @Test - func `divider presents once the fresh page and bake are applied`() async { - let staleMessages = (0..<50).map { makeMessage(index: $0) } - let coordinator = await makeWarmCoordinator(staleMessages: staleMessages, staleUnreadCount: 20) + reopenedViewModel.timeline.completePopulate(.loaded) - let newMessages = (50..<68).map { makeMessage(index: $0) } - let currentMessages = staleMessages + newMessages - - // The reopen load completed: fresh page replaced, this session's divider - // computed, items rebaked. Mirrors `configure` binding the writer and - // populate finishing. - let reopenedViewModel = ChatViewModel() + #expect(reopenedViewModel.timeline.firstSnapshot == .withhold) reopenedViewModel.bindCoordinatorForTesting(coordinator) coordinator.replaceAllForTesting(currentMessages) - reopenedViewModel.bake.computeDividerPosition( - from: currentMessages, - unreadCount: newMessages.count, - isDM: false - ) reopenedViewModel.buildItems() await coordinator.buildItemsTask?.value - let decision = firstSnapshotDecision( - for: reopenedViewModel, - unreadCount: newMessages.count, - initialLoadSettled: true - ) - - #expect(decision == .present(target: newMessages[0].id)) + #expect(reopenedViewModel.timeline.firstSnapshot == .present(target: newMessages[0].id)) } @Test @@ -109,74 +64,19 @@ struct ChatOpenAtDividerCompositionTests { let reopenedViewModel = ChatViewModel() reopenedViewModel.attachCoordinator(coordinator) + reopenedViewModel.timeline.stageOpen(makeConversation(unreadCount: 8)) reopenedViewModel.bake.computeDividerPosition(from: staleMessages, unreadCount: 8, isDM: false) #expect(reopenedViewModel.bake.newMessagesDividerMessageID == staleMessages[42].id) - let decision = firstSnapshotDecision(for: reopenedViewModel, unreadCount: 8) - - // Id is on screen without the divider flag: presenting would spend the - // one-shot, and the later flag-bearing rebake would push content under - // the input bar. - #expect(decision == .withhold) - } - - @Test - func `a fully read conversation presents immediately with no target`() async { - let staleMessages = (0..<50).map { makeMessage(index: $0) } - let coordinator = await makeWarmCoordinator(staleMessages: staleMessages, staleUnreadCount: 20) - - let reopenedViewModel = ChatViewModel() - reopenedViewModel.attachCoordinator(coordinator) - - // No unread backlog: nothing to wait for, even before the load settles. - let decision = firstSnapshotDecision(for: reopenedViewModel, unreadCount: 0) - - #expect(decision == .present(target: nil)) - } - - @Test - func `a settled load with no divider target presents at the bottom`() async { - let staleMessages = (0..<50).map { makeMessage(index: $0) } - let coordinator = await makeWarmCoordinator(staleMessages: staleMessages, staleUnreadCount: 20) - - // Populate finished without computing a divider (failed or empty fetch): - // the escape hatch must present rather than withhold forever. - let reopenedViewModel = ChatViewModel() - reopenedViewModel.attachCoordinator(coordinator) - - let decision = firstSnapshotDecision( - for: reopenedViewModel, - unreadCount: 18, - initialLoadSettled: true - ) - - #expect(decision == .present(target: nil)) + #expect(reopenedViewModel.timeline.firstSnapshot == .withhold) } } -/// Resolve the decision the same way `ChatTimeline.firstSnapshot` does, so -/// these tests exercise the production readiness fact against real composed state. -@MainActor -private func firstSnapshotDecision( - for viewModel: ChatViewModel, - unreadCount: Int, - initialLoadSettled: Bool = false, - hasConsumed: Bool = false -) -> ChatInitialScrollPolicy.FirstSnapshotDecision { - let dividerMessageID = viewModel.bake.newMessagesDividerMessageID - let items = viewModel.items - let itemIndexByID = viewModel.itemIndexByID - let dividerRowOnScreen = dividerMessageID.flatMap { id -> Bool? in - guard let index = itemIndexByID[id], items.indices.contains(index) else { return nil } - return items[index].grouping.showNewMessagesDivider - } ?? false - return ChatInitialScrollPolicy.firstSnapshotDecision( - hasConsumed: hasConsumed, - unreadCount: unreadCount, - initialLoadSettled: initialLoadSettled, - dividerMessageID: dividerMessageID, - dividerRowOnScreen: dividerRowOnScreen - ) +private func makeConversation(unreadCount: Int) -> ChatConversationType { + .channel(ChannelDTO( + id: UUID(), radioID: UUID(), index: 1, name: "Fixture", secret: Data(), + isEnabled: true, lastMessageDate: nil, unreadCount: unreadCount + )) } /// A coordinator carrying a previous session's fully baked page, including its diff --git a/MC1Tests/Views/Chats/ChatPinInfoSheetTests.swift b/MC1Tests/Views/Chats/ChatPinInfoSheetTests.swift index 60ece0fbaa..efe2698ce6 100644 --- a/MC1Tests/Views/Chats/ChatPinInfoSheetTests.swift +++ b/MC1Tests/Views/Chats/ChatPinInfoSheetTests.swift @@ -129,7 +129,6 @@ struct ChatPinInfoSheetTests { connectionState: { .disconnected }, connectedDevice: { nil }, currentRadioID: { nil }, - session: { nil }, reactionService: { nil }, chatSendQueueService: { nil }, inlineImageDimensionsStore: { nil }, diff --git a/MC1Tests/Views/Chats/ChatReconnectPopulateTests.swift b/MC1Tests/Views/Chats/ChatReconnectPopulateTests.swift index 4d18aec853..8d3558502e 100644 --- a/MC1Tests/Views/Chats/ChatReconnectPopulateTests.swift +++ b/MC1Tests/Views/Chats/ChatReconnectPopulateTests.swift @@ -109,13 +109,11 @@ struct ChatReconnectPopulateTests { viewModel.configureForTesting(dependencies: .testDefaults(dataStore: { dataStore })) viewModel.bindCoordinatorForTesting(coordinator) viewModel.timeline.stageOpen(.dm(contact)) - #expect(viewModel.timeline.initialLoadSettled == false) + #expect(viewModel.timeline.firstSnapshot == .withhold) let loaded = await viewModel.primeInitialMessages(for: contact, populateMode: .refreshWindow) #expect(loaded) - #expect(viewModel.timeline.initialLoadSettled, - "First open must run populate, not skip the warm window") let dividerID = try #require(viewModel.bake.newMessagesDividerMessageID, "The interactive open must bake the New Messages divider") await coordinator.buildItemsTask?.value @@ -137,7 +135,7 @@ struct ChatReconnectPopulateTests { let contact = makeContact(radioID: UUID(), unreadCount: 0) let viewModel = ChatViewModel() viewModel.configure( - dependencies: appState.makeChatViewModelDependencies(), + dependencies: appState.makeChatViewModelDependencies(radioID: contact.radioID), onNavigateToMap: nil, linkPreviewCache: nil, chatCoordinatorRegistry: appState.ensureChatCoordinatorRegistry(), @@ -169,12 +167,19 @@ struct ChatReconnectPopulateTests { timestamp: 9000 ) try await env.dataStore.saveMessage(incoming) + try await env.dataStore.saveDevice(DeviceDTO(from: Device( + radioID: env.contact.radioID, + publicKey: Data(repeating: 0x17, count: 32), + nodeName: "TestRadio" + ))) + let scope = try #require(await env.dataStore.captureReceiveScope(radioID: env.contact.radioID, link: .init())) + let contact = try #require(await env.dataStore.fetchContact(id: env.contact.id)) - await env.viewModel.handle(.directMessageReceived(message: incoming, contact: env.contact)) + await env.viewModel.handle(.directMessageReceived(message: incoming, contact: contact, scope: scope)) #expect(env.viewModel.messages.contains { $0.id == incoming.id }) let countAfterAdmit = env.viewModel.messages.count - await env.viewModel.handle(.directMessageReceived(message: incoming, contact: env.contact)) + await env.viewModel.handle(.directMessageReceived(message: incoming, contact: contact, scope: scope)) #expect(env.viewModel.messages.count == countAfterAdmit) } diff --git a/MC1Tests/Views/Chats/ChatSendAdmissionTests.swift b/MC1Tests/Views/Chats/ChatSendAdmissionTests.swift index cd55e4461f..c222fef68b 100644 --- a/MC1Tests/Views/Chats/ChatSendAdmissionTests.swift +++ b/MC1Tests/Views/Chats/ChatSendAdmissionTests.swift @@ -10,27 +10,20 @@ import UIKit struct ChatSendAdmissionTests { private let timeout: Duration = .seconds(3) - @Test(arguments: [false, true]) - func `service loss before message creation surfaces a send failure`(isChannel: Bool) async { - let viewModel = ChatViewModel() - let radioID = UUID() - viewModel.configureForTesting(dependencies: .testDefaults()) - - selectConversation(viewModel, radioID: radioID, isChannel: isChannel) - let reachedService = await submit("Retain this text", to: viewModel, isChannel: isChannel) - - #expect(!reachedService) - #expect(viewModel.messages.isEmpty) - #expect(viewModel.sendErrorMessage == L10n.Chats.Chats.Alert.UnableToSend.message) - } - @Test(arguments: [false, true]) func `queue rejection retains one failed Message without restoring a duplicate Draft`(isChannel: Bool) async throws { let radioID = UUID() let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) - let service = MessageService(session: MeshCoreSession(transport: MockTransport()), dataStore: store, contactService: nil) + let services = ServiceContainer( + session: MeshCoreSession(transport: MockTransport()), dataStore: store, radioID: radioID + ) + await store.setPendingSendInsertHandler { throw CocoaError(.fileWriteUnknown) } let viewModel = ChatViewModel() - viewModel.configureForTesting(dependencies: .testDefaults(dataStore: { store }, messageService: { service })) + viewModel.configureForTesting(dependencies: .testDefaults( + dataStore: { store }, + messageService: { services.messageService }, + chatSendQueueService: { services.chatSendQueueService } + )) viewModel.bindCoordinatorForTesting(ChatCoordinator.makeForTesting()) selectConversation(viewModel, radioID: radioID, isChannel: isChannel) if let contact = viewModel.currentContact { try await store.saveContact(contact) } @@ -42,6 +35,32 @@ struct ChatSendAdmissionTests { #expect(viewModel.messages.count == 1) #expect(message.status == .failed) #expect(try await store.fetchMessage(id: message.id)?.status == .failed) + #expect(try await store.fetchMessage(id: message.id)?.failureSeen == true) + #expect(try await store.fetchPendingSends(radioID: radioID).isEmpty) + #expect(viewModel.sendErrorMessage == L10n.Chats.Chats.Error.sendQueuePersistFailed) + await services.chatSendQueueService.shutdown() + } + + @Test(arguments: [false, true]) + func `retired queue rejects before creation so the composer restores the Draft`(isChannel: Bool) async throws { + let radioID = UUID() + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let services = ServiceContainer( + session: MeshCoreSession(transport: MockTransport()), dataStore: store, radioID: radioID + ) + let viewModel = ChatViewModel() + viewModel.configureForTesting(dependencies: .testDefaults( + dataStore: { store }, + messageService: { services.messageService }, + chatSendQueueService: { services.chatSendQueueService } + )) + selectConversation(viewModel, radioID: radioID, isChannel: isChannel) + await services.chatSendQueueService.shutdown() + + let reachedService = await submit("Retain this text", to: viewModel, isChannel: isChannel) + + #expect(!reachedService) + #expect(viewModel.messages.isEmpty) #expect(try await store.fetchPendingSends(radioID: radioID).isEmpty) #expect(viewModel.sendErrorMessage == L10n.Chats.Chats.Alert.UnableToSend.message) } diff --git a/MC1Tests/Views/Chats/ChatTimelineOpeningCancellationTests.swift b/MC1Tests/Views/Chats/ChatTimelineOpeningCancellationTests.swift index 9ec8f78218..6d1c5987c6 100644 --- a/MC1Tests/Views/Chats/ChatTimelineOpeningCancellationTests.swift +++ b/MC1Tests/Views/Chats/ChatTimelineOpeningCancellationTests.swift @@ -120,13 +120,102 @@ struct ChatTimelineOpeningCancellationTests { return false }.value #expect(refreshCancelled) - #expect(timeline.initialLoadSettled) #expect(timeline.firstSnapshot == settledSnapshot) case .failed, .noUnread: #expect(timeline.firstSnapshot == .present(target: nil)) } } + @Test(.timeLimit(.minutes(1))) + func `an unread anchor consumed during reaction indexing stays consumed when open finishes`() async throws { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radioID = UUID() + let channel = makeChannel(radioID: radioID) + try await store.saveChannel(channel) + let readMessage = MessageDTO(from: Message( + radioID: radioID, channelIndex: channel.index, text: "Read message", timestamp: Metrics.timestamp, + createdAt: Date(timeIntervalSince1970: TimeInterval(Metrics.timestamp)), + directionRawValue: MessageDirection.incoming.rawValue, + statusRawValue: MessageStatus.delivered.rawValue, isRead: true + )) + try await store.saveMessage(readMessage) + let unreadTimestamp = Metrics.timestamp + UInt32(Metrics.readCount) + let unreadMessage = MessageDTO(from: Message( + radioID: radioID, channelIndex: channel.index, text: "Unread message", timestamp: unreadTimestamp, + createdAt: Date(timeIntervalSince1970: TimeInterval(unreadTimestamp)), + directionRawValue: MessageDirection.incoming.rawValue, + statusRawValue: MessageStatus.delivered.rawValue, senderNodeName: "Alice", isRead: false + )) + try await store.saveMessage(unreadMessage) + + let reactionService = ReactionService() + let rawText = reactionService.buildReactionText( + emoji: "👍", targetSender: "Alice", targetText: unreadMessage.text, + targetTimestamp: unreadMessage.reactionTimestamp + ) + try await reactionService.queuePendingReaction( + parsed: #require(ReactionParser.parse(rawText)), channelIndex: channel.index, + senderNodeName: "Bob", rawText: rawText, radioID: radioID + ) + let indexingStarted = AsyncStream.makeStream() + let resumeIndexing = AsyncStream.makeStream() + defer { + indexingStarted.continuation.finish() + resumeIndexing.continuation.finish() + } + await reactionService.setReactionAdmitHoldForTesting { + indexingStarted.continuation.yield(()) + for await _ in resumeIndexing.stream {} + } + + let coordinator = ChatCoordinator( + conversationID: .channel(radioID: radioID, channelIndex: channel.index), dataStore: store + ) + let timeline = ChatTimeline(role: .interactive) + timeline.stageOpen(.channel(channel)) + timeline.bind(coordinator, dataStore: { store }, senderTables: { .empty }, postApply: nil) + var openFinished = false + let openTask = Task { + defer { + openFinished = true + indexingStarted.continuation.finish() + } + return await timeline.open( + .channel(channel), + reactions: .init(service: reactionService, scope: .channel(channel, localNodeName: nil)), + populateMode: .replace + ) + } + defer { openTask.cancel() } + var indexingEvents = indexingStarted.stream.makeAsyncIterator() + try #require(await indexingEvents.next() != nil) + await coordinator.buildItemsTask?.value + try #require(timeline.firstSnapshot == .present(target: unreadMessage.id)) + #expect(!openFinished) + timeline.consumeAnchor() + #expect(timeline.firstSnapshot == .present(target: nil)) + + resumeIndexing.continuation.finish() + let outcome = await openTask.value + guard case .loaded = outcome else { + Issue.record("The open must finish after reaction indexing resumes") + return + } + await coordinator.coalescedReloadTask?.value + await coordinator.buildItemsTask?.value + #expect(try await store.fetchReactions(for: unreadMessage.id).map(\.emoji) == ["👍"]) + #expect(timeline.bake.newMessagesDividerMessageID == unreadMessage.id) + #expect(timeline.firstSnapshot == .present(target: nil)) + + timeline.releaseWriter() + timeline.stageOpen(.channel(channel)) + #expect(timeline.firstSnapshot == .withhold) + timeline.bind(coordinator, dataStore: { store }, senderTables: { .empty }, postApply: nil) + _ = await timeline.open(.channel(channel), reactions: nil, populateMode: .refreshWindow) + await coordinator.buildItemsTask?.value + #expect(timeline.firstSnapshot == .present(target: unreadMessage.id)) + } + @Test(arguments: [false, true]) func `unbound entry settles only when its task has not been cancelled`(cancelled: Bool) async { let channel = makeChannel(radioID: UUID()) diff --git a/MC1Tests/Views/Chats/ChatViewModelAdmissionTests.swift b/MC1Tests/Views/Chats/ChatViewModelAdmissionTests.swift index 5191297a4e..6ab9c171fd 100644 --- a/MC1Tests/Views/Chats/ChatViewModelAdmissionTests.swift +++ b/MC1Tests/Views/Chats/ChatViewModelAdmissionTests.swift @@ -640,7 +640,6 @@ private actor AdmissionStubDataStore: PersistenceStoreProtocol { func updateMessageStatus(id: UUID, status: MessageStatus) async throws {} func updateMessageAck(id: UUID, ackCode: UInt32, status: MessageStatus, roundTripTime: UInt32?) async throws {} func updateMessageRetryStatus(id: UUID, status: MessageStatus, retryAttempt: Int, maxRetryAttempts: Int) async throws {} - func updateMessageHeardRepeats(id: UUID, heardRepeats: Int) async throws {} func updateMessageLinkPreview(id: UUID, url: String?, title: String?, imageData: Data?, iconData: Data?, fetched: Bool) throws {} func fetchContacts(radioID: UUID) async throws -> [ContactDTO] { @@ -827,6 +826,7 @@ private actor AdmissionStubDataStore: PersistenceStoreProtocol { func admitSentEcho( messageID: UUID, + expectedTimestamp: UInt32, receivedAt: Date, pathNodes: Data, pathLength: UInt8, @@ -837,12 +837,20 @@ private actor AdmissionStubDataStore: PersistenceStoreProtocol { nil } - func deleteMessageRepeats(messageID: UUID) async throws {} func incrementMessageSendCount(id: UUID) async throws -> Int { 0 } func updateMessageTimestamp(id: UUID, timestamp: UInt32) async throws {} + func commitOutgoingDirectMessageTimestamp(id: UUID, timestamp: UInt32) async throws -> UInt32? { + nil + } + + func setPendingSendWireAttempt(id: UUID, to next: UInt8) async throws -> Bool { + false + } + + func prepareChannelMessageResend(id: UUID, timestamp: UInt32) async throws {} func saveDebugLogEntries(_ dtos: [DebugLogEntryDTO]) async throws {} func fetchDebugLogEntries(since date: Date, limit: Int) async throws -> [DebugLogEntryDTO] { @@ -975,28 +983,23 @@ private actor AdmissionStubDataStore: PersistenceStoreProtocol { } func markMessageAsRead(id: UUID) async throws {} - func incrementPendingSendAttemptCount(messageID: UUID) async throws -> Int? { + func savePendingAcknowledgement(_ dto: PendingSendDTO, replacingPendingSendID: UUID?, markSent _: Bool) async throws -> Bool { + false + } + + func resolvePendingAcknowledgement(id: UUID, expectedDeadline: Date?, status: MessageStatus, ackCode: UInt32?, roundTripTime: UInt32?) async throws -> Bool { + false + } + + func preparePendingSendAttempt(messageID: UUID) async throws -> (pendingSendID: UUID, attemptCount: Int)? { nil } func saveDevice(_ dto: DeviceDTO) async throws {} - func updateDeviceNodeName(radioID: UUID, name: String) async throws {} - func updateDeviceCoordinates(radioID: UUID, latitude: Double, longitude: Double) async throws {} - func updateDeviceRadio( - radioID: UUID, - frequency: UInt32, - bandwidth: UInt32, - spreadingFactor: UInt8, - codingRate: UInt8, - appliedRadioPresetID: String? - ) async throws {} - func updateDeviceTxPower(radioID: UUID, txPower: Int8) async throws {} - func updateDeviceObservation(radioID: UUID, mapped: DeviceDTO) async throws {} - func updateDeviceOtherParams(radioID: UUID, intent: OtherParamsIntent) async throws {} - func updateDeviceClientRepeat(radioID: UUID, enabled: Bool) async throws {} - func updateDevicePathHashMode(radioID: UUID, mode: UInt8) async throws {} - func updateDeviceAutoAdd(radioID: UUID, config: UInt8, maxHops: UInt8) async throws {} - func updateDeviceDefaultFloodScopeName(radioID: UUID, name: String?) async throws {} + func updateDeviceOCVSettings(id: UUID, preset: String, customArray: String?) async throws -> DeviceDTO? { + nil + } + func fetchRemoteNodeSessionByPrefix(_ prefix: Data) async throws -> RemoteNodeSessionDTO? { nil } @@ -1102,6 +1105,23 @@ private actor AdmissionStubDataStore: PersistenceStoreProtocol { func deleteOldNodeStatusSnapshots(olderThan date: Date) async throws {} + func recordSelfTelemetrySnapshot( + deviceID: UUID, + radioID: UUID, + nodePublicKey: Data, + telemetry: [TelemetrySnapshotEntry]?, + location: NodeLocationFix? + ) async throws -> UUID? { + nil + } + + func fetchSelfTelemetrySnapshots( + radioID: UUID, + nodePublicKey: Data + ) async throws -> [NodeStatusSnapshotDTO] { + [] + } + func upsertPendingSend(_ dto: PendingSendDTO) async throws {} func insertPendingSendAssigningSequence(_ dto: PendingSendDTO) async throws -> Int { 0 diff --git a/MC1Tests/Views/Chats/ChatViewModelConversationTests.swift b/MC1Tests/Views/Chats/ChatViewModelConversationTests.swift index f77eb16e67..d68a32f827 100644 --- a/MC1Tests/Views/Chats/ChatViewModelConversationTests.swift +++ b/MC1Tests/Views/Chats/ChatViewModelConversationTests.swift @@ -73,7 +73,6 @@ struct ChatViewModelConversationTests { connectionState: { .disconnected }, connectedDevice: { nil }, currentRadioID: { nil }, - session: { nil }, reactionService: { nil }, chatSendQueueService: { nil }, inlineImageDimensionsStore: { nil }, diff --git a/MC1Tests/Views/Chats/ChatViewModelDependencies+Testing.swift b/MC1Tests/Views/Chats/ChatViewModelDependencies+Testing.swift index d42b100310..97cc644aa7 100644 --- a/MC1Tests/Views/Chats/ChatViewModelDependencies+Testing.swift +++ b/MC1Tests/Views/Chats/ChatViewModelDependencies+Testing.swift @@ -17,7 +17,6 @@ extension ChatViewModel.Dependencies { connectionState: @escaping @MainActor () -> DeviceConnectionState = { .disconnected }, connectedDevice: @escaping @MainActor () -> DeviceDTO? = { nil }, currentRadioID: @escaping @MainActor () -> UUID? = { nil }, - session: @escaping @MainActor () -> MeshCoreSession? = { nil }, reactionService: @escaping @MainActor () -> ReactionService? = { nil }, chatSendQueueService: @escaping @MainActor () -> ChatSendQueueService? = { nil }, inlineImageDimensionsStore: @escaping @MainActor () -> InlineImageDimensionsStore? = { nil }, @@ -34,7 +33,6 @@ extension ChatViewModel.Dependencies { connectionState: connectionState, connectedDevice: connectedDevice, currentRadioID: currentRadioID, - session: session, reactionService: reactionService, chatSendQueueService: chatSendQueueService, inlineImageDimensionsStore: inlineImageDimensionsStore, diff --git a/MC1Tests/Views/Chats/ChatViewModelFailedSendTests.swift b/MC1Tests/Views/Chats/ChatViewModelFailedSendTests.swift index 97849a0e84..3a14b49861 100644 --- a/MC1Tests/Views/Chats/ChatViewModelFailedSendTests.swift +++ b/MC1Tests/Views/Chats/ChatViewModelFailedSendTests.swift @@ -309,12 +309,15 @@ struct ChatViewModelFailedSendTests { let messageID = UUID() let contact = makeContact() let message = makeMessage(radioID: contact.radioID, contactID: contact.id) + let scope = ReceiveScope(radioID: contact.radioID, link: .init(), partition: .init()) #expect(!viewModel.shouldRefreshFailedSendIndicators( - for: .directMessageReceived(message: message, contact: contact) + for: .directMessageReceived(message: message, contact: contact, scope: scope) )) #expect(!viewModel.shouldRefreshFailedSendIndicators( - for: .channelMessageReceived(message: message, channelIndex: 0) + for: .channelMessageReceived( + message: message, channelIndex: 0, scope: scope + ) )) #expect(!viewModel.shouldRefreshFailedSendIndicators( for: .roomMessageReceived( @@ -324,7 +327,8 @@ struct ChatViewModelFailedSendTests { text: "hi", timestamp: 1 ), - sessionID: UUID() + sessionID: UUID(), + scope: scope ) )) #expect(!viewModel.shouldRefreshFailedSendIndicators( diff --git a/MC1Tests/Views/Chats/ChatViewModelReactionDeleteTests.swift b/MC1Tests/Views/Chats/ChatViewModelReactionDeleteTests.swift new file mode 100644 index 0000000000..e5ee54b1e1 --- /dev/null +++ b/MC1Tests/Views/Chats/ChatViewModelReactionDeleteTests.swift @@ -0,0 +1,135 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import Testing + +@Suite("ChatViewModel reaction deletion") +@MainActor +struct ChatViewModelReactionDeleteTests { + private static let baseTimestamp: UInt32 = 1_700_000_000 + private static let olderRowRemainder = 3 + private static let emoji = "👀" + private static let senderName = "Melody" + + @Test(arguments: [false, true], [false, true]) + func `deleting a target removes its reaction and preserves older paging`(isChannel: Bool, isFailed: Bool) async throws { + let environment = try await makeEnvironment(isChannel: isChannel, isFailed: isFailed) + let viewModel = environment.viewModel + await viewModel.loadOlderMessages() + let oldestLoadedID = try #require(viewModel.messages.first?.id) + let rawCount = viewModel.totalFetchedCount + #expect(rawCount == ChatCoordinator.pageSize * 2) + #expect((viewModel.messagesByID[environment.child.id] != nil) == isFailed) + + await viewModel.deleteMessage(environment.target) + await viewModel.coordinator?.buildItemsTask?.value + + #expect(viewModel.errorMessage == nil) + #expect(viewModel.messagesByID[environment.target.id] == nil) + #expect(viewModel.messagesByID[environment.child.id] == nil) + #expect(viewModel.items.contains { $0.id == environment.child.id } == false) + #expect(viewModel.messagesByID[oldestLoadedID] != nil) + #expect(viewModel.totalFetchedCount == rawCount - 2) + #expect(try await environment.store.fetchMessage(id: environment.child.id) == nil) + + await viewModel.loadOlderMessages() + await viewModel.coordinator?.buildItemsTask?.value + + #expect(Set(viewModel.messages.map(\.id)) == Set(environment.history.map(\.id))) + #expect(viewModel.totalFetchedCount == environment.history.count) + #expect(viewModel.hasMoreMessages == false) + } + + private func makeEnvironment(isChannel: Bool, isFailed: Bool) async throws -> Environment { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radioID = UUID() + let viewModel = ChatViewModel() + viewModel.configureForTesting(dependencies: .testDefaults( + dataStore: { store }, connectionState: { .ready }, currentRadioID: { radioID } + )) + let contactID: UUID? + let channelIndex: UInt8? + let conversationID: ChatConversationID + if isChannel { + let channel = ChannelDTO( + id: UUID(), radioID: radioID, index: 0, name: "test", + secret: Data(repeating: 1, count: 16), isEnabled: true, + lastMessageDate: nil, unreadCount: 0 + ) + try await store.saveChannel(channel) + viewModel.currentChannel = channel + contactID = nil + channelIndex = channel.index + conversationID = .channel(radioID: radioID, channelIndex: channel.index) + } else { + let contact = ContactDTO( + id: UUID(), radioID: radioID, publicKey: Data(repeating: 2, count: 32), + name: Self.senderName, typeRawValue: ContactType.chat.rawValue, flags: 0, + outPathLength: 0, outPath: Data(), lastAdvertTimestamp: 0, + latitude: 0, longitude: 0, lastModified: 0, lastHeardTimestamp: nil, + nickname: nil, isBlocked: false, isMuted: false, isFavorite: false, + lastMessageDate: nil, unreadCount: 0 + ) + try await store.saveContact(contact) + viewModel.currentContact = contact + contactID = contact.id + channelIndex = nil + conversationID = .dm(radioID: radioID, contactID: contact.id) + } + let olderCount = ChatCoordinator.pageSize * 2 + Self.olderRowRemainder + var history: [MessageDTO] = [] + for index in 0..