From d4d101346b192bcf26f94368b74321f37f9eed3a Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:04:46 -0800 Subject: [PATCH 01/66] feat: opt in to debug log collection - Persisted debug logs stay off until the user turns collection on. - Turning it off waits out an in-flight save, drops memory, then deletes the rows. A failed delete turns the toggle back on. --- MC1/Resources/Generated/L10n.swift | 14 + .../Localization/de.lproj/Settings.strings | 15 + .../Localization/en.lproj/Settings.strings | 15 + .../Localization/es.lproj/Settings.strings | 15 + .../Localization/fr.lproj/Settings.strings | 15 + .../Localization/it.lproj/Settings.strings | 15 + .../Localization/ko.lproj/Settings.strings | 15 + .../Localization/nl.lproj/Settings.strings | 15 + .../Localization/pl.lproj/Settings.strings | 15 + .../Localization/pt.lproj/Settings.strings | 15 + .../Localization/ru.lproj/Settings.strings | 15 + .../Localization/uk.lproj/Settings.strings | 15 + .../zh-Hans.lproj/Settings.strings | 15 + .../Sections/DiagnosticsSection.swift | 110 ++++- .../MC1Services/Services/AppStorageKey.swift | 4 + .../MC1Services/Services/DebugLogBuffer.swift | 125 ++++- .../Mocks/MockPersistenceStore.swift | 4 + .../Services/DebugLogBufferTests.swift | 33 ++ .../DebugLogCollectionGateTests.swift | 437 ++++++++++++++++++ .../Services/PersistentLoggerTests.swift | 94 +++- .../DiagnosticsSectionCollectionTests.swift | 427 +++++++++++++++++ 21 files changed, 1407 insertions(+), 21 deletions(-) create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/DebugLogCollectionGateTests.swift create mode 100644 MC1Tests/Views/Settings/DiagnosticsSectionCollectionTests.swift diff --git a/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index b84a3a5932..376ab482ca 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -5012,6 +5012,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,11 +5029,23 @@ 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 diff --git a/MC1/Resources/Localization/de.lproj/Settings.strings b/MC1/Resources/Localization/de.lproj/Settings.strings index 2dc599399e..55eb8ae077 100644 --- a/MC1/Resources/Localization/de.lproj/Settings.strings +++ b/MC1/Resources/Localization/de.lproj/Settings.strings @@ -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 beendet. Exportierte Protokolldateien bleiben unberührt."; + /* Error when export fails */ "diagnostics.error.exportFailed" = "Exportdatei konnte nicht erstellt werden"; diff --git a/MC1/Resources/Localization/en.lproj/Settings.strings b/MC1/Resources/Localization/en.lproj/Settings.strings index 392e51b1b5..bbeefe8db6 100644 --- a/MC1/Resources/Localization/en.lproj/Settings.strings +++ b/MC1/Resources/Localization/en.lproj/Settings.strings @@ -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"; diff --git a/MC1/Resources/Localization/es.lproj/Settings.strings b/MC1/Resources/Localization/es.lproj/Settings.strings index 7cc9ab4fdd..57647f90a6 100644 --- a/MC1/Resources/Localization/es.lproj/Settings.strings +++ b/MC1/Resources/Localization/es.lproj/Settings.strings @@ -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"; diff --git a/MC1/Resources/Localization/fr.lproj/Settings.strings b/MC1/Resources/Localization/fr.lproj/Settings.strings index 8acf72b407..6af9737e8f 100644 --- a/MC1/Resources/Localization/fr.lproj/Settings.strings +++ b/MC1/Resources/Localization/fr.lproj/Settings.strings @@ -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"; diff --git a/MC1/Resources/Localization/it.lproj/Settings.strings b/MC1/Resources/Localization/it.lproj/Settings.strings index 0d08844501..6ca2381d60 100644 --- a/MC1/Resources/Localization/it.lproj/Settings.strings +++ b/MC1/Resources/Localization/it.lproj/Settings.strings @@ -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"; diff --git a/MC1/Resources/Localization/ko.lproj/Settings.strings b/MC1/Resources/Localization/ko.lproj/Settings.strings index bee41bda00..7ca76e0fc8 100644 --- a/MC1/Resources/Localization/ko.lproj/Settings.strings +++ b/MC1/Resources/Localization/ko.lproj/Settings.strings @@ -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" = "내보내기 파일을 만들지 못함"; diff --git a/MC1/Resources/Localization/nl.lproj/Settings.strings b/MC1/Resources/Localization/nl.lproj/Settings.strings index 76b71eb1f5..7cc9c67fa1 100644 --- a/MC1/Resources/Localization/nl.lproj/Settings.strings +++ b/MC1/Resources/Localization/nl.lproj/Settings.strings @@ -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"; diff --git a/MC1/Resources/Localization/pl.lproj/Settings.strings b/MC1/Resources/Localization/pl.lproj/Settings.strings index 2cef662aa7..50e34031c9 100644 --- a/MC1/Resources/Localization/pl.lproj/Settings.strings +++ b/MC1/Resources/Localization/pl.lproj/Settings.strings @@ -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"; diff --git a/MC1/Resources/Localization/pt.lproj/Settings.strings b/MC1/Resources/Localization/pt.lproj/Settings.strings index 6f3dc4e662..b4709070f8 100644 --- a/MC1/Resources/Localization/pt.lproj/Settings.strings +++ b/MC1/Resources/Localization/pt.lproj/Settings.strings @@ -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"; diff --git a/MC1/Resources/Localization/ru.lproj/Settings.strings b/MC1/Resources/Localization/ru.lproj/Settings.strings index 615f6852da..8999e4f348 100644 --- a/MC1/Resources/Localization/ru.lproj/Settings.strings +++ b/MC1/Resources/Localization/ru.lproj/Settings.strings @@ -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" = "Не удалось создать файл экспорта"; diff --git a/MC1/Resources/Localization/uk.lproj/Settings.strings b/MC1/Resources/Localization/uk.lproj/Settings.strings index 807e23a4c4..fad917c184 100644 --- a/MC1/Resources/Localization/uk.lproj/Settings.strings +++ b/MC1/Resources/Localization/uk.lproj/Settings.strings @@ -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" = "Не вдалося створити файл експорту"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings index f6fdeb8d8c..06f5466913 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings @@ -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" = "创建导出文件失败"; diff --git a/MC1/Views/Settings/Sections/DiagnosticsSection.swift b/MC1/Views/Settings/Sections/DiagnosticsSection.swift index b2d47ca363..926734512b 100644 --- a/MC1/Views/Settings/Sections/DiagnosticsSection.swift +++ b/MC1/Views/Settings/Sections/DiagnosticsSection.swift @@ -7,34 +7,59 @@ 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 string as `presentedErrorMessage`, kept on this view value so it is + /// still readable after `disableCollection(using:)` suspends. The alert binds + /// the state property, which is written in the same assignment. + 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 +70,54 @@ 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) + } + + /// Turning off raises the confirm alert and does not write the key. Confirm + /// calls `disableCollection`, which sets the key false until it returns. This + /// view writes the key true only when that call throws. Turning on during the + /// wipe does not write the key. + private var collectionBinding: Binding { + Binding( + get: { collectLogs }, + set: { setCollectionEnabled($0) } + ) + } + + func setCollectionEnabled(_ isOn: Bool) { + if isOn { + DebugLogBuffer.enableCollection() + } else { + showingDisableCollectionAlert = true + } + } + + /// Confirm action for the disable alert. On success the service already left + /// the key false, so this does not write it. On throw the service left the + /// key false and left the rows; this turns the key 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 +131,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 +144,7 @@ struct DiagnosticsSection: View { do { try await dataStore.clearDebugLogEntries() } catch { - errorMessage = error.userFacingMessage + setErrorMessage(error.userFacingMessage, record: errorRecord) } } } diff --git a/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift b/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift index 0116b800f2..777969dbaf 100644 --- a/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift +++ b/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift @@ -63,6 +63,10 @@ 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 + /// Intentionally device-local: not registered in BackupUserDefaults so a foreign + /// phone's "on" can't silently turn on log collection after restore. Absent means + /// off (opt-in), matching the fresh-install default. + case collectDebugLogs // Notification toggles read by NotificationPreferences and // NotificationPreferencesStore; all share defaultNotificationEnabled. diff --git a/MC1Services/Sources/MC1Services/Services/DebugLogBuffer.swift b/MC1Services/Sources/MC1Services/Services/DebugLogBuffer.swift index fa240d1411..22cef70ebd 100644 --- a/MC1Services/Sources/MC1Services/Services/DebugLogBuffer.swift +++ b/MC1Services/Sources/MC1Services/Services/DebugLogBuffer.swift @@ -14,8 +14,26 @@ public actor DebugLogBuffer { } private static let sharedState = OSAllocatedUnfairLock(initialState: SharedState()) + /// Depth of `disableCollection` calls in progress. The key write that turns + /// collection off and a turn-on both happen under this lock, so a toggle + /// during the wipe cannot land true. + private struct CollectionDisable { + var depth = 0 + } + + private static let collectionDisable = OSAllocatedUnfairLock(initialState: CollectionDisable()) static let maxPendingEntries = 500 + /// Opt-in gate for persisted debug-log collection. Read fresh on every `record` + /// so it works off the main actor and at early launch, before the first + /// connection creates a buffer. A missing key means off (opt-in), matching both + /// fresh installs and upgrades from any prior version. The app target writes it + /// via `@AppStorage`; MC1Services only reads it, so this shares the app's + /// standard `UserDefaults` domain. + nonisolated static var isCollectionEnabled: Bool { + UserDefaults.standard.bool(forKey: AppStorageKey.collectDebugLogs.rawValue) + } + /// 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 @@ -41,9 +59,12 @@ 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. + /// assigned. When collection is off, drops the entry before any queueing, buffer + /// handoff, or `Task` creation. Entries already in `pending` or `buffer` are not + /// discarded by a mere read of the setting; only `disableCollection` discards them. 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,6 +76,50 @@ public actor DebugLogBuffer { Task { await buffer.append(entry) } } + /// Turns collection on unless `disableCollection` owns it. A turn-on that + /// loses the race with a disable in progress 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) + } + } + + /// Owns collection from the write that sets the key false until this returns. + /// Waits out a save already inside `saveDebugLogEntries`, drops whatever that + /// save put back in memory, then deletes rows. The save cannot finish after + /// the delete. A throw leaves the key false and the rows that could not be + /// deleted; the caller turns the key back on. The depth returns to zero + /// before this returns, including on throw. + 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 the pending queue so tests can exercise the no-buffer window from a /// known state. static func resetPendingStateForTesting() { @@ -81,6 +146,13 @@ public actor DebugLogBuffer { /// succeeding together must not persist duplicate summaries. private var isPersistingDropSummary = false + /// `flushBuffer` calls that have passed the collection gate and not yet + /// returned. `disableCollection` waits for this to hit zero before it + /// deletes rows, so a save already inside `saveDebugLogEntries` cannot + /// finish after that 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 +162,7 @@ public actor DebugLogBuffer { } public func append(_ entry: DebugLogEntryDTO) { + guard Self.isCollectionEnabled else { return } buffer.append(entry) if buffer.count >= Self.maxBufferSize { @@ -113,6 +186,47 @@ 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 saves already in flight, then drops memory. Called only after + /// the collection key is false, so a flush that starts 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 +248,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)) diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift index b14ae77518..7b26d72039 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift @@ -64,6 +64,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 { diff --git a/MC1Services/Tests/MC1ServicesTests/Services/DebugLogBufferTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/DebugLogBufferTests.swift index df80333c0d..fa6d9dd7fa 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/DebugLogBufferTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/DebugLogBufferTests.swift @@ -14,6 +14,25 @@ struct DebugLogBufferTests { /// `pruneIfDue` stamps cutoff with `Date()` at call time; the test reads it a tick later. private static let pruneCutoffSlack: TimeInterval = 2 + /// The on-path tests below exercise the queue/drain/flush behavior that predates + /// the collection gate; that behavior is reachable only when collection is on, so + /// each pins the key true and restores the captured value afterward. + 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) @@ -102,6 +121,8 @@ struct DebugLogBufferTests { /// pending entries into its own buffer. @Test func `entries logged before shared is assigned are drained in order once a buffer is set`() async { + let captured = enableCollectionForTesting() + defer { restoreCollection(captured) } let store = MockPersistenceStore() let buffer = DebugLogBuffer(dataStore: store) @@ -128,6 +149,8 @@ struct DebugLogBufferTests { /// relaunch) can't grow the queue without bound. @Test func `pending queue drops oldest entries once the bound is exceeded`() async { + let captured = enableCollectionForTesting() + defer { restoreCollection(captured) } let store = MockPersistenceStore() let buffer = DebugLogBuffer(dataStore: store) let overflow = 3 @@ -250,6 +273,8 @@ struct DebugLogBufferTests { /// reports the other batch as lost. @Test func `dropped entries during save failures are reported once the store recovers`() async throws { + let captured = enableCollectionForTesting() + defer { restoreCollection(captured) } let store = GatedDebugLogStore() let buffer = DebugLogBuffer(dataStore: store) @@ -274,6 +299,8 @@ struct DebugLogBufferTests { /// forward and the next successful save reports it in full. @Test func `a failed summary save carries the dropped count forward to the next successful save`() async throws { + let captured = enableCollectionForTesting() + defer { restoreCollection(captured) } let store = GatedDebugLogStore() let buffer = DebugLogBuffer(dataStore: store) @@ -352,6 +379,8 @@ struct DebugLogBufferTests { @Test func `hourly prune is skipped when last prune is within pruneInterval`() async { + let captured = enableCollectionForTesting() + defer { restoreCollection(captured) } let store = RecordingDebugLogStore() let buffer = DebugLogBuffer(dataStore: store) await buffer.setLastPruneForTesting(Date()) @@ -366,6 +395,8 @@ struct DebugLogBufferTests { @Test func `hourly prune runs when last prune is older than pruneInterval`() async { + let captured = enableCollectionForTesting() + defer { restoreCollection(captured) } let store = RecordingDebugLogStore() let buffer = DebugLogBuffer(dataStore: store) await buffer.setLastPruneForTesting(Date().addingTimeInterval(-DebugLogRetention.pruneInterval)) @@ -379,6 +410,8 @@ struct DebugLogBufferTests { @Test func `hourly prune retries on the next flush after a failed prune`() async { + let captured = enableCollectionForTesting() + defer { restoreCollection(captured) } let store = RecordingDebugLogStore() await store.setPruneShouldFail(true) let buffer = DebugLogBuffer(dataStore: store) diff --git a/MC1Services/Tests/MC1ServicesTests/Services/DebugLogCollectionGateTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/DebugLogCollectionGateTests.swift new file mode 100644 index 0000000000..434d993500 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/DebugLogCollectionGateTests.swift @@ -0,0 +1,437 @@ +import Foundation +@testable import MC1Services +import os +import Testing + +/// Serialized because every test reassigns the process-global +/// `DebugLogBuffer.shared` and drives the process-global +/// `UserDefaults.standard` collection key, both of which other suites (and +/// `ServiceContainer.init`) can interleave on. As in `DebugLogBufferTests`, +/// assertions read back through a bounded retry to absorb a foreign suite +/// reassigning the global mid-sequence. +/// +/// The gate reads `UserDefaults.standard`, so every test captures the current +/// value for the key in setup, drives it through `UserDefaults.standard` itself, +/// and restores the captured value in teardown. A `UserDefaults(suiteName:)` +/// instance would be a different domain and never move the gate. +@Suite("DebugLogBuffer collection gate", .serialized) +struct DebugLogCollectionGateTests { + private static let key = AppStorageKey.collectDebugLogs.rawValue + private static let maxReadBackAttempts = 5 + + /// Captures the current standard-defaults value for the collection key so + /// teardown can restore it, leaving the process domain as the test found it. + private struct CapturedKey { + let value: Any? + init() { + value = UserDefaults.standard.object(forKey: DebugLogCollectionGateTests.key) + } + + func restore() { + if let value { + UserDefaults.standard.set(value, forKey: DebugLogCollectionGateTests.key) + } else { + UserDefaults.standard.removeObject(forKey: DebugLogCollectionGateTests.key) + } + } + } + + /// 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. + private func writeAndReadBack(_ buffer: DebugLogBuffer, attempts: Int = maxReadBackAttempts) -> Bool { + for _ in 0.. [DebugLogEntryDTO] { + for _ in 0..= minimumCount { + return matches + } + try? await Task.sleep(for: delay) + } + return await store.debugLogEntries.filter { $0.category == category } + } + + /// Key absent (fresh install and upgrade from any prior version): `record` drops + /// the entry, assigning a buffer cannot drain it, and a flush leaves the store + /// empty. + @Test + func `missing key means off so record drops the entry and the store stays empty`() async { + let captured = CapturedKey() + defer { captured.restore() } + UserDefaults.standard.removeObject(forKey: Self.key) + #expect(UserDefaults.standard.object(forKey: Self.key) == nil) + + let store = MockPersistenceStore() + let buffer = DebugLogBuffer(dataStore: store) + let category = UUID().uuidString + DebugLogBuffer.shared = nil + DebugLogBuffer.resetPendingStateForTesting() + DebugLogBuffer.record( + DebugLogEntryDTO(level: .info, subsystem: "test", category: category, message: "dropped") + ) + #expect(writeAndReadBack(buffer)) + await buffer.flush() + try? await Task.sleep(for: .milliseconds(50)) + let matches = await store.debugLogEntries.filter { $0.category == category } + #expect(matches.isEmpty) + DebugLogBuffer.shared = nil + } + + /// Key true: an `.info` entry recorded through `PersistentLogger` persists. + @Test + func `collection on persists an info entry`() async { + let captured = CapturedKey() + defer { captured.restore() } + UserDefaults.standard.set(true, forKey: Self.key) + #expect(UserDefaults.standard.bool(forKey: Self.key)) + + let store = MockPersistenceStore() + let buffer = DebugLogBuffer(dataStore: store) + var messages: [String] = [] + 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") + } + + /// A `DebugLogPersisting` fake whose saves park on a gate. The park is an + /// `await`, so `clearDebugLogEntries` can reenter the actor while a save is + /// held — the same window a suspended `saveDebugLogEntries` leaves open. + 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/PersistentLoggerTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/PersistentLoggerTests.swift index 988b50f123..1602981587 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/PersistentLoggerTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/PersistentLoggerTests.swift @@ -41,8 +41,21 @@ struct PersistentLoggerTests { .map(\.message) } + /// On-path pin: with collection on, `PersistentLogger.persist` queues `.info` + /// and above but not `.debug`. @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,9 +76,88 @@ struct PersistentLoggerTests { ) if messages.contains("info-line") { break } } - defer { DebugLogBuffer.shared = nil } #expect(!messages.contains("debug-line")) #expect(messages.contains("info-line")) } + + /// With collection on, an `.info` logged through `PersistentLogger` persists. + @Test + func `collection on persists an info line through the logger`() 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 + } + #expect(UserDefaults.standard.bool(forKey: AppStorageKey.collectDebugLogs.rawValue)) + + let store = MockPersistenceStore() + let buffer = DebugLogBuffer(dataStore: store) + + var messages: [String] = [] + for _ in 0.. AppState { + let container = try PersistenceStore.createContainer(inMemory: true) + return AppState(modelContainer: container, isPlaceholder: true) + } + + /// Hosts `DiagnosticsSection` in a `NavigationStack` so section rows and footers + /// lay out and the disable alert can present over the hosting window. No + /// `.defaultAppStorage` is applied, so `@AppStorage` resolves to standard defaults. + private func host(_ appState: AppState) throws -> (window: UIWindow, controller: UIHostingController) { + let root = NavigationStack { + FeedbackView() + } + .environment(\.appState, appState) + .environment(\.appTheme, Theme.default) + .environment(\.scenePhase, .active) + + let controller = UIHostingController(rootView: AnyView(root)) + controller.view.frame = CGRect(origin: .zero, size: CGSize(width: 390, height: 844)) + + let scene = try #require( + UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first, + "no connected UIWindowScene; the app test host requires one" + ) + let window = UIWindow(windowScene: scene) + window.frame = CGRect(origin: .zero, size: CGSize(width: 390, height: 844)) + window.rootViewController = controller + window.makeKeyAndVisible() + window.layoutIfNeeded() + return (window, controller) + } + + private func tearDown(window: inout UIWindow?, controller: UIHostingController?, appState: AppState?) { + controller?.view.endEditing(true) + window?.rootViewController = nil + window?.isHidden = true + window?.windowScene = nil + window = nil + appState?.shutdown() + } + + // MARK: - View-tree traversal + + private func descendants(of view: UIView, _ type: T.Type) -> [T] { + ((view as? T).map { [$0] } ?? []) + view.subviews.flatMap { descendants(of: $0, type) } + } + + private func sceneWindows() -> [UIWindow] { + UIApplication.shared.connectedScenes.flatMap { ($0 as? UIWindowScene)?.windows ?? [] } + } + + private func matchesLabel(_ candidate: String?, target: String) -> Bool { + guard let candidate else { return false } + let trimmed = candidate.trimmingCharacters(in: .whitespacesAndNewlines) + if matchesCore(trimmed, target: target) { return true } + let stripped = trimmed.drop { !$0.isLetter && !$0.isNumber } + return matchesCore(String(stripped), target: target) + } + + /// Section headers render uppercase without changing their localized text, and rows + /// concatenate label + value, so an exact / prefix match is the contract. + private func matchesCore(_ text: String, target: String) -> Bool { + let text = text.folding(options: .caseInsensitive, locale: .current) + let target = target.folding(options: .caseInsensitive, locale: .current) + if text == target { return true } + return text.hasPrefix(target + ",") || text.hasPrefix(target + "\n") || text.hasPrefix(target + " ") + } + + /// The labels SwiftUI exposes across the accessibility-element tree — this is how + /// `List` rows and alert actions surface text, since SwiftUI draws `Text` as CoreText + /// layers with no backing `UILabel`. Mirrors `SettingsTabHarness.activateAccessibility`. + private func accessibilityLabels(in view: UIView) -> [String] { + var found: [String] = [] + func walk(_ object: NSObject) { + if object !== view, let label = object.accessibilityLabel { found.append(label) } + guard let view = object as? UIView else { return } + let count = view.accessibilityElementCount() + if count != NSNotFound, count > 0 { + for index in 0.. [String] { + sceneWindows().flatMap { accessibilityLabels(in: $0) } + } + + private func labelMatches(_ target: String) -> Bool { + allLabels().contains { matchesLabel($0, target: target) } + } + + /// The `UISwitch` SwiftUI's `Toggle` renders: the switch on the same cell as the + /// toggle's accessibility identifier. + private func collectionSwitch(in window: UIWindow) -> UISwitch? { + descendants(of: window, UISwitch.self).first + } + + /// Drives the collection switch to `targetValue` through the live view tree, the + /// same `setOn` + `valueChanged` path the chat pin-switch tests use for a SwiftUI + /// `Toggle`. + private func driveSwitch(to targetValue: Bool, in window: UIWindow) -> Bool { + window.layoutIfNeeded() + guard let toggle = collectionSwitch(in: window), toggle.isOn != targetValue else { return false } + toggle.setOn(targetValue, animated: false) + toggle.sendActions(for: .valueChanged) + return true + } + + /// Polls a synchronous UI `condition`, yielding with `Task.sleep` so a pending + /// SwiftUI re-render or alert presentation can settle. Between reads, `layoutIfNeeded` + /// on each connected window forces a synchronous layout pass. + private func waitFor(_ condition: @MainActor () -> Bool) async -> Bool { + let deadline = ContinuousClock.now + Timing.timeout + while ContinuousClock.now < deadline { + if condition() { return true } + try? await Task.sleep(for: Timing.pollInterval) + pump() + } + pump() + return condition() + } + + /// Forces a synchronous layout on every scene window so a just-committed state + /// change is reflected in the view tree on the next `condition()` read. + private func pump() { + for window in sceneWindows() { + window.layoutIfNeeded() + } + } + + // MARK: - Key capture / restore + + private func captureKey() -> Any? { + UserDefaults.standard.object(forKey: Self.key) + } + + private func restoreKey(_ captured: Any?) { + if let captured { + UserDefaults.standard.set(captured, forKey: Self.key) + } else { + UserDefaults.standard.removeObject(forKey: Self.key) + } + } + + // MARK: - Tests + + /// Key true: the toggle row is present and reads on; both action buttons appear; + /// the footer is today's on-path string. + @Test + func `collection on shows toggle, both buttons, and the on footer`() async throws { + let captured = captureKey() + UserDefaults.standard.set(true, forKey: Self.key) + defer { restoreKey(captured) } + + let appState = try makeLiveAppState() + var window: UIWindow? + var controller: UIHostingController? + do { + let hostResult = try host(appState) + window = hostResult.window + controller = hostResult.controller + } + defer { tearDown(window: &window, controller: controller, appState: appState) } + let root = try #require(window) + + let ready = await waitFor { self.labelMatches(Self.enableText) } + #expect(ready) + + #expect(self.labelMatches(Self.exportText)) + #expect(self.labelMatches(Self.clearText)) + #expect(self.labelMatches(Self.footerOnText)) + #expect(self.collectionSwitch(in: root)?.isOn == true) + } + + /// Key false: both action buttons are absent and the disabled footer replaces the + /// on-path footer. + @Test + func `collection off hides both buttons and shows the disabled footer`() async throws { + let captured = captureKey() + UserDefaults.standard.set(false, forKey: Self.key) + defer { restoreKey(captured) } + + let appState = try makeLiveAppState() + var window: UIWindow? + var controller: UIHostingController? + do { + let hostResult = try host(appState) + window = hostResult.window + controller = hostResult.controller + } + defer { tearDown(window: &window, controller: controller, appState: appState) } + let root = try #require(window) + + let ready = await waitFor { self.labelMatches(Self.footerOffText) } + #expect(ready) + + #expect(!self.labelMatches(Self.exportText)) + #expect(!self.labelMatches(Self.clearText)) + #expect(!self.labelMatches(Self.footerOnText)) + #expect(self.collectionSwitch(in: root)?.isOn == false) + } + + /// Off-transition through the view: seed a persisted row, flip the switch off (which + /// raises the confirm alert instead of writing), then run the confirm action against + /// the live store. The alert appears; toggling the switch off does not write the key + /// or delete rows. The confirm action is `disableCollection(using:)`, called here + /// because SwiftUI's alert button exposes no in-process driver. The test does not + /// write the key; a successful confirm leaves it false. + @Test + func `toggling off raises the alert and confirm clears rows and sets the key false`() async throws { + let captured = captureKey() + UserDefaults.standard.set(true, forKey: Self.key) + defer { restoreKey(captured) } + + let appState = try makeLiveAppState() + let store = appState.connectionManager.persistenceStore + try await store.saveDebugLogEntries([ + DebugLogEntryDTO(level: .info, subsystem: "test", category: "ui", message: "seed") + ]) + #expect(try await store.countDebugLogEntries() == 1) + + var window: UIWindow? + var controller: UIHostingController? + do { + let hostResult = try host(appState) + window = hostResult.window + controller = hostResult.controller + } + defer { tearDown(window: &window, controller: controller, appState: appState) } + let root = try #require(window) + + let ready = await waitFor { self.collectionSwitch(in: root)?.isOn == true } + #expect(ready) + + // Flip the switch off; the setter raises the confirm alert instead of writing. + #expect(driveSwitch(to: false, in: root)) + + let alertReady = await waitFor { self.labelMatches(Self.disableConfirmText) } + #expect(alertReady) + // The deferred-write contract: raising the alert writes nothing yet. + #expect(UserDefaults.standard.bool(forKey: Self.key)) + + let section = DiagnosticsSection(exportedFile: .constant(nil), isSidebar: false) + await section.disableCollection(using: store) + + #expect(UserDefaults.standard.bool(forKey: Self.key) == false) + let remaining = try await store.countDebugLogEntries() + #expect(remaining == 0) + } + + /// Confirm against a store whose clear throws. The service leaves the key false + /// and the rows in place; the confirm action turns the key back on and sets + /// `errorMessage`. + @Test + func `failed confirm restores the key, keeps the rows, and sets errorMessage`() async throws { + let captured = captureKey() + UserDefaults.standard.set(true, forKey: Self.key) + defer { restoreKey(captured) } + + let container = try PersistenceStore.createContainer(inMemory: true) + let inner = PersistenceStore(modelContainer: container) + try await inner.saveDebugLogEntries([ + DebugLogEntryDTO(level: .info, subsystem: "test", category: "ui", message: "seed") + ]) + let failing = FailingClearStore(inner: inner) + let section = DiagnosticsSection(exportedFile: .constant(nil), isSidebar: false) + + await section.disableCollection(using: failing) + + #expect(UserDefaults.standard.bool(forKey: Self.key)) + #expect(try await inner.countDebugLogEntries() == 1) + let message = section.errorMessage + #expect( + message == ClearFailure.message, + "errorMessage was \(message ?? "nil")" + ) + } + + /// Clear parks, confirm is in flight, and the on-write does not stick. After + /// confirm returns, a later on-write sets the key true. + @Test + func `on write during confirm does not stick and a later on write enables collection`() async { + let captured = captureKey() + UserDefaults.standard.set(true, forKey: Self.key) + defer { restoreKey(captured) } + + let store = SuspendingClearStore() + let section = DiagnosticsSection(exportedFile: .constant(nil), isSidebar: false) + let confirm = Task { await section.disableCollection(using: store) } + + let started = await waitForClearToStart(store) + #expect(started) + + section.setCollectionEnabled(true) + #expect(UserDefaults.standard.bool(forKey: Self.key) == false) + + await store.releaseClear() + await confirm.value + + #expect(UserDefaults.standard.bool(forKey: Self.key) == false) + section.setCollectionEnabled(true) + #expect(UserDefaults.standard.bool(forKey: Self.key)) + } + + private func waitForClearToStart(_ store: SuspendingClearStore) async -> Bool { + let deadline = ContinuousClock.now + Timing.timeout + while ContinuousClock.now < deadline { + if await store.clearDidStart { return true } + try? await Task.sleep(for: Timing.pollInterval) + } + return await store.clearDidStart + } +} + +/// Wraps an in-memory `PersistenceStore` and throws from `clearDebugLogEntries`, +/// mirroring the app view's `any DebugLogPersisting` seam used by `disableCollection`. +private struct ClearFailure: LocalizedError { + static let message = "The debug log could not be cleared." + var errorDescription: String? { + Self.message + } +} + +private actor FailingClearStore: DebugLogPersisting { + private let inner: PersistenceStore + + init(inner: PersistenceStore) { + self.inner = inner + } + + func saveDebugLogEntries(_ dtos: [DebugLogEntryDTO]) async throws { + try await inner.saveDebugLogEntries(dtos) + } + + func fetchDebugLogEntries(since date: Date, limit: Int) async throws -> [DebugLogEntryDTO] { + try await inner.fetchDebugLogEntries(since: date, limit: limit) + } + + func countDebugLogEntries() async throws -> Int { + try await inner.countDebugLogEntries() + } + + func pruneDebugLogEntries(olderThan cutoff: Date, keepCount: Int) async throws { + try await inner.pruneDebugLogEntries(olderThan: cutoff, keepCount: keepCount) + } + + func clearDebugLogEntries() async throws { + throw ClearFailure() + } +} + +/// Parks `clearDebugLogEntries` until `releaseClear`, so a test can turn the +/// toggle on while confirm is in flight. +private actor SuspendingClearStore: DebugLogPersisting { + private var waiter: CheckedContinuation? + private(set) var clearDidStart = false + + func saveDebugLogEntries(_ dtos: [DebugLogEntryDTO]) async throws {} + + func fetchDebugLogEntries(since date: Date, limit: Int) async throws -> [DebugLogEntryDTO] { + [] + } + + func countDebugLogEntries() async throws -> Int { + 0 + } + + func pruneDebugLogEntries(olderThan cutoff: Date, keepCount: Int) async throws {} + + func clearDebugLogEntries() async throws { + clearDidStart = true + await withCheckedContinuation { continuation in + waiter = continuation + } + } + + func releaseClear() { + waiter?.resume() + waiter = nil + } +} From 8d28a21ebd4f37a9954f9eea18068be6f722b5b6 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:58:52 -0800 Subject: [PATCH 02/66] chore: tighten debug log collection checks - The logger and buffer suites already cover the on path, so those checks added nothing. - German agreement and the Korean disable button now match the existing diagnostics wording. --- .../Localization/de.lproj/Settings.strings | 2 +- .../Localization/ko.lproj/Settings.strings | 4 +- .../Sections/DiagnosticsSection.swift | 14 +- .../MC1Services/Services/AppStorageKey.swift | 4 +- .../MC1Services/Services/DebugLogBuffer.swift | 69 ++------ .../Services/DebugLogBufferTests.swift | 66 ++----- .../DebugLogCollectionGateTests.swift | 164 ++++-------------- .../Services/PersistentLoggerTests.swift | 83 +-------- .../DiagnosticsSectionCollectionTests.swift | 65 ++----- 9 files changed, 88 insertions(+), 383 deletions(-) diff --git a/MC1/Resources/Localization/de.lproj/Settings.strings b/MC1/Resources/Localization/de.lproj/Settings.strings index 55eb8ae077..2a5d75eb2c 100644 --- a/MC1/Resources/Localization/de.lproj/Settings.strings +++ b/MC1/Resources/Localization/de.lproj/Settings.strings @@ -759,7 +759,7 @@ "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 beendet. Exportierte Protokolldateien bleiben unberührt."; +"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"; diff --git a/MC1/Resources/Localization/ko.lproj/Settings.strings b/MC1/Resources/Localization/ko.lproj/Settings.strings index 7ca76e0fc8..4e97d7b498 100644 --- a/MC1/Resources/Localization/ko.lproj/Settings.strings +++ b/MC1/Resources/Localization/ko.lproj/Settings.strings @@ -742,10 +742,10 @@ "diagnostics.footer.disabled" = "로컬 디버그 로그가 수집되지 않습니다."; /* Alert title for disabling collection */ -"diagnostics.alert.disable.title" = "수집 비활성화"; +"diagnostics.alert.disable.title" = "디버그 로그 수집 끄기"; /* Button to confirm disabling collection */ -"diagnostics.alert.disable.confirm" = "수집 비활성화"; +"diagnostics.alert.disable.confirm" = "끄기"; /* Alert message for disabling collection */ "diagnostics.alert.disable.message" = "저장된 모든 디버그 로그가 삭제되고 수집이 중단됩니다. 내보낸 로그 파일에는 영향을 주지 않습니다."; diff --git a/MC1/Views/Settings/Sections/DiagnosticsSection.swift b/MC1/Views/Settings/Sections/DiagnosticsSection.swift index 926734512b..b552306499 100644 --- a/MC1/Views/Settings/Sections/DiagnosticsSection.swift +++ b/MC1/Views/Settings/Sections/DiagnosticsSection.swift @@ -12,9 +12,7 @@ struct DiagnosticsSection: View { @State private var showingClearLogsAlert = false @State private var showingDisableCollectionAlert = false @State private var presentedErrorMessage: String? - /// Same string as `presentedErrorMessage`, kept on this view value so it is - /// still readable after `disableCollection(using:)` suspends. The alert binds - /// the state property, which is written in the same assignment. + /// Same text as `presentedErrorMessage`, kept here so it stays readable after `disableCollection(using:)` suspends. private let errorRecord = ErrorRecord() var errorMessage: String? { @@ -82,10 +80,7 @@ struct DiagnosticsSection: View { .errorAlert($presentedErrorMessage) } - /// Turning off raises the confirm alert and does not write the key. Confirm - /// calls `disableCollection`, which sets the key false until it returns. This - /// view writes the key true only when that call throws. Turning on during the - /// wipe does not write the key. + /// 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 }, @@ -101,10 +96,7 @@ struct DiagnosticsSection: View { } } - /// Confirm action for the disable alert. On success the service already left - /// the key false, so this does not write it. On throw the service left the - /// key false and left the rows; this turns the key back on and sets - /// `errorMessage`. + /// 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 { diff --git a/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift b/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift index 777969dbaf..1db97245a3 100644 --- a/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift +++ b/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift @@ -63,9 +63,7 @@ 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 - /// Intentionally device-local: not registered in BackupUserDefaults so a foreign - /// phone's "on" can't silently turn on log collection after restore. Absent means - /// off (opt-in), matching the fresh-install default. + /// 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 diff --git a/MC1Services/Sources/MC1Services/Services/DebugLogBuffer.swift b/MC1Services/Sources/MC1Services/Services/DebugLogBuffer.swift index 22cef70ebd..ff8ae892e6 100644 --- a/MC1Services/Sources/MC1Services/Services/DebugLogBuffer.swift +++ b/MC1Services/Sources/MC1Services/Services/DebugLogBuffer.swift @@ -4,19 +4,14 @@ 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()) - /// Depth of `disableCollection` calls in progress. The key write that turns - /// collection off and a turn-on both happen under this lock, so a toggle - /// during the wipe cannot land true. + /// 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 } @@ -24,21 +19,12 @@ public actor DebugLogBuffer { private static let collectionDisable = OSAllocatedUnfairLock(initialState: CollectionDisable()) static let maxPendingEntries = 500 - /// Opt-in gate for persisted debug-log collection. Read fresh on every `record` - /// so it works off the main actor and at early launch, before the first - /// connection creates a buffer. A missing key means off (opt-in), matching both - /// fresh installs and upgrades from any prior version. The app target writes it - /// via `@AppStorage`; MC1Services only reads it, so this shares the app's - /// standard `UserDefaults` domain. + /// 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) } - /// 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. + /// 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 { @@ -57,11 +43,8 @@ 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. When collection is off, drops the entry before any queueing, buffer - /// handoff, or `Task` creation. Entries already in `pending` or `buffer` are not - /// discarded by a mere read of the setting; only `disableCollection` discards them. + /// 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 } @@ -76,8 +59,7 @@ public actor DebugLogBuffer { Task { await buffer.append(entry) } } - /// Turns collection on unless `disableCollection` owns it. A turn-on that - /// loses the race with a disable in progress leaves the key false. + /// 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 } @@ -88,12 +70,9 @@ public actor DebugLogBuffer { } } - /// Owns collection from the write that sets the key false until this returns. - /// Waits out a save already inside `saveDebugLogEntries`, drops whatever that - /// save put back in memory, then deletes rows. The save cannot finish after - /// the delete. A throw leaves the key false and the rows that could not be - /// deleted; the caller turns the key back on. The depth returns to zero - /// before this returns, including on throw. + /// 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() } @@ -120,8 +99,7 @@ public actor DebugLogBuffer { } } - /// Empties the pending queue so tests can exercise the no-buffer window from a - /// known state. + /// Empties `pending` so a test starts from the no-buffer window. static func resetPendingStateForTesting() { sharedState.withLock { $0.pending = [] } } @@ -136,20 +114,14 @@ 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 that have passed the collection gate and not yet - /// returned. `disableCollection` waits for this to hit zero before it - /// deletes rows, so a save already inside `saveDebugLogEntries` cannot - /// finish after that delete. + /// `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] = [] @@ -194,9 +166,7 @@ public actor DebugLogBuffer { buffer = [] } - /// Waits out saves already in flight, then drops memory. Called only after - /// the collection key is false, so a flush that starts during the wait - /// does not publish. + /// 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 @@ -295,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/Tests/MC1ServicesTests/Services/DebugLogBufferTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/DebugLogBufferTests.swift index fa6d9dd7fa..6c120f9b52 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/DebugLogBufferTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/DebugLogBufferTests.swift @@ -2,21 +2,15 @@ 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 - /// The on-path tests below exercise the queue/drain/flush behavior that predates - /// the collection gate; that behavior is reachable only when collection is on, so - /// each pins the key true and restores the captured value afterward. + /// 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? { @@ -39,10 +33,7 @@ struct DebugLogBufferTests { 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.. [DebugLogEntryDTO] { - for _ in 0..= minimumCount { - return matches - } - try? await Task.sleep(for: delay) - } - return await store.debugLogEntries.filter { $0.category == category } - } - - /// Key absent (fresh install and upgrade from any prior version): `record` drops - /// the entry, assigning a buffer cannot drain it, and a flush leaves the store - /// empty. @Test func `missing key means off so record drops the entry and the store stays empty`() async { let captured = CapturedKey() defer { captured.restore() } - UserDefaults.standard.removeObject(forKey: Self.key) - #expect(UserDefaults.standard.object(forKey: Self.key) == nil) let store = MockPersistenceStore() let buffer = DebugLogBuffer(dataStore: store) - let category = UUID().uuidString - DebugLogBuffer.shared = nil - DebugLogBuffer.resetPendingStateForTesting() - DebugLogBuffer.record( - DebugLogEntryDTO(level: .info, subsystem: "test", category: category, message: "dropped") - ) - #expect(writeAndReadBack(buffer)) - await buffer.flush() - try? await Task.sleep(for: .milliseconds(50)) - let matches = await store.debugLogEntries.filter { $0.category == category } - #expect(matches.isEmpty) - DebugLogBuffer.shared = nil - } - - /// Key true: an `.info` entry recorded through `PersistentLogger` persists. - @Test - func `collection on persists an info entry`() async { - let captured = CapturedKey() - defer { captured.restore() } - UserDefaults.standard.set(true, forKey: Self.key) - #expect(UserDefaults.standard.bool(forKey: Self.key)) - - let store = MockPersistenceStore() - let buffer = DebugLogBuffer(dataStore: store) - var messages: [String] = [] + var stayedEmpty = false for _ in 0.. AppState { let container = try PersistenceStore.createContainer(inMemory: true) return AppState(modelContainer: container, isPlaceholder: true) } - /// Hosts `DiagnosticsSection` in a `NavigationStack` so section rows and footers - /// lay out and the disable alert can present over the hosting window. No - /// `.defaultAppStorage` is applied, so `@AppStorage` resolves to standard defaults. + /// Hosts `DiagnosticsSection` so rows, footers, and the disable alert lay out. No `.defaultAppStorage`, so `@AppStorage` uses standard defaults. private func host(_ appState: AppState) throws -> (window: UIWindow, controller: UIHostingController) { let root = NavigationStack { FeedbackView() @@ -94,8 +83,7 @@ struct DiagnosticsSectionCollectionTests { return matchesCore(String(stripped), target: target) } - /// Section headers render uppercase without changing their localized text, and rows - /// concatenate label + value, so an exact / prefix match is the contract. + /// Headers render uppercase, and rows concatenate label and value, so the match is exact or a prefix. private func matchesCore(_ text: String, target: String) -> Bool { let text = text.folding(options: .caseInsensitive, locale: .current) let target = target.folding(options: .caseInsensitive, locale: .current) @@ -103,9 +91,7 @@ struct DiagnosticsSectionCollectionTests { return text.hasPrefix(target + ",") || text.hasPrefix(target + "\n") || text.hasPrefix(target + " ") } - /// The labels SwiftUI exposes across the accessibility-element tree — this is how - /// `List` rows and alert actions surface text, since SwiftUI draws `Text` as CoreText - /// layers with no backing `UILabel`. Mirrors `SettingsTabHarness.activateAccessibility`. + /// Labels from the accessibility tree. `List` rows and alert actions have no `UILabel`; this matches `SettingsTabHarness`. private func accessibilityLabels(in view: UIView) -> [String] { var found: [String] = [] func walk(_ object: NSObject) { @@ -126,7 +112,6 @@ struct DiagnosticsSectionCollectionTests { return found } - /// Every accessibility label rendered in any scene window. private func allLabels() -> [String] { sceneWindows().flatMap { accessibilityLabels(in: $0) } } @@ -135,15 +120,12 @@ struct DiagnosticsSectionCollectionTests { allLabels().contains { matchesLabel($0, target: target) } } - /// The `UISwitch` SwiftUI's `Toggle` renders: the switch on the same cell as the - /// toggle's accessibility identifier. + /// The section's only `UISwitch`, which is the collection `Toggle`. private func collectionSwitch(in window: UIWindow) -> UISwitch? { descendants(of: window, UISwitch.self).first } - /// Drives the collection switch to `targetValue` through the live view tree, the - /// same `setOn` + `valueChanged` path the chat pin-switch tests use for a SwiftUI - /// `Toggle`. + /// Drives the collection `UISwitch` with `setOn` and `valueChanged`, the path a SwiftUI `Toggle` observes. private func driveSwitch(to targetValue: Bool, in window: UIWindow) -> Bool { window.layoutIfNeeded() guard let toggle = collectionSwitch(in: window), toggle.isOn != targetValue else { return false } @@ -152,9 +134,7 @@ struct DiagnosticsSectionCollectionTests { return true } - /// Polls a synchronous UI `condition`, yielding with `Task.sleep` so a pending - /// SwiftUI re-render or alert presentation can settle. Between reads, `layoutIfNeeded` - /// on each connected window forces a synchronous layout pass. + /// Polls `condition` until the timeout. `pump` lays out each window so a pending render can settle. private func waitFor(_ condition: @MainActor () -> Bool) async -> Bool { let deadline = ContinuousClock.now + Timing.timeout while ContinuousClock.now < deadline { @@ -166,8 +146,7 @@ struct DiagnosticsSectionCollectionTests { return condition() } - /// Forces a synchronous layout on every scene window so a just-committed state - /// change is reflected in the view tree on the next `condition()` read. + /// Lays out every scene window so the next `condition` read sees the latest state. private func pump() { for window in sceneWindows() { window.layoutIfNeeded() @@ -190,8 +169,6 @@ struct DiagnosticsSectionCollectionTests { // MARK: - Tests - /// Key true: the toggle row is present and reads on; both action buttons appear; - /// the footer is today's on-path string. @Test func `collection on shows toggle, both buttons, and the on footer`() async throws { let captured = captureKey() @@ -218,8 +195,6 @@ struct DiagnosticsSectionCollectionTests { #expect(self.collectionSwitch(in: root)?.isOn == true) } - /// Key false: both action buttons are absent and the disabled footer replaces the - /// on-path footer. @Test func `collection off hides both buttons and shows the disabled footer`() async throws { let captured = captureKey() @@ -246,12 +221,7 @@ struct DiagnosticsSectionCollectionTests { #expect(self.collectionSwitch(in: root)?.isOn == false) } - /// Off-transition through the view: seed a persisted row, flip the switch off (which - /// raises the confirm alert instead of writing), then run the confirm action against - /// the live store. The alert appears; toggling the switch off does not write the key - /// or delete rows. The confirm action is `disableCollection(using:)`, called here - /// because SwiftUI's alert button exposes no in-process driver. The test does not - /// write the key; a successful confirm leaves it false. + /// The switch raises the alert and does not write the key. Confirm calls `disableCollection(using:)` directly; the alert button has no in-process driver. @Test func `toggling off raises the alert and confirm clears rows and sets the key false`() async throws { let captured = captureKey() @@ -278,12 +248,10 @@ struct DiagnosticsSectionCollectionTests { let ready = await waitFor { self.collectionSwitch(in: root)?.isOn == true } #expect(ready) - // Flip the switch off; the setter raises the confirm alert instead of writing. #expect(driveSwitch(to: false, in: root)) let alertReady = await waitFor { self.labelMatches(Self.disableConfirmText) } #expect(alertReady) - // The deferred-write contract: raising the alert writes nothing yet. #expect(UserDefaults.standard.bool(forKey: Self.key)) let section = DiagnosticsSection(exportedFile: .constant(nil), isSidebar: false) @@ -294,9 +262,6 @@ struct DiagnosticsSectionCollectionTests { #expect(remaining == 0) } - /// Confirm against a store whose clear throws. The service leaves the key false - /// and the rows in place; the confirm action turns the key back on and sets - /// `errorMessage`. @Test func `failed confirm restores the key, keeps the rows, and sets errorMessage`() async throws { let captured = captureKey() @@ -322,8 +287,6 @@ struct DiagnosticsSectionCollectionTests { ) } - /// Clear parks, confirm is in flight, and the on-write does not stick. After - /// confirm returns, a later on-write sets the key true. @Test func `on write during confirm does not stick and a later on write enables collection`() async { let captured = captureKey() @@ -358,8 +321,7 @@ struct DiagnosticsSectionCollectionTests { } } -/// Wraps an in-memory `PersistenceStore` and throws from `clearDebugLogEntries`, -/// mirroring the app view's `any DebugLogPersisting` seam used by `disableCollection`. +/// Throws from `clearDebugLogEntries` so `disableCollection(using:)` takes its restore path. private struct ClearFailure: LocalizedError { static let message = "The debug log could not be cleared." var errorDescription: String? { @@ -395,8 +357,7 @@ private actor FailingClearStore: DebugLogPersisting { } } -/// Parks `clearDebugLogEntries` until `releaseClear`, so a test can turn the -/// toggle on while confirm is in flight. +/// Parks `clearDebugLogEntries` until `releaseClear`, so a turn-on can run while confirm is in flight. private actor SuspendingClearStore: DebugLogPersisting { private var waiter: CheckedContinuation? private(set) var clearDidStart = false From affb2c6310554adfa9c0568c67bf93964fade960 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:45:27 -0800 Subject: [PATCH 03/66] chore: update test tooling and small cleanup (#482) Build package tests before starting the CI timeout. Add package Make targets, raw log capture, test selectors, and shared build flags with matching docs. Accept either offline-map destination state in navigation tests and combine the equivalent draft guards. --- .github/workflows/test.yml | 8 +++-- MC1/State/ChatDraftEditor.swift | 3 +- MC1Tests/Views/SettingsDestination.swift | 2 +- Makefile | 39 ++++++++++++++++++------ docs/Testing.md | 20 +++++++----- 5 files changed, 50 insertions(+), 22 deletions(-) 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/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/MC1Tests/Views/SettingsDestination.swift b/MC1Tests/Views/SettingsDestination.swift index 31f6ca106d..46db0e8c68 100644 --- a/MC1Tests/Views/SettingsDestination.swift +++ b/MC1Tests/Views/SettingsDestination.swift @@ -37,7 +37,7 @@ enum SettingsDestination: CaseIterable, Sendable, CustomTestStringConvertible { var markers: [String] { switch self { case .translateInto: [L10n.Settings.Language.matchAppLanguage] - case .offlineMaps: [L10n.Settings.OfflineMaps.emptyTitle] + case .offlineMaps: [L10n.Settings.OfflineMaps.emptyTitle, L10n.Settings.OfflineMaps.storageUsed] case .manageRegions: [L10n.Chats.Chats.ChannelInfo.Region.addManually] } } diff --git a/Makefile b/Makefile index 73f9786767..dd57c6b08e 100644 --- a/Makefile +++ b/Makefile @@ -20,8 +20,17 @@ PROJECT := MC1.xcodeproj # The full app suite runs on the project-standard iOS 27 simulator. Override SIM to retarget. SIM ?= platform=iOS Simulator,name=iPhone 17e,OS=27.0 + +# Additional test options, including result-bundle paths and repetition settings. XCODEBUILD_TEST_ARGS ?= +# Use suite-level selectors for Swift Testing; method-level selectors can run zero tests. +TEST_ARGS ?= +# Optional raw xcodebuild output, normally under repo tmp/; the caller creates its directory. +TEST_LOG ?= +# Shared build settings, e.g. a CI DerivedData path. +XCODEBUILD_TEST_FLAGS ?= + # StoreKit (SKTestSession) suites must run on an iOS 18.x simulator. Under `xcodebuild # test`, iOS 26.x simulators deliver 0 products to storekitd (Apple regression # FB22237318 / FB22774836), so every product-dependent test falsely fails. A method-level @@ -80,11 +89,9 @@ XCSIFT_WITH_HEARTBEAT = { \ } .DEFAULT_GOAL := help -.PHONY: help generate test test-app test-store -# `make test` runs two xcodebuild passes because a single invocation targets one OS: the full -# app suite on iOS 27 and the StoreKit suites on iOS 18.x (where SKTestSession actually serves -# products; iOS 26.x auto-skips those suites). .NOTPARALLEL keeps `make -j` from running -# both passes at once and colliding on the shared build. +.PHONY: help generate test test-packages test-meshcore test-services test-app test-store +# Package suites run on the host. The app and StoreKit passes use separate simulator OSes. +# .NOTPARALLEL keeps `make -j` from colliding on shared builds and simulators. .NOTPARALLEL: help: ## List available targets @@ -105,22 +112,36 @@ dev.yml: generate: dev.yml ## Regenerate MC1.xcodeproj from project.yml (xcodegen) xcodegen generate -test: test-app test-store ## Run everything: full app suite (iOS 27) + StoreKit suites (iOS 18) +test: test-packages test-app test-store ## Run package suites, app tests (iOS 27), and StoreKit tests (iOS 18) + +test-packages: test-meshcore test-services ## Run both Swift package suites on the macOS host + +# SwiftPM's --no-parallel does not serialize Swift Testing suites on this toolchain. +# Width one also isolates suites that use process-wide state, including the persistent logger. +test-meshcore: ## Run MeshCore protocol/session tests on the macOS host + swift test --package-path MeshCore --no-parallel --experimental-maximum-parallelization-width 1 + +test-services: ## Run MC1Services transport/lifecycle tests on the macOS host + swift test --package-path MC1Services --no-parallel --experimental-maximum-parallelization-width 1 # Skip sysdiagnose collection. xcodebuild can spawn simctl diagnose after the # suite and block the recipe for minutes even when every test passed. test-app: generate ## Run the full app suite on iOS 27 @dest='$(SIM)'; $(SIM_LOCK); \ xcodebuild test -project $(PROJECT) -scheme $(SCHEME) \ - -destination "$$dest" \ + -destination "$$dest" $(TEST_ARGS) \ -parallel-testing-enabled NO $(XCODEBUILD_TEST_ARGS) \ + $(XCODEBUILD_TEST_FLAGS) \ -collect-test-diagnostics never \ - 2>&1 | $(XCSIFT_WITH_HEARTBEAT) + 2>&1 | { if [ -n "$(TEST_LOG)" ]; then tee "$(TEST_LOG)"; else cat; fi; } \ + | $(XCSIFT_WITH_HEARTBEAT) test-store: generate ## Run every StoreKit/IAP SKTestSession suite on iOS 18.x @dest='$(STORE_SIM)'; $(SIM_LOCK); \ xcodebuild test -project $(PROJECT) -scheme $(SCHEME) \ -destination "$$dest" $(STORE_SUITES) \ -parallel-testing-enabled NO $(XCODEBUILD_TEST_ARGS) \ + $(XCODEBUILD_TEST_FLAGS) \ -collect-test-diagnostics never \ - 2>&1 | $(XCSIFT_WITH_HEARTBEAT) + 2>&1 | { if [ -n "$(TEST_LOG)" ]; then tee "$(TEST_LOG)"; else cat; fi; } \ + | $(XCSIFT_WITH_HEARTBEAT) diff --git a/docs/Testing.md b/docs/Testing.md index 38a10fcb09..2ca99b003c 100644 --- a/docs/Testing.md +++ b/docs/Testing.md @@ -8,19 +8,21 @@ Use the Test navigator (Cmd+6) or Cmd+U to run all tests. ### Command Line -Prefer the `make` targets; they take a per-simulator lock so concurrent sessions serialize instead of hanging: +Prefer the `make` targets. Simulator passes take a per-simulator lock so concurrent sessions serialize instead of hanging: ```bash -make test-app # full app suite on iPhone 17e / iOS 27.0 -make test-store # StoreKit/IAP SKTestSession suites on iOS 18.x -make test # both of the above +make test-meshcore # protocol/session package suite on the macOS host +make test-services # transport/service package suite on the macOS host +make test-app # full app suite on iPhone 17e / iOS 27.0 +make test-store # StoreKit/IAP SKTestSession suites on iOS 18.x +make test # all four passes above ``` The full app suite can take several minutes. `xcsift` prints its summary when the run ends. The periodic elapsed-time messages do not show whether tests are still making progress. Save the raw log when investigating a slow or stuck run: ```bash mkdir -p tmp -make test-app XCSIFT_WITH_HEARTBEAT='tee tmp/test-app-raw.log | xcsift -f toon' +make test-app TEST_LOG=tmp/test-app-raw.log ``` Check the command's exit status and Xcode's test summary in the raw log. `xcsift` can report zero failures even when a Swift Testing assertion failed. Look in the `.xcresult` bundle for failure details. @@ -31,18 +33,20 @@ Pass filters, repetition settings, or a result-bundle path through `XCODEBUILD_T make test-app XCODEBUILD_TEST_ARGS='-only-testing:MC1Tests/LifecycleTransitionTests -test-iterations 5' ``` +Use suite-level filters for Swift Testing; a method-level selector can run zero tests. `TEST_ARGS` remains available for app-only selectors, and `XCODEBUILD_TEST_FLAGS` supplies build settings to both simulator targets. These arguments are combined with `XCODEBUILD_TEST_ARGS`; `TEST_LOG` captures raw output without replacing the heartbeat. + App tests run one at a time. Parallel testing is disabled in both the generated scheme and the make targets because several suites share the key window and keyboard. `@MainActor` and `.serialized` on a suite still allow other suites to run while a test is suspended. Keep parallel testing disabled for the full app suite. -Run the SPM packages from the repository root, with parallel testing disabled as it is in CI: +Run the SPM packages from the repository root. The make targets disable parallel testing and set Swift Testing width to one: ```bash set -o pipefail # Services package tests -swift test --package-path MC1Services --no-parallel 2>&1 | xcsift -f toon +make test-services 2>&1 | xcsift -f toon # MeshCore package tests -swift test --package-path MeshCore --no-parallel 2>&1 | xcsift -f toon +make test-meshcore 2>&1 | xcsift -f toon ``` Use `xcsift` to get structured output. Add `-c` for code coverage or `-w` for a detailed warnings list. See CLAUDE.md for the full flag reference. From a38e24fa285eb128b21a30aafcbe1aeae7cee578 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Mon, 2 Nov 2026 15:17:06 -0800 Subject: [PATCH 04/66] bump version to 1.6.3 --- project.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/project.yml b/project.yml index f435e12e5b..e78853a17b 100644 --- a/project.yml +++ b/project.yml @@ -75,7 +75,7 @@ targets: base: SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD: YES ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon - MARKETING_VERSION: 1.6.2 + MARKETING_VERSION: 1.6.3 CURRENT_PROJECT_VERSION: 1 VERSIONING_SYSTEM: apple-generic TARGETED_DEVICE_FAMILY: "1,2" @@ -109,7 +109,7 @@ targets: settings: base: INFOPLIST_FILE: MC1Tests/Info.plist - MARKETING_VERSION: 1.6.2 + MARKETING_VERSION: 1.6.3 CURRENT_PROJECT_VERSION: 1 VERSIONING_SYSTEM: apple-generic TEST_HOST: "$(BUILT_PRODUCTS_DIR)/MC1.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/MC1" @@ -123,7 +123,7 @@ targets: - path: Shared settings: base: - MARKETING_VERSION: 1.6.2 + MARKETING_VERSION: 1.6.3 CURRENT_PROJECT_VERSION: 1 VERSIONING_SYSTEM: apple-generic TARGETED_DEVICE_FAMILY: "1,2" From d4b8be9e1f0b1c0fbe762ada8b69630062c949a5 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Wed, 4 Nov 2026 10:20:08 -0800 Subject: [PATCH 05/66] fix: own each bluetooth connection's recovery (#481) * fix: own each bluetooth connection's recovery Bind requests, links, sessions, and recovery tasks to their connection so stale work cannot publish ready, replace a session, or retire a newer link. Scope WiFi observations, identity import, and queued sends to the current connection. Preserve accepted DM acknowledgement deadlines across reconnects without sending the message again. --- .../Errors/Error+UserFacingMessage.swift | 3 + ...essageServiceError+UserFacingMessage.swift | 2 +- .../IdentityImportRecovery+Presentation.swift | 12 + MC1/Extensions/View+LiquidGlass.swift | 3 +- MC1/Intents/AppState+IntentRefresh.swift | 6 +- MC1/Intents/SendMessageIntent+Routing.swift | 2 +- MC1/Resources/Generated/L10n.swift | 34 + .../Localization/de.lproj/Onboarding.strings | 3 + .../Localization/de.lproj/Settings.strings | 39 + .../Localization/en.lproj/Onboarding.strings | 3 + .../Localization/en.lproj/Settings.strings | 39 + .../Localization/es.lproj/Onboarding.strings | 3 + .../Localization/es.lproj/Settings.strings | 39 + .../Localization/fr.lproj/Onboarding.strings | 3 + .../Localization/fr.lproj/Settings.strings | 39 + .../Localization/it.lproj/Onboarding.strings | 3 + .../Localization/it.lproj/Settings.strings | 39 + .../Localization/ko.lproj/Onboarding.strings | 3 + .../Localization/ko.lproj/Settings.strings | 39 + .../Localization/nl.lproj/Onboarding.strings | 3 + .../Localization/nl.lproj/Settings.strings | 39 + .../Localization/pl.lproj/Onboarding.strings | 3 + .../Localization/pl.lproj/Settings.strings | 39 + .../Localization/pt.lproj/Onboarding.strings | 3 + .../Localization/pt.lproj/Settings.strings | 39 + .../Localization/ru.lproj/Onboarding.strings | 3 + .../Localization/ru.lproj/Settings.strings | 39 + .../Localization/uk.lproj/Onboarding.strings | 3 + .../Localization/uk.lproj/Settings.strings | 39 + .../zh-Hans.lproj/Onboarding.strings | 3 + .../zh-Hans.lproj/Settings.strings | 39 + MC1/Services/InlineImageCache.swift | 1 + MC1/State/AppConnectionWiringJob.swift | 62 + MC1/State/AppState+ChatPrefetch.swift | 28 +- MC1/State/AppState+ConnectionSource.swift | 12 + MC1/State/AppState+DeviceActions.swift | 374 +++--- MC1/State/AppState+DeviceSelection.swift | 3 +- MC1/State/AppState+Wiring.swift | 135 ++- MC1/State/AppState.swift | 265 +++-- MC1/State/BatteryMonitor.swift | 49 +- .../ConnectionActivity+Presentation.swift | 27 + MC1/State/ConnectionCallbackContext.swift | 19 + MC1/State/ConnectionUIState.swift | 79 +- MC1/State/LiveActivityManager.swift | 111 +- MC1/State/MessageEventDispatcher.swift | 35 +- MC1/State/RemoteAdminWorkspaces.swift | 13 +- MC1/State/StatusPillState.swift | 10 +- MC1/Views/Chats/ChatConversationView.swift | 2 +- .../Chats/Room/RoomAuthenticationSheet.swift | 9 +- .../ChatViewModel+MessageActions.swift | 17 +- .../Components/BLEStatusIndicatorView.swift | 93 +- .../Components/PairingRecoveryStatus.swift | 12 + MC1/Views/Components/SyncingPillView.swift | 8 +- MC1/Views/Onboarding/DeviceScanView.swift | 79 +- .../Onboarding/WiFiConnectionSheet.swift | 10 +- .../RemoteNodes/NodeAuthPathViewModel.swift | 6 +- .../RemoteNodes/NodeAuthenticationSheet.swift | 80 +- .../Repeaters/RepeaterSettingsView.swift | 36 +- .../Repeaters/RepeaterSettingsViewModel.swift | 1 + .../Repeaters/RepeaterStatusView.swift | 35 +- .../Rooms/RoomConversationView.swift | 64 +- .../RemoteNodes/Rooms/RoomSettingsView.swift | 16 +- .../Rooms/RoomSettingsViewModel.swift | 1 + .../RemoteNodes/Rooms/RoomStatusView.swift | 14 +- MC1/Views/Settings/AdvancedSettingsView.swift | 3 +- .../Settings/ConnectionSettingsView.swift | 12 +- MC1/Views/Settings/ConnectionWiFiPage.swift | 5 +- MC1/Views/Settings/DeviceSelectionSheet.swift | 52 +- .../NodeConfigImportRecoveryList.swift | 55 + .../NodeConfig/NodeConfigImportView.swift | 26 +- .../NodeConfigImportViewModel+FileInput.swift | 110 ++ .../NodeConfigImportViewModel+Recovery.swift | 92 ++ .../NodeConfigImportViewModel.swift | 361 +++--- .../Sections/DangerZoneViewModel.swift | 32 +- .../Sections/RadioWiFiEditSheet.swift | 11 +- .../Settings/Sections/RadioWiFiSection.swift | 14 +- .../Sections/RadioWiFiViewModel+Editor.swift | 131 +++ .../RadioWiFiViewModel+Observation.swift | 147 +++ .../RadioWiFiViewModel+Operations.swift | 152 +++ .../Sections/RadioWiFiViewModel.swift | 804 ++++--------- .../Settings/Sections/WiFiEditSheet.swift | 11 +- MC1/Views/Settings/SettingsDetailView.swift | 5 +- MC1/Views/Settings/SettingsListContent.swift | 21 + MC1/Views/Settings/SettingsSubpage.swift | 14 +- MC1/Views/Settings/SettingsView.swift | 33 +- .../CLI/CLIToolViewModel+LocalCommands.swift | 15 +- MC1/Views/Tools/CLI/CLIToolViewModel.swift | 49 +- .../Tools/TracePath/TracePathViewModel.swift | 39 +- .../BLEReconnectionCoordinator.swift | 428 +++---- .../Connection/ConnectionActivity.swift | 17 + .../Connection/ConnectionAttempt.swift | 17 + .../Connection/ConnectionDeviceIdentity.swift | 27 + .../Connection/ConnectionLink.swift | 45 + .../Connection/ConnectionLossReceipt.swift | 8 + .../Connection/ConnectionManager+BLE.swift | 638 +--------- .../ConnectionManager+BLEHealth.swift | 247 ++++ ...ctionManager+BLEReconnectionDelegate.swift | 388 ------- .../ConnectionManager+BLERecovery.swift | 111 ++ .../ConnectionManager+Connect.swift | 137 +++ .../ConnectionManager+DeviceUpdates.swift | 203 ++++ .../ConnectionManager+Diagnostics.swift | 43 + .../ConnectionManager+Identity.swift | 129 +++ ...ectionManager+IdentityReconciliation.swift | 119 ++ .../ConnectionManager+IdentityRecovery.swift | 119 ++ .../ConnectionManager+IdentityRuntime.swift | 96 ++ .../ConnectionManager+Lifecycle.swift | 683 +---------- ...onnectionManager+NotificationTesting.swift | 10 + .../ConnectionManager+Pairing.swift | 732 ++---------- .../ConnectionManager+PowerOff.swift | 2 +- .../ConnectionManager+Preparation.swift | 267 +++++ .../ConnectionManager+Presentation.swift | 36 + .../ConnectionManager+RadioWiFiState.swift | 38 + .../ConnectionManager+Removal.swift | 166 +++ .../ConnectionManager+Requests.swift | 346 ++++++ ...onnectionManager+ResourcePreparation.swift | 54 + .../ConnectionManager+SyncCompletion.swift | 113 ++ .../ConnectionManager+Teardown.swift | 136 ++- .../Connection/ConnectionManager+WiFi.swift | 526 ++------- .../Connection/ConnectionManager.swift | 1021 ++++------------- .../Connection/ConnectionRemovalContext.swift | 23 + .../Connection/ConnectionRemovalResult.swift | 6 + .../Connection/ConnectionRequest.swift | 79 ++ .../Connection/ConnectionRequestFailure.swift | 10 + .../Connection/ConnectionResource.swift | 66 ++ .../Connection/ConnectionResult.swift | 10 + .../Connection/ConnectionRetirement.swift | 9 + .../Connection/ConnectionSnapshot.swift | 11 + .../Connection/IdentityImportReceipt.swift | 37 + .../Connection/IdentityImportRecovery.swift | 12 + .../IdentityImportRecoveryRequired.swift | 4 + .../Connection/WiFiMeshTransport.swift | 11 + .../Sources/MC1Services/Models/Device.swift | 8 +- .../MC1Services/Models/PendingSend.swift | 36 +- .../Models/PendingSendEnvelope.swift | 12 +- .../Persistence/DevicePersisting.swift | 22 +- .../Persistence/MessagePersisting.swift | 10 +- .../MC1Services/ServiceContainer.swift | 205 ++-- .../Services/AdvertisementService.swift | 81 +- .../Services/BLETransportOpenedSignal.swift | 6 + .../MC1Services/Services/ChannelService.swift | 14 +- .../Services/ChatSendQueueService.swift | 184 ++- .../ConfigIdentityImportFailure.swift | 5 + .../MC1Services/Services/DeviceService.swift | 21 +- .../Services/MessagePollingService.swift | 10 +- .../Services/MessageService+ACK.swift | 50 +- .../Services/MessageService+ACKRecovery.swift | 176 +++ .../MessageService+ChannelScope.swift | 31 +- .../MessageService+InlineSendLifecycle.swift | 22 + .../Services/MessageService+SendChannel.swift | 11 +- .../Services/MessageService+SendDM.swift | 45 +- .../Services/MessageService+SendHelpers.swift | 11 +- .../MC1Services/Services/MessageService.swift | 101 +- .../Services/MessageServiceError.swift | 2 + .../Services/NodeConfigImportPlanner.swift | 4 +- .../Services/NodeConfigService.swift | 248 ++-- .../MC1Services/Services/PendingAck.swift | 5 + .../PersistenceStore+Acknowledgements.swift | 75 ++ .../PersistenceStore+BackupBatchInsert.swift | 9 +- .../PersistenceStore+Connection.swift | 91 ++ .../Services/PersistenceStore+Devices.swift | 194 ++-- .../Services/PersistenceStore+Messages.swift | 14 +- .../PersistenceStore+PendingSends.swift | 51 +- .../Services/PersistenceStore.swift | 13 +- .../MC1Services/Services/RadioCLIReply.swift | 16 +- .../Services/RadioWiFiBinding.swift | 12 + .../Services/RadioWiFiCommandResult.swift | 9 + .../RadioWiFiCredentialBaseline.swift | 41 + .../Services/RadioWiFiEnabledReceipt.swift | 9 + .../Services/RadioWiFiMutationReceipt.swift | 13 + .../Services/RadioWiFiReadResult.swift | 15 + .../Services/RadioWiFiResetObservation.swift | 35 + .../Services/RadioWiFiSnapshot.swift | 19 + .../MC1Services/Services/RadioWiFiState.swift | 149 +++ .../Services/RemoteNodeService+Login.swift | 6 +- .../RemoteNodeService+Reconnection.swift | 32 +- .../Services/RemoteNodeService.swift | 23 +- .../MC1Services/Services/RxLogService.swift | 10 +- .../MC1Services/Services/SendQueue.swift | 20 +- .../MC1Services/Services/SettingsEvent.swift | 1 + .../Services/SettingsService+RadioWiFi.swift | 114 ++ .../SettingsService+RadioWiFiCommands.swift | 50 + .../SettingsService+RadioWiFiMutations.swift | 287 +++++ .../SettingsService+RadioWiFiReboot.swift | 66 ++ .../Services/SettingsService.swift | 143 ++- .../Sync/ConnectionManager+SyncRetry.swift | 153 +-- .../SyncCoordinator+MessageHandlers.swift | 7 +- .../MC1Services/Sync/SyncCoordinator.swift | 14 + .../Transport/BLEIngressDiagnostics.swift | 18 + .../Transport/BLELifecycleEvent.swift | 16 + .../Transport/BLELifecycleOrigin.swift | 14 + .../Transport/BLEOperationClock.swift | 10 + .../BLEStateMachine+CBDelegate.swift | 201 +++- .../BLEStateMachine+CallbackHandlers.swift | 84 +- .../BLEStateMachine+LifecycleOrigin.swift | 36 + .../Transport/BLEStateMachine.swift | 495 +++++--- .../Transport/BLEStateMachineProtocol.swift | 15 +- .../Transport/ReconnectPolicy.swift | 4 +- .../Transport/iOSBLETransport.swift | 173 ++- .../Transport/iOSMeshTransport.swift | 10 +- .../AdvertisementCleanupContractTests.swift | 264 +++++ ...AdvertisementDeltaDrainContractTests.swift | 88 ++ .../AdvertisementServiceTests.swift | 9 +- ...nectionCoordinatorOwnershipPortTests.swift | 57 + .../BLEReconnectionCoordinatorTests.swift | 931 ++++----------- .../BLEReconnectionTimeoutTests.swift | 183 +++ ...grationTests+PendingAcknowledgements.swift | 36 + .../BondLossPairingRecoveryTests.swift | 235 ++-- .../CanonicalIdentityAdmissionTests.swift | 93 ++ .../CanonicalIdentityConsumerTests.swift | 164 +++ .../CanonicalIdentityContractTests.swift | 124 ++ .../CanonicalIdentityDurabilityTests.swift | 181 +++ .../CanonicalIdentityEnqueueDrainTests.swift | 68 ++ .../CanonicalIdentityProvenanceTests.swift | 157 +++ ...nonicalIdentityQueueWorkerDrainTests.swift | 97 ++ ...nonicalIdentityReceiptAmbiguityTests.swift | 57 + .../CanonicalIdentitySettlementTests.swift | 98 ++ .../CanonicalWiFiCertificateTests.swift | 65 ++ .../ConnectRadioIDResolutionTests.swift | 732 ++++++------ .../ConnectionActivityTests.swift | 331 ++++++ ...onnectionDeviceUpdateProvenanceTests.swift | 251 ++++ .../ConnectionLifecycleDiagnosticsTests.swift | 261 +++++ .../ConnectionManagerACKRecoveryTests.swift | 65 ++ .../ConnectionManagerAdmissionPortTests.swift | 102 ++ .../ConnectionManagerAdoptionRaceTests.swift | 128 ++- ...ectionManagerAuthFailureRoutingTests.swift | 89 +- ...ectionManagerAutoReconnectEntryTests.swift | 62 +- ...ConnectionManagerAutonomousPortTests.swift | 107 ++ ...tionManagerAvailabilityRecoveryTests.swift | 138 +++ ...ctionManagerBLEAttemptOwnershipTests.swift | 295 +++++ .../ConnectionManagerBLEHealthTests.swift | 88 +- ...ConnectionManagerCapabilityPortTests.swift | 69 ++ ...ConnectionManagerCircuitBreakerTests.swift | 6 +- ...ionManagerDisconnectDiagnosticsTests.swift | 43 +- ...ctionManagerFullSyncConsumptionTests.swift | 181 +++ ...ConnectionManagerLateCompletionTests.swift | 154 +++ ...ctionManagerLaunchPreflightPortTests.swift | 143 +++ ...onnectionManagerLaunchTransportTests.swift | 195 ++-- .../ConnectionManagerMembershipTests.swift | 155 +++ ...ctionManagerOwnershipRegressionTests.swift | 98 ++ .../ConnectionManagerPairingTests.swift | 6 +- ...onnectionManagerPlatformRemovalTests.swift | 135 +++ .../ConnectionManagerPowerOffTests.swift | 507 +++++--- ...nectionManagerPreparedQueuePortTests.swift | 98 ++ .../ConnectionManagerPromotionTests.swift | 477 +++----- ...ConnectionManagerRadioWiFiDrainTests.swift | 53 + ...nectionManagerRebuildResultPortTests.swift | 150 +++ ...tionManagerReconnectAbandonmentTests.swift | 295 ++--- ...onnectionManagerReconnectWindowTests.swift | 312 +++++ ...nectionManagerRecoveryOwnershipTests.swift | 303 +++++ ...ectionManagerRestorationHandoffTests.swift | 104 ++ .../ConnectionManagerResyncLoopTests.swift | 95 +- .../ConnectionManagerSessionTests.swift | 205 ++-- ...onManagerSiblingEntryRegressionTests.swift | 231 ++++ ...ConnectionManagerSystemAdoptionTests.swift | 83 ++ .../ConnectionManagerTeardownTests.swift | 667 +++++------ ...nnectionManagerWatchdogDeferralTests.swift | 156 +++ ...ManagerWiFiEstablishmentControlTests.swift | 147 +++ ...ionManagerWiFiEstablishmentLossTests.swift | 112 ++ .../ConnectionManagerWiFiGiveUpTests.swift | 78 +- .../ConnectionManagerWiFiHeartbeatTests.swift | 143 ++- ...nectionManagerWiFiLossOwnershipTests.swift | 238 ++++ .../ConnectionNativeTCPPortTests.swift | 103 ++ .../ConnectionRegistrationRekeyTests.swift | 154 +++ .../ConnectionRemovalConfirmationTests.swift | 243 ++++ .../ConnectionRemovalDrainTests.swift | 433 +++++++ .../ConnectionRemovalRecoveryTests.swift | 94 ++ .../ConnectionRemovalTests.swift | 221 ++++ .../ConnectionRequestCancellationTests.swift | 244 ++++ .../ConnectionResourceRetirementTests.swift | 101 ++ .../ConnectionResyncFinalizationTests.swift | 226 ++++ .../MC1ServicesTests/DeviceWriterTests.swift | 120 ++ .../ExplicitIdentityRecoveryTests.swift | 112 ++ .../Helpers/BLEAdoptionOriginTransport.swift | 106 ++ .../Helpers/BLEAdoptionTestHarness.swift | 109 ++ .../Helpers/BLEReconnectionTestHarness.swift | 125 ++ .../Helpers/BLESetupRetirementHarness.swift | 115 ++ .../Helpers/CanonicalIdentityFixture.swift | 32 + .../Helpers/ConnectionLoopbackRadioPeer.swift | 175 +++ ...ConnectionManager+BLERecoveryTesting.swift | 37 + .../Helpers/ConnectionManager+Testing.swift | 15 +- .../ConnectionManagerRadioTestHarness.swift | 73 ++ .../ConnectionRadioHandoffHarness.swift | 127 ++ .../ConnectionTestRadioTransport.swift | 663 +++++++++++ .../ConnectionWiFiEstablishmentHarness.swift | 194 ++++ .../Helpers/HydratedChannelSendHarness.swift | 83 ++ .../Helpers/IdentityRecoveryFixture.swift | 59 + .../Helpers/NativeConnectionPortHarness.swift | 51 + .../Helpers/PlatformRemovalTestHarness.swift | 103 ++ .../Helpers/RadioWiFiFirmware.swift | 78 ++ .../Helpers/RetirementBLEManagerHarness.swift | 140 +++ .../Helpers/TestPolling.swift | 116 +- .../Helpers/WatchdogDeferralFixture.swift | 140 +++ .../IdentityImportPrivateRuntimeTests.swift | 209 ++++ ...dentityImportResponseProvenanceTests.swift | 111 ++ .../IdentityImportRuntimeAdmissionTests.swift | 274 +++++ .../IdentityImportTailOrderingTests.swift | 129 +++ .../IdentityImportTailSettlementTests.swift | 239 ++++ .../IdentityImportTransportFailureTests.swift | 306 +++++ .../IdentityRecoveryAssociationTests.swift | 115 ++ .../IdentityRecoveryOwnershipTests.swift | 198 ++++ .../IdentityRecoveryPreflightTests.swift | 128 +++ ...dentityRecoverySourceValidationTests.swift | 99 ++ .../IdleIdentityRecoveryRemovalTests.swift | 100 ++ ...terruptedIdentityImportRecoveryTests.swift | 268 +++++ .../Mocks/MockAccessorySetupKitService.swift | 7 + .../Mocks/MockBLEStateMachine.swift | 90 +- .../Mocks}/MockConfigurationSession.swift | 82 +- .../Mocks/MockMeshCoreSession.swift | 23 + .../Mocks/MockMeshTransport.swift | 152 ++- .../Mocks/MockPersistenceStore.swift | 161 +-- ...OpportunisticBluetoothStandDownTests.swift | 141 +-- .../PairingStrandedAssociationTests.swift | 205 ++-- .../PairingWhileConnectedTests.swift | 112 +- ...ndingAcknowledgementPersistenceTests.swift | 217 ++++ .../PersistenceStoreTests.swift | 6 +- .../RadioWiFiResetEvidenceTests.swift | 415 +++++++ .../ReconnectRebuildLifecycleTests.swift | 452 ++------ .../RemoteNodeLoginContactRecoveryTests.swift | 66 ++ .../ServiceContainerWiringTests.swift | 37 + ...ChatSendQueueHydrationOccupancyTests.swift | 239 ++++ .../Services/ChatSendQueueServiceTests.swift | 58 +- .../MessageServiceACKRecoveryTests.swift | 348 ++++++ ...MessageServiceSendDMBookkeepingTests.swift | 263 ++++- .../Services/NodeConfigRFOrderingTests.swift | 8 +- .../Services/NodeConfigServiceTests.swift | 59 - .../Services/RadioCLIReplyTests.swift | 8 +- .../RadioWiFiResetObservationTests.swift | 57 + .../Services/RadioWiFiStateTests.swift | 94 ++ ...ingsServiceRadioWiFiCredentialsTests.swift | 154 +++ ...ettingsServiceRadioWiFiFirmwareTests.swift | 55 + ...ttingsServiceRadioWiFiOwnershipTests.swift | 238 ++++ .../SettingsServiceRadioWiFiRebootTests.swift | 176 +++ .../Services/SettingsSnapshotWriteTests.swift | 24 +- .../BLEIngressDiagnosticsTests.swift | 173 +++ ...EPendingEstablishmentRetirementTests.swift | 212 ++++ .../Transport/BLERetirementTests.swift | 166 +++ .../Transport/BLESessionOwnershipTests.swift | 182 +++ ...EStateMachineAutoReconnectRetryTests.swift | 7 +- ...StateMachineBondSuspectRecoveryTests.swift | 23 +- ...LEStateMachineCallbackAdmissionTests.swift | 87 ++ ...tateMachineDisconnectionMappingTests.swift | 18 +- .../BLEStateMachineEmptyGATTHoldTests.swift | 9 +- ...ateMachineFringeEncryptionGraceTests.swift | 7 +- ...MachinePeripheralEventAdmissionTests.swift | 116 ++ .../BLEStateMachineReliabilityTests.swift | 229 ++++ ...teMachineRestorationAndTeardownTests.swift | 5 +- ...tateMachineWriteWithoutResponseTests.swift | 105 +- .../Transport/BLETestOperationClock.swift | 57 + .../Transport/BLETransportHarness.swift | 335 ++++++ .../Transport/BondShieldRefreshTests.swift | 12 +- .../ConnectionManagerBLERetirementTests.swift | 70 ++ .../IdentityImportRetirementTests.swift | 226 ++++ .../NativeBLEOwnershipIntegrationTests.swift | 108 ++ .../RetirementStaleReadinessTests.swift | 163 +++ .../AppConnectionOwnershipTests.swift | 312 +++++ .../AppStateSwitchTransportTests.swift | 97 +- .../CanonicalIdentityCallerTests.swift | 164 +++ ...ChatCoordinatorRegistrySurvivalTests.swift | 45 +- .../CommittedChannelSlotCleanupTests.swift | 187 +++ .../AppState/ConnectionLinkSwitchTests.swift | 789 ++++--------- ...onnectionRecoveryCallerBoundaryTests.swift | 306 +++++ .../ConnectionStatusLifecycleTests.swift | 15 +- ...versationUnreadMutationTests+Fixture.swift | 11 +- .../AppState/MacOSPairingRecoveryTests.swift | 99 +- .../NodesContactInvalidationTests.swift | 12 +- .../PairingRecoveryOwnershipTests.swift | 305 +++++ .../RecipientPublicationWiringTests.swift | 55 +- .../AppState/RemoveFailedPairingTests.swift | 178 +++ .../RetirementContractCallerTests.swift | 210 ++++ .../Helpers/ConnectionLinkSwitchHarness.swift | 172 +++ .../MockAccessorySetupKitService.swift | 6 + MC1Tests/Helpers/MockMeshTransport.swift | 136 ++- .../RetainedAdminPartitionSurface.swift | 123 ++ ...RetainedConversationPartitionHarness.swift | 228 ++++ .../Services/InlineImagePrefetcherTests.swift | 31 +- MC1Tests/Services/LinkPreviewCacheTests.swift | 31 +- .../Services/LogExportLifecycleTests.swift | 250 ++++ .../State/ChatTimelineFreshnessTests.swift | 12 +- .../ConnectionManagerDeleteDeviceTests.swift | 2 +- .../DeviceSelectionConnectionTests.swift | 76 +- .../SystemPairingSetupAppStateTests.swift | 17 +- .../LineOfSightViewModelTests.swift | 31 +- .../NodeConfigImportNormalInputTests.swift | 213 ++++ .../NodeConfigImportRecoveryTests.swift | 293 +++++ ...odeConfigImportTailPresentationTests.swift | 245 ++++ .../NodeConfigImportViewModelTests.swift | 17 +- .../RetainedAdminPartitionTests.swift | 118 ++ ...versationDMPersistenceAdmissionTests.swift | 242 ++++ .../RetainedConversationPartitionTests.swift | 107 ++ ...tainedConversationSourceSiblingTests.swift | 182 +++ ...etadataProvenanceTests+DirectActions.swift | 170 +++ ...ntityMetadataProvenanceTests+Fixture.swift | 93 ++ ...etadataProvenanceTests+ImportWriters.swift | 328 ++++++ ...dataProvenanceTests+LateContinuation.swift | 245 ++++ ...tingsIdentityMetadataProvenanceTests.swift | 202 ++++ .../SettingsRefreshPropagationTests.swift | 170 +-- .../Chats/ChatReconnectPopulateTests.swift | 2 +- .../Chats/ChatViewModelAdmissionTests.swift | 31 +- .../Views/ConnectionControlMenuTests.swift | 195 ++++ ...uthenticationSourcePresentationTests.swift | 185 +++ MC1Tests/Views/NodesContactRefreshTests.swift | 4 +- .../RegionDiscoveryStateTests+Support.swift | 68 +- .../Views/RegionDiscoveryStateTests.swift | 405 ++++--- .../Settings/CLIProvenanceContractTests.swift | 110 ++ .../DangerZoneRemovalOverlapTests.swift | 126 ++ .../Settings/DangerZoneRemovalTests.swift | 235 ++++ .../RadioWiFiContractAdmissionTests.swift | 190 +++ .../RadioWiFiContractBindingTests.swift | 175 +++ .../RadioWiFiContractCredentialTests.swift | 134 +++ .../RadioWiFiContractFramedValueTests.swift | 44 + .../Settings/RadioWiFiContractHarness.swift | 117 ++ ...ioWiFiContractManagerProvenanceTests.swift | 219 ++++ .../RadioWiFiContractObservationTests.swift | 101 ++ .../RadioWiFiContractOwnershipTests.swift | 73 ++ ...iFiContractPresentationTests+Context.swift | 94 ++ ...iContractPresentationTests+Lifecycle.swift | 77 ++ ...iFiContractPresentationTests+Partial.swift | 79 ++ .../RadioWiFiContractPresentationTests.swift | 149 +++ ...dioWiFiContractRepresentabilityTests.swift | 100 ++ .../Settings/RadioWiFiContractTransport.swift | 155 +++ .../RadioWiFiContractUnicodeTests.swift | 78 ++ ...RadioWiFiContractUnknownEnabledTests.swift | 56 + .../Settings/RadioWiFiObservationTests.swift | 61 + .../Settings/RadioWiFiViewModelTests.swift | 593 +++++++++- .../Views/SettingsTabNavigationTestHost.swift | 6 +- .../CLIToolViewModelLocalCommandsTests.swift | 125 +- .../Tools/CLI/CLIToolViewModelTests.swift | 31 +- .../MeshCore/Events/MeshTransportError.swift | 2 + .../Protocols/ConfigurationSessionOps.swift | 3 + .../Protocols/MessagingSessionOps.swift | 9 + .../IdentityImportReconnectionError.swift | 5 + .../MeshCoreSession+ChannelSending.swift | 88 +- .../Session/MeshCoreSession+Channels.swift | 58 +- .../MeshCoreSession+DeviceConfig.swift | 18 +- .../MeshCoreSession+EventWaiting.swift | 3 +- ...MeshCoreSession+IdentityReconnection.swift | 57 + .../Session/MeshCoreSession+Messaging.swift | 17 - .../Session/MeshCoreSession+RadioCLI.swift | 62 + .../MeshCoreSession+TransportWrites.swift | 23 +- .../MeshCore/Session/MeshCoreSession.swift | 99 +- .../MeshCore/Session/PowerOffExchange.swift | 19 +- .../Session/RadioCLICorrelationScope.swift | 73 ++ .../MeshCore/Session/RequestContext.swift | 30 + .../MeshCore/Transport/MeshTransport.swift | 29 + .../Transport/SessionBoundTransport.swift | 57 + .../Transport/SessionTransportBinding.swift | 72 ++ .../MeshCore/Transport/WiFiTransport.swift | 76 +- .../Tests/MeshCoreTestSupport/TestClock.swift | 25 + .../Session/CLIProvenanceScopeTests.swift | 286 +++++ .../Session/CLIProvenanceSessionTests.swift | 179 +++ ...shCoreSessionLifecycleOwnershipTests.swift | 147 +++ ...erifiedChannelSendSerializationTests.swift | 149 +++ .../SessionTransportBindingTests.swift | 119 ++ docs/Testing.md | 2 + project.yml | 4 + 455 files changed, 40479 insertions(+), 11728 deletions(-) create mode 100644 MC1/Extensions/IdentityImportRecovery+Presentation.swift create mode 100644 MC1/State/AppConnectionWiringJob.swift create mode 100644 MC1/State/AppState+ConnectionSource.swift create mode 100644 MC1/State/ConnectionActivity+Presentation.swift create mode 100644 MC1/State/ConnectionCallbackContext.swift create mode 100644 MC1/Views/Components/PairingRecoveryStatus.swift create mode 100644 MC1/Views/Settings/NodeConfig/NodeConfigImportRecoveryList.swift create mode 100644 MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+FileInput.swift create mode 100644 MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+Recovery.swift create mode 100644 MC1/Views/Settings/Sections/RadioWiFiViewModel+Editor.swift create mode 100644 MC1/Views/Settings/Sections/RadioWiFiViewModel+Observation.swift create mode 100644 MC1/Views/Settings/Sections/RadioWiFiViewModel+Operations.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionActivity.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionAttempt.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionDeviceIdentity.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionLink.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionLossReceipt.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+BLEHealth.swift delete mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+BLEReconnectionDelegate.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+BLERecovery.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+Connect.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+DeviceUpdates.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+Diagnostics.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+Identity.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+IdentityReconciliation.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+IdentityRecovery.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+IdentityRuntime.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+NotificationTesting.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+Preparation.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+Presentation.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+RadioWiFiState.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+Removal.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+Requests.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+ResourcePreparation.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+SyncCompletion.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionRemovalContext.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionRemovalResult.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionRequest.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionRequestFailure.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionResource.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionResult.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionRetirement.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionSnapshot.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/IdentityImportReceipt.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/IdentityImportRecovery.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/IdentityImportRecoveryRequired.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/WiFiMeshTransport.swift create mode 100644 MC1Services/Sources/MC1Services/Services/ConfigIdentityImportFailure.swift create mode 100644 MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift create mode 100644 MC1Services/Sources/MC1Services/Services/MessageService+InlineSendLifecycle.swift create mode 100644 MC1Services/Sources/MC1Services/Services/PersistenceStore+Acknowledgements.swift create mode 100644 MC1Services/Sources/MC1Services/Services/PersistenceStore+Connection.swift create mode 100644 MC1Services/Sources/MC1Services/Services/RadioWiFiBinding.swift create mode 100644 MC1Services/Sources/MC1Services/Services/RadioWiFiCommandResult.swift create mode 100644 MC1Services/Sources/MC1Services/Services/RadioWiFiCredentialBaseline.swift create mode 100644 MC1Services/Sources/MC1Services/Services/RadioWiFiEnabledReceipt.swift create mode 100644 MC1Services/Sources/MC1Services/Services/RadioWiFiMutationReceipt.swift create mode 100644 MC1Services/Sources/MC1Services/Services/RadioWiFiReadResult.swift create mode 100644 MC1Services/Sources/MC1Services/Services/RadioWiFiResetObservation.swift create mode 100644 MC1Services/Sources/MC1Services/Services/RadioWiFiSnapshot.swift create mode 100644 MC1Services/Sources/MC1Services/Services/RadioWiFiState.swift create mode 100644 MC1Services/Sources/MC1Services/Services/SettingsService+RadioWiFi.swift create mode 100644 MC1Services/Sources/MC1Services/Services/SettingsService+RadioWiFiCommands.swift create mode 100644 MC1Services/Sources/MC1Services/Services/SettingsService+RadioWiFiMutations.swift create mode 100644 MC1Services/Sources/MC1Services/Services/SettingsService+RadioWiFiReboot.swift create mode 100644 MC1Services/Sources/MC1Services/Transport/BLEIngressDiagnostics.swift create mode 100644 MC1Services/Sources/MC1Services/Transport/BLELifecycleEvent.swift create mode 100644 MC1Services/Sources/MC1Services/Transport/BLELifecycleOrigin.swift create mode 100644 MC1Services/Sources/MC1Services/Transport/BLEOperationClock.swift create mode 100644 MC1Services/Sources/MC1Services/Transport/BLEStateMachine+LifecycleOrigin.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/AdvertisementCleanupContractTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/AdvertisementDeltaDrainContractTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/BLEReconnectionCoordinatorOwnershipPortTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/BLEReconnectionTimeoutTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests+PendingAcknowledgements.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/CanonicalIdentityAdmissionTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/CanonicalIdentityConsumerTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/CanonicalIdentityContractTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/CanonicalIdentityDurabilityTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/CanonicalIdentityEnqueueDrainTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/CanonicalIdentityProvenanceTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/CanonicalIdentityQueueWorkerDrainTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/CanonicalIdentityReceiptAmbiguityTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/CanonicalIdentitySettlementTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/CanonicalWiFiCertificateTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionActivityTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionDeviceUpdateProvenanceTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionLifecycleDiagnosticsTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerACKRecoveryTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerAdmissionPortTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerAutonomousPortTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerAvailabilityRecoveryTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerBLEAttemptOwnershipTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerCapabilityPortTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerFullSyncConsumptionTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerLateCompletionTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerLaunchPreflightPortTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerMembershipTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerOwnershipRegressionTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerPlatformRemovalTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerPreparedQueuePortTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerRadioWiFiDrainTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerRebuildResultPortTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerReconnectWindowTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerRecoveryOwnershipTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerRestorationHandoffTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerSiblingEntryRegressionTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerSystemAdoptionTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerWatchdogDeferralTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiEstablishmentControlTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiEstablishmentLossTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionManagerWiFiLossOwnershipTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionNativeTCPPortTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionRegistrationRekeyTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionRemovalConfirmationTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionRemovalDrainTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionRemovalRecoveryTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionRemovalTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionRequestCancellationTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionResourceRetirementTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ConnectionResyncFinalizationTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/DeviceWriterTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/ExplicitIdentityRecoveryTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/BLEAdoptionOriginTransport.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/BLEAdoptionTestHarness.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/BLEReconnectionTestHarness.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/BLESetupRetirementHarness.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/CanonicalIdentityFixture.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionLoopbackRadioPeer.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManager+BLERecoveryTesting.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManagerRadioTestHarness.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionRadioHandoffHarness.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionTestRadioTransport.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionWiFiEstablishmentHarness.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/HydratedChannelSendHarness.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/IdentityRecoveryFixture.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/NativeConnectionPortHarness.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/PlatformRemovalTestHarness.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/RadioWiFiFirmware.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/RetirementBLEManagerHarness.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/WatchdogDeferralFixture.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/IdentityImportPrivateRuntimeTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/IdentityImportResponseProvenanceTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/IdentityImportRuntimeAdmissionTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/IdentityImportTailOrderingTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/IdentityImportTailSettlementTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/IdentityImportTransportFailureTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/IdentityRecoveryAssociationTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/IdentityRecoveryOwnershipTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/IdentityRecoveryPreflightTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/IdentityRecoverySourceValidationTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/IdleIdentityRecoveryRemovalTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/InterruptedIdentityImportRecoveryTests.swift rename {MC1Tests/Views/Tools/CLI => MC1Services/Tests/MC1ServicesTests/Mocks}/MockConfigurationSession.swift (87%) create mode 100644 MC1Services/Tests/MC1ServicesTests/PendingAcknowledgementPersistenceTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/RadioWiFiResetEvidenceTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/RemoteNodeLoginContactRecoveryTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueHydrationOccupancyTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKRecoveryTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/RadioWiFiResetObservationTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/RadioWiFiStateTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/SettingsServiceRadioWiFiCredentialsTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/SettingsServiceRadioWiFiFirmwareTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/SettingsServiceRadioWiFiOwnershipTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/SettingsServiceRadioWiFiRebootTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Transport/BLEIngressDiagnosticsTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Transport/BLEPendingEstablishmentRetirementTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Transport/BLERetirementTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Transport/BLESessionOwnershipTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineCallbackAdmissionTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachinePeripheralEventAdmissionTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Transport/BLEStateMachineReliabilityTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Transport/BLETestOperationClock.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Transport/BLETransportHarness.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Transport/ConnectionManagerBLERetirementTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Transport/IdentityImportRetirementTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Transport/NativeBLEOwnershipIntegrationTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Transport/RetirementStaleReadinessTests.swift create mode 100644 MC1Tests/AppState/AppConnectionOwnershipTests.swift create mode 100644 MC1Tests/AppState/CanonicalIdentityCallerTests.swift create mode 100644 MC1Tests/AppState/CommittedChannelSlotCleanupTests.swift create mode 100644 MC1Tests/AppState/ConnectionRecoveryCallerBoundaryTests.swift create mode 100644 MC1Tests/AppState/PairingRecoveryOwnershipTests.swift create mode 100644 MC1Tests/AppState/RemoveFailedPairingTests.swift create mode 100644 MC1Tests/AppState/RetirementContractCallerTests.swift create mode 100644 MC1Tests/Helpers/ConnectionLinkSwitchHarness.swift create mode 100644 MC1Tests/Helpers/RetainedAdminPartitionSurface.swift create mode 100644 MC1Tests/Helpers/RetainedConversationPartitionHarness.swift create mode 100644 MC1Tests/Services/LogExportLifecycleTests.swift create mode 100644 MC1Tests/ViewModels/NodeConfigImportNormalInputTests.swift create mode 100644 MC1Tests/ViewModels/NodeConfigImportRecoveryTests.swift create mode 100644 MC1Tests/ViewModels/NodeConfigImportTailPresentationTests.swift create mode 100644 MC1Tests/ViewModels/RetainedAdminPartitionTests.swift create mode 100644 MC1Tests/ViewModels/RetainedConversationDMPersistenceAdmissionTests.swift create mode 100644 MC1Tests/ViewModels/RetainedConversationPartitionTests.swift create mode 100644 MC1Tests/ViewModels/RetainedConversationSourceSiblingTests.swift create mode 100644 MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests+DirectActions.swift create mode 100644 MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests+Fixture.swift create mode 100644 MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests+ImportWriters.swift create mode 100644 MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests+LateContinuation.swift create mode 100644 MC1Tests/ViewModels/SettingsIdentityMetadataProvenanceTests.swift create mode 100644 MC1Tests/Views/ConnectionControlMenuTests.swift create mode 100644 MC1Tests/Views/NodeAuthenticationSourcePresentationTests.swift create mode 100644 MC1Tests/Views/Settings/CLIProvenanceContractTests.swift create mode 100644 MC1Tests/Views/Settings/DangerZoneRemovalOverlapTests.swift create mode 100644 MC1Tests/Views/Settings/DangerZoneRemovalTests.swift create mode 100644 MC1Tests/Views/Settings/RadioWiFiContractAdmissionTests.swift create mode 100644 MC1Tests/Views/Settings/RadioWiFiContractBindingTests.swift create mode 100644 MC1Tests/Views/Settings/RadioWiFiContractCredentialTests.swift create mode 100644 MC1Tests/Views/Settings/RadioWiFiContractFramedValueTests.swift create mode 100644 MC1Tests/Views/Settings/RadioWiFiContractHarness.swift create mode 100644 MC1Tests/Views/Settings/RadioWiFiContractManagerProvenanceTests.swift create mode 100644 MC1Tests/Views/Settings/RadioWiFiContractObservationTests.swift create mode 100644 MC1Tests/Views/Settings/RadioWiFiContractOwnershipTests.swift create mode 100644 MC1Tests/Views/Settings/RadioWiFiContractPresentationTests+Context.swift create mode 100644 MC1Tests/Views/Settings/RadioWiFiContractPresentationTests+Lifecycle.swift create mode 100644 MC1Tests/Views/Settings/RadioWiFiContractPresentationTests+Partial.swift create mode 100644 MC1Tests/Views/Settings/RadioWiFiContractPresentationTests.swift create mode 100644 MC1Tests/Views/Settings/RadioWiFiContractRepresentabilityTests.swift create mode 100644 MC1Tests/Views/Settings/RadioWiFiContractTransport.swift create mode 100644 MC1Tests/Views/Settings/RadioWiFiContractUnicodeTests.swift create mode 100644 MC1Tests/Views/Settings/RadioWiFiContractUnknownEnabledTests.swift create mode 100644 MC1Tests/Views/Settings/RadioWiFiObservationTests.swift create mode 100644 MeshCore/Sources/MeshCore/Session/IdentityImportReconnectionError.swift create mode 100644 MeshCore/Sources/MeshCore/Session/MeshCoreSession+IdentityReconnection.swift create mode 100644 MeshCore/Sources/MeshCore/Session/MeshCoreSession+RadioCLI.swift create mode 100644 MeshCore/Sources/MeshCore/Session/RadioCLICorrelationScope.swift create mode 100644 MeshCore/Sources/MeshCore/Transport/SessionBoundTransport.swift create mode 100644 MeshCore/Sources/MeshCore/Transport/SessionTransportBinding.swift create mode 100644 MeshCore/Tests/MeshCoreTests/Session/CLIProvenanceScopeTests.swift create mode 100644 MeshCore/Tests/MeshCoreTests/Session/CLIProvenanceSessionTests.swift create mode 100644 MeshCore/Tests/MeshCoreTests/Session/MeshCoreSessionLifecycleOwnershipTests.swift create mode 100644 MeshCore/Tests/MeshCoreTests/Session/VerifiedChannelSendSerializationTests.swift create mode 100644 MeshCore/Tests/MeshCoreTests/Transport/SessionTransportBindingTests.swift 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/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..8db56df124 100644 --- a/MC1/Extensions/View+LiquidGlass.swift +++ b/MC1/Extensions/View+LiquidGlass.swift @@ -100,8 +100,7 @@ struct ToolbarMenu: View { Menu { content } label: { - Rectangle() - .fill(.clear) + label .contentShape(Rectangle()) } .colorMultiply(.clear) 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/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index 376ab482ca..5d4aa568d6 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -3098,6 +3098,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 @@ -4426,6 +4428,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 +4444,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 +4469,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 { @@ -4610,6 +4624,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 +4648,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 +4664,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 +4686,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) @@ -4960,6 +4990,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 @@ -5607,6 +5639,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 diff --git a/MC1/Resources/Localization/de.lproj/Onboarding.strings b/MC1/Resources/Localization/de.lproj/Onboarding.strings index ce77c47b92..d39c53dcf6 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"; diff --git a/MC1/Resources/Localization/de.lproj/Settings.strings b/MC1/Resources/Localization/de.lproj/Settings.strings index 2a5d75eb2c..04ea9f6867 100644 --- a/MC1/Resources/Localization/de.lproj/Settings.strings +++ b/MC1/Resources/Localization/de.lproj/Settings.strings @@ -180,6 +180,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"; @@ -998,6 +1001,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"; @@ -1177,12 +1183,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"; @@ -1195,6 +1213,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"; @@ -1333,6 +1354,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"; diff --git a/MC1/Resources/Localization/en.lproj/Onboarding.strings b/MC1/Resources/Localization/en.lproj/Onboarding.strings index d8384eb031..80cefe4e18 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"; diff --git a/MC1/Resources/Localization/en.lproj/Settings.strings b/MC1/Resources/Localization/en.lproj/Settings.strings index bbeefe8db6..f9f8c374ed 100644 --- a/MC1/Resources/Localization/en.lproj/Settings.strings +++ b/MC1/Resources/Localization/en.lproj/Settings.strings @@ -165,6 +165,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"; @@ -1038,6 +1041,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"; @@ -1217,12 +1223,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"; @@ -1235,6 +1253,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"; @@ -1338,6 +1359,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"; diff --git a/MC1/Resources/Localization/es.lproj/Onboarding.strings b/MC1/Resources/Localization/es.lproj/Onboarding.strings index b7bcc864f1..4b23039bbe 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"; diff --git a/MC1/Resources/Localization/es.lproj/Settings.strings b/MC1/Resources/Localization/es.lproj/Settings.strings index 57647f90a6..b6f1c13737 100644 --- a/MC1/Resources/Localization/es.lproj/Settings.strings +++ b/MC1/Resources/Localization/es.lproj/Settings.strings @@ -165,6 +165,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"; @@ -998,6 +1001,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"; @@ -1177,12 +1183,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"; @@ -1195,6 +1213,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"; @@ -1333,6 +1354,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"; diff --git a/MC1/Resources/Localization/fr.lproj/Onboarding.strings b/MC1/Resources/Localization/fr.lproj/Onboarding.strings index 6b23125a0c..2d23f62b97 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é"; diff --git a/MC1/Resources/Localization/fr.lproj/Settings.strings b/MC1/Resources/Localization/fr.lproj/Settings.strings index 6af9737e8f..0d1aaa038e 100644 --- a/MC1/Resources/Localization/fr.lproj/Settings.strings +++ b/MC1/Resources/Localization/fr.lproj/Settings.strings @@ -165,6 +165,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"; @@ -998,6 +1001,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"; @@ -1177,12 +1183,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é"; @@ -1195,6 +1213,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"; @@ -1333,6 +1354,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"; diff --git a/MC1/Resources/Localization/it.lproj/Onboarding.strings b/MC1/Resources/Localization/it.lproj/Onboarding.strings index 8716e23aa0..2f1332c6cc 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"; diff --git a/MC1/Resources/Localization/it.lproj/Settings.strings b/MC1/Resources/Localization/it.lproj/Settings.strings index 6ca2381d60..a8b00bf610 100644 --- a/MC1/Resources/Localization/it.lproj/Settings.strings +++ b/MC1/Resources/Localization/it.lproj/Settings.strings @@ -165,6 +165,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"; @@ -1048,6 +1051,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"; @@ -1227,12 +1233,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"; @@ -1245,6 +1263,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"; @@ -1348,6 +1369,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"; diff --git a/MC1/Resources/Localization/ko.lproj/Onboarding.strings b/MC1/Resources/Localization/ko.lproj/Onboarding.strings index 10cbf6f03f..272740c80b 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" = "기기가 이미 페어링되어 있습니다"; diff --git a/MC1/Resources/Localization/ko.lproj/Settings.strings b/MC1/Resources/Localization/ko.lproj/Settings.strings index 4e97d7b498..9a3d729af8 100644 --- a/MC1/Resources/Localization/ko.lproj/Settings.strings +++ b/MC1/Resources/Localization/ko.lproj/Settings.strings @@ -165,6 +165,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" = "설정"; @@ -1038,6 +1041,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 설정 지우기"; @@ -1217,12 +1223,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" = "연결됨"; @@ -1235,6 +1253,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" = "기기를 연결하려면 이중 탭하십시오"; @@ -1338,6 +1359,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" = "구성을 가져왔습니다"; diff --git a/MC1/Resources/Localization/nl.lproj/Onboarding.strings b/MC1/Resources/Localization/nl.lproj/Onboarding.strings index 7b1b6914aa..0929c7ce65 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"; diff --git a/MC1/Resources/Localization/nl.lproj/Settings.strings b/MC1/Resources/Localization/nl.lproj/Settings.strings index 7cc9c67fa1..0138e7d0cc 100644 --- a/MC1/Resources/Localization/nl.lproj/Settings.strings +++ b/MC1/Resources/Localization/nl.lproj/Settings.strings @@ -165,6 +165,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"; @@ -998,6 +1001,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"; @@ -1177,12 +1183,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"; @@ -1195,6 +1213,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"; @@ -1333,6 +1354,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"; diff --git a/MC1/Resources/Localization/pl.lproj/Onboarding.strings b/MC1/Resources/Localization/pl.lproj/Onboarding.strings index cf24de7a0d..e736a28918 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"; diff --git a/MC1/Resources/Localization/pl.lproj/Settings.strings b/MC1/Resources/Localization/pl.lproj/Settings.strings index 50e34031c9..0d4b9b616f 100644 --- a/MC1/Resources/Localization/pl.lproj/Settings.strings +++ b/MC1/Resources/Localization/pl.lproj/Settings.strings @@ -165,6 +165,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"; @@ -998,6 +1001,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"; @@ -1177,12 +1183,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"; @@ -1195,6 +1213,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"; @@ -1333,6 +1354,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"; diff --git a/MC1/Resources/Localization/pt.lproj/Onboarding.strings b/MC1/Resources/Localization/pt.lproj/Onboarding.strings index dc2239b295..262bd566ff 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"; diff --git a/MC1/Resources/Localization/pt.lproj/Settings.strings b/MC1/Resources/Localization/pt.lproj/Settings.strings index b4709070f8..bd9091ee4e 100644 --- a/MC1/Resources/Localization/pt.lproj/Settings.strings +++ b/MC1/Resources/Localization/pt.lproj/Settings.strings @@ -165,6 +165,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"; @@ -1048,6 +1051,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"; @@ -1227,12 +1233,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"; @@ -1245,6 +1263,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"; @@ -1348,6 +1369,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"; diff --git a/MC1/Resources/Localization/ru.lproj/Onboarding.strings b/MC1/Resources/Localization/ru.lproj/Onboarding.strings index e279579676..d117bd6801 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" = "Ваше устройство уже сопряжено"; diff --git a/MC1/Resources/Localization/ru.lproj/Settings.strings b/MC1/Resources/Localization/ru.lproj/Settings.strings index 8999e4f348..a766d7b3f1 100644 --- a/MC1/Resources/Localization/ru.lproj/Settings.strings +++ b/MC1/Resources/Localization/ru.lproj/Settings.strings @@ -165,6 +165,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" = "Настроить"; @@ -998,6 +1001,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"; @@ -1177,12 +1183,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" = "Подключено"; @@ -1195,6 +1213,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" = "Дважды коснитесь для подключения устройства"; @@ -1333,6 +1354,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" = "Конфигурация успешно импортирована"; diff --git a/MC1/Resources/Localization/uk.lproj/Onboarding.strings b/MC1/Resources/Localization/uk.lproj/Onboarding.strings index 34ef6f5207..2ac1bd442b 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" = "Ваш пристрій вже сполучено"; diff --git a/MC1/Resources/Localization/uk.lproj/Settings.strings b/MC1/Resources/Localization/uk.lproj/Settings.strings index fad917c184..3ac2334f85 100644 --- a/MC1/Resources/Localization/uk.lproj/Settings.strings +++ b/MC1/Resources/Localization/uk.lproj/Settings.strings @@ -165,6 +165,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" = "Налаштувати"; @@ -998,6 +1001,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"; @@ -1177,12 +1183,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" = "Підключено"; @@ -1195,6 +1213,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" = "Подвійний дотик для підключення пристрою"; @@ -1333,6 +1354,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" = "Конфігурацію успішно імпортовано"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Onboarding.strings b/MC1/Resources/Localization/zh-Hans.lproj/Onboarding.strings index 24fbc40527..029c7c8cc9 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" = "您的设备已配对"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings index 06f5466913..203579954b 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings @@ -165,6 +165,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" = "设置"; @@ -1033,6 +1036,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 设置"; @@ -1212,12 +1218,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" = "已连接"; @@ -1230,6 +1248,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" = "双击以连接设备"; @@ -1333,6 +1354,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" = "配置导入成功"; 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/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..431c3be2cc 100644 --- a/MC1/State/AppState+ChatPrefetch.swift +++ b/MC1/State/AppState+ChatPrefetch.swift @@ -17,23 +17,23 @@ 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 } + session: { self.connectionSnapshot(for: radioID)?.services.session }, + 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 } ) } 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..dc092e0998 100644 --- a/MC1/State/AppState+DeviceActions.swift +++ b/MC1/State/AppState+DeviceActions.swift @@ -11,24 +11,16 @@ extension AppState { /// Start device scan/pairing func startDeviceScan() { - // Hide disconnected pill when starting new connection + guard !isRecoveringPairing else { return } + let (operation, previous) = beginFreshPairingOperation(source: .explicitSwitch) 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 { + freshPairingTask = Task { + defer { finishFreshPairingWork(operation.actionID) } + await withPairingFlowErrorHandling(actionID: operation.actionID) { let pending = try await connectionManager.systemAccessoriesMissingDeviceRecord() + guard ownsFreshPairingOperation(operation.actionID), + operation.requestID == connectionManager.connectionRequestID else { return } if !pending.isEmpty { if connectionUI.pendingSystemPairingSetup == nil { connectionUI.pendingSystemPairingSetup = SystemPairingSetupPrompt( @@ -37,7 +29,8 @@ extension AppState { } return } - try await completeFreshPairing() + await previous?.value + try await completeFreshPairing(actionID: operation.actionID) } } } @@ -45,14 +38,11 @@ extension AppState { func cancelSystemPairingSetup() { connectionUI.pendingSystemPairingSetup = nil connectionUI.queuedSystemPairingSetup = nil - connectionUI.shouldCompleteFreshPairingOnForeground = false - isFreshPairingForegroundRetry = false - connectionManager.isPairingFlowActive = false + cancelFreshPairingOperation() } func handleSystemPairingSetupSheetDismissed() { - guard !isConfirmingSystemPairingSetup else { return } - guard connectionUI.pendingSystemPairingSetup == nil else { return } + guard !isConfirmingSystemPairingSetup, connectionUI.pendingSystemPairingSetup == nil else { return } cancelSystemPairingSetup() } @@ -60,112 +50,196 @@ extension AppState { /// 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 + let (operation, previous) = beginFreshPairingOperation(source: .systemPairingSetup) connectionUI.pendingSystemPairingSetup = nil - connectionUI.isBusy = true - Task { - defer { - connectionUI.isBusy = false - isConfirmingSystemPairingSetup = false - if !connectionUI.shouldCompleteFreshPairingOnForeground { - connectionManager.isPairingFlowActive = false - } - } - await withPairingFlowErrorHandling { + freshPairingTask = Task { + defer { finishFreshPairingWork(operation.actionID) } + await withPairingFlowErrorHandling(actionID: operation.actionID) { try await connectionManager.removeSystemAccessoriesMissingDeviceRecord(prompt.accessories.map(\.id)) - try await completeFreshPairing() + await previous?.value + try await completeFreshPairing(actionID: operation.actionID) } } } - private func completeFreshPairing() async throws { - if connectionState != .disconnected { - await disconnect(reason: .switchingDevice) + 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 + connectionUI.shouldCompleteFreshPairingOnForeground = false + isFreshPairingForegroundRetry = false + isConfirmingSystemPairingSetup = source == .systemPairingSetup + connectionManager.isPairingFlowActive = true + return (operation, previous) + } + + private func ownsFreshPairingOperation(_ actionID: UUID) -> Bool { + freshPairingOperation?.actionID == actionID && connectionUI.isCurrentConnectionAction(actionID) + } + + private func finishFreshPairingWork(_ actionID: UUID) { + guard freshPairingOperation?.actionID == actionID else { return } + isConfirmingSystemPairingSetup = false + if isFreshPairingForegroundRetry { return } + if ownsFreshPairingOperation(actionID), + connectionUI.shouldCompleteFreshPairingOnForeground || connectionUI.pendingSystemPairingSetup != nil { + connectionUI.isBusy = false + return + } + finishFreshPairingOperation(actionID) + } + + private func finishFreshPairingOperation(_ actionID: UUID) { + guard freshPairingOperation?.actionID == actionID else { return } + freshPairingOperation = nil + freshPairingForegroundRetryTask?.cancel() + freshPairingForegroundRetryTask = nil + connectionUI.shouldCompleteFreshPairingOnForeground = false + isFreshPairingForegroundRetry = false + isConfirmingSystemPairingSetup = false + connectionManager.isPairingFlowActive = false + connectionUI.finishConnectionAction(actionID) + } + + func cancelFreshPairingOperation() { + freshPairingTask?.cancel() + freshPairingForegroundRetryTask?.cancel() + if let operation = freshPairingOperation { + finishFreshPairingOperation(operation.actionID) + } else { + connectionUI.shouldCompleteFreshPairingOnForeground = false + isFreshPairingForegroundRetry = false + connectionManager.isPairingFlowActive = false } - try await connectionManager.pairNewDevice() - await wireServicesIfConnected() + } + + 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(_ work: () async throws -> Void) async { + private func withPairingFlowErrorHandling(actionID: UUID, _ 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) + 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 isFreshPairingForegroundRetry { + 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) + } } } - /// 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 + 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 } - scheduleFreshPairingOnForeground() + return error } - private func scheduleFreshPairingOnForeground() { + private func scheduleFreshPairingOnForeground(actionID: UUID) { + guard ownsFreshPairingOperation(actionID), + freshPairingOperation?.requestID == connectionManager.connectionRequestID else { return } connectionUI.shouldCompleteFreshPairingOnForeground = true - connectionManager.isPairingFlowActive = true - Task { + freshPairingForegroundRetryTask?.cancel() + freshPairingForegroundRetryTask = Task { try? await Task.sleep(for: Self.freshPairingForegroundRetryDelay) - await resumeFreshPairingIfNeeded() + guard !Task.isCancelled, freshPairingOperation?.actionID == actionID else { return } + resumeFreshPairingIfNeeded() } } - private func resumeFreshPairingIfNeeded() async { - guard connectionUI.shouldCompleteFreshPairingOnForeground else { return } + private func resumeFreshPairingIfNeeded() { + guard connectionUI.shouldCompleteFreshPairingOnForeground, let operation = freshPairingOperation else { return } connectionUI.shouldCompleteFreshPairingOnForeground = false - isFreshPairingForegroundRetry = true + guard ownsFreshPairingOperation(operation.actionID), + operation.requestID == connectionManager.connectionRequestID else { + finishFreshPairingOperation(operation.actionID) + return + } + freshPairingForegroundRetryTask?.cancel() + freshPairingForegroundRetryTask = nil + let previous = freshPairingTask connectionUI.isBusy = true - connectionManager.isPairingFlowActive = true - defer { - connectionUI.isBusy = false - isFreshPairingForegroundRetry = false - if !connectionUI.shouldCompleteFreshPairingOnForeground { - connectionManager.isPairingFlowActive = false + isFreshPairingForegroundRetry = true + freshPairingTask = Task { + await previous?.value + defer { + if freshPairingOperation?.actionID == operation.actionID { isFreshPairingForegroundRetry = false } + finishFreshPairingWork(operation.actionID) + } + await withPairingFlowErrorHandling(actionID: operation.actionID) { + try await completeFreshPairing(actionID: operation.actionID) } - } - 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() + /// 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) } + 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 } /// Retry connecting to the device that just failed without removing the bond. @@ -174,18 +248,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)) + } } } @@ -201,26 +283,19 @@ extension AppState { connectionManager.clearSurfacedAuthenticationFailure() if connectionUI.shouldCompleteFreshPairingOnForeground { - Task { await resumeFreshPairingIfNeeded() } + 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 +307,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 +347,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 +383,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 +429,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+Wiring.swift b/MC1/State/AppState+Wiring.swift index 7a4ec8aece..feea27925d 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,25 +90,27 @@ 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: contactsVersion += 1 @@ -122,11 +122,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 +142,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 +159,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 +172,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 +204,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..026e7ab57f 100644 --- a/MC1/State/AppState.swift +++ b/MC1/State/AppState.swift @@ -298,15 +298,33 @@ final class AppState { /// second `pickerUnavailable` is presented instead of rescheduled. var isFreshPairingForegroundRetry = false + struct FreshPairingOperation { + enum Source { + case explicitSwitch + case systemPairingSetup + case bondLossRecovery + } + + let actionID: UUID + let source: Source + var requestID: UUID? + } + + var freshPairingOperation: FreshPairingOperation? + var freshPairingTask: Task? + var freshPairingForegroundRetryTask: Task? + + var isRecoveringPairing: Bool { + freshPairingOperation?.source == .bondLossRecovery + } + /// Battery monitoring (polling, thresholds, low-battery notifications) let batteryMonitor = BatteryMonitor() /// 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 +347,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 +366,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 +414,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 +423,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 +466,7 @@ final class AppState { ) { self.defaults = defaults self.conversationUnreadOperations = conversationUnreadOperations + onboarding = OnboardingState(defaults: defaults) draftStore = DraftStore(defaults: defaults) let store = StoreService() @@ -451,6 +478,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 +511,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 +534,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 +552,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 +584,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 +628,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 +684,155 @@ 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() + } + + 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 + await liveActivityManager.handleConnectionLost { [weak self] in + self?.connectionManager.isCurrent(receipt) ?? false + } + } - // Reset transient sync UI before wiring awaits so a replacement connection - // cannot inherit activity, phase, or a Ready timer. + 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() await remoteAdminWorkspaces.rebind( - repeaterAdminService: { services.repeaterAdminService }, - roomAdminService: { services.roomAdminService }, - contactService: { services.contactService }, - nodeSnapshotService: { services.nodeSnapshotService }, - deviceHashSize: { [weak self] in self?.connectedDevice?.hashSize } + radioID: snapshot.device.radioID, + repeaterAdminService: { [weak self] in + guard let self, context.isCurrent(self.connectionManager) else { return nil } + return self.connectionSnapshot(for: snapshot.device.radioID)?.services.repeaterAdminService + }, + roomAdminService: { [weak self] in + guard let self, context.isCurrent(self.connectionManager) else { return nil } + return self.connectionSnapshot(for: snapshot.device.radioID)?.services.roomAdminService + }, + contactService: { [weak self] in + guard let self, context.isCurrent(self.connectionManager) else { return nil } + return self.connectionSnapshot(for: snapshot.device.radioID)?.services.contactService + }, + nodeSnapshotService: { [weak self] in + guard let self, context.isCurrent(self.connectionManager) else { return nil } + return self.connectionSnapshot(for: snapshot.device.radioID)?.services.nodeSnapshotService + }, + deviceHashSize: { [weak self] in + guard let self, context.isCurrent(self.connectionManager) else { return nil } + return self.connectionSnapshot(for: snapshot.device.radioID)?.device.hashSize + }, + 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/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..1228afe0ff 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,9 +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 @@ -137,6 +139,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 +263,7 @@ final class ConnectionUIState { private func updateSyncPhase( _ phase: SyncPhase?, connectionManager: ConnectionManager, - syncCoordinator: SyncCoordinator + context: ConnectionCallbackContext ) { currentSyncPhase = phase guard phase == .messages, !syncFailedPillVisible, @@ -252,10 +273,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 +323,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 +375,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/LiveActivityManager.swift b/MC1/State/LiveActivityManager.swift index 046fd6829d..31291c6fb1 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? @@ -97,8 +98,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 +121,7 @@ final class LiveActivityManager { unreadCount: unreadCount, disconnectedDate: .some(nil) ) + guard lifecycleGeneration == generation, isCurrent() else { return } startDecayTimer() startObservingActivityState() return @@ -123,20 +129,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,11 +160,13 @@ 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() } } @@ -177,13 +191,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 +215,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 +234,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 +246,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 +263,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 +312,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 +338,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 +378,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 +399,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 +432,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 +449,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 +540,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, @@ -516,13 +555,14 @@ final class LiveActivityManager { Calendar.current.date(byAdding: .minute, value: 5, to: .now) } let content = ActivityContent(state: state, staleDate: staleDate) - await currentActivity?.update(content) + await activity.update(content) } /// 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 +575,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 +604,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/MessageEventDispatcher.swift b/MC1/State/MessageEventDispatcher.swift index 2d16bbcf35..e4050bea29 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,21 +49,24 @@ 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)) // 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) + appState.ensureChatPrewarmRefresher().noteDirectMessage(contact: contact) case let .channelMessageReceived(message, channelIndex): stream.send(.channelMessageReceived(message: message, channelIndex: channelIndex)) - appState?.ensureChatPrewarmRefresher().noteChannelMessage( + appState.ensureChatPrewarmRefresher().noteChannelMessage( radioID: message.radioID, channelIndex: channelIndex ) @@ -67,7 +74,7 @@ final class MessageEventDispatcher { stream.send(.roomMessageReceived(message: message, sessionID: message.sessionID)) case let .reactionReceived(messageID, summary): stream.send(.reactionReceived(messageID: messageID, summary: summary)) - await appState?.handleReactionNotification(messageID: messageID) + await appState.handleReactionNotification(messageID: messageID) case .contactsChanged, .conversationsChanged: break } @@ -77,9 +84,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 +96,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 +109,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 +124,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 +137,7 @@ final class MessageEventDispatcher { stream.send(.roomMessageStatusUpdated(messageID: messageID)) } case .connectionRecovered: - appState?.handleSessionStateChange() + appState.handleSessionStateChange() } } } @@ -130,9 +145,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)) diff --git a/MC1/State/RemoteAdminWorkspaces.swift b/MC1/State/RemoteAdminWorkspaces.swift index b78deda908..fb65c850f7 100644 --- a/MC1/State/RemoteAdminWorkspaces.swift +++ b/MC1/State/RemoteAdminWorkspaces.swift @@ -73,17 +73,21 @@ final class RemoteAdminWorkspaces { /// 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?, + isCurrent: @MainActor () -> Bool ) async { - for models in repeaters.values { + guard isCurrent() else { return } + 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 +95,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 +104,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..908ffb42f5 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,6 +18,8 @@ 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: "" @@ -25,9 +29,9 @@ enum StatusPillState: Hashable { 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 +43,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/Views/Chats/ChatConversationView.swift b/MC1/Views/Chats/ChatConversationView.swift index 86297b327c..b0eacb8858 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(), 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/ViewModel/ChatViewModel+MessageActions.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+MessageActions.swift index d883738670..d2b9d83d9c 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+MessageActions.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+MessageActions.swift @@ -20,8 +20,8 @@ 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 } @@ -83,8 +83,8 @@ 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 } @@ -165,4 +165,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/Components/BLEStatusIndicatorView.swift b/MC1/Views/Components/BLEStatusIndicatorView.swift index e4aff28020..078a55d5da 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 @@ -26,7 +27,7 @@ struct BLEStatusIndicatorView: View { } 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,13 @@ 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 { + 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 +69,51 @@ struct BLEStatusIndicatorView: View { ) .font(.caption) .foregroundStyle(.secondary) + .tint(.secondary) } } - .foregroundStyle(.secondary) - .tint(.secondary) Button { - showingDeviceSelection = true - } label: { - Label(L10n.Settings.BleStatus.changeDevice, systemImage: "flipphone") - } - - Button(role: .destructive) { 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)) - } - Section { Button { - sendAdvert(flood: false) + showingDeviceSelection = true } label: { - Label(L10n.Settings.BleStatus.sendZeroHopAdvert, systemImage: "dot.radiowaves.right") + Label(L10n.Settings.BleStatus.changeDevice, systemImage: "flipphone") } - .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 +125,9 @@ struct BLEStatusIndicatorView: View { } } - private var accessibilityHint: String { - appState.connectedDevice != nil - ? L10n.Settings.BleStatus.AccessibilityHint.connected - : L10n.Settings.BleStatus.AccessibilityHint.disconnected + 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 +156,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/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/Onboarding/DeviceScanView.swift b/MC1/Views/Onboarding/DeviceScanView.swift index 2f42bc018b..ad9f8d386a 100644 --- a/MC1/Views/Onboarding/DeviceScanView.swift +++ b/MC1/Views/Onboarding/DeviceScanView.swift @@ -32,7 +32,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,29 +126,36 @@ 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 + #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) } + .liquidGlassProminentButtonStyle() + .disabled(appState.connectionUI.isBusy) + } + #endif + } } @ViewBuilder @@ -183,30 +190,38 @@ struct DeviceScanView: View { } private func retryConnection(deviceID: UUID) { - appState.connectionUI.isBusy = true + let actionID = appState.connectionUI.beginConnectionAction() Task { @MainActor in - defer { appState.connectionUI.isBusy = false } + 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 case let .operational(snapshot) = result, appState.connectionManager.isCurrent(snapshot) else { return } + await appState.wireServices(for: snapshot) + guard appState.connectionManager.isCurrent(snapshot) else { return } appState.onboarding.onboardingPath.append(.region) } catch { - appState.connectionUI.presentSavedDeviceConnectFailure(deviceID: deviceID, error: error) + guard 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 } + 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 case let .operational(snapshot) = result, appState.connectionManager.isCurrent(snapshot) else { return } + await appState.wireServices(for: snapshot) + guard appState.connectionManager.isCurrent(snapshot) else { return } appState.onboarding.onboardingPath.append(.region) } catch { - appState.connectionUI.presentConnectionFailure(message: error.userFacingMessage) + guard let failure = appState.currentConnectionFailure(error) else { return } + appState.connectionUI.presentConnectionFailure(message: failure.userFacingMessage) } } } 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..c4a867ae9f 100644 --- a/MC1/Views/RemoteNodes/NodeAuthenticationSheet.swift +++ b/MC1/Views/RemoteNodes/NodeAuthenticationSheet.swift @@ -73,23 +73,35 @@ struct NodeAuthenticationSheet: View { } } .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) 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) + .onChange(of: appState.connectionManager.currentConnection?.generation) { _, _ in + authenticationTask?.cancel() + authenticationTask = nil + isAuthenticating = false + isRetryingViaFlood = false + didResetPath = false + cleanupCountdownState() + } .onDisappear { authenticationTask?.cancel() cleanupCountdownState() @@ -137,6 +149,11 @@ struct NodeAuthenticationSheet: View { // MARK: - Authentication private func authenticate() { + guard let source = appState.connectionSnapshot(for: contact.radioID) else { + errorMessage = RemoteNodeError.notConnected.userFacingMessage + return + } + let context = ConnectionCallbackContext(source) // Clear any previous error errorMessage = nil isAuthenticating = true @@ -146,13 +163,8 @@ struct NodeAuthenticationSheet: View { authenticationTask = Task { do { - guard let device = appState.connectedDevice else { - throw RemoteNodeError.notConnected - } - - guard let services = appState.services else { - throw RemoteNodeError.notConnected - } + guard accepts(context) 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. @@ -161,9 +173,10 @@ struct NodeAuthenticationSheet: View { let pathLength: UInt8 if useFloodRouting && !contact.isFloodRouted && !didResetPath { try await services.contactService.resetPath( - radioID: device.radioID, + radioID: contact.radioID, publicKey: contact.publicKey ) + guard accepts(context) else { return } didResetPath = true pathLength = PacketBuilder.floodPathSentinel } else if useFloodRouting || didResetPath { @@ -181,7 +194,7 @@ struct NodeAuthenticationSheet: View { do { session = try await performLogin( services: services, - device: device, + context: context, password: passwordToUse, pathLength: pathLength ) @@ -189,21 +202,25 @@ struct NodeAuthenticationSheet: View { // 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 { + guard accepts(context) else { return } isRetryingViaFlood = true cleanupCountdownState() } + guard accepts(context) else { return } try await services.contactService.resetPath( - radioID: device.radioID, + radioID: contact.radioID, publicKey: contact.publicKey ) + guard accepts(context) else { return } didResetPath = true session = try await performLogin( services: services, - device: device, + context: context, password: passwordToUse, pathLength: PacketBuilder.floodPathSentinel ) } + guard accepts(context) else { return } // Delete saved password if user unchecked "Remember Password" if hasSavedPassword, !rememberPassword { @@ -215,6 +232,7 @@ struct NodeAuthenticationSheet: View { } await MainActor.run { + guard accepts(context) else { return } authenticationTask = nil isRetryingViaFlood = false cleanupCountdownState() @@ -223,6 +241,7 @@ struct NodeAuthenticationSheet: View { } } catch is CancellationError { await MainActor.run { + guard accepts(context) else { return } authenticationTask = nil isRetryingViaFlood = false cleanupCountdownState() @@ -230,6 +249,7 @@ struct NodeAuthenticationSheet: View { } } catch RemoteNodeError.timeout { await MainActor.run { + guard accepts(context) else { return } authenticationTask = nil isRetryingViaFlood = false cleanupCountdownState() @@ -238,6 +258,7 @@ struct NodeAuthenticationSheet: View { } } catch { await MainActor.run { + guard accepts(context) else { return } authenticationTask = nil isRetryingViaFlood = false cleanupCountdownState() @@ -250,23 +271,24 @@ struct NodeAuthenticationSheet: View { private func performLogin( services: ServiceContainer, - device: DeviceDTO, + context: ConnectionCallbackContext, password: String, 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) else { return } authTimeoutSeconds = seconds authStartTime = Date.now authSecondsRemaining = seconds - startCountdownTask() + startCountdownTask(context: context) } } - if role == .roomServer { - return try await services.roomServerService.joinRoom( - radioID: device.radioID, + let result: RemoteNodeSessionDTO = if role == .roomServer { + try await services.roomServerService.joinRoom( + radioID: contact.radioID, contact: contact, password: password, rememberPassword: rememberPassword, @@ -274,8 +296,8 @@ struct NodeAuthenticationSheet: View { onTimeoutKnown: onTimeoutKnown ) } else { - return try await services.repeaterAdminService.connectAsAdmin( - radioID: device.radioID, + try await services.repeaterAdminService.connectAsAdmin( + radioID: contact.radioID, contact: contact, password: password, rememberPassword: rememberPassword, @@ -283,13 +305,20 @@ struct NodeAuthenticationSheet: View { onTimeoutKnown: onTimeoutKnown ) } + guard accepts(context) else { throw CancellationError() } + return result + } + + private func accepts(_ context: ConnectionCallbackContext) -> Bool { + !Task.isCancelled && context.isCurrent(appState.connectionManager) + && appState.connectionSnapshot(for: contact.radioID) != nil } // MARK: - Countdown private static let countdownTickInterval: Duration = .seconds(1) - private func startCountdownTask() { + private func startCountdownTask(context: ConnectionCallbackContext) { countdownTask = Task { while !Task.isCancelled, let timeout = authTimeoutSeconds, let startTime = authStartTime { do { @@ -297,6 +326,7 @@ struct NodeAuthenticationSheet: View { } catch { break } + guard accepts(context) else { return } let elapsed = Date.now.timeIntervalSince(startTime) let remaining = max(0, timeout - Int(elapsed)) 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..1a878760fe 100644 --- a/MC1/Views/RemoteNodes/Rooms/RoomConversationView.swift +++ b/MC1/Views/RemoteNodes/Rooms/RoomConversationView.swift @@ -102,30 +102,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 +160,7 @@ 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) } .task { for await event in appState.messageEventStream.events() { @@ -191,10 +176,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 +190,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 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/Settings/AdvancedSettingsView.swift b/MC1/Views/Settings/AdvancedSettingsView.swift index 3ca19bbb39..e5353025dc 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 @@ -65,7 +66,7 @@ struct AdvancedSettingsView: View { } .themedCanvas(theme) .environment(discovery) - .settingsSubpageDestinations(regions: discovery, requestRegionAdd: requestRegionAdd) + .settingsSubpageDestinations(regions: discovery, requestRegionAdd: requestRegionAdd, configImport: configImport) .sheet(isPresented: $showingImportKeySheet) { ImportKeySheet() } 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/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/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+FileInput.swift b/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+FileInput.swift new file mode 100644 index 0000000000..ce606051d1 --- /dev/null +++ b/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+FileInput.swift @@ -0,0 +1,110 @@ +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 } + parseTask?.cancel() + cancelConfirmation() + isParsing = true + 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 } + isParsing = false + importedConfig = config + inputReceiptID = recovery?.receiptID + inputSource = source + 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 } + isParsing = false + 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() { + parseTask?.cancel() + currentParseID = nil + previewTask?.cancel() + currentPreviewID = nil + isParsing = false + isPreparingConfirmation = false + showFilePicker = false + cancelConfirmation() + guard !isApplying else { return } + if let inputReceiptID, + connectionManager?.identityImportRecoveries.contains(where: { $0.receiptID == inputReceiptID }) == true { + return + } + resetToFileSelection() + } + + 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 + recovery = nil + identityRecoveryComplete = false + } +} diff --git a/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+Recovery.swift b/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+Recovery.swift new file mode 100644 index 0000000000..9af78dafc1 --- /dev/null +++ b/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+Recovery.swift @@ -0,0 +1,92 @@ +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() + } + recovery = nil + } + + @discardableResult + func beginRecovery(_ summary: IdentityImportRecovery) -> Bool { + guard !isApplying, let current = connectionManager?.prepareIdentityImportRecovery(receiptID: summary.receiptID) else { + return false + } + parseTask?.cancel() + currentParseID = nil + previewTask?.cancel() + currentPreviewID = nil + cancelConfirmation() + if inputReceiptID != current.receiptID { + resetToFileSelection() + } + recovery = current + identityRecoveryComplete = false + 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, validatedRecoveryKey != nil else { + errorMessage = L10n.Settings.ConfigImport.identityRecoveryKeyRequired + showFilePicker = true + return + } + self.recovery = current + confirmation = .recovery(current, inputID: inputID) + 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, selectedInputID: UUID) { + guard inputID == selectedInputID, inputReceiptID == summary.receiptID, + recovery?.receiptID == summary.receiptID, let manager = connectionManager, + manager.prepareIdentityImportRecovery(receiptID: summary.receiptID) == summary, + let key = validatedRecoveryKey else { return } + isApplying = true + errorMessage = nil + identityRecoveryComplete = false + importComplete = false + importTask = Task { + do { + let result = try await manager.retryIdentityImport(confirmation: summary, privateKey: key) + guard inputID == selectedInputID, recovery?.receiptID == summary.receiptID else { return } + isApplying = false + if case .operational = result, manager.isCurrent(result) { + identityRecoveryComplete = true + } else if manager.identityImportRecoveries.contains(where: { $0.receiptID == summary.receiptID }) { + errorMessage = L10n.Settings.ConfigImport.identityOutcomeUnknown(summary.sourceName) + } + } catch { + guard inputID == selectedInputID, recovery?.receiptID == summary.receiptID else { return } + isApplying = false + if let interrupted = error as? IdentityImportRecoveryRequired { + retainInterruptedInput(interrupted.recovery, selectedInputID: selectedInputID) + } else if error is CancellationError { + errorMessage = L10n.Settings.ConfigImport.identityOutcomeUnknown(summary.sourceName) + } else { + errorMessage = error.userFacingMessage + } + } + } + } + + func retainInterruptedInput(_ summary: IdentityImportRecovery, selectedInputID: UUID) { + guard inputID == selectedInputID else { return } + inputReceiptID = summary.receiptID + recovery = summary + importComplete = false + 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..7cc83f372a 100644 --- a/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel.swift +++ b/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel.swift @@ -5,51 +5,93 @@ 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 + } + } + + enum Confirmation { + case config(ImportSource, inputID: UUID, sections: ConfigSections) + case recovery(IdentityImportRecovery, inputID: UUID) + } + + var importedConfig: MeshCoreNodeConfig? { + didSet { + inputID = UUID() + inputSource = nil + inputReceiptID = nil + cancelConfirmation() + } + } + var errorMessage: String? var showFilePicker = false var isParsing = false - - /// Section selection 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 + var recovery: IdentityImportRecovery? + var identityRecoveryComplete = false + + var channelsWouldOverwrite = false + var didApplyAnyWrite = false + var importTask: Task? + var parseTask: Task? + var currentParseID: UUID? + var previewTask: Task? + var currentPreviewID: UUID? + var inputID = UUID() + var inputSource: ImportSource? + var inputReceiptID: UUID? + var confirmation: Confirmation? + 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() + } - /// 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? + var settingsService: SettingsService? { + settingsServiceProvider() + } - private let logger = Logger(subsystem: "com.mc1", category: "NodeConfigImportVM") + var connectedDevice: DeviceDTO? { + connectedDeviceProvider() + } - // MARK: - Dynamic confirmation text + 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 + } private var hasOverwriteSections: Bool { sections.radioSettings || sections.nodeIdentity || sections.positionSettings @@ -61,149 +103,113 @@ final class NodeConfigImportViewModel { } var confirmTitle: String { + if recovery != nil { return L10n.Settings.ConfigImport.confirmTitleIdentityRecovery } switch (hasOverwriteSections, hasAdditiveSections) { - case (false, true): L10n.Settings.ConfigImport.confirmTitleAdd - case (true, false): L10n.Settings.ConfigImport.confirmTitleOverwrite - default: L10n.Settings.ConfigImport.confirmTitle + case (false, true): return L10n.Settings.ConfigImport.confirmTitleAdd + case (true, false): return L10n.Settings.ConfigImport.confirmTitleOverwrite + default: return 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 - } + var confirmButtonRole: ButtonRole? { + recovery == nil ? nil : .destructive } - 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) - } + /// The recovery sheet stays up while the identity write is in flight, so its result stays visible. + var recoverySheetDismissalDisabled: Bool { + recovery != nil && isApplying } - /// 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) - } + 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 } } - 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)") + var confirmMessage: String { + if case let .recovery(summary, _) = confirmation { + return L10n.Settings.ConfigImport.confirmIdentityRecovery("\(summary.sourceName) (\(summary.targetDescription))") + } + guard case let .config(source, _, _) = confirmation else { return "" } + switch (hasOverwriteSections, hasAdditiveSections) { + case (false, true): return L10n.Settings.ConfigImport.confirmMessageAdd(source.name) + case (true, false): return L10n.Settings.ConfigImport.confirmMessageOverwrite(source.name) + case (true, true): return L10n.Settings.ConfigImport.confirmMessageMixed(source.name) + default: return L10n.Settings.ConfigImport.confirmMessage(source.name) } } - /// 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 } - + func prepareConfirmation() { + guard !isPreparingConfirmation, !isApplying, !isParsing else { return } + if recovery != nil { + prepareRecoveryConfirmation() + return + } + guard let config = importedConfig, let service = nodeConfigService, + let snapshot = connectionManager?.currentConnection, + connectedDevice?.id == snapshot.device.id else { return } + let source = ImportSource(snapshot) + guard inputSource == nil || inputSource == source else { return } + inputSource = source + let selectedInputID = inputID + let selectedSections = sections + let previewID = UUID() + currentPreviewID = previewID errorMessage = nil isPreparingConfirmation = true previewTask = Task { - defer { isPreparingConfirmation = false } + defer { + if currentPreviewID == previewID { 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 } + let preview = try await service.previewImport(config, sections: selectedSections) + guard !Task.isCancelled, currentPreviewID == previewID, inputID == selectedInputID, + connectionManager?.isCurrent(generation: source.generation, requestID: source.requestID) == true else { return } channelsWouldOverwrite = preview.channelsOverwriteExisting - errorMessage = nil + confirmation = .config(source, inputID: selectedInputID, sections: selectedSections) showConfirmation = true } catch is CancellationError { - // The user left the screen mid-preview — leave the UI untouched. + return } catch { + guard currentPreviewID == previewID else { return } 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 } + func cancelConfirmation() { + confirmation = nil + showConfirmation = false + } + + func applyConfig() { + guard !isApplying, let confirmation else { return } + cancelConfirmation() + switch confirmation { + case let .recovery(summary, selectedInputID): + applyIdentityRecovery(summary, selectedInputID: selectedInputID) + case let .config(source, selectedInputID, selectedSections): + guard inputID == selectedInputID, sections == selectedSections, + connectionManager?.isCurrent(generation: source.generation, requestID: source.requestID) == true, + let config = importedConfig, let service = nodeConfigService else { return } + applyConfiguration(config, service: service, source: source, selectedSections: selectedSections) + } + } + private func applyConfiguration( + _ config: MeshCoreNodeConfig, service: NodeConfigService, source: ImportSource, selectedSections: ConfigSections + ) { isApplying = true applyProgress = 0 errorMessage = nil importComplete = false didApplyAnyWrite = false - + let selectedInputID = inputID 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 { @@ -212,38 +218,32 @@ final class NodeConfigImportViewModel { applyStepDescription = Self.description(for: progress.step) } } - do { - try await service.importConfig( - config, - sections: sections, - radioID: radioID - ) { progress in - progressContinuation.yield(progress) + try await service.importConfig(config, sections: selectedSections, radioID: source.radioID) { + progressContinuation.yield($0) } progressContinuation.finish() await consumer.value - // Refresh cached device state so Settings UI reflects imported values - if let settingsService { + if connectedDevice?.id == source.deviceID, let settingsService { try? await settingsService.refreshDeviceInfo() } isApplying = false importComplete = true - try? await Task.sleep(for: .seconds(1.5)) - guard !Task.isCancelled else { return } + try? await Task.sleep(for: Timing.resultDisplay) + guard !Task.isCancelled, inputID == selectedInputID 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)") + if let interrupted = error as? IdentityImportRecoveryRequired { + retainInterruptedInput(interrupted.recovery, selectedInputID: selectedInputID) + } else if error is CancellationError { + errorMessage = Self.cancellationMessage(didApplyAnyWrite: didApplyAnyWrite) + } else { + errorMessage = Self.failureMessage(for: error, didApplyAnyWrite: didApplyAnyWrite) + logger.error("Import failed: \(error.localizedDescription)") + } } } } @@ -252,23 +252,11 @@ final class NodeConfigImportViewModel { 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() + private enum Timing { + static let resultDisplay: Duration = .seconds(1.5) } - /// 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 { + static func description(for step: ImportStep) -> String { switch step { case .position: L10n.Settings.ConfigImport.stepPosition case .otherParameters: L10n.Settings.ConfigImport.stepOtherParameters @@ -281,38 +269,11 @@ final class NodeConfigImportViewModel { } } - /// 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 + 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 + didApplyAnyWrite ? L10n.Settings.ConfigImport.failedPartial(error.userFacingMessage) : error.userFacingMessage } } diff --git a/MC1/Views/Settings/Sections/DangerZoneViewModel.swift b/MC1/Views/Settings/Sections/DangerZoneViewModel.swift index 5d0977d68b..421cbd7d70 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 @@ -52,14 +53,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 } } @@ -68,14 +73,19 @@ final class DangerZoneViewModel { /// A nil service or device ID mirrors a disconnected state. func factoryReset() async -> Bool { guard let settingsService, - let deviceID = connectedDevice?.id, - let connectionManager else { + 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. @@ -86,9 +96,9 @@ final class DangerZoneViewModel { // Expected: device reboots before sending OK response } - // Always clean up: remove from ASK, disconnect, delete from SwiftData - await connectionManager.forgetDevice(id: deviceID) - return true + let result = await connectionManager.forgetDeviceAfterReset(context) + guard removalOperationID == operationID, case let .removed(receipt) = result else { return false } + return connectionManager.isCurrent(receipt) } func fetchUnfavoritedCount() async { 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..b9ff8e9b1b --- /dev/null +++ b/MC1/Views/Settings/Sections/RadioWiFiViewModel+Operations.swift @@ -0,0 +1,152 @@ +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, + 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/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/SettingsDetailView.swift b/MC1/Views/Settings/SettingsDetailView.swift index 591bbf025b..96aeb9b062 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,7 +21,9 @@ 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: diff --git a/MC1/Views/Settings/SettingsListContent.swift b/MC1/Views/Settings/SettingsListContent.swift index e4e3f12442..b61e5adc10 100644 --- a/MC1/Views/Settings/SettingsListContent.swift +++ b/MC1/Views/Settings/SettingsListContent.swift @@ -13,6 +13,7 @@ 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 { @@ -58,6 +59,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") diff --git a/MC1/Views/Settings/SettingsSubpage.swift b/MC1/Views/Settings/SettingsSubpage.swift index 0ad1b6e9e1..fbeeb209e4 100644 --- a/MC1/Views/Settings/SettingsSubpage.swift +++ b/MC1/Views/Settings/SettingsSubpage.swift @@ -56,7 +56,7 @@ 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) } @@ -71,9 +71,10 @@ 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 { @@ -103,7 +104,10 @@ private struct SettingsSubpageDestination: View { case .configExport: NodeConfigExportView() case .configImport: - NodeConfigImportView() + if case let .advanced(_, _, configImport) = context { + NodeConfigImportView(viewModel: configImport) + .onAppear { configImport.beginImport() } + } case .blockedChannelSenders: BlockedChannelSendersView() case .blockedContacts: @@ -124,7 +128,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: diff --git a/MC1/Views/Settings/SettingsView.swift b/MC1/Views/Settings/SettingsView.swift index 745868cfe5..e72ce3933f 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( @@ -159,6 +178,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/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/TracePath/TracePathViewModel.swift b/MC1/Views/Tools/TracePath/TracePathViewModel.swift index 4173722075..e666b9da72 100644 --- a/MC1/Views/Tools/TracePath/TracePathViewModel.swift +++ b/MC1/Views/Tools/TracePath/TracePathViewModel.swift @@ -259,8 +259,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 @@ -377,8 +376,7 @@ 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 } + guard !completedResults.isEmpty, let firstSuccess = successfulResults.first else { return false } return fullPathBytes == firstSuccess.tracedPathBytes } else { guard let result, result.success else { return false } @@ -393,8 +391,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 +438,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 @@ -874,12 +869,10 @@ final class TracePathViewModel { 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 } @@ -915,12 +908,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 } @@ -1151,8 +1142,7 @@ final class TracePathViewModel { } 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 pendingTag != nil, let waitingTicket, waitingTicket.isCurrent(in: executionEpoch), let next = advertisementService, next !== finished else { return } startListening() } @@ -1164,8 +1154,7 @@ final class TracePathViewModel { /// 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(), 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..6818cad6bd --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Connect.swift @@ -0,0 +1,137 @@ +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 + let container = ServiceContainer( + session: session, dataStore: persistenceStore, radioID: MockDataProvider.simulatorDeviceID, + appStateProvider: appStateProvider, connectionStateEvents: connectionStateEvents, + initialConnectionState: .connected, radioWiFiState: radioWiFiState(for: MockDataProvider.simulatorDeviceID), + notificationService: notificationServiceForTesting() + ) + 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..c846543c28 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+IdentityRuntime.swift @@ -0,0 +1,96 @@ +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 { 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..409cfbec54 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)") @@ -112,6 +107,7 @@ public extension ConnectionManager { // 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,6 +171,21 @@ 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() + } catch { + logger.error("Failed to activate pairing session: \(error.localizedDescription)") + } + guard desiredRequest?.id == activationRequestID else { return } + await checkWiFiConnectionHealth() + await checkBLEConnectionHealth() + return + } + #if targetEnvironment(simulator) // Skip auto-reconnect if user explicitly disconnected if connectionIntent.isUserDisconnected { @@ -211,670 +222,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..39fc7c7948 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Pairing.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Pairing.swift @@ -4,109 +4,82 @@ 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 - } + /// 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 +97,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 +148,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 +203,23 @@ 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)") - } - - await clearPersistedConnection(for: deviceID) - logger.info("Device forgotten") + @discardableResult + func forgetDevice(_ context: ConnectionRemovalContext, deleteData: Bool) async throws -> ConnectionRemovalResult { + try await removeDevice( + context, policy: .wholeDevice(deleteData: deleteData), reason: .forgetDevice, systemPolicy: .required + ) } - /// 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)") - } - - let dataStore = persistenceStore + @discardableResult + func forgetDeviceAfterReset(_ context: ConnectionRemovalContext) async -> ConnectionRemovalResult { do { - try await dataStore.deleteDeviceAndData(id: id) + return try await removeDevice( + context, policy: .wholeDevice(deleteData: true), reason: .factoryReset, systemPolicy: .bestEffort + ) } catch { - logger.warning("Failed to delete device data from SwiftData: \(error.localizedDescription)") + logger.warning("Reset cleanup failed: \(error.localizedDescription)") + return .superseded } - - // 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 +359,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 +378,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 +412,34 @@ 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 - } - - let keptWiFi = await retainedWiFiRowAfterBluetoothRemoval(peripheralID: bluetoothID) != nil - if disconnectBluetoothSession { - await disconnect(reason: .deviceRemovedFromSettings) - } - if keptWiFi { - return - } - - 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)") - } - } + public func devicePairing(_ service: any DevicePairingService, didRemoveDeviceWithID bluetoothID: UUID) { + guard removalDeviceID != bluetoothID else { return } + handleRegistryRemoval(bluetoothID, pairingFailed: false) } - 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) + public func devicePairing(_ service: any DevicePairingService, didFailPairingForDeviceWithID bluetoothID: UUID) { + guard removalDeviceID != bluetoothID else { return } + handleRegistryRemoval(bluetoothID, pairingFailed: true) + } - // 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..767b06c5b5 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Preparation.swift @@ -0,0 +1,267 @@ +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 + try await store.registerConnectionDevice(observation, bluetoothPeripheralID: bluetoothPeripheralID) + } + 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 + ) + 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 + + /// 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(.seconds(10), 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) + } + 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 + + /// 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+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..e55bf2eb44 --- /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) + } + + private 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) + } + } + + private 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) + } + } + + private 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..a71a2a1068 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Requests.swift @@ -0,0 +1,346 @@ +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) + } + if 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..b61b45057e --- /dev/null +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+ResourcePreparation.swift @@ -0,0 +1,54 @@ +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 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 + } +} 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+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..fd04e4f4ed 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,28 @@ 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? /// 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 +65,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 +85,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 +93,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 +110,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 +122,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. @@ -300,17 +163,64 @@ public final class ConnectionManager { private let defaults: UserDefaults private let lastConnectionStore: LastConnectionStore 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 +236,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 @@ -376,7 +287,7 @@ public final class ConnectionManager { /// 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 +317,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 +373,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 +389,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 +427,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 +437,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 +474,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 +508,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 +529,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 +583,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,9 +615,15 @@ 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() } ) { 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) @@ -730,7 +645,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 +665,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 transport.setLifecycleHandler { [weak self] event in + Task { @MainActor in await self?.handleBLELifecycleEvent(event) } } - - await stateMachine.setRemoteLinkLostHandler { [weak self] deviceID, eventTime in - Task { @MainActor in - self?.notePowerOffRemoteLoss(deviceID: deviceID, eventTime: eventTime) - } - } - - // 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 +699,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 +734,76 @@ 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) + } + + func persistIntent() { + connectionIntent.persist(to: defaults) } - /// Full cleanup including state reset (used on explicit disconnect) - func cleanupConnection() async { - logger.info("[BLE] cleanupConnection: state → .disconnected") - connectionState = .disconnected - connectingDeviceID = nil + // 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 + 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 + } + currentTransportType = phase == .disconnected ? nil : request.target.transportType + connectionState = phase + } + + @discardableResult + func detachPublication(phase: DeviceConnectionState) -> ConnectionLink? { + 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 +827,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 +855,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, @@ -1481,14 +883,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,6 +909,23 @@ 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 } 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/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/PendingSend.swift b/MC1Services/Sources/MC1Services/Models/PendingSend.swift index 26836068d0..b7076bcefa 100644 --- a/MC1Services/Sources/MC1Services/Models/PendingSend.swift +++ b/MC1Services/Sources/MC1Services/Models/PendingSend.swift @@ -60,7 +60,7 @@ public final class PendingSend { /// 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: + /// attempt, before any wire-affecting work. For queued rows, three distinguishable states: /// /// - `nil` — pre-migration row, lightweight-migrated from a schema /// version without this column. Drain history is ambiguous, @@ -83,6 +83,11 @@ public final class PendingSend { /// which lightweight migration maps to `nil` and warmUp purges on connect. public var attemptCount: Int? + /// 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 +101,10 @@ public final class PendingSend { localNodeName: String?, sequence: Int, enqueuedAt: Date, - attemptCount: Int? = nil + attemptCount: Int? = nil, + ackCodes: [Data]? = nil, + ackSentAt: Date? = nil, + ackDeadline: Date? = nil ) { self.id = id self.radioID = radioID @@ -111,6 +119,9 @@ public final class PendingSend { self.sequence = sequence self.enqueuedAt = enqueuedAt self.attemptCount = attemptCount + self.ackCodes = ackCodes + self.ackSentAt = ackSentAt + self.ackDeadline = ackDeadline } var kind: PendingSendKind { @@ -155,6 +166,9 @@ public struct PendingSendDTO: Sendable, Hashable, Identifiable { /// new envelopes enter disk distinguishable from pre-migration rows that /// lightweight-migrate to `nil`. public let attemptCount: Int? + public let ackCodes: [Data]? + public let ackSentAt: Date? + public let ackDeadline: Date? init( id: UUID, @@ -169,7 +183,10 @@ public struct PendingSendDTO: Sendable, Hashable, Identifiable { localNodeName: String?, sequence: Int, enqueuedAt: Date, - attemptCount: Int? = 0 + attemptCount: Int? = 0, + ackCodes: [Data]? = nil, + ackSentAt: Date? = nil, + ackDeadline: Date? = nil ) { self.id = id self.radioID = radioID @@ -184,6 +201,9 @@ public struct PendingSendDTO: Sendable, Hashable, Identifiable { self.sequence = sequence self.enqueuedAt = enqueuedAt self.attemptCount = attemptCount + self.ackCodes = ackCodes + self.ackSentAt = ackSentAt + self.ackDeadline = ackDeadline } } @@ -202,7 +222,10 @@ public extension PendingSend { localNodeName: dto.localNodeName, sequence: dto.sequence, enqueuedAt: dto.enqueuedAt, - attemptCount: dto.attemptCount + attemptCount: dto.attemptCount, + ackCodes: dto.ackCodes, + ackSentAt: dto.ackSentAt, + ackDeadline: dto.ackDeadline ) } @@ -220,7 +243,10 @@ public extension PendingSend { localNodeName: localNodeName, sequence: sequence, enqueuedAt: enqueuedAt, - attemptCount: attemptCount + attemptCount: attemptCount, + ackCodes: ackCodes, + ackSentAt: ackSentAt, + ackDeadline: ackDeadline ) } } diff --git a/MC1Services/Sources/MC1Services/Models/PendingSendEnvelope.swift b/MC1Services/Sources/MC1Services/Models/PendingSendEnvelope.swift index c9035ceec1..d410d2b115 100644 --- a/MC1Services/Sources/MC1Services/Models/PendingSendEnvelope.swift +++ b/MC1Services/Sources/MC1Services/Models/PendingSendEnvelope.swift @@ -6,7 +6,7 @@ import Foundation /// channel row into the DM queue or vice versa. public extension PendingSendDTO { func directMessageEnvelope() -> DirectMessageEnvelope? { - guard kind == .dm, let contactID else { return nil } + guard kind == .dm, ackDeadline == nil, let contactID else { return nil } return DirectMessageEnvelope(messageID: messageID, contactID: contactID, isResend: isResend) } @@ -37,7 +37,10 @@ public extension PendingSendDTO { 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 @@ -60,7 +63,10 @@ public extension PendingSendDTO { messageTimestamp: 0, localNodeName: nil, sequence: 0, - enqueuedAt: enqueuedAt + enqueuedAt: enqueuedAt, + ackCodes: ackCodes, + ackSentAt: ackSentAt, + ackDeadline: ackDeadline ) } 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/MessagePersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift index d2dba541cc..f7f4a4f2ae 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift @@ -157,6 +157,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?) 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] @@ -172,11 +178,11 @@ public protocol MessagePersisting: Actor { 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. + /// `messageID`. Returns that row's ID and new count, or `nil` if no queued row matched. /// Throws on SwiftData read/write failure; callers must treat a thrown /// error as transient (park + retry) and `nil` as terminal (deleted row). @discardableResult - func incrementPendingSendAttemptCount(messageID: UUID) async throws -> Int? + func incrementPendingSendAttemptCount(messageID: UUID) async throws -> (pendingSendID: UUID, attemptCount: Int)? } // MARK: - Default Parameter Values diff --git a/MC1Services/Sources/MC1Services/ServiceContainer.swift b/MC1Services/Sources/MC1Services/ServiceContainer.swift index bc92654b99..7c1335e001 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 { @@ -154,16 +94,8 @@ 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 // MARK: - Notification Actions @@ -194,6 +126,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 +146,19 @@ 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 ) { self.session = session self.appStateProvider = appStateProvider @@ -234,7 +167,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 @@ -268,20 +201,23 @@ public final class ServiceContainer { messageService = MessageService( session: session, dataStore: dataStore, - contactService: contactService + contactService: contactService, + config: messageConfig, + ackEvents: ackEvents ) 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) binaryProtocolService = BinaryProtocolService( @@ -357,28 +293,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 +368,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 +396,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 +408,21 @@ public final class ServiceContainer { /// so the chat send queue drains. `stopEventMonitoring()` alone does not /// cover that. func tearDown() async { + isTornDown = true + if let tearDownTask { + await tearDownTask.value + return + } + let worker = Task { await performTearDown() } + tearDownTask = worker + await worker.value + } + + private func performTearDown() async { + await messageService.retireInlineSends() + await messageService.waitForAcknowledgementSaves() await stopEventMonitoring() + await remoteNodeService.retireKeepAlives() // Break the retain cycles the wired handlers form. The message // closures and the discovery event task capture this container's @@ -464,13 +456,24 @@ public final class ServiceContainer { await chatSendQueueService.shutdown() } + func prepareForIdentityImport() async { + isTornDown = true + await messageService.retireInlineSends() + await remoteNodeService.retireKeepAlives() + 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/AdvertisementService.swift b/MC1Services/Sources/MC1Services/Services/AdvertisementService.swift index 6a7d34acd8..a2ef456fbf 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 @@ -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) } 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. @@ -666,7 +685,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 +715,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/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/ChannelService.swift b/MC1Services/Sources/MC1Services/Services/ChannelService.swift index b5b84d6f43..6c5f9c9f08 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 } } @@ -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/ChatSendQueueService.swift b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift index 1fdb6cbe40..7ad94e7837 100644 --- a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift +++ b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift @@ -82,6 +82,12 @@ 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()`. @@ -115,9 +121,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 @@ -164,6 +172,7 @@ public final class ChatSendQueueService { osLogger: osLoggerRef ) else { return } preserveTimestamp = result.preserveTimestamp + pendingSendID = result.pendingSendID } catch { _ = try? await dataStoreRef.updateMessageStatusUnlessDelivered(id: envelope.messageID, status: .pending) try await ChatSendQueueService.parkAndCancel( @@ -176,25 +185,27 @@ public final class ChatSendQueueService { } do { - if envelope.isResend { - _ = try await messageServiceRef.resendDirectMessage( + let message: MessageDTO = if envelope.isResend { + try await messageServiceRef.resendDirectMessage( messageID: envelope.messageID, to: contact, - preserveTimestamp: preserveTimestamp + preserveTimestamp: preserveTimestamp, + pendingSendID: pendingSendID ) } else { - _ = try await messageServiceRef.sendPendingDirectMessage( + try await messageServiceRef.sendPendingDirectMessage( messageID: envelope.messageID, to: contact, - preserveTimestamp: preserveTimestamp + preserveTimestamp: preserveTimestamp, + pendingSendID: pendingSendID ) } - try? await dataStoreRef.deletePendingSendsForMessage(messageID: envelope.messageID) + if message.status != .sent, let pendingSendID { + try? await dataStoreRef.deletePendingSend(id: pendingSendID) + } 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() @@ -221,15 +232,14 @@ public final class ChatSendQueueService { } catch let cancellation as CancellationError { 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))") @@ -244,6 +254,17 @@ public final class ChatSendQueueService { // terminal failure for the envelope and calls // `notifyMessageFailed` exactly once. do { + guard let expectedChannelSecret = try await ChatSendQueueService.validateQueuedChannel( + envelope: envelope, + radioID: radioID, + dataStore: dataStoreRef, + channelService: channelServiceRef, + triggers: triggers, + logger: loggerRef, + timeout: configRef.transportWaitTimeout + ) else { return } + try ChatSendQueueService.cancelSendIfRetired(sendsRetired) + // Pre-send gate + attemptCount bump; see DM closure for rationale. let postBumpCount: Int let preserveTimestamp: Bool @@ -279,10 +300,14 @@ public final class ChatSendQueueService { if envelope.isResend { indexTimestamp = try await messageServiceRef.resendChannelMessage( messageID: envelope.messageID, - preserveTimestamp: preserveTimestamp + preserveTimestamp: preserveTimestamp, + expectedChannelSecret: expectedChannelSecret ) } else { - try await messageServiceRef.sendPendingChannelMessage(messageID: envelope.messageID) + try await messageServiceRef.sendPendingChannelMessage( + messageID: envelope.messageID, + expectedChannelSecret: expectedChannelSecret + ) indexTimestamp = envelope.messageTimestamp } if let nodeName = envelope.localNodeName { @@ -397,12 +422,18 @@ public final class ChatSendQueueService { /// fails so the caller can surface the failure instead of silently /// dropping the queued send. public 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) } @@ -414,14 +445,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 +465,7 @@ public final class ChatSendQueueService { initial: DeviceConnectionState, events: AsyncStream ) { + guard !isRetired else { return } connectionStateTask?.cancel() if initial.canDrainSendQueue { transportDidOpen() @@ -460,6 +493,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() @@ -503,7 +537,7 @@ public final class ChatSendQueueService { 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,12 +552,14 @@ public final class ChatSendQueueService { } let postBumpCount: Int + let pendingSendID: UUID do { guard let bumped = try await dataStore.incrementPendingSendAttemptCount(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") throw error @@ -531,7 +567,44 @@ public final class ChatSendQueueService { 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) + } + + private nonisolated static func cancelSendIfRetired(_ sendsRetired: OSAllocatedUnfairLock) throws { + if sendsRetired.withLock({ $0 }) { + throw CancellationError() + } + } + + private nonisolated static func validateQueuedChannel( + envelope: ChannelMessageEnvelope, + radioID: UUID, + dataStore: any MessagePersisting, + channelService: ChannelService, + triggers: BLETransportOpenedSignal, + logger: PersistentLogger, + timeout: TimeInterval + ) async throws -> Data? { + do { + try Task.checkCancellation() + guard try await dataStore.hasPendingSend(messageID: envelope.messageID) else { return nil } + guard let expected = try await channelService.getChannel(radioID: radioID, index: envelope.channelIndex), + let current = try await channelService.fetchChannel(index: envelope.channelIndex), + current.secret == expected.secret else { + throw MessageServiceError.channelNotFound + } + try Task.checkCancellation() + return expected.secret + } 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 +638,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 +726,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 +758,14 @@ public final class ChatSendQueueService { } #if DEBUG + var isRetiredForTesting: Bool { + isRetired + } + + var parkedDrainCountForTesting: Int { + get async { await triggers.waiterCountForTesting } + } + /// Test-only: drain readiness for synchronizing tests. func awaitDrainCompletion() async { await dmQueue.awaitDrainCompletion() @@ -713,11 +785,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() } + + private func beginAdmission() -> Bool { + guard !isRetired else { return false } + admittedWork += 1 + return true + } + + private 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/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/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/MessagePollingService.swift b/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift index fe08727b95..4edd4ba406 100644 --- a/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift +++ b/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift @@ -132,7 +132,7 @@ actor MessagePollingService { if isAutoFetchEnabled { await stopAutoFetch() } else { - stopEventMonitoring() + await stopEventMonitoring() currentRadioID = nil } } @@ -167,7 +167,7 @@ actor MessagePollingService { await session.stopAutoMessageFetching() // Stop event monitoring - stopEventMonitoring() + await stopEventMonitoring() logger.info("Auto-fetch stopped") } @@ -268,9 +268,11 @@ actor MessagePollingService { } /// Stop monitoring events - private func stopEventMonitoring() { - eventMonitorTask?.cancel() + private func stopEventMonitoring() async { + let eventMonitorTaskToStop = eventMonitorTask eventMonitorTask = nil + eventMonitorTaskToStop?.cancel() + await eventMonitorTaskToStop?.value } /// Handle incoming MeshCore event diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+ACK.swift b/MC1Services/Sources/MC1Services/Services/MessageService+ACK.swift index fe3f228465..49bd43c930 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. @@ -72,10 +74,10 @@ public extension MessageService { let expiredEntries = pendingAcks.filter { _, tracking in !tracking.isDelivered && - now.timeIntervalSince(tracking.sentAt) > max(window, tracking.timeout) + now > (tracking.deadline ?? tracking.sentAt.addingTimeInterval(max(window, tracking.timeout))) } - for (messageID, snapshot) in expiredEntries { + for (messageID, tracking) in expiredEntries { #if DEBUG if let gate = ackExpiryWriteGateForTesting { await gate(messageID) @@ -83,16 +85,20 @@ public extension MessageService { #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.sentAt == tracking.sentAt, + now > (current.deadline ?? current.sentAt.addingTimeInterval(max(window, current.timeout))) 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 +108,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]?.isDelivered == false else { continue } + do { + _ = try await commitPendingAcknowledgement(messageID: messageID, sentAt: tracking.sentAt) + } catch { + logger.error("Failed to fail pending message: \(error.localizedDescription)") } } } @@ -122,8 +129,7 @@ public extension MessageService { /// /// - Throws: Database errors when updating message status func stopAndFailAllPending() async throws { - ackCheckTask?.cancel() - ackCheckTask = nil + await stopAckExpiryChecking() try await failAllPendingMessages() } diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift b/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift new file mode 100644 index 0000000000..57cc701c3e --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift @@ -0,0 +1,176 @@ +import Foundation + +enum PendingAcknowledgementCommit { + case committed(MessageStatus) + case unchanged + case waitingForOwner +} + +extension MessageService { + func restorePendingAcknowledgements(radioID: UUID) async throws { + 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 + } + pendingAcks[row.messageID] = PendingAck( + messageID: row.messageID, contactID: contactID, ackCodes: Set(codes), + sentAt: sentAt, timeout: deadline.timeIntervalSince(sentAt), + pendingSendID: row.id, deadline: deadline + ) + } + } + + func persistAcknowledgement( + messageID: UUID, radioID: UUID, pendingSendID: UUID? + ) async throws -> Bool { + beginAcknowledgementSave(messageID) + defer { endAcknowledgementSave(messageID) } + guard let tracking = pendingAcks[messageID], !tracking.isDelivered else { return false } + #if DEBUG + if let gate = acknowledgementSaveGateForTesting { await gate() } + #endif + let ownerID = pendingSendID ?? UUID() + let deadline = tracking.sentAt.addingTimeInterval(max(config.ackGiveUpWindow, tracking.timeout)) + let row = PendingSendDTO( + id: ownerID, envelope: DirectMessageEnvelope(messageID: messageID, contactID: tracking.contactID), + radioID: radioID, enqueuedAt: tracking.sentAt, + ackCodes: Array(tracking.ackCodes), ackSentAt: tracking.sentAt, ackDeadline: deadline + ) + let saved: Bool + do { + saved = try await dataStore.savePendingAcknowledgement(row, replacingPendingSendID: pendingSendID) + } catch { + throw MessageServiceError.persistenceError(error) + } + noteAcknowledgementSaveCommitted(messageID) + guard saved else { + removePendingAckIfCurrent(tracking) + return false + } + #if DEBUG + if let gate = acknowledgementInstallGateForTesting { await gate() } + #endif + if let current = pendingAcks[messageID] { + if current.sentAt == tracking.sentAt, !current.isDelivered { + pendingAcks[messageID]?.pendingSendID = ownerID + pendingAcks[messageID]?.deadline = deadline + if current.matchedAckCode != nil { + _ = try await commitPendingAcknowledgement(messageID: messageID, sentAt: current.sentAt) + } + } else if current.sentAt != tracking.sentAt { + try await dataStore.deletePendingSend(id: ownerID) + } else { + try await resolveFinishedOwner(messageID: messageID, ownerID: ownerID, deadline: deadline) + } + } else { + try await resolveFinishedOwner(messageID: messageID, ownerID: ownerID, deadline: deadline) + } + return true + } + + 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 let current = pendingAcks[messageID], current.sentAt == sentAt else { return .unchanged } + if uncommittedAcknowledgementSaves.contains(messageID), current.pendingSendID == nil { + return .waitingForOwner + } + let status: MessageStatus = current.matchedAckCode == nil ? .failed : .delivered + let updated = try await writeTerminalAcknowledgement(current, status: status) + guard pendingAcks[messageID]?.sentAt == sentAt else { + return updated ? .committed(status) : .unchanged + } + guard updated else { + pendingAcks.removeValue(forKey: messageID) + return .unchanged + } + pendingAcks[messageID]?.isDelivered = true + if status == .delivered { + do { + try await dataStore.updateContactLastMessage(contactID: current.contactID, date: Date()) + } catch { + logger.error("Failed to update contact lastMessageDate: \(error.localizedDescription)") + } + } + let tripTime = pendingAcks[messageID]?.matchedTripTime + pendingAcks.removeValue(forKey: messageID) + switch status { + case .delivered: + statusEventBroadcaster.yield(.statusResolved(messageID: messageID, status: .delivered, roundTripTime: tripTime)) + case .failed: + statusEventBroadcaster.yield(.failed(messageID: messageID)) + default: + break + } + return .committed(status) + } + + private func beginAcknowledgementSave(_ messageID: UUID) { + acknowledgementSavesInFlight[messageID, default: 0] += 1 + uncommittedAcknowledgementSaves.insert(messageID) + } + + private func noteAcknowledgementSaveCommitted(_ messageID: UUID) { + uncommittedAcknowledgementSaves.remove(messageID) + } + + private func endAcknowledgementSave(_ messageID: UUID) { + uncommittedAcknowledgementSaves.remove(messageID) + let remaining = (acknowledgementSavesInFlight[messageID] ?? 1) - 1 + if remaining > 0 { + acknowledgementSavesInFlight[messageID] = remaining + } else { + acknowledgementSavesInFlight.removeValue(forKey: 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 ownerID = current.pendingSendID { + return try await dataStore.resolvePendingAcknowledgement( + id: ownerID, expectedDeadline: current.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 resolveFinishedOwner(messageID: UUID, ownerID: UUID, deadline: Date) async throws { + let message = try await dataStore.fetchMessage(id: messageID) + guard message == nil || message?.status == .delivered || message?.status == .failed else { return } + _ = try await dataStore.resolvePendingAcknowledgement( + id: ownerID, expectedDeadline: deadline, status: message?.status ?? .failed, + ackCode: message?.ackCode, roundTripTime: message?.roundTripTime + ) + } + + @discardableResult + func removePendingAckIfCurrent(_ tracking: PendingAck) -> Bool { + guard let current = pendingAcks[tracking.messageID], current.sentAt == tracking.sentAt, + current.pendingSendID == tracking.pendingSendID else { return false } + pendingAcks.removeValue(forKey: tracking.messageID) + return true + } +} diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift b/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift index 2d96a422e4..944b0aa883 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift @@ -8,7 +8,8 @@ extension MessageService { text: String, channelIndex: UInt8, radioID: UUID, - timestamp: Date + timestamp: Date, + expectedChannelSecret: Data? = nil ) async throws { let channel = try await dataStore.fetchChannel(radioID: radioID, index: channelIndex) let device = try await dataStore.fetchDevice(radioID: radioID) @@ -18,17 +19,35 @@ extension MessageService { 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 expectedChannelSecret { + do { + try await session.sendVerifiedChannelMessage( + channel: channelIndex, + text: text, + timestamp: timestamp, + floodScope: appliedScope, + expectedSecret: expectedChannelSecret + ) + } catch let error as MeshCoreError { + guard case .invalidResponse = error else { throw error } + throw MessageServiceError.channelNotFound + } + } else 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+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+SendChannel.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift index 409923fc9d..e3d4ea700f 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift @@ -138,7 +138,7 @@ public extension MessageService { /// success or `.failed` on error. /// /// - Parameter messageID: The ID of the pending message to send - func sendPendingChannelMessage(messageID: UUID) async throws { + func sendPendingChannelMessage(messageID: UUID, expectedChannelSecret: Data? = nil) async throws { // Catch 1: validation guards + send + status flip. Validation lives // inside the do/catch so a missing message or missing channel index // consistently writes `.failed` to the DB before propagating — paired @@ -162,7 +162,8 @@ public extension MessageService { text: message.text, channelIndex: channelIndex, radioID: radioID, - timestamp: Date(timeIntervalSince1970: TimeInterval(message.timestamp)) + timestamp: Date(timeIntervalSince1970: TimeInterval(message.timestamp)), + expectedChannelSecret: expectedChannelSecret ) } try await dataStore.updateMessageStatus(id: messageID, status: .sent) @@ -199,7 +200,8 @@ public extension MessageService { @discardableResult func resendChannelMessage( messageID: UUID, - preserveTimestamp: Bool = false + preserveTimestamp: Bool = false, + expectedChannelSecret: Data? = nil ) async throws -> UInt32 { // Broadcast .resent only after .sent is committed. The sentCommitted // flag suppresses a spurious broadcast if catch 1 rethrows; @@ -243,7 +245,8 @@ public extension MessageService { text: message.text, channelIndex: channelIndex, radioID: message.radioID, - timestamp: wireDate + timestamp: wireDate, + expectedChannelSecret: expectedChannelSecret ) } try await dataStore.updateMessageStatus(id: messageID, status: .sent) diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift index 0d2124d010..e1a06bffcc 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift @@ -37,6 +37,10 @@ extension MessageService { 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() @@ -96,6 +100,10 @@ extension MessageService { try await failMessageAndRethrow(error, messageID: messageID) } + #if DEBUG + if let gate = inlineSendAcceptedGateForTesting { await gate() } + #endif + let ackTimeout = TimeInterval(sentInfo.suggestedTimeoutMs) / 1000.0 * 1.2 if sentInfo.expectedAck != predictedAck { @@ -118,6 +126,7 @@ extension MessageService { // end-to-end ACK or the expiry checker owns the terminal state now, // mirroring the channel send path. do { + _ = try await persistAcknowledgement(messageID: messageID, radioID: contact.radioID, pendingSendID: nil) // updateMessageAck preserves `.delivered`, so writing `.sent` here // is a no-op when the listener already won the race. try await dataStore.updateMessageAck( @@ -287,13 +296,15 @@ extension MessageService { public 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, + pendingSendID: pendingSendID ) } @@ -308,13 +319,15 @@ extension MessageService { public 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, + pendingSendID: pendingSendID ) } @@ -322,7 +335,8 @@ extension MessageService { messageID: UUID, to contact: ContactDTO, preserveTimestamp: Bool, - isResend: Bool + isResend: Bool, + pendingSendID: UUID? ) async throws -> MessageDTO { guard !inFlightRetries.contains(messageID) else { logger.warning("Send already in progress for message: \(messageID)") @@ -384,7 +398,8 @@ extension MessageService { radioID: contact.radioID, publicKey: contact.publicKey, sentInfo: sentInfo, - initialPathLength: initialPathLength + initialPathLength: initialPathLength, + pendingSendID: pendingSendID ) // Broadcast after the DB write so the downstream refetch sees both @@ -401,7 +416,8 @@ extension MessageService { pendingAcks.removeValue(forKey: messageID) throw CancellationError() } - try await failMessageAndRethrow(error, messageID: messageID) + if case MessageServiceError.persistenceError = error { throw error } + try await failMessageAndRethrow(error, messageID: messageID, pendingSendID: pendingSendID) } } @@ -659,6 +675,8 @@ extension MessageService { existing.ackCodes.insert(ackCode) existing.sentAt = Date() existing.timeout = timeout + existing.pendingSendID = nil + existing.deadline = nil pendingAcks[messageID] = existing } else { pendingAcks[messageID] = PendingAck( @@ -682,7 +700,8 @@ extension MessageService { radioID: UUID, publicKey: Data, sentInfo: MessageSentInfo?, - initialPathLength: UInt8 + 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 @@ -711,10 +730,12 @@ extension MessageService { // 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) + // The original PendingSend becomes a durable ACK owner in the same + // transaction that clears `.retrying`; a replacement or terminal row + // cannot be adopted by this send. + let movedToSent = try await persistAcknowledgement( + messageID: messageID, radioID: radioID, pendingSendID: pendingSendID + ) if movedToSent { statusEventBroadcaster.yield(.statusResolved(messageID: messageID, status: .sent, roundTripTime: nil)) } diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+SendHelpers.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendHelpers.swift index 6a328b7e48..521e2ff6f8 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendHelpers.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendHelpers.swift @@ -38,7 +38,7 @@ func withPoolBackoff( } extension MessageService { - func failMessageAndRethrow(_ error: Error, messageID: UUID) async throws -> Never { + func failMessageAndRethrow(_ error: Error, messageID: UUID, pendingSendID: UUID? = nil) async throws -> Never { pendingAcks.removeValue(forKey: messageID) // Persistence layer absorbs `.delivered`: if the listener won the race // before the throw path runs, the row stays delivered. Same invariant as @@ -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..b10f57e728 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService.swift @@ -53,14 +53,49 @@ public actor MessageService { /// can still mark the message delivered. var pendingAcks: [UUID: PendingAck] = [:] + /// Owner saves inside `persistAcknowledgement`, keyed by message. + var acknowledgementSavesInFlight: [UUID: Int] = [:] + /// Saves whose store commit has not returned. A nil-owner status write waits for that commit. + var uncommittedAcknowledgementSaves: 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 the owner row commits and before `pendingSendID` is attached. + var acknowledgementInstallGateForTesting: (@Sendable () 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 setAcknowledgementInstallGateForTesting(_ gate: (@Sendable () async -> Void)?) { + acknowledgementInstallGateForTesting = gate + } + + var acknowledgementSaveWaiterCountForTesting: Int { + acknowledgementSaveWaiters.count + } + + var inlineSendWaiterCountForTesting: Int { + inlineSendWaiters.count + } #endif /// Multicast broadcaster for outbound-message lifecycle events. @@ -75,6 +110,7 @@ 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 @@ -95,12 +131,14 @@ public actor MessageService { session: any MeshCoreSessionProtocol, dataStore: any PersistenceStoreProtocol, contactService: ContactService?, - config: MessageServiceConfig = .default + config: MessageServiceConfig = .default, + ackEvents: AsyncStream? = nil ) { self.session = session self.dataStore = dataStore self.contactService = contactService self.config = config + bufferedAckEvents = ackEvents } /// Whether a contact service was injected at construction. @@ -110,6 +148,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 +168,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,9 +192,11 @@ 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 @@ -156,9 +204,8 @@ public actor MessageService { /// 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. + /// CRC and commits that match. The entry stays until the terminal save + /// succeeds, so a thrown write can be retried with the same code. func handleAcknowledgement(code: Data, tripTime: UInt32?) async { guard let (messageID, tracking) = pendingAcks.first(where: { $0.value.ackCodes.contains(code) && !$0.value.isDelivered @@ -175,41 +222,13 @@ public actor MessageService { 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 - + pendingAcks[messageID]?.matchedAckCode = code.ackCodeUInt32 + pendingAcks[messageID]?.matchedTripTime = tripTime do { - try await dataStore.updateMessageAck( - id: messageID, - ackCode: ackCodeUInt32, - status: .delivered, - roundTripTime: tripTime - ) + _ = try await commitPendingAcknowledgement(messageID: messageID, sentAt: tracking.sentAt) } 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)") } // MARK: - Status Events 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/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..5d250bcdc9 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,12 +193,14 @@ 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) + guard !publicAdmissionRetired else { throw CancellationError() } + let meshContacts = try await capturedSession.getContacts(since: nil) config.contacts = meshContacts.map { Self.buildContactConfig(from: $0) } } @@ -203,66 +227,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,13 +352,20 @@ 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 @@ -321,15 +376,17 @@ public actor NodeConfigService { // firmware no longer intercepts ADD and would store it as a real contact). 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, @@ -359,11 +416,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 +520,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 +549,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/PendingAck.swift b/MC1Services/Sources/MC1Services/Services/PendingAck.swift index f1fa272a15..b98e534f47 100644 --- a/MC1Services/Sources/MC1Services/Services/PendingAck.swift +++ b/MC1Services/Sources/MC1Services/Services/PendingAck.swift @@ -17,4 +17,9 @@ struct PendingAck { /// so a slow high-spreading-factor round-trip is not failed while still in flight. var timeout: TimeInterval var isDelivered: Bool = false + var pendingSendID: UUID? + var deadline: Date? + /// Set when an acknowledgement matches and kept until the terminal save commits. + var matchedAckCode: UInt32? + var matchedTripTime: UInt32? } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Acknowledgements.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Acknowledgements.swift new file mode 100644 index 0000000000..ff2896feec --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Acknowledgements.swift @@ -0,0 +1,75 @@ +import Foundation +import SwiftData + +public extension PersistenceStore { + func savePendingAcknowledgement(_ dto: PendingSendDTO, replacingPendingSendID: UUID?) 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, message.status != .failed 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 + message.status = .sent + do { + 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 } + } + if row.ackDeadline != nil { modelContext.delete(row) } + do { + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + return shouldUpdate + } +} diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift index ad54daa20f..82a4e61e67 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, diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Connection.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Connection.swift new file mode 100644 index 0000000000..3464226908 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Connection.swift @@ -0,0 +1,91 @@ +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) + 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 } + 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+Devices.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Devices.swift index c922fd9355..39c02efd7d 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 @@ -397,29 +299,51 @@ 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) else { return nil } + try commitPendingRxLogEntries() + guard let radioID = try stageGhostIdentity(current: current, newPublicKey: newPublicKey) else { return nil } + try saveIdentityChanges() + return radioID + } + + /// 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 else { return nil } + guard let selfInfo else { return DeviceDTO(from: current) } + try commitPendingRxLogEntries() + do { + current.apply(DeviceDTO(from: current).updating(from: selfInfo)) + _ = try stageGhostIdentity(current: current, newPublicKey: selfInfo.publicKey) + try saveIdentityChanges() + 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 -> 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 - } - - let currentPredicate = #Predicate { device in - device.id == lookupID - } - var currentDescriptor = FetchDescriptor(predicate: currentPredicate) - currentDescriptor.fetchLimit = 1 - guard let current = try modelContext.fetch(currentDescriptor).first else { return nil } - + guard let ghost = try modelContext.fetch(ghostDescriptor).first, + !ghost.connectionMethods.contains(where: \.isBluetooth) else { return nil } let newRadioID = ghost.radioID current.radioID = newRadioID current.publicKey = newPublicKey @@ -429,12 +353,22 @@ 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 } + private func saveIdentityChanges() throws { + do { + #if DEBUG + try identityReconciliationFaultInjection?() + #endif + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } + } + /// Stages deletion of all device-scoped data without calling save(). /// Used by both `deleteDeviceData` and `deleteDeviceAndData` to compose /// operations while maintaining single-save atomicity. @@ -586,6 +520,10 @@ public extension PersistenceStore { } #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+Messages.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift index f9ae6069e6..d65ec3add3 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift @@ -437,7 +437,12 @@ public extension PersistenceStore { message.failureSeen = false } message.status = status - try modelContext.save() + do { + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } return true } @@ -533,7 +538,12 @@ public extension PersistenceStore { message.ackCode = ackCode message.status = status message.roundTripTime = roundTripTime - try modelContext.save() + do { + try modelContext.save() + } catch { + modelContext.rollback() + throw error + } } } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+PendingSends.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+PendingSends.swift index f8d3bb96d7..b4d447318b 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+PendingSends.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+PendingSends.swift @@ -36,6 +36,9 @@ public extension PersistenceStore { existing.sequence = dto.sequence existing.enqueuedAt = dto.enqueuedAt existing.attemptCount = dto.attemptCount + existing.ackCodes = dto.ackCodes + existing.ackSentAt = dto.ackSentAt + existing.ackDeadline = dto.ackDeadline } else { modelContext.insert(PendingSend(dto: dto)) } @@ -52,7 +55,10 @@ 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 + await pendingSendInsertHandler?() + #endif let scopedRadioID = dto.radioID let radioPredicate = #Predicate { row in row.radioID == scopedRadioID @@ -173,26 +179,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) @@ -329,24 +329,33 @@ public extension PersistenceStore { /// `?? 0` fallback degrades gracefully without pretending the row had /// prior drain attempts. @discardableResult - func incrementPendingSendAttemptCount(messageID: UUID) throws -> Int? { + func incrementPendingSendAttemptCount(messageID: UUID) async throws -> (pendingSendID: UUID, attemptCount: Int)? { #if DEBUG + await pendingSendAttemptHandler?() try incrementPendingSendAttemptCountFaultInjection?() #endif 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 + return (row.id, nextCount) } #if DEBUG + func setPendingSendAttemptHandler(_ handler: (@Sendable () async -> Void)?) { + pendingSendAttemptHandler = handler + } + + func setPendingSendInsertHandler(_ handler: (@Sendable () async -> Void)?) { + pendingSendInsertHandler = handler + } + func setIncrementPendingSendAttemptCountFaultInjection(_ hook: (@Sendable () throws -> Void)?) { incrementPendingSendAttemptCountFaultInjection = hook } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift index 4eca662121..aa08c0ce32 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift @@ -84,6 +84,9 @@ public actor PersistenceStore: ModelActor, PersistenceStoreProtocol { } #if DEBUG + var pendingSendInsertHandler: (@Sendable () async -> 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 @@ -196,14 +199,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() 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/RemoteNodeService+Login.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift index 1fd312cb00..486c423bc7 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift @@ -261,6 +261,7 @@ public extension RemoteNodeService { /// 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 !keepAliveAdmissionRetired else { return } stopKeepAlive(sessionID: sessionID) let interval = keepAliveIntervals[sessionID] ?? Self.defaultKeepAliveInterval @@ -324,8 +325,9 @@ public extension RemoteNodeService { /// Stop keep-alive for a session internal func stopKeepAlive(sessionID: UUID) { - keepAliveTasks[sessionID]?.cancel() - keepAliveTasks.removeValue(forKey: sessionID) + guard let worker = keepAliveTasks.removeValue(forKey: sessionID) else { return } + worker.cancel() + retiredKeepAliveTasks.append(worker) } /// Send keep-alive only if the session has a direct routing path. diff --git a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Reconnection.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Reconnection.swift index 0383227c55..399b68ab65 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Reconnection.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Reconnection.swift @@ -1,24 +1,22 @@ 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 keep-alives and publishes disconnected sessions, returning their IDs + /// so only previously connected sessions are re-authenticated after link recovery. + func handleLinkDisconnection(radioID: UUID) async -> Set { 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,14 +33,11 @@ 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 @@ -53,7 +48,7 @@ public extension RemoteNodeService { // 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,12 +57,13 @@ public extension RemoteNodeService { guard !sessionsToReauth.isEmpty else { return } - logger.info("BLE reconnection: re-authenticating \(sessionsToReauth.count) session(s)") + logger.info("Link reconnection: re-authenticating \(sessionsToReauth.count) session(s)") isReauthenticating = true defer { isReauthenticating = false } await withTaskGroup(of: Void.self) { group in for remoteSession in sessionsToReauth { + guard !Task.isCancelled else { break } group.addTask { [self] in let previousPermission = remoteSession.permissionLevel do { diff --git a/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift index f81a1ece55..46bdc95450 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift @@ -74,6 +74,9 @@ public actor RemoteNodeService { /// Keep-alive timer tasks var keepAliveTasks: [UUID: Task] = [:] + var retiredKeepAliveTasks: [Task] = [] + var keepAliveAdmissionRetired = false + private var keepAliveRetirement: Task? /// Keep-alive intervals per session (from login response, in seconds) /// Default to 90 seconds if not specified @@ -173,9 +176,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 @@ -358,6 +363,7 @@ public actor RemoteNodeService { public func stopAllKeepAlives() { for task in keepAliveTasks.values { task.cancel() + retiredKeepAliveTasks.append(task) } keepAliveTasks.removeAll() @@ -368,6 +374,19 @@ public actor RemoteNodeService { } } + func retireKeepAlives() async { + if let keepAliveRetirement { await keepAliveRetirement.value; return } + keepAliveAdmissionRetired = true + stopAllKeepAlives() + let workers = retiredKeepAliveTasks + retiredKeepAliveTasks.removeAll() + let drain = Task { for worker in workers { + await worker.value + } } + keepAliveRetirement = drain + await drain.value + } + /// Number of login continuations currently parked. Exposed for teardown tests. var pendingLoginCount: Int { pendingLogins.count diff --git a/MC1Services/Sources/MC1Services/Services/RxLogService.swift b/MC1Services/Sources/MC1Services/Services/RxLogService.swift index ab0cb1f6e7..d81448e000 100644 --- a/MC1Services/Sources/MC1Services/Services/RxLogService.swift +++ b/MC1Services/Sources/MC1Services/Services/RxLogService.swift @@ -153,11 +153,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. diff --git a/MC1Services/Sources/MC1Services/Services/SendQueue.swift b/MC1Services/Sources/MC1Services/Services/SendQueue.swift index ef9ee48069..42f38e903f 100644 --- a/MC1Services/Sources/MC1Services/Services/SendQueue.swift +++ b/MC1Services/Sources/MC1Services/Services/SendQueue.swift @@ -69,20 +69,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/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/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/SyncCoordinator+MessageHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift index 6076b606f2..ebf44facbf 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift @@ -369,6 +369,7 @@ extension SyncCoordinator { } do { + await runTestBeforeMessageSave(messageDTO) try await dependencies.dataStore.saveMessage(messageDTO) var savedDTO = messageDTO if case .channel = resolvedKind { @@ -693,9 +694,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.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator.swift index 43882abdee..6b8fd4a9bc 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator.swift @@ -251,6 +251,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 +266,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() {} 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..1ddf1a0f4b 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. /// @@ -35,6 +36,7 @@ actor BLEStateMachine: BLEStateMachineProtocol { // 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,7 +740,9 @@ 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, @@ -682,34 +751,52 @@ actor BLEStateMachine: BLEStateMachineProtocol { } 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 BLEError.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 } // 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 @@ -718,11 +805,7 @@ actor BLEStateMachine: BLEStateMachineProtocol { try Task.checkCancellation() - guard case let .connected(peripheral, _, _, _) = phase else { - throw BLEError.notConnected - } - - guard peripheral.state == .connected else { + guard case let .connected(peripheral, _, _, _) = phase, peripheral.state == .connected else { throw BLEError.notConnected } @@ -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 } @@ -752,29 +844,43 @@ actor BLEStateMachine: BLEStateMachineProtocol { 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() + } + + private func cancelWriteWaiter(id: UUID) { + guard let index = writeWaiters.firstIndex(where: { $0.id == id }) else { return } + writeWaiters.remove(at: index).continuation.resume(throwing: CancellationError()) } - /// 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 { + /// 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: BLEError.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) } - /// 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 cancelWriteWithoutResponseReadiness(id: UUID) { + guard writeWithoutResponseReadyID == id else { return } + completeWriteWithoutResponseReadiness(error: CancellationError()) + } + + func cancelUnsubmittedWrites(sessionBinding: SessionTransportBinding) { + guard writeWithoutResponseReadyBinding === sessionBinding else { return } + completeWriteWithoutResponseReadiness(error: MeshTransportError.cancelledBeforeSubmission) + } + + 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,7 +1142,7 @@ actor BLEStateMachine: BLEStateMachineProtocol { // Reset queue tracking consecutiveQueuedWrites = 0 - earliestNextWrite = .now + earliestNextWrite = operationClock.now() // Cancel pending write if let pending = pendingWriteContinuation { @@ -966,7 +1152,7 @@ actor BLEStateMachine: BLEStateMachineProtocol { // Resume all write waiters (they'll fail on the .connected check) while !writeWaiters.isEmpty { - writeWaiters.removeFirst().resume() + writeWaiters.removeFirst().continuation.resume(throwing: BLEError.notConnected) } // Get peripheral before cancelling @@ -985,31 +1171,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 +1203,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 +1272,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 +1296,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 +1343,12 @@ extension BLEStateMachine { } switch oldPhase { + case .waitingForBluetooth: + bluetoothWaitID = nil + bluetoothPowerOffGraceTask?.cancel() + bluetoothPowerOffGraceTask = nil + bluetoothPowerOffGraceID = nil + case let .connecting(_, _, timeoutTask): timeoutTask.cancel() @@ -1149,7 +1362,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 +1377,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. @@ -1176,11 +1389,11 @@ extension BLEStateMachine { } while !writeWaiters.isEmpty { - writeWaiters.removeFirst().resume() + writeWaiters.removeFirst().continuation.resume(throwing: error) } // Release a Write-Command sender parked on backpressure so it doesn't hang past the drop. - handlePeripheralReadyForWriteWithoutResponse() + resumeWriteWithoutResponseReadiness() } /// Cancels the current operation, resuming any pending continuation with an error. @@ -1313,7 +1526,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..d7447237f5 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,6 +194,13 @@ 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. @@ -157,6 +210,11 @@ actor iOSBLETransport: MeshTransport { 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 } @@ -170,24 +228,15 @@ actor iOSBLETransport: MeshTransport { 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/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..6c59937abe 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) @@ -3433,11 +3437,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/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+PendingAcknowledgements.swift b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests+PendingAcknowledgements.swift new file mode 100644 index 0000000000..058611c021 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests+PendingAcknowledgements.swift @@ -0,0 +1,36 @@ +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), 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(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) + } +} 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/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..a9dad1ed28 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerMembershipTests.swift @@ -0,0 +1,155 @@ +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() + await harness.bluetooth.simulateReconnected() + try await waitUntil("new BLE batch should attempt both retained memberships") { + await harness.bluetooth.heldLoginResultCount == 2 + } + + #expect(harness.manager.connectionState == .ready) + #expect(harness.manager.membershipBatch?.sessionIDs == [activeA.id, addedDuringRestore.id]) + #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 + } + } + } + + @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)) + } + } + + 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..2f1c41fb24 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPairingTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerPairingTests.swift @@ -403,7 +403,8 @@ struct ConnectionManagerPairingTests { manager.persistConnection(deviceID: deviceID, radioID: UUID(), deviceName: "Radio") #expect(manager.lastConnectedDeviceID == deviceID) - await manager.forgetDevice(id: deviceID) + let context = try await manager.captureRemoval(id: deviceID) + await manager.forgetDeviceAfterReset(context) // The auto-reconnect / onboarding-resume signal must not survive forgetting its own radio. #expect(manager.lastConnectedDeviceID == nil) @@ -419,7 +420,8 @@ struct ConnectionManagerPairingTests { let lastConnected = UUID() manager.persistConnection(deviceID: lastConnected, radioID: UUID(), deviceName: "Radio") - await manager.forgetDevice(id: UUID()) + let context = try await manager.captureRemoval(id: UUID()) + await manager.forgetDeviceAfterReset(context) #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..637db41290 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerResyncLoopTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerResyncLoopTests.swift @@ -12,9 +12,11 @@ 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 let session = MeshCoreSession( @@ -37,7 +39,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 +56,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 +70,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 +78,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 +92,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 +106,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 +130,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 +148,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 +169,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 +181,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 +203,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 +219,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 +231,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 +239,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 +250,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 +270,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 +293,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 +319,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 +333,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 +341,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 +356,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 +367,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) @@ -381,7 +391,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 +406,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 +416,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..77cbd17946 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalConfirmationTests.swift @@ -0,0 +1,243 @@ +#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 retains its best effort system removal policy`() 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 + let result = await env.manager.forgetDeviceAfterReset(context) + if case let .removed(receipt) = result { + #expect(env.manager.isCurrent(receipt)) + } else { + Issue.record("After a submitted factory reset, local cleanup remains best effort across system removal failure") + } + #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..c2943b98b0 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalDrainTests.swift @@ -0,0 +1,433 @@ +import Foundation +@testable import MC1Services +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 park in retirement while the admitted save is held") { + fixture.env.manager.connectionTeardownCount > 0 + } + try await fixture.observeDeletionStillPending() + #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) + var removal: Task? + var successor: Task? + do { + try await fixture.admitSentinel() + 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") { + fixture.env.manager.connectionTeardownCount > 0 + } + 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) + fixture.gate.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 { + 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 = ConfirmationGate() + var removal: Task? + var successor: Task? + do { + try await fixture.admitSentinel() + 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 retirement must park on the admitted writer") { + let dials = await fixture.env.wifi.connectCount + return fixture.env.manager.connectionRequestID != previousRequest && fixture.env.manager.connectionTeardownCount > 0 + && 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) + fixture.gate.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() + 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 = ConfirmationGate() + var removal: Task? + var successor: Task? + do { + try await fixture.admitSentinel() + 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 && fixture.env.manager.connectionTeardownCount > 0 + } + confirmation.release() + try await waitUntil("accepted confirmation must queue removal while the admitted save 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)) + fixture.gate.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.session?.getTime() != nil) + await fixture.finish() + } catch { + confirmation.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: ConfirmationGate, accessoryID: UUID) { + env.pairing.isSessionActive = true + env.pairing.setPairedAccessories([ASAccessory(bluetoothIdentifier: accessoryID, displayName: "Radio")]) + env.pairing.beforeRemovalResult = { await confirmation.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() + 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 ConfirmationGate { + 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/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/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/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..3c40baa716 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManager+BLERecoveryTesting.swift @@ -0,0 +1,37 @@ +import Foundation +@testable import MC1Services + +extension ConnectionManager { + @MainActor + @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 + } + + @MainActor + 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() } + } + + @MainActor + 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..5276c7c0b8 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManagerRadioTestHarness.swift @@ -0,0 +1,73 @@ +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 + ) throws { + self.clock = clock + self.sessionClock = sessionClock + let store = try PersistenceStore.createContainer(inMemory: true) + ble = ConnectionTestRadioTransport(publicKey: publicKey) + let wifi = ConnectionTestRadioTransport(publicKey: sameRadio ? publicKey : Data(repeating: 2, count: 32)) + 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..ca92937103 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionRadioHandoffHarness.swift @@ -0,0 +1,127 @@ +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) + try await KeychainService.shared.storePassword("synthetic-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/HydratedChannelSendHarness.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/HydratedChannelSendHarness.swift new file mode 100644 index 0000000000..3c3615351d --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/HydratedChannelSendHarness.swift @@ -0,0 +1,83 @@ +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 queue: ChatSendQueueService + let message: MessageDTO + let radioID: UUID + + private init( + store: PersistenceStore, radio: ConnectionTestRadioTransport, session: MeshCoreSession, + queue: ChatSendQueueService, message: MessageDTO, radioID: UUID + ) { + self.store = store + self.radio = radio + self.session = session + self.queue = queue + self.message = message + self.radioID = radioID + } + + static func make(clock: (any Clock)? = nil) async throws -> HydratedChannelSendHarness { + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let radio = ConnectionTestRadioTransport() + let session = MeshCoreSession( + transport: radio, configuration: SessionConfiguration(defaultTimeout: 2), clock: clock + ) + 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 queue = ChatSendQueueService( + radioID: saved.radioID, dataStore: store, + messageService: MessageService(session: session, dataStore: store, contactService: nil), + channelService: ChannelService(session: session, dataStore: store, rxLogService: nil), + reactionService: ReactionService() + ) + return HydratedChannelSendHarness(store: store, radio: radio, session: session, 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 + } + + static func channelPacket(secret: Data) -> Data { + let name = Data("Original".utf8) + return Data([ResponseCode.channelInfo.rawValue, 0]) + name + Data(repeating: 0, count: 32 - name.count) + secret + } + + var sendFrames: [Data] { + get async { await radio.sentData.filter { $0.first == CommandCode.sendChannelMessage.rawValue } } + } + + func waitForValidation() async throws { + try await waitUntil("hydrated work must reach occupancy validation or expose an unchecked send") { + if await self.radio.heldReplyCount(for: .getChannel) == 1 { return true } + return await !self.sendFrames.isEmpty + } + try #require(await radio.heldReplyCount(for: .getChannel) == 1, "A hydrated envelope reached send without validating its slot") + } + + 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/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..2fbfc11c39 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/IdentityImportPrivateRuntimeTests.swift @@ -0,0 +1,209 @@ +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(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(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..e0aafa8467 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/IdentityImportTransportFailureTests.swift @@ -0,0 +1,306 @@ +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) + 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") { + await harness.bluetooth.sentData.contains { $0.first == CommandCode.setFloodScope.rawValue } + } + if priorOutcome == .cancelledBeforeMessage { + ordinary.cancel() + await #expect(throws: CancellationError.self) { try await ordinary.value } + await harness.bluetooth.releaseReplies(for: .setFloodScope) + } 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) + 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") { + await radio.sentData.contains { $0.first == CommandCode.setFloodScope.rawValue } + } + 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() + await #expect(throws: CancellationError.self) { try await ordinary.value } + #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() + } + 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/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/Mocks/MockAccessorySetupKitService.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockAccessorySetupKitService.swift index 8c96d591bd..34ee9b613f 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockAccessorySetupKitService.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockAccessorySetupKitService.swift @@ -44,6 +44,7 @@ public final class MockAccessorySetupKitService: AccessorySetupKitServicing { /// modelling the user declining the system removal confirmation so the /// accessory stays registered. public var removeAccessoryError: Error? + public var beforeRemovalResult: (@MainActor () async -> Void)? public init() {} @@ -55,6 +56,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 +85,7 @@ public final class MockAccessorySetupKitService: AccessorySetupKitServicing { public func removeAccessory(_ accessory: ASAccessory) async throws { removeAccessoryCallCount += 1 lastRemovedDeviceID = accessory.bluetoothIdentifier + 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 87% rename from MC1Tests/Views/Tools/CLI/MockConfigurationSession.swift rename to MC1Services/Tests/MC1ServicesTests/Mocks/MockConfigurationSession.swift index d6809a38f7..a9c2769062 100644 --- a/MC1Tests/Views/Tools/CLI/MockConfigurationSession.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockConfigurationSession.swift @@ -16,9 +16,20 @@ actor MockConfigurationSession: ConfigurationSessionOps { 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 +54,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 +111,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 +321,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 +420,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 +453,9 @@ actor MockConfigurationSession: ConfigurationSessionOps { holdNextCLI = false return await parkCLI(command) } + if let reply = wiFiFirmware?.reply(to: command) { + return reply + } return dequeueCLIReply() } @@ -396,6 +471,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 +505,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 { diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift index 2000d30e1d..4d9ebfea36 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift @@ -143,6 +143,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 @@ -355,6 +356,10 @@ 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 @@ -523,6 +528,21 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps try await sendChannelMessage(channel: channel, text: text, timestamp: timestamp) } + public func sendVerifiedChannelMessage( + channel: UInt8, + text: String, + timestamp: Date, + floodScope: ResolvedFloodScope?, + expectedSecret: Data + ) async throws { + let info = try await getChannel(index: channel) + guard info.index == channel, info.secret == expectedSecret, + !info.name.isEmpty || info.secret.contains(where: { $0 != 0 }) else { + throw MeshCoreError.invalidResponse(expected: "unchanged channel occupancy", got: "different or missing channel occupancy") + } + try await sendChannelMessage(channel: channel, text: text, timestamp: timestamp) + } + public func getContacts(since lastModified: Date?) async throws -> [MeshContact] { try await getContactsReportingTotal(since: lastModified).contacts } @@ -640,6 +660,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 } 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/MockPersistenceStore.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift index 7b26d72039..bdbb5b5784 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? @@ -48,6 +49,14 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { // MARK: - Stub Configuration + public func setStubbedUpdateMessageStatusError(_ error: Error?) { + stubbedUpdateMessageStatusError = error + } + + public func setStubbedResolvePendingAcknowledgementError(_ error: Error?) { + stubbedResolvePendingAcknowledgementError = error + } + public func setStubbedFetchContactError(_ error: Error?) { stubbedFetchContactError = error } @@ -1983,107 +1992,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 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 + 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 } - body(&device) - devices[radioID] = device + devices[updated.radioID] = updated + return updated } // MARK: - Room Session State @@ -2718,12 +2634,44 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { localNodeName: dto.localNodeName, sequence: nextSequence, enqueuedAt: dto.enqueuedAt, - attemptCount: dto.attemptCount + attemptCount: dto.attemptCount, + ackCodes: dto.ackCodes, + ackSentAt: dto.ackSentAt, + ackDeadline: dto.ackDeadline ) pendingSends[dto.id] = assigned return nextSequence } + public func savePendingAcknowledgement(_ dto: PendingSendDTO, replacingPendingSendID: UUID?) async throws -> Bool { + guard var message = messages[dto.messageID], message.status != .delivered, message.status != .failed else { return false } + if let replacingPendingSendID { + guard let existing = pendingSends[replacingPendingSendID], existing.messageID == dto.messageID, + existing.ackDeadline == nil else { return false } + } else if pendingSends.values.contains(where: { $0.messageID == dto.messageID }) { + return false + } + pendingSends[dto.id] = dto + message.status = .sent + messages[dto.messageID] = message + return true + } + + public func resolvePendingAcknowledgement( + id: UUID, expectedDeadline: Date?, status: MessageStatus, ackCode: UInt32?, roundTripTime: UInt32? + ) async throws -> Bool { + 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 + return true + } + public func fetchPendingSends(radioID: UUID) async throws -> [PendingSendDTO] { pendingSends.values.filter { $0.radioID == radioID }.sorted { $0.sequence < $1.sequence } } @@ -2744,8 +2692,8 @@ 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 incrementPendingSendAttemptCount(messageID: UUID) async throws -> (pendingSendID: UUID, attemptCount: Int)? { + guard let row = pendingSends.values.first(where: { $0.messageID == messageID && $0.ackDeadline == nil }) else { return nil } let nextCount = (row.attemptCount ?? 0) + 1 pendingSends[row.id] = PendingSendDTO( id: row.id, @@ -2760,9 +2708,12 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { localNodeName: row.localNodeName, sequence: row.sequence, enqueuedAt: row.enqueuedAt, - attemptCount: nextCount + attemptCount: nextCount, + ackCodes: row.ackCodes, + ackSentAt: row.ackSentAt, + ackDeadline: row.ackDeadline ) - return nextCount + return (row.id, nextCount) } // 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/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..9440f7e13c --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/PendingAcknowledgementPersistenceTests.swift @@ -0,0 +1,217 @@ +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) + await live.service.setPendingAckForTest(PendingAck( + messageID: live.message.id, + contactID: live.contact.id, + ackCodes: Set(saved.ackCodes ?? []), + sentAt: saved.ackSentAt ?? Date(), + timeout: 1, + pendingSendID: saved.id, + deadline: saved.ackDeadline + )) + 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/PersistenceStoreTests.swift b/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift index a2fe58d736..bb2f7197e7 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 @@ -1784,7 +1784,7 @@ struct PersistenceStoreTests { try await store.upsertPendingSend(dto) let result = try await store.incrementPendingSendAttemptCount(messageID: messageID) - #expect(result == 1, "first drain attempt should bump 0 → 1") + #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") @@ -1796,7 +1796,7 @@ struct PersistenceStoreTests { 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") + #expect(result?.pendingSendID == nil, "missing-row case is terminal — return nil instead of creating a new row") } @Test 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..39b4a4be39 --- /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: "synthetic-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/ChatSendQueueHydrationOccupancyTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueHydrationOccupancyTests.swift new file mode 100644 index 0000000000..3d9520c7cb --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueHydrationOccupancyTests.swift @@ -0,0 +1,239 @@ +import Foundation +@testable import MC1Services +@testable import MeshCore +import MeshCoreTestSupport +import Testing + +@Suite("Hydrated channel occupancy") +@MainActor +struct ChatSendQueueHydrationOccupancyTests { + enum Scenario { + case reassignedBeforeSync, reassignedInBackground, reassignedAfterRecentClean, reassignedAfterRecentAttempt + case unchangedWithPartialSync + + var isReassigned: Bool { + self != .unchangedWithPartialSync + } + } + + struct HydrationSample: Sendable { + var type: TransportType + var scenario: Scenario + } + + /// Bluetooth covers each sync gate. 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: .reassignedAfterRecentClean), + HydrationSample(type: .bluetooth, scenario: .reassignedAfterRecentAttempt), + HydrationSample(type: .bluetooth, scenario: .unchangedWithPartialSync), + HydrationSample(type: .wifi, scenario: .unchangedWithPartialSync), + ] + + @Test(.timeLimit(.minutes(1)), arguments: hydrationSamples) + func `hydration validates its slot independently of full sync`(_ 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 .reassignedAfterRecentClean: + env.manager.lastCleanChannelSync = (saved.radioID, Date()) + case .reassignedAfterRecentAttempt: + env.manager.lastAttemptedChannelSync = (saved.radioID, Date()) + case .unchangedWithPartialSync: + await radio.enqueueResponsePackets(for: .getChannel, packets: [HydratedChannelSendHarness.channelPacket(secret: actualSecret)]) + await radio.enqueueResponsePackets(for: .getChannel, packets: [HydratedChannelSendHarness.channelPacket(secret: actualSecret)]) + 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 } + if scenario.isReassigned { + #expect(sends.isEmpty, "A persisted message for secret A must never be submitted to slot B") + #expect(try await !env.manager.persistenceStore.hasPendingSend(messageID: message.id)) + } else { + #expect(sends.count == 1) + let readIndex = try #require(frames.firstIndex { $0.first == CommandCode.getChannel.rawValue }) + let sendIndex = try #require(frames.firstIndex { $0.first == CommandCode.sendChannelMessage.rawValue }) + #expect(readIndex < sendIndex, "Even an unchanged slot needs a current occupancy read before replay") + #expect(try await env.manager.persistenceStore.fetchMessage(id: message.id)?.status == .sent) + } + if scenario == .reassignedInBackground || scenario == .reassignedAfterRecentClean + || scenario == .reassignedAfterRecentAttempt { + #expect(env.manager.installedLink?.usableSyncResult?.channels == .skipped) + #expect(frames.filter { $0.first == CommandCode.getChannel.rawValue }.count == 1, + "Skipped global sync must still validate and reject a reassigned slot") + } else if scenario == .unchangedWithPartialSync { + #expect(env.manager.installedLink?.usableSyncResult?.channels == .partial) + } + } catch { + await env.close() + throw error + } + await env.close() + } + + @Test(.timeLimit(.minutes(1)), arguments: [false, true], [false, true]) + func `queued sends revalidate a slot after hydration rejected its prior occupant`(isResend: Bool, slotMatches: Bool) async throws { + let harness = try await HydratedChannelSendHarness.make() + do { + await harness.radio.setChannel(index: 0, name: "Replacement", secret: HydratedChannelSendHarness.secretB) + await harness.queue.hydrate() + await harness.queue.awaitDrainCompletion() + #expect(await harness.sendFrames.isEmpty) + #expect(try await harness.store.fetchMessage(id: harness.message.id)?.status == .failed) + #expect(try await !harness.store.hasPendingSend(messageID: harness.message.id)) + let retained = try #require(try await harness.store.fetchChannel(radioID: harness.radioID, index: 0)) + #expect(retained.secret == HydratedChannelSendHarness.secretA, + "A skipped global sync leaves the original Channel available for Retry and Send Again") + + if slotMatches { + await harness.radio.setChannel(index: 0, name: "Original", secret: HydratedChannelSendHarness.secretA) + } + let message: MessageDTO + if isResend { + message = harness.message + } else { + let service = MessageService(session: harness.session, dataStore: harness.store, contactService: nil) + message = try await service.createPendingChannelMessage( + text: "New message for channel A", channelIndex: 0, radioID: harness.radioID + ) + } + let envelope = ChannelMessageEnvelope( + messageID: message.id, channelIndex: 0, isResend: isResend, + messageText: message.text, messageTimestamp: message.timestamp, localNodeName: nil + ) + try await harness.queue.enqueueChannel(envelope) + await harness.queue.awaitDrainCompletion() + + #expect(await harness.sendFrames.count == (slotMatches ? 1 : 0)) + #expect(try await harness.store.fetchMessage(id: message.id)?.status == (slotMatches ? .sent : .failed)) + #expect(try await !harness.store.hasPendingSend(messageID: message.id)) + } catch { + await harness.close() + throw error + } + await harness.close() + } + + @Test + func `unreadable occupancy preserves the pending owner and wire attempt count until retry`() async throws { + let clock = TestClock() + let harness = try await HydratedChannelSendHarness.make(clock: clock) + do { + await harness.radio.setResponsePackets(for: .getChannel, packets: [Data([ResponseCode.error.rawValue, ErrorCode.fileIOError.rawValue])]) + try await resultAdvancingMatchedSessionClock(clock, observation: { + await sessionClockObservation(radio: harness.radio, session: harness.session) + }) { + await harness.queue.hydrate() + try await waitUntil("validation must either park or finish") { + if await harness.queue.parkedDrainCountForTesting > 0 { return true } + return await (try? harness.store.hasPendingSend(messageID: harness.message.id)) == false + } + } + #expect(await harness.queue.parkedDrainCountForTesting > 0) + let pending = try #require(try await harness.store.fetchPendingSendsForMessage(messageID: harness.message.id).first) + #expect(pending.attemptCount == 0, "An occupancy read failure is not a wire-send attempt") + #expect(try await harness.store.fetchMessage(id: harness.message.id)?.status == .pending) + #expect(await harness.sendFrames.isEmpty) + + await harness.radio.setResponsePackets(for: .getChannel, packets: [HydratedChannelSendHarness.channelPacket(secret: HydratedChannelSendHarness.secretA)]) + harness.queue.transportDidOpen() + try await waitUntil("a readable matching slot must release the parked send") { + await (try? harness.store.fetchMessage(id: harness.message.id))?.status == .sent + } + await harness.queue.awaitDrainCompletion() + #expect(await harness.sendFrames.count == 1) + #expect(try await !harness.store.hasPendingSend(messageID: harness.message.id)) + #expect(try await harness.store.fetchMessage(id: harness.message.id)?.status == .sent) + } catch { + await harness.close() + throw error + } + await harness.close() + } + + @Test + func `retirement during occupancy read preserves unsent work`() async throws { + let harness = try await HydratedChannelSendHarness.make() + do { + await harness.radio.holdReplies(for: .getChannel) + await harness.queue.hydrate() + try await harness.waitForValidation() + let retirement = Task { await harness.queue.shutdown() } + try await waitUntil("retirement must revoke queue admission") { harness.queue.isRetiredForTesting } + await harness.radio.releaseReplies(for: .getChannel) + 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 `occupancy cleanup during validation prevents a stale envelope from sending`() async throws { + let harness = try await HydratedChannelSendHarness.make() + do { + await harness.radio.holdReplies(for: .getChannel) + await harness.queue.hydrate() + try await harness.waitForValidation() + try await harness.store.deleteMessagesForChannel(radioID: harness.radioID, channelIndex: 0) + await harness.radio.releaseReplies(for: .getChannel) + 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/ChatSendQueueServiceTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceTests.swift index 091c77ac9c..edd53486f5 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() @@ -280,7 +280,8 @@ struct ChatSendQueueServiceTests { await harness.queue.awaitDrainCompletion() #expect(try await harness.dataStore.fetchMessage(id: harness.messageID)?.status == .failed) - #expect(await harness.session.getChannelIndices == [0]) + #expect(await harness.session.getChannelIndices == Array(repeating: 0, count: harness.occupancyReadCount + 1)) + #expect(await harness.session.sendChannelMessageInvocations.count == harness.poolAttempts) await harness.queue.shutdown() } @@ -288,34 +289,38 @@ 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)) - #expect(await harness.session.getChannelIndices.isEmpty) + #expect(await harness.session.getChannelIndices == Array(repeating: 0, count: harness.occupancyReadCount), + "Below the threshold, only occupancy validation may read the channel") await harness.queue.shutdown() } @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 +331,8 @@ struct ChatSendQueueServiceTests { } await harness.queue.awaitDrainCompletion() - #expect(await harness.session.getChannelIndices == [0, 0]) + #expect(await harness.session.getChannelIndices == Array(repeating: 0, count: failureCap * (harness.occupancyReadCount + 1))) + #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 +344,17 @@ struct ChatSendQueueServiceTests { let session: MockMeshCoreSession let dataStore: PersistenceStore let messageID: UUID + let channel: ChannelInfo + let poolAttempts: Int + + var occupancyReadCount: Int { + 1 + poolAttempts + } + + func channelReads(endingWith error: Error) -> [Result] { + // The outer read and each serialized send read succeed before disambiguation fails. + Array(repeating: .success(channel), count: occupancyReadCount) + [.failure(error)] + } } private static func setUpChannelCapHarness( @@ -365,6 +382,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 +435,9 @@ struct ChatSendQueueServiceTests { queue: queueService, session: session, dataStore: store, - messageID: pending.id + messageID: pending.id, + channel: channelInfo, + poolAttempts: messageConfig.poolBackoff.attemptCap + 1 ) } @@ -583,14 +604,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() @@ -611,15 +632,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 } } diff --git a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKRecoveryTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKRecoveryTests.swift new file mode 100644 index 0000000000..84a4879d1d --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKRecoveryTests.swift @@ -0,0 +1,348 @@ +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 == 5) + #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(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 == 5) + 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)?.pendingSendID == 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 == 0) + #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/MessageServiceSendDMBookkeepingTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendDMBookkeepingTests.swift index 76656f6e05..4fb89dcd69 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,229 @@ 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 == 0) + + 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 thrown delivery write before the owner id is installed keeps the owner and the matched code`() async throws { + let code = Data([0xAB, 0xCD, 0xEF, 0x12]) + let harness = try await makeHarness(ackGiveUpWindow: 0, suggestedTimeoutMs: 0, code: code) + let gate = SuspendGate() + await harness.service.setAcknowledgementInstallGateForTesting { + await gate.park() + } + await harness.store.setStubbedUpdateMessageStatusError(InjectedBookkeepingError.simulated) + let send = Task { + try await harness.service.sendDirectMessage(text: "held delivery", to: harness.contact) + } + try await waitUntil("owner row is committed before the id is installed") { + guard gate.isParked else { return false } + return try await harness.store.fetchPendingSends(radioID: harness.contact.radioID).count == 1 + } + let messageID = try #require( + try await harness.store.fetchMessages(contactID: harness.contact.id, limit: 1, offset: 0).first?.id + ) + #expect(try await harness.store.fetchMessage(id: messageID)?.status == .sent) + #expect(await harness.service.pendingAckForTest(messageID)?.pendingSendID == nil) + #expect(await harness.service.pendingAckForTest(messageID)?.isDelivered == false) + + await harness.service.handleAcknowledgement(code: code, tripTime: 77) + try await waitUntil("give-up deadline has elapsed") { + guard let tracking = await harness.service.pendingAckForTest(messageID) else { return false } + let deadline = tracking.deadline ?? tracking.sentAt.addingTimeInterval(max(0, tracking.timeout)) + return Date() > deadline + } + try await harness.service.checkExpiredAcks() + + #expect(try await harness.store.fetchMessage(id: messageID)?.status == .sent) + #expect(await harness.service.pendingAckForTest(messageID)?.isDelivered == false) + #expect(await harness.service.pendingAckForTest(messageID)?.matchedAckCode == code.ackCodeUInt32) + #expect(await harness.service.pendingAckForTest(messageID)?.pendingSendID == nil) + #expect(try await harness.store.fetchPendingSends(radioID: harness.contact.radioID).count == 1) + #expect(await harness.store.updatedMessageAcks.map(\.status) == [.delivered, .delivered]) + #expect(await harness.store.updatedMessageStatuses.isEmpty) + + await harness.store.setStubbedUpdateMessageStatusError(nil) + gate.release() + let accepted = try await send.value + #expect(accepted.status == .delivered) + #expect(accepted.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)?.pendingSendID != 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)?.pendingSendID != 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.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)?.pendingSendID != 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)?.isDelivered == false) + #expect(await harness.service.pendingAckForTest(accepted.id)?.matchedAckCode == code.ackCodeUInt32) + #expect(await harness.service.pendingAckForTest(accepted.id)?.pendingSendID != 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.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 +308,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/NodeConfigRFOrderingTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/NodeConfigRFOrderingTests.swift index a3bd656acd..257c8b0231 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/NodeConfigRFOrderingTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/NodeConfigRFOrderingTests.swift @@ -16,7 +16,8 @@ struct NodeConfigRFOrderingTests { let collect = await log.collect(from: stack.settings) defer { collect.cancel() } let gate = SuspendGate() - await stack.service.setOnPostIdentityImport { + await stack.service.setIdentityImportHandler { key in + try await stack.settings.importPrivateKey(key) await gate.park() return nil } @@ -28,7 +29,7 @@ struct NodeConfigRFOrderingTests { radioID: UUID() ) } - try await waitUntil("import should reach the post-identity callback with the session idle") { + try await waitUntil("import should reach the identity-import handler with the session idle") { gate.isParked } _ = try await stack.settings.applyRadioPresetVerified(usa) @@ -96,7 +97,8 @@ struct NodeConfigRFOrderingTests { let stack = try await RFStack.make(radio: .preset(eu)) defer { stack.stop() } let gate = SuspendGate() - await stack.service.setOnPostIdentityImport { + await stack.service.setIdentityImportHandler { key in + try await stack.settings.importPrivateKey(key) await gate.park() return nil } diff --git a/MC1Services/Tests/MC1ServicesTests/Services/NodeConfigServiceTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/NodeConfigServiceTests.swift index dd9e84bda8..da044c598f 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/NodeConfigServiceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/NodeConfigServiceTests.swift @@ -518,65 +518,6 @@ struct NodeConfigServiceTests { #expect(progress.total == 10) } - // MARK: - Post-Identity Resolution Seam - - @Test - func `resolveEffectiveRadioID returns callback result when private key was imported`() async throws { - let original = UUID() - let reconciled = UUID() - let result = try await resolveEffectiveRadioID( - original: original, - didImportPrivateKey: true, - callback: { @Sendable in reconciled } - ) - #expect(result == reconciled) - } - - @Test - func `resolveEffectiveRadioID skips callback when no private key was imported`() async throws { - actor CallTracker { - var calls = 0 - func bump() { - calls += 1 - } - } - let tracker = CallTracker() - let original = UUID() - let result = try await resolveEffectiveRadioID( - original: original, - didImportPrivateKey: false, - callback: { @Sendable in - await tracker.bump() - return UUID() - } - ) - #expect(result == original) - #expect(await tracker.calls == 0, - "Callback must not fire when no private key was imported") - } - - @Test - func `resolveEffectiveRadioID returns original when callback returns nil`() async throws { - let original = UUID() - let result = try await resolveEffectiveRadioID( - original: original, - didImportPrivateKey: true, - callback: { @Sendable in nil } - ) - #expect(result == original) - } - - @Test - func `resolveEffectiveRadioID handles nil callback gracefully`() async throws { - let original = UUID() - let result = try await resolveEffectiveRadioID( - original: original, - didImportPrivateKey: true, - callback: nil - ) - #expect(result == original) - } - // MARK: - Execute orchestration seam private static let executeSections = ConfigSections( 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/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/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/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/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..75c25c333f --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLETransportHarness.swift @@ -0,0 +1,335 @@ +@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])] + 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/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..111eabb39b --- /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.importedConfig = config + 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.importedConfig = 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)] + ) + 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..939dcf545f 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() @@ -40,12 +43,15 @@ struct ChatCoordinatorRegistrySurvivalTests { @Test func `notifyDataRestored bumps servicesVersion and the next load binds a fresh coordinator`() async throws { - let appState = AppState() + 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() } - appState.connectionManager.testLastConnectedDeviceID = UUID() + let radioID = UUID() + appState.connectionManager.persistConnection(deviceID: UUID(), radioID: radioID, deviceName: "Fixture") let store = try #require(appState.offlineDataStore) - let radioID = UUID() let contact = makeForgetTestContact(radioID: radioID) try await store.saveContact(contact) try await store.saveMessage(makeForgetTestMessage( @@ -57,7 +63,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 +76,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 +92,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 +121,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 +140,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..4b6079ad91 100644 --- a/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift +++ b/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift @@ -16,10 +16,16 @@ struct ConnectionStatusLifecycleTests { } 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 +153,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 +211,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))) 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..2be2e99f34 --- /dev/null +++ b/MC1Tests/AppState/PairingRecoveryOwnershipTests.swift @@ -0,0 +1,305 @@ +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.connectionUI.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.connectionUI.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.connectionUI.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.connectionUI.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.connectionUI.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.connectionUI.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) + } + } + + 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/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..581238ba3e --- /dev/null +++ b/MC1Tests/Helpers/RetainedAdminPartitionSurface.swift @@ -0,0 +1,123 @@ +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 + ) + } + } + + 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/Services/InlineImagePrefetcherTests.swift b/MC1Tests/Services/InlineImagePrefetcherTests.swift index 530eb216bf..ed6543f0d5 100644 --- a/MC1Tests/Services/InlineImagePrefetcherTests.swift +++ b/MC1Tests/Services/InlineImagePrefetcherTests.swift @@ -656,28 +656,23 @@ private actor StubDataStore: PersistenceStoreProtocol { } func markMessageAsRead(id: UUID) async throws {} - func incrementPendingSendAttemptCount(messageID: UUID) async throws -> Int? { + func savePendingAcknowledgement(_ dto: PendingSendDTO, replacingPendingSendID: UUID?) async throws -> Bool { + false + } + + func resolvePendingAcknowledgement(id: UUID, expectedDeadline: Date?, status: MessageStatus, ackCode: UInt32?, roundTripTime: UInt32?) async throws -> Bool { + false + } + + func incrementPendingSendAttemptCount(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 } diff --git a/MC1Tests/Services/LinkPreviewCacheTests.swift b/MC1Tests/Services/LinkPreviewCacheTests.swift index 16e0eae079..1e4d645561 100644 --- a/MC1Tests/Services/LinkPreviewCacheTests.swift +++ b/MC1Tests/Services/LinkPreviewCacheTests.swift @@ -627,28 +627,23 @@ private actor MockPreviewDataStore: PersistenceStoreProtocol { } func markMessageAsRead(id: UUID) async throws {} - func incrementPendingSendAttemptCount(messageID: UUID) async throws -> Int? { + func savePendingAcknowledgement(_ dto: PendingSendDTO, replacingPendingSendID: UUID?) async throws -> Bool { + false + } + + func resolvePendingAcknowledgement(id: UUID, expectedDeadline: Date?, status: MessageStatus, ackCode: UInt32?, roundTripTime: UInt32?) async throws -> Bool { + false + } + + func incrementPendingSendAttemptCount(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 } 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/ChatTimelineFreshnessTests.swift b/MC1Tests/State/ChatTimelineFreshnessTests.swift index f4e07b09ca..a2c57d6ff8 100644 --- a/MC1Tests/State/ChatTimelineFreshnessTests.swift +++ b/MC1Tests/State/ChatTimelineFreshnessTests.swift @@ -333,11 +333,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 +359,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/SystemPairingSetupAppStateTests.swift b/MC1Tests/State/SystemPairingSetupAppStateTests.swift index 3f58311413..d7df8c493f 100644 --- a/MC1Tests/State/SystemPairingSetupAppStateTests.swift +++ b/MC1Tests/State/SystemPairingSetupAppStateTests.swift @@ -300,35 +300,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) } diff --git a/MC1Tests/ViewModels/LineOfSightViewModelTests.swift b/MC1Tests/ViewModels/LineOfSightViewModelTests.swift index c175bfb6c4..105226fae6 100644 --- a/MC1Tests/ViewModels/LineOfSightViewModelTests.swift +++ b/MC1Tests/ViewModels/LineOfSightViewModelTests.swift @@ -494,28 +494,23 @@ actor MockPersistenceStore: PersistenceStoreProtocol { } func markMessageAsRead(id: UUID) async throws {} - func incrementPendingSendAttemptCount(messageID: UUID) async throws -> Int? { + func savePendingAcknowledgement(_ dto: PendingSendDTO, replacingPendingSendID: UUID?) async throws -> Bool { + false + } + + func resolvePendingAcknowledgement(id: UUID, expectedDeadline: Date?, status: MessageStatus, ackCode: UInt32?, roundTripTime: UInt32?) async throws -> Bool { + false + } + + func incrementPendingSendAttemptCount(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 } 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/NodeConfigImportRecoveryTests.swift b/MC1Tests/ViewModels/NodeConfigImportRecoveryTests.swift new file mode 100644 index 0000000000..aab4b02c80 --- /dev/null +++ b/MC1Tests/ViewModels/NodeConfigImportRecoveryTests.swift @@ -0,0 +1,293 @@ +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.importedConfig = MeshCoreNodeConfig( + channels: [.init(name: Self.tailChannelName, secret: String(repeating: "CD", count: 16))] + ) + 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 `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.importedConfig = MeshCoreNodeConfig( + privateKey: Self.privateKey, + channels: [.init(name: Self.tailChannelName, secret: String(repeating: "CD", count: 16))] + ) + 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..7aae431fab 100644 --- a/MC1Tests/ViewModels/NodeConfigImportViewModelTests.swift +++ b/MC1Tests/ViewModels/NodeConfigImportViewModelTests.swift @@ -124,9 +124,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,7 +138,8 @@ 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 } @@ -154,11 +157,13 @@ struct NodeConfigImportViewModelTests { 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/RetainedAdminPartitionTests.swift b/MC1Tests/ViewModels/RetainedAdminPartitionTests.swift new file mode 100644 index 0000000000..9801091226 --- /dev/null +++ b/MC1Tests/ViewModels/RetainedAdminPartitionTests.swift @@ -0,0 +1,118 @@ +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 replacementSettings = switch role { + case .roomServer: appState.remoteAdminWorkspaces.room(for: retained.session).settings.helper + case .repeater: appState.remoteAdminWorkspaces.repeater(for: retained.session).settings.helper + } + let previousWorkspaceReset = replacementSettings !== retained.settings + #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 }, + 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/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..214a8675a2 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.importedConfig = 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 + ) + ) + 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/Views/Chats/ChatReconnectPopulateTests.swift b/MC1Tests/Views/Chats/ChatReconnectPopulateTests.swift index 4d18aec853..2676dd593d 100644 --- a/MC1Tests/Views/Chats/ChatReconnectPopulateTests.swift +++ b/MC1Tests/Views/Chats/ChatReconnectPopulateTests.swift @@ -137,7 +137,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(), diff --git a/MC1Tests/Views/Chats/ChatViewModelAdmissionTests.swift b/MC1Tests/Views/Chats/ChatViewModelAdmissionTests.swift index 5191297a4e..9cad93aeb3 100644 --- a/MC1Tests/Views/Chats/ChatViewModelAdmissionTests.swift +++ b/MC1Tests/Views/Chats/ChatViewModelAdmissionTests.swift @@ -975,28 +975,23 @@ private actor AdmissionStubDataStore: PersistenceStoreProtocol { } func markMessageAsRead(id: UUID) async throws {} - func incrementPendingSendAttemptCount(messageID: UUID) async throws -> Int? { + func savePendingAcknowledgement(_ dto: PendingSendDTO, replacingPendingSendID: UUID?) async throws -> Bool { + false + } + + func resolvePendingAcknowledgement(id: UUID, expectedDeadline: Date?, status: MessageStatus, ackCode: UInt32?, roundTripTime: UInt32?) async throws -> Bool { + false + } + + func incrementPendingSendAttemptCount(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 } diff --git a/MC1Tests/Views/ConnectionControlMenuTests.swift b/MC1Tests/Views/ConnectionControlMenuTests.swift new file mode 100644 index 0000000000..15b31b2396 --- /dev/null +++ b/MC1Tests/Views/ConnectionControlMenuTests.swift @@ -0,0 +1,195 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import SwiftUI +import Testing +import UIKit + +@Suite("Connection control menu", .serialized, .timeLimit(.minutes(1))) +@MainActor +struct ConnectionControlMenuTests { + private enum Layout { + static let viewport = CGRect(x: 0, y: 0, width: 390, height: 844) + static let presentationSettle = Duration.milliseconds(750) + } + + @Test(arguments: [false, true]) + func `recovery menu exports status and renders controls with standard and accessible hosting sizes`(accessibleSize: Bool) async throws { + let env = try await ConnectionLinkSwitchHarness.make() + var host: MenuHost? + do { + let original = try #require(env.manager.currentConnection) + let targetName = "Mountain Rescue Operations Relay 27" + env.manager.persistConnection(deviceID: env.device.id, radioID: env.device.radioID, deviceName: targetName) + await env.bluetooth.simulateAutoReconnecting(deviceID: env.device.id) + try await waitUntil("physical loss must publish a recovery activity") { + env.manager.currentConnection == nil && env.manager.connectionActivity?.phase == .reconnecting + } + let activity = try #require(env.manager.connectionActivity) + #expect(activity.requestID == original.requestID) + #expect(activity.targetName == targetName) + let title = L10n.Settings.BleStatus.accessibilityValue(L10n.Settings.BleStatus.accessibilityLabel, activity.accessibilityValue) + let mounted = try MenuHost(app: env.appState, accessibleSize: accessibleSize) + host = mounted + try await waitUntil("production toolbar must export target and status: \(mounted.describe())") { + mounted.nodes(in: [mounted.window]).contains { $0.label == title && $0.traits.contains(.button) } + } + let controls = mounted.nodes(in: [mounted.window]).filter { $0.label == title && $0.traits.contains(.button) } + #expect(controls.count == 1, "\(mounted.describe())") + let control = try #require(controls.first) + #expect(control.hasWindowContainedAXFrame) + try #require(mounted.openMenu(control), "Native toolbar did not accept activation: \(mounted.describe())") + let menuTitles = [activity.accessibilityValue, L10n.Settings.BleStatus.stopReconnecting, L10n.Settings.BleStatus.changeDevice] + try await waitUntil("native menu must render target, state and both controls: \(mounted.describe())") { + let nodes = mounted.nodes(in: mounted.visibleWindows) + return menuTitles.allSatisfy { title in nodes.contains { $0.label == title && $0.hasWindowContainedAXFrame } } + } + try await Task.sleep(for: Layout.presentationSettle) + let menuNodes = mounted.nodes(in: mounted.visibleWindows) + for title in [L10n.Settings.BleStatus.stopReconnecting, L10n.Settings.BleStatus.changeDevice] { + #expect(menuNodes.contains { $0.label == title && $0.traits.contains(.button) && $0.hasWindowContainedAXFrame }) + } + let header = try #require(menuNodes.first { $0.label == activity.accessibilityValue }) + let actions = menuNodes.filter { + [L10n.Settings.BleStatus.stopReconnecting, L10n.Settings.BleStatus.changeDevice].contains($0.label) + && $0.traits.contains(.button) + } + #expect(actions.allSatisfy { !header.frame.intersects($0.frame) }) + Attachment.record(Data(mounted.describe().utf8), named: "connection-menu-accessibility-tree.txt") + let stop = try #require(menuNodes.first { $0.label == L10n.Settings.BleStatus.stopReconnecting && $0.traits.contains(.button) }) + let change = try #require(menuNodes.first { $0.label == L10n.Settings.BleStatus.changeDevice && $0.traits.contains(.button) }) + #expect(stop.window === change.window) + #expect(stop.frame.minY < change.frame.minY, "Stopping the current request must precede changing devices") + let sizes = [ + "application: \(UIApplication.shared.preferredContentSizeCategory.rawValue)", + "nativeMenuWindow: \(stop.window.traitCollection.preferredContentSizeCategory.rawValue)", + "accessibleHostingOverride: \(accessibleSize)" + ].joined(separator: "\n") + Attachment.record(Data(sizes.utf8), named: "connection-menu-content-sizes.txt") + var didDraw = false + let image = UIGraphicsImageRenderer(bounds: stop.window.bounds).image { _ in + didDraw = stop.window.drawHierarchy(in: stop.window.bounds, afterScreenUpdates: true) + } + #expect(didDraw) + let name = accessibleSize ? "connection-menu-accessibility5.png" : "connection-menu-standard.png" + try Attachment.record(#require(image.pngData()), named: name) + } catch { + host?.close() + await env.close() + throw error + } + host?.close() + await env.close() + } + + @MainActor + private final class MenuHost { + let window: UIWindow + private let scene: UIWindowScene + private let previousKeyWindow: UIWindow? + + init(app: AppState, accessibleSize: Bool) throws { + let selectedScene = try #require(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) + scene = selectedScene + previousKeyWindow = selectedScene.windows.first(where: \.isKeyWindow) + let root = NavigationStack { + Text("Connection menu fixture") + .toolbar { ToolbarItem(placement: .topBarLeading) { BLEStatusIndicatorView() } } + } + .environment(\.appState, app) + .environment(\.dynamicTypeSize, accessibleSize ? .accessibility5 : .large) + let controller = UIHostingController(rootView: root) + controller.traitOverrides.preferredContentSizeCategory = accessibleSize + ? UIContentSizeCategory.accessibilityExtraExtraExtraLarge : UIContentSizeCategory.large + window = UIWindow(windowScene: scene) + window.frame = Layout.viewport + window.rootViewController = controller + controller.view.frame = window.bounds + window.makeKeyAndVisible() + window.layoutIfNeeded() + } + + var visibleWindows: [UIWindow] { + scene.windows.filter { !$0.isHidden && $0.alpha > 0 } + } + + func close() { + window.rootViewController?.dismiss(animated: false) + window.rootViewController = nil + window.isHidden = true + window.windowScene = nil + previousKeyWindow?.makeKeyAndVisible() + } + + func describe() -> String { + nodes(in: visibleWindows).map { node in + "[\(node.label) traits=\(node.traits.rawValue) type=\(type(of: node.object)) frame=\(node.frame)]" + }.joined(separator: " ") + } + + func openMenu(_ node: AccessNode) -> Bool { + var ancestor = node.object as? UIView + while let view = ancestor { + if let control = view as? UIControl, control.isEnabled { + control.performPrimaryAction() + return true + } + ancestor = view.superview + } + if node.object.accessibilityActivate() { return true } + let center = CGPoint(x: node.frame.midX, y: node.frame.midY) + guard let control = controls(in: node.window).first(where: { + $0.showsMenuAsPrimaryAction && $0.convert($0.bounds, to: nil).contains(center) + }) else { return false } + control.performPrimaryAction() + return true + } + + private func controls(in view: UIView) -> [UIControl] { + guard !view.isHidden, view.alpha > 0 else { return [] } + return ((view as? UIControl).map { [$0] } ?? []) + view.subviews.flatMap { controls(in: $0) } + } + + func nodes(in windows: [UIWindow]) -> [AccessNode] { + var result: [AccessNode] = [] + var seen = Set() + func visit(_ object: NSObject, in owner: UIWindow) { + guard seen.insert(ObjectIdentifier(object)).inserted else { return } + if let view = object as? UIView, view.isHidden || view.accessibilityElementsHidden { return } + let count = object.accessibilityElementCount() + let label = object.accessibilityLabel ?? "" + if object.isAccessibilityElement, !label.isEmpty { + result.append(AccessNode(object: object, window: owner, label: label, traits: object.accessibilityTraits, frame: object.accessibilityFrame)) + } + if count != NSNotFound, count > 0 { + for index in 0.. 0 { + visit(child, in: owner) + } + } + } + windows.forEach { visit($0, in: $0) } + return result + } + } + + @MainActor + private struct AccessNode { + let object: NSObject + let window: UIWindow + let label: String + let traits: UIAccessibilityTraits + let frame: CGRect + + var hasWindowContainedAXFrame: Bool { + !frame.isEmpty && window.convert(window.bounds, to: nil).contains(frame) + } + } +} diff --git a/MC1Tests/Views/NodeAuthenticationSourcePresentationTests.swift b/MC1Tests/Views/NodeAuthenticationSourcePresentationTests.swift new file mode 100644 index 0000000000..867d48e96c --- /dev/null +++ b/MC1Tests/Views/NodeAuthenticationSourcePresentationTests.swift @@ -0,0 +1,185 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import OSLog +import SwiftUI +import Testing +import UIKit +import Vision + +@Suite("Node authentication external native source smoke", .serialized) +@MainActor +struct NodeAuthenticationSourcePresentationTests { + @Test(.enabled(if: UserDefaults.standard.bool(forKey: Smoke.preferenceKey), "Requires external native interaction"), + arguments: Mode.allCases) + func `retained authentication uses only its admitted source`(mode: Mode) async throws { + let env = try await ConnectionLinkSwitchHarness.make(live: .wifi, wifiHost: Smoke.host) + guard let original = env.manager.currentConnection else { throw FixtureError.noSource } + let vault = original.services.remoteNodeService + let key = Data(UUID().uuidString.utf8.prefix(ProtocolLimits.publicKeySize)) + let ghost = env.device.copy { + $0.id = UUID(); $0.radioID = UUID(); $0.publicKey = Self.canonicalKey + $0.isActive = false; $0.connectionMethods = [] + } + var host: SettingsTabHarness? + var caught: (any Error)? + do { + await env.bluetooth.setConnectError(nil) + await env.wifi.setConnectError(nil) + try await env.manager.persistenceStore.saveDevice(ghost) + if mode == .current { try await adoptGhost(in: env, expectedRadioID: ghost.radioID) } + let contact = makeContact(radioID: mode == .current ? ghost.radioID : original.device.radioID, key: key) + guard let setupSource = env.manager.currentConnection else { throw FixtureError.noSource } + try await setupSource.services.contactService.addOrUpdateContact( + radioID: contact.radioID, contact: contact.toContactFrame() + ) + try await vault.storePassword(Smoke.password, forNodeKey: key) + let harness = try SettingsTabHarness.make(connected: false, injectedAppState: env.appState) + host = harness + var prepared = false + var successes = 0 + let sheet = NodeAuthenticationSheet(contact: contact, role: .repeater) { _ in successes += 1 } + .environment(\.appState, env.appState) + let root = VStack(spacing: 0) { + sheet + Button("Fixture prepared") { prepared = true }.accessibilityIdentifier("auth-source-fixture-prepared") + } + harness.window.rootViewController = UIHostingController(rootView: root) + harness.window.makeKeyAndVisible() + logger.notice("MC1NodeAuthUISmoke prepare mode=\(mode.rawValue, privacy: .public): flood on, remember off, then Fixture prepared") + try await waitUntil { prepared } + if mode == .foreign { + try await adoptGhost(in: env, expectedRadioID: ghost.radioID) + try await env.manager.persistenceStore.saveContact(makeContact(radioID: ghost.radioID, key: key)) + } + if mode.isHeld { await env.wifi.holdLoginResults() } + let start = await env.wifi.sentData.count + logger.notice("MC1NodeAuthUISmoke connect-ready mode=\(mode.rawValue, privacy: .public): tap actual Connect once") + if mode.isHeld { + try await waitUntil { await env.wifi.heldLoginResultCount > 0 } + let originalLoginEntered = await vault.pendingLoginCount == 1 + try #require(originalLoginEntered) + #expect(successes == 0) + logger.notice("MC1NodeAuthUISmoke admitted mode=\(mode.rawValue, privacy: .public)") + if mode == .heldSamePartition { + _ = try await env.manager.connectViaWiFi(host: Smoke.host, port: ConnectionMethod.defaultWiFiPort) + } else { try await adoptGhost(in: env, expectedRadioID: ghost.radioID) } + let live = env.manager.currentConnection + let replacedGeneration = live.map { $0.generation != original.generation } ?? false + let expectedPartition = live?.device.radioID == (mode == .heldSamePartition ? original.device.radioID : ghost.radioID) + #expect(replacedGeneration) + #expect(expectedPartition) + let pendingWasRetired = await vault.pendingLoginCount == 0 + #expect(pendingWasRetired) + let replacementStart = await env.wifi.sentData.count + await env.wifi.releaseLoginResults() + let settledCountdown = countdown(in: harness.window) + try await Task.sleep(for: Smoke.countdownProbe) + let laterCountdown = countdown(in: harness.window) + let noLateCountdownUpdate = laterCountdown == settledCountdown + #expect(noLateCountdownUpdate) + let staleErrorVisible = visible(RemoteNodeError.cancelled.userFacingMessage, on: harness) + || visible(L10n.RemoteNodes.RemoteNodes.Status.requestTimedOut, on: harness) + #expect(staleErrorVisible == false) + #expect(successes == 0) + let replacementFrames = await env.wifi.sentData.dropFirst(replacementStart) + let noReplacementAuth = !replacementFrames.contains { Self.authCodes.contains($0.first ?? 0xFF) } + #expect(noReplacementAuth) + } else { + try await waitUntil { + successes > 0 || visible(RemoteNodeError.notConnected.userFacingMessage, on: harness) + } + let frames = await env.wifi.sentData.dropFirst(start) + let resets = frames.filter { $0.first == CommandCode.resetPath.rawValue }.count + let logins = frames.filter { $0.first == CommandCode.sendLogin.rawValue }.count + #expect(resets == (mode == .current ? 1 : 0)) + #expect(logins == (mode == .current ? 1 : 0)) + #expect(successes == (mode == .current ? 1 : 0)) + let savedContact = try await env.manager.persistenceStore.fetchContact(radioID: ghost.radioID, publicKey: key) + let pathMatchesExpected = savedContact.map { $0.isFloodRouted == (mode == .current) } ?? false + #expect(pathMatchesExpected) + } + let admittedContactSurvived = try await env.manager.persistenceStore.fetchContact( + radioID: contact.radioID, publicKey: key + ) != nil + #expect(admittedContactSurvived) + let passwordPreserved = await vault.retrievePassword(forContact: contact) == Smoke.password + #expect(passwordPreserved == (mode != .current)) + let sessions = try await env.manager.persistenceStore.fetchRemoteNodeSessions(radioID: ghost.radioID) + let connectedCount = sessions.filter { $0.publicKey == key && $0.isConnected }.count + #expect(connectedCount == (mode == .current ? 1 : 0)) + let time = try await env.manager.session?.getTime() + let laterIOWorks = (time?.timeIntervalSince1970 ?? 0) > 0 + #expect(laterIOWorks) + logger.notice("MC1NodeAuthUISmoke settled mode=\(mode.rawValue, privacy: .public) successCount=\(successes, privacy: .public)") + } catch { caught = error } + host?.tearDown() + await env.wifi.releaseAllGates() + await env.bluetooth.releaseAllGates() + try? await vault.deletePassword(forContact: makeContact(radioID: original.device.radioID, key: key)) + await env.close() + if let caught { throw caught } + } + + private func adoptGhost(in env: ConnectionLinkSwitchHarness, expectedRadioID: UUID) async throws { + guard let source = env.manager.currentConnection else { throw FixtureError.noSource } + await env.wifi.setIdentityImportPublicKey(Self.canonicalKey) + try await source.services.nodeConfigService.importConfig( + MeshCoreNodeConfig(privateKey: Self.privateKey), sections: ConfigSections(nodeIdentity: true), radioID: source.device.radioID + ) + let adoptedCanonicalPartition = env.manager.currentConnection?.device.radioID == expectedRadioID + try #require(adoptedCanonicalPartition) + } + + private func visible(_ text: String, on host: SettingsTabHarness) -> Bool { + host.labels(in: host.window).contains { $0.contains(text) } || !host.windowRects(matching: text).isEmpty + } + + private func countdown(in window: UIWindow) -> String? { + let image = UIGraphicsImageRenderer(bounds: window.bounds).image { window.layer.render(in: $0.cgContext) } + guard let pixels = image.cgImage else { return nil } + let request = VNRecognizeTextRequest() + request.recognitionLevel = .accurate + try? VNImageRequestHandler(cgImage: pixels, options: [:]).perform([request]) + let words = request.results?.compactMap { $0.topCandidates(1).first?.string } ?? [] + return (1...Smoke.maximumCountdown).map { L10n.RemoteNodes.RemoteNodes.Auth.secondsRemaining($0) } + .first { words.contains($0) } + } + + private func makeContact(radioID: UUID, key: Data) -> ContactDTO { + ContactDTO( + id: UUID(), radioID: radioID, publicKey: key, name: "Native retained auth", typeRawValue: ContactType.repeater.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 + ) + } + + enum Mode: String, CaseIterable, Sendable { + case foreign, current, heldForeign, heldSamePartition + var isHeld: Bool { + self == .heldForeign || self == .heldSamePartition + } + } + + private enum FixtureError: Error { case noSource, interactionTimedOut } + private enum Smoke { + nonisolated static let preferenceKey = "MC1NodeAuthUISmoke" + static let host = "source.local" + static let password = "synthetic-auth" + static let interactionTimeout: Duration = .seconds(120) + static let poll: Duration = .milliseconds(100) + static let countdownProbe: Duration = .milliseconds(1100) + static let maximumCountdown = 120 + } + + private let logger = Logger(subsystem: "com.mc1.tests", category: "NodeAuthUISmoke") + private static let authCodes = [CommandCode.resetPath.rawValue, CommandCode.sendLogin.rawValue] + private static 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 + ]) + private static let privateKey = "7065e18fd9fabb70c1ed90dca19907de698c88b709ea146eafd93d9b830c7b60" + + "c4681193c79bbc39945ba8064104bb618f8fd7a84a0af6f57033d6e8ddcd6471" +} diff --git a/MC1Tests/Views/NodesContactRefreshTests.swift b/MC1Tests/Views/NodesContactRefreshTests.swift index e4bf1b6a7d..0b44f0bf90 100644 --- a/MC1Tests/Views/NodesContactRefreshTests.swift +++ b/MC1Tests/Views/NodesContactRefreshTests.swift @@ -33,12 +33,12 @@ struct NodesContactRefreshTests { appState.connectionManager.persistConnection(deviceID: device.id, radioID: radioID, deviceName: device.nodeName) let session = MeshCoreSession(transport: MockTransport()) let services = ServiceContainer(session: session, dataStore: store, radioID: radioID) - appState.connectionManager.setTestState(connectionState: .ready, services: services, connectedDevice: device) + appState.connectionManager.setTestState(connectionState: .ready, services: services, session: session, connectedDevice: device) let key = Data(repeating: 0x42, count: ProtocolLimits.publicKeySize) let inserted = try await store.saveContact(radioID: radioID, from: frame(key, favorite: false)) let contact = try #require(try await store.fetchContact(id: inserted.id)) appState.navigation.selectedTab = AppTab.nodes.rawValue - appState.wireSyncDataEvents(services: services) + try appState.wireSyncDataEvents(snapshot: #require(appState.connectionManager.currentConnection)) appState.navigation.navigateToContactDetail(contact) let revision = appState.navigation.nodesPresentationRevision diff --git a/MC1Tests/Views/RegionDiscoveryStateTests+Support.swift b/MC1Tests/Views/RegionDiscoveryStateTests+Support.swift index 756df36fd5..371113fee6 100644 --- a/MC1Tests/Views/RegionDiscoveryStateTests+Support.swift +++ b/MC1Tests/Views/RegionDiscoveryStateTests+Support.swift @@ -2,6 +2,7 @@ import Foundation @testable import MC1 @testable import MC1Services import MeshCore +import Testing extension RegionDiscoveryStateTests { @MainActor @@ -60,17 +61,31 @@ extension RegionDiscoveryStateTests { let sessions: SessionBox private let defaults: UserDefaults private let suiteName: String + private var containers: [ServiceContainer] = [] + private var ownedSessions: [MeshCoreSession] = [] + private var startups: [Task] = [] - init() throws { + init() async throws { suiteName = "region-discovery-\(UUID().uuidString)" guard let defaults = UserDefaults(suiteName: suiteName) else { throw DiscoveryFixtureError.defaultsUnavailable } defaults.removePersistentDomain(forName: suiteName) self.defaults = defaults - appState = AppState(defaults: defaults) + let modelContainer = try PersistenceStore.createContainer(inMemory: true) + let manager = ConnectionManager( + modelContainer: modelContainer, defaults: defaults, stateMachine: MockBLEStateMachine(), transport: MockMeshTransport() + ) + appState = AppState( + modelContainer: modelContainer, isPlaceholder: true, defaults: defaults, injectedConnectionManager: manager + ) sessions = SessionBox(MeshCoreSession(transport: MockTransport())) - install(device: device()) + do { + try await install(device: device()) + } catch { + await tearDown() + throw error + } let box = sessions let state = appState owner.configure( @@ -83,18 +98,29 @@ extension RegionDiscoveryStateTests { ) } - func install(device: DeviceDTO) { + func install(device: DeviceDTO) async throws { + let store = appState.connectionManager.persistenceStore + try await store.saveDevice(device) + let services = ServiceContainer(session: sessions.session, dataStore: store, radioID: device.radioID) + containers.append(services) appState.connectionManager.setTestState( connectionState: .ready, - services: .some(nil), + services: .some(services), session: .some(sessions.session), - connectedDevice: .some(device) + connectedDevice: .some(device), + currentTransportType: .bluetooth, + connectionIntent: .wantsConnection() ) } - func replaceSession() { + func replaceSession() async throws { sessions.session = MeshCoreSession(transport: MockTransport()) - appState.connectionManager.setTestState(session: .some(sessions.session)) + try await install(device: #require(appState.connectedDevice)) + } + + func own(session: MeshCoreSession, startup: Task) { + ownedSessions.append(session) + startups.append(startup) } func device( @@ -143,12 +169,36 @@ extension RegionDiscoveryStateTests { } } - func tearDown() { + func tearDown() async { + owner.setWorkflowActive(false) + startups.forEach { $0.cancel() } + for session in ownedSessions { + await session.stop() + } + for startup in startups { + _ = await startup.result + } + await appState.disconnect(reason: .userInitiated) + for container in containers { + await container.tearDown() + await container.session.stop() + } appState.shutdown() defaults.removePersistentDomain(forName: suiteName) } } + func withFixture(_ body: @MainActor (DiscoveryFixture) async throws -> Void) async throws { + let fixture = try await DiscoveryFixture() + do { + try await body(fixture) + } catch { + await fixture.tearDown() + throw error + } + await fixture.tearDown() + } + enum Wait { static let yieldLimit = 50 } diff --git a/MC1Tests/Views/RegionDiscoveryStateTests.swift b/MC1Tests/Views/RegionDiscoveryStateTests.swift index 7d944e4936..e83b9e64b7 100644 --- a/MC1Tests/Views/RegionDiscoveryStateTests.swift +++ b/MC1Tests/Views/RegionDiscoveryStateTests.swift @@ -10,258 +10,257 @@ import Testing struct RegionDiscoveryStateTests { @Test func `configuration publishes regions observed before providers were installed`() async throws { - let fixture = try DiscoveryFixture() - defer { fixture.tearDown() } - fixture.install(device: fixture.device(regions: ["North", "South"])) - let owner = RegionDiscoveryState() - let state = fixture.appState - let sessions = fixture.sessions + try await withFixture { fixture in + try await fixture.install(device: fixture.device(regions: ["North", "South"])) + let owner = RegionDiscoveryState() + let state = fixture.appState + let sessions = fixture.sessions - await confirmation("Initial region reader is invalidated") { changed in - let initial = withObservationTracking { - owner.knownRegions - } onChange: { - changed() - } - #expect(initial.isEmpty) + await confirmation("Initial region reader is invalidated") { changed in + let initial = withObservationTracking { + owner.knownRegions + } onChange: { + changed() + } + #expect(initial.isEmpty) - owner.configure( - session: { sessions.session }, - contactService: { nil }, - connectedDevice: { state.connectedDevice }, - connectionState: { state.connectionState }, - connectionManager: state.connectionManager, - dataStore: nil - ) - #expect(owner.knownRegions == ["North", "South"]) + owner.configure( + session: { sessions.session }, + contactService: { nil }, + connectedDevice: { state.connectedDevice }, + connectionState: { state.connectionState }, + connectionManager: state.connectionManager, + dataStore: nil + ) + #expect(owner.knownRegions == ["North", "South"]) + } } } @Test func `advanced and regions share one run and live regions`() async throws { - let fixture = try DiscoveryFixture() - defer { fixture.tearDown() } - let owner = fixture.owner - fixture.install(device: fixture.device(regions: ["South"])) - owner.setWorkflowActive(true) - #expect(owner.knownRegions == ["South"]) + try await withFixture { fixture in + let owner = fixture.owner + try await fixture.install(device: fixture.device(regions: ["South"])) + owner.setWorkflowActive(true) + #expect(owner.knownRegions == ["South"]) - owner.discover = { .noRepeatersResponded } - owner.start() - await fixture.flush() - #expect(owner.isDiscovering == false) - #expect(owner.discoveryMessage == L10n.Chats.Chats.ChannelInfo.Region.noRepeatersResponded) + owner.discover = { .noRepeatersResponded } + owner.start() + await fixture.flush() + #expect(owner.isDiscovering == false) + #expect(owner.discoveryMessage == L10n.Chats.Chats.ChannelInfo.Region.noRepeatersResponded) - fixture.install(device: fixture.device(regions: ["North", "South"])) - owner.noteRegionsChanged() - #expect(owner.knownRegions == ["North", "South"]) - #expect(owner.discoveryMessage == L10n.Chats.Chats.ChannelInfo.Region.noRepeatersResponded) + try await fixture.install(device: fixture.device(regions: ["North", "South"])) + owner.noteRegionsChanged() + #expect(owner.knownRegions == ["North", "South"]) + #expect(owner.discoveryMessage == L10n.Chats.Chats.ChannelInfo.Region.noRepeatersResponded) + } } @Test func `leaving retains completed feedback`() async throws { - let fixture = try DiscoveryFixture() - defer { fixture.tearDown() } - let calls = CallCount() - fixture.owner.discover = { - calls.count += 1 - return .errorLoadingRepeaters + try await withFixture { fixture in + let calls = CallCount() + fixture.owner.discover = { + calls.count += 1 + return .errorLoadingRepeaters + } + fixture.owner.setWorkflowActive(true) + fixture.owner.start() + await fixture.flush() + let message = fixture.owner.discoveryMessage + fixture.owner.setWorkflowActive(false) + fixture.owner.setWorkflowActive(true) + await fixture.flush() + #expect(calls.count == 1) + #expect(fixture.owner.discoveryMessage == message) + #expect(message == L10n.Chats.Chats.ChannelInfo.Region.errLoadingRepeaters) + #expect(fixture.owner.isDiscovering == false) } - fixture.owner.setWorkflowActive(true) - fixture.owner.start() - await fixture.flush() - let message = fixture.owner.discoveryMessage - fixture.owner.setWorkflowActive(false) - fixture.owner.setWorkflowActive(true) - await fixture.flush() - #expect(calls.count == 1) - #expect(fixture.owner.discoveryMessage == message) - #expect(message == L10n.Chats.Chats.ChannelInfo.Region.errLoadingRepeaters) - #expect(fixture.owner.isDiscovering == false) } @Test func `newer run keeps busy when the older result arrives first`() async throws { - let fixture = try DiscoveryFixture() - defer { fixture.tearDown() } - let gate = DiscoveryGate() - defer { gate.resumeAll(.sendFailed) } - fixture.owner.discover = { await gate.wait() } - fixture.owner.setWorkflowActive(true) - fixture.owner.start() - #expect(await gate.untilWaiting(1)) - fixture.owner.start() - #expect(await gate.untilWaiting(2)) + try await withFixture { fixture in + let gate = DiscoveryGate() + defer { gate.resumeAll(.sendFailed) } + fixture.owner.discover = { await gate.wait() } + fixture.owner.setWorkflowActive(true) + fixture.owner.start() + #expect(await gate.untilWaiting(1)) + fixture.owner.start() + #expect(await gate.untilWaiting(2)) - gate.resumeFirst(.completed(newRegions: ["Old"], allRepeatersTableFull: false)) - await fixture.flush() - #expect(fixture.owner.isDiscovering) - #expect(fixture.owner.knownRegions.contains("Old") == false) + gate.resumeFirst(.completed(newRegions: ["Old"], allRepeatersTableFull: false)) + await fixture.flush() + #expect(fixture.owner.isDiscovering) + #expect(fixture.owner.knownRegions.contains("Old") == false) - gate.resumeFirst(.noRepeatersResponded) - await fixture.flush() - #expect(fixture.owner.isDiscovering == false) - #expect(fixture.owner.discoveryMessage == L10n.Chats.Chats.ChannelInfo.Region.noRepeatersResponded) - #expect(fixture.owner.knownRegions.contains("Old") == false) + gate.resumeFirst(.noRepeatersResponded) + await fixture.flush() + #expect(fixture.owner.isDiscovering == false) + #expect(fixture.owner.discoveryMessage == L10n.Chats.Chats.ChannelInfo.Region.noRepeatersResponded) + #expect(fixture.owner.knownRegions.contains("Old") == false) + } } @Test func `older result does not replace A finished newer run`() async throws { - let fixture = try DiscoveryFixture() - defer { fixture.tearDown() } - let gate = DiscoveryGate() - defer { gate.resumeAll(.sendFailed) } - fixture.owner.discover = { await gate.wait() } - fixture.owner.setWorkflowActive(true) - fixture.owner.start() - #expect(await gate.untilWaiting(1)) - fixture.owner.start() - #expect(await gate.untilWaiting(2)) + try await withFixture { fixture in + let gate = DiscoveryGate() + defer { gate.resumeAll(.sendFailed) } + fixture.owner.discover = { await gate.wait() } + fixture.owner.setWorkflowActive(true) + fixture.owner.start() + #expect(await gate.untilWaiting(1)) + fixture.owner.start() + #expect(await gate.untilWaiting(2)) - gate.resumeLast(.completed(newRegions: ["New"], allRepeatersTableFull: false)) - await fixture.flush() - #expect(fixture.owner.knownRegions == ["New"]) - #expect(fixture.owner.isDiscovering == false) + gate.resumeLast(.completed(newRegions: ["New"], allRepeatersTableFull: false)) + await fixture.flush() + #expect(fixture.owner.knownRegions == ["New"]) + #expect(fixture.owner.isDiscovering == false) - gate.resumeFirst(.completed(newRegions: ["Old"], allRepeatersTableFull: false)) - await fixture.flush() - #expect(fixture.owner.knownRegions == ["New"]) - #expect(fixture.owner.discoveryMessage == nil) + gate.resumeFirst(.completed(newRegions: ["Old"], allRepeatersTableFull: false)) + await fixture.flush() + #expect(fixture.owner.knownRegions == ["New"]) + #expect(fixture.owner.discoveryMessage == nil) + } } @Test func `cancelled run does not publish or mutate`() async throws { - let fixture = try DiscoveryFixture() - defer { fixture.tearDown() } - let gate = DiscoveryGate() - defer { gate.resumeAll(.sendFailed) } - fixture.owner.discover = { await gate.wait() } - fixture.owner.setWorkflowActive(true) - fixture.owner.start() - #expect(await gate.untilWaiting(1)) - fixture.owner.setWorkflowActive(false) - #expect(fixture.owner.isDiscovering == false) - gate.resumeFirst(.completed(newRegions: ["Late"], allRepeatersTableFull: false)) - await fixture.flush() - #expect(fixture.owner.knownRegions.isEmpty) - #expect(fixture.owner.discoveryMessage == nil) - fixture.owner.addKnownRegion("Manual") - #expect(fixture.owner.knownRegions.contains("Manual") == false) + try await withFixture { fixture in + let gate = DiscoveryGate() + defer { gate.resumeAll(.sendFailed) } + fixture.owner.discover = { await gate.wait() } + fixture.owner.setWorkflowActive(true) + fixture.owner.start() + #expect(await gate.untilWaiting(1)) + fixture.owner.setWorkflowActive(false) + #expect(fixture.owner.isDiscovering == false) + gate.resumeFirst(.completed(newRegions: ["Late"], allRepeatersTableFull: false)) + await fixture.flush() + #expect(fixture.owner.knownRegions.isEmpty) + #expect(fixture.owner.discoveryMessage == nil) + fixture.owner.addKnownRegion("Manual") + #expect(fixture.owner.knownRegions.contains("Manual") == false) + } } @Test func `radio or session replacement drops the run`() async throws { - let fixture = try DiscoveryFixture() - defer { fixture.tearDown() } - let gate = DiscoveryGate() - defer { gate.resumeAll(.sendFailed) } - fixture.owner.discover = { await gate.wait() } - fixture.owner.setWorkflowActive(true) - fixture.owner.start() - #expect(await gate.untilWaiting(1)) + try await withFixture { fixture in + let gate = DiscoveryGate() + defer { gate.resumeAll(.sendFailed) } + fixture.owner.discover = { await gate.wait() } + fixture.owner.setWorkflowActive(true) + fixture.owner.start() + #expect(await gate.untilWaiting(1)) - fixture.install(device: fixture.device(radioID: UUID(), regions: [])) - fixture.owner.noteConnectionChanged() - #expect(fixture.owner.isDiscovering == false) - gate.resumeAll(.completed(newRegions: ["Moved"], allRepeatersTableFull: false)) - await fixture.flush() - #expect(fixture.owner.knownRegions.contains("Moved") == false) + try await fixture.install(device: fixture.device(radioID: UUID(), regions: [])) + fixture.owner.noteConnectionChanged() + #expect(fixture.owner.isDiscovering == false) + gate.resumeAll(.completed(newRegions: ["Moved"], allRepeatersTableFull: false)) + await fixture.flush() + #expect(fixture.owner.knownRegions.contains("Moved") == false) - fixture.replaceSession() - fixture.owner.noteConnectionChanged() - fixture.owner.start() - #expect(await gate.untilWaiting(1)) - fixture.replaceSession() - fixture.owner.noteConnectionChanged() - #expect(fixture.owner.isDiscovering == false) - gate.resumeFirst(.completed(newRegions: ["Stale"], allRepeatersTableFull: false)) - await fixture.flush() - #expect(fixture.owner.knownRegions.contains("Stale") == false) - #expect(fixture.owner.isDiscovering == false) + try await fixture.replaceSession() + fixture.owner.noteConnectionChanged() + fixture.owner.start() + #expect(await gate.untilWaiting(1)) + try await fixture.replaceSession() + fixture.owner.noteConnectionChanged() + #expect(fixture.owner.isDiscovering == false) + gate.resumeFirst(.completed(newRegions: ["Stale"], allRepeatersTableFull: false)) + await fixture.flush() + #expect(fixture.owner.knownRegions.contains("Stale") == false) + #expect(fixture.owner.isDiscovering == false) + } } @Test func `same radio snapshot keeps the run`() async throws { - let fixture = try DiscoveryFixture() - defer { fixture.tearDown() } - let gate = DiscoveryGate() - defer { gate.resumeAll(.sendFailed) } - fixture.owner.discover = { await gate.wait() } - fixture.owner.setWorkflowActive(true) - fixture.owner.start() - #expect(await gate.untilWaiting(1)) - fixture.install(device: fixture.device(name: "Field", regions: [])) - fixture.owner.noteConnectionChanged() - #expect(fixture.owner.isDiscovering) - gate.resumeFirst(.completed(newRegions: ["North"], allRepeatersTableFull: false)) - await fixture.flush() - #expect(fixture.owner.knownRegions == ["North"]) - #expect(fixture.owner.isDiscovering == false) + try await withFixture { fixture in + let gate = DiscoveryGate() + defer { gate.resumeAll(.sendFailed) } + fixture.owner.discover = { await gate.wait() } + fixture.owner.setWorkflowActive(true) + fixture.owner.start() + #expect(await gate.untilWaiting(1)) + try await fixture.install(device: fixture.device(name: "Field", regions: [])) + fixture.owner.noteConnectionChanged() + #expect(fixture.owner.isDiscovering) + gate.resumeFirst(.completed(newRegions: ["North"], allRepeatersTableFull: false)) + await fixture.flush() + #expect(fixture.owner.knownRegions == ["North"]) + #expect(fixture.owner.isDiscovering == false) + } } @Test - func `admitted callback can add and A closed workflow cannot`() throws { - let fixture = try DiscoveryFixture() - defer { fixture.tearDown() } - fixture.owner.setWorkflowActive(true) - fixture.owner.addKnownRegion("North") - #expect(fixture.owner.knownRegions == ["North"]) - fixture.owner.removeKnownRegion("North") - #expect(fixture.owner.knownRegions.isEmpty) - fixture.owner.setWorkflowActive(false) - fixture.owner.addKnownRegion("South") - #expect(fixture.owner.knownRegions.isEmpty) + func `admitted callback can add and A closed workflow cannot`() async throws { + try await withFixture { fixture in + fixture.owner.setWorkflowActive(true) + fixture.owner.addKnownRegion("North") + #expect(fixture.owner.knownRegions == ["North"]) + fixture.owner.removeKnownRegion("North") + #expect(fixture.owner.knownRegions.isEmpty) + fixture.owner.setWorkflowActive(false) + fixture.owner.addKnownRegion("South") + #expect(fixture.owner.knownRegions.isEmpty) + } } @Test func `suspended production discovery does not retain its owner`() async throws { - let fixture = try DiscoveryFixture() - defer { fixture.tearDown() } - let transport = MockTransport() - let session = MeshCoreSession(transport: transport) - defer { Task { await session.stop() } } - let startup = Task { try await session.start() } - defer { startup.cancel() } - try await waitUntil(timeout: .seconds(1), "app start should send") { - await transport.sentData.count == 1 - } - var packet = Data([ResponseCode.selfInfo.rawValue, 1, 22, 22]) - packet.append(Data(repeating: 1, count: ProtocolLimits.publicKeySize)) - packet.append(Data(repeating: 0, count: 12)) - packet.append(contentsOf: withUnsafeBytes(of: UInt32(915_000).littleEndian) { Array($0) }) - packet.append(contentsOf: withUnsafeBytes(of: UInt32(125_000).littleEndian) { Array($0) }) - packet.append(contentsOf: [7, 5]) - await transport.simulateReceive(packet) - try await startup.value + try await withFixture { fixture in + let transport = MockTransport() + let session = MeshCoreSession(transport: transport) + let startup = Task { try await session.start() } + fixture.own(session: session, startup: startup) + try await waitUntil(timeout: .seconds(1), "app start should send") { + await transport.sentData.count == 1 + } + var packet = Data([ResponseCode.selfInfo.rawValue, 1, 22, 22]) + packet.append(Data(repeating: 1, count: ProtocolLimits.publicKeySize)) + packet.append(Data(repeating: 0, count: 12)) + packet.append(contentsOf: withUnsafeBytes(of: UInt32(915_000).littleEndian) { Array($0) }) + packet.append(contentsOf: withUnsafeBytes(of: UInt32(125_000).littleEndian) { Array($0) }) + packet.append(contentsOf: [7, 5]) + await transport.simulateReceive(packet) + try await startup.value - let dataStore = fixture.appState.connectionManager.persistenceStore - let contactService = ContactService( - session: session, - dataStore: dataStore, - syncCoordinator: nil, - cleanupCoordinator: nil - ) - let state = fixture.appState - var owner: RegionDiscoveryState? = RegionDiscoveryState() - owner?.configure( - session: { session }, - contactService: { contactService }, - connectedDevice: { state.connectedDevice }, - connectionState: { state.connectionState }, - connectionManager: state.connectionManager, - dataStore: dataStore - ) - owner?.setWorkflowActive(true) - weak let releasedOwner = owner - owner?.start() - try await waitUntil(timeout: .seconds(1), "production discovery should send its probe") { - await transport.sentData.count == 2 - } + let dataStore = fixture.appState.connectionManager.persistenceStore + let contactService = ContactService( + session: session, + dataStore: dataStore, + syncCoordinator: nil, + cleanupCoordinator: nil + ) + let state = fixture.appState + var owner: RegionDiscoveryState? = RegionDiscoveryState() + owner?.configure( + session: { session }, + contactService: { contactService }, + connectedDevice: { state.connectedDevice }, + connectionState: { state.connectionState }, + connectionManager: state.connectionManager, + dataStore: dataStore + ) + owner?.setWorkflowActive(true) + weak let releasedOwner = owner + owner?.start() + try await waitUntil(timeout: .seconds(1), "production discovery should send its probe") { + await transport.sentData.count == 2 + } - owner = nil - await fixture.flush() + owner = nil + await fixture.flush() - #expect(releasedOwner == nil) - await session.stop() + #expect(releasedOwner == nil) + await session.stop() + } } } diff --git a/MC1Tests/Views/Settings/CLIProvenanceContractTests.swift b/MC1Tests/Views/Settings/CLIProvenanceContractTests.swift new file mode 100644 index 0000000000..378e511f58 --- /dev/null +++ b/MC1Tests/Views/Settings/CLIProvenanceContractTests.swift @@ -0,0 +1,110 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("Radio CLI request provenance contract") +@MainActor +struct CLIProvenanceContractTests { + @Test + func `unrelated CLI rejection cannot reject applied typed mutation`() async throws { + try await RadioWiFiContractHarness.withHarness { harness in + await harness.viewModel.noteSessionReadiness() + await harness.transport.holdNext("set wifi.enabled 0") + let write = harness.start { await harness.viewModel.setWiFiEnabled(false) } + try await waitUntil("typed mutation physically applied but reply held") { + await harness.transport.heldCount("set wifi.enabled 0") == 1 + } + + await harness.transport.injectCLIReply("Error: rejected") + await harness.transport.release("set wifi.enabled 0") + await write.value + + let errorPresentationMatchesContract1 = harness.viewModel.errorMessage == nil + #expect(errorPresentationMatchesContract1) + let enabledObservationMatchesContract1 = !harness.viewModel.wifiEnabled + #expect(enabledObservationMatchesContract1) + let viewStateMatchesContract1 = harness.viewModel.rebootPending + #expect(viewStateMatchesContract1) + let settings = try #require(harness.settings) + #expect(try await settings.getRadioCLIValue("wifi.enabled") == "0") + } + } + + @Test + func `timed out password cannot become retry SSID`() async throws { + try await RadioWiFiContractHarness.withHarness { harness in + let secret = "synthetic-private-value" + var firmware = RadioWiFiFirmware(defaultSSID: "configured") + firmware.savedPassword = secret + await harness.transport.useFirmware(firmware) + await harness.viewModel.noteSessionReadiness() + harness.viewModel.openEditor() + await harness.transport.holdNext("get wifi.pwd") + let first = harness.start { await harness.viewModel.loadEditor() } + try await waitUntil("the first password frame is held after physical send") { + await harness.transport.heldCount("get wifi.pwd") == 1 && harness.clock.sleeperCount > 0 + } + harness.clock.advance(by: .seconds(31)) + await first.value + let errorPresentationMatchesContract2 = harness.viewModel.errorMessage != nil + #expect(errorPresentationMatchesContract2) + let credentialKnowledgeMatchesContract1 = harness.viewModel.needsEditorRead + #expect(credentialKnowledgeMatchesContract1) + let saveEligibilityMatchesContract1 = !harness.viewModel.canSave + #expect(saveEligibilityMatchesContract1) + await harness.transport.holdNext("get wifi.ssid") + let retry = harness.start { await harness.viewModel.loadEditor() } + try await waitUntil("Retry owns a fresh SSID exchange") { + await harness.transport.heldCount("get wifi.ssid") == 1 + } + + await harness.transport.release("get wifi.pwd") + await harness.transport.release("get wifi.ssid") + await retry.value + + let correctSSID = harness.viewModel.ssidField == "configured" + let correctPassword = harness.viewModel.passwordField == secret + let secretAbsentFromNonsecretFields = harness.viewModel.ssidField != secret + && harness.viewModel.networkName != secret && !harness.viewModel.rebootMessage.contains(secret) + #expect(correctSSID) + #expect(correctPassword) + #expect(secretAbsentFromNonsecretFields) + let errorPresentationMatchesContract3 = harness.viewModel.errorMessage == nil + #expect(errorPresentationMatchesContract3) + let credentialKnowledgeMatchesContract2 = !harness.viewModel.needsEditorRead + #expect(credentialKnowledgeMatchesContract2) + harness.viewModel.ssidField = "replacement" + let saveEligibilityMatchesContract2 = harness.viewModel.canSave + #expect(saveEligibilityMatchesContract2) + await harness.viewModel.requestSave() + let editorPresentationMatchesContract1 = !harness.viewModel.editorOpen + #expect(editorPresentationMatchesContract1) + let settings = try #require(harness.settings) + #expect(try await settings.getRadioCLIValue("wifi.ssid") == "replacement") + } + } + + @Test + func `raw tools retains bytes and reflected prefix between typed reads`() async throws { + try await RadioWiFiContractHarness.withHarness { harness in + await harness.viewModel.noteSessionReadiness() + let tools = harness.makeTools() + let command = " z9|set wifi.enabled 0" + + tools.executeCommand(command) + try await waitUntil("raw Tools command settles") { !tools.isWaitingForResponse } + + #expect(await harness.transport.commands.last == command) + #expect(tools.outputLines.contains { $0.text == "z9|> wifi.enabled updated (reboot to apply)" }) + await harness.viewModel.refresh() + let enabledObservationMatchesContract2 = !harness.viewModel.wifiEnabled + #expect(enabledObservationMatchesContract2) + let viewStateMatchesContract2 = harness.viewModel.rebootPending + #expect(viewStateMatchesContract2) + let settings = try #require(harness.settings) + #expect(try await settings.getRadioCLIValue("wifi.enabled") == "0") + } + } +} diff --git a/MC1Tests/Views/Settings/DangerZoneRemovalOverlapTests.swift b/MC1Tests/Views/Settings/DangerZoneRemovalOverlapTests.swift new file mode 100644 index 0000000000..ea489e18b1 --- /dev/null +++ b/MC1Tests/Views/Settings/DangerZoneRemovalOverlapTests.swift @@ -0,0 +1,126 @@ +#if canImport(UIKit) + import AccessorySetupKit +#endif +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Danger Zone overlapping removal ownership") +@MainActor +struct DangerZoneRemovalOverlapTests { + @Test + func `superseded reset cleanup cannot replace current forget admission`() async throws { + let env = try await ConnectionLinkSwitchHarness.make(foreignWiFiRadio: true) + let model = DangerZoneViewModel() + model.configure( + settingsService: { env.manager.services?.settingsService }, + connectedDevice: { env.manager.connectedDevice }, connectionManager: env.manager + ) + let gate = Gate() + var resetting: Task? + var connecting: Task? + var forgetting: Task? + var heldOperationID: UUID? + var removalsAtForgetEntry = 0 + do { + let source = try #require(env.manager.currentConnection) + let successorID = UUID() + let successor = env.device.copy { + $0.id = successorID + $0.radioID = UUID() + $0.publicKey = Data(repeating: 0xB2, count: ProtocolLimits.publicKeySize) + $0.nodeName = "Successor" + $0.isActive = false + $0.connectionMethods = [ + .bluetooth(peripheralUUID: successorID, displayName: "Successor"), + .wifi(host: "successor.radio", port: 4242, displayName: nil) + ] + } + try await env.manager.persistenceStore.saveDevice(successor) + env.pairing.isSessionActive = true + env.pairing.setPairedAccessories([ + ASAccessory(bluetoothIdentifier: source.device.id, displayName: "Source"), + ASAccessory(bluetoothIdentifier: successor.id, displayName: "Successor") + ]) + env.pairing.beforeRemovalResult = { + if env.pairing.lastRemovedDeviceID == successor.id { + heldOperationID = env.manager.removalOperationID + removalsAtForgetEntry = env.pairing.removeAccessoryCallCount + await gate.wait() + } + } + await env.wifi.setConnectError(nil) + await env.bluetooth.holdNextSendCompletion() + let reset = Task { await model.factoryReset() } + resetting = reset + try await waitUntil("source reset should remain at its actual physical completion") { + let held = await env.bluetooth.sendCompletionIsHeld + let frames = await env.bluetooth.sentData + return held && frames.contains { $0.first == CommandCode.factoryReset.rawValue } + } + let connect = Task { try await env.manager.connectViaWiFi(host: "successor.radio", port: 4242) } + connecting = connect + try await waitUntil("foreign WiFi request should supersede the reset source") { + env.manager.connectionRequestID != source.requestID + } + await env.bluetooth.releaseSendCompletion() + #expect(try await env.manager.isCurrent(connect.value)) + let current = try #require(env.manager.currentConnection) + #expect(current.device.id == successor.id) + #expect(current.device.radioID == successor.radioID) + #expect(current.requestID != source.requestID) + try #require(model.isResetting) + let forget = Task { await model.forgetDevice(deleteData: true) } + forgetting = forget + try await waitUntil("current forget should hold its real ASK confirmation") { gate.entered } + try #require(removalsAtForgetEntry == 1, "source reset cleanup must start after current forget admission") + let operation = try #require(heldOperationID) + #expect(await reset.value == false) + #expect(env.manager.isCurrent(current)) + #expect(env.manager.removalOperationID == operation) + #expect(try await env.manager.persistenceStore.fetchDevice(id: current.device.id) != nil) + #expect(model.errorMessage == nil) + let time = try await current.services.session.getTime() + #expect(time.timeIntervalSince1970 > 0) + gate.release() + #expect(await forget.value) + #expect(env.manager.currentConnection == nil) + #expect(try await env.manager.persistenceStore.fetchDevice(id: current.device.id) == nil) + #expect(try await env.manager.persistenceStore.fetchDevice(radioID: current.device.radioID) == nil) + #expect(model.errorMessage == nil) + } catch { + gate.release() + env.pairing.beforeRemovalResult = nil + await env.bluetooth.releaseAllGates() + await env.wifi.releaseAllGates() + _ = await resetting?.value + _ = await connecting?.result + _ = await forgetting?.value + await env.close() + throw error + } + env.pairing.beforeRemovalResult = nil + 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/MC1Tests/Views/Settings/DangerZoneRemovalTests.swift b/MC1Tests/Views/Settings/DangerZoneRemovalTests.swift new file mode 100644 index 0000000000..4a0a0db75f --- /dev/null +++ b/MC1Tests/Views/Settings/DangerZoneRemovalTests.swift @@ -0,0 +1,235 @@ +#if canImport(UIKit) + import AccessorySetupKit +#endif +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Danger Zone removal ownership") +@MainActor +struct DangerZoneRemovalTests { + enum ForgetOutcome: CaseIterable { + case owned, declined, ownedFailure, superseded, supersededFailure + + var superseded: Bool { + self == .superseded || self == .supersededFailure + } + + var failed: Bool { + self == .ownedFailure || self == .supersededFailure + } + } + + @Test(arguments: ForgetOutcome.allCases, [false, true]) + func `forget confirmation retains its source outcome`(outcome: ForgetOutcome, deleteData: Bool) async throws { + let env = try await ConnectionLinkSwitchHarness.make(foreignWiFiRadio: true) + let model = DangerZoneViewModel() + model.configure( + settingsService: { env.manager.services?.settingsService }, + connectedDevice: { env.manager.connectedDevice }, connectionManager: env.manager + ) + let gate = Gate() + var forgetting: Task? + do { + env.pairing.isSessionActive = true + env.pairing.setPairedAccessories([ASAccessory(bluetoothIdentifier: env.device.id, displayName: "Source")]) + env.pairing.beforeRemovalResult = { await gate.wait() } + if outcome == .declined { env.pairing.removeAccessoryError = DevicePairingError.cancelled } + if outcome.failed { env.pairing.removeAccessoryError = NSError(domain: "RemovalSystem", code: 1) } + let forget = Task { await model.forgetDevice(deleteData: deleteData) } + forgetting = forget + try await waitUntil { gate.entered } + if outcome.superseded { + await env.wifi.setConnectError(nil) + #expect(try await env.manager.isCurrent(env.manager.connectViaWiFi(host: "successor.radio", port: 4242))) + } + let current = try #require(env.manager.currentConnection) + gate.release() + #expect(await forget.value == (outcome == .owned)) + #expect((model.errorMessage != nil) == (outcome == .ownedFailure)) + if outcome == .owned { + let disconnected = env.manager.currentConnection == nil + #expect(disconnected) + #expect(try await env.manager.persistenceStore.fetchDevice(id: env.device.id) == nil) + } else { + #expect(env.manager.isCurrent(current)) + #expect(try await env.manager.persistenceStore.fetchDevice(id: current.device.id)?.radioID == current.device.radioID) + let observedTime = try await current.services.session.getTime() + #expect(observedTime.timeIntervalSince1970 > 0) + } + } catch { + gate.release() + _ = await forgetting?.value + await env.close() + throw error + } + env.pairing.beforeRemovalResult = nil + await env.close() + } + + @Test + func `forget metadata finishes before successor without dismissing it`() async throws { + let env = try await ConnectionLinkSwitchHarness.make(foreignWiFiRadio: true) + let model = DangerZoneViewModel() + model.configure( + settingsService: { env.manager.services?.settingsService }, + connectedDevice: { env.manager.connectedDevice }, connectionManager: env.manager + ) + let gate = Gate() + var forgetting: Task? + var connecting: Task? + let sourceID = env.device.id + let accepted = env.manager.enqueueMetadata { store in + await gate.wait() + try await store.updateConnectionDevice(id: sourceID) { $0.copy { $0.nodeName = "Accepted before removal" } } + } + do { + try await waitUntil { gate.entered } + let forget = Task { await model.forgetDevice(deleteData: false) } + forgetting = forget + try await waitUntil { env.manager.currentConnection == nil } + let terminalID = env.manager.connectionRequestID + await env.wifi.setConnectError(nil) + let connect = Task { try await env.manager.connectViaWiFi(host: "successor.radio", port: 4242) } + connecting = connect + try await waitUntil { env.manager.connectionRequestID != terminalID } + #expect(await env.wifi.connectCount == env.initialWiFiAttempts) + gate.release() + try await accepted.value + #expect(await forget.value == false) + #expect(try await env.manager.isCurrent(connect.value)) + #expect(model.errorMessage == nil) + let ghost = try #require(try await env.manager.persistenceStore.fetchDevice(publicKey: env.device.publicKey)) + #expect(ghost.radioID == env.device.radioID) + #expect(ghost.nodeName == "Accepted before removal") + #expect(ghost.connectionMethods.isEmpty) + let observedTime = try await #require(env.manager.session).getTime() + #expect(observedTime.timeIntervalSince1970 > 0) + } catch { + gate.release() + _ = await accepted.result + _ = await forgetting?.value + _ = await connecting?.result + await env.close() + throw error + } + await env.close() + } + + @Test(arguments: [false, true]) + func `reset completion cannot retire same request replacement link`(loseSuccessor: Bool) async throws { + let env = try await ConnectionLinkSwitchHarness.make() + let model = DangerZoneViewModel() + model.configure( + settingsService: { env.manager.services?.settingsService }, + connectedDevice: { env.manager.connectedDevice }, connectionManager: env.manager + ) + var resetting: Task? + do { + let source = try #require(env.manager.currentConnection) + await env.bluetooth.setConnectError(nil) + await env.bluetooth.holdNextSendCompletion() + let reset = Task { await model.factoryReset() } + resetting = reset + try await waitUntil { await env.bluetooth.sentData.contains { $0.first == CommandCode.factoryReset.rawValue } } + await env.bluetooth.simulateAutoReconnecting(deviceID: source.device.id) + try await waitUntil { env.manager.currentConnection == nil } + await env.bluetooth.releaseSendCompletion() + try await waitUntil { env.manager.connectionTeardownCount == 0 } + await env.bluetooth.simulateReconnected() + try await waitUntil { + env.manager.connectionState == .ready && env.manager.currentConnection?.generation != source.generation + } + let successor = try #require(env.manager.currentConnection) + #expect(successor.requestID == source.requestID) + if loseSuccessor { + await env.bluetooth.simulateAutoReconnecting(deviceID: successor.device.id) + try await waitUntil { env.manager.currentConnection == nil } + try await waitUntil { env.manager.connectionTeardownCount == 0 } + } + #expect(await reset.value == false) + let requestSurvives = env.manager.connectionRequestID == source.requestID + #expect(requestSurvives) + #expect(try await env.manager.persistenceStore.fetchDevice(id: successor.device.id) != nil) + if loseSuccessor, requestSurvives { + await env.bluetooth.simulateReconnected() + try await waitUntil { + env.manager.connectionState == .ready && env.manager.currentConnection?.generation != successor.generation + } + let observedTime = try await #require(env.manager.session).getTime() + #expect(observedTime.timeIntervalSince1970 > 0) + } else if !loseSuccessor { + let successorIsCurrent = env.manager.isCurrent(successor) + #expect(successorIsCurrent) + let observedTime = try await successor.services.session.getTime() + #expect(observedTime.timeIntervalSince1970 > 0) + } + } catch { + await env.bluetooth.releaseAllGates() + _ = await resetting?.value + await env.close() + throw error + } + await env.close() + } + + @Test + func `factory reset cannot forget successor`() async throws { + let env = try await ConnectionLinkSwitchHarness.make(foreignWiFiRadio: true) + let model = DangerZoneViewModel() + model.configure( + settingsService: { env.manager.services?.settingsService }, + connectedDevice: { env.manager.connectedDevice }, connectionManager: env.manager + ) + var resetting: Task? + var connecting: Task? + do { + await env.wifi.setConnectError(nil) + await env.bluetooth.holdReplies(for: .factoryReset) + let reset = Task { await model.factoryReset() } + resetting = reset + try await waitUntil { await env.bluetooth.sentData.contains { $0.first == CommandCode.factoryReset.rawValue } } + let connect = Task { try await env.manager.connectViaWiFi(host: "successor.radio", port: 4242) } + connecting = connect + try await waitUntil { env.manager.connectionRequestID != env.manager.currentConnection?.requestID } + await env.bluetooth.releaseReplies(for: .factoryReset) + let result = try await connect.value + #expect(env.manager.isCurrent(result)) + let successor = try #require(env.manager.currentConnection) + let observedTime = try await successor.services.session.getTime() + #expect(observedTime.timeIntervalSince1970 > 0) + #expect(await reset.value == false, "A superseded reset cannot dismiss the successor page") + let successorIsCurrent = env.manager.isCurrent(successor) + #expect(successorIsCurrent) + #expect(try await env.manager.persistenceStore.fetchDevice(id: successor.device.id) != nil) + } catch { + await env.bluetooth.releaseAllGates() + await env.wifi.releaseAllGates() + _ = await resetting?.value + _ = 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/MC1Tests/Views/Settings/RadioWiFiContractAdmissionTests.swift b/MC1Tests/Views/Settings/RadioWiFiContractAdmissionTests.swift new file mode 100644 index 0000000000..a45cfa9121 --- /dev/null +++ b/MC1Tests/Views/Settings/RadioWiFiContractAdmissionTests.swift @@ -0,0 +1,190 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("Radio WiFi complete admission certificates") +@MainActor +struct RadioWiFiContractAdmissionTests { + @Test(arguments: ["save", "disable", "clear", "reboot", "raw-read", "raw-setter"]) + func `old context cannot admit on equal revision successor`(_ action: String) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + let settings = try #require(harness.settings) + let old = settings.radioWiFiBinding + let oldWire = harness.transport + let editorID = UUID() + let baseline = try #require(try await settings.readRadioWiFiCredentials(editorID: editorID)) + let successor = try await harness.replaceSettingsRuntime() + let viewStateMatchesContract1 = successor.radioWiFiState.revision == baseline.revision + #expect(viewStateMatchesContract1) + let before = await harness.transport.sentData.count + let oldFrames = await oldWire.sentData.count + for target in [settings, successor] { + await #expect { + switch action { + case "save": + _ = try await target.saveRadioWiFiCredentials( + ssid: "stale", password: baseline.password, baseline: baseline, editorID: editorID, + ownerIsCurrent: { true } + ) + case "disable": + _ = try await target.setRadioWiFiEnabled( + false, expectedContextID: old.contextID, expectedRevision: baseline.revision + ) + case "clear": + _ = try await target.clearRadioWiFi( + expectedContextID: old.contextID, expectedRevision: baseline.revision + ) + case "reboot": + try await target.reboot(expectedContextID: old.contextID, expectedRevision: baseline.revision) + case "raw-read": + _ = try await target.runCliCommand("get wifi.ssid", expectedContextID: old.contextID) + default: + _ = try await target.runCliCommand("set wifi.ssid stale", expectedContextID: old.contextID) + } + } throws: { $0 is CancellationError } + } + #expect(await oldWire.sentData.count == oldFrames) + #expect(await harness.transport.sentData.count == before) + let viewStateMatchesContract2 = successor.radioWiFiState.revision == baseline.revision + #expect(viewStateMatchesContract2) + #expect(!settings.radioWiFiState.rebootPending) + #expect(!successor.radioWiFiState.rebootPending) + let current = successor.radioWiFiBinding + let settled = try await successor.setRadioWiFiEnabled( + false, expectedContextID: current.contextID, expectedRevision: baseline.revision + ) + #expect(settled == successor.radioWiFiState.stableRevision()) + #expect(await harness.transport.count("set wifi.enabled 0") == 1) + #expect(try await successor.getRadioCLIValue("wifi.enabled") == "0") + } + } + + @Test + func `exhausted correlation rejects mutation without pending evidence`() async throws { + let scope = RadioCLICorrelationScope() + for _ in 0.. 1") + } + try await RadioWiFiContractHarness.withHarness { harness in + let settings = try #require(harness.settings) + let binding = settings.radioWiFiBinding + let settled = try await settings.setRadioWiFiEnabled( + false, expectedContextID: binding.contextID, expectedRevision: 0 + ) + #expect(settled != nil) + #expect(settings.radioWiFiState.rebootPending) + #expect(try await settings.getRadioCLIValue("wifi.enabled") == "0") + } + } + + @Test(arguments: [false, true]) + func `rejected local preflight cannot invent pending evidence`(_ reusesPrefix: Bool) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + let settings = try #require(harness.settings) + if reusesPrefix { _ = try await settings.runCliCommand("z9|get wifi.enabled") } + let before = await harness.transport.sentData.count + let command = reusesPrefix ? "z9|set wifi.enabled 0" + : "set wifi.ssid " + String(repeating: "x", count: PacketBuilder.runCliCommandMaxUTF8Bytes) + await #expect { + try await settings.runCliCommand(command) + } throws: { error in + guard let error = error as? SettingsServiceError, + case .sessionError(.invalidInput) = error else { return false } + return true + } + #expect(await harness.transport.sentData.count == before) + #expect(!settings.radioWiFiState.rebootPending) + #expect(settings.radioWiFiState.stableRevision() != nil) + #expect(try await settings.getRadioCLIValue("wifi.enabled") == "1") + try await settings.setRadioCLIValue("wifi.ssid", to: "after-rejection") + #expect(settings.radioWiFiState.rebootPending) + #expect(try await settings.getRadioCLIValue("wifi.ssid") == "after-rejection") + } + } + + @Test + func `unreflected replies cannot grant support or credentials and fresh reflection recovers`() async throws { + try await RadioWiFiContractHarness.withHarness { harness in + await harness.transport.setReflectsPrefixes(false) + let read = harness.start { await harness.viewModel.noteSessionReadiness() } + try await waitUntil("the unreflected enabled read owns a real timeout") { + await harness.transport.count("get wifi.enabled") == 1 && harness.clock.sleeperCount > 0 + } + harness.clock.advance(by: .seconds(31)) + await read.value + let viewStateMatchesContract3 = !harness.viewModel.showsSection + #expect(viewStateMatchesContract3) + #expect(harness.viewModel.networkValue == L10n.Settings.DeviceInfo.unknown) + #expect(harness.viewModel.statusValue == L10n.Settings.DeviceInfo.unknown) + let viewStateMatchesContract4 = !harness.viewModel.canEditNetwork + #expect(viewStateMatchesContract4) + let saveEligibilityMatchesContract1 = !harness.viewModel.canSave + #expect(saveEligibilityMatchesContract1) + #expect(await harness.transport.count("get wifi.ssid") == 0) + #expect(await harness.transport.count("get wifi.pwd") == 0) + await harness.transport.setReflectsPrefixes(true) + await harness.viewModel.refresh() + let viewStateMatchesContract5 = harness.viewModel.canEditNetwork + #expect(viewStateMatchesContract5) + harness.viewModel.openEditor() + await harness.viewModel.loadEditor() + harness.viewModel.ssidField = "after-reflection" + let saveEligibilityMatchesContract2 = harness.viewModel.canSave + #expect(saveEligibilityMatchesContract2) + await harness.viewModel.requestSave() + #expect(try await harness.settings?.getRadioCLIValue("wifi.ssid") == "after-reflection") + } + } + + @Test + func `rejected enabled receipt keeps its actual settlement and throwing wrapper`() async throws { + try await RadioWiFiContractHarness.withHarness { harness in + let settings = try #require(harness.settings) + let binding = settings.radioWiFiBinding + await harness.transport.rejectNext("set wifi.enabled 0") + let receipt = try await settings.changeRadioWiFiEnabled( + false, expectedContextID: binding.contextID, expectedRevision: 0 + ) + let rejected = if case .rejected = receipt.outcome { true } else { false } + #expect(rejected) + #expect(receipt.contextID == binding.contextID) + #expect(receipt.revision == settings.radioWiFiState.stableRevision()) + #expect(receipt.error != nil) + #expect(!settings.radioWiFiState.rebootPending) + #expect(await harness.transport.count("set wifi.enabled 0") == 1) + let revision = try #require(receipt.revision) + await harness.transport.rejectNext("set wifi.enabled 0") + await #expect { + try await settings.setRadioWiFiEnabled( + false, expectedContextID: binding.contextID, expectedRevision: revision + ) + } throws: { error in + guard let error = error as? SettingsServiceError, case .radioCLIRejected = error else { return false } + return true + } + #expect(!settings.radioWiFiState.rebootPending) + #expect(await harness.transport.count("set wifi.enabled 0") == 2) + #expect(try await settings.getRadioCLIValue("wifi.enabled") == "1") + } + } +} diff --git a/MC1Tests/Views/Settings/RadioWiFiContractBindingTests.swift b/MC1Tests/Views/Settings/RadioWiFiContractBindingTests.swift new file mode 100644 index 0000000000..3bff6243d2 --- /dev/null +++ b/MC1Tests/Views/Settings/RadioWiFiContractBindingTests.swift @@ -0,0 +1,175 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import Testing + +@Suite("Radio WiFi replacement binding contract") +@MainActor +struct RadioWiFiContractBindingTests { + @Test + func `old context cannot admit reads on equal revision successor`() async throws { + try await RadioWiFiContractHarness.withHarness { harness in + let settings = try #require(harness.settings) + let previous = settings.radioWiFiBinding + let oldWire = harness.transport + let successor = try await harness.replaceSettingsRuntime() + #expect(successor !== settings) + #expect(successor.radioWiFiState.revision == previous.state.revision) + let before = await harness.transport.commands.count + + let oldFrames = await oldWire.sentData.count + for target in [settings, successor] { + let capability = try await target.probeRadioWiFiSettings(expectedContextID: previous.contextID) + let oldProbeWasRejected = if case .busy = capability { true } else { false } + #expect(oldProbeWasRejected) + let oldRead = try await target.readRadioWiFiCredentials( + editorID: UUID(), expectedContextID: previous.contextID + ) + #expect(oldRead == nil) + } + #expect(await oldWire.sentData.count == oldFrames) + #expect(await harness.transport.commands.count == before) + let current = successor.radioWiFiBinding + _ = try await successor.probeRadioWiFiSettings(expectedContextID: current.contextID) + let fresh = try #require(try await successor.readRadioWiFiCredentials( + editorID: UUID(), expectedContextID: current.contextID + )) + #expect(fresh.contextID == current.contextID) + #expect(try await successor.getRadioCLIValue("wifi.enabled") == "1") + } + } + + @Test + func `tools intent cannot borrow successor before its task runs`() async throws { + try await RadioWiFiContractHarness.withHarness { harness in + let previous = try #require(harness.settings) + let tools = harness.makeTools() + let staleCommand = "set wifi.ssid old-intent" + + tools.executeCommand(staleCommand) + let successor = SettingsService( + session: harness.session, radioWiFiState: RadioWiFiState(radioID: harness.device.radioID) + ) + harness.settings = successor + try await waitUntil("the old UI task completes after service replacement") { !tools.isWaitingForResponse } + + #expect(await harness.transport.count(staleCommand) == 0) + #expect(!successor.radioWiFiState.rebootPending) + #expect(!tools.outputLines.contains { $0.type == .response || $0.type == .error }) + tools.executeCommand("set wifi.ssid current-intent") + try await waitUntil("the fresh Tools intent settles") { !tools.isWaitingForResponse } + #expect(await harness.transport.count("set wifi.ssid current-intent") == 1) + #expect(try await successor.getRadioCLIValue("wifi.ssid") == "current-intent") + await previous.retireRadioWiFiOperations() + } + } + + @Test + func `old read settles before equal revision successor`() async throws { + try await RadioWiFiContractHarness.withHarness { harness in + await harness.viewModel.noteSessionReadiness() + harness.viewModel.openEditor() + await harness.transport.holdNext("get wifi.ssid") + let read = harness.start { await harness.viewModel.loadEditor() } + try await waitUntil("old editor SSID frame is held") { + await harness.transport.heldCount("get wifi.ssid") == 1 + } + let settings = try #require(harness.settings) + let previous = settings.radioWiFiBinding + let oldWire = harness.transport + + await settings.retireRadioWiFiOperations() + #expect(harness.settings === settings) + await oldWire.release("get wifi.ssid") + await read.value + #expect(await oldWire.count("get wifi.pwd") == 0) + let successor = try await harness.replaceSettingsRuntime() + #expect(previous.state.revision == successor.radioWiFiState.revision) + await harness.viewModel.noteSessionReadiness() + + #expect(await harness.transport.count("get wifi.pwd") == 0) + let editorPresentationMatchesContract1 = !harness.viewModel.editorOpen + #expect(editorPresentationMatchesContract1) + let passwordKnowledgeMatchesContract1 = harness.viewModel.passwordField.isEmpty + #expect(passwordKnowledgeMatchesContract1) + let networkKnowledgeMatchesContract1 = harness.viewModel.ssidField.isEmpty + #expect(networkKnowledgeMatchesContract1) + let viewStateMatchesContract1 = !harness.viewModel.isBusy + #expect(viewStateMatchesContract1) + let networkObservationMatchesContract1 = harness.viewModel.networkName == "initial" + #expect(networkObservationMatchesContract1) + harness.viewModel.openEditor() + await harness.viewModel.loadEditor() + harness.viewModel.ssidField = "after-binding" + let saveEligibilityMatchesContract1 = harness.viewModel.canSave + #expect(saveEligibilityMatchesContract1) + await harness.viewModel.requestSave() + #expect(try await successor.getRadioCLIValue("wifi.ssid") == "after-binding") + } + } + + @Test(arguments: ["save", "disable", "clear", "reboot"]) + func `binding replacement withdraws all confirmation siblings`(_ action: String) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + harness.transportType = .wifi + let settings = try #require(harness.settings) + try await settings.setRadioCLIValue("wifi.ssid", to: "initial") + await harness.viewModel.noteSessionReadiness() + harness.viewModel.openEditor() + await harness.viewModel.loadEditor() + harness.viewModel.ssidField = "old-draft" + harness.viewModel.passwordField = "synthetic-old-secret" + let entry: RadioWiFiViewModel.AlertAction + switch action { + case "save": + await harness.viewModel.requestSave() + entry = .wifiWarning + case "disable": + await harness.viewModel.setWiFiEnabled(false) + entry = .wifiWarning + case "clear": + harness.viewModel.requestClear() + entry = .clear + default: + harness.viewModel.requestReboot() + entry = .reboot + } + let viewStateMatchesContract2 = harness.viewModel.confirmation != nil + #expect(viewStateMatchesContract2) + let previous = settings.radioWiFiBinding + let oldRevision = previous.state.revision + + let successor = try await harness.replaceSettingsRuntime() + try await successor.setRadioCLIValue("wifi.ssid", to: "successor") + #expect(successor.radioWiFiBinding.contextID != previous.contextID) + #expect(successor.radioWiFiState.revision == oldRevision) + let before = await harness.transport.commands.count + await harness.viewModel.confirmFromAlert(entry).value + + #expect(await harness.transport.commands.count == before) + let saveEligibilityMatchesContract2 = !harness.viewModel.canSave + #expect(saveEligibilityMatchesContract2) + await harness.viewModel.noteSessionReadiness() + let editorPresentationMatchesContract2 = !harness.viewModel.editorOpen + #expect(editorPresentationMatchesContract2) + let passwordKnowledgeMatchesContract2 = harness.viewModel.passwordField.isEmpty + #expect(passwordKnowledgeMatchesContract2) + let networkKnowledgeMatchesContract2 = harness.viewModel.ssidField.isEmpty + #expect(networkKnowledgeMatchesContract2) + let viewStateMatchesContract3 = harness.viewModel.confirmation == nil + #expect(viewStateMatchesContract3) + let networkObservationMatchesContract2 = harness.viewModel.networkName == "successor" + #expect(networkObservationMatchesContract2) + let viewStateMatchesContract4 = harness.viewModel.canRunCommands + #expect(viewStateMatchesContract4) + harness.viewModel.openEditor() + await harness.viewModel.loadEditor() + harness.viewModel.ssidField = "current-save" + let saveEligibilityMatchesContract3 = harness.viewModel.canSave + #expect(saveEligibilityMatchesContract3) + await harness.viewModel.requestSave() + await harness.viewModel.confirmFromAlert(.wifiWarning).value + #expect(try await successor.getRadioCLIValue("wifi.ssid") == "current-save") + } + } +} diff --git a/MC1Tests/Views/Settings/RadioWiFiContractCredentialTests.swift b/MC1Tests/Views/Settings/RadioWiFiContractCredentialTests.swift new file mode 100644 index 0000000000..33305cd87e --- /dev/null +++ b/MC1Tests/Views/Settings/RadioWiFiContractCredentialTests.swift @@ -0,0 +1,134 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import Testing + +@Suite("Radio WiFi credential effect contract") +@MainActor +struct RadioWiFiContractCredentialTests { + @Test(arguments: ["", " synthetic-key ", "(not set)"]) + func `real credential pair keeps verbatim password`(_ savedPassword: String) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + var firmware = RadioWiFiFirmware(defaultSSID: "configured") + firmware.savedPassword = savedPassword + await harness.transport.useFirmware(firmware) + await harness.viewModel.noteSessionReadiness() + harness.viewModel.openEditor() + + await harness.viewModel.loadEditor() + + let exactPasswordKnown = harness.viewModel.passwordField == savedPassword + #expect(exactPasswordKnown) + let credentialKnowledgeMatchesContract1 = !harness.viewModel.needsEditorRead + #expect(credentialKnowledgeMatchesContract1) + harness.viewModel.ssidField = "verbatim-network" + let saveEligibilityMatchesContract1 = harness.viewModel.canSave + #expect(saveEligibilityMatchesContract1) + await harness.viewModel.requestSave() + let editorPresentationMatchesContract1 = !harness.viewModel.editorOpen + #expect(editorPresentationMatchesContract1) + let settings = try #require(harness.settings) + let passwordUnchanged = try await settings.getRadioCLIValue("wifi.pwd") == savedPassword + #expect(passwordUnchanged) + #expect(try await settings.getRadioCLIValue("wifi.ssid") == "verbatim-network") + } + } + + @Test(arguments: [false, true]) + func `actual setter timeout retains uncertainty until fresh read`(_ applied: Bool) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + await harness.viewModel.noteSessionReadiness() + harness.viewModel.openEditor() + await harness.viewModel.loadEditor() + harness.viewModel.ssidField = "submitted" + let command = "set wifi.ssid submitted" + if applied { + await harness.transport.holdNext(command) + } else { + await harness.transport.dropNextBeforeApply(command) + } + let save = harness.start { await harness.viewModel.requestSave() } + try await waitUntil("the real setter exchange is waiting for its reply") { + await harness.transport.count(command) == 1 && harness.clock.sleeperCount > 0 + } + harness.clock.advance(by: .seconds(31)) + await save.value + + let errorPresentationMatchesContract1 = harness.viewModel.errorMessage != nil + #expect(errorPresentationMatchesContract1) + let credentialKnowledgeMatchesContract2 = harness.viewModel.needsEditorRead + #expect(credentialKnowledgeMatchesContract2) + let saveEligibilityMatchesContract2 = !harness.viewModel.canSave + #expect(saveEligibilityMatchesContract2) + #expect(harness.settings?.radioWiFiState.rebootPending == true) + let uncertainNetworkCannotClear = !harness.viewModel.canClear + let uncertainNetworkUsesGenericRebootCopy = harness.viewModel.rebootMessage + == L10n.Settings.RadioWiFi.Alert.Reboot.restart + #expect(uncertainNetworkCannotClear) + #expect(uncertainNetworkUsesGenericRebootCopy) + await harness.viewModel.loadEditor() + let capturedBaseline = harness.viewModel.editor?.baseline + let baseline = try #require(capturedBaseline) + let networkKnowledgeMatchesContract1 = baseline.ssid == (applied ? "submitted" : "initial") + #expect(networkKnowledgeMatchesContract1) + let credentialKnowledgeMatchesContract3 = !harness.viewModel.needsEditorRead + #expect(credentialKnowledgeMatchesContract3) + harness.viewModel.ssidField = "recovered" + let saveEligibilityMatchesContract3 = harness.viewModel.canSave + #expect(saveEligibilityMatchesContract3) + await harness.viewModel.requestSave() + let settings = try #require(harness.settings) + #expect(try await settings.getRadioCLIValue("wifi.ssid") == "recovered") + } + } + + @Test(arguments: [false, true]) + func `accepted SSID survives later password uncertainty`(_ passwordApplied: Bool) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + await harness.viewModel.noteSessionReadiness() + harness.viewModel.openEditor() + await harness.viewModel.loadEditor() + harness.viewModel.ssidField = "accepted-network" + let submittedPassword = "synthetic-partial-secret" + harness.viewModel.passwordField = submittedPassword + let command = "set wifi.pwd " + submittedPassword + if passwordApplied { + await harness.transport.holdNext(command) + } else { + await harness.transport.dropNextBeforeApply(command) + } + let save = harness.start { await harness.viewModel.requestSave() } + try await waitUntil("the accepted SSID is followed by a real password timeout") { + await harness.transport.count(command) == 1 && harness.clock.sleeperCount > 0 + } + harness.clock.advance(by: .seconds(31)) + await save.value + + let confirmedSSIDRemainsVisible = harness.viewModel.networkName == "accepted-network" + #expect(harness.viewModel.networkValue == "accepted-network") + let confirmedSSIDCanClear = harness.viewModel.canClear + let confirmedSSIDNamesReboot = harness.viewModel.rebootMessage + == L10n.Settings.RadioWiFi.Alert.Reboot.join("accepted-network") + let uncertainPasswordCannotSave = !harness.viewModel.canSave && harness.viewModel.needsEditorRead + #expect(confirmedSSIDRemainsVisible) + #expect(confirmedSSIDCanClear) + #expect(confirmedSSIDNamesReboot) + #expect(uncertainPasswordCannotSave) + #expect(harness.settings?.radioWiFiState.rebootPending == true) + + await harness.viewModel.loadEditor() + let capturedBaseline = harness.viewModel.editor?.baseline + let baseline = try #require(capturedBaseline) + let passwordMatchesStoredEffect = baseline.password == (passwordApplied ? submittedPassword : "") + #expect(passwordMatchesStoredEffect) + harness.viewModel.ssidField = "after-partial-uncertainty" + let recoveredDraftCanSave = harness.viewModel.canSave + #expect(recoveredDraftCanSave) + await harness.viewModel.requestSave() + let settings = try #require(harness.settings) + #expect(try await settings.getRadioCLIValue("wifi.ssid") == "after-partial-uncertainty") + let storedPasswordMatchesValidSave = try await settings.getRadioCLIValue("wifi.pwd") == submittedPassword + #expect(storedPasswordMatchesValidSave) + } + } +} diff --git a/MC1Tests/Views/Settings/RadioWiFiContractFramedValueTests.swift b/MC1Tests/Views/Settings/RadioWiFiContractFramedValueTests.swift new file mode 100644 index 0000000000..1edf53c675 --- /dev/null +++ b/MC1Tests/Views/Settings/RadioWiFiContractFramedValueTests.swift @@ -0,0 +1,44 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import Testing + +@Suite("Radio WiFi framed credential values") +@MainActor +struct RadioWiFiContractFramedValueTests { + @Test(arguments: ["\r", "\n", "\r\n"]) + func `trailing line endings are stored credential bytes`(_ ending: String) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + let initialSSID = "framed-network" + ending + let savedPassword = "synthetic-framed" + ending + var firmware = RadioWiFiFirmware() + firmware.savedSSID = initialSSID + firmware.savedPassword = savedPassword + firmware.boot() + await harness.transport.useFirmware(firmware) + await harness.viewModel.noteSessionReadiness() + let exactNetworkObserved = harness.viewModel.networkName == initialSSID + #expect(exactNetworkObserved) + harness.viewModel.openEditor() + await harness.viewModel.loadEditor() + let exactSSIDKnown = harness.viewModel.ssidField == initialSSID + let exactPasswordKnown = harness.viewModel.passwordField == savedPassword + #expect(exactSSIDKnown) + #expect(exactPasswordKnown) + let settings = try #require(harness.settings) + let actualFrameCarriesPasswordBytes = try await settings.runCliCommand("get wifi.pwd") == "> " + savedPassword + #expect(actualFrameCarriesPasswordBytes) + + let updatedSSID = "after-frame" + ending + harness.viewModel.ssidField = updatedSSID + let validDraftCanSave = harness.viewModel.canSave + #expect(validDraftCanSave) + await harness.viewModel.requestSave() + await harness.viewModel.refresh() + let savedNetworkIsExact = harness.viewModel.networkName == updatedSSID + let savedPasswordIsExact = try await settings.getRadioCLIValue("wifi.pwd") == savedPassword + #expect(savedNetworkIsExact) + #expect(savedPasswordIsExact) + } + } +} diff --git a/MC1Tests/Views/Settings/RadioWiFiContractHarness.swift b/MC1Tests/Views/Settings/RadioWiFiContractHarness.swift new file mode 100644 index 0000000000..0a27472046 --- /dev/null +++ b/MC1Tests/Views/Settings/RadioWiFiContractHarness.swift @@ -0,0 +1,117 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +@testable import MeshCore +import Testing + +@MainActor +final class RadioWiFiContractHarness { + private(set) var transport = RadioWiFiContractTransport() + let clock = TestClock() + let viewModel = RadioWiFiViewModel() + private(set) var session: MeshCoreSession + var settings: SettingsService? + var connectionState: DeviceConnectionState = .ready + var transportType: TransportType? = .bluetooth + var device: DeviceDTO + private var workers: [Task] = [] + private var tools: [CLIToolViewModel] = [] + + private init(scope: RadioCLICorrelationScope) { + session = MeshCoreSession( + transport: transport, configuration: SessionConfiguration(defaultTimeout: 30), clock: clock, + radioCLICorrelationScope: scope + ) + device = DeviceDTO( + id: UUID(), radioID: UUID(), publicKey: Data(repeating: 0xA1, count: ProtocolLimits.publicKeySize), + nodeName: "Contract Radio", firmwareVersion: 14, firmwareVersionString: "1.18.0", + manufacturerName: "Test", buildDate: "2026-10-18", maxContacts: 100, maxChannels: 1, + frequency: 915_000, bandwidth: 250_000, spreadingFactor: 7, codingRate: 5, + txPower: 22, maxTxPower: 22, latitude: 0, longitude: 0, blePin: 0, manualAddContacts: false, + multiAcks: 0, telemetryModeBase: 0, telemetryModeLoc: 0, telemetryModeEnv: 0, + advertLocationPolicy: 0, lastConnected: Date(), lastContactSync: 0, isActive: true, + ocvPreset: nil, customOCVArrayString: nil + ) + settings = SettingsService(session: session, radioWiFiState: RadioWiFiState(radioID: device.radioID)) + viewModel.configure( + settingsService: { self.settings }, connectionState: { self.connectionState }, + connectedDevice: { self.device }, currentTransportType: { self.transportType } + ) + } + + func start(_ body: @escaping @MainActor () async -> Void) -> Task { + let task = Task { await body() } + workers.append(task) + return task + } + + func makeTools() -> CLIToolViewModel { + let tools = CLIToolViewModel() + tools.configure( + dependencies: CLIToolViewModel.Dependencies( + repeaterAdminService: { nil }, remoteNodeService: { nil }, settingsService: { self.settings }, + dataStore: { nil }, radioID: { self.device.radioID }, connectedDevice: { self.device }, + powerOffRadio: {}, powerOffCancelAvailable: { true } + ), localDeviceName: "Contract Radio", sendSelfAdvert: { _ in } + ) + tools.activeSession = .local(deviceName: "Contract Radio") + self.tools.append(tools) + return tools + } + + func replaceSettingsRuntime() async throws -> SettingsService { + await settings?.retireRadioWiFiOperations() + await session.stop() + await session.waitForQuiescence() + #expect(await session.subscriberCountForTest == 0) + #expect(clock.sleeperCount == 0) + #expect(await transport.isConnected == false) + transport = RadioWiFiContractTransport() + session = MeshCoreSession( + transport: transport, configuration: SessionConfiguration(defaultTimeout: 30), clock: clock + ) + try await session.start() + let successor = SettingsService(session: session, radioWiFiState: RadioWiFiState(radioID: device.radioID)) + settings = successor + return successor + } + + func close() async { + await transport.releaseAll() + for tool in tools { + tool.cleanup() + } + tools.removeAll() + await session.stop() + for task in workers { + await task.value + } + workers.removeAll() + await settings?.retireRadioWiFiOperations() + await session.waitForQuiescence() + viewModel.configure( + settingsService: { nil }, connectionState: { .disconnected }, + connectedDevice: { nil }, currentTransportType: { nil } + ) + await viewModel.noteSessionReadiness() + settings = nil + #expect(await session.subscriberCountForTest == 0) + #expect(clock.sleeperCount == 0) + #expect(await transport.isConnected == false) + } + + static func withHarness( + scope: RadioCLICorrelationScope = RadioCLICorrelationScope(), + _ body: (RadioWiFiContractHarness) async throws -> Void + ) async throws { + let harness = RadioWiFiContractHarness(scope: scope) + do { + try await harness.session.start() + try await body(harness) + await harness.close() + } catch { + await harness.close() + throw error + } + } +} diff --git a/MC1Tests/Views/Settings/RadioWiFiContractManagerProvenanceTests.swift b/MC1Tests/Views/Settings/RadioWiFiContractManagerProvenanceTests.swift new file mode 100644 index 0000000000..117280042b --- /dev/null +++ b/MC1Tests/Views/Settings/RadioWiFiContractManagerProvenanceTests.swift @@ -0,0 +1,219 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +@testable import MeshCore +import Synchronization +import Testing + +@Suite("Radio WiFi manager CLI request provenance") +@MainActor +struct RadioWiFiContractManagerProvenanceTests { + @Test(arguments: [false, true]) + func `timed out password cannot cross actual manager session replacement`(canonicalImport: Bool) async throws { + let env = try await ConnectionLinkSwitchHarness.make() + let model = RadioWiFiViewModel() + let importer = NodeConfigImportViewModel() + importer.configure( + nodeConfigService: { env.manager.services?.nodeConfigService }, + settingsService: { env.manager.services?.settingsService }, + connectedDevice: { env.manager.connectedDevice }, + connectionManager: env.manager + ) + let firmware = Firmware() + let oldRequestID = env.manager.connectionRequestID + var workers: [Task] = [] + var sessions: [MeshCoreSession] = [] + model.configure( + settingsService: { env.manager.services?.settingsService }, + connectionState: { env.manager.connectionState }, + connectedDevice: { env.manager.connectedDevice }, + currentTransportType: { env.manager.currentTransportType } + ) + do { + await env.bluetooth.setConnectError(nil) + await env.bluetooth.setCLIResponder { firmware.reply(to: $0) } + let initialCLICommands = await env.bluetooth.cliCommands.map { + ConnectionTestRadioTransport.splitCLICommand($0).command + } + let originalSettings = try #require(env.manager.services?.settingsService) + await env.bluetooth.holdCLIReplies(for: "get wifi.pwd") + let first: Task = Task { + _ = await #expect { + try await originalSettings.readRadioWiFiCredentials(editorID: UUID()) + } throws: { error in + guard let error = error as? SettingsServiceError, + case .sessionError(.timeout) = error else { return false } + return true + } + } + workers.append(first) + try await waitUntil("the original password frame remains physically delayed") { + await env.bluetooth.heldCLIReplyCount(for: "get wifi.pwd") == 1 + } + await first.value + let oldPasswordCommand = try #require(await env.bluetooth.cliCommands.last { + ConnectionTestRadioTransport.splitCLICommand($0).command == "get wifi.pwd" + }) + let oldSession = try #require(env.manager.session) + sessions.append(oldSession) + await env.bluetooth.simulateAutoReconnecting(deviceID: env.device.id) + try await waitUntil("the previous session is withdrawn during automatic Bluetooth recovery") { + env.manager.services == nil + } + await env.bluetooth.simulateReconnected() + try await waitUntil("the same request finishes recovery with a new session") { + env.manager.connectionState == .ready && env.manager.services != nil + && env.manager.session !== oldSession && env.manager.installedLink?.didCompleteSync == true + } + let recoveredSession = try #require(env.manager.session) + sessions.append(recoveredSession) + let recoveryInitialization = await env.bluetooth.cliCommands.dropFirst(initialCLICommands.count + 2).map { + ConnectionTestRadioTransport.splitCLICommand($0).command + } + #expect(recoveryInitialization == initialCLICommands) + let canonicalInitializationStart = await env.bluetooth.cliCommands.count + if canonicalImport { + let previousSettings = try #require(env.manager.services?.settingsService) + let ghost = env.device.copy { + $0.id = UUID() + $0.radioID = UUID() + $0.publicKey = Self.canonicalKey + $0.isActive = false + $0.connectionMethods = [] + } + try await env.manager.persistenceStore.saveDevice(ghost) + await env.bluetooth.setPublicKey(Self.canonicalKey, for: env.device.id) + importer.importedConfig = MeshCoreNodeConfig(privateKey: Self.privateKey) + importer.sections = ConfigSections(nodeIdentity: true, channels: false, contacts: false) + importer.prepareConfirmation() + try await waitUntil("the real identity import caller presents confirmation") { + importer.showConfirmation || importer.errorMessage != nil + } + #expect(importer.showConfirmation) + importer.applyConfig() + try await waitUntil("the actual identity import and canonical graph rebuild settle") { + !importer.isApplying && importer.importComplete && env.manager.connectionState == .ready + && env.manager.connectedDevice?.radioID == ghost.radioID + && env.manager.installedLink?.didCompleteSync == true + } + #expect(env.manager.services?.settingsService !== previousSettings) + #expect(env.manager.session !== recoveredSession) + let canonicalInitialization = await env.bluetooth.cliCommands.dropFirst(canonicalInitializationStart).map { + ConnectionTestRadioTransport.splitCLICommand($0).command + } + #expect(canonicalInitialization == initialCLICommands) + await recoveredSession.waitForQuiescence() + #expect(await recoveredSession.subscriberCountForTest == 0) + } + #expect(env.manager.connectionRequestID == oldRequestID) + #expect(env.manager.session !== oldSession) + try sessions.append(#require(env.manager.session)) + await oldSession.waitForQuiescence() + #expect(await oldSession.subscriberCountForTest == 0) + await env.bluetooth.holdCLIReplies(for: "get wifi.ssid") + let fresh = Task { await model.noteSessionReadiness() } + workers.append(fresh) + try await waitUntil("the replacement session's first SSID request is physically delayed") { + await env.bluetooth.heldCLIReplyCount(for: "get wifi.ssid") == 1 + } + let freshSSIDCommand = try #require(await env.bluetooth.cliCommands.last { + ConnectionTestRadioTransport.splitCLICommand($0).command == "get wifi.ssid" + }) + let oldPrefix = ConnectionTestRadioTransport.splitCLICommand(oldPasswordCommand).prefix + let freshPrefix = ConnectionTestRadioTransport.splitCLICommand(freshSSIDCommand).prefix + #expect(!oldPrefix.isEmpty) + #expect(!freshPrefix.isEmpty) + #expect(oldPrefix != freshPrefix) + await env.bluetooth.releaseCLIReplies(for: "get wifi.pwd") + await env.bluetooth.releaseCLIReplies(for: "get wifi.ssid") + await fresh.value + let correctNetwork = model.networkName == Firmware.network + let secretAbsentFromNonsecretDisplay = model.networkName?.contains(Firmware.secret) != true + && !model.rebootMessage.contains(Firmware.secret) + #expect(correctNetwork) + #expect(secretAbsentFromNonsecretDisplay) + model.openEditor() + await model.loadEditor() + let correctPassword = model.passwordField == Firmware.secret + #expect(correctPassword) + model.ssidField = "after-real-replacement" + let saveEligibilityMatchesContract1 = model.canSave + #expect(saveEligibilityMatchesContract1) + await model.requestSave() + await model.refresh() + let networkObservationMatchesContract1 = model.networkName == "after-real-replacement" + #expect(networkObservationMatchesContract1) + #expect(try await env.manager.services?.settingsService.getTime() != nil) + } catch { + importer.cancelImport() + await env.bluetooth.releaseAllGates() + await env.manager.disconnect(reason: .userInitiated) + for worker in workers { + await worker.value + } + await close(model, env: env, sessions: sessions) + throw error + } + importer.cancelImport() + for worker in workers { + await worker.value + } + await close(model, env: env, sessions: sessions) + } + + private func close( + _ model: RadioWiFiViewModel, env: ConnectionLinkSwitchHarness, sessions: [MeshCoreSession] + ) async { + model.configure( + settingsService: { nil }, connectionState: { .disconnected }, + connectedDevice: { nil }, currentTransportType: { nil } + ) + await model.noteSessionReadiness() + await env.close() + for session in sessions { + await session.waitForQuiescence() + #expect(await session.subscriberCountForTest == 0) + } + let passwordKnowledgeMatchesContract1 = model.passwordField.isEmpty + #expect(passwordKnowledgeMatchesContract1) + #expect(env.manager.session == nil) + } + + private func waitUntil( + _ reason: String, _ predicate: @escaping @MainActor () async -> Bool + ) async throws { + let deadline = ContinuousClock.now + .seconds(15) + while await !predicate() { + guard ContinuousClock.now < deadline else { throw NSError(domain: reason, code: 1) } + try await Task.sleep(for: .milliseconds(1)) + } + } + + private final class Firmware: Sendable { + static let network = "configured-network" + static let secret = "synthetic-manager-password" + private let storage: Mutex + + init() { + var firmware = RadioWiFiFirmware() + firmware.savedSSID = Self.network + firmware.savedPassword = Self.secret + firmware.boot() + storage = Mutex(firmware) + } + + func reply(to command: String) -> String? { + let effective = ConnectionTestRadioTransport.splitCLICommand(command).command + if effective == "get tz.offset" { return RadioWiFiFirmware.reflectedReply("> 0", to: command) } + if effective.hasPrefix("set tz.offset ") { return RadioWiFiFirmware.reflectedReply("OK", to: command) } + return storage.withLock { $0.reply(to: command) } + } + } + + private static 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 + ]) + private static let privateKey = "7065e18fd9fabb70c1ed90dca19907de698c88b709ea146eafd93d9b830c7b60" + + "c4681193c79bbc39945ba8064104bb618f8fd7a84a0af6f57033d6e8ddcd6471" +} diff --git a/MC1Tests/Views/Settings/RadioWiFiContractObservationTests.swift b/MC1Tests/Views/Settings/RadioWiFiContractObservationTests.swift new file mode 100644 index 0000000000..70bf0060b7 --- /dev/null +++ b/MC1Tests/Views/Settings/RadioWiFiContractObservationTests.swift @@ -0,0 +1,101 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import Testing + +@Suite("Radio WiFi shared observation contract") +@MainActor +struct RadioWiFiContractObservationTests { + @Test(arguments: [ + (false, "get wifi.ssid", "initial", L10n.Settings.DeviceInfo.unknown), + (false, "get wifi.status", "confirmed", L10n.Settings.DeviceInfo.unknown), + (false, "get wifi.ip", "confirmed", L10n.Settings.RadioWiFi.Status.notConnected), + (true, "get wifi.ssid", "initial", L10n.Settings.DeviceInfo.unknown), + (true, "get wifi.status", "confirmed", L10n.Settings.DeviceInfo.unknown), + (true, "get wifi.ip", "confirmed", L10n.Settings.RadioWiFi.Status.connected) + ]) + func `partial read keeps latest enabled`( + _ initialEnabled: Bool, _ failedCommand: String, _ expectedNetwork: String, _ expectedStatus: String + ) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + var firmware = RadioWiFiFirmware(defaultSSID: "initial") + firmware.enabled = initialEnabled + firmware.boot() + await harness.transport.useFirmware(firmware) + await harness.viewModel.noteSessionReadiness() + let enabledObservationMatchesContract1 = harness.viewModel.wifiEnabled == initialEnabled + #expect(enabledObservationMatchesContract1) + let networkObservationMatchesContract1 = harness.viewModel.networkName == "initial" + #expect(networkObservationMatchesContract1) + let tools = harness.makeTools() + tools.executeCommand("set wifi.enabled \(initialEnabled ? "0" : "1")") + try await waitUntil("tracked Tools mutation settles") { !tools.isWaitingForResponse } + #expect(harness.settings?.radioWiFiState.rebootPending == true) + let settings = try #require(harness.settings) + try await settings.setRadioCLIValue("wifi.ssid", to: "confirmed") + await harness.transport.rejectNext(failedCommand) + + await harness.viewModel.refresh() + + let enabledObservationMatchesContract2 = harness.viewModel.wifiEnabled == !initialEnabled + #expect(enabledObservationMatchesContract2) + let errorPresentationMatchesContract1 = harness.viewModel.errorMessage != nil + #expect(errorPresentationMatchesContract1) + #expect(harness.viewModel.networkValue == expectedNetwork) + #expect(harness.viewModel.statusValue == expectedStatus) + if failedCommand != "get wifi.ssid" { + let networkObservationMatchesContract2 = harness.viewModel.networkName == "confirmed" + #expect(networkObservationMatchesContract2) + } + if initialEnabled { + let rebootCopyMatchesContract1 = harness.viewModel.rebootMessage == L10n.Settings.RadioWiFi.Alert.Reboot.disabled + #expect(rebootCopyMatchesContract1) + } else if failedCommand == "get wifi.ssid" { + let rebootCopyMatchesContract2 = harness.viewModel.rebootMessage == L10n.Settings.RadioWiFi.Alert.Reboot.restart + #expect(rebootCopyMatchesContract2) + } else { + let rebootCopyMatchesContract3 = harness.viewModel.rebootMessage == L10n.Settings.RadioWiFi.Alert.Reboot.join("confirmed") + #expect(rebootCopyMatchesContract3) + } + + await harness.viewModel.refresh() + let errorPresentationMatchesContract2 = harness.viewModel.errorMessage == nil + #expect(errorPresentationMatchesContract2) + let enabledObservationMatchesContract3 = harness.viewModel.wifiEnabled == !initialEnabled + #expect(enabledObservationMatchesContract3) + let networkObservationMatchesContract3 = harness.viewModel.networkName == "confirmed" + #expect(networkObservationMatchesContract3) + #expect(try await settings.getRadioCLIValue("wifi.enabled") == (initialEnabled ? "0" : "1")) + } + } + + @Test(arguments: [ + ("", L10n.Settings.RadioWiFi.Network.notSet), + ("(not connected)", "(not connected)") + ]) + func `partial read preserves known network knowledge`(_ storedSSID: String, _ expectedNetwork: String) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + var firmware = RadioWiFiFirmware() + firmware.savedSSID = "initial" + firmware.boot() + await harness.transport.useFirmware(firmware) + await harness.viewModel.noteSessionReadiness() + let settings = try #require(harness.settings) + try await settings.setRadioCLIValue("wifi.ssid", to: storedSSID) + await harness.transport.rejectNext("get wifi.status") + + await harness.viewModel.refresh() + + let networkObservationMatchesContract4 = harness.viewModel.networkName == (storedSSID.isEmpty ? nil : storedSSID) + #expect(networkObservationMatchesContract4) + #expect(harness.viewModel.networkValue == expectedNetwork) + #expect(harness.viewModel.statusValue == L10n.Settings.DeviceInfo.unknown) + let errorPresentationMatchesContract3 = harness.viewModel.errorMessage != nil + #expect(errorPresentationMatchesContract3) + await harness.viewModel.refresh() + let errorPresentationMatchesContract4 = harness.viewModel.errorMessage == nil + #expect(errorPresentationMatchesContract4) + #expect(try await settings.getRadioCLIValue("wifi.enabled") == "1") + } + } +} diff --git a/MC1Tests/Views/Settings/RadioWiFiContractOwnershipTests.swift b/MC1Tests/Views/Settings/RadioWiFiContractOwnershipTests.swift new file mode 100644 index 0000000000..5cfe86fbec --- /dev/null +++ b/MC1Tests/Views/Settings/RadioWiFiContractOwnershipTests.swift @@ -0,0 +1,73 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import Testing + +@Suite("Radio WiFi shared read ownership contract") +@MainActor +struct RadioWiFiContractOwnershipTests { + @Test + func `raw mutation during real editor read requires fresh pair`() async throws { + try await RadioWiFiContractHarness.withHarness { harness in + await harness.viewModel.noteSessionReadiness() + harness.viewModel.openEditor() + await harness.transport.holdNext("get wifi.ssid") + let read = harness.start { await harness.viewModel.loadEditor() } + try await waitUntil("editor SSID read is physically submitted") { + await harness.transport.heldCount("get wifi.ssid") == 1 + } + let tools = harness.makeTools() + tools.executeCommand("set wifi.enabled 0") + try await waitUntil("Tools mutation invalidates the read before its own send") { + harness.settings?.radioWiFiState.stableRevision() == nil + } + await harness.transport.release("get wifi.ssid") + await read.value + try await waitUntil("the queued Tools command settles") { !tools.isWaitingForResponse } + + #expect(await harness.transport.count("get wifi.pwd") == 0) + let credentialKnowledgeMatchesContract1 = harness.viewModel.needsEditorRead + #expect(credentialKnowledgeMatchesContract1) + let saveEligibilityMatchesContract1 = !harness.viewModel.canSave + #expect(saveEligibilityMatchesContract1) + await harness.viewModel.loadEditor() + let credentialKnowledgeMatchesContract2 = !harness.viewModel.needsEditorRead + #expect(credentialKnowledgeMatchesContract2) + harness.viewModel.ssidField = "after-mutation" + let saveEligibilityMatchesContract2 = harness.viewModel.canSave + #expect(saveEligibilityMatchesContract2) + await harness.viewModel.requestSave() + let settings = try #require(harness.settings) + #expect(try await settings.getRadioCLIValue("wifi.ssid") == "after-mutation") + } + } + + @Test + func `unsupported probe admits no followup and retry recovers`() async throws { + try await RadioWiFiContractHarness.withHarness { harness in + await harness.transport.markUnsupported("get wifi.enabled") + + await harness.viewModel.noteSessionReadiness() + + let viewStateMatchesContract1 = harness.viewModel.wifiSettingsSupport == .unavailable + #expect(viewStateMatchesContract1) + let viewStateMatchesContract2 = !harness.viewModel.canRunCommands + #expect(viewStateMatchesContract2) + #expect(harness.viewModel.networkValue == L10n.Settings.DeviceInfo.unknown) + #expect(harness.viewModel.statusValue == L10n.Settings.DeviceInfo.unknown) + #expect(await harness.transport.count("get wifi.ssid") == 0) + #expect(await harness.transport.count("get wifi.pwd") == 0) + harness.viewModel.openEditor() + let editorPresentationMatchesContract1 = !harness.viewModel.editorOpen + #expect(editorPresentationMatchesContract1) + await harness.transport.support("get wifi.enabled") + await harness.viewModel.refresh() + let viewStateMatchesContract3 = harness.viewModel.canRunCommands + #expect(viewStateMatchesContract3) + let networkObservationMatchesContract1 = harness.viewModel.networkName == "initial" + #expect(networkObservationMatchesContract1) + let settings = try #require(harness.settings) + #expect(try await settings.getRadioCLIValue("wifi.enabled") == "1") + } + } +} diff --git a/MC1Tests/Views/Settings/RadioWiFiContractPresentationTests+Context.swift b/MC1Tests/Views/Settings/RadioWiFiContractPresentationTests+Context.swift new file mode 100644 index 0000000000..08f9bfa1f5 --- /dev/null +++ b/MC1Tests/Views/Settings/RadioWiFiContractPresentationTests+Context.swift @@ -0,0 +1,94 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import Testing + +extension RadioWiFiContractPresentationTests { + @Test(arguments: [false, true]) + func `replacement rejects late observation at equal revision`(_ foreignRadio: Bool) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + await harness.viewModel.noteSessionReadiness() + let previous = try #require(harness.settings) + let previousBinding = previous.radioWiFiBinding + await harness.transport.useFirmware(RadioWiFiFirmware(defaultSSID: "obsolete")) + await harness.transport.holdNext("get wifi.ssid") + let read = harness.start { await harness.viewModel.refresh() } + try await waitUntil("the old observation SSID reply is held") { + await harness.transport.heldCount("get wifi.ssid") == 1 + } + await previous.retireRadioWiFiOperations() + if foreignRadio { harness.device.radioID = UUID() } + let successor = SettingsService( + session: harness.session, radioWiFiState: RadioWiFiState(radioID: harness.device.radioID) + ) + harness.settings = successor + #expect(successor.radioWiFiState.revision == previousBinding.state.revision) + #expect(successor.radioWiFiBinding.contextID != previousBinding.contextID) + await harness.transport.useFirmware(RadioWiFiFirmware(defaultSSID: "successor")) + await harness.viewModel.noteSessionReadiness() + + #expect(harness.viewModel.networkValue == L10n.Settings.DeviceInfo.unknown) + #expect(harness.viewModel.statusValue == L10n.Settings.DeviceInfo.unknown) + #expect(!harness.viewModel.statusConnected) + #expect(harness.viewModel.ipAddress == nil) + await harness.transport.holdNext("get wifi.ssid") + await harness.transport.release("get wifi.ssid") + try await waitUntil("the successor SSID read owns a real timeout after the old result") { + let held = await harness.transport.heldCount("get wifi.ssid") + let submitted = await harness.transport.count("get wifi.ssid") + return held == 1 && submitted == 3 && harness.clock.sleeperCount > 0 + } + #expect(harness.viewModel.showsSection) + #expect(harness.viewModel.networkValue == L10n.Settings.DeviceInfo.unknown) + #expect(harness.viewModel.statusValue == L10n.Settings.DeviceInfo.unknown) + #expect(await harness.transport.count("get wifi.status") == 1) + #expect(await harness.transport.count("get wifi.pwd") == 0) + harness.clock.advance(by: .seconds(31)) + await read.value + #expect(harness.viewModel.networkValue == L10n.Settings.DeviceInfo.unknown) + #expect(harness.viewModel.statusValue == L10n.Settings.DeviceInfo.unknown) + #expect(harness.viewModel.errorMessage != nil) + await harness.transport.release("get wifi.ssid") + await harness.viewModel.refresh() + #expect(harness.viewModel.networkValue == "successor") + #expect(harness.viewModel.statusValue == L10n.Settings.RadioWiFi.Status.connected) + #expect(harness.viewModel.errorMessage == nil) + harness.viewModel.openEditor() + await harness.viewModel.loadEditor() + harness.viewModel.ssidField = "after-context" + #expect(harness.viewModel.canSave) + await harness.viewModel.requestSave() + #expect(harness.viewModel.networkValue == "after-context") + #expect(try await successor.getRadioCLIValue("wifi.ssid") == "after-context") + } + } + + @Test + func `fresh session at equal revision starts with unknown observations`() async throws { + try await RadioWiFiContractHarness.withHarness { harness in + await harness.viewModel.noteSessionReadiness() + let previous = try #require(harness.settings) + let previousBinding = previous.radioWiFiBinding + let successor = try await harness.replaceSettingsRuntime() + #expect(successor !== previous) + #expect(successor.radioWiFiState.revision == previousBinding.state.revision) + #expect(successor.radioWiFiBinding.contextID != previousBinding.contextID) + await harness.transport.holdNext("get wifi.ssid") + let read = harness.start { await harness.viewModel.noteSessionReadiness() } + try await waitUntil("the fresh runtime SSID read owns a real timeout") { + await harness.transport.heldCount("get wifi.ssid") == 1 && harness.clock.sleeperCount > 0 + } + #expect(harness.viewModel.networkValue == L10n.Settings.DeviceInfo.unknown) + #expect(harness.viewModel.statusValue == L10n.Settings.DeviceInfo.unknown) + harness.clock.advance(by: .seconds(31)) + await read.value + #expect(harness.viewModel.networkValue == L10n.Settings.DeviceInfo.unknown) + #expect(harness.viewModel.statusValue == L10n.Settings.DeviceInfo.unknown) + await harness.transport.release("get wifi.ssid") + await harness.viewModel.refresh() + #expect(harness.viewModel.networkValue == "initial") + #expect(harness.viewModel.statusValue == L10n.Settings.RadioWiFi.Status.connected) + #expect(try await successor.getRadioCLIValue("wifi.enabled") == "1") + } + } +} diff --git a/MC1Tests/Views/Settings/RadioWiFiContractPresentationTests+Lifecycle.swift b/MC1Tests/Views/Settings/RadioWiFiContractPresentationTests+Lifecycle.swift new file mode 100644 index 0000000000..9fa9d8b0c6 --- /dev/null +++ b/MC1Tests/Views/Settings/RadioWiFiContractPresentationTests+Lifecycle.swift @@ -0,0 +1,77 @@ +@testable import MC1 +import Testing + +extension RadioWiFiContractPresentationTests { + @Test(arguments: [false, true]) + func `unavailable live context retains only saved observation`(_ missingService: Bool) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + await harness.viewModel.noteSessionReadiness() + let settings = try #require(harness.settings) + let before = await harness.transport.commands.count + if missingService { + harness.settings = nil + } else { + harness.connectionState = .syncing + } + + await harness.viewModel.noteSessionReadiness() + + #expect(harness.viewModel.showsSection) + #expect(harness.viewModel.networkValue == "initial") + #expect(harness.viewModel.statusValue == L10n.Settings.DeviceInfo.unknown) + #expect(!harness.viewModel.statusConnected) + #expect(harness.viewModel.ipAddress == nil) + #expect(!harness.viewModel.canRunCommands) + #expect(harness.viewModel.errorMessage == nil) + #expect(await harness.transport.commands.count == before) + harness.settings = settings + harness.connectionState = .ready + await harness.viewModel.refresh() + #expect(harness.viewModel.networkValue == "initial") + #expect(harness.viewModel.statusValue == L10n.Settings.RadioWiFi.Status.connected) + #expect(try await settings.getRadioCLIValue("wifi.enabled") == "1") + } + } + + @Test + func `contended accepted network remains visible without current revision`() async throws { + try await RadioWiFiContractHarness.withHarness { harness in + await harness.viewModel.noteSessionReadiness() + harness.viewModel.openEditor() + await harness.viewModel.loadEditor() + harness.viewModel.ssidField = "accepted-network" + harness.viewModel.passwordField = "synthetic-contended-secret" + let command = "set wifi.ssid accepted-network" + await harness.transport.holdNext(command) + let save = harness.start { await harness.viewModel.requestSave() } + try await waitUntil("the real SSID setter is held before its acknowledgement") { + await harness.transport.heldCount(command) == 1 + } + let settings = try #require(harness.settings) + let saveRevision = settings.radioWiFiState.revision + let tools = harness.makeTools() + tools.executeCommand("set wifi.enabled 0") + try await waitUntil("tracked Tools work contends with the accepted SSID setter") { + settings.radioWiFiState.revision > saveRevision + } + await harness.transport.release(command) + await save.value + try await waitUntil("the contending Tools command settles") { !tools.isWaitingForResponse } + + #expect(harness.viewModel.editorOpen) + #expect(harness.viewModel.observation.networkRevision == nil) + #expect(harness.viewModel.networkValue == "accepted-network") + #expect(!harness.viewModel.canClear) + #expect(!harness.viewModel.canSave) + #expect(harness.viewModel.needsEditorRead) + #expect(harness.viewModel.rebootMessage == L10n.Settings.RadioWiFi.Alert.Reboot.restart) + #expect(await harness.transport.count("set wifi.pwd synthetic-contended-secret") == 0) + await harness.viewModel.loadEditor() + harness.viewModel.ssidField = "after-contention" + #expect(harness.viewModel.canSave) + await harness.viewModel.requestSave() + #expect(harness.viewModel.networkValue == "after-contention") + #expect(try await settings.getRadioCLIValue("wifi.ssid") == "after-contention") + } + } +} diff --git a/MC1Tests/Views/Settings/RadioWiFiContractPresentationTests+Partial.swift b/MC1Tests/Views/Settings/RadioWiFiContractPresentationTests+Partial.swift new file mode 100644 index 0000000000..c9ecc13f0f --- /dev/null +++ b/MC1Tests/Views/Settings/RadioWiFiContractPresentationTests+Partial.swift @@ -0,0 +1,79 @@ +@testable import MC1 +import Testing + +extension RadioWiFiContractPresentationTests { + @Test(arguments: [ + (true, L10n.Settings.RadioWiFi.Status.connected), + (false, L10n.Settings.RadioWiFi.Status.notConnected) + ]) + func `confirmed association survives IP timeout`(_ enabled: Bool, _ expectedStatus: String) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + var firmware = RadioWiFiFirmware(defaultSSID: "configured") + firmware.enabled = enabled + firmware.boot() + await harness.transport.useFirmware(firmware) + await harness.transport.holdNext("get wifi.ip") + let read = harness.start { await harness.viewModel.noteSessionReadiness() } + try await waitUntil("the submitted IP read owns a real exchange timeout") { + await harness.transport.heldCount("get wifi.ip") == 1 && harness.clock.sleeperCount > 0 + } + harness.clock.advance(by: .seconds(31)) + await read.value + + #expect(harness.viewModel.networkValue == "configured") + #expect(harness.viewModel.statusValue == expectedStatus) + #expect(harness.viewModel.wifiEnabled == enabled) + #expect(harness.viewModel.ipAddress == nil) + #expect(harness.viewModel.errorMessage != nil) + #expect(await harness.transport.effectiveCommands() == [ + "get wifi.enabled", "get wifi.ssid", "get wifi.status", "get wifi.ip" + ]) + harness.viewModel.errorMessage = nil + #expect(harness.viewModel.networkValue == "configured") + #expect(harness.viewModel.statusValue == expectedStatus) + await harness.transport.release("get wifi.ip") + await harness.viewModel.refresh() + #expect(harness.viewModel.networkValue == "configured") + #expect(harness.viewModel.statusValue == expectedStatus) + #expect(harness.viewModel.errorMessage == nil) + let settings = try #require(harness.settings) + #expect(try await settings.getRadioCLIValue("wifi.enabled") != nil) + } + } + + @Test(arguments: [ + ("configured", "configured"), + ("", L10n.Settings.RadioWiFi.Network.notSet) + ]) + func `failed reload retains previously observed network`(_ ssid: String, _ expectedNetwork: String) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + await harness.transport.useFirmware(RadioWiFiFirmware(defaultSSID: ssid)) + await harness.viewModel.noteSessionReadiness() + #expect(harness.viewModel.networkValue == expectedNetwork) + await harness.transport.holdNext("get wifi.ssid") + let read = harness.start { await harness.viewModel.refresh() } + try await waitUntil("the reload SSID read owns a real exchange timeout") { + await harness.transport.heldCount("get wifi.ssid") == 1 && harness.clock.sleeperCount > 0 + } + + #expect(harness.viewModel.networkValue == expectedNetwork) + #expect(harness.viewModel.statusValue == L10n.Settings.DeviceInfo.unknown) + harness.clock.advance(by: .seconds(31)) + await read.value + #expect(harness.viewModel.networkValue == expectedNetwork) + #expect(harness.viewModel.statusValue == L10n.Settings.DeviceInfo.unknown) + #expect(harness.viewModel.errorMessage != nil) + #expect(await harness.transport.count("get wifi.status") == 1) + #expect(await harness.transport.count("get wifi.ip") == 1) + #expect(await harness.transport.count("get wifi.pwd") == 0) + harness.viewModel.errorMessage = nil + #expect(harness.viewModel.networkValue == expectedNetwork) + await harness.transport.release("get wifi.ssid") + await harness.viewModel.refresh() + #expect(harness.viewModel.networkValue == expectedNetwork) + #expect(harness.viewModel.errorMessage == nil) + let settings = try #require(harness.settings) + #expect(try await settings.getRadioCLIValue("wifi.enabled") == "1") + } + } +} diff --git a/MC1Tests/Views/Settings/RadioWiFiContractPresentationTests.swift b/MC1Tests/Views/Settings/RadioWiFiContractPresentationTests.swift new file mode 100644 index 0000000000..a3b4c9b7bb --- /dev/null +++ b/MC1Tests/Views/Settings/RadioWiFiContractPresentationTests.swift @@ -0,0 +1,149 @@ +@testable import MC1 +import Testing + +@Suite("Radio WiFi row presentation contract") +@MainActor +struct RadioWiFiContractPresentationTests { + @Test(arguments: [ + ("configured", true, "configured", L10n.Settings.RadioWiFi.Status.connected), + ("configured", false, "configured", L10n.Settings.RadioWiFi.Status.notConnected), + ("", true, L10n.Settings.RadioWiFi.Network.notSet, L10n.Settings.RadioWiFi.Status.notConnected), + ("", false, L10n.Settings.RadioWiFi.Network.notSet, L10n.Settings.RadioWiFi.Status.notConnected) + ]) + func `complete read uses observed presentation`( + _ ssid: String, _ enabled: Bool, _ expectedNetwork: String, _ expectedStatus: String + ) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + var firmware = RadioWiFiFirmware(defaultSSID: ssid) + firmware.enabled = enabled + firmware.boot() + await harness.transport.useFirmware(firmware) + + await harness.viewModel.noteSessionReadiness() + + #expect(harness.viewModel.showsSection) + #expect(harness.viewModel.wifiEnabled == enabled) + #expect(harness.viewModel.networkValue == expectedNetwork) + #expect(harness.viewModel.statusValue == expectedStatus) + #expect(harness.viewModel.errorMessage == nil) + #expect(await harness.transport.effectiveCommands() == [ + "get wifi.enabled", "get wifi.ssid", "get wifi.status", "get wifi.ip" + ]) + let settings = try #require(harness.settings) + #expect(try await settings.getRadioCLIValue("wifi.enabled") != nil) + } + } + + @Test(arguments: [ + (false, L10n.Settings.RadioWiFi.Status.notConnected, "0"), + (true, L10n.Settings.RadioWiFi.Status.connected, "1") + ]) + func `fresh SSID timeout keeps unread rows unknown`( + _ enabled: Bool, _ expectedStatus: String, _ expectedEnabled: String + ) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + var firmware = RadioWiFiFirmware(defaultSSID: "configured") + firmware.enabled = enabled + firmware.boot() + await harness.transport.useFirmware(firmware) + await harness.transport.holdNext("get wifi.ssid") + let read = harness.start { await harness.viewModel.noteSessionReadiness() } + try await waitUntil("the submitted SSID read owns a real exchange timeout") { + await harness.transport.heldCount("get wifi.ssid") == 1 && harness.clock.sleeperCount > 0 + } + + #expect(harness.viewModel.showsSection) + #expect(harness.viewModel.wifiEnabled == enabled) + #expect(harness.viewModel.networkValue == L10n.Settings.DeviceInfo.unknown) + #expect(harness.viewModel.statusValue == L10n.Settings.DeviceInfo.unknown) + #expect(harness.viewModel.ipAddress == nil) + #expect(harness.viewModel.errorMessage == nil) + #expect(await harness.transport.effectiveCommands() == ["get wifi.enabled", "get wifi.ssid"]) + + harness.clock.advance(by: .seconds(31)) + await read.value + + #expect(!harness.viewModel.isBusy) + #expect(harness.viewModel.showsSection) + #expect(harness.viewModel.wifiEnabled == enabled) + #expect(harness.viewModel.networkValue == L10n.Settings.DeviceInfo.unknown) + #expect(harness.viewModel.statusValue == L10n.Settings.DeviceInfo.unknown) + #expect(harness.viewModel.ipAddress == nil) + #expect(harness.viewModel.errorMessage != nil) + #expect(await harness.transport.effectiveCommands() == ["get wifi.enabled", "get wifi.ssid"]) + + harness.viewModel.errorMessage = nil + #expect(harness.viewModel.networkValue == L10n.Settings.DeviceInfo.unknown) + #expect(harness.viewModel.statusValue == L10n.Settings.DeviceInfo.unknown) + #expect(await harness.transport.effectiveCommands() == ["get wifi.enabled", "get wifi.ssid"]) + await harness.transport.release("get wifi.ssid") + await harness.viewModel.refresh() + + #expect(await harness.transport.heldCount("get wifi.ssid") == 0) + #expect(harness.viewModel.networkValue == "configured") + #expect(harness.viewModel.statusValue == expectedStatus) + #expect(harness.viewModel.errorMessage == nil) + #expect(harness.viewModel.canRunCommands) + let settings = try #require(harness.settings) + #expect(try await settings.getRadioCLIValue("wifi.enabled") == expectedEnabled) + } + } + + @Test(arguments: [ + ("configured", "configured", L10n.Settings.RadioWiFi.Status.connected), + ("", L10n.Settings.RadioWiFi.Network.notSet, L10n.Settings.RadioWiFi.Status.notConnected) + ]) + func `confirmed SSID survives status timeout`( + _ ssid: String, _ expectedNetwork: String, _ expectedStatus: String + ) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + await harness.transport.useFirmware(RadioWiFiFirmware(defaultSSID: ssid)) + await harness.transport.holdNext("get wifi.status") + let read = harness.start { await harness.viewModel.noteSessionReadiness() } + try await waitUntil("the submitted status read owns a real exchange timeout") { + await harness.transport.heldCount("get wifi.status") == 1 && harness.clock.sleeperCount > 0 + } + + #expect(harness.viewModel.showsSection) + #expect(harness.viewModel.wifiEnabled) + #expect(harness.viewModel.networkValue == L10n.Settings.DeviceInfo.unknown) + #expect(harness.viewModel.statusValue == L10n.Settings.DeviceInfo.unknown) + #expect(harness.viewModel.ipAddress == nil) + #expect(harness.viewModel.errorMessage == nil) + #expect(await harness.transport.effectiveCommands() == [ + "get wifi.enabled", "get wifi.ssid", "get wifi.status" + ]) + + harness.clock.advance(by: .seconds(31)) + await read.value + + #expect(!harness.viewModel.isBusy) + #expect(harness.viewModel.showsSection) + #expect(harness.viewModel.wifiEnabled) + #expect(harness.viewModel.networkValue == expectedNetwork) + #expect(harness.viewModel.statusValue == L10n.Settings.DeviceInfo.unknown) + #expect(harness.viewModel.ipAddress == nil) + #expect(harness.viewModel.errorMessage != nil) + #expect(await harness.transport.effectiveCommands() == [ + "get wifi.enabled", "get wifi.ssid", "get wifi.status" + ]) + + harness.viewModel.errorMessage = nil + #expect(harness.viewModel.networkValue == expectedNetwork) + #expect(harness.viewModel.statusValue == L10n.Settings.DeviceInfo.unknown) + #expect(await harness.transport.effectiveCommands() == [ + "get wifi.enabled", "get wifi.ssid", "get wifi.status" + ]) + await harness.transport.release("get wifi.status") + await harness.viewModel.refresh() + + #expect(await harness.transport.heldCount("get wifi.status") == 0) + #expect(harness.viewModel.networkValue == expectedNetwork) + #expect(harness.viewModel.statusValue == expectedStatus) + #expect(harness.viewModel.errorMessage == nil) + #expect(harness.viewModel.canRunCommands) + let settings = try #require(harness.settings) + #expect(try await settings.getRadioCLIValue("wifi.enabled") == "1") + } + } +} diff --git a/MC1Tests/Views/Settings/RadioWiFiContractRepresentabilityTests.swift b/MC1Tests/Views/Settings/RadioWiFiContractRepresentabilityTests.swift new file mode 100644 index 0000000000..c0373cf07e --- /dev/null +++ b/MC1Tests/Views/Settings/RadioWiFiContractRepresentabilityTests.swift @@ -0,0 +1,100 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import Testing + +@Suite("Radio WiFi firmware string representability") +@MainActor +struct RadioWiFiContractRepresentabilityTests { + @Test(arguments: [false, true]) + func `embedded NUL cannot grant draft or save authority`(_ editsPassword: Bool) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + await harness.viewModel.noteSessionReadiness() + harness.viewModel.openEditor() + await harness.viewModel.loadEditor() + let settings = try #require(harness.settings) + let capturedBaseline = harness.viewModel.editor?.baseline + let baseline = try #require(capturedBaseline) + if editsPassword { + harness.viewModel.passwordField = "synthetic\0private-value" + } else { + harness.viewModel.ssidField = "network\0truncated" + } + let invalidDraftWasRejected = !harness.viewModel.canSave + #expect(invalidDraftWasRejected) + let representabilityIsExplained = harness.viewModel.editorFooter + == L10n.Settings.RadioWiFi.Editor.unsupportedCharacter + #expect(representabilityIsExplained) + let before = await harness.transport.commands.count + var rejected = false + do { + _ = try await settings.saveRadioWiFiCredentials( + ssid: harness.viewModel.ssidField, password: harness.viewModel.passwordField, + baseline: baseline, editorID: baseline.editorID, ownerIsCurrent: { true } + ) + } catch SettingsServiceError.invalidResponse { + rejected = true + } + #expect(rejected) + #expect(await harness.transport.commands.count == before) + #expect(!settings.radioWiFiState.rebootPending) + let revisionDidNotChange = settings.radioWiFiState.stableRevision() == baseline.revision + #expect(revisionDidNotChange) + await harness.viewModel.loadEditor() + harness.viewModel.ssidField = "after-representability" + harness.viewModel.passwordField = "synthetic-valid-value" + let validDraftCanSave = harness.viewModel.canSave + #expect(validDraftCanSave) + await harness.viewModel.requestSave() + #expect(try await settings.getRadioCLIValue("wifi.ssid") == "after-representability") + let correctPassword = try await settings.getRadioCLIValue("wifi.pwd") == "synthetic-valid-value" + #expect(correctPassword) + } + } + + @Test(arguments: ["wifi.ssid", "wifi.pwd"]) + func `typed setter cannot certify A value after firmware NUL truncation`(_ key: String) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + let settings = try #require(harness.settings) + let before = await harness.transport.commands.count + var rejected = false + do { + try await settings.setRadioCLIValue(key, to: "synthetic\0truncated") + } catch let error as SettingsServiceError { + switch error { + case .invalidResponse, .sessionError(.invalidInput): rejected = true + default: throw error + } + } + #expect(rejected) + #expect(await harness.transport.commands.count == before) + #expect(!settings.radioWiFiState.rebootPending) + #expect(settings.radioWiFiState.stableRevision() != nil) + try await settings.setRadioCLIValue(key, to: "synthetic-valid-value") + let correctValue = try await settings.getRadioCLIValue(key) == "synthetic-valid-value" + #expect(correctValue) + } + } + + @Test + func `raw tools retains submitted NUL bytes and reports actual firmware effect`() async throws { + try await RadioWiFiContractHarness.withHarness { harness in + let tools = harness.makeTools() + let raw = " n0|set wifi.ssid raw-network\0ignored" + tools.executeCommand(raw) + try await waitUntil("the actual raw Tools command settles") { !tools.isWaitingForResponse } + let preservedBytes = await harness.transport.commands.contains(raw) + #expect(preservedBytes) + #expect(tools.outputLines.contains { $0.type == .response && $0.text.hasPrefix("n0|") }) + #expect(try await harness.settings?.getRadioCLIValue("wifi.ssid") == "raw-network") + await harness.viewModel.noteSessionReadiness() + harness.viewModel.openEditor() + await harness.viewModel.loadEditor() + harness.viewModel.ssidField = "after-raw-bytes" + let validDraftCanSave = harness.viewModel.canSave + #expect(validDraftCanSave) + await harness.viewModel.requestSave() + #expect(try await harness.settings?.getRadioCLIValue("wifi.ssid") == "after-raw-bytes") + } + } +} diff --git a/MC1Tests/Views/Settings/RadioWiFiContractTransport.swift b/MC1Tests/Views/Settings/RadioWiFiContractTransport.swift new file mode 100644 index 0000000000..6a41c285c2 --- /dev/null +++ b/MC1Tests/Views/Settings/RadioWiFiContractTransport.swift @@ -0,0 +1,155 @@ +import Foundation +import MC1Services + +actor RadioWiFiContractTransport: MeshTransport { + private var firmware = RadioWiFiFirmware(defaultSSID: "initial") + private let stream: AsyncStream + private let continuation: AsyncStream.Continuation + private var holds: [String: Int] = [:] + private var held: [String: [Data]] = [:] + private var rejected: Set = [] + private var unsupported: Set = [] + private var droppedBeforeApply: Set = [] + private var reflectsPrefixes = true + private(set) var commands: [String] = [] + private(set) var sentData: [Data] = [] + private(set) var isConnected = false + + init() { + (stream, continuation) = AsyncStream.makeStream(of: Data.self) + } + + var receivedData: AsyncStream { + stream + } + + func connect() { + isConnected = true + } + + func disconnect() { + isConnected = false + continuation.finish() + } + + func send(_ data: Data) throws { + guard isConnected else { throw MeshTransportError.notConnected } + guard let code = data.first else { return } + sentData.append(data) + if code == CommandCode.getStats.rawValue { + var reply = Data([ResponseCode.stats.rawValue, 0, 0x74, 0x0E]) + reply.append(withUnsafeBytes(of: UInt32(1000).littleEndian) { Data($0) }) + reply.append(contentsOf: [0, 0, 0]) + continuation.yield(reply) + return + } + if code == CommandCode.appStart.rawValue { + continuation.yield(Self.selfInfoPacket()) + return + } + guard code == CommandCode.runCliCommand.rawValue else { return } + let command = String(decoding: data.dropFirst(), as: UTF8.self) + commands.append(command) + let firmwareCommand = String(decoding: command.utf8.prefix(while: { $0 != 0 }), as: UTF8.self) + let effective = Self.effective(firmwareCommand) + if droppedBeforeApply.remove(effective) != nil { return } + let reply: Data + if rejected.remove(effective) != nil { + let text = RadioWiFiFirmware.reflectedReply("Error: rejected", to: firmwareCommand) + reply = Data([ResponseCode.cliReply.rawValue]) + Data(text.utf8) + } else { + var text = unsupported.contains(effective) + ? RadioWiFiFirmware.reflectedReply("Unknown command", to: firmwareCommand) + : firmware.reply(to: firmwareCommand) ?? "Unknown command" + if !reflectsPrefixes { + let prefix = RadioWiFiFirmware.reflectedReply("", to: firmwareCommand) + text = String(text.dropFirst(prefix.count)) + } + reply = Data([ResponseCode.cliReply.rawValue]) + Data(text.utf8) + } + if holds[effective, default: 0] > 0 { + holds[effective, default: 0] -= 1 + held[effective, default: []].append(reply) + } else { + continuation.yield(reply) + } + } + + func useFirmware(_ firmware: RadioWiFiFirmware) { + self.firmware = firmware + } + + func setReflectsPrefixes(_ value: Bool) { + reflectsPrefixes = value + } + + func rejectNext(_ command: String) { + rejected.insert(command) + } + + func dropNextBeforeApply(_ command: String) { + droppedBeforeApply.insert(command) + } + + func markUnsupported(_ command: String) { + unsupported.insert(command) + } + + func support(_ command: String) { + unsupported.remove(command) + } + + func holdNext(_ command: String) { + holds[command, default: 0] += 1 + } + + func heldCount(_ command: String) -> Int { + held[command]?.count ?? 0 + } + + func count(_ command: String) -> Int { + commands.filter { Self.effective($0) == command }.count + } + + func release(_ command: String) { + for reply in held.removeValue(forKey: command) ?? [] { + continuation.yield(reply) + } + } + + func releaseAll() { + holds.removeAll() + for replies in held.values { + for reply in replies { + continuation.yield(reply) + } + } + held.removeAll() + } + + func injectCLIReply(_ text: String) { + continuation.yield(Data([ResponseCode.cliReply.rawValue]) + Data(text.utf8)) + } + + func effectiveCommands() -> [String] { + commands.map(Self.effective) + } + + static func effective(_ command: String) -> String { + var bytes = Array(command.utf8.drop(while: { $0 == 0x20 })) + if bytes.count > 4, bytes[2] == 0x7C { bytes.removeFirst(3) } + return String(decoding: bytes, as: UTF8.self) + } + + private static func selfInfoPacket() -> Data { + var reply = Data([ResponseCode.selfInfo.rawValue, 1, 22, 22]) + reply.append(Data(repeating: 0xA1, count: ProtocolLimits.publicKeySize)) + 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: "Contract Radio".utf8) + return reply + } +} diff --git a/MC1Tests/Views/Settings/RadioWiFiContractUnicodeTests.swift b/MC1Tests/Views/Settings/RadioWiFiContractUnicodeTests.swift new file mode 100644 index 0000000000..141df960a2 --- /dev/null +++ b/MC1Tests/Views/Settings/RadioWiFiContractUnicodeTests.swift @@ -0,0 +1,78 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import Testing + +@Suite("Radio WiFi credential UTF8 identity") +@MainActor +struct RadioWiFiContractUnicodeTests { + @Test(arguments: [false, true]) + func `canonically equivalent credential edit changes stored bytes`(_ editsPassword: Bool) async throws { + try await RadioWiFiContractHarness.withHarness { harness in + let initialSSID = "unicode-network-\u{00E9}" + let initialPassword = "synthetic-unicode-\u{00E9}" + var firmware = RadioWiFiFirmware() + firmware.savedSSID = initialSSID + firmware.savedPassword = initialPassword + firmware.boot() + await harness.transport.useFirmware(firmware) + await harness.viewModel.noteSessionReadiness() + harness.viewModel.openEditor() + await harness.viewModel.loadEditor() + let initialPairMatchesWireBytes = harness.viewModel.ssidField.utf8.elementsEqual(initialSSID.utf8) + && harness.viewModel.passwordField.utf8.elementsEqual(initialPassword.utf8) + #expect(initialPairMatchesWireBytes) + let settings = try #require(harness.settings) + let capturedBaseline = harness.viewModel.editor?.baseline + let baseline = try #require(capturedBaseline) + let changedSSID = editsPassword ? initialSSID : "unicode-network-e\u{0301}" + let changedPassword = editsPassword ? "synthetic-unicode-e\u{0301}" : initialPassword + if editsPassword { + harness.viewModel.passwordField = changedPassword + } else { + harness.viewModel.ssidField = changedSSID + } + let byteChangeIsEligible = harness.viewModel.canSave + #expect(byteChangeIsEligible) + let before = await harness.transport.commands.count + let receipt = try await settings.saveRadioWiFiCredentials( + ssid: changedSSID, password: changedPassword, baseline: baseline, + editorID: baseline.editorID, ownerIsCurrent: { true } + ) + let ssidWasAccepted = receipt.ssidAccepted + let passwordOutcomeMatchesEdit = receipt.passwordAccepted == editsPassword + let noFailureReported = receipt.error == nil + #expect(ssidWasAccepted) + #expect(passwordOutcomeMatchesEdit) + #expect(noFailureReported) + let actualCommands = await harness.transport.effectiveCommands().dropFirst(before) + let submittedSSIDHasExactBytes = actualCommands.contains { + $0.utf8.elementsEqual(("set wifi.ssid " + changedSSID).utf8) + } + let submittedPasswordHasExactBytes = actualCommands.contains { + $0.utf8.elementsEqual(("set wifi.pwd " + changedPassword).utf8) + } + #expect(submittedSSIDHasExactBytes) + #expect(submittedPasswordHasExactBytes == editsPassword) + let storedSSID = try await settings.getRadioCLIValue("wifi.ssid") + let storedPassword = try await settings.getRadioCLIValue("wifi.pwd") + let changedPairMatchesWireBytes = storedSSID?.utf8.elementsEqual(changedSSID.utf8) == true + && storedPassword?.utf8.elementsEqual(changedPassword.utf8) == true + #expect(changedPairMatchesWireBytes) + + await harness.viewModel.closeEditor() + await harness.viewModel.refresh() + harness.viewModel.openEditor() + await harness.viewModel.loadEditor() + harness.viewModel.ssidField = "after-unicode-edit" + harness.viewModel.passwordField = "synthetic-later-valid" + let laterDraftCanSave = harness.viewModel.canSave + #expect(laterDraftCanSave) + await harness.viewModel.requestSave() + #expect(try await settings.getRadioCLIValue("wifi.ssid") == "after-unicode-edit") + let laterPassword = try await settings.getRadioCLIValue("wifi.pwd") + let laterPasswordMatchesWireBytes = laterPassword?.utf8.elementsEqual("synthetic-later-valid".utf8) == true + #expect(laterPasswordMatchesWireBytes) + } + } +} diff --git a/MC1Tests/Views/Settings/RadioWiFiContractUnknownEnabledTests.swift b/MC1Tests/Views/Settings/RadioWiFiContractUnknownEnabledTests.swift new file mode 100644 index 0000000000..8300e4ce46 --- /dev/null +++ b/MC1Tests/Views/Settings/RadioWiFiContractUnknownEnabledTests.swift @@ -0,0 +1,56 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import Testing + +@Suite("Radio WiFi unknown enabled knowledge") +@MainActor +struct RadioWiFiContractUnknownEnabledTests { + @Test + func `failed readback after uncertain enabled write withdraws commands until retry`() async throws { + try await RadioWiFiContractHarness.withHarness { harness in + await harness.viewModel.noteSessionReadiness() + await harness.transport.holdNext("set wifi.enabled 0") + await harness.transport.rejectNext("get wifi.enabled") + let write = harness.start { await harness.viewModel.setWiFiEnabled(false) } + try await waitUntil("the submitted enabled change owns a real exchange timeout") { + await harness.transport.heldCount("set wifi.enabled 0") == 1 && harness.clock.sleeperCount > 0 + } + harness.clock.advance(by: .seconds(31)) + await write.value + let readbackFailed = harness.viewModel.errorMessage != nil + let commandsWithdrawn = !harness.viewModel.canRunCommands + let editorWithdrawn = !harness.viewModel.canEditNetwork + let pendingRetained = harness.viewModel.rebootPending + #expect(readbackFailed) + #expect(commandsWithdrawn) + #expect(editorWithdrawn) + #expect(pendingRetained) + let before = await harness.transport.sentData.count + harness.viewModel.openEditor() + let editorStayedClosed = !harness.viewModel.editorOpen + #expect(editorStayedClosed) + harness.viewModel.requestReboot() + let rebootNotAdmitted = !harness.viewModel.showingRebootConfirm + #expect(rebootNotAdmitted) + await harness.viewModel.confirmFromAlert(.reboot).value + await harness.viewModel.setWiFiEnabled(true) + #expect(await harness.transport.sentData.count == before) + await harness.viewModel.closeEditor() + + await harness.viewModel.refresh() + let freshKnowledgeRestoresCommands = harness.viewModel.canRunCommands + #expect(freshKnowledgeRestoresCommands) + harness.viewModel.openEditor() + await harness.viewModel.loadEditor() + harness.viewModel.ssidField = "after-failed-enabled-read" + let freshPairCanSave = harness.viewModel.canSave + #expect(freshPairCanSave) + await harness.viewModel.requestSave() + let settings = try #require(harness.settings) + #expect(try await settings.getRadioCLIValue("wifi.ssid") == "after-failed-enabled-read") + await harness.viewModel.setWiFiEnabled(true) + #expect(try await settings.getRadioCLIValue("wifi.enabled") == "1") + } + } +} diff --git a/MC1Tests/Views/Settings/RadioWiFiObservationTests.swift b/MC1Tests/Views/Settings/RadioWiFiObservationTests.swift new file mode 100644 index 0000000000..c4befec8eb --- /dev/null +++ b/MC1Tests/Views/Settings/RadioWiFiObservationTests.swift @@ -0,0 +1,61 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import MeshCore +import Testing + +@Suite("Radio WiFi observation") +@MainActor +struct RadioWiFiObservationTests { + @Test + func `expected reboot readback refreshes the badge without a configuration mutation`() async throws { + try await ConnectionLinkSwitchHarness.withHarness { harness in + let appState = harness.appState + await appState.wireServicesIfConnected() + let service = try #require(appState.services?.settingsService) + let viewModel = RadioWiFiViewModel() + viewModel.configure( + settingsService: { appState.services?.settingsService }, + connectionState: { appState.connectionState }, + connectedDevice: { appState.connectedDevice }, + currentTransportType: { appState.connectionManager.currentTransportType } + ) + await viewModel.noteSessionReadiness() + let beforeMutation = appState.radioWiFiSettingsRevision + try await service.setRadioCLIValue("wifi.enabled", to: "0") + try await waitUntil("accepted mutation should refresh WiFi observation") { + appState.radioWiFiSettingsRevision == beforeMutation + 2 + } + #expect(viewModel.rebootPending) + + let state = service.radioWiFiState + let oldContextID = UUID() + let observedAt = ContinuousClock.now + let before = RadioWiFiResetObservation(uptimeSeconds: 1000, startedAt: observedAt, completedAt: observedAt) + let candidate = try #require(state.prepareExpectedReboot(contextID: oldContextID, observation: before)) + state.completeRebootSubmission(id: candidate, succeeded: true) + state.noteLinkEnded(contextID: oldContextID) + await harness.bluetooth.setResponsePackets( + for: .getStats, packets: [Data([ResponseCode.stats.rawValue, 0, 0x74, 0x0E, 1, 0, 0, 0, 0, 0, 0])] + ) + let mutationRevision = state.revision + let beforeClear = appState.radioWiFiSettingsRevision + let staleOwnerCleared = await service.confirmExpectedRadioWiFiReboot( + id: candidate, expectedRadioID: state.radioID, ownerIsCurrent: { false } + ) + #expect(!staleOwnerCleared) + #expect(state.rebootPending) + #expect(appState.radioWiFiSettingsRevision == beforeClear) + + #expect(await service.confirmExpectedRadioWiFiReboot( + id: candidate, expectedRadioID: state.radioID, ownerIsCurrent: { true } + )) + + try await waitUntil("readback clear should refresh WiFi observation") { + appState.radioWiFiSettingsRevision == beforeClear + 1 + } + #expect(state.revision == mutationRevision) + #expect(!viewModel.rebootPending) + } + } +} diff --git a/MC1Tests/Views/Settings/RadioWiFiViewModelTests.swift b/MC1Tests/Views/Settings/RadioWiFiViewModelTests.swift index 1e6bf2082e..84dc25ec20 100644 --- a/MC1Tests/Views/Settings/RadioWiFiViewModelTests.swift +++ b/MC1Tests/Views/Settings/RadioWiFiViewModelTests.swift @@ -1,6 +1,7 @@ import Foundation @testable import MC1 @testable import MC1Services +import SwiftUI import Testing @Suite("Radio WiFi view model") @@ -73,6 +74,180 @@ struct RadioWiFiViewModelTests { #expect(calls.count == before) } + @Test + func `a failed first password read keeps Save disabled`() async { + let harness = await Harness.make() + await harness.mock.setCLIReplyQueue(["> 1", "> stored", "> connected", "> 10.0.0.8"]) + await harness.viewModel.noteSessionReadiness() + harness.viewModel.openEditor() + await harness.mock.setCLIReplyQueue(["> stored"]) + await harness.mock.failCLICommand(after: 1, MeshCoreError.timeout) + + await harness.viewModel.loadEditor() + harness.viewModel.ssidField = "replacement" + let before = await harness.mock.runCliCommandCalls.count + + #expect(harness.viewModel.errorMessage != nil) + #expect(harness.viewModel.canSave == false) + await harness.viewModel.requestSave() + + #expect(await harness.mock.runCliCommandCalls.count == before) + #expect(harness.viewModel.editorOpen) + } + + @Test(arguments: CredentialReadFailure.allCases) + private func `unknown password knowledge requires a fresh editor Retry`(_ failure: CredentialReadFailure) async { + let harness = await Harness.make() + await harness.mock.setCLIReplyQueue(["> 1", "> stored", "> connected", "> 10.0.0.8"]) + await harness.viewModel.noteSessionReadiness() + harness.viewModel.openEditor() + await failure.prime(harness.mock) + + await harness.viewModel.loadEditor() + harness.viewModel.ssidField = "draft" + let before = await harness.mock.runCliCommandCalls.count + #expect(!harness.viewModel.canSave) + #expect(harness.viewModel.needsEditorRead) + await harness.viewModel.requestSave() + #expect(await harness.mock.runCliCommandCalls.count == before) + + await harness.mock.setCLIReplyQueue(["> stored", "> recovered-key"]) + await harness.viewModel.loadEditor() + + #expect(harness.viewModel.canSave) + #expect(harness.viewModel.ssidField == "draft") + #expect(!harness.viewModel.needsEditorRead) + #expect(harness.viewModel.errorMessage == nil) + await harness.viewModel.closeEditor() + #expect(harness.viewModel.passwordField.isEmpty) + #expect(harness.viewModel.ssidField.isEmpty) + } + + @Test + func `Retry refreshes an untouched password after a foreign mutation`() async throws { + let harness = await Harness.make() + await harness.mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + await harness.viewModel.noteSessionReadiness() + harness.viewModel.openEditor() + await harness.viewModel.loadEditor() + harness.viewModel.ssidField = "draft" + let settings = try #require(harness.settings) + _ = try await settings.runCliCommand("set wifi.pwd terminal-key") + #expect(!harness.viewModel.canSave) + + await harness.viewModel.loadEditor() + let passwordRefreshed = harness.viewModel.passwordField == "terminal-key" + #expect(passwordRefreshed) + let before = await harness.mock.runCliCommandCalls.count + await harness.viewModel.requestSave() + + #expect(await Array(harness.mock.runCliCommandCalls.dropFirst(before)) == ["set wifi.ssid draft"]) + await harness.mock.bootWiFiFirmware() + #expect(await harness.mock.wiFiBootUses(ssid: "draft", password: "terminal-key")) + #expect(harness.viewModel.passwordField.isEmpty) + } + + @Test + func `repeated raw mutations invalidate an open editor after each fresh Retry`() async throws { + let harness = await Harness.make() + await harness.mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + await harness.viewModel.noteSessionReadiness() + harness.viewModel.openEditor() + await harness.viewModel.loadEditor() + harness.viewModel.ssidField = "draft" + let settings = try #require(harness.settings) + + for value in ["first-key", "second-key"] { + _ = try await settings.runCliCommand("set wifi.pwd \(value)") + await harness.viewModel.noteSessionReadiness() + #expect(harness.viewModel.needsEditorRead) + #expect(!harness.viewModel.canSave) + await harness.viewModel.loadEditor() + #expect(!harness.viewModel.needsEditorRead) + #expect(harness.viewModel.canSave) + #expect(harness.viewModel.ssidField == "draft") + let passwordRefreshed = harness.viewModel.passwordField == value + #expect(passwordRefreshed) + } + await harness.viewModel.closeEditor() + } + + @Test + func `same-service unreadiness freezes the draft and replacement erases it`() async { + let harness = await Harness.make() + await harness.loadNetwork(ssid: "stored", password: "stored-key") + harness.viewModel.openEditor() + harness.viewModel.ssidField = "draft" + harness.connectionState = .syncing + await harness.viewModel.noteSessionReadiness() + + #expect(!harness.viewModel.canSave) + #expect(harness.viewModel.editorOpen) + #expect(harness.viewModel.ssidField == "draft") + #expect(!harness.viewModel.statusConnected) + + harness.connectionState = .ready + await harness.viewModel.noteSessionReadiness() + #expect(harness.viewModel.canSave) + let replacement = MockConfigurationSession() + await replacement.setCLIReply("Unknown command") + harness.settings = SettingsService(session: replacement, radioWiFiState: RadioWiFiState(radioID: harness.device.radioID)) + await harness.viewModel.noteSessionReadiness() + + #expect(!harness.viewModel.editorOpen) + #expect(harness.viewModel.passwordField.isEmpty) + #expect(harness.viewModel.ssidField.isEmpty) + #expect(!harness.viewModel.canSave) + } + + @Test + func `a WiFi warning cannot submit credentials after a raw mutation`() async throws { + let harness = await Harness.make() + harness.transport.value = .wifi + await harness.loadNetwork(ssid: "stored", password: "stored-key") + harness.viewModel.openEditor() + harness.viewModel.ssidField = "draft" + await harness.viewModel.requestSave() + #expect(harness.viewModel.showingWiFiWarning) + let settings = try #require(harness.settings) + _ = try await settings.runCliCommand("set wifi.enabled 0") + let before = await harness.mock.runCliCommandCalls.count + + await harness.viewModel.confirmFromAlert(.wifiWarning).value + + #expect(await harness.mock.runCliCommandCalls.count == before) + #expect(!harness.viewModel.showingWiFiWarning) + #expect(!harness.viewModel.canSave) + #expect(harness.viewModel.needsEditorRead) + #expect(harness.viewModel.editorOpen) + } + + @Test + func `an uncertain enable write reads back before restoring commands`() async { + let harness = await Harness.make() + await harness.mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + await harness.viewModel.noteSessionReadiness() + await harness.mock.failWiFiCommand("set wifi.enabled 0", with: .timeoutAfterApply) + let before = await harness.mock.runCliCommandCalls.count + + await harness.viewModel.setWiFiEnabled(false) + + let readback = await harness.mock.runCliCommandCalls.dropFirst(before) + #expect(Array(readback) == [ + "set wifi.enabled 0", "get wifi.enabled", "get wifi.ssid", "get wifi.status", "get wifi.ip" + ]) + #expect(harness.viewModel.canRunCommands) + #expect(!harness.viewModel.wifiEnabled) + #expect(harness.viewModel.errorMessage == nil) + #expect(harness.viewModel.rebootPending) + await harness.viewModel.refresh() + #expect(harness.viewModel.canRunCommands) + #expect(!harness.viewModel.wifiEnabled) + #expect(harness.viewModel.statusConnected) + #expect(harness.viewModel.rebootPending) + #expect(harness.viewModel.errorMessage == nil) + } + @Test func `an empty password is sent with a trailing space`() async { let harness = await Harness.make() @@ -206,7 +381,7 @@ struct RadioWiFiViewModelTests { #expect(harness.viewModel.linkWarningTitle == L10n.Settings.RadioWiFi.Alert.Save.title) #expect(harness.viewModel.linkWarningConfirmTitle == L10n.Localizable.Common.save) - await harness.viewModel.continuePastWiFiWarning() + await harness.viewModel.confirmFromAlert(.wifiWarning).value calls = await harness.mock.runCliCommandCalls #expect(Array(calls.dropFirst(before)) == ["set wifi.ssid other"]) } @@ -241,22 +416,22 @@ struct RadioWiFiViewModelTests { harness.viewModel.requestReboot() harness.viewModel.cancelReboot() - #expect(harness.rebootCount == 0) + #expect(await harness.mock.rebootCallCount == 0) #expect(harness.viewModel.showingRebootConfirm == false) harness.viewModel.requestReboot() - await harness.viewModel.confirmReboot() - #expect(harness.rebootCount == 1) + await harness.viewModel.confirmFromAlert(.reboot).value + #expect(await harness.mock.rebootCallCount == 1) } @Test func `a load that finishes after services change applies nothing`() async { let mock = MockConfigurationSession() await mock.setCLIReplyQueue(["> 1", "> myssid", "> connected", "> 10.0.0.8"]) - let first = SettingsService(session: mock) - let replacement = SettingsService(session: mock) - let viewModel = RadioWiFiViewModel() let device = Harness.radio() + let first = SettingsService(session: mock, radioWiFiState: RadioWiFiState(radioID: device.radioID)) + let replacement = SettingsService(session: mock, radioWiFiState: RadioWiFiState(radioID: device.radioID)) + let viewModel = RadioWiFiViewModel() var current: SettingsService? = first viewModel.configure( settingsService: { @@ -266,15 +441,14 @@ struct RadioWiFiViewModelTests { }, connectionState: { .ready }, connectedDevice: { device }, - currentTransportType: { .bluetooth }, - reboot: {} + currentTransportType: { .bluetooth } ) await viewModel.load() #expect(viewModel.showsSection == false) #expect(viewModel.networkName == nil) - #expect(await mock.runCliCommandCalls == ["get wifi.enabled"]) + #expect(await mock.runCliCommandCalls.isEmpty) } @Test @@ -300,7 +474,7 @@ struct RadioWiFiViewModelTests { "> (not connected)" ]) await harness.viewModel.noteSessionReadiness() - await harness.mock.setCLIReply("> pw ") + await harness.mock.setCLIReplyQueue(["> (not connected)", "> pw "]) await harness.viewModel.loadEditor() #expect(harness.viewModel.networkName == "(not connected)") @@ -342,7 +516,7 @@ struct RadioWiFiViewModelTests { await harness.viewModel.requestSave() harness.viewModel.ssidField = "B" - await harness.viewModel.continuePastWiFiWarning() + await harness.viewModel.confirmFromAlert(.wifiWarning).value let calls = await harness.mock.runCliCommandCalls #expect(Array(calls.dropFirst(before)) == ["set wifi.ssid A"]) @@ -364,7 +538,7 @@ struct RadioWiFiViewModelTests { await harness.viewModel.requestSave() await harness.viewModel.load() await harness.viewModel.setWiFiEnabled(false) - await harness.viewModel.confirmClear() + await harness.viewModel.confirmFromAlert(.clear).value await harness.mock.releaseHeldCLIReply() await task.value @@ -376,8 +550,8 @@ struct RadioWiFiViewModelTests { func `the editor is busy until the password read returns`() async throws { let harness = await Harness.make() await harness.loadNetwork(ssid: "old", password: "old") - await harness.mock.holdNextCLIReply() - await harness.mock.setCLIReply("> pw") + await harness.mock.holdCLIReply(after: 1) + await harness.mock.setCLIReplyQueue(["> old", "> pw"]) let task = Task { await harness.viewModel.loadEditor() } try await waitUntil("password read held") { await harness.mock.heldCLICommand == "get wifi.pwd" @@ -398,7 +572,7 @@ struct RadioWiFiViewModelTests { await harness.loadNetwork(ssid: "old", password: "") harness.viewModel.ssidField = "new" harness.viewModel.passwordField = "P" - harness.viewModel.editorOpen = true + harness.viewModel.openEditor() await harness.mock.setCLIReplyQueue(["OK", "Error: bad"]) let before = await harness.mock.runCliCommandCalls.count @@ -487,7 +661,7 @@ struct RadioWiFiViewModelTests { await harness.viewModel.setWiFiEnabled(false) #expect(harness.viewModel.showingWiFiWarning) - await harness.viewModel.continuePastWiFiWarning() + await harness.viewModel.confirmFromAlert(.wifiWarning).value #expect(harness.viewModel.wifiEnabled == false) #expect(harness.viewModel.networkName == "Field Net") @@ -516,6 +690,8 @@ struct RadioWiFiViewModelTests { let harness = await Harness.make() await harness.mock.setCLIReplyQueue(["> 1", "> myssid", "> connected", "> 10.0.0.8"]) await harness.viewModel.noteSessionReadiness() + await harness.mock.setCLIReplyQueue(["> myssid", "> original-key"]) + await harness.viewModel.loadEditor() harness.viewModel.ssidField = "myssid" harness.viewModel.passwordField = "pw" await harness.mock.setCLIReply("OK") @@ -561,7 +737,7 @@ struct RadioWiFiViewModelTests { #expect(harness.viewModel.rebootPending == false) let nextMock = MockConfigurationSession() - let next = SettingsService(session: nextMock) + let next = SettingsService(session: nextMock, radioWiFiState: RadioWiFiState(radioID: harness.device.radioID)) await nextMock.setCLIReply("OK") try await next.setRadioCLIValue("wifi.enabled", to: "0") await nextMock.setCLIReplyQueue(["> 0", "> cafe", "> (not connected)", "> 192.168.0.4"]) @@ -598,6 +774,8 @@ struct RadioWiFiViewModelTests { #expect(harness.viewModel.wifiEnabled) #expect(harness.viewModel.networkName == "myssid") #expect(harness.viewModel.statusConnected) + #expect(harness.viewModel.networkValue == "myssid") + #expect(harness.viewModel.statusValue == L10n.Settings.RadioWiFi.Status.connected) #expect(harness.viewModel.ipAddress == "10.0.0.8") } @@ -606,7 +784,7 @@ struct RadioWiFiViewModelTests { let harness = await Harness.make() await harness.mock.setCLIReplyQueue(["> 1", "> myssid", "> connected", "> 10.0.0.8"]) await harness.viewModel.noteSessionReadiness() - harness.viewModel.editorOpen = true + harness.viewModel.openEditor() let before = await harness.mock.runCliCommandCalls.count await harness.mock.setCLIReplyQueue(["> 1", "> cafe", "> connected", "> 10.0.0.5"]) @@ -616,7 +794,7 @@ struct RadioWiFiViewModelTests { #expect(harness.viewModel.networkName == "myssid") #expect(harness.viewModel.ipAddress == "10.0.0.8") - harness.viewModel.editorOpen = false + await harness.viewModel.closeEditor() try await waitUntil("editor close reloads wifi") { harness.viewModel.networkName == "cafe" } @@ -670,7 +848,7 @@ struct RadioWiFiViewModelTests { await harness.viewModel.noteSessionReadiness() let laterMock = MockConfigurationSession() - let later = SettingsService(session: laterMock) + let later = SettingsService(session: laterMock, radioWiFiState: RadioWiFiState(radioID: harness.device.radioID)) await laterMock.setCLIReply("OK") try await later.setRadioCLIValue("wifi.ssid", to: "later") await laterMock.setCLIReplyQueue(["> 1", "> later", "> connected", "> 10.2.2.2"]) @@ -721,9 +899,9 @@ struct RadioWiFiViewModelTests { await harness.viewModel.requestSave() await harness.viewModel.setWiFiEnabled(false) harness.viewModel.requestClear() - await harness.viewModel.confirmClear() + await harness.viewModel.confirmFromAlert(.clear).value harness.viewModel.requestReboot() - await harness.viewModel.confirmReboot() + await harness.viewModel.confirmFromAlert(.reboot).value #expect(await harness.mock.runCliCommandCalls.count == before) #expect(harness.viewModel.errorMessage == nil) @@ -731,13 +909,15 @@ struct RadioWiFiViewModelTests { #expect(harness.viewModel.networkName == "myssid") #expect(harness.viewModel.showingClearConfirm == false) #expect(harness.viewModel.showingRebootConfirm == false) - #expect(harness.rebootCount == 0) + #expect(await harness.mock.rebootCallCount == 0) } @Test - func `a reboot that drops the link does not alert`() async { + func `a reboot that drops the link does not alert`() async throws { let harness = await Harness.make() await harness.loadNetwork(ssid: "myssid", password: "secret") + let settings = try #require(harness.settings) + try await settings.setRadioCLIValue("wifi.ssid", to: "myssid") let errors: [any Error] = [ BLEError.notConnected, BLEError.operationTimeout, @@ -746,26 +926,28 @@ struct RadioWiFiViewModelTests { ] for error in errors { - harness.rebootError = error + await harness.mock.failReboot(error) harness.viewModel.requestReboot() - await harness.viewModel.confirmReboot() + await harness.viewModel.confirmFromAlert(.reboot).value #expect(harness.viewModel.errorMessage == nil) } - #expect(harness.rebootCount == errors.count) + #expect(await harness.mock.rebootCallCount == errors.count) #expect(harness.viewModel.networkName == "myssid") } @Test - func `a reboot that fails before the radio resets still alerts`() async { + func `a reboot that fails before the radio resets still alerts`() async throws { let harness = await Harness.make() await harness.loadNetwork(ssid: "myssid", password: "secret") - harness.rebootError = SettingsServiceError.notConnected + let settings = try #require(harness.settings) + try await settings.setRadioCLIValue("wifi.ssid", to: "myssid") + await harness.mock.failReboot(SettingsServiceError.notConnected) harness.viewModel.requestReboot() - await harness.viewModel.confirmReboot() + await harness.viewModel.confirmFromAlert(.reboot).value - #expect(harness.rebootCount == 1) + #expect(await harness.mock.rebootCallCount == 1) #expect(harness.viewModel.errorMessage == SettingsServiceError.notConnected.userFacingMessage) #expect(harness.viewModel.networkName == "myssid") } @@ -785,7 +967,7 @@ struct RadioWiFiViewModelTests { } @Test(arguments: [1, 2, 3]) - func `a later read failure keeps support and clears association`(_ skip: Int) async { + func `a later read failure retains completed nonsecret fields`(_ skip: Int) async { let harness = await Harness.make() await harness.mock.setCLIReplyQueue(["> 1", "> myssid", "> connected", "> 10.0.0.8"]) await harness.mock.failCLICommand(after: skip, MeshCoreError.timeout) @@ -795,10 +977,10 @@ struct RadioWiFiViewModelTests { #expect(harness.viewModel.showsSection) #expect(harness.viewModel.wifiSettingsSupport == .supported) #expect(harness.viewModel.wifiEnabled) - #expect(harness.viewModel.statusConnected == false) + #expect(harness.viewModel.statusConnected == (skip == 3)) #expect(harness.viewModel.ipAddress == nil) #expect(harness.viewModel.errorMessage != nil) - #expect(harness.viewModel.canClear == false) + #expect(harness.viewModel.canClear == (skip > 1)) let calls = await harness.mock.runCliCommandCalls #expect(calls.count == skip + 1) #expect(calls.first == "get wifi.enabled") @@ -882,17 +1064,20 @@ struct RadioWiFiViewModelTests { @Test func `refresh waits until the editor closes`() async throws { let harness = await Harness.make() - await harness.mock.failNextCLICommand(MeshCoreError.timeout) + await harness.mock.setCLIReplyQueue(["> 1", "> original", "> connected", "> 10.0.0.8"]) await harness.viewModel.noteSessionReadiness() + harness.viewModel.openEditor() + await harness.mock.setCLIReplyQueue(["> original"]) + await harness.mock.failCLICommand(after: 1, MeshCoreError.timeout) + await harness.viewModel.loadEditor() #expect(harness.viewModel.errorMessage != nil) - harness.viewModel.editorOpen = true await harness.mock.setCLIReplyQueue(["> 1", "> cafe", "> connected", "> 10.2.2.2"]) let before = await harness.mock.runCliCommandCalls.count await harness.viewModel.refresh() #expect(await harness.mock.runCliCommandCalls.count == before) - #expect(harness.viewModel.showsSection == false) + #expect(harness.viewModel.showsSection) #expect( RadioWiFiViewModel.recoverySurface( errorMessage: harness.viewModel.errorMessage, @@ -901,7 +1086,7 @@ struct RadioWiFiViewModelTests { ) == .editor ) - harness.viewModel.editorOpen = false + await harness.viewModel.closeEditor() try await waitUntil("editor close recovers wifi") { harness.viewModel.ipAddress == "10.2.2.2" } @@ -936,7 +1121,7 @@ struct RadioWiFiViewModelTests { let nextMock = MockConfigurationSession() await nextMock.failNextCLICommand(MeshCoreError.timeout) harness.device = Harness.radio() - harness.settings = SettingsService(session: nextMock) + harness.settings = SettingsService(session: nextMock, radioWiFiState: RadioWiFiState(radioID: harness.device.radioID)) await harness.viewModel.noteSessionReadiness() #expect(harness.viewModel.showsSection == false) @@ -959,7 +1144,7 @@ struct RadioWiFiViewModelTests { let nextMock = MockConfigurationSession() await nextMock.setCLIReply("Unknown command") harness.device = Harness.radio() - harness.settings = SettingsService(session: nextMock) + harness.settings = SettingsService(session: nextMock, radioWiFiState: RadioWiFiState(radioID: harness.device.radioID)) await harness.viewModel.noteSessionReadiness() #expect(harness.viewModel.wifiSettingsSupport == .unavailable) @@ -979,7 +1164,7 @@ struct RadioWiFiViewModelTests { #expect(harness.viewModel.rebootPending) let nextMock = MockConfigurationSession() - let next = SettingsService(session: nextMock) + let next = SettingsService(session: nextMock, radioWiFiState: RadioWiFiState(radioID: harness.device.radioID)) await nextMock.setCLIReplyQueue(["> 1", "> cafe", "> connected", "> 10.4.4.4"]) await nextMock.holdNextCLIReply() harness.settings = next @@ -1019,7 +1204,7 @@ struct RadioWiFiViewModelTests { let nextMock = MockConfigurationSession() await nextMock.failNextCLICommand(MeshCoreError.timeout) - harness.settings = SettingsService(session: nextMock) + harness.settings = SettingsService(session: nextMock, radioWiFiState: RadioWiFiState(radioID: harness.device.radioID)) await harness.viewModel.noteSessionReadiness() #expect(harness.viewModel.showsSection == false) @@ -1036,6 +1221,8 @@ struct RadioWiFiViewModelTests { let harness = await Harness.make() await harness.mock.setCLIReplyQueue(["> 1", "> old", "> connected", "> 10.0.0.8"]) await harness.viewModel.noteSessionReadiness() + await harness.mock.setCLIReplyQueue(["> old", "> original-key"]) + await harness.viewModel.loadEditor() harness.viewModel.ssidField = "older" await harness.mock.setCLIReply("OK") await harness.viewModel.requestSave() @@ -1051,7 +1238,7 @@ struct RadioWiFiViewModelTests { let nextMock = MockConfigurationSession() await nextMock.setCLIReplyQueue(["> 0", "> fresh", "> (not connected)", "> (not connected)"]) harness.device = Harness.radio() - harness.settings = SettingsService(session: nextMock) + harness.settings = SettingsService(session: nextMock, radioWiFiState: RadioWiFiState(radioID: harness.device.radioID)) await harness.viewModel.noteSessionReadiness() await harness.mock.releaseHeldCLIReply() await task.value @@ -1084,7 +1271,7 @@ struct RadioWiFiViewModelTests { let nextMock = MockConfigurationSession() await nextMock.failNextCLICommand(MeshCoreError.timeout) harness.device = Harness.radio() - harness.settings = SettingsService(session: nextMock) + harness.settings = SettingsService(session: nextMock, radioWiFiState: RadioWiFiState(radioID: harness.device.radioID)) await harness.viewModel.noteSessionReadiness() await harness.mock.setCLIReply("OK") await harness.mock.releaseHeldCLIReply() @@ -1114,7 +1301,7 @@ struct RadioWiFiViewModelTests { let nextMock = MockConfigurationSession() await nextMock.setCLIReply("Unknown command") harness.device = Harness.radio() - harness.settings = SettingsService(session: nextMock) + harness.settings = SettingsService(session: nextMock, radioWiFiState: RadioWiFiState(radioID: harness.device.radioID)) await harness.viewModel.noteSessionReadiness() #expect(harness.viewModel.errorMessage == nil) @@ -1128,6 +1315,197 @@ struct RadioWiFiViewModelTests { #expect(harness.viewModel.canClear == false) } + @Test(arguments: AlertConfirmationCase.allCases) + private func `alert button consumption survives framework binding dismissal`( + _ action: AlertConfirmationCase + ) async throws { + let harness = await Harness.make() + await harness.mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + await harness.viewModel.noteSessionReadiness() + try await action.prepare(harness) + let before = await harness.mock.runCliCommandCalls.count + let binding = action.presentationBinding(harness.viewModel) + #expect(binding.wrappedValue) + + let accepted = harness.viewModel.confirmFromAlert(action.entry) + binding.wrappedValue = false + await accepted.value + + let writes = await harness.mock.runCliCommandCalls.dropFirst(before).filter { $0.hasPrefix("set ") } + #expect(writes == action.expectedWrites) + #expect(await harness.mock.rebootCallCount == (action == .reboot ? 1 : 0)) + #expect(harness.viewModel.confirmation == nil) + #expect(!harness.viewModel.isBusy) + await harness.viewModel.closeEditor() + await harness.settings?.retireRadioWiFiOperations() + } + + @Test(arguments: AlertConfirmationCase.allCases) + private func `duplicate alert confirm submits once`(_ action: AlertConfirmationCase) async throws { + let harness = await Harness.make() + await harness.mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + await harness.viewModel.noteSessionReadiness() + try await action.prepare(harness) + let before = await harness.mock.runCliCommandCalls.count + let accepted = harness.viewModel.confirmFromAlert(action.entry) + let duplicate = harness.viewModel.confirmFromAlert(action.entry) + action.presentationBinding(harness.viewModel).wrappedValue = false + await accepted.value + await duplicate.value + + let writes = await harness.mock.runCliCommandCalls.dropFirst(before).filter { $0.hasPrefix("set ") } + #expect(writes == action.expectedWrites) + #expect(await harness.mock.rebootCallCount == (action == .reboot ? 1 : 0)) + await harness.viewModel.closeEditor() + await harness.settings?.retireRadioWiFiOperations() + } + + @Test(arguments: AlertConfirmationCase.allCases, [false, true]) + private func `cancelled and obsolete alert contexts submit nothing`( + _ action: AlertConfirmationCase, obsolete: Bool + ) async throws { + let harness = await Harness.make() + await harness.mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + await harness.viewModel.noteSessionReadiness() + try await action.prepare(harness) + let before = await harness.mock.runCliCommandCalls.count + if obsolete { + let accepted = harness.viewModel.confirmFromAlert(action.entry) + action.presentationBinding(harness.viewModel).wrappedValue = false + harness.connectionState = .disconnected + await accepted.value + } else { + action.presentationBinding(harness.viewModel).wrappedValue = false + await harness.viewModel.confirmFromAlert(action.entry).value + } + + #expect(await harness.mock.runCliCommandCalls.count == before) + #expect(await harness.mock.rebootCallCount == 0) + #expect(harness.viewModel.confirmation == nil) + await harness.viewModel.closeEditor() + await harness.settings?.retireRadioWiFiOperations() + } + + @Test(arguments: AlertConfirmationCase.allCases) + private func `accepted alert cannot write a newer WiFi revision`(_ action: AlertConfirmationCase) async throws { + let harness = await Harness.make() + await harness.mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + await harness.viewModel.noteSessionReadiness() + try await action.prepare(harness) + let settings = try #require(harness.settings) + let before = await harness.mock.runCliCommandCalls.count + let accepted = harness.viewModel.confirmFromAlert(action.entry) + action.presentationBinding(harness.viewModel).wrappedValue = false + let token = try #require(settings.radioWiFiState.beginMutation(expectedRevision: nil)) + settings.radioWiFiState.settle(token, outcome: .accepted) + await accepted.value + + let writes = await harness.mock.runCliCommandCalls.dropFirst(before).filter { $0.hasPrefix("set ") } + #expect(writes.isEmpty) + #expect(await harness.mock.rebootCallCount == 0) + await harness.viewModel.closeEditor() + await settings.retireRadioWiFiOperations() + } + + @Test + func `accepted Save cannot write after its editor closes`() async throws { + let harness = await Harness.make() + await harness.mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + await harness.viewModel.noteSessionReadiness() + try await AlertConfirmationCase.save.prepare(harness) + let before = await harness.mock.runCliCommandCalls.count + let accepted = harness.viewModel.confirmFromAlert(.wifiWarning) + harness.viewModel.showingWiFiWarning = false + harness.viewModel.editor = nil + await accepted.value + + #expect(await harness.mock.runCliCommandCalls.count == before) + await harness.viewModel.closeEditor() + await harness.settings?.retireRadioWiFiOperations() + } + + @Test + func `reboot confirmation cannot open during a pending Tools WiFi mutation`() async throws { + let harness = try await Harness.makeRebootBoundary() + let tools = harness.makeTools() + await harness.mock.holdNextCLIReply() + tools.executeCommand("01|set wifi.ssid newer") + do { + try await waitUntil("Tools WiFi setter must remain pending") { + await harness.mock.heldCLICommand == "01|set wifi.ssid newer" + } + #expect(harness.settings?.radioWiFiState.stableRevision() == nil) + harness.viewModel.requestReboot() + #expect(!harness.viewModel.showingRebootConfirm) + await harness.mock.releaseHeldCLIReply() + try await waitUntil("Tools setter must settle") { !tools.isWaitingForResponse } + let accepted = harness.viewModel.confirmFromAlert(.reboot) + AlertConfirmationCase.reboot.presentationBinding(harness.viewModel).wrappedValue = false + await accepted.value + #expect(await harness.mock.rebootCallCount == 0) + await harness.confirmCurrentRebootOnce() + } catch { + await harness.mock.releaseHeldCLIReply() + tools.cleanup() + await harness.settings?.retireRadioWiFiOperations() + throw error + } + tools.cleanup() + await harness.settings?.retireRadioWiFiOperations() + } + + @Test + func `settled Tools WiFi mutation invalidates an already open reboot confirmation`() async throws { + let harness = try await Harness.makeRebootBoundary() + let tools = harness.makeTools() + harness.viewModel.requestReboot() + #expect(harness.viewModel.showingRebootConfirm) + tools.executeCommand("01|set wifi.ssid newer") + try await waitUntil("Tools setter must settle") { !tools.isWaitingForResponse } + let accepted = harness.viewModel.confirmFromAlert(.reboot) + AlertConfirmationCase.reboot.presentationBinding(harness.viewModel).wrappedValue = false + await accepted.value + + #expect(await harness.mock.rebootCallCount == 0) + await harness.confirmCurrentRebootOnce() + tools.cleanup() + await harness.settings?.retireRadioWiFiOperations() + } + + @Test(arguments: [false, true]) + func `reboot service admission rejects pending and settled Tools interference`(pending: Bool) async throws { + let harness = try await Harness.makeRebootBoundary() + let settings = try #require(harness.settings) + let revision = try #require(settings.radioWiFiState.stableRevision()) + let tools = harness.makeTools() + await harness.mock.holdNextCLIReply() + tools.executeCommand("01|set wifi.ssid newer") + do { + try await waitUntil("Tools setter must reach firmware") { + await harness.mock.heldCLICommand == "01|set wifi.ssid newer" + } + if !pending { + await harness.mock.releaseHeldCLIReply() + try await waitUntil("Tools setter must settle before reboot admission") { !tools.isWaitingForResponse } + } + await #expect(throws: CancellationError.self) { + try await settings.reboot(expectedContextID: settings.radioWiFiContextID, expectedRevision: revision) + } + #expect(await harness.mock.rebootCallCount == 0) + if pending { await harness.mock.releaseHeldCLIReply() } + try await waitUntil("Tools setter must complete") { !tools.isWaitingForResponse } + #expect(harness.viewModel.errorMessage == nil) + await harness.confirmCurrentRebootOnce() + } catch { + await harness.mock.releaseHeldCLIReply() + tools.cleanup() + await settings.retireRadioWiFiOperations() + throw error + } + tools.cleanup() + await settings.retireRadioWiFiOperations() + } + private static func wifiSwitchEnabled(on viewModel: RadioWiFiViewModel, dialHost: String?) -> Bool { let dial = dialHost.map { ConnectionLinkWiFiDial(host: $0, port: ConnectionMethod.defaultWiFiPort) } let snapshot = ConnectionLinkRows.make( @@ -1142,6 +1520,78 @@ struct RadioWiFiViewModelTests { } } +private enum AlertConfirmationCase: CaseIterable, Sendable { + case clear, reboot, save, disable + + var entry: RadioWiFiViewModel.AlertAction { + switch self { + case .clear: .clear + case .reboot: .reboot + case .save, .disable: .wifiWarning + } + } + + var expectedWrites: [String] { + switch self { + case .clear: ["set wifi.clear"] + case .reboot: [] + case .save: ["set wifi.ssid replacement"] + case .disable: ["set wifi.enabled 0"] + } + } + + @MainActor + func prepare(_ harness: Harness) async throws { + switch self { + case .clear: + harness.viewModel.requestClear() + case .reboot: + let settings = try #require(harness.settings) + try await settings.setRadioCLIValue("wifi.ssid", to: "built-in") + harness.viewModel.requestReboot() + case .save: + harness.transport.value = .wifi + harness.viewModel.openEditor() + await harness.viewModel.loadEditor() + harness.viewModel.ssidField = "replacement" + await harness.viewModel.requestSave() + case .disable: + harness.transport.value = .wifi + await harness.viewModel.setWiFiEnabled(false) + } + } + + @MainActor + func presentationBinding(_ viewModel: RadioWiFiViewModel) -> Binding { + @Bindable var viewModel = viewModel + switch self { + case .clear: return $viewModel.showingClearConfirm + case .reboot: return $viewModel.showingRebootConfirm + case .save, .disable: return $viewModel.showingWiFiWarning + } + } +} + +private enum CredentialReadFailure: CaseIterable, Sendable { + case unsupported + case malformed + case rejected + case cancelled + + func prime(_ mock: MockConfigurationSession) async { + let reply = switch self { + case .unsupported: "Unknown command" + case .malformed: "OK" + case .rejected: "Error: rejected" + case .cancelled: "> ignored" + } + await mock.setCLIReplyQueue(["> stored", reply]) + if case .cancelled = self { + await mock.failCLICommand(after: 1, CancellationError()) + } + } +} + enum ProbeFailure: CaseIterable, Sendable, CustomTestStringConvertible { case empty case blankValue @@ -1187,8 +1637,6 @@ private final class Harness { var device: DeviceDTO var connectionState: DeviceConnectionState = .ready let transport = TransportBox() - var rebootCount = 0 - var rebootError: (any Error)? static func radio() -> DeviceDTO { DeviceDTO( @@ -1227,18 +1675,14 @@ private final class Harness { static func make() async -> Harness { let mock = MockConfigurationSession() - let harness = Harness(mock: mock, settings: SettingsService(session: mock), device: radio()) + let device = radio() + let settings = SettingsService(session: mock, radioWiFiState: RadioWiFiState(radioID: device.radioID)) + let harness = Harness(mock: mock, settings: settings, device: device) harness.viewModel.configure( settingsService: { harness.settings }, connectionState: { harness.connectionState }, connectedDevice: { harness.device }, - currentTransportType: { harness.transport.value }, - reboot: { - harness.rebootCount += 1 - if let rebootError = harness.rebootError { - throw rebootError - } - } + currentTransportType: { harness.transport.value } ) return harness } @@ -1249,10 +1693,45 @@ private final class Harness { self.device = device } + static func makeRebootBoundary() async throws -> Harness { + let harness = await make() + await harness.mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + let settings = try #require(harness.settings) + try await settings.setRadioCLIValue("wifi.ssid", to: "initial") + await harness.viewModel.noteSessionReadiness() + return harness + } + + func makeTools() -> CLIToolViewModel { + let tools = CLIToolViewModel() + tools.configure( + dependencies: CLIToolViewModel.Dependencies( + repeaterAdminService: { nil }, remoteNodeService: { nil }, settingsService: { self.settings }, + dataStore: { nil }, radioID: { self.device.radioID }, connectedDevice: { self.device }, + powerOffRadio: {}, powerOffCancelAvailable: { true } + ), + localDeviceName: "Radio", sendSelfAdvert: { _ in } + ) + tools.activeSession = .local(deviceName: "Radio") + return tools + } + + func confirmCurrentRebootOnce() async { + viewModel.requestReboot() + #expect(viewModel.showingRebootConfirm) + let accepted = viewModel.confirmFromAlert(.reboot) + let duplicate = viewModel.confirmFromAlert(.reboot) + AlertConfirmationCase.reboot.presentationBinding(viewModel).wrappedValue = false + await accepted.value + await duplicate.value + #expect(await mock.rebootCallCount == 1) + #expect(settings?.radioWiFiState.expectedRebootID != nil) + } + func loadNetwork(ssid: String, password: String) async { await mock.setCLIReplyQueue(["> 1", "> \(ssid)", "> connected", "> (not connected)"]) await viewModel.noteSessionReadiness() - await mock.setCLIReply(password.isEmpty ? "> " : "> \(password)") + await mock.setCLIReplyQueue(["> \(ssid)", password.isEmpty ? "> " : "> \(password)"]) await viewModel.loadEditor() await mock.setCLIReply("OK") } diff --git a/MC1Tests/Views/SettingsTabNavigationTestHost.swift b/MC1Tests/Views/SettingsTabNavigationTestHost.swift index 05520a92e3..175503a83f 100644 --- a/MC1Tests/Views/SettingsTabNavigationTestHost.swift +++ b/MC1Tests/Views/SettingsTabNavigationTestHost.swift @@ -58,7 +58,9 @@ final class SettingsTabHarness { self.controller = controller } - static func make(connected: Bool, regularWidth: Bool = false, compactHeight: Bool = false) throws -> SettingsTabHarness { + static func make( + connected: Bool, regularWidth: Bool = false, compactHeight: Bool = false, injectedAppState: AppState? = nil + ) throws -> SettingsTabHarness { let suiteName = "settings-tab-navigation-\(UUID().uuidString)" guard let defaults = UserDefaults(suiteName: suiteName) else { throw SettingsTabHarnessError.defaultsUnavailable @@ -68,7 +70,7 @@ final class SettingsTabHarness { defaults.set(false, forKey: AppStorageKey.useDefaultTranslationApp.rawValue) defaults.set(translationLanguageCode, forKey: AppStorageKey.translationTargetLanguage.rawValue) - let appState = AppState(defaults: defaults) + let appState = injectedAppState ?? AppState(defaults: defaults) appState.navigation.selectedSetting = nil appState.navigation.selectedTab = AppTab.chats.rawValue if connected { diff --git a/MC1Tests/Views/Tools/CLI/CLIToolViewModelLocalCommandsTests.swift b/MC1Tests/Views/Tools/CLI/CLIToolViewModelLocalCommandsTests.swift index 66a6f955af..a4389ef95a 100644 --- a/MC1Tests/Views/Tools/CLI/CLIToolViewModelLocalCommandsTests.swift +++ b/MC1Tests/Views/Tools/CLI/CLIToolViewModelLocalCommandsTests.swift @@ -953,6 +953,120 @@ struct CLIToolViewModelLocalCommandsTests { #expect(await mock.runCliCommandCalls.isEmpty) } + @Test(arguments: ["set wifi.ssid terminal", " set wifi.ssid terminal", "01|set wifi.ssid terminal", " 01|set wifi.ssid terminal"]) + func `Tools WiFi setters invalidate the open editor certificate`(_ command: String) async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + let tools = makeViewModel(mock: mock, device: makeDevice(firmwareVersion: 14)) + let service = try #require(tools.settingsService) + let editorID = UUID() + let baseline = try #require(try await service.readRadioWiFiCredentials(editorID: editorID)) + + await run(tools, command) + + #expect(!tools.isWaitingForResponse) + #expect(await mock.runCliCommandCalls.last == command) + #expect(try await service.getRadioCLIValue("wifi.ssid") == "terminal") + #expect(service.radioWiFiState.rebootPending) + let before = await mock.runCliCommandCalls.count + await #expect(throws: CancellationError.self) { + _ = try await service.saveRadioWiFiCredentials( + ssid: baseline.ssid, password: "changed", baseline: baseline, + editorID: editorID, ownerIsCurrent: { true } + ) + } + #expect(await mock.runCliCommandCalls.count == before) + tools.cleanup() + await service.retireRadioWiFiOperations() + } + + @Test + func `Tools prefixed mutation after boot prevents old reboot evidence clearing`() async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + let first = SettingsService(session: mock) + try await first.setRadioCLIValue("wifi.ssid", to: "before-boot") + try await first.reboot() + let state = first.radioWiFiState + let candidate = try #require(state.expectedRebootID) + state.noteLinkEnded(contextID: first.radioWiFiContextID) + await first.retireRadioWiFiOperations() + await mock.bootWiFiFirmware() + let replacement = SettingsService(session: mock, radioWiFiState: state) + let tools = makeViewModel(mock: mock, device: makeDevice(firmwareVersion: 14), settings: replacement) + + await run(tools, " 01|set wifi.ssid after-boot") + 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) + let cleared = await replacement.confirmExpectedRadioWiFiReboot( + id: candidate, expectedRadioID: state.radioID, ownerIsCurrent: { true } + ) + + #expect(!cleared) + #expect(state.rebootPending) + #expect(await mock.wiFiBootUses(ssid: "before-boot", password: "")) + #expect(observation.networkName == "after-boot") + tools.cleanup() + await replacement.retireRadioWiFiOperations() + } + + @Test(arguments: [MockConfigurationSession.WiFiFailure.rejected, .timeoutAfterApply]) + func `Tools reflected rejection and uncertain apply settle the captured radio`( + _ failure: MockConfigurationSession.WiFiFailure + ) async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + let tools = makeViewModel(mock: mock, device: makeDevice(firmwareVersion: 14)) + let service = try #require(tools.settingsService) + let command = " 01|set wifi.ssid terminal" + await mock.failWiFiCommand(command, with: failure) + + await run(tools, command) + + #expect(!tools.isWaitingForResponse) + #expect(await mock.runCliCommandCalls == [command]) + #expect(service.radioWiFiState.revision > 0) + #expect(service.radioWiFiState.stableRevision() != nil) + switch failure { + case .rejected: + #expect(!service.radioWiFiState.rebootPending) + #expect(lastResponse(tools) == "01|Error: rejected") + #expect(try await service.getRadioCLIValue("wifi.ssid") == "built-in") + case .timeoutAfterApply: + #expect(service.radioWiFiState.rebootPending) + #expect(try await service.getRadioCLIValue("wifi.ssid") == "terminal") + case .timeoutBeforeApply: + Issue.record("unexpected failure control") + } + tools.cleanup() + await service.retireRadioWiFiOperations() + } + + @Test + func `Tools prefixed unknown key leaves no apply evidence and empty password stays empty`() async throws { + let mock = MockConfigurationSession() + await mock.useWiFiFirmware(RadioWiFiFirmware(defaultSSID: "built-in")) + let tools = makeViewModel(mock: mock, device: makeDevice(firmwareVersion: 14)) + let service = try #require(tools.settingsService) + await run(tools, "01|set wifi.unknown ignored") + #expect(lastResponse(tools) == "01|Unknown command") + #expect(!service.radioWiFiState.rebootPending) + await run(tools, "02|set wifi.pwd ") + let originalBytesPreserved = await mock.runCliCommandCalls.last == "02|set wifi.pwd " + #expect(originalBytesPreserved) + #expect(service.radioWiFiState.rebootPending) + let emptyPassword = try await service.getRadioCLIValue("wifi.pwd")?.isEmpty == true + #expect(emptyPassword) + tools.cleanup() + await service.retireRadioWiFiOperations() + } + // MARK: - Helpers private func makeViewModel( @@ -960,9 +1074,12 @@ struct CLIToolViewModelLocalCommandsTests { device: DeviceDTO? = nil, floods: FloodRecorder? = nil, powerOff: @escaping @MainActor () async throws -> Void = {}, - powerOffCancelAvailable: @escaping @MainActor () -> Bool = { true } + powerOffCancelAvailable: @escaping @MainActor () -> Bool = { true }, + settings: SettingsService? = nil ) -> CLIToolViewModel { - let service = SettingsService(session: mock) + let radioID = settings?.radioWiFiState.radioID ?? device?.radioID ?? UUID() + let service = settings ?? SettingsService(session: mock, radioWiFiState: RadioWiFiState(radioID: radioID)) + let currentDevice = device?.copy { $0.radioID = radioID } let viewModel = CLIToolViewModel() viewModel.configure( dependencies: CLIToolViewModel.Dependencies( @@ -970,8 +1087,8 @@ struct CLIToolViewModelLocalCommandsTests { remoteNodeService: { nil }, settingsService: { service }, dataStore: { nil }, - radioID: { UUID() }, - connectedDevice: { device }, + radioID: { currentDevice?.radioID }, + connectedDevice: { currentDevice }, powerOffRadio: powerOff, powerOffCancelAvailable: powerOffCancelAvailable ), diff --git a/MC1Tests/Views/Tools/CLI/CLIToolViewModelTests.swift b/MC1Tests/Views/Tools/CLI/CLIToolViewModelTests.swift index dcd72fbdf3..ac3f72ab41 100644 --- a/MC1Tests/Views/Tools/CLI/CLIToolViewModelTests.swift +++ b/MC1Tests/Views/Tools/CLI/CLIToolViewModelTests.swift @@ -876,28 +876,23 @@ actor ParkingContactStore: PersistenceStoreProtocol { } func markMessageAsRead(id: UUID) async throws {} - func incrementPendingSendAttemptCount(messageID: UUID) async throws -> Int? { + func savePendingAcknowledgement(_ dto: PendingSendDTO, replacingPendingSendID: UUID?) async throws -> Bool { + false + } + + func resolvePendingAcknowledgement(id: UUID, expectedDeadline: Date?, status: MessageStatus, ackCode: UInt32?, roundTripTime: UInt32?) async throws -> Bool { + false + } + + func incrementPendingSendAttemptCount(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 } diff --git a/MeshCore/Sources/MeshCore/Events/MeshTransportError.swift b/MeshCore/Sources/MeshCore/Events/MeshTransportError.swift index 0dbc3a42b3..d3bad94885 100644 --- a/MeshCore/Sources/MeshCore/Events/MeshTransportError.swift +++ b/MeshCore/Sources/MeshCore/Events/MeshTransportError.swift @@ -11,6 +11,8 @@ public enum MeshTransportError: Error, Sendable, Equatable { case connectionFailed(String) /// Indicates sending data failed with a specific reason. case sendFailed(String) + /// Confirms that this send was cancelled before physical submission. + case cancelledBeforeSubmission /// Indicates the target device could not be found. case deviceNotFound /// Indicates a required service was not found on the device. diff --git a/MeshCore/Sources/MeshCore/Protocols/ConfigurationSessionOps.swift b/MeshCore/Sources/MeshCore/Protocols/ConfigurationSessionOps.swift index 0865119c99..e3c0b660a6 100644 --- a/MeshCore/Sources/MeshCore/Protocols/ConfigurationSessionOps.swift +++ b/MeshCore/Sources/MeshCore/Protocols/ConfigurationSessionOps.swift @@ -198,6 +198,9 @@ public protocol ConfigurationSessionOps: Actor { /// Sent verbatim. Empty, whitespace-only, or out-of-range UTF-8 length is rejected before send. func runCliCommand(_ command: String) async throws -> String + /// Runs a typed CLI command with a unique reflected request tag and returns its unprefixed reply. + func runCorrelatedCliCommand(_ command: String) async throws -> String + /// Sets a custom variable on the device. /// /// - Parameters: diff --git a/MeshCore/Sources/MeshCore/Protocols/MessagingSessionOps.swift b/MeshCore/Sources/MeshCore/Protocols/MessagingSessionOps.swift index c5b68fad57..ad058e75e6 100644 --- a/MeshCore/Sources/MeshCore/Protocols/MessagingSessionOps.swift +++ b/MeshCore/Sources/MeshCore/Protocols/MessagingSessionOps.swift @@ -44,6 +44,15 @@ public protocol MessagingSessionOps: Actor { timestamp: Date, floodScope: ResolvedFloodScope ) async throws + + /// Verifies the slot secret and sends under the same command-response serialization. + func sendVerifiedChannelMessage( + channel: UInt8, + text: String, + timestamp: Date, + floodScope: ResolvedFloodScope?, + expectedSecret: Data + ) async throws } // MARK: - Default Implementations diff --git a/MeshCore/Sources/MeshCore/Session/IdentityImportReconnectionError.swift b/MeshCore/Sources/MeshCore/Session/IdentityImportReconnectionError.swift new file mode 100644 index 0000000000..f767b59d31 --- /dev/null +++ b/MeshCore/Sources/MeshCore/Session/IdentityImportReconnectionError.swift @@ -0,0 +1,5 @@ +/// Outcomes specific to the private-key exchange's admission and first response. +public enum IdentityImportReconnectionError: Error, Sendable { + case uncertainResponseHistory + case rejected(MeshCoreError) +} diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+ChannelSending.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+ChannelSending.swift index fa26f3cb1f..0f058db91d 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+ChannelSending.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+ChannelSending.swift @@ -2,6 +2,23 @@ import Foundation import os public extension MeshCoreSession { + /// Sends a message to a channel. + /// + /// Channel messages are broadcast to all nodes with the same channel configuration. + /// + /// - Parameters: + /// - channel: Channel index (0-255). + /// - text: The message text to send. + /// - timestamp: Message timestamp. Defaults to current time. + /// - Throws: ``MeshCoreError/timeout`` or ``MeshCoreError/deviceError(code:)`` on failure. + func sendChannelMessage( + channel: UInt8, + text: String, + timestamp: Date = Date() + ) async throws { + try await performChannelSend(channel: channel, text: text, timestamp: timestamp, floodScope: nil, expectedSecret: nil) + } + /// Applies a channel's flood scope and sends while holding one command-response slot. func sendChannelMessage( channel: UInt8, @@ -9,28 +26,71 @@ public extension MeshCoreSession { timestamp: Date, floodScope: ResolvedFloodScope ) async throws { - let scopeCommand = switch floodScope { - case .unscoped: - PacketBuilder.setFloodScopeUnscoped() - case let .scope(scope): - PacketBuilder.setFloodScope(scope.scopeKey()) + try await performChannelSend(channel: channel, text: text, timestamp: timestamp, floodScope: floodScope, expectedSecret: nil) + } + + /// Verifies channel occupancy and sends without allowing a channel replacement between them. + func sendVerifiedChannelMessage( + channel: UInt8, + text: String, + timestamp: Date, + floodScope: ResolvedFloodScope?, + expectedSecret: Data + ) async throws { + try await performChannelSend(channel: channel, text: text, timestamp: timestamp, floodScope: floodScope, expectedSecret: expectedSecret) + } + + private static let unconfiguredChannelSecretByte: UInt8 = 0 + + private static let channelOccupancyMismatch = MeshCoreError.invalidResponse( + expected: "unchanged channel occupancy", got: "different or missing channel occupancy" + ) + + private func performChannelSend( + channel: UInt8, + text: String, + timestamp: Date, + floodScope: ResolvedFloodScope?, + expectedSecret: Data? + ) async throws { + var commands: [Data] = [] + if let floodScope { + let scopeCommand = switch floodScope { + case .unscoped: + PacketBuilder.setFloodScopeUnscoped() + case let .scope(scope): + PacketBuilder.setFloodScope(scope.scopeKey()) + } + commands.append(scopeCommand) } - let messageCommand = PacketBuilder.sendChannelMessage(channel: channel, text: text, timestamp: timestamp) + commands.append(PacketBuilder.sendChannelMessage(channel: channel, text: text, timestamp: timestamp)) let cancelled = OSAllocatedUnfairLock(initialState: false) try await withTaskCancellationHandler { - try await requestResponseSerializer.withSerialization { [self] in - for command in [scopeCommand, messageCommand] { - // Cancellation still drains an outstanding ACK, but prevents the next write. - let _: Bool = try await sendAndMatchHoldingSerialization(command, beforeSend: { + try await requestResponseSerializer.withSerialization { [self, commands] in + if let expectedSecret { + let _: Bool = try await sendAndMatchHoldingSerialization(PacketBuilder.getChannel(index: channel), beforeSend: { if cancelled.withLock({ $0 }) { throw CancellationError() } }) { event in - if let error = Self.deviceErrorMatcher(event) { - return .failure(error) + if case let .error(code) = event, code == ErrorCode.notFound.rawValue { + return .failure(Self.channelOccupancyMismatch) } - if case .ok(nil) = event { - return .success(true) + if let error = Self.deviceErrorMatcher(event) { return .failure(error) } + guard case let .channelInfo(info) = event, info.index == channel else { return .ignore } + guard info.secret == expectedSecret, + !info.name.isEmpty || info.secret.contains(where: { $0 != Self.unconfiguredChannelSecretByte }) else { + return .failure(Self.channelOccupancyMismatch) } + return .success(true) + } + } + for command in commands { + // Cancellation still drains the current response, but prevents the next write. + let _: Bool = try await sendAndMatchHoldingSerialization(command, beforeSend: { + if cancelled.withLock({ $0 }) { throw CancellationError() } + }) { event in + if let error = Self.deviceErrorMatcher(event) { return .failure(error) } + if case .ok(nil) = event { return .success(true) } return .ignore } } diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Channels.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Channels.swift index 661cb8899c..d01b53b75e 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Channels.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Channels.swift @@ -3,7 +3,7 @@ import Foundation /// Result a channel-pipeline task group task contributes: the consumer's collected channels, /// or a watchdog tick that has already finished the subscription. private enum ChannelPipelineOutcome { - case collected([UInt8: ChannelInfo]) + case collected([UInt8: ChannelInfo], allSubmittedReceived: Bool) case watchdog } @@ -58,7 +58,6 @@ public extension MeshCoreSession { indices: [UInt8] ) async throws -> (received: [ChannelInfo], missing: [UInt8]) { let requested = indices - let requestedSet = Set(indices) let window = max(1, configuration.channelPipelineWindow) let idleTimeout = configuration.channelPipelineIdleTimeout let hardTimeout = configuration.channelPipelineHardTimeout @@ -80,13 +79,24 @@ public extension MeshCoreSession { // them with acknowledged reads. That reconcile path is load-bearing, not just a // disconnect fallback. let primeCount = min(window, requested.count) + var primed: [UInt8] = [] + var primeFailure: (any Error)? for index in requested.prefix(primeCount) { - try await sendSessionDataWithoutResponse(PacketBuilder.getChannel(index: index)) + do { + try await sendSessionDataWithoutResponse(PacketBuilder.getChannel(index: index)) + primed.append(index) + } catch { + guard !primed.isEmpty else { throw error } + primeFailure = error + break + } } + let submitted = primed + let initialFailure = primeFailure let progressTracker = StreamProgressTracker() - let received: [UInt8: ChannelInfo] = try await withThrowingTaskGroup( + let result: (received: [UInt8: ChannelInfo], allSubmittedReceived: Bool) = try await withThrowingTaskGroup( of: ChannelPipelineOutcome.self ) { group in // Consumer: records matching responses, refills the window, returns as soon as @@ -94,29 +104,35 @@ public extension MeshCoreSession { // or when the watchdog finishes the subscription. group.addTask { [self] in var collected: [UInt8: ChannelInfo] = [:] - var nextToSend = primeCount + var expected = Set(submitted) + var nextToSend = submitted.count + var canSubmit = initialFailure == nil for await event in events { guard case let .channelInfo(info) = event, - requestedSet.contains(info.index), + expected.contains(info.index), collected[info.index] == nil else { continue } await progressTracker.markProgress() collected[info.index] = info - if nextToSend < requested.count { + if canSubmit, nextToSend < requested.count { let nextIndex = requested[nextToSend] nextToSend += 1 - // A refill failure (disconnect mid-drain) just stops sending; the - // watchdog's idle timeout then returns the partial set. - try? await self.sendSessionDataWithoutResponse( - PacketBuilder.getChannel(index: nextIndex) - ) + do { + try await self.sendSessionDataWithoutResponse(PacketBuilder.getChannel(index: nextIndex)) + expected.insert(nextIndex) + } catch { + canSubmit = false + } } - if collected.count == requested.count { - return .collected(collected) + if collected.count == expected.count, !canSubmit || nextToSend == requested.count { + return .collected(collected, allSubmittedReceived: collected.count == expected.count) } } - return .collected(collected) + if !canSubmit, collected.count != expected.count { + await requestResponseSerializer.noteUncertainResponseHistory() + } + return .collected(collected, allSubmittedReceived: collected.count == expected.count) } // Watchdog: ends the stream on an inactivity gap or the hard cap so the consumer @@ -143,27 +159,31 @@ public extension MeshCoreSession { } var collected: [UInt8: ChannelInfo] = [:] + var allSubmittedReceived = false for try await outcome in group { - if case let .collected(dict) = outcome { + if case let .collected(dict, allReplies) = outcome { collected = dict + allSubmittedReceived = allReplies group.cancelAll() break } // A watchdog tick already finished the subscription; loop until the // consumer returns its (possibly partial) collected set. } - return collected + return (collected, allSubmittedReceived) } + let received = result.received let missing = requested.filter { received[$0] == nil } - if missing.isEmpty { - // Every index answered. Hold the slot for the grace window with the subscription + if result.allSubmittedReceived { + // Every submitted index answered. Hold the slot for the grace window with the subscription // still open so duplicate/straggler frames are absorbed here instead of leaking // into the next command. try? await sessionClock.sleep(for: .seconds(graceTimeout)) } await dispatcher.finishSubscription(id: subscriptionID) + if let initialFailure { throw initialFailure } let receivedSorted = received.keys.sorted().compactMap { received[$0] } return (received: receivedSorted, missing: missing) } catch { diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+DeviceConfig.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+DeviceConfig.swift index 6fa3eaf5f3..5320f22a89 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+DeviceConfig.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+DeviceConfig.swift @@ -378,23 +378,7 @@ public extension MeshCoreSession { /// Runs a UTF-8 CLI command on the paired radio (firmware v14+). /// Sent verbatim. A too-short frame is unsupported on the radio, and a frame over `MAX_FRAME_SIZE` is dropped. func runCliCommand(_ command: String) async throws -> String { - let isBlank = command.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - guard !isBlank, command.utf8.count >= PacketBuilder.runCliCommandMinUTF8Bytes else { - throw MeshCoreError.invalidInput( - isBlank ? "CLI command is empty" : "CLI command is too short" - ) - } - guard command.utf8.count <= PacketBuilder.runCliCommandMaxUTF8Bytes else { - throw MeshCoreError.invalidInput("CLI command exceeds maximum length") - } - return try await sendAndWaitWithError( - PacketBuilder.runCliCommand(command), - matching: { event in - if case let .cliReply(text) = event { return text } - return nil - }, - errorMatcher: Self.deviceErrorMatcher - ) + try await runVerbatimCLICommand(command) } /// Sets a custom variable on the device. diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+EventWaiting.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+EventWaiting.swift index f2d4fea47a..6b08446003 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+EventWaiting.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+EventWaiting.swift @@ -170,6 +170,7 @@ extension MeshCoreSession { _ data: Data, timeout: TimeInterval? = nil, beforeSend: @escaping @Sendable () throws -> Void = {}, + identityImport: Bool = false, matching matcher: @escaping @Sendable (MeshEvent) -> ResponseDisposition ) async throws -> T { let effectiveTimeout = timeout ?? configuration.defaultTimeout @@ -179,7 +180,7 @@ extension MeshCoreSession { let (subscriptionID, events) = await dispatcher.subscribeTracked() do { - try await sendSessionData(data, beforeSend: beforeSend) + try await sendSessionData(data, beforeSend: beforeSend, identityImport: identityImport) return try await withThrowingTaskGroup(of: T?.self) { group in group.addTask { diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+IdentityReconnection.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+IdentityReconnection.swift new file mode 100644 index 0000000000..93cf106543 --- /dev/null +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+IdentityReconnection.swift @@ -0,0 +1,57 @@ +import Foundation + +public extension MeshCoreSession { + /// Stops ordinary commands before the owner joins workers that could issue them. + func prepareForIdentityImport() async throws { + guard !identityImportInProgress else { throw CancellationError() } + try await requestResponseSerializer.requireIdentityImportResponseAttribution() + identityImportInProgress = true + } + + /// Closes ordinary command admission while identity and SelfInfo change together. + /// The owner replaces this session after the authenticated observation settles. + func importPrivateKeyForReconnection( + _ key: Data, binding: SessionTransportBinding, onAcknowledged: @escaping @Sendable () -> Void + ) async throws -> SelfInfo { + guard key.count == PacketBuilder.privateKeySize else { + throw MeshCoreError.invalidInput("Full \(PacketBuilder.privateKeySize)-byte private key required for importPrivateKey") + } + guard identityImportInProgress, !identityImportHasStarted else { throw CancellationError() } + identityImportHasStarted = true + return try await requestResponseSerializer.withSerialization { [self] in + defer { binding.revoke() } + await binding.waitForQuiescence() + try await requestResponseSerializer.requireIdentityImportResponseAttribution() + do { + let accepted: Bool = try await sendAndMatchHoldingSerialization( + PacketBuilder.importPrivateKey(key), beforeSend: { try binding.checkActive() }, identityImport: true + ) { event in + switch event { + case .ok(value: nil): .success(true) + case .disabled: .success(false) + case let .error(code?): .failure(.deviceError(code: code)) + default: .ignore + } + } + guard accepted else { throw IdentityImportReconnectionError.rejected(.featureDisabled) } + } catch let failure as MeshCoreError { + if case .deviceError = failure { throw IdentityImportReconnectionError.rejected(failure) } + throw failure + } + onAcknowledged() + let info: SelfInfo = try await sendAndMatchHoldingSerialization( + PacketBuilder.appStart(clientId: configuration.clientIdentifier), + beforeSend: { try binding.checkActive() }, identityImport: true + ) { event in + if case let .selfInfo(info) = event { return .success(info) } + return .ignore + } + await cacheImportedSelfInfo(info) + return info + } + } + + private func cacheImportedSelfInfo(_ info: SelfInfo) { + selfInfo = info + } +} diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift index 4bcd07ab86..919a40ae01 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift @@ -302,23 +302,6 @@ public extension MeshCoreSession { ) } - /// Sends a message to a channel. - /// - /// Channel messages are broadcast to all nodes with the same channel configuration. - /// - /// - Parameters: - /// - channel: Channel index (0-255). - /// - text: The message text to send. - /// - timestamp: Message timestamp. Defaults to current time. - /// - Throws: ``MeshCoreError/timeout`` or ``MeshCoreError/deviceError(code:)`` on failure. - func sendChannelMessage( - channel: UInt8, - text: String, - timestamp: Date = Date() - ) async throws { - try await sendSimpleCommand(PacketBuilder.sendChannelMessage(channel: channel, text: text, timestamp: timestamp)) - } - /// Sends a binary datagram to a channel. /// /// Requires firmware v11+ (MeshCore v1.15.0+). diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+RadioCLI.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+RadioCLI.swift new file mode 100644 index 0000000000..48cba89349 --- /dev/null +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+RadioCLI.swift @@ -0,0 +1,62 @@ +import Foundation + +extension MeshCoreSession { + private static let cliNullByte: UInt8 = 0 + + /// Typed commands accept only the exact request tag reflected by supported firmware. + public func runCorrelatedCliCommand(_ command: String) async throws -> String { + try validateCLICommand(command) + return try await requestResponseSerializer.withSerialization { [self] in + let prefix = try radioCLICorrelationScope.allocate() + let taggedCommand = prefix + command + try await validateCLICommand(taggedCommand) + let reply = try await performCLIExchange(taggedCommand, expectedPrefix: prefix) + return String(decoding: reply.utf8.dropFirst(prefix.utf8.count), as: UTF8.self) + } + } + + func runVerbatimCLICommand(_ command: String) async throws -> String { + try validateCLICommand(command, allowsNullBytes: true) + return try await requestResponseSerializer.withSerialization { [self] in + let prefix = RadioCLICorrelationScope.commandPrefix(command) + if let prefix { + try radioCLICorrelationScope.reserve(prefix) + } else { + try radioCLICorrelationScope.requireUnprefixedReplyAuthority() + } + do { + return try await performCLIExchange(command, expectedPrefix: prefix) + } catch { + if prefix == nil { radioCLICorrelationScope.noteUnprefixedReplyUncertainty() } + throw error + } + } + } + + private func performCLIExchange(_ command: String, expectedPrefix: String?) async throws -> String { + let scope = radioCLICorrelationScope + return try await sendAndMatchHoldingSerialization(PacketBuilder.runCliCommand(command)) { event in + if case let .cliReply(text) = event { + if let expectedPrefix { + return text.utf8.starts(with: expectedPrefix.utf8) ? .success(text) : .ignore + } + return scope.recognizesReplyPrefix(text) ? .ignore : .success(text) + } + if expectedPrefix == nil, let error = Self.deviceErrorMatcher(event) { return .failure(error) } + return .ignore + } + } + + private func validateCLICommand(_ command: String, allowsNullBytes: Bool = false) throws { + guard allowsNullBytes || !command.utf8.contains(Self.cliNullByte) else { + throw MeshCoreError.invalidInput("CLI text contains a null character") + } + let isBlank = command.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + guard !isBlank, command.utf8.count >= PacketBuilder.runCliCommandMinUTF8Bytes else { + throw MeshCoreError.invalidInput(isBlank ? "CLI command is empty" : "CLI command is too short") + } + guard command.utf8.count <= PacketBuilder.runCliCommandMaxUTF8Bytes else { + throw MeshCoreError.invalidInput("CLI command exceeds maximum length") + } + } +} diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+TransportWrites.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+TransportWrites.swift index cb678fac3b..641b1e8ae8 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+TransportWrites.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+TransportWrites.swift @@ -4,15 +4,32 @@ extension MeshCoreSession { /// stop() can leave the transport connected for the next session, so a stopped session does not write. func sendSessionData( _ data: Data, - beforeSend: @Sendable () throws -> Void = {} + beforeSend: @Sendable () throws -> Void = {}, + identityImport: Bool = false ) async throws { + guard !identityImportInProgress || identityImport else { throw CancellationError() } guard sessionIsRunning else { throw CancellationError() } try beforeSend() - try await transport.send(data) + do { + try await transport.send(data) + } catch MeshTransportError.cancelledBeforeSubmission { + throw CancellationError() + } catch { + await requestResponseSerializer.noteUncertainResponseHistory() + throw error + } } func sendSessionDataWithoutResponse(_ data: Data) async throws { + guard !identityImportInProgress else { throw CancellationError() } guard sessionIsRunning else { throw CancellationError() } - try await transport.sendWithoutResponse(data) + do { + try await transport.sendWithoutResponse(data) + } catch MeshTransportError.cancelledBeforeSubmission { + throw CancellationError() + } catch { + await requestResponseSerializer.noteUncertainResponseHistory() + throw error + } } } diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift index 9f54bed757..4e9ae3710f 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift @@ -80,7 +80,8 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { let transport: any MeshTransport let configuration: SessionConfiguration - let clock: any Clock + public nonisolated let clock: any Clock + let radioCLICorrelationScope: RadioCLICorrelationScope let dispatcher = EventDispatcher() let requestResponseSerializer = RequestResponseSerializer() @@ -109,6 +110,13 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { } private var isRunning = false + var identityImportInProgress = false + var identityImportHasStarted = false + private var isStarting = false + private var isStopped = false + private var retiredWorkers: [Task] = [] + private var stopTask: Task? + private var transportCloseTask: Task? /// False after `stop()`. `performBinaryExchange`, `sendAndMatch`, and `performGetMessage` /// read this so a stopped session does not send or report a radio timeout. @@ -126,6 +134,8 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { var inFlightGetMessage: Task? var getMessageCallerCountForTest = 0 private(set) var processedMessagesWaitingCountForTest = 0 + /// Channel info frames handed to subscribers. A pipeline idle sleep is safe to elapse only after this catches the yielded frames. + private(set) var dispatchedChannelInfoCountForTest = 0 // MARK: - Connection State @@ -177,11 +187,13 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { public init( transport: any MeshTransport, configuration: SessionConfiguration = .default, - clock: (any Clock)? = nil + clock: (any Clock)? = nil, + radioCLICorrelationScope: RadioCLICorrelationScope = RadioCLICorrelationScope() ) { self.transport = transport self.configuration = configuration self.clock = clock ?? ContinuousClock() + self.radioCLICorrelationScope = radioCLICorrelationScope } /// Connects to the device and starts the session. @@ -204,11 +216,14 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { /// - Throws: ``MeshTransportError`` if the transport connection fails. /// ``MeshCoreError/timeout`` if the device doesn't respond to appStart. public func start(reconnectingAttempt: Int? = nil, disconnectTransportOnFailure: Bool = true) async throws { + guard !isStopped, !isStarting else { throw CancellationError() } // Guard against being called multiple times if isRunning { logger.warning("Session already running - skipping redundant start()") return } + isStarting = true + defer { isStarting = false } logger.info("Starting MeshCore session...") if let reconnectingAttempt { @@ -219,7 +234,9 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { logger.info("Connecting via transport...") do { try await transport.connect() + guard !isStopped else { throw CancellationError() } } catch { + guard !isStopped else { throw CancellationError() } logger.warning("Transport connection failed: \(error.localizedDescription)") updateConnectionState(.failed(error as? MeshTransportError ?? .connectionFailed(error.localizedDescription))) throw error @@ -236,13 +253,17 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { // Send appstart logger.info("Sending appStart command...") do { - selfInfo = try await sendAppStart() + let info = try await sendAppStart() + guard !isStopped else { throw CancellationError() } + selfInfo = info } catch { + guard !isStopped else { throw CancellationError() } // Unwind the half-started session so a retry start() runs the full // handshake instead of hitting the isRunning guard and no-opping. logger.warning("appStart failed: \(error.localizedDescription)") isRunning = false receiveTask?.cancel() + if let receiveTask { retiredWorkers.append(receiveTask) } receiveTask = nil if disconnectTransportOnFailure { await transport.disconnect() @@ -253,36 +274,67 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { logger.info("MeshCore session started") } - /// Stops the session and disconnects from the device. - /// - /// This method is safe to call multiple times. It cancels all pending operations, - /// stops the receive loop, and closes the transport connection unless - /// `disconnectTransport` is `false`. - /// - /// After calling this method, the session cannot be reused. Create a new session - /// to reconnect. - /// - /// - Parameter disconnectTransport: When `false`, the transport link is left - /// open. Pass `false` when the caller does not own the link — e.g. tearing - /// down a superseded session while a newer reconnect cycle (or an OS-level - /// pending connect) still rides on the same transport. - public func stop(disconnectTransport: Bool = true) async { + /// Stops this session permanently; leave the transport open when its owner outlives this session. + /// Revoke the binding before `drainExchanges` so admitted replies or timeouts settle before receiving stops. + public func stop(disconnectTransport: Bool = true, drainExchanges: Bool = false) async { + if let stopTask { + await stopTask.value + if disconnectTransport { await closeTransport() } + return + } logger.info("Stopping MeshCore session...") isRunning = false + isStopped = true + if let autoMessageFetchTask { retiredWorkers.append(autoMessageFetchTask) } + if let autoMessageDrainTask { retiredWorkers.append(autoMessageDrainTask) } + if let autoContactRefreshTask { retiredWorkers.append(autoContactRefreshTask) } + if let receiveTask { retiredWorkers.append(receiveTask) } stopAutoMessageFetching() autoContactRefreshTask?.cancel() autoContactRefreshTask = nil autoContactRefreshRequested = false + let worker = Task { + await finishStopping(drainExchanges: drainExchanges) + } + stopTask = worker + await worker.value + if disconnectTransport { await closeTransport() } + } + + private func finishStopping(drainExchanges: Bool) async { + if drainExchanges { + await otherParamsSerializer.waitForQuiescence() + await requestResponseSerializer.waitForQuiescence() + } receiveTask?.cancel() + receiveTask = nil await dispatcher.finishAllSubscriptions() - if disconnectTransport { - logger.info("Disconnecting transport...") - await transport.disconnect() - } updateConnectionState(.disconnected) logger.info("MeshCore session stopped") } + private func closeTransport() async { + if let transportCloseTask { + await transportCloseTask.value + return + } + let worker = Task { await transport.disconnect() } + transportCloseTask = worker + await worker.value + } + + /// After stop, joins receive workers and exchanges that outlive cancelled callers. + public func waitForQuiescence() async { + let workers = retiredWorkers + for worker in workers { + await worker.value + } + if let inFlightGetMessage { _ = await inFlightGetMessage.result } + await otherParamsSerializer.waitForQuiescence() + await requestResponseSerializer.waitForQuiescence() + retiredWorkers.removeAll() + } + // MARK: - Events /// Subscribes to all events from the device. @@ -353,6 +405,8 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { /// /// Call this to disable the automatic fetching started by ``startAutoMessageFetching()``. public func stopAutoMessageFetching() { + if let autoMessageFetchTask { retiredWorkers.append(autoMessageFetchTask) } + if let autoMessageDrainTask { retiredWorkers.append(autoMessageDrainTask) } isAutoFetchingMessages = false autoMessageDrainRequested = false autoMessageFetchTask?.cancel() @@ -473,6 +527,9 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { trackContactChanges(event: event) await dispatcher.dispatch(event) + if case .channelInfo = event { + dispatchedChannelInfoCountForTest += 1 + } } /// Tracks contact-related changes from received events. diff --git a/MeshCore/Sources/MeshCore/Session/PowerOffExchange.swift b/MeshCore/Sources/MeshCore/Session/PowerOffExchange.swift index 50c89b98fc..131e201c46 100644 --- a/MeshCore/Sources/MeshCore/Session/PowerOffExchange.swift +++ b/MeshCore/Sources/MeshCore/Session/PowerOffExchange.swift @@ -75,6 +75,7 @@ private final class PowerOffReplyInbox: @unchecked Sendable { private struct Waiter { let id: UUID let continuation: CheckedContinuation + var timeout: Task? } private struct State { @@ -101,6 +102,7 @@ private final class PowerOffReplyInbox: @unchecked Sendable { return waiters } for waiter in waiters { + waiter.timeout?.cancel() waiter.continuation.resume(returning: matched) } return true @@ -114,6 +116,7 @@ private final class PowerOffReplyInbox: @unchecked Sendable { return waiters } for waiter in waiters { + waiter.timeout?.cancel() waiter.continuation.resume(returning: nil) } } @@ -122,7 +125,7 @@ private final class PowerOffReplyInbox: @unchecked Sendable { lock.withLock { $0.ended && $0.event == nil } } - func take(waiting seconds: TimeInterval) async -> MeshEvent? { + func take(waiting seconds: TimeInterval, clock: any Clock) async -> MeshEvent? { let first = lock.withLock { state -> Immediate in if let event = state.event { return .event(event) } if state.ended { return .ended } @@ -143,7 +146,7 @@ private final class PowerOffReplyInbox: @unchecked Sendable { let immediate = lock.withLock { state -> Immediate in if let event = state.event { return .event(event) } if state.ended { return .ended } - state.waiters.append(Waiter(id: id, continuation: continuation)) + state.waiters.append(Waiter(id: id, continuation: continuation, timeout: nil)) return .waiting } switch immediate { @@ -152,14 +155,20 @@ private final class PowerOffReplyInbox: @unchecked Sendable { case .ended: continuation.resume(returning: nil) case .waiting: - Task { - try? await Task.sleep(for: .seconds(seconds)) + let timeout = Task { + try? await clock.sleep(for: .seconds(seconds)) let removed = lock.withLock { state -> Waiter? in guard let index = state.waiters.firstIndex(where: { $0.id == id }) else { return nil } return state.waiters.remove(at: index) } removed?.continuation.resume(returning: nil) } + let stillWaiting = lock.withLock { state -> Bool in + guard let index = state.waiters.firstIndex(where: { $0.id == id }) else { return false } + state.waiters[index].timeout = timeout + return true + } + if !stillWaiting { timeout.cancel() } } } } @@ -214,7 +223,7 @@ public extension MeshCoreSession { } let grace = sendFailed ? Self.powerOffBufferedReplyGrace : Self.powerOffReplyWindow - if let event = await inbox.take(waiting: grace) { + if let event = await inbox.take(waiting: grace, clock: clock) { return Self.classifyPowerOffReply(event) } if inbox.streamEnded { diff --git a/MeshCore/Sources/MeshCore/Session/RadioCLICorrelationScope.swift b/MeshCore/Sources/MeshCore/Session/RadioCLICorrelationScope.swift new file mode 100644 index 0000000000..ff38eb372d --- /dev/null +++ b/MeshCore/Sources/MeshCore/Session/RadioCLICorrelationScope.swift @@ -0,0 +1,73 @@ +import Foundation +import Synchronization + +/// CLI request tags remain reserved until their connection request retires. +public final class RadioCLICorrelationScope: Sendable { + private struct State { + var nextOrdinal = 0 + var reserved: Set = [] + var unprefixedReplyIsUncertain = false + } + + private static let alphabet = Array("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".utf8) + static let capacity = alphabet.count * alphabet.count + private static let prefixMarker: UInt8 = 0x7C + private static let spaceByte: UInt8 = 0x20 + private static let prefixMarkerOffset = 2 + private static let prefixSize = 3 + private static let minimumPrefixedCommandBytes = 5 + private let state = Mutex(State()) + + public init() {} + + func allocate() throws -> String { + try state.withLock { state in + while state.nextOrdinal < Self.capacity { + let ordinal = state.nextOrdinal + state.nextOrdinal += 1 + let bytes = [ + Self.alphabet[ordinal / Self.alphabet.count], + Self.alphabet[ordinal % Self.alphabet.count], Self.prefixMarker + ] + let prefix = String(decoding: bytes, as: UTF8.self) + if state.reserved.insert(Data(prefix.utf8)).inserted { return prefix } + } + throw MeshCoreError.invalidInput("CLI request correlation is exhausted") + } + } + + func reserve(_ prefix: String) throws { + try state.withLock { state in + guard state.reserved.insert(Data(prefix.utf8)).inserted else { + throw MeshCoreError.invalidInput("CLI request prefix was already used") + } + } + } + + func requireUnprefixedReplyAuthority() throws { + try state.withLock { state in + guard !state.unprefixedReplyIsUncertain else { + throw MeshCoreError.invalidInput("CLI reply provenance requires a new connection") + } + } + } + + func noteUnprefixedReplyUncertainty() { + state.withLock { $0.unprefixedReplyIsUncertain = true } + } + + func recognizesReplyPrefix(_ reply: String) -> Bool { + let bytes = Array(reply.utf8.prefix(Self.prefixSize)) + guard bytes.count == Self.prefixSize, bytes.last == Self.prefixMarker else { return false } + return state.withLock { $0.reserved.contains(Data(bytes)) } + } + + static func commandPrefix(_ command: String) -> String? { + let bytes = command.utf8.drop(while: { $0 == Self.spaceByte }) + guard bytes.count >= Self.minimumPrefixedCommandBytes, + bytes[bytes.index(bytes.startIndex, offsetBy: Self.prefixMarkerOffset)] == Self.prefixMarker else { + return nil + } + return String(decoding: bytes.prefix(Self.prefixSize), as: UTF8.self) + } +} diff --git a/MeshCore/Sources/MeshCore/Session/RequestContext.swift b/MeshCore/Sources/MeshCore/Session/RequestContext.swift index e1a6fc877c..b433fb53f7 100644 --- a/MeshCore/Sources/MeshCore/Session/RequestContext.swift +++ b/MeshCore/Sources/MeshCore/Session/RequestContext.swift @@ -15,6 +15,16 @@ import os public actor RequestResponseSerializer { private var isRequestInFlight = false private var waiters: [CheckedContinuation] = [] + private var settlementWaiters: [CheckedContinuation] = [] + private var hasUncertainResponseHistory = false + + func requireIdentityImportResponseAttribution() throws { + guard !hasUncertainResponseHistory else { throw IdentityImportReconnectionError.uncertainResponseHistory } + } + + func noteUncertainResponseHistory() { + hasUncertainResponseHistory = true + } /// ContactService lives outside MeshCore, and the memberwise initializer is internal. public init() {} @@ -23,6 +33,12 @@ public actor RequestResponseSerializer { waiters.count } + #if DEBUG + var quiescenceWaiterCountForTesting: Int { + settlementWaiters.count + } + #endif + /// Acquires the serializer, waiting if another request/response exchange is active. public func acquire() async { if !isRequestInFlight { @@ -42,9 +58,20 @@ public actor RequestResponseSerializer { next.resume() } else { isRequestInFlight = false + let settled = settlementWaiters + settlementWaiters.removeAll() + for waiter in settled { + waiter.resume() + } } } + /// Joins the exchanges themselves, rather than their cancellable callers. + public func waitForQuiescence() async { + guard isRequestInFlight else { return } + await withCheckedContinuation { settlementWaiters.append($0) } + } + /// Executes a request/response operation while holding the serializer. /// /// The slot is held until the wire exchange the operation owns actually terminates — @@ -85,6 +112,9 @@ public actor RequestResponseSerializer { do { outcome = try await .success(operation()) } catch { + if let failure = error as? MeshCoreError, case .timeout = failure { + noteUncertainResponseHistory() + } outcome = .failure(error) } release() diff --git a/MeshCore/Sources/MeshCore/Transport/MeshTransport.swift b/MeshCore/Sources/MeshCore/Transport/MeshTransport.swift index 9b5295f42a..51f7708898 100644 --- a/MeshCore/Sources/MeshCore/Transport/MeshTransport.swift +++ b/MeshCore/Sources/MeshCore/Transport/MeshTransport.swift @@ -60,6 +60,11 @@ import Foundation /// Implementations must conform to `Sendable`. Using an `actor` is the recommended way to /// manage internal state and ensure concurrency safety in a modern Swift environment. public protocol MeshTransport: Sendable { + func connect(sessionBinding: SessionTransportBinding) async throws + func disconnect(sessionBinding: SessionTransportBinding) async + func send(_ data: Data, sessionBinding: SessionTransportBinding) async throws + func sendWithoutResponse(_ data: Data, sessionBinding: SessionTransportBinding) async throws + func receivedData(sessionBinding: SessionTransportBinding) async -> AsyncStream /// Establishes a connection to the MeshCore device. /// /// This method initializes the underlying physical layer and prepares the transport @@ -127,6 +132,30 @@ public protocol MeshTransport: Sendable { } public extension MeshTransport { + func connect(sessionBinding: SessionTransportBinding) async throws { + try sessionBinding.checkActive() + try await connect() + } + + func disconnect(sessionBinding: SessionTransportBinding) async { + await disconnect() + } + + func send(_ data: Data, sessionBinding: SessionTransportBinding) async throws { + try sessionBinding.checkActive() + try await send(data) + } + + func sendWithoutResponse(_ data: Data, sessionBinding: SessionTransportBinding) async throws { + try sessionBinding.checkActive() + try await sendWithoutResponse(data) + } + + func receivedData(sessionBinding: SessionTransportBinding) async -> AsyncStream { + guard sessionBinding.isActive else { return AsyncStream { $0.finish() } } + return await receivedData + } + /// Routes unacknowledged writes to the acknowledged ``send(_:)`` path. Transports that /// support Write Commands override this; everyone else degrades safely to a Write Request. func sendWithoutResponse(_ data: Data) async throws { diff --git a/MeshCore/Sources/MeshCore/Transport/SessionBoundTransport.swift b/MeshCore/Sources/MeshCore/Transport/SessionBoundTransport.swift new file mode 100644 index 0000000000..0e6e982054 --- /dev/null +++ b/MeshCore/Sources/MeshCore/Transport/SessionBoundTransport.swift @@ -0,0 +1,57 @@ +import Foundation + +/// A session's revocable view of its owner's physical transport. +public struct SessionBoundTransport: MeshTransport { + private let transport: any MeshTransport + public let binding: SessionTransportBinding + + public init(transport: any MeshTransport, binding: SessionTransportBinding) { + self.transport = transport + self.binding = binding + } + + public func connect() async throws { + try binding.beginOperation() + defer { binding.endOperation() } + try await transport.connect(sessionBinding: binding) + try binding.checkActive() + } + + public func disconnect() async { + await transport.disconnect(sessionBinding: binding) + } + + public func send(_ data: Data) async throws { + try binding.beginOperation() + defer { binding.endOperation() } + try await transport.send(data, sessionBinding: binding) + } + + public func sendWithoutResponse(_ data: Data) async throws { + try binding.beginOperation() + defer { binding.endOperation() } + try await transport.sendWithoutResponse(data, sessionBinding: binding) + } + + public var receivedData: AsyncStream { + get async { + guard binding.isActive else { return AsyncStream { $0.finish() } } + return await transport.receivedData(sessionBinding: binding) + } + } + + public var isConnected: Bool { + get async { + guard binding.isActive else { return false } + return await transport.isConnected + } + } + + public var supportsWriteWithoutResponse: Bool { + get async { await transport.supportsWriteWithoutResponse } + } + + public var supportsPipelinedReads: Bool { + get async { await transport.supportsPipelinedReads } + } +} diff --git a/MeshCore/Sources/MeshCore/Transport/SessionTransportBinding.swift b/MeshCore/Sources/MeshCore/Transport/SessionTransportBinding.swift new file mode 100644 index 0000000000..5305e8eec1 --- /dev/null +++ b/MeshCore/Sources/MeshCore/Transport/SessionTransportBinding.swift @@ -0,0 +1,72 @@ +import Synchronization + +/// Revocable command admission for one session over a caller-owned transport. +public final class SessionTransportBinding: Sendable { + private struct State { + var isRevoked = false + var operations = 0 + var waiters: [CheckedContinuation] = [] + } + + private let state = Mutex(State()) + + public init() {} + + public var isActive: Bool { + state.withLock { !$0.isRevoked } + } + + #if DEBUG + var quiescenceWaiterCountForTesting: Int { + state.withLock { $0.waiters.count } + } + #endif + + public func revoke() { + state.withLock { $0.isRevoked = true } + } + + public func checkActive() throws { + guard isActive else { throw CancellationError() } + } + + /// Linearizes physical submission with revocation; submitted work must still settle. + public func performIfActive(_ submission: () throws -> Void) throws { + try state.withLock { state in + guard !state.isRevoked else { throw CancellationError() } + try submission() + } + } + + func beginOperation() throws { + try state.withLock { + guard !$0.isRevoked else { throw CancellationError() } + $0.operations += 1 + } + } + + func endOperation() { + let waiters = state.withLock { state -> [CheckedContinuation] in + state.operations -= 1 + guard state.operations == 0 else { return [] } + let waiters = state.waiters + state.waiters.removeAll() + return waiters + } + for waiter in waiters { + waiter.resume() + } + } + + /// Joins actual transport calls, including calls whose original waiter was cancelled. + public func waitForQuiescence() async { + await withCheckedContinuation { continuation in + let complete = state.withLock { state -> Bool in + guard state.operations != 0 else { return true } + state.waiters.append(continuation) + return false + } + if complete { continuation.resume() } + } + } +} diff --git a/MeshCore/Sources/MeshCore/Transport/WiFiTransport.swift b/MeshCore/Sources/MeshCore/Transport/WiFiTransport.swift index 6dc8f99165..2b3fbe2723 100644 --- a/MeshCore/Sources/MeshCore/Transport/WiFiTransport.swift +++ b/MeshCore/Sources/MeshCore/Transport/WiFiTransport.swift @@ -102,6 +102,15 @@ public actor WiFiTransport: MeshTransport { /// Establishes a TCP connection to the configured host and port. /// Call `setConnectionInfo(host:port:)` first. public func connect() async throws { + try await performConnect(sessionBinding: nil) + } + + public func connect(sessionBinding: SessionTransportBinding) async throws { + try await performConnect(sessionBinding: sessionBinding) + } + + private func performConnect(sessionBinding: SessionTransportBinding?) async throws { + try sessionBinding?.checkActive() // Idempotent: skip if already connected. Without this guard, // session.start() orphans the TCP connection the caller already established. if _isConnected { @@ -136,7 +145,7 @@ public actor WiFiTransport: MeshTransport { // Race connection against timeout try await withThrowingTaskGroup(of: Void.self) { group in group.addTask { - try await self.performConnection(newConnection) + try await self.performConnection(newConnection, sessionBinding: sessionBinding) } group.addTask { @@ -162,7 +171,7 @@ public actor WiFiTransport: MeshTransport { } /// Performs the actual connection wait via continuation. - private func performConnection(_ newConnection: NWConnection) async throws { + private func performConnection(_ newConnection: NWConnection, sessionBinding: SessionTransportBinding?) async throws { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in self.connectContinuation = continuation @@ -172,7 +181,18 @@ public actor WiFiTransport: MeshTransport { } } - newConnection.start(queue: .global(qos: .userInitiated)) + do { + if let sessionBinding { + try sessionBinding.performIfActive { + newConnection.start(queue: .global(qos: .userInitiated)) + } + } else { + newConnection.start(queue: .global(qos: .userInitiated)) + } + } catch { + connectContinuation = nil + continuation.resume(throwing: error) + } } } @@ -208,6 +228,19 @@ public actor WiFiTransport: MeshTransport { } public func send(_ data: Data) async throws { + try await performSend(data, sessionBinding: nil) + } + + public func send(_ data: Data, sessionBinding: SessionTransportBinding) async throws { + try await performSend(data, sessionBinding: sessionBinding) + } + + public func sendWithoutResponse(_ data: Data, sessionBinding: SessionTransportBinding) async throws { + try await performSend(data, sessionBinding: sessionBinding) + } + + private func performSend(_ data: Data, sessionBinding: SessionTransportBinding?) async throws { + try sessionBinding?.checkActive() guard let connection, _isConnected else { throw WiFiTransportError.notConnected } @@ -234,15 +267,38 @@ public actor WiFiTransport: MeshTransport { return } - connection.send(content: frame, completion: .contentProcessed { error in - if let cont = state.withLock({ let cont = $0; $0 = nil; return cont }) { - if let error { - cont.resume(throwing: WiFiTransportError.sendFailed(error.localizedDescription)) - } else { - cont.resume() + let submit = { + connection.send(content: frame, completion: .contentProcessed { error in + sessionBinding?.endOperation() + if let cont = state.withLock({ let cont = $0; $0 = nil; return cont }) { + if let error { + cont.resume(throwing: WiFiTransportError.sendFailed(error.localizedDescription)) + } else { + cont.resume() + } + } + }) + } + do { + if let sessionBinding { + try sessionBinding.beginOperation() + do { + try sessionBinding.performIfActive(submit) + } catch { + sessionBinding.endOperation() + throw error } + } else { + submit() } - }) + } catch { + let waiting = state.withLock { stored -> CheckedContinuation? in + let waiting = stored + stored = nil + return waiting + } + waiting?.resume(throwing: error) + } } } onCancel: { if let cont = state.withLock({ let cont = $0; $0 = nil; return cont }) { diff --git a/MeshCore/Tests/MeshCoreTestSupport/TestClock.swift b/MeshCore/Tests/MeshCoreTestSupport/TestClock.swift index cd8be15d11..e906333c69 100644 --- a/MeshCore/Tests/MeshCoreTestSupport/TestClock.swift +++ b/MeshCore/Tests/MeshCoreTestSupport/TestClock.swift @@ -56,6 +56,14 @@ public final class TestClock: Clock, @unchecked Sendable { return sleepers.count } + /// Time until the earliest parked deadline. `nil` when nobody is parked. + public var nextSleepDuration: Duration? { + lock.lock() + defer { lock.unlock() } + guard let deadline = sleepers.map(\.deadline).min() else { return nil } + return _now.duration(to: deadline) + } + public func sleep(until deadline: Instant, tolerance: Duration? = nil) async throws { let id = UUID() try await withTaskCancellationHandler { @@ -86,6 +94,23 @@ public final class TestClock: Clock, @unchecked Sendable { } } + /// Moves virtual time to the earliest parked deadline and resumes those sleepers. + /// Production timeout values stay in place; the test does not wait them out. + public 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. public func advance(by duration: Duration = .zero) { lock.lock() diff --git a/MeshCore/Tests/MeshCoreTests/Session/CLIProvenanceScopeTests.swift b/MeshCore/Tests/MeshCoreTests/Session/CLIProvenanceScopeTests.swift new file mode 100644 index 0000000000..1f601b7d8c --- /dev/null +++ b/MeshCore/Tests/MeshCoreTests/Session/CLIProvenanceScopeTests.swift @@ -0,0 +1,286 @@ +import Foundation +@testable import MeshCore +import Synchronization +import Testing + +@Suite("CLI correlation scope lifetime") +@MainActor +struct CLIProvenanceScopeTests { + @Test + func `exhaustion rejects typed command before wire and fresh owner works`() async throws { + let scope = RadioCLICorrelationScope() + var prefixes: Set = [] + for _ in 0.. 1")) + #expect(try await command.value == "> 1") + await fresh.close() + } catch { + await fresh.close() + throw error + } + } + + @Test + func `shared scope rejects timed out retired session password`() async throws { + let scope = RadioCLICorrelationScope() + let first = try await Harness.make(scope: scope) + let previousPrefix: String + do { + let before = await first.transport.sentData.count + let password = first.start { try await first.session.runCorrelatedCliCommand("get wifi.pwd") } + try await waitUntil { await first.transport.sentData.count == before + 1 } + previousPrefix = try #require(await first.lastPrefix()) + await #expect { try await password.value } throws: { error in + guard let error = error as? MeshCoreError, case .timeout = error else { return false } + return true + } + await first.close() + } catch { + await first.close() + throw error + } + let next = try await Harness.make(scope: scope) + do { + let before = await next.transport.sentData.count + let ssid = next.start { try await next.session.runCorrelatedCliCommand("get wifi.ssid") } + try await waitUntil { await next.transport.sentData.count == before + 1 } + let prefix = try #require(await next.lastPrefix()) + #expect(prefix != previousPrefix) + await next.transport.simulateReceive(Self.reply(previousPrefix + "> synthetic-private-value")) + await next.transport.simulateReceive(Self.reply(prefix + "> configured")) + let belongsToCurrentRequest = try await ssid.value == "> configured" + #expect(belongsToCurrentRequest) + let laterBefore = await next.transport.sentData.count + let later = next.start { try await next.session.runCorrelatedCliCommand("get wifi.enabled") } + try await waitUntil { await next.transport.sentData.count == laterBefore + 1 } + let laterPrefix = try #require(await next.lastPrefix()) + await next.transport.simulateReceive(Self.reply(laterPrefix + "> 1")) + #expect(try await later.value == "> 1") + await next.close() + } catch { + await next.close() + throw error + } + } + + @Test + func `raw pipe value and multibyte prefix keep their bytes`() async throws { + let harness = try await Harness.make(scope: RadioCLICorrelationScope()) + do { + let before = await harness.transport.sentData.count + let raw = harness.start { try await harness.session.runCliCommand("get wifi.ssid") } + try await waitUntil { await harness.transport.sentData.count == before + 1 } + await harness.transport.simulateReceive(Self.reply("> |network")) + #expect(try await raw.value == "> |network") + let original = " é|get wifi.ssid" + let tagged = harness.start { try await harness.session.runCliCommand(original) } + try await waitUntil { await harness.transport.sentData.count == before + 2 } + let actual = await harness.transport.sentData.last + #expect(actual == PacketBuilder.runCliCommand(original)) + await harness.transport.simulateReceive(Self.reply("é|> configured")) + #expect(try await tagged.value == "é|> configured") + await harness.close() + } catch { + await harness.close() + throw error + } + } + + @Test + func `unprefixed timeout blocks raw authority but typed read still works`() async throws { + let harness = try await Harness.make(scope: RadioCLICorrelationScope()) + do { + await #expect { + try await harness.session.runCliCommand("get wifi.pwd") + } throws: { error in + guard let error = error as? MeshCoreError, case .timeout = error else { return false } + return true + } + let before = await harness.transport.sentData.count + await #expect { + try await harness.session.runCliCommand("get wifi.ssid") + } throws: { error in + guard let error = error as? MeshCoreError, case .invalidInput = error else { return false } + return true + } + #expect(await harness.transport.sentData.count == before) + let typed = harness.start { try await harness.session.runCorrelatedCliCommand("get wifi.ssid") } + try await waitUntil { await harness.transport.sentData.count == before + 1 } + let prefix = try #require(await harness.lastPrefix()) + await harness.transport.simulateReceive(Self.reply("> synthetic-private-value")) + await harness.transport.simulateReceive(Self.reply(prefix + "> configured")) + let currentValue = try await typed.value == "> configured" + #expect(currentValue) + await harness.close() + } catch { + await harness.close() + throw error + } + } + + @Test + func `typed null text is rejected before wire and valid typed read works`() async throws { + let harness = try await Harness.make(scope: RadioCLICorrelationScope()) + do { + let before = await harness.transport.sentData.count + var rejected = false + do { + _ = try await harness.session.runCorrelatedCliCommand("set wifi.pwd synthetic\0truncated") + } catch let error as MeshCoreError { + if case .invalidInput = error { rejected = true } else { throw error } + } + #expect(rejected) + #expect(await harness.transport.sentData.count == before) + let typed = harness.start { try await harness.session.runCorrelatedCliCommand("get wifi.enabled") } + try await waitUntil { await harness.transport.sentData.count == before + 1 } + let prefix = try #require(await harness.lastPrefix()) + await harness.transport.simulateReceive(Self.reply(prefix + "> 1")) + #expect(try await typed.value == "> 1") + await harness.close() + } catch { + await harness.close() + throw error + } + } + + @Test + func `canonically equivalent raw prefixes keep distinct wire identity`() async throws { + let harness = try await Harness.make(scope: RadioCLICorrelationScope()) + let prefixes = ["\u{0340}|", "\u{0300}|"] + do { + for prefix in prefixes { + let command = prefix + "get wifi.ssid" + let expected = prefix + "> configured" + let before = await harness.transport.sentData.count + let finished = Mutex(false) + let raw = harness.start { + defer { finished.withLock { $0 = true } } + return try await harness.session.runCliCommand(command) + } + try await waitUntil { + await harness.transport.sentData.count == before + 1 || finished.withLock { $0 } + } + let actualPacket = await harness.transport.sentData.last + let submittedExactWireBytes = actualPacket == PacketBuilder.runCliCommand(command) + #expect(submittedExactWireBytes) + if submittedExactWireBytes { await harness.transport.simulateReceive(Self.reply(expected)) } + switch await raw.result { + case let .success(reply): + let reflectedExactPrefixBytes = reply.utf8.elementsEqual(expected.utf8) + #expect(reflectedExactPrefixBytes) + case .failure: + Issue.record("Distinct wire prefix bytes must remain usable") + } + } + for prefix in prefixes { + let before = await harness.transport.sentData.count + await #expect { + try await harness.session.runCliCommand(prefix + "get wifi.enabled") + } throws: { error in + guard let error = error as? MeshCoreError, case .invalidInput = error else { return false } + return true + } + #expect(await harness.transport.sentData.count == before) + } + let before = await harness.transport.sentData.count + let later = harness.start { try await harness.session.runCorrelatedCliCommand("get wifi.enabled") } + try await waitUntil { await harness.transport.sentData.count == before + 1 } + let prefix = try #require(await harness.lastPrefix()) + await harness.transport.simulateReceive(Self.reply(prefix + "> 1")) + #expect(try await later.value == "> 1") + await harness.close() + } catch { + await harness.close() + throw error + } + } + + private static func reply(_ text: String) -> Data { + Data([ResponseCode.cliReply.rawValue]) + Data(text.utf8) + } + + @MainActor + private final class Harness { + let transport: MockTransport + let session: MeshCoreSession + private var workers: [Task] = [] + + private init(transport: MockTransport, session: MeshCoreSession) { + self.transport = transport + self.session = session + } + + static func make(scope: RadioCLICorrelationScope) async throws -> Harness { + let transport = MockTransport() + let session = MeshCoreSession( + transport: transport, configuration: SessionConfiguration(defaultTimeout: 0.1), + radioCLICorrelationScope: scope + ) + let start = Task { try await session.start() } + do { + try await waitUntil { await transport.sentData.count == 1 } + 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]) + await transport.simulateReceive(packet) + try await start.value + return Harness(transport: transport, session: session) + } catch { + await session.stop() + _ = await start.result + await session.waitForQuiescence() + throw error + } + } + + func start(_ body: @escaping @MainActor @Sendable () async throws -> String) -> Task { + let worker = Task { try await body() } + workers.append(worker) + return worker + } + + func lastPrefix() async -> String? { + guard let command = await transport.sentData.last else { return nil } + return RadioCLICorrelationScope.commandPrefix(String(decoding: command.dropFirst(), as: UTF8.self)) + } + + func close() async { + await session.stop() + for worker in workers { + _ = await worker.result + } + workers.removeAll() + await session.waitForQuiescence() + #expect(await session.subscriberCountForTest == 0) + #expect(await transport.isConnected == false) + } + } +} diff --git a/MeshCore/Tests/MeshCoreTests/Session/CLIProvenanceSessionTests.swift b/MeshCore/Tests/MeshCoreTests/Session/CLIProvenanceSessionTests.swift new file mode 100644 index 0000000000..6da611a007 --- /dev/null +++ b/MeshCore/Tests/MeshCoreTests/Session/CLIProvenanceSessionTests.swift @@ -0,0 +1,179 @@ +import Foundation +@testable import MeshCore +import Testing + +@Suite("CLI request provenance") +struct CLIProvenanceSessionTests { + @Test + func `bare error cannot reject tagged command`() async throws { + let transport = MockTransport() + let session = MeshCoreSession( + transport: transport, configuration: SessionConfiguration(defaultTimeout: 1) + ) + let start = Task { try await session.start() } + do { + try await waitUntil("appStart was physically sent") { await transport.sentData.count == 1 } + await transport.simulateReceive(Self.selfInfoPacket()) + try await start.value + let command = Task { try await session.runCliCommand("AD|set wifi.enabled 0") } + do { + try await waitUntil("tagged setter is physically submitted") { await transport.sentData.count == 2 } + await transport.simulateReceive(Data([ResponseCode.error.rawValue, 1])) + await transport.simulateReceive(Self.reply("AD|> wifi.enabled updated (reboot to apply)")) + let result = await command.result + switch result { + case let .success(reply): + #expect(reply == "AD|> wifi.enabled updated (reboot to apply)") + case .failure: + Issue.record("A bare device error cannot identify a tagged command as rejected") + } + let later = Task { try await session.runCliCommand("AE|get wifi.enabled") } + do { + try await waitUntil("later command physically submits") { await transport.sentData.count == 3 } + await transport.simulateReceive(Self.reply("AE|> 0")) + #expect(try await later.value == "AE|> 0") + } catch { + await session.stop() + _ = await later.result + throw error + } + } catch { + await session.stop() + _ = await command.result + throw error + } + await session.stop() + await session.waitForQuiescence() + #expect(await session.subscriberCountForTest == 0) + } catch { + await session.stop() + _ = await start.result + await session.waitForQuiescence() + throw error + } + } + + @Test(arguments: [false, true]) + func `explicit prefix cannot be reused`(_ firstTimedOut: Bool) async throws { + let transport = MockTransport() + let session = MeshCoreSession( + transport: transport, configuration: SessionConfiguration(defaultTimeout: 0.1) + ) + let start = Task { try await session.start() } + do { + try await waitUntil("appStart was physically sent") { await transport.sentData.count == 1 } + await transport.simulateReceive(Self.selfInfoPacket()) + try await start.value + let first = Task { try await session.runCliCommand("AF|get wifi.enabled") } + do { + try await waitUntil("first use owns the prefix") { await transport.sentData.count == 2 } + if !firstTimedOut { await transport.simulateReceive(Self.reply("AF|> 1")) } + let result = await first.result + if !firstTimedOut, case .failure = result { Issue.record("First prefix use should be usable") } + if firstTimedOut, case .success = result { Issue.record("Missing first reply should time out") } + let before = await transport.sentData.count + + await #expect { + try await session.runCliCommand("AF|get wifi.ssid") + } throws: { error in + guard let error = error as? MeshCoreError, case .invalidInput = error else { return false } + return true + } + + #expect(await transport.sentData.count == before) + let afterReuse = await transport.sentData.count + let later = Task { try await session.runCliCommand("AG|get wifi.enabled") } + do { + try await waitUntil("a fresh prefix remains usable") { await transport.sentData.count == afterReuse + 1 } + await transport.simulateReceive(Self.reply("AG|> 1")) + #expect(try await later.value == "AG|> 1") + } catch { + await session.stop() + _ = await later.result + throw error + } + } catch { + await session.stop() + _ = await first.result + throw error + } + await session.stop() + await session.waitForQuiescence() + #expect(await session.subscriberCountForTest == 0) + } catch { + await session.stop() + _ = await start.result + await session.waitForQuiescence() + throw error + } + } + + @Test(arguments: [false, true]) + func `timed out reply cannot certify next request`(_ nextIsPrefixed: Bool) async throws { + let transport = MockTransport() + let session = MeshCoreSession( + transport: transport, configuration: SessionConfiguration(defaultTimeout: 0.1) + ) + let start = Task { try await session.start() } + do { + try await waitUntil("appStart was physically sent") { await transport.sentData.count == 1 } + await transport.simulateReceive(Self.selfInfoPacket()) + try await start.value + await #expect { + try await session.runCliCommand("AA|get wifi.pwd") + } throws: { error in + guard let error = error as? MeshCoreError, case .timeout = error else { return false } + return true + } + let command = nextIsPrefixed ? "AB|get wifi.ssid" : "get wifi.enabled" + let expected = nextIsPrefixed ? "AB|> configured" : "> 1" + let next = Task { try await session.runCliCommand(command) } + do { + try await waitUntil("next CLI request owns its wire exchange") { await transport.sentData.count == 3 } + await transport.simulateReceive(Self.reply("AA|> synthetic-private-value")) + await transport.simulateReceive(Self.reply(expected)) + let actual = try await next.value + let belongsToCurrentRequest = actual == expected + #expect(belongsToCurrentRequest) + let later = Task { try await session.runCliCommand("AC|get wifi.enabled") } + do { + try await waitUntil("a later actual command is submitted") { await transport.sentData.count == 4 } + await transport.simulateReceive(Self.reply("AC|> 1")) + #expect(try await later.value == "AC|> 1") + } catch { + await session.stop() + _ = await later.result + throw error + } + } catch { + await session.stop() + _ = await next.result + throw error + } + await session.stop() + await session.waitForQuiescence() + #expect(await session.subscriberCountForTest == 0) + #expect(await transport.isConnected == false) + } catch { + await session.stop() + _ = await start.result + await session.waitForQuiescence() + throw error + } + } + + private static func reply(_ text: String) -> Data { + Data([ResponseCode.cliReply.rawValue]) + Data(text.utf8) + } + + private static func selfInfoPacket() -> Data { + var reply = Data([ResponseCode.selfInfo.rawValue, 1, 22, 22]) + reply.append(Data(repeating: 1, count: 32)) + 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]) + return reply + } +} diff --git a/MeshCore/Tests/MeshCoreTests/Session/MeshCoreSessionLifecycleOwnershipTests.swift b/MeshCore/Tests/MeshCoreTests/Session/MeshCoreSessionLifecycleOwnershipTests.swift new file mode 100644 index 0000000000..f335059b66 --- /dev/null +++ b/MeshCore/Tests/MeshCoreTests/Session/MeshCoreSessionLifecycleOwnershipTests.swift @@ -0,0 +1,147 @@ +import Foundation +@testable import MeshCore +import MeshCoreTestSupport +import Testing + +@Suite("MeshCoreSession lifecycle ownership") +struct MeshCoreSessionLifecycleOwnershipTests { + @Test + func `stopping during transport connect prevents a late startup handshake`() async throws { + let transport = HeldConnectTransport() + let session = MeshCoreSession( + transport: transport, + configuration: SessionConfiguration(defaultTimeout: 0.05, clientIdentifier: "MCTst") + ) + let starting = Task { + try await session.start(disconnectTransportOnFailure: false) + } + try await waitUntil { await transport.connectIsWaiting } + + await session.stop(disconnectTransport: false) + await transport.releaseConnect() + await #expect(throws: CancellationError.self) { + try await starting.value + } + + #expect(await transport.sentData.isEmpty) + #expect(await session.sessionIsRunning == false) + #expect(await transport.disconnectCount == 0) + await transport.disconnect() + } + + @Test + func `a later default stop still closes an independently owned transport`() async throws { + let transport = MockTransport() + try await transport.connect() + let session = MeshCoreSession(transport: transport) + await session.stop(disconnectTransport: false) + #expect(await transport.isConnected) + await session.stop() + #expect(await transport.isConnected == false) + } + + @Test(arguments: [false, true]) + func `owned retirement drains a cancelled caller exchange and held physical completion`(replyBeforeCompletion: Bool) async throws { + let physical = MockTransport() + let binding = SessionTransportBinding() + let session = MeshCoreSession( + transport: SessionBoundTransport(transport: physical, binding: binding), + configuration: SessionConfiguration(defaultTimeout: 1, clientIdentifier: "MCTst") + ) + try await start(session, physical: physical, expectedSends: 1) + await physical.holdNextSend() + let caller = Task { try await session.factoryReset() } + try await waitUntil { await physical.sendIsWaiting } + caller.cancel() + await #expect(throws: CancellationError.self) { try await caller.value } + + binding.revoke() + let stopped = CallTracker() + let retirement = Task { + await session.stop(disconnectTransport: false, drainExchanges: true) + await binding.waitForQuiescence() + await session.waitForQuiescence() + stopped.markCalled() + } + try await waitUntil { await !session.sessionIsRunning } + #expect(!stopped.wasCalled) + if replyBeforeCompletion { await physical.simulateOK() } + await physical.releaseHeldSend() + await binding.waitForQuiescence() + if !replyBeforeCompletion { + #expect(!stopped.wasCalled) + await physical.simulateOK() + } + await retirement.value + #expect(stopped.wasCalled) + #expect(await physical.isConnected) + + await physical.disconnect() + let replacement = MeshCoreSession(transport: physical) + try await start(replacement, physical: physical, expectedSends: 3) + let probe = Task { try await replacement.factoryReset() } + try await waitUntil { await physical.sentData.count == 4 } + await physical.simulateOK() + try await probe.value + await replacement.stop() + await replacement.waitForQuiescence() + } + + private func start(_ session: MeshCoreSession, physical: MockTransport, expectedSends: Int) async throws { + let starting = Task { try await session.start(disconnectTransportOnFailure: false) } + try await waitUntil { await physical.sentData.count == expectedSends } + await physical.simulateReceive(selfInfoPacket()) + try await starting.value + } + + private func selfInfoPacket() -> Data { + var packet = Data([ResponseCode.selfInfo.rawValue, 1, 22, 22]) + packet.append(Data(repeating: 1, count: 32)) + packet.append(Data(repeating: 0, count: 12)) + packet.append(contentsOf: withUnsafeBytes(of: UInt32(915_000).littleEndian) { Array($0) }) + packet.append(contentsOf: withUnsafeBytes(of: UInt32(125_000).littleEndian) { Array($0) }) + packet.append(contentsOf: [7, 5]) + packet.append(contentsOf: "Test".utf8) + return packet + } +} + +private actor HeldConnectTransport: MeshTransport { + private let base = MockTransport() + private var connectContinuation: CheckedContinuation? + private(set) var disconnectCount = 0 + var connectIsWaiting: Bool { + connectContinuation != nil + } + + var sentData: [Data] { + get async { await base.sentData } + } + + var receivedData: AsyncStream { + get async { await base.receivedData } + } + + var isConnected: Bool { + get async { await base.isConnected } + } + + func connect() async throws { + await withCheckedContinuation { connectContinuation = $0 } + try await base.connect() + } + + func releaseConnect() { + connectContinuation?.resume() + connectContinuation = nil + } + + func disconnect() async { + disconnectCount += 1 + await base.disconnect() + } + + func send(_ data: Data) async throws { + try await base.send(data) + } +} diff --git a/MeshCore/Tests/MeshCoreTests/Session/VerifiedChannelSendSerializationTests.swift b/MeshCore/Tests/MeshCoreTests/Session/VerifiedChannelSendSerializationTests.swift new file mode 100644 index 0000000000..ed795e6be1 --- /dev/null +++ b/MeshCore/Tests/MeshCoreTests/Session/VerifiedChannelSendSerializationTests.swift @@ -0,0 +1,149 @@ +import Foundation +@testable import MeshCore +import Testing + +@Suite("Verified channel send serialization") +struct VerifiedChannelSendSerializationTests { + private static let index: UInt8 = 1 + private static let timestamp = Date(timeIntervalSince1970: 1_700_000_000) + private static let secretA = Data(repeating: 0xAA, count: 16) + private static let secretB = Data(repeating: 0xBB, count: 16) + private static let scope = ResolvedFloodScope.scope(.region("Test")) + + @Test(arguments: [false, true]) + func `a queued channel replacement is read before deciding whether to send`(scoped: Bool) async throws { + let (session, transport) = try await startSession() + defer { Task { await session.stop() } } + let replacement = Task { + try await session.setChannel(index: Self.index, name: "B", secret: Self.secretB) + } + try await waitForFrames(2, transport: transport) + let send = verifiedSend(session, scoped: scoped) + try await waitForWaiters(1, session: session) + #expect(await transport.sentData.count == 2) + await transport.simulateOK() + try await replacement.value + try await waitForFrames(3, transport: transport) + #expect(await transport.sentData[2] == PacketBuilder.getChannel(index: Self.index)) + await transport.simulateReceive(channelPacket(secret: Self.secretB)) + await expectOccupancyMismatch(send) + #expect(await transport.sentData.allSatisfy { $0.first != CommandCode.sendChannelMessage.rawValue }) + #expect(await transport.sentData.allSatisfy { $0.first != CommandCode.setFloodScope.rawValue }) + await session.stop() + } + + @Test(arguments: [false, true]) + func `a replacement queued during validation waits until the verified send finishes`(scoped: Bool) async throws { + let (session, transport) = try await startSession() + defer { Task { await session.stop() } } + let send = verifiedSend(session, scoped: scoped) + try await waitForFrames(2, transport: transport) + #expect(await transport.sentData[1] == PacketBuilder.getChannel(index: Self.index)) + let replacement = Task { + try await session.setChannel(index: Self.index, name: "B", secret: Self.secretB) + } + try await waitForWaiters(1, session: session) + await transport.simulateReceive(channelPacket(secret: Self.secretA)) + if scoped { + try await waitForFrames(3, transport: transport) + #expect(await transport.sentData[2].first == CommandCode.setFloodScope.rawValue) + await transport.simulateOK() + } + let sendFrameCount = scoped ? 4 : 3 + try await waitForFrames(sendFrameCount, transport: transport) + #expect(await transport.sentData[sendFrameCount - 1] == PacketBuilder.sendChannelMessage( + channel: Self.index, text: "Only for A", timestamp: Self.timestamp + )) + #expect(await transport.sentData.allSatisfy { $0.first != CommandCode.setChannel.rawValue }) + await transport.simulateOK() + try await send.value + try await waitForFrames(sendFrameCount + 1, transport: transport) + #expect(await transport.sentData[sendFrameCount] == PacketBuilder.setChannel( + index: Self.index, name: "B", secret: Self.secretB + )) + await transport.simulateOK() + try await replacement.value + await session.stop() + } + + @Test(arguments: [false, true]) + func `cancellation drains channel validation without writing scope or message`(scoped: Bool) async throws { + let (session, transport) = try await startSession() + defer { Task { await session.stop() } } + let send = verifiedSend(session, scoped: scoped) + try await waitForFrames(2, transport: transport) + send.cancel() + await #expect(throws: CancellationError.self) { try await send.value } + let following = Task { try await session.setChannel(index: Self.index, name: "B", secret: Self.secretB) } + try await waitForWaiters(1, session: session) + #expect(await transport.sentData.count == 2) + await transport.simulateReceive(channelPacket(secret: Self.secretA)) + try await waitForFrames(3, transport: transport) + #expect(await transport.sentData[2].first == CommandCode.setChannel.rawValue) + #expect(await transport.sentData.allSatisfy { $0.first != CommandCode.sendChannelMessage.rawValue }) + #expect(await transport.sentData.allSatisfy { $0.first != CommandCode.setFloodScope.rawValue }) + await transport.simulateOK() + try await following.value + await session.stop() + } + + @Test + func `a missing slot is an occupancy mismatch rather than channel send pool exhaustion`() async throws { + let (session, transport) = try await startSession() + defer { Task { await session.stop() } } + let send = verifiedSend(session, scoped: false) + try await waitForFrames(2, transport: transport) + await transport.simulateError(code: ErrorCode.notFound.rawValue) + await expectOccupancyMismatch(send) + #expect(await transport.sentData.count == 2) + await session.stop() + } + + private func verifiedSend(_ session: MeshCoreSession, scoped: Bool) -> Task { + Task { + try await session.sendVerifiedChannelMessage( + channel: Self.index, text: "Only for A", timestamp: Self.timestamp, + floodScope: scoped ? Self.scope : nil, expectedSecret: Self.secretA + ) + } + } + + private func expectOccupancyMismatch(_ send: Task) async { + let error = await #expect(throws: MeshCoreError.self) { try await send.value } + guard case .invalidResponse? = error else { + Issue.record("Expected an occupancy mismatch, got \(String(describing: error))") + return + } + } + + private func channelPacket(secret: Data) -> Data { + Data([ResponseCode.channelInfo.rawValue, Self.index]) + Data("Channel".utf8) + + Data(repeating: 0, count: 25) + secret + } + + private func waitForFrames(_ count: Int, transport: MockTransport) async throws { + try await waitUntil("Expected \(count) command frames") { await transport.sentData.count >= count } + } + + private func waitForWaiters(_ count: Int, session: MeshCoreSession) async throws { + try await waitUntil("Expected \(count) serialized command waiters") { + await session.requestResponseSerializer.waiterCountForTest == count + } + } + + private func startSession() async throws -> (MeshCoreSession, MockTransport) { + let transport = MockTransport() + let session = MeshCoreSession(transport: transport, configuration: SessionConfiguration(defaultTimeout: 10)) + let start = Task { try await session.start() } + try await waitForFrames(1, transport: transport) + var packet = Data([ResponseCode.selfInfo.rawValue, 1, 22, 22]) + packet.append(Data(repeating: 1, count: 32)) + packet.append(Data(repeating: 0, count: 12)) + packet.append(contentsOf: withUnsafeBytes(of: UInt32(915_000).littleEndian) { Array($0) }) + packet.append(contentsOf: withUnsafeBytes(of: UInt32(125_000).littleEndian) { Array($0) }) + packet.append(contentsOf: [7, 5]) + await transport.simulateReceive(packet) + try await start.value + return (session, transport) + } +} diff --git a/MeshCore/Tests/MeshCoreTests/Transport/SessionTransportBindingTests.swift b/MeshCore/Tests/MeshCoreTests/Transport/SessionTransportBindingTests.swift new file mode 100644 index 0000000000..bfbf7f7455 --- /dev/null +++ b/MeshCore/Tests/MeshCoreTests/Transport/SessionTransportBindingTests.swift @@ -0,0 +1,119 @@ +import Foundation +@testable import MeshCore +import MeshCoreTestSupport +import Testing + +@Suite("Session transport binding") +struct SessionTransportBindingTests { + @Test + func `revocation rejects every queued physical submission and receive access`() async throws { + let physical = GatedPhysicalTransport() + let binding = SessionTransportBinding() + let transport = SessionBoundTransport(transport: physical, binding: binding) + let writing = Task { try await transport.send(Data([1])) } + while await !physical.sendIsWaiting { + await Task.yield() + } + + binding.revoke() + let settled = CallTracker() + let joining = Task { + await binding.waitForQuiescence() + settled.markCalled() + } + try await waitUntil("binding join should register or return") { + binding.quiescenceWaiterCountForTesting > 0 || settled.wasCalled + } + #expect(!settled.wasCalled) + await physical.releaseSend() + await #expect(throws: CancellationError.self) { try await writing.value } + await joining.value + + await #expect(throws: CancellationError.self) { try await transport.connect() } + await #expect(throws: CancellationError.self) { try await transport.sendWithoutResponse(Data([2])) } + var iterator = await transport.receivedData.makeAsyncIterator() + #expect(await iterator.next() == nil) + #expect(await physical.submissions.isEmpty) + + let replacement = SessionBoundTransport(transport: physical, binding: SessionTransportBinding()) + try await replacement.sendWithoutResponse(Data([3])) + #expect(await physical.submissions == [Data([3])]) + } + + @Test + func `serializer quiescence waits for exchange after its caller is cancelled`() async throws { + let serializer = RequestResponseSerializer() + let gate = ExchangeGate() + let caller = Task { + try await serializer.withSerialization { await gate.wait() } + } + while await !gate.isWaiting { + await Task.yield() + } + caller.cancel() + await #expect(throws: CancellationError.self) { try await caller.value } + + let settled = CallTracker() + let joining = Task { + await serializer.waitForQuiescence() + settled.markCalled() + } + try await waitUntil("serializer join should register or return") { + await serializer.quiescenceWaiterCountForTesting > 0 || settled.wasCalled + } + #expect(!settled.wasCalled) + await gate.release() + await joining.value + #expect(settled.wasCalled) + let probe = try await serializer.withSerialization { true } + #expect(probe) + } +} + +private actor GatedPhysicalTransport: MeshTransport { + private var waiter: CheckedContinuation? + private(set) var submissions: [Data] = [] + var sendIsWaiting: Bool { + waiter != nil + } + + var isConnected: Bool { + true + } + + var receivedData: AsyncStream { + AsyncStream { $0.finish() } + } + + func connect() {} + func disconnect() {} + func send(_ data: Data) { + submissions.append(data) + } + + func send(_ data: Data, sessionBinding: SessionTransportBinding) async throws { + await withCheckedContinuation { waiter = $0 } + try sessionBinding.performIfActive { submissions.append(data) } + } + + func releaseSend() { + waiter?.resume() + waiter = nil + } +} + +private actor ExchangeGate { + private var waiter: CheckedContinuation? + var isWaiting: Bool { + waiter != nil + } + + func wait() async { + await withCheckedContinuation { waiter = $0 } + } + + func release() { + waiter?.resume() + waiter = nil + } +} diff --git a/docs/Testing.md b/docs/Testing.md index 2ca99b003c..28c708175d 100644 --- a/docs/Testing.md +++ b/docs/Testing.md @@ -51,6 +51,8 @@ make test-meshcore 2>&1 | xcsift -f toon Use `xcsift` to get structured output. Add `-c` for code coverage or `-w` for a detailed warnings list. See CLAUDE.md for the full flag reference. +The service-only `SettingsServiceRadioWiFi` suites run in `MC1ServicesTests`; app presentation tests share their configuration-session and firmware helpers through `project.yml`. + The Build workflow runs both SPM package suites and builds the app for the iOS Simulator. GitHub CI does not run the app or StoreKit test suites for now. Run those locally with the make targets above. For a local app test run that saves logs and an `.xcresult` bundle, use `scripts/test-app-ci.py`. It runs `make test-app` on iPhone 17e / iOS 27.0 and reuses `.derivedData`. diff --git a/project.yml b/project.yml index e78853a17b..490601e48a 100644 --- a/project.yml +++ b/project.yml @@ -104,6 +104,10 @@ targets: platform: iOS sources: - path: MC1Tests + - path: MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionTestRadioTransport.swift + - path: MC1Services/Tests/MC1ServicesTests/Mocks/MockBLEStateMachine.swift + - path: MC1Services/Tests/MC1ServicesTests/Mocks/MockConfigurationSession.swift + - path: MC1Services/Tests/MC1ServicesTests/Helpers/RadioWiFiFirmware.swift dependencies: - target: MC1 settings: From c4946645191e72884be5dc63963a25fd3b52d0d5 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Wed, 4 Nov 2026 10:40:58 -0800 Subject: [PATCH 06/66] feat: add meshcore sensor support (#473) --- MC1/Extensions/ContactType+Display.swift | 4 + .../RemoteNodeError+UserFacingMessage.swift | 8 + MC1/Resources/Generated/L10n.swift | 56 ++++ .../Localization/de.lproj/Contacts.strings | 15 + .../Localization/de.lproj/Localizable.strings | 15 + .../Localization/de.lproj/Map.strings | 9 + .../Localization/de.lproj/RemoteNodes.strings | 33 ++ .../Localization/de.lproj/Settings.strings | 3 + .../Localization/en.lproj/Contacts.strings | 10 + .../Localization/en.lproj/Localizable.strings | 10 + .../Localization/en.lproj/Map.strings | 6 + .../Localization/en.lproj/RemoteNodes.strings | 22 ++ .../Localization/en.lproj/Settings.strings | 2 + .../Localization/es.lproj/Contacts.strings | 15 + .../Localization/es.lproj/Localizable.strings | 15 + .../Localization/es.lproj/Map.strings | 9 + .../Localization/es.lproj/RemoteNodes.strings | 33 ++ .../Localization/es.lproj/Settings.strings | 3 + .../Localization/fr.lproj/Contacts.strings | 15 + .../Localization/fr.lproj/Localizable.strings | 15 + .../Localization/fr.lproj/Map.strings | 9 + .../Localization/fr.lproj/RemoteNodes.strings | 33 ++ .../Localization/fr.lproj/Settings.strings | 3 + .../Localization/it.lproj/Contacts.strings | 15 + .../Localization/it.lproj/Localizable.strings | 15 + .../Localization/it.lproj/Map.strings | 9 + .../Localization/it.lproj/RemoteNodes.strings | 33 ++ .../Localization/it.lproj/Settings.strings | 3 + .../Localization/ko.lproj/Contacts.strings | 15 + .../Localization/ko.lproj/Localizable.strings | 15 + .../Localization/ko.lproj/Map.strings | 9 + .../Localization/ko.lproj/RemoteNodes.strings | 33 ++ .../Localization/ko.lproj/Settings.strings | 3 + .../Localization/nl.lproj/Contacts.strings | 15 + .../Localization/nl.lproj/Localizable.strings | 15 + .../Localization/nl.lproj/Map.strings | 9 + .../Localization/nl.lproj/RemoteNodes.strings | 33 ++ .../Localization/nl.lproj/Settings.strings | 3 + .../Localization/pl.lproj/Contacts.strings | 15 + .../Localization/pl.lproj/Localizable.strings | 15 + .../Localization/pl.lproj/Map.strings | 9 + .../Localization/pl.lproj/RemoteNodes.strings | 33 ++ .../Localization/pl.lproj/Settings.strings | 3 + .../Localization/pt.lproj/Contacts.strings | 15 + .../Localization/pt.lproj/Localizable.strings | 15 + .../Localization/pt.lproj/Map.strings | 9 + .../Localization/pt.lproj/RemoteNodes.strings | 33 ++ .../Localization/pt.lproj/Settings.strings | 3 + .../Localization/ru.lproj/Contacts.strings | 15 + .../Localization/ru.lproj/Localizable.strings | 15 + .../Localization/ru.lproj/Map.strings | 9 + .../Localization/ru.lproj/RemoteNodes.strings | 33 ++ .../Localization/ru.lproj/Settings.strings | 3 + .../Localization/uk.lproj/Contacts.strings | 15 + .../Localization/uk.lproj/Localizable.strings | 15 + .../Localization/uk.lproj/Map.strings | 9 + .../Localization/uk.lproj/RemoteNodes.strings | 33 ++ .../Localization/uk.lproj/Settings.strings | 3 + .../zh-Hans.lproj/Contacts.strings | 15 + .../zh-Hans.lproj/Localizable.strings | 15 + .../Localization/zh-Hans.lproj/Map.strings | 9 + .../zh-Hans.lproj/RemoteNodes.strings | 33 ++ .../zh-Hans.lproj/Settings.strings | 3 + .../NotificationStringProviderImpl.swift | 2 + MC1/State/AppState.swift | 19 +- MC1/State/RemoteAdminWorkspaces.swift | 47 ++- MC1/Views/Chats/NewChatView.swift | 4 +- .../ChatViewModel+ConversationCache.swift | 2 +- MC1/Views/Components/GlassFilterBar.swift | 5 +- MC1/Views/Components/MapControlsToolbar.swift | 2 +- MC1/Views/Components/NodeAvatar.swift | 7 +- .../Contacts/ContactActionsSection.swift | 2 +- .../ContactAddConfirmationContent.swift | 6 + .../Contacts/ContactDetailAvatarView.swift | 13 +- .../ContactDetailPresenter+Sheets.swift | 26 +- .../Contacts/ContactDetailState+Actions.swift | 20 ++ MC1/Views/Contacts/ContactRowView.swift | 9 +- MC1/Views/Contacts/ContactsEmptyView.swift | 6 + MC1/Views/Contacts/ContactsViewModel.swift | 4 + MC1/Views/Contacts/DiscoveryView.swift | 10 +- MC1/Views/Contacts/DiscoveryViewModel.swift | 4 + MC1/Views/Contacts/NodeActionRows.swift | 26 +- MC1/Views/Map/ContactCalloutContent.swift | 2 + MC1/Views/Map/ContactDetailSheet.swift | 70 ++++- .../Map/DiscoveredNodeCalloutContent.swift | 2 + MC1/Views/Map/MC1MapView+Layers.swift | 1 + MC1/Views/Map/MapFilter.swift | 2 +- MC1/Views/Map/MapPoint.swift | 1 + MC1/Views/Map/MapSnapshotRenderer.swift | 4 + MC1/Views/Map/PinSpriteRenderer.swift | 2 + .../RemoteNodes/NodeAuthenticationSheet.swift | 184 +++++------ MC1/Views/RemoteNodes/NodeCLIView.swift | 2 +- MC1/Views/RemoteNodes/NodeCLIViewModel.swift | 28 +- MC1/Views/RemoteNodes/NodeManagementTab.swift | 2 +- .../RemoteNodes/NodeManagementTabPicker.swift | 6 +- MC1/Views/RemoteNodes/NodeTelemetryView.swift | 17 +- .../Sensors/SensorSettingsContent.swift | 95 ++++++ .../Sensors/SensorSettingsView.swift | 28 ++ .../Sensors/SensorSettingsViewModel.swift | 244 +++++++++++++++ .../NotificationSettingsSection.swift | 2 +- MC1/Views/Tools/CLI/CLICompletionEngine.swift | 23 +- MC1/Views/Tools/CLI/CLIRemoteTarget.swift | 3 + .../NodeDiscovery/NodeDiscoveryView.swift | 2 +- .../NodeDiscoveryViewModel.swift | 114 +++++-- .../MC1Services/Errors/RemoteNodeError.swift | 12 + .../MC1Services/Models/ProtocolLimits.swift | 1 + .../MC1Services/Models/ProtocolTypes.swift | 3 + .../Models/RemoteNodeSession.swift | 10 +- .../MC1Services/Models/SensorSetting.swift | 41 +++ .../MC1Services/ServiceContainer.swift | 5 +- .../AdvertisementService+DeltaSync.swift | 1 + .../Services/CommandAuditLogger.swift | 9 + .../MC1Services/Services/LoginResult.swift | 4 + .../Services/MessageService+SendDM.swift | 2 +- .../Services/NotificationService.swift | 3 +- .../Services/PersistenceStore.swift | 4 +- .../Services/RemoteCLINoReplyCommand.swift | 17 +- .../Services/RemoteNodeService+CLI.swift | 29 +- .../Services/RemoteNodeService+Login.swift | 125 ++++---- .../RemoteNodeService+Reconnection.swift | 52 ++-- .../Services/RemoteNodeService+Sensor.swift | 121 ++++++++ .../RemoteNodeService+Telemetry.swift | 8 +- .../Services/RemoteNodeService.swift | 70 ++++- .../SensorSettingsResponseParser.swift | 64 ++++ .../Simulator/MockDataProvider+Contacts.swift | 21 ++ .../Simulator/MockDataProvider.swift | 1 + .../Utilities/ContactShareUtilities.swift | 2 +- .../BackupIntegrationTests.swift | 61 +++- .../ContactShareUtilitiesTests.swift | 4 +- .../RemoteNodeLoginContactRecoveryTests.swift | 2 +- .../NodeConfigImportPlannerTests.swift | 24 +- .../NotificationStringProviderTests.swift | 1 + .../Services/RemoteNodeSensorTests.swift | 293 ++++++++++++++++++ .../SensorSettingsResponseParserTests.swift | 51 +++ .../ConnectionStatusLifecycleTests.swift | 4 +- .../RetainedAdminPartitionSurface.swift | 2 + .../ViewModels/ContactsViewModelTests.swift | 16 + .../ViewModels/DiscoveryViewModelTests.swift | 10 + .../NodeDiscoveryLifetimeTests.swift | 71 +++++ .../ViewModels/RemoteAdminLifetimeTests.swift | 16 + .../RetainedAdminPartitionTests.swift | 11 +- .../SensorSettingsViewModelTests.swift | 234 ++++++++++++++ MC1Tests/Views/ContactDetailStateTests.swift | 15 + MC1Tests/Views/Map/MapFilterStateTests.swift | 11 + .../RemoteNodes/NodeCLIViewModelTests.swift | 29 ++ .../Tools/CLI/CLICompletionEngineTests.swift | 13 + .../MeshCore/Models/ContactTypes.swift | 1 + .../MeshCoreTests/Protocol/RegionTests.swift | 14 +- .../Protocol/UpdateContactTests.swift | 8 + .../DiscoverResponseParsingTests.swift | 17 + 150 files changed, 3142 insertions(+), 362 deletions(-) create mode 100644 MC1/Views/RemoteNodes/Sensors/SensorSettingsContent.swift create mode 100644 MC1/Views/RemoteNodes/Sensors/SensorSettingsView.swift create mode 100644 MC1/Views/RemoteNodes/Sensors/SensorSettingsViewModel.swift create mode 100644 MC1Services/Sources/MC1Services/Models/SensorSetting.swift create mode 100644 MC1Services/Sources/MC1Services/Services/RemoteNodeService+Sensor.swift create mode 100644 MC1Services/Sources/MC1Services/Services/SensorSettingsResponseParser.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeSensorTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/SensorSettingsResponseParserTests.swift create mode 100644 MC1Tests/ViewModels/SensorSettingsViewModelTests.swift 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/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/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index 5d4aa568d6..344a845a44 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -1526,6 +1526,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 +1600,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 +1619,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 +2099,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 +2659,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 +2681,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 +2779,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 +2846,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 +2861,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 +3067,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 @@ -3411,6 +3441,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 @@ -3624,6 +3656,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)") @@ -5376,6 +5430,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 diff --git a/MC1/Resources/Localization/de.lproj/Contacts.strings b/MC1/Resources/Localization/de.lproj/Contacts.strings index 8a6fca7369..491b848142 100644 --- a/MC1/Resources/Localization/de.lproj/Contacts.strings +++ b/MC1/Resources/Localization/de.lproj/Contacts.strings @@ -44,6 +44,9 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Raum"; +/* TODO: translate */ +"contacts.nodeKind.sensor" = "Sensor"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Entdeckt"; @@ -75,6 +78,9 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Räume"; +/* TODO: translate */ +"contacts.segment.sensors" = "Sensors"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "Knoten filtern"; @@ -168,9 +174,15 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "Keine Räume"; +/* TODO: translate */ +"contacts.list.empty.sensors.title" = "No Sensors"; + /* 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."; +/* TODO: translate */ +"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" = "Keine Ergebnisse"; @@ -623,6 +635,9 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter - Rooms */ "contacts.discovery.segment.rooms" = "Räume"; +/* TODO: translate */ +"contacts.discovery.segment.sensors" = "Sensors"; + /* 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..4d75fc9f7c 100644 --- a/MC1/Resources/Localization/de.lproj/Localizable.strings +++ b/MC1/Resources/Localization/de.lproj/Localizable.strings @@ -142,6 +142,9 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "Neuer Raum entdeckt"; +/* TODO: translate */ +"notifications.discovery.sensor" = "New Sensor Discovered"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -489,6 +492,18 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Ungültige Antwort vom Remote-Knoten"; +/* TODO: translate */ +"error.remoteNode.sensorOutcomeUnknown" = "The change could not be verified. Reload settings before saving again."; + +/* TODO: translate */ +"error.remoteNode.sensorSettingRejected" = "The sensor rejected this setting."; + +/* TODO: translate */ +"error.remoteNode.invalidSensorSetting" = "Use a nonempty key and value without whitespace. The complete command must fit within 160 UTF-8 bytes."; + +/* TODO: translate */ +"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" = "Zugriff verweigert"; diff --git a/MC1/Resources/Localization/de.lproj/Map.strings b/MC1/Resources/Localization/de.lproj/Map.strings index 60b0f2a676..d10f282420 100644 --- a/MC1/Resources/Localization/de.lproj/Map.strings +++ b/MC1/Resources/Localization/de.lproj/Map.strings @@ -40,6 +40,9 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Filter"; +/* TODO: translate */ +"map.controls.contactsAndSensors" = "Contacts & Sensors"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Filter aktiv"; @@ -264,6 +267,9 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Raum"; +/* TODO: translate */ +"map.nodeKind.sensor" = "Sensor"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -281,6 +287,9 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Raum"; +/* TODO: translate */ +"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/RemoteNodes.strings b/MC1/Resources/Localization/de.lproj/RemoteNodes.strings index c71ceb7f3e..0509b9de4f 100644 --- a/MC1/Resources/Localization/de.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/de.lproj/RemoteNodes.strings @@ -32,6 +32,9 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Repeater"; +/* TODO: translate */ +"remoteNodes.auth.typeSensor" = "Sensor"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Authentifizierung"; @@ -84,6 +87,36 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Repeater-Einstellungen"; +/* TODO: translate */ +"remoteNodes.sensor.adminRequired" = "Sensor management requires administrator access."; + +/* TODO: translate */ +"remoteNodes.sensor.saved" = "Setting verified."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootSent" = "Reboot request sent. The sensor has not confirmed a restart. Authenticate again before sending more commands."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootConfirmation" = "Send a reboot request to this sensor?"; + +/* TODO: translate */ +"remoteNodes.sensor.runtimeOnly" = "Changes affect the running sensor. Persistence across reboot depends on its firmware."; + +/* TODO: translate */ +"remoteNodes.sensor.value" = "Value"; + +/* TODO: translate */ +"remoteNodes.sensor.save" = "Save"; + +/* TODO: translate */ +"remoteNodes.sensor.reload" = "Reload"; + +/* TODO: translate */ +"remoteNodes.sensor.empty" = "This sensor exposes no settings."; + +/* TODO: translate */ +"remoteNodes.sensor.title" = "Sensor Management"; + /* 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 04ea9f6867..0b29548b81 100644 --- a/MC1/Resources/Localization/de.lproj/Settings.strings +++ b/MC1/Resources/Localization/de.lproj/Settings.strings @@ -840,6 +840,9 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Companion"; +/* TODO: translate */ +"notifications.discoveryCompanionsAndSensors" = "Companions & Sensors"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Repeater"; 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/RemoteNodes.strings b/MC1/Resources/Localization/en.lproj/RemoteNodes.strings index 263e19fefd..7d404deff0 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"; @@ -84,6 +86,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 f9f8c374ed..eb98ec5322 100644 --- a/MC1/Resources/Localization/en.lproj/Settings.strings +++ b/MC1/Resources/Localization/en.lproj/Settings.strings @@ -880,6 +880,8 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Companion"; +"notifications.discoveryCompanionsAndSensors" = "Companions & Sensors"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Repeater"; diff --git a/MC1/Resources/Localization/es.lproj/Contacts.strings b/MC1/Resources/Localization/es.lproj/Contacts.strings index 26f868ded3..f007957939 100644 --- a/MC1/Resources/Localization/es.lproj/Contacts.strings +++ b/MC1/Resources/Localization/es.lproj/Contacts.strings @@ -44,6 +44,9 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Sala"; +/* TODO: translate */ +"contacts.nodeKind.sensor" = "Sensor"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Descubierto"; @@ -75,6 +78,9 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Salas"; +/* TODO: translate */ +"contacts.segment.sensors" = "Sensors"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "Filtrar nodos"; @@ -168,9 +174,15 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "Sin salas"; +/* TODO: translate */ +"contacts.list.empty.sensors.title" = "No Sensors"; + /* 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."; +/* TODO: translate */ +"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" = "Sin resultados"; @@ -623,6 +635,9 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter - Rooms */ "contacts.discovery.segment.rooms" = "Salas"; +/* TODO: translate */ +"contacts.discovery.segment.sensors" = "Sensors"; + /* 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..8f230bbe5e 100644 --- a/MC1/Resources/Localization/es.lproj/Localizable.strings +++ b/MC1/Resources/Localization/es.lproj/Localizable.strings @@ -145,6 +145,9 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "Nueva sala descubierta"; +/* TODO: translate */ +"notifications.discovery.sensor" = "New Sensor Discovered"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -493,6 +496,18 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Respuesta no válida del nodo remoto"; +/* TODO: translate */ +"error.remoteNode.sensorOutcomeUnknown" = "The change could not be verified. Reload settings before saving again."; + +/* TODO: translate */ +"error.remoteNode.sensorSettingRejected" = "The sensor rejected this setting."; + +/* TODO: translate */ +"error.remoteNode.invalidSensorSetting" = "Use a nonempty key and value without whitespace. The complete command must fit within 160 UTF-8 bytes."; + +/* TODO: translate */ +"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" = "Permiso denegado"; diff --git a/MC1/Resources/Localization/es.lproj/Map.strings b/MC1/Resources/Localization/es.lproj/Map.strings index 36a2ad56c1..adbc8e9ce3 100644 --- a/MC1/Resources/Localization/es.lproj/Map.strings +++ b/MC1/Resources/Localization/es.lproj/Map.strings @@ -40,6 +40,9 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Filtrar"; +/* TODO: translate */ +"map.controls.contactsAndSensors" = "Contacts & Sensors"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Filtros activos"; @@ -264,6 +267,9 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Sala"; +/* TODO: translate */ +"map.nodeKind.sensor" = "Sensor"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -281,6 +287,9 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Sala"; +/* TODO: translate */ +"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/RemoteNodes.strings b/MC1/Resources/Localization/es.lproj/RemoteNodes.strings index 2bb04362e6..4b9e9a261d 100644 --- a/MC1/Resources/Localization/es.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/es.lproj/RemoteNodes.strings @@ -32,6 +32,9 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Repetidor"; +/* TODO: translate */ +"remoteNodes.auth.typeSensor" = "Sensor"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Autenticación"; @@ -84,6 +87,36 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Ajustes del repetidor"; +/* TODO: translate */ +"remoteNodes.sensor.adminRequired" = "Sensor management requires administrator access."; + +/* TODO: translate */ +"remoteNodes.sensor.saved" = "Setting verified."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootSent" = "Reboot request sent. The sensor has not confirmed a restart. Authenticate again before sending more commands."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootConfirmation" = "Send a reboot request to this sensor?"; + +/* TODO: translate */ +"remoteNodes.sensor.runtimeOnly" = "Changes affect the running sensor. Persistence across reboot depends on its firmware."; + +/* TODO: translate */ +"remoteNodes.sensor.value" = "Value"; + +/* TODO: translate */ +"remoteNodes.sensor.save" = "Save"; + +/* TODO: translate */ +"remoteNodes.sensor.reload" = "Reload"; + +/* TODO: translate */ +"remoteNodes.sensor.empty" = "This sensor exposes no settings."; + +/* TODO: translate */ +"remoteNodes.sensor.title" = "Sensor Management"; + /* 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 b6f1c13737..d06e85343b 100644 --- a/MC1/Resources/Localization/es.lproj/Settings.strings +++ b/MC1/Resources/Localization/es.lproj/Settings.strings @@ -840,6 +840,9 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Acompañante"; +/* TODO: translate */ +"notifications.discoveryCompanionsAndSensors" = "Companions & Sensors"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Repetidor"; diff --git a/MC1/Resources/Localization/fr.lproj/Contacts.strings b/MC1/Resources/Localization/fr.lproj/Contacts.strings index 9776cc1875..36d3984629 100644 --- a/MC1/Resources/Localization/fr.lproj/Contacts.strings +++ b/MC1/Resources/Localization/fr.lproj/Contacts.strings @@ -44,6 +44,9 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Salon"; +/* TODO: translate */ +"contacts.nodeKind.sensor" = "Sensor"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Découvert"; @@ -75,6 +78,9 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Salons"; +/* TODO: translate */ +"contacts.segment.sensors" = "Sensors"; + /* 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 +174,15 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "Aucun salon"; +/* TODO: translate */ +"contacts.list.empty.sensors.title" = "No Sensors"; + /* 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."; +/* TODO: translate */ +"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" = "Aucun résultat"; @@ -623,6 +635,9 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter - Rooms */ "contacts.discovery.segment.rooms" = "Salons"; +/* TODO: translate */ +"contacts.discovery.segment.sensors" = "Sensors"; + /* 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..a7c6794540 100644 --- a/MC1/Resources/Localization/fr.lproj/Localizable.strings +++ b/MC1/Resources/Localization/fr.lproj/Localizable.strings @@ -136,6 +136,9 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "Nouvelle salle découverte"; +/* TODO: translate */ +"notifications.discovery.sensor" = "New Sensor Discovered"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -499,6 +502,18 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Réponse non valide du nœud distant"; +/* TODO: translate */ +"error.remoteNode.sensorOutcomeUnknown" = "The change could not be verified. Reload settings before saving again."; + +/* TODO: translate */ +"error.remoteNode.sensorSettingRejected" = "The sensor rejected this setting."; + +/* TODO: translate */ +"error.remoteNode.invalidSensorSetting" = "Use a nonempty key and value without whitespace. The complete command must fit within 160 UTF-8 bytes."; + +/* TODO: translate */ +"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" = "Autorisation refusée"; diff --git a/MC1/Resources/Localization/fr.lproj/Map.strings b/MC1/Resources/Localization/fr.lproj/Map.strings index c2adc70f20..58fa1d1090 100644 --- a/MC1/Resources/Localization/fr.lproj/Map.strings +++ b/MC1/Resources/Localization/fr.lproj/Map.strings @@ -40,6 +40,9 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Filtrer"; +/* TODO: translate */ +"map.controls.contactsAndSensors" = "Contacts & Sensors"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Filtres actifs"; @@ -264,6 +267,9 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Salon"; +/* TODO: translate */ +"map.nodeKind.sensor" = "Sensor"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -281,6 +287,9 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Salon"; +/* TODO: translate */ +"map.callout.nodeKind.sensor" = "Sensor"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "Ajouter"; diff --git a/MC1/Resources/Localization/fr.lproj/RemoteNodes.strings b/MC1/Resources/Localization/fr.lproj/RemoteNodes.strings index bf52ee12d1..387c2d57d8 100644 --- a/MC1/Resources/Localization/fr.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/fr.lproj/RemoteNodes.strings @@ -32,6 +32,9 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Répéteur"; +/* TODO: translate */ +"remoteNodes.auth.typeSensor" = "Sensor"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Authentification"; @@ -84,6 +87,36 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Réglages du répéteur"; +/* TODO: translate */ +"remoteNodes.sensor.adminRequired" = "Sensor management requires administrator access."; + +/* TODO: translate */ +"remoteNodes.sensor.saved" = "Setting verified."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootSent" = "Reboot request sent. The sensor has not confirmed a restart. Authenticate again before sending more commands."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootConfirmation" = "Send a reboot request to this sensor?"; + +/* TODO: translate */ +"remoteNodes.sensor.runtimeOnly" = "Changes affect the running sensor. Persistence across reboot depends on its firmware."; + +/* TODO: translate */ +"remoteNodes.sensor.value" = "Value"; + +/* TODO: translate */ +"remoteNodes.sensor.save" = "Save"; + +/* TODO: translate */ +"remoteNodes.sensor.reload" = "Reload"; + +/* TODO: translate */ +"remoteNodes.sensor.empty" = "This sensor exposes no settings."; + +/* TODO: translate */ +"remoteNodes.sensor.title" = "Sensor Management"; + /* 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 0d1aaa038e..af84832b1b 100644 --- a/MC1/Resources/Localization/fr.lproj/Settings.strings +++ b/MC1/Resources/Localization/fr.lproj/Settings.strings @@ -840,6 +840,9 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Compagnon"; +/* TODO: translate */ +"notifications.discoveryCompanionsAndSensors" = "Companions & Sensors"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Répéteur"; diff --git a/MC1/Resources/Localization/it.lproj/Contacts.strings b/MC1/Resources/Localization/it.lproj/Contacts.strings index eb4480ea76..975abbde25 100644 --- a/MC1/Resources/Localization/it.lproj/Contacts.strings +++ b/MC1/Resources/Localization/it.lproj/Contacts.strings @@ -44,6 +44,9 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Stanza"; +/* TODO: translate */ +"contacts.nodeKind.sensor" = "Sensor"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Scoperto"; @@ -75,6 +78,9 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Stanze"; +/* TODO: translate */ +"contacts.segment.sensors" = "Sensors"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "Filtra nodi"; @@ -168,9 +174,15 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "Non ci sono stanze"; +/* TODO: translate */ +"contacts.list.empty.sensors.title" = "No Sensors"; + /* 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."; +/* TODO: translate */ +"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" = "Nessun risultato"; @@ -623,6 +635,9 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter: Rooms */ "contacts.discovery.segment.rooms" = "Stanze"; +/* TODO: translate */ +"contacts.discovery.segment.sensors" = "Sensors"; + /* 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..be4441f445 100644 --- a/MC1/Resources/Localization/it.lproj/Localizable.strings +++ b/MC1/Resources/Localization/it.lproj/Localizable.strings @@ -150,6 +150,9 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "Nuova stanza scoperta"; +/* TODO: translate */ +"notifications.discovery.sensor" = "New Sensor Discovered"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -495,6 +498,18 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Risposta non valida dal nodo remoto"; +/* TODO: translate */ +"error.remoteNode.sensorOutcomeUnknown" = "The change could not be verified. Reload settings before saving again."; + +/* TODO: translate */ +"error.remoteNode.sensorSettingRejected" = "The sensor rejected this setting."; + +/* TODO: translate */ +"error.remoteNode.invalidSensorSetting" = "Use a nonempty key and value without whitespace. The complete command must fit within 160 UTF-8 bytes."; + +/* TODO: translate */ +"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" = "Permesso negato"; diff --git a/MC1/Resources/Localization/it.lproj/Map.strings b/MC1/Resources/Localization/it.lproj/Map.strings index e4acab08b2..1aa754a78d 100644 --- a/MC1/Resources/Localization/it.lproj/Map.strings +++ b/MC1/Resources/Localization/it.lproj/Map.strings @@ -37,6 +37,9 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Filtra"; +/* TODO: translate */ +"map.controls.contactsAndSensors" = "Contacts & Sensors"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Filtri attivi"; @@ -261,6 +264,9 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Stanza"; +/* TODO: translate */ +"map.nodeKind.sensor" = "Sensor"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -278,6 +284,9 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Stanza"; +/* TODO: translate */ +"map.callout.nodeKind.sensor" = "Sensor"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "Aggiungi"; diff --git a/MC1/Resources/Localization/it.lproj/RemoteNodes.strings b/MC1/Resources/Localization/it.lproj/RemoteNodes.strings index 029c601f4b..7ca16b0cda 100644 --- a/MC1/Resources/Localization/it.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/it.lproj/RemoteNodes.strings @@ -32,6 +32,9 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Ripetitore"; +/* TODO: translate */ +"remoteNodes.auth.typeSensor" = "Sensor"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Autenticazione"; @@ -84,6 +87,36 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Impostazioni ripetitore"; +/* TODO: translate */ +"remoteNodes.sensor.adminRequired" = "Sensor management requires administrator access."; + +/* TODO: translate */ +"remoteNodes.sensor.saved" = "Setting verified."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootSent" = "Reboot request sent. The sensor has not confirmed a restart. Authenticate again before sending more commands."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootConfirmation" = "Send a reboot request to this sensor?"; + +/* TODO: translate */ +"remoteNodes.sensor.runtimeOnly" = "Changes affect the running sensor. Persistence across reboot depends on its firmware."; + +/* TODO: translate */ +"remoteNodes.sensor.value" = "Value"; + +/* TODO: translate */ +"remoteNodes.sensor.save" = "Save"; + +/* TODO: translate */ +"remoteNodes.sensor.reload" = "Reload"; + +/* TODO: translate */ +"remoteNodes.sensor.empty" = "This sensor exposes no settings."; + +/* TODO: translate */ +"remoteNodes.sensor.title" = "Sensor Management"; + /* 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 a8b00bf610..21916da317 100644 --- a/MC1/Resources/Localization/it.lproj/Settings.strings +++ b/MC1/Resources/Localization/it.lproj/Settings.strings @@ -890,6 +890,9 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Companion"; +/* TODO: translate */ +"notifications.discoveryCompanionsAndSensors" = "Companions & Sensors"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Ripetitore"; diff --git a/MC1/Resources/Localization/ko.lproj/Contacts.strings b/MC1/Resources/Localization/ko.lproj/Contacts.strings index 8317fcc955..931bd6a925 100644 --- a/MC1/Resources/Localization/ko.lproj/Contacts.strings +++ b/MC1/Resources/Localization/ko.lproj/Contacts.strings @@ -44,6 +44,9 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "룸"; +/* TODO: translate */ +"contacts.nodeKind.sensor" = "Sensor"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "발견됨"; @@ -75,6 +78,9 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "룸"; +/* TODO: translate */ +"contacts.segment.sensors" = "Sensors"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "노드 필터"; @@ -168,9 +174,15 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "룸 없음"; +/* TODO: translate */ +"contacts.list.empty.sensors.title" = "No Sensors"; + /* Location: ContactsListView.swift - Purpose: No rooms empty description */ "contacts.list.empty.rooms.description" = "룸은 메시의 공개 채팅 서버입니다. 발견되면 여기에 표시됩니다."; +/* TODO: translate */ +"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" = "결과 없음"; @@ -623,6 +635,9 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter: Rooms */ "contacts.discovery.segment.rooms" = "룸"; +/* TODO: translate */ +"contacts.discovery.segment.sensors" = "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..48251d79f0 100644 --- a/MC1/Resources/Localization/ko.lproj/Localizable.strings +++ b/MC1/Resources/Localization/ko.lproj/Localizable.strings @@ -150,6 +150,9 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "새 룸 발견"; +/* TODO: translate */ +"notifications.discovery.sensor" = "New Sensor Discovered"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -495,6 +498,18 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "원격 노드의 응답이 잘못됨"; +/* TODO: translate */ +"error.remoteNode.sensorOutcomeUnknown" = "The change could not be verified. Reload settings before saving again."; + +/* TODO: translate */ +"error.remoteNode.sensorSettingRejected" = "The sensor rejected this setting."; + +/* TODO: translate */ +"error.remoteNode.invalidSensorSetting" = "Use a nonempty key and value without whitespace. The complete command must fit within 160 UTF-8 bytes."; + +/* TODO: translate */ +"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" = "권한이 거부됨"; diff --git a/MC1/Resources/Localization/ko.lproj/Map.strings b/MC1/Resources/Localization/ko.lproj/Map.strings index 2bae1a1997..6670e06c14 100644 --- a/MC1/Resources/Localization/ko.lproj/Map.strings +++ b/MC1/Resources/Localization/ko.lproj/Map.strings @@ -37,6 +37,9 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "필터"; +/* TODO: translate */ +"map.controls.contactsAndSensors" = "Contacts & Sensors"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "필터 적용됨"; @@ -261,6 +264,9 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "룸"; +/* TODO: translate */ +"map.nodeKind.sensor" = "Sensor"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -278,6 +284,9 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "룸"; +/* TODO: translate */ +"map.callout.nodeKind.sensor" = "Sensor"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "추가"; diff --git a/MC1/Resources/Localization/ko.lproj/RemoteNodes.strings b/MC1/Resources/Localization/ko.lproj/RemoteNodes.strings index 395d952034..0594b2f5fd 100644 --- a/MC1/Resources/Localization/ko.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/ko.lproj/RemoteNodes.strings @@ -32,6 +32,9 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "리피터"; +/* TODO: translate */ +"remoteNodes.auth.typeSensor" = "Sensor"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "인증"; @@ -84,6 +87,36 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "리피터 설정"; +/* TODO: translate */ +"remoteNodes.sensor.adminRequired" = "Sensor management requires administrator access."; + +/* TODO: translate */ +"remoteNodes.sensor.saved" = "Setting verified."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootSent" = "Reboot request sent. The sensor has not confirmed a restart. Authenticate again before sending more commands."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootConfirmation" = "Send a reboot request to this sensor?"; + +/* TODO: translate */ +"remoteNodes.sensor.runtimeOnly" = "Changes affect the running sensor. Persistence across reboot depends on its firmware."; + +/* TODO: translate */ +"remoteNodes.sensor.value" = "Value"; + +/* TODO: translate */ +"remoteNodes.sensor.save" = "Save"; + +/* TODO: translate */ +"remoteNodes.sensor.reload" = "Reload"; + +/* TODO: translate */ +"remoteNodes.sensor.empty" = "This sensor exposes no settings."; + +/* TODO: translate */ +"remoteNodes.sensor.title" = "Sensor Management"; + /* 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 9a3d729af8..11a2f849ae 100644 --- a/MC1/Resources/Localization/ko.lproj/Settings.strings +++ b/MC1/Resources/Localization/ko.lproj/Settings.strings @@ -880,6 +880,9 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "컴패니언"; +/* TODO: translate */ +"notifications.discoveryCompanionsAndSensors" = "Companions & Sensors"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "리피터"; diff --git a/MC1/Resources/Localization/nl.lproj/Contacts.strings b/MC1/Resources/Localization/nl.lproj/Contacts.strings index 513b8f309a..685035193b 100644 --- a/MC1/Resources/Localization/nl.lproj/Contacts.strings +++ b/MC1/Resources/Localization/nl.lproj/Contacts.strings @@ -44,6 +44,9 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Kamer"; +/* TODO: translate */ +"contacts.nodeKind.sensor" = "Sensor"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Ontdekt"; @@ -75,6 +78,9 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Kamers"; +/* TODO: translate */ +"contacts.segment.sensors" = "Sensors"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "Nodes filteren"; @@ -168,9 +174,15 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "Geen kamers"; +/* TODO: translate */ +"contacts.list.empty.sensors.title" = "No Sensors"; + /* 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."; +/* TODO: translate */ +"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" = "Geen resultaten"; @@ -623,6 +635,9 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter - Rooms */ "contacts.discovery.segment.rooms" = "Kamers"; +/* TODO: translate */ +"contacts.discovery.segment.sensors" = "Sensors"; + /* 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..ccf0ea3f27 100644 --- a/MC1/Resources/Localization/nl.lproj/Localizable.strings +++ b/MC1/Resources/Localization/nl.lproj/Localizable.strings @@ -137,6 +137,9 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "Nieuwe ruimte ontdekt"; +/* TODO: translate */ +"notifications.discovery.sensor" = "New Sensor Discovered"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -500,6 +503,18 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Ongeldig antwoord van de externe node"; +/* TODO: translate */ +"error.remoteNode.sensorOutcomeUnknown" = "The change could not be verified. Reload settings before saving again."; + +/* TODO: translate */ +"error.remoteNode.sensorSettingRejected" = "The sensor rejected this setting."; + +/* TODO: translate */ +"error.remoteNode.invalidSensorSetting" = "Use a nonempty key and value without whitespace. The complete command must fit within 160 UTF-8 bytes."; + +/* TODO: translate */ +"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" = "Toegang geweigerd"; diff --git a/MC1/Resources/Localization/nl.lproj/Map.strings b/MC1/Resources/Localization/nl.lproj/Map.strings index 2a8dd848af..2fdd064c19 100644 --- a/MC1/Resources/Localization/nl.lproj/Map.strings +++ b/MC1/Resources/Localization/nl.lproj/Map.strings @@ -40,6 +40,9 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Filter"; +/* TODO: translate */ +"map.controls.contactsAndSensors" = "Contacts & Sensors"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Filters actief"; @@ -264,6 +267,9 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Kamer"; +/* TODO: translate */ +"map.nodeKind.sensor" = "Sensor"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -281,6 +287,9 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Kamer"; +/* TODO: translate */ +"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/RemoteNodes.strings b/MC1/Resources/Localization/nl.lproj/RemoteNodes.strings index 4d5e0d9e89..5d672db9bd 100644 --- a/MC1/Resources/Localization/nl.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/nl.lproj/RemoteNodes.strings @@ -32,6 +32,9 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Repeater"; +/* TODO: translate */ +"remoteNodes.auth.typeSensor" = "Sensor"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Authenticatie"; @@ -84,6 +87,36 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Repeater-instellingen"; +/* TODO: translate */ +"remoteNodes.sensor.adminRequired" = "Sensor management requires administrator access."; + +/* TODO: translate */ +"remoteNodes.sensor.saved" = "Setting verified."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootSent" = "Reboot request sent. The sensor has not confirmed a restart. Authenticate again before sending more commands."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootConfirmation" = "Send a reboot request to this sensor?"; + +/* TODO: translate */ +"remoteNodes.sensor.runtimeOnly" = "Changes affect the running sensor. Persistence across reboot depends on its firmware."; + +/* TODO: translate */ +"remoteNodes.sensor.value" = "Value"; + +/* TODO: translate */ +"remoteNodes.sensor.save" = "Save"; + +/* TODO: translate */ +"remoteNodes.sensor.reload" = "Reload"; + +/* TODO: translate */ +"remoteNodes.sensor.empty" = "This sensor exposes no settings."; + +/* TODO: translate */ +"remoteNodes.sensor.title" = "Sensor Management"; + /* 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 0138e7d0cc..c3ef2cd025 100644 --- a/MC1/Resources/Localization/nl.lproj/Settings.strings +++ b/MC1/Resources/Localization/nl.lproj/Settings.strings @@ -840,6 +840,9 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Companion"; +/* TODO: translate */ +"notifications.discoveryCompanionsAndSensors" = "Companions & Sensors"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Repeater"; diff --git a/MC1/Resources/Localization/pl.lproj/Contacts.strings b/MC1/Resources/Localization/pl.lproj/Contacts.strings index 489850b7fc..f79eeeb1dc 100644 --- a/MC1/Resources/Localization/pl.lproj/Contacts.strings +++ b/MC1/Resources/Localization/pl.lproj/Contacts.strings @@ -44,6 +44,9 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Pokój"; +/* TODO: translate */ +"contacts.nodeKind.sensor" = "Sensor"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Odkryty"; @@ -75,6 +78,9 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Pokoje"; +/* TODO: translate */ +"contacts.segment.sensors" = "Sensors"; + /* 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 +174,15 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "Brak pokoi"; +/* TODO: translate */ +"contacts.list.empty.sensors.title" = "No Sensors"; + /* 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."; +/* TODO: translate */ +"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" = "Brak wyników"; @@ -623,6 +635,9 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter - Rooms */ "contacts.discovery.segment.rooms" = "Pokoje"; +/* TODO: translate */ +"contacts.discovery.segment.sensors" = "Sensors"; + /* 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..313c4d2324 100644 --- a/MC1/Resources/Localization/pl.lproj/Localizable.strings +++ b/MC1/Resources/Localization/pl.lproj/Localizable.strings @@ -135,6 +135,9 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "Odkryto nowy pokój"; +/* TODO: translate */ +"notifications.discovery.sensor" = "New Sensor Discovered"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -498,6 +501,18 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Nieprawidłowa odpowiedź zdalnego węzła"; +/* TODO: translate */ +"error.remoteNode.sensorOutcomeUnknown" = "The change could not be verified. Reload settings before saving again."; + +/* TODO: translate */ +"error.remoteNode.sensorSettingRejected" = "The sensor rejected this setting."; + +/* TODO: translate */ +"error.remoteNode.invalidSensorSetting" = "Use a nonempty key and value without whitespace. The complete command must fit within 160 UTF-8 bytes."; + +/* TODO: translate */ +"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" = "Odmowa dostępu"; diff --git a/MC1/Resources/Localization/pl.lproj/Map.strings b/MC1/Resources/Localization/pl.lproj/Map.strings index 2b1c0ef887..49b0727add 100644 --- a/MC1/Resources/Localization/pl.lproj/Map.strings +++ b/MC1/Resources/Localization/pl.lproj/Map.strings @@ -40,6 +40,9 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Filtr"; +/* TODO: translate */ +"map.controls.contactsAndSensors" = "Contacts & Sensors"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Filtry aktywne"; @@ -264,6 +267,9 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Pokój"; +/* TODO: translate */ +"map.nodeKind.sensor" = "Sensor"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -281,6 +287,9 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Pokój"; +/* TODO: translate */ +"map.callout.nodeKind.sensor" = "Sensor"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "Dodaj"; diff --git a/MC1/Resources/Localization/pl.lproj/RemoteNodes.strings b/MC1/Resources/Localization/pl.lproj/RemoteNodes.strings index 5aa84ff4c8..ee3d33063f 100644 --- a/MC1/Resources/Localization/pl.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/pl.lproj/RemoteNodes.strings @@ -32,6 +32,9 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Przekaźnik"; +/* TODO: translate */ +"remoteNodes.auth.typeSensor" = "Sensor"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Uwierzytelnianie"; @@ -84,6 +87,36 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Ustawienia przekaźnika"; +/* TODO: translate */ +"remoteNodes.sensor.adminRequired" = "Sensor management requires administrator access."; + +/* TODO: translate */ +"remoteNodes.sensor.saved" = "Setting verified."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootSent" = "Reboot request sent. The sensor has not confirmed a restart. Authenticate again before sending more commands."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootConfirmation" = "Send a reboot request to this sensor?"; + +/* TODO: translate */ +"remoteNodes.sensor.runtimeOnly" = "Changes affect the running sensor. Persistence across reboot depends on its firmware."; + +/* TODO: translate */ +"remoteNodes.sensor.value" = "Value"; + +/* TODO: translate */ +"remoteNodes.sensor.save" = "Save"; + +/* TODO: translate */ +"remoteNodes.sensor.reload" = "Reload"; + +/* TODO: translate */ +"remoteNodes.sensor.empty" = "This sensor exposes no settings."; + +/* TODO: translate */ +"remoteNodes.sensor.title" = "Sensor Management"; + /* 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 0d4b9b616f..6c491a8f4f 100644 --- a/MC1/Resources/Localization/pl.lproj/Settings.strings +++ b/MC1/Resources/Localization/pl.lproj/Settings.strings @@ -840,6 +840,9 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Towarzysz"; +/* TODO: translate */ +"notifications.discoveryCompanionsAndSensors" = "Companions & Sensors"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Przekaźnik"; diff --git a/MC1/Resources/Localization/pt.lproj/Contacts.strings b/MC1/Resources/Localization/pt.lproj/Contacts.strings index 0ad38afff9..0c8974c3ac 100644 --- a/MC1/Resources/Localization/pt.lproj/Contacts.strings +++ b/MC1/Resources/Localization/pt.lproj/Contacts.strings @@ -44,6 +44,9 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Sala"; +/* TODO: translate */ +"contacts.nodeKind.sensor" = "Sensor"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Descoberto"; @@ -75,6 +78,9 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Salas"; +/* TODO: translate */ +"contacts.segment.sensors" = "Sensors"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "Filtrar nós"; @@ -168,9 +174,15 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "Nenhuma sala"; +/* TODO: translate */ +"contacts.list.empty.sensors.title" = "No Sensors"; + /* 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."; +/* TODO: translate */ +"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" = "Nenhum resultado"; @@ -623,6 +635,9 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter: Rooms */ "contacts.discovery.segment.rooms" = "Salas"; +/* TODO: translate */ +"contacts.discovery.segment.sensors" = "Sensors"; + /* 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..833414320a 100644 --- a/MC1/Resources/Localization/pt.lproj/Localizable.strings +++ b/MC1/Resources/Localization/pt.lproj/Localizable.strings @@ -150,6 +150,9 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "Nova sala descoberta"; +/* TODO: translate */ +"notifications.discovery.sensor" = "New Sensor Discovered"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -495,6 +498,18 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Resposta inválida do nó remoto"; +/* TODO: translate */ +"error.remoteNode.sensorOutcomeUnknown" = "The change could not be verified. Reload settings before saving again."; + +/* TODO: translate */ +"error.remoteNode.sensorSettingRejected" = "The sensor rejected this setting."; + +/* TODO: translate */ +"error.remoteNode.invalidSensorSetting" = "Use a nonempty key and value without whitespace. The complete command must fit within 160 UTF-8 bytes."; + +/* TODO: translate */ +"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" = "Permissão recusada"; diff --git a/MC1/Resources/Localization/pt.lproj/Map.strings b/MC1/Resources/Localization/pt.lproj/Map.strings index 96ca477f68..15d6bedd8a 100644 --- a/MC1/Resources/Localization/pt.lproj/Map.strings +++ b/MC1/Resources/Localization/pt.lproj/Map.strings @@ -37,6 +37,9 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Filtrar"; +/* TODO: translate */ +"map.controls.contactsAndSensors" = "Contacts & Sensors"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Filtros ativos"; @@ -261,6 +264,9 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Sala"; +/* TODO: translate */ +"map.nodeKind.sensor" = "Sensor"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -278,6 +284,9 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Sala"; +/* TODO: translate */ +"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/RemoteNodes.strings b/MC1/Resources/Localization/pt.lproj/RemoteNodes.strings index 862457a4c7..98995bb209 100644 --- a/MC1/Resources/Localization/pt.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/pt.lproj/RemoteNodes.strings @@ -32,6 +32,9 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Repetidor"; +/* TODO: translate */ +"remoteNodes.auth.typeSensor" = "Sensor"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Autenticação"; @@ -84,6 +87,36 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Definições do repetidor"; +/* TODO: translate */ +"remoteNodes.sensor.adminRequired" = "Sensor management requires administrator access."; + +/* TODO: translate */ +"remoteNodes.sensor.saved" = "Setting verified."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootSent" = "Reboot request sent. The sensor has not confirmed a restart. Authenticate again before sending more commands."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootConfirmation" = "Send a reboot request to this sensor?"; + +/* TODO: translate */ +"remoteNodes.sensor.runtimeOnly" = "Changes affect the running sensor. Persistence across reboot depends on its firmware."; + +/* TODO: translate */ +"remoteNodes.sensor.value" = "Value"; + +/* TODO: translate */ +"remoteNodes.sensor.save" = "Save"; + +/* TODO: translate */ +"remoteNodes.sensor.reload" = "Reload"; + +/* TODO: translate */ +"remoteNodes.sensor.empty" = "This sensor exposes no settings."; + +/* TODO: translate */ +"remoteNodes.sensor.title" = "Sensor Management"; + /* 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 bd9091ee4e..306875cb7f 100644 --- a/MC1/Resources/Localization/pt.lproj/Settings.strings +++ b/MC1/Resources/Localization/pt.lproj/Settings.strings @@ -890,6 +890,9 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Contacto"; +/* TODO: translate */ +"notifications.discoveryCompanionsAndSensors" = "Companions & Sensors"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Repetidor"; diff --git a/MC1/Resources/Localization/ru.lproj/Contacts.strings b/MC1/Resources/Localization/ru.lproj/Contacts.strings index cf81edac5f..7974abe301 100644 --- a/MC1/Resources/Localization/ru.lproj/Contacts.strings +++ b/MC1/Resources/Localization/ru.lproj/Contacts.strings @@ -44,6 +44,9 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Комната"; +/* TODO: translate */ +"contacts.nodeKind.sensor" = "Sensor"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Обнаружен"; @@ -75,6 +78,9 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Комнаты"; +/* TODO: translate */ +"contacts.segment.sensors" = "Sensors"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "Фильтр узлов"; @@ -168,9 +174,15 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "Нет комнат"; +/* TODO: translate */ +"contacts.list.empty.sensors.title" = "No Sensors"; + /* Location: ContactsListView.swift - Purpose: No rooms empty description */ "contacts.list.empty.rooms.description" = "Комнаты — это публичные чат-серверы в сети mesh. Они появятся здесь после обнаружения."; +/* TODO: translate */ +"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" = "Нет результатов"; @@ -623,6 +635,9 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter - Rooms */ "contacts.discovery.segment.rooms" = "Комнаты"; +/* TODO: translate */ +"contacts.discovery.segment.sensors" = "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..4578ca84e1 100644 --- a/MC1/Resources/Localization/ru.lproj/Localizable.strings +++ b/MC1/Resources/Localization/ru.lproj/Localizable.strings @@ -134,6 +134,9 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "Обнаружена новая комната"; +/* TODO: translate */ +"notifications.discovery.sensor" = "New Sensor Discovered"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -497,6 +500,18 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Недопустимый ответ удалённого узла"; +/* TODO: translate */ +"error.remoteNode.sensorOutcomeUnknown" = "The change could not be verified. Reload settings before saving again."; + +/* TODO: translate */ +"error.remoteNode.sensorSettingRejected" = "The sensor rejected this setting."; + +/* TODO: translate */ +"error.remoteNode.invalidSensorSetting" = "Use a nonempty key and value without whitespace. The complete command must fit within 160 UTF-8 bytes."; + +/* TODO: translate */ +"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" = "Доступ запрещён"; diff --git a/MC1/Resources/Localization/ru.lproj/Map.strings b/MC1/Resources/Localization/ru.lproj/Map.strings index 5b0032d6b6..14f0e43cf3 100644 --- a/MC1/Resources/Localization/ru.lproj/Map.strings +++ b/MC1/Resources/Localization/ru.lproj/Map.strings @@ -40,6 +40,9 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Фильтр"; +/* TODO: translate */ +"map.controls.contactsAndSensors" = "Contacts & Sensors"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Фильтры активны"; @@ -264,6 +267,9 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Комната"; +/* TODO: translate */ +"map.nodeKind.sensor" = "Sensor"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -281,6 +287,9 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Комната"; +/* TODO: translate */ +"map.callout.nodeKind.sensor" = "Sensor"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "Добавить"; diff --git a/MC1/Resources/Localization/ru.lproj/RemoteNodes.strings b/MC1/Resources/Localization/ru.lproj/RemoteNodes.strings index 713049b1d4..98879fef4c 100644 --- a/MC1/Resources/Localization/ru.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/ru.lproj/RemoteNodes.strings @@ -32,6 +32,9 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Ретранслятор"; +/* TODO: translate */ +"remoteNodes.auth.typeSensor" = "Sensor"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Аутентификация"; @@ -84,6 +87,36 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Настройки ретранслятора"; +/* TODO: translate */ +"remoteNodes.sensor.adminRequired" = "Sensor management requires administrator access."; + +/* TODO: translate */ +"remoteNodes.sensor.saved" = "Setting verified."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootSent" = "Reboot request sent. The sensor has not confirmed a restart. Authenticate again before sending more commands."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootConfirmation" = "Send a reboot request to this sensor?"; + +/* TODO: translate */ +"remoteNodes.sensor.runtimeOnly" = "Changes affect the running sensor. Persistence across reboot depends on its firmware."; + +/* TODO: translate */ +"remoteNodes.sensor.value" = "Value"; + +/* TODO: translate */ +"remoteNodes.sensor.save" = "Save"; + +/* TODO: translate */ +"remoteNodes.sensor.reload" = "Reload"; + +/* TODO: translate */ +"remoteNodes.sensor.empty" = "This sensor exposes no settings."; + +/* TODO: translate */ +"remoteNodes.sensor.title" = "Sensor Management"; + /* 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 a766d7b3f1..863a9cc6d5 100644 --- a/MC1/Resources/Localization/ru.lproj/Settings.strings +++ b/MC1/Resources/Localization/ru.lproj/Settings.strings @@ -840,6 +840,9 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Компаньон"; +/* TODO: translate */ +"notifications.discoveryCompanionsAndSensors" = "Companions & Sensors"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Ретранслятор"; diff --git a/MC1/Resources/Localization/uk.lproj/Contacts.strings b/MC1/Resources/Localization/uk.lproj/Contacts.strings index aaa2ae75a6..ab0b944f99 100644 --- a/MC1/Resources/Localization/uk.lproj/Contacts.strings +++ b/MC1/Resources/Localization/uk.lproj/Contacts.strings @@ -44,6 +44,9 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "Кімната"; +/* TODO: translate */ +"contacts.nodeKind.sensor" = "Sensor"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "Виявлений"; @@ -75,6 +78,9 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "Кімнати"; +/* TODO: translate */ +"contacts.segment.sensors" = "Sensors"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "Фільтр вузлів"; @@ -168,9 +174,15 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "Немає кімнат"; +/* TODO: translate */ +"contacts.list.empty.sensors.title" = "No Sensors"; + /* Location: ContactsListView.swift - Purpose: No rooms empty description */ "contacts.list.empty.rooms.description" = "Кімнати — це публічні чат-сервери в mesh-мережі. Вони з'являться тут після виявлення."; +/* TODO: translate */ +"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" = "Немає результатів"; @@ -623,6 +635,9 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter - Rooms */ "contacts.discovery.segment.rooms" = "Кімнати"; +/* TODO: translate */ +"contacts.discovery.segment.sensors" = "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..c285faa8d9 100644 --- a/MC1/Resources/Localization/uk.lproj/Localizable.strings +++ b/MC1/Resources/Localization/uk.lproj/Localizable.strings @@ -137,6 +137,9 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "Виявлено нову кімнату"; +/* TODO: translate */ +"notifications.discovery.sensor" = "New Sensor Discovered"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -500,6 +503,18 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "Неприпустима відповідь віддаленого вузла"; +/* TODO: translate */ +"error.remoteNode.sensorOutcomeUnknown" = "The change could not be verified. Reload settings before saving again."; + +/* TODO: translate */ +"error.remoteNode.sensorSettingRejected" = "The sensor rejected this setting."; + +/* TODO: translate */ +"error.remoteNode.invalidSensorSetting" = "Use a nonempty key and value without whitespace. The complete command must fit within 160 UTF-8 bytes."; + +/* TODO: translate */ +"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" = "Доступ заборонено"; diff --git a/MC1/Resources/Localization/uk.lproj/Map.strings b/MC1/Resources/Localization/uk.lproj/Map.strings index 6bae83870b..c0d2aded5f 100644 --- a/MC1/Resources/Localization/uk.lproj/Map.strings +++ b/MC1/Resources/Localization/uk.lproj/Map.strings @@ -40,6 +40,9 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "Фільтр"; +/* TODO: translate */ +"map.controls.contactsAndSensors" = "Contacts & Sensors"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "Фільтри активні"; @@ -264,6 +267,9 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "Кімната"; +/* TODO: translate */ +"map.nodeKind.sensor" = "Sensor"; + // MARK: - Contact Callout /* Location: ContactCalloutContent.swift - Purpose: Button to view contact details */ @@ -281,6 +287,9 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "Кімната"; +/* TODO: translate */ +"map.callout.nodeKind.sensor" = "Sensor"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "Додати"; diff --git a/MC1/Resources/Localization/uk.lproj/RemoteNodes.strings b/MC1/Resources/Localization/uk.lproj/RemoteNodes.strings index be7d1658e4..f55b4fbbd2 100644 --- a/MC1/Resources/Localization/uk.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/uk.lproj/RemoteNodes.strings @@ -32,6 +32,9 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "Ретранслятор"; +/* TODO: translate */ +"remoteNodes.auth.typeSensor" = "Sensor"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "Автентифікація"; @@ -84,6 +87,36 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "Налаштування ретранслятора"; +/* TODO: translate */ +"remoteNodes.sensor.adminRequired" = "Sensor management requires administrator access."; + +/* TODO: translate */ +"remoteNodes.sensor.saved" = "Setting verified."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootSent" = "Reboot request sent. The sensor has not confirmed a restart. Authenticate again before sending more commands."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootConfirmation" = "Send a reboot request to this sensor?"; + +/* TODO: translate */ +"remoteNodes.sensor.runtimeOnly" = "Changes affect the running sensor. Persistence across reboot depends on its firmware."; + +/* TODO: translate */ +"remoteNodes.sensor.value" = "Value"; + +/* TODO: translate */ +"remoteNodes.sensor.save" = "Save"; + +/* TODO: translate */ +"remoteNodes.sensor.reload" = "Reload"; + +/* TODO: translate */ +"remoteNodes.sensor.empty" = "This sensor exposes no settings."; + +/* TODO: translate */ +"remoteNodes.sensor.title" = "Sensor Management"; + /* 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 3ac2334f85..805a11a751 100644 --- a/MC1/Resources/Localization/uk.lproj/Settings.strings +++ b/MC1/Resources/Localization/uk.lproj/Settings.strings @@ -840,6 +840,9 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "Компаньйон"; +/* TODO: translate */ +"notifications.discoveryCompanionsAndSensors" = "Companions & Sensors"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "Ретранслятор"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Contacts.strings b/MC1/Resources/Localization/zh-Hans.lproj/Contacts.strings index e215b4d858..2aa0a760fe 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Contacts.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Contacts.strings @@ -44,6 +44,9 @@ /* Location: Multiple files - Purpose: Room contact type label */ "contacts.nodeKind.room" = "房间"; +/* TODO: translate */ +"contacts.nodeKind.sensor" = "Sensor"; + /* Location: TracePathListView.swift, PathEditingSheet.swift - Purpose: Badge label for discovered nodes */ "contacts.nodeKind.discovered" = "已发现"; @@ -75,6 +78,9 @@ /* Location: ContactsViewModel.swift - Purpose: Rooms segment */ "contacts.segment.rooms" = "房间"; +/* TODO: translate */ +"contacts.segment.sensors" = "Sensors"; + /* Location: NodeSegmentPicker.swift - Purpose: VoiceOver label for the Nodes tab segment filter picker (iOS 18 fallback) */ "contacts.segment.pickerLabel" = "筛选节点"; @@ -168,9 +174,15 @@ /* Location: ContactsListView.swift - Purpose: No rooms empty title */ "contacts.list.empty.rooms.title" = "无房间"; +/* TODO: translate */ +"contacts.list.empty.sensors.title" = "No Sensors"; + /* Location: ContactsListView.swift - Purpose: No rooms empty description */ "contacts.list.empty.rooms.description" = "房间是 Mesh 网络上的公共聊天服务器。发现后会显示在这里。"; +/* TODO: translate */ +"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" = "无结果"; @@ -623,6 +635,9 @@ /* Location: DiscoveryView.swift - Purpose: Segment filter: Rooms */ "contacts.discovery.segment.rooms" = "房间"; +/* TODO: translate */ +"contacts.discovery.segment.sensors" = "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..6b13a5b8bc 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Localizable.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Localizable.strings @@ -151,6 +151,9 @@ /* Notification title when a new room is discovered on the mesh network */ "notifications.discovery.room" = "发现新房间"; +/* TODO: translate */ +"notifications.discovery.sensor" = "New Sensor Discovered"; + // MARK: - Notification Actions /* Notification action button to reply to a message */ @@ -496,6 +499,18 @@ /* Location: RemoteNodeError+UserFacingMessage.swift - Malformed response from the remote node */ "error.remoteNode.invalidResponse" = "远程节点响应无效"; +/* TODO: translate */ +"error.remoteNode.sensorOutcomeUnknown" = "The change could not be verified. Reload settings before saving again."; + +/* TODO: translate */ +"error.remoteNode.sensorSettingRejected" = "The sensor rejected this setting."; + +/* TODO: translate */ +"error.remoteNode.invalidSensorSetting" = "Use a nonempty key and value without whitespace. The complete command must fit within 160 UTF-8 bytes."; + +/* TODO: translate */ +"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" = "权限被拒绝"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Map.strings b/MC1/Resources/Localization/zh-Hans.lproj/Map.strings index f1fc58917e..fbd0271512 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Map.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Map.strings @@ -39,6 +39,9 @@ /* Location: MapControlsToolbar.swift - Purpose: Accessibility label for map filter control */ "map.controls.filter" = "筛选"; +/* TODO: translate */ +"map.controls.contactsAndSensors" = "Contacts & Sensors"; + /* Location: MapControlsToolbar.swift - Purpose: Accessibility value when filter differs from host defaults */ "map.controls.filterActive" = "已启用筛选"; @@ -263,6 +266,9 @@ /* Location: MapView.swift ContactDetailSheet - Purpose: Display name for room type */ "map.nodeKind.room" = "房间"; +/* TODO: translate */ +"map.nodeKind.sensor" = "Sensor"; + // MARK: - Contact Callout /* Location: MapView.swift ContactDetailSheet - Purpose: Button to view contact details */ @@ -280,6 +286,9 @@ /* Location: ContactCalloutContent.swift - Purpose: Display name for room in callout */ "map.callout.nodeKind.room" = "房间"; +/* TODO: translate */ +"map.callout.nodeKind.sensor" = "Sensor"; + /* Location: DiscoveredNodeCalloutContent.swift - Purpose: Add discovered node from callout */ "map.callout.add" = "添加"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/RemoteNodes.strings b/MC1/Resources/Localization/zh-Hans.lproj/RemoteNodes.strings index 74f6a0a7a9..06661b4709 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/RemoteNodes.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/RemoteNodes.strings @@ -32,6 +32,9 @@ /* Location: NodeAuthenticationSheet.swift - Repeater type value */ "remoteNodes.auth.typeRepeater" = "转发节点"; +/* TODO: translate */ +"remoteNodes.auth.typeSensor" = "Sensor"; + /* Location: NodeAuthenticationSheet.swift - Authentication section header */ "remoteNodes.auth.authentication" = "身份验证"; @@ -84,6 +87,36 @@ /* Location: RepeaterSettingsView.swift - Navigation title */ "remoteNodes.settings.title" = "转发节点设置"; +/* TODO: translate */ +"remoteNodes.sensor.adminRequired" = "Sensor management requires administrator access."; + +/* TODO: translate */ +"remoteNodes.sensor.saved" = "Setting verified."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootSent" = "Reboot request sent. The sensor has not confirmed a restart. Authenticate again before sending more commands."; + +/* TODO: translate */ +"remoteNodes.sensor.rebootConfirmation" = "Send a reboot request to this sensor?"; + +/* TODO: translate */ +"remoteNodes.sensor.runtimeOnly" = "Changes affect the running sensor. Persistence across reboot depends on its firmware."; + +/* TODO: translate */ +"remoteNodes.sensor.value" = "Value"; + +/* TODO: translate */ +"remoteNodes.sensor.save" = "Save"; + +/* TODO: translate */ +"remoteNodes.sensor.reload" = "Reload"; + +/* TODO: translate */ +"remoteNodes.sensor.empty" = "This sensor exposes no settings."; + +/* TODO: translate */ +"remoteNodes.sensor.title" = "Sensor Management"; + /* 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 203579954b..fd3ccd0b3c 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings @@ -875,6 +875,9 @@ /* Toggle label for companion discovery notifications */ "notifications.discoveryContact" = "伴侣节点"; +/* TODO: translate */ +"notifications.discoveryCompanionsAndSensors" = "Companions & Sensors"; + /* Toggle label for repeater discovery notifications */ "notifications.discoveryRepeater" = "中继器"; 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/State/AppState.swift b/MC1/State/AppState.swift index 026e7ab57f..213a23a3e1 100644 --- a/MC1/State/AppState.swift +++ b/MC1/State/AppState.swift @@ -758,28 +758,35 @@ final class AppState { lastWiredDevice = (snapshot.device.id, snapshot.device.radioID) tracePathViewModel?.reattachIfWaiting() nodeDiscoveryViewModel?.reattachIfWaiting() + let radioID = snapshot.device.radioID await remoteAdminWorkspaces.rebind( - radioID: snapshot.device.radioID, + radioID: radioID, repeaterAdminService: { [weak self] in guard let self, context.isCurrent(self.connectionManager) else { return nil } - return self.connectionSnapshot(for: snapshot.device.radioID)?.services.repeaterAdminService + 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: snapshot.device.radioID)?.services.roomAdminService + 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: snapshot.device.radioID)?.services.contactService + 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: snapshot.device.radioID)?.services.nodeSnapshotService + 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: snapshot.device.radioID)?.device.hashSize + 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) diff --git a/MC1/State/RemoteAdminWorkspaces.swift b/MC1/State/RemoteAdminWorkspaces.swift index fb65c850f7..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,6 +100,11 @@ 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() } @@ -79,9 +117,16 @@ final class RemoteAdminWorkspaces { contactService: @escaping @MainActor () -> ContactService?, nodeSnapshotService: @escaping @MainActor () -> NodeSnapshotService?, deviceHashSize: @escaping @MainActor () -> Int?, + remoteNodeService: @escaping @MainActor () -> RemoteNodeService?, + dataStore: @escaping @MainActor () -> PersistenceStore?, + connectionState: @escaping @MainActor () -> DeviceConnectionState, isCurrent: @MainActor () -> Bool ) async { 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, 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/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/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/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..63de0936d2 100644 --- a/MC1/Views/Contacts/ContactDetailAvatarView.swift +++ b/MC1/Views/Contacts/ContactDetailAvatarView.swift @@ -2,6 +2,7 @@ import MC1Services import SwiftUI struct ContactDetailAvatarView: View { + private static let avatarSize: CGFloat = 150 let contact: ContactDTO let isSavingAvatar: Bool @Binding var showSourceMenu: Bool @@ -12,11 +13,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) } @@ -29,9 +30,11 @@ struct ContactDetailAvatarView: View { } 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 +59,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/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/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/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/DiscoveryView.swift b/MC1/Views/Contacts/DiscoveryView.swift index a900e80a09..c78fb844a1 100644 --- a/MC1/Views/Contacts/DiscoveryView.swift +++ b/MC1/Views/Contacts/DiscoveryView.swift @@ -194,6 +194,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 +290,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 +305,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 } } 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/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/RemoteNodes/NodeAuthenticationSheet.swift b/MC1/Views/RemoteNodes/NodeAuthenticationSheet.swift index c4a867ae9f..db4aa4708f 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,7 +72,7 @@ struct NodeAuthenticationSheet: View { .toolbar { ToolbarItem(placement: .cancellationAction) { Button(L10n.RemoteNodes.RemoteNodes.Auth.cancel) { - authenticationTask?.cancel() + cancelAuthentication() dismiss() } } @@ -76,7 +81,7 @@ struct NodeAuthenticationSheet: View { 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) else { return } + guard accepts(context), password.isEmpty, !isAuthenticating else { return } password = saved hasSavedPassword = true } @@ -95,17 +100,10 @@ struct NodeAuthenticationSheet: View { } .sensoryFeedback(.error, trigger: errorMessage) .onChange(of: appState.connectionManager.currentConnection?.generation) { _, _ in - authenticationTask?.cancel() - authenticationTask = nil - isAuthenticating = false - isRetryingViaFlood = false + cancelAuthentication() didResetPath = false - cleanupCountdownState() - } - .onDisappear { - authenticationTask?.cancel() - cleanupCountdownState() } + .onDisappear { cancelAuthentication() } } } @@ -125,8 +123,7 @@ struct NodeAuthenticationSheet: View { errorMessage: $errorMessage, authSecondsRemaining: $authSecondsRemaining, isRetryingViaFlood: isRetryingViaFlood, - role: role, - maxPasswordLength: maxPasswordLength + maxPasswordBytes: maxPasswordBytes ) } @@ -148,35 +145,45 @@ struct NodeAuthenticationSheet: View { // MARK: - Authentication + private func cancelAuthentication() { + authEpoch.bump() + authenticationTask?.cancel() + authenticationTask = nil + isAuthenticating = false + isRetryingViaFlood = false + cleanupCountdownState() + } + private func authenticate() { + 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) - // Clear any previous error + let submittedPassword = password + let submittedRememberPassword = rememberPassword + cancelAuthentication() + let ticket = authEpoch.ticket() errorMessage = nil isAuthenticating = true - isRetryingViaFlood = false - authenticationTask?.cancel() - cleanupCountdownState() authenticationTask = Task { do { - guard accepts(context) else { return } + 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: contact.radioID, publicKey: contact.publicKey ) - guard accepts(context) else { return } + guard accepts(context, ticket: ticket) else { return } didResetPath = true pathLength = PacketBuilder.floodPathSentinel } else if useFloodRouting || didResetPath { @@ -185,45 +192,40 @@ 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, context: context, - password: passwordToUse, + 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 { - guard accepts(context) else { return } - isRetryingViaFlood = true - cleanupCountdownState() - } - guard accepts(context) else { return } + guard accepts(context, ticket: ticket) else { return } + // The stored route produced no reply. Clear it and let the network find a path. + isRetryingViaFlood = true + cleanupCountdownState() try await services.contactService.resetPath( radioID: contact.radioID, publicKey: contact.publicKey ) - guard accepts(context) else { return } + guard accepts(context, ticket: ticket) else { return } didResetPath = true session = try await performLogin( services: services, context: context, - password: passwordToUse, + password: submittedPassword, + rememberPassword: submittedRememberPassword, + ticket: ticket, pathLength: PacketBuilder.floodPathSentinel ) } - guard accepts(context) else { return } + 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 { @@ -231,39 +233,26 @@ struct NodeAuthenticationSheet: View { } } - await MainActor.run { - guard accepts(context) else { return } - 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 { - guard accepts(context) else { return } - authenticationTask = nil - isRetryingViaFlood = false - cleanupCountdownState() - isAuthenticating = false - } + guard accepts(context, ticket: ticket) else { return } + cancelAuthentication() } catch RemoteNodeError.timeout { - await MainActor.run { - guard accepts(context) else { return } - 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 { - guard accepts(context) else { return } - 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 } } } @@ -273,21 +262,24 @@ struct NodeAuthenticationSheet: View { services: ServiceContainer, 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) else { return } + guard accepts(context, ticket: ticket) else { return } authTimeoutSeconds = seconds authStartTime = Date.now authSecondsRemaining = seconds - startCountdownTask(context: context) + startCountdownTask(context: context, ticket: ticket) } } - let result: RemoteNodeSessionDTO = if role == .roomServer { - try await services.roomServerService.joinRoom( + guard accepts(context, ticket: ticket) else { throw CancellationError() } + switch role { + case .roomServer: + return try await services.roomServerService.joinRoom( radioID: contact.radioID, contact: contact, password: password, @@ -295,8 +287,14 @@ struct NodeAuthenticationSheet: View { pathLength: pathLength, onTimeoutKnown: onTimeoutKnown ) - } else { - try await services.repeaterAdminService.connectAsAdmin( + 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: contact.radioID, contact: contact, password: password, @@ -305,20 +303,19 @@ struct NodeAuthenticationSheet: View { onTimeoutKnown: onTimeoutKnown ) } - guard accepts(context) else { throw CancellationError() } - return result } - private func accepts(_ context: ConnectionCallbackContext) -> Bool { + 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(context: ConnectionCallbackContext) { + private func startCountdownTask(context: ConnectionCallbackContext, ticket: Epoch.Ticket) { countdownTask = Task { while !Task.isCancelled, let timeout = authTimeoutSeconds, let startTime = authStartTime { do { @@ -326,7 +323,7 @@ struct NodeAuthenticationSheet: View { } catch { break } - guard accepts(context) else { return } + guard accepts(context, ticket: ticket) else { return } let elapsed = Date.now.timeIntervalSince(startTime) let remaining = max(0, timeout - Int(elapsed)) @@ -350,6 +347,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 @@ -357,7 +362,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) } @@ -379,8 +384,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 { @@ -396,8 +400,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) 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/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/Sensors/SensorSettingsContent.swift b/MC1/Views/RemoteNodes/Sensors/SensorSettingsContent.swift new file mode 100644 index 0000000000..d08bcdc403 --- /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) + .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) {} + } + } + + 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) + } + } + .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/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/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/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/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/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/RemoteNodeSession.swift b/MC1Services/Sources/MC1Services/Models/RemoteNodeSession.swift index 507f8ff8cf..ec92b861b2 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]) @@ -215,6 +215,10 @@ public extension RemoteNodeSession { role == .repeater } + var isSensor: Bool { + role == .sensor + } + /// 6-byte public key prefix for addressing var publicKeyPrefix: Data { publicKey.prefix(6) @@ -453,6 +457,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/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/ServiceContainer.swift b/MC1Services/Sources/MC1Services/ServiceContainer.swift index 7c1335e001..3dfd06fcab 100644 --- a/MC1Services/Sources/MC1Services/ServiceContainer.swift +++ b/MC1Services/Sources/MC1Services/ServiceContainer.swift @@ -419,10 +419,11 @@ public final class ServiceContainer { } private func performTearDown() async { + await remoteNodeService.beginRetirement() await messageService.retireInlineSends() await messageService.waitForAcknowledgementSaves() await stopEventMonitoring() - await remoteNodeService.retireKeepAlives() + await remoteNodeService.retire() // Break the retain cycles the wired handlers form. The message // closures and the discovery event task capture this container's @@ -459,7 +460,7 @@ public final class ServiceContainer { func prepareForIdentityImport() async { isTornDown = true await messageService.retireInlineSends() - await remoteNodeService.retireKeepAlives() + await remoteNodeService.retire() await chatSendQueueService.shutdown() await stopEventMonitoring() await syncCoordinator.cancelDiscoveryEventMonitoring() diff --git a/MC1Services/Sources/MC1Services/Services/AdvertisementService+DeltaSync.swift b/MC1Services/Sources/MC1Services/Services/AdvertisementService+DeltaSync.swift index 2e69735b5d..44696693ca 100644 --- a/MC1Services/Sources/MC1Services/Services/AdvertisementService+DeltaSync.swift +++ b/MC1Services/Sources/MC1Services/Services/AdvertisementService+DeltaSync.swift @@ -310,6 +310,7 @@ extension AdvertisementService { let frame = ContactFrame( publicKey: contact.publicKey, type: contact.type, + typeRawValue: contact.typeRawValue, flags: contact.flags, outPathLength: contact.outPathLength, outPath: contact.outPath, 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/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/MessageService+SendDM.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift index e1a06bffcc..360c9b868c 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift @@ -690,7 +690,7 @@ extension MessageService { } private func validateDirectMessage(text: String, to contact: ContactDTO) throws { - guard contact.type != .repeater else { throw MessageServiceError.invalidRecipient } + guard contact.type != .repeater, contact.type != .sensor else { throw MessageServiceError.invalidRecipient } guard text.utf8.count <= ProtocolLimits.maxDirectMessageLength else { throw MessageServiceError.messageTooLong } } diff --git a/MC1Services/Sources/MC1Services/Services/NotificationService.swift b/MC1Services/Sources/MC1Services/Services/NotificationService.swift index 27b05f776c..cb42c02905 100644 --- a/MC1Services/Sources/MC1Services/Services/NotificationService.swift +++ b/MC1Services/Sources/MC1Services/Services/NotificationService.swift @@ -487,7 +487,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 +527,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" } } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift index aa08c0ce32..626ed5700b 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift @@ -250,7 +250,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 @@ -264,7 +264,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/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/RemoteNodeService+CLI.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+CLI.swift index 44442c54d7..90987d20b0 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+CLI.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+CLI.swift @@ -69,13 +69,16 @@ 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)) @@ -85,6 +88,28 @@ extension RemoteNodeService { defer { releaseCLISlot(for: destinationPrefix) } try Task.checkCancellation() + if remoteSession.isSensor { + _ = try await requireSensorAdmin(sessionID: sessionID) + 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, + requestID: requestID, textType: .cliData + ) + } + // A no-reply command is sent once. Path reset and resend would repeat it. if RemoteCLINoReplyCommand(command) != nil { return try await performCLIExchange( diff --git a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift index 486c423bc7..b399fc3733 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift @@ -5,7 +5,7 @@ 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 +17,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,18 +33,19 @@ public extension RemoteNodeService { throw RemoteNodeError.passwordNotFound } + 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(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) + cancelPendingLogin(for: prefix) + let attemptID = UUID() + loginAttemptIDs[prefix] = attemptID + defer { + if loginAttemptIDs[prefix] == attemptID { loginAttemptIDs[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 @@ -50,7 +53,11 @@ public extension RemoteNodeService { 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) + guard !Task.isCancelled, loginAttemptIDs[prefix] == attemptID, !isRetired else { + continuation.resume(throwing: RemoteNodeError.cancelled) + return + } + pendingLogins[prefix] = PendingLogin(id: attemptID, sessionID: sessionID, continuation: continuation) let timeoutTask = Task { [self] in let sentInfo: MessageSentInfo @@ -64,7 +71,7 @@ public extension RemoteNodeService { // 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 } + guard !Task.isCancelled, loginAttemptIDs[prefix] == attemptID, !isRetired else { return } pendingLoginTimeoutTasks.removeValue(forKey: prefix) if let pending = pendingLogins.removeValue(forKey: prefix) { let rnError = (error as? RemoteNodeError) @@ -74,6 +81,7 @@ public extension RemoteNodeService { return } + guard !Task.isCancelled, loginAttemptIDs[prefix] == attemptID, !isRetired else { return } let timeout = RemoteOperationTimeoutPolicy.loginTimeout(for: sentInfo, pathLength: pathLength) logger.info("login: send succeeded, starting \(timeout) timeout for prefix \(prefixHex)") @@ -95,7 +103,7 @@ public extension RemoteNodeService { guard remaining > .zero else { break } let sleepFor = remaining < retransmitInterval ? remaining : retransmitInterval try? await Task.sleep(for: sleepFor) - guard !Task.isCancelled else { return } + guard !Task.isCancelled, loginAttemptIDs[prefix] == attemptID, !isRetired else { return } guard pendingLogins[prefix] != nil else { logger.info("login: continuation consumed for prefix \(prefixHex); stopping retransmits") return @@ -114,7 +122,7 @@ public extension RemoteNodeService { } } - guard !Task.isCancelled else { return } + guard !Task.isCancelled, loginAttemptIDs[prefix] == attemptID, !isRetired else { return } if let pending = pendingLogins.removeValue(forKey: prefix) { logger.warning("Login timeout after \(timeout) for session \(sessionID), prefix \(prefixHex)") pendingLoginTimeoutTasks.removeValue(forKey: prefix) @@ -127,7 +135,7 @@ public extension RemoteNodeService { } } onCancel: { [weak self] in Task { [weak self] in - await self?.cancelPendingLogin(for: prefix) + await self?.cancelPendingLogin(for: prefix, attemptID: attemptID) } } } @@ -201,56 +209,34 @@ public extension RemoteNodeService { 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 loginAttemptIDs[prefix] == pending.id, !isRetired else { throw RemoteNodeError.cancelled } + guard let remoteSession = try await dataStore.fetchRemoteNodeSession(id: pending.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 loginAttemptIDs[prefix] == pending.id, !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") + } + await auditLogger.logLoginSuccess(target: target, publicKey: prefix, isAdmin: result.isAdmin) + guard loginAttemptIDs[prefix] == pending.id, !isRetired else { throw RemoteNodeError.cancelled } + try await dataStore.updateRemoteNodeSessionConnection( + id: remoteSession.id, + isConnected: true, + permissionLevel: result.permissionLevel(for: remoteSession.role) + ) + guard loginAttemptIDs[prefix] == pending.id, !isRetired else { + // A cancelled store turn may already have committed; retire it unless a new login owns the row. + if loginAttemptIDs[prefix] == nil { try? await dataStore.markSessionDisconnected(remoteSession.id) } + throw RemoteNodeError.cancelled } - continuation.resume(throwing: RemoteNodeError.loginFailed("authentication failed")) + eventBroadcaster.yield(.sessionStateChanged(sessionID: remoteSession.id, isConnected: true)) + if remoteSession.isRoom { keepAliveIntervals[remoteSession.id] = Self.defaultKeepAliveInterval } + continuation.resume(returning: result) + } catch { + continuation.resume(throwing: error) } } @@ -261,7 +247,7 @@ public extension RemoteNodeService { /// 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 !keepAliveAdmissionRetired else { return } + guard !isRetired else { return } stopKeepAlive(sessionID: sessionID) let interval = keepAliveIntervals[sessionID] ?? Self.defaultKeepAliveInterval @@ -337,6 +323,8 @@ public extension RemoteNodeService { throw RemoteNodeError.sessionNotFound } + guard !remoteSession.isSensor else { throw RemoteNodeError.invalidResponse } + // Check contact's routing status guard let contact = try await dataStore.fetchContact(radioID: remoteSession.radioID, publicKey: publicKey) else { throw RemoteNodeError.contactNotFound @@ -348,7 +336,7 @@ public extension RemoteNodeService { } // Log keep-alive - let targetType: CommandAuditLogger.Target = remoteSession.isRoom ? .room : .repeater + let targetType: CommandAuditLogger.Target = CommandAuditLogger.target(for: remoteSession.role) await auditLogger.logKeepAlive(target: targetType, publicKey: publicKey) // Send keep-alive with sync_since for force-resync hint @@ -400,7 +388,7 @@ public extension RemoteNodeService { // Request status (which triggers sync) do { - let contactType: ContactType = remoteSession.isRoom ? .room : .repeater + let contactType: ContactType = .room _ = try await session.requestStatus(from: remoteSession.publicKey, type: contactType) } catch let error as MeshCoreError { throw RemoteNodeError.sessionError(error) @@ -417,8 +405,13 @@ public extension RemoteNodeService { throw RemoteNodeError.sessionNotFound } + if remoteSession.isSensor { + await disconnect(sessionID: sessionID) + return + } + // Log logout - let targetType: CommandAuditLogger.Target = remoteSession.isRoom ? .room : .repeater + let targetType: CommandAuditLogger.Target = CommandAuditLogger.target(for: remoteSession.role) await auditLogger.logLogout(target: targetType, publicKey: remoteSession.publicKey) stopKeepAlive(sessionID: sessionID) diff --git a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Reconnection.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Reconnection.swift index 399b68ab65..f09e8acb2b 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Reconnection.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Reconnection.swift @@ -3,9 +3,11 @@ import Foundation public extension RemoteNodeService { // MARK: - Link Disconnection - /// Stops keep-alives and publishes disconnected sessions, returning their IDs + /// 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.fetchRemoteNodeSessions(radioID: radioID).filter(\.isConnected) @@ -43,7 +45,9 @@ public extension RemoteNodeService { 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] = [] @@ -58,35 +62,23 @@ public extension RemoteNodeService { guard !sessionsToReauth.isEmpty else { return } logger.info("Link reconnection: re-authenticating \(sessionsToReauth.count) session(s)") - isReauthenticating = true - defer { isReauthenticating = false } - - await withTaskGroup(of: Void.self) { group in - for remoteSession in sessionsToReauth { - guard !Task.isCancelled else { break } - 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)) - } + 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+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+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 46bdc95450..9efdc17bf0 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 @@ -23,7 +23,12 @@ public actor RemoteNodeService { let logger = PersistentLogger(subsystem: "com.mc1", category: "RemoteNode") let auditLogger = CommandAuditLogger() + var isRetired = false + var loginAttemptIDs: [Data: UUID] = [:] + var sensorConnectAttempts: [UUID: UUID] = [:] + struct PendingLogin { + let id: UUID /// Session that called `login`, so a prefix match cannot update another radio's row. let sessionID: UUID let continuation: CheckedContinuation @@ -75,15 +80,14 @@ public actor RemoteNodeService { /// Keep-alive timer tasks var keepAliveTasks: [UUID: Task] = [:] var retiredKeepAliveTasks: [Task] = [] - var keepAliveAdmissionRetired = false - private var keepAliveRetirement: Task? + private var retirementTask: Task? /// 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 @@ -150,6 +154,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 @@ -267,7 +272,9 @@ public actor RemoteNodeService { return TimeInterval(seconds) + TimeInterval(attoseconds) / 1e18 } - func cancelPendingLogin(for prefix: Data) { + func cancelPendingLogin(for prefix: Data, attemptID: UUID? = nil) { + if let attemptID, loginAttemptIDs[prefix] != attemptID { return } + loginAttemptIDs[prefix] = nil pendingLoginTimeoutTasks.removeValue(forKey: prefix)?.cancel() if let pending = pendingLogins.removeValue(forKey: prefix) { pending.continuation.resume(throwing: RemoteNodeError.cancelled) @@ -286,6 +293,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 } @@ -300,6 +316,7 @@ public actor RemoteNodeService { await hold() } #endif + try validateSessionCreation(contactID: contact.id, sensorAttemptID: sensorAttemptID) let saved = try await dataStore.reuseOrCreateRemoteNodeSession( RoomSessionPresentation( radioID: radioID, @@ -310,10 +327,17 @@ 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) @@ -361,6 +385,7 @@ public actor RemoteNodeService { /// Stop all keep-alive timers and resume any parked login continuations (call on app termination) public func stopAllKeepAlives() { + loginAttemptIDs.removeAll() for task in keepAliveTasks.values { task.cancel() retiredKeepAliveTasks.append(task) @@ -374,16 +399,37 @@ public actor RemoteNodeService { } } - func retireKeepAlives() async { - if let keepAliveRetirement { await keepAliveRetirement.value; return } - keepAliveAdmissionRetired = true + func beginRetirement() { + guard !isRetired else { return } + isRetired = true + sensorConnectAttempts.removeAll() stopAllKeepAlives() + for (prefix, pending) in pendingCLIRequests { + cancelPendingCLIRequest(for: prefix, requestID: pending.id) + } + let waiters = cliSlotWaiters.values.flatMap(\.self) + cliSlotWaiters.removeAll() + for waiter in waiters { + waiter.continuation.resume(throwing: CancellationError()) + } + } + + func retire() async { + if let retirementTask { + await retirementTask.value + return + } + + beginRetirement() let workers = retiredKeepAliveTasks retiredKeepAliveTasks.removeAll() - let drain = Task { for worker in workers { - await worker.value - } } - keepAliveRetirement = drain + let drain = Task { + await stopEventMonitoring() + for worker in workers { + await worker.value + } + } + retirementTask = drain await drain.value } 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/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..b937a860a7 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. diff --git a/MC1Services/Sources/MC1Services/Utilities/ContactShareUtilities.swift b/MC1Services/Sources/MC1Services/Utilities/ContactShareUtilities.swift index 81cde9ff1b..38cada44b0 100644 --- a/MC1Services/Sources/MC1Services/Utilities/ContactShareUtilities.swift +++ b/MC1Services/Sources/MC1Services/Utilities/ContactShareUtilities.swift @@ -4,7 +4,7 @@ import Foundation /// /// - `publicKeyHex` is the 32-byte public key as 64 hex characters (uppercase on emit, /// case-insensitive on parse). -/// - `type` is a ``ContactType`` raw value (1 chat, 2 repeater, 3 room). +/// - `type` is a ``ContactType`` raw value (1 chat, 2 repeater, 3 room, 4 sensor). /// - `name` is the node's advertised name. `>` is the reserved terminator and is stripped /// from the name on emit; the name may legitimately contain `:`. public enum ContactShareUtilities { diff --git a/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift index 446fbc9d09..a83ace02d3 100644 --- a/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift @@ -8,6 +8,55 @@ import Testing /// exercising the complete data flow rather than manually constructed envelopes. @Suite("BackupIntegration") struct BackupIntegrationTests { + @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 +231,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 +250,7 @@ struct BackupIntegrationTests { radioID: radioID, publicKey: Data(repeating: 0xAB, count: 32), name: "FutureType", - typeRawValue: 0x04 + typeRawValue: 0x7F ) try await sourceStore.saveContact(contact) @@ -214,7 +263,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) } 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/RemoteNodeLoginContactRecoveryTests.swift b/MC1Services/Tests/MC1ServicesTests/RemoteNodeLoginContactRecoveryTests.swift index 39b4a4be39..adad878e6b 100644 --- a/MC1Services/Tests/MC1ServicesTests/RemoteNodeLoginContactRecoveryTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/RemoteNodeLoginContactRecoveryTests.swift @@ -34,7 +34,7 @@ struct RemoteNodeLoginContactRecoveryTests { 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: "synthetic-fixture") + try await link.services.remoteNodeService.login(sessionID: membership.id, password: "test-fixture") }) if hasLocalContact { #expect(try await login.value.success) diff --git a/MC1Services/Tests/MC1ServicesTests/Services/NodeConfigImportPlannerTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/NodeConfigImportPlannerTests.swift index c441f99c4a..66bedbdbaa 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/NodeConfigImportPlannerTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/NodeConfigImportPlannerTests.swift @@ -1021,14 +1021,14 @@ struct ContactTypeBytePreservationTests { @Test func `parseContactData preserves an unmodeled type byte while falling back to .chat`() throws { - let contact = try #require(Parsers.parseContactData(contactBytes(typeByte: 0x04))) - #expect(contact.typeRawValue == 0x04) + let contact = try #require(Parsers.parseContactData(contactBytes(typeByte: 0x7F))) + #expect(contact.typeRawValue == 0x7F) #expect(contact.type == .chat) } @Test func `parseContactData keeps modeled type bytes and their enum in sync`() throws { - for (raw, expected): (UInt8, ContactType) in [(0x01, .chat), (0x02, .repeater), (0x03, .room)] { + for (raw, expected): (UInt8, ContactType) in [(0x01, .chat), (0x02, .repeater), (0x03, .room), (0x04, .sensor)] { let contact = try #require(Parsers.parseContactData(contactBytes(typeByte: raw))) #expect(contact.typeRawValue == raw) #expect(contact.type == expected) @@ -1036,33 +1036,33 @@ struct ContactTypeBytePreservationTests { } @Test - func `ContactFrame ↔ MeshContact ↔ Contact/ContactDTO and export all keep 0x04`() { + func `ContactFrame ↔ MeshContact ↔ Contact/ContactDTO and export all keep 0x7F`() { let radioID = UUID() let frame = ContactFrame( publicKey: Data(repeating: 0xAB, count: 32), - type: .chat, typeRawValue: 0x04, flags: 0, + type: .chat, typeRawValue: 0x7F, flags: 0, outPathLength: 0xFF, outPath: Data(), name: "FutureType", lastAdvertTimestamp: 0, latitude: 0, longitude: 0, lastModified: 0 ) // Frame → MeshContact → Frame let meshContact = frame.toMeshContact() - #expect(meshContact.typeRawValue == 0x04) - #expect(meshContact.toContactFrame().typeRawValue == 0x04) + #expect(meshContact.typeRawValue == 0x7F) + #expect(meshContact.toContactFrame().typeRawValue == 0x7F) // Frame → Contact @Model → Frame, and through the DTO let contact = Contact(radioID: radioID, from: frame) - #expect(contact.typeRawValue == 0x04) - #expect(contact.toContactFrame().typeRawValue == 0x04) - #expect(ContactDTO(from: contact).toContactFrame().typeRawValue == 0x04) + #expect(contact.typeRawValue == 0x7F) + #expect(contact.toContactFrame().typeRawValue == 0x7F) + #expect(ContactDTO(from: contact).toContactFrame().typeRawValue == 0x7F) // Export re-emits the raw byte - #expect(NodeConfigService.buildContactConfig(from: meshContact).type == 0x04) + #expect(NodeConfigService.buildContactConfig(from: meshContact).type == 0x7F) } @Test func `Export and decode stay byte-identical for modeled types`() throws { - for raw: UInt8 in [0x01, 0x02, 0x03] { + for raw: UInt8 in [0x01, 0x02, 0x03, 0x04] { let meshContact = try MeshContact( id: "m", publicKey: Data(repeating: 0xAB, count: 32), type: #require(ContactType(rawValue: raw)), typeRawValue: raw, 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/RemoteNodeSensorTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeSensorTests.swift new file mode 100644 index 0000000000..288796c31a --- /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.cliSlotWaiters.isEmpty } + 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.loginAttemptIDs[prefix]) + 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/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/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift b/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift index 4b6079ad91..8f81916030 100644 --- a/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift +++ b/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift @@ -8,11 +8,13 @@ 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 { diff --git a/MC1Tests/Helpers/RetainedAdminPartitionSurface.swift b/MC1Tests/Helpers/RetainedAdminPartitionSurface.swift index 581238ba3e..3e9b42a646 100644 --- a/MC1Tests/Helpers/RetainedAdminPartitionSurface.swift +++ b/MC1Tests/Helpers/RetainedAdminPartitionSurface.swift @@ -68,6 +68,8 @@ struct RetainedAdminPartitionSurface { canMakeCLISend: { models.settings.makeNodeCLISendClosure(session: session) != nil }, cliObservation: cliObservation ) + case .sensor: + preconditionFailure("Sensors use a separate settings workspace") } } 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/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/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/RemoteAdminLifetimeTests.swift b/MC1Tests/ViewModels/RemoteAdminLifetimeTests.swift index b2d7472e7a..f2611b08f1 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, diff --git a/MC1Tests/ViewModels/RetainedAdminPartitionTests.swift b/MC1Tests/ViewModels/RetainedAdminPartitionTests.swift index 9801091226..95d0b73d22 100644 --- a/MC1Tests/ViewModels/RetainedAdminPartitionTests.swift +++ b/MC1Tests/ViewModels/RetainedAdminPartitionTests.swift @@ -25,11 +25,11 @@ struct RetainedAdminPartitionTests { let perRadioNavigationCleared = appState.navigation.chatsSelectedRoute == nil && appState.navigation.selectedContact == nil #expect(perRadioNavigationCleared) - let replacementSettings = switch role { - case .roomServer: appState.remoteAdminWorkspaces.room(for: retained.session).settings.helper - case .repeater: appState.remoteAdminWorkspaces.repeater(for: retained.session).settings.helper + 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 } - let previousWorkspaceReset = replacementSettings !== retained.settings #expect(previousWorkspaceReset) let framesBefore = await outgoingAdminFrameCount(harness) await harness.radio.rejectNext(.sendStatusRequest) @@ -69,6 +69,9 @@ struct RetainedAdminPartitionTests { 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() diff --git a/MC1Tests/ViewModels/SensorSettingsViewModelTests.swift b/MC1Tests/ViewModels/SensorSettingsViewModelTests.swift new file mode 100644 index 0000000000..60645f66f7 --- /dev/null +++ b/MC1Tests/ViewModels/SensorSettingsViewModelTests.swift @@ -0,0 +1,234 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +@testable import MeshCore +import Testing + +@Suite("Sensor settings workspace") +@MainActor +struct SensorSettingsViewModelTests { + @MainActor + private final class Harness { + let transport = MockTransport() + 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 { + session = MeshCoreSession(transport: transport, configuration: SessionConfiguration(defaultTimeout: 1, clientIdentifier: "Test")) + 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 + 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) + } + + 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/Views/ContactDetailStateTests.swift b/MC1Tests/Views/ContactDetailStateTests.swift index 644be0ade6..ccaa34a472 100644 --- a/MC1Tests/Views/ContactDetailStateTests.swift +++ b/MC1Tests/Views/ContactDetailStateTests.swift @@ -6,6 +6,21 @@ import UIKit @Suite("Retained contact detail state") @MainActor struct ContactDetailStateTests { + @Test + func `nonadmin sensor cannot handoff to repeater or management`() { + let contact = ContactDTO(from: Contact(radioID: UUID(), publicKey: Data(repeating: 0xA4, count: 32), + name: "Sensor", typeRawValue: ContactType.sensor.rawValue, lastHeardTimestamp: 0)) + let state = ContactDetailState(contact: contact) + state.configure(appState: AppState(), onClose: {}) + let session = RemoteNodeSessionDTO(radioID: contact.radioID, publicKey: contact.publicKey, + name: contact.name, role: .sensor, isConnected: true, permissionLevel: .guest) + state.queueAdminSheet(for: session, context: state.operationContext) + #expect(state.pendingSheet == nil) + state.presentPendingSheet() + #expect(state.activeSheet == nil) + state.end() + } + @Test func `payload refresh preserves the nickname draft and rejects a different contact`() { let contact = refreshed(makeContact(), nickname: "Stored nickname") diff --git a/MC1Tests/Views/Map/MapFilterStateTests.swift b/MC1Tests/Views/Map/MapFilterStateTests.swift index fb17f86de2..f0e7e2079f 100644 --- a/MC1Tests/Views/Map/MapFilterStateTests.swift +++ b/MC1Tests/Views/Map/MapFilterStateTests.swift @@ -6,6 +6,17 @@ import Testing @Suite("MapFilterState") struct MapFilterStateTests { + @Test(arguments: [true, false]) + func `sensors share the stored contact gate`(enabled: Bool) { + let state = MapFilterState(showChat: enabled) + #expect(state.allowsContactType(.sensor) == enabled) + #expect(state.allowsContactType(.repeater)) + #expect(state.allowsContactType(.room)) + var favorites = state + favorites.setFavoritesOnly(true) + #expect(favorites.allowsContactType(.sensor)) + } + @Test func `struct defaults match design`() { let s = MapFilterState() diff --git a/MC1Tests/Views/RemoteNodes/NodeCLIViewModelTests.swift b/MC1Tests/Views/RemoteNodes/NodeCLIViewModelTests.swift index 3e6a545f68..3e1d14dd1f 100644 --- a/MC1Tests/Views/RemoteNodes/NodeCLIViewModelTests.swift +++ b/MC1Tests/Views/RemoteNodes/NodeCLIViewModelTests.swift @@ -6,6 +6,35 @@ import Testing @Suite("NodeCLIViewModel Tests") @MainActor struct NodeCLIViewModelTests { + @Test + func `sensor host timeout is an error and does not claim reboot was sent`() async throws { + let spy = SendSpy() + spy.error = RemoteNodeError.timeout + let model = makeViewModel(spy: spy, remoteTarget: .sensor) + model.executeCommand("reboot") + try await waitUntil("sensor command should finish") { !model.isWaitingForResponse } + #expect(spy.calls.count == 1) + #expect(model.outputLines.contains { $0.type == .error }) + #expect(!model.outputLines.contains { $0.type == .success }) + } + + @Test + func `sensor no reply submission cannot be cancelled and duplicated`() async throws { + let send = HeldSend() + let model = NodeCLIViewModel() + model.configure(sessionName: "Sensor", remoteTarget: .sensor, sendRawCommand: send.send) + model.executeCommand("rebootx") + try await waitUntil("host acceptance should be pending") { send.commands.count == 1 } + #expect(!model.canCancelCurrentCommand) + model.cancelCurrentCommand() + model.executeCommand("rebootx") + #expect(model.isWaitingForResponse) + #expect(send.commands == ["rebootx"]) + send.finish("rebootx", with: .success("")) + try await waitUntil("accepted submission should finish") { !model.isWaitingForResponse } + #expect(model.outputLines.contains { $0.text == L10n.RemoteNodes.RemoteNodes.Sensor.rebootSent }) + } + /// Records the commands/timeouts passed to the injected send closure and /// returns a configurable result (or throws a configurable error). @MainActor diff --git a/MC1Tests/Views/Tools/CLI/CLICompletionEngineTests.swift b/MC1Tests/Views/Tools/CLI/CLICompletionEngineTests.swift index 4940906be2..a2dbcb54a8 100644 --- a/MC1Tests/Views/Tools/CLI/CLICompletionEngineTests.swift +++ b/MC1Tests/Views/Tools/CLI/CLICompletionEngineTests.swift @@ -4,6 +4,19 @@ import Testing @Suite("CLICompletionEngine Tests") @MainActor struct CLICompletionEngineTests { + @Test + func `sensor completions exclude unsupported repeater commands`() { + let engine = CLICompletionEngine() + let commands = engine.completions(for: "", isLocal: false, remoteTarget: .sensor, includeSessionCommands: false) + #expect(commands.contains("sensor")) + #expect(commands.contains("reboot")) + #expect(!commands.contains("neighbors")) + #expect(!commands.contains("room.post")) + #expect(!commands.contains("log")) + #expect(!commands.contains("start")) + #expect(!engine.completions(for: "get ", isLocal: false, remoteTarget: .sensor).contains("owner.info")) + } + // MARK: - Helper private func createEngine() -> CLICompletionEngine { diff --git a/MeshCore/Sources/MeshCore/Models/ContactTypes.swift b/MeshCore/Sources/MeshCore/Models/ContactTypes.swift index 376b7d893a..9cf8129075 100644 --- a/MeshCore/Sources/MeshCore/Models/ContactTypes.swift +++ b/MeshCore/Sources/MeshCore/Models/ContactTypes.swift @@ -10,6 +10,7 @@ public enum ContactType: UInt8, Sendable, Codable { case chat = 0x01 case repeater = 0x02 case room = 0x03 + case sensor = 0x04 } // MARK: - Contact Flags diff --git a/MeshCore/Tests/MeshCoreTests/Protocol/RegionTests.swift b/MeshCore/Tests/MeshCoreTests/Protocol/RegionTests.swift index 48f97a06cc..f38ef0f784 100644 --- a/MeshCore/Tests/MeshCoreTests/Protocol/RegionTests.swift +++ b/MeshCore/Tests/MeshCoreTests/Protocol/RegionTests.swift @@ -511,8 +511,8 @@ struct RequestRegionsIntegrationTests { await session.stop() } - @Test - func `requestRegions preserves an unmodeled raw type byte in the temp write`() async throws { + @Test(arguments: [UInt8(0x04), UInt8(0x7F)]) + func `requestRegions preserves sensor and unknown raw types in the temp write`(rawType: UInt8) async throws { let transport = MockTransport() // Short overall budget with retransmits disabled so the test can observe // the temp contact write after a fast timeout. @@ -525,10 +525,10 @@ struct RequestRegionsIntegrationTests { ) try await startSession(session, transport: transport) - // type falls back to .chat for the unmodeled 0x04 byte; typeRawValue carries the real byte. + // Unknown types keep their wire byte alongside the typed fallback. let contact = MeshContact( - id: "r", publicKey: Data(repeating: 0xCD, count: 32), type: .chat, - typeRawValue: 0x04, flags: ContactFlags(rawValue: 0), outPathLength: 0xFF, + id: "r", publicKey: Data(repeating: 0xCD, count: 32), type: ContactType(rawValue: rawType) ?? .chat, + typeRawValue: rawType, flags: ContactFlags(rawValue: 0), outPathLength: 0xFF, outPath: Data(), advertisedName: "Repeater", lastAdvertisement: Date(timeIntervalSince1970: 1000), latitude: 0, longitude: 0, lastModified: Date() ) @@ -545,10 +545,10 @@ struct RequestRegionsIntegrationTests { try await acknowledgeNextCommand(transport, sentCountBefore: 2, label: "resetPath") _ = try? await regionsTask.value - // First sent packet is the zero-hop temp write; its type byte must be the raw 0x04. + // The temporary write preserves the original type byte. let tempFrame = await transport.sentData[0] #expect(tempFrame[0] == CommandCode.updateContact.rawValue) // 0x09 - #expect(tempFrame[33] == 0x04, "raw type byte must survive, not coerce to 0x01") + #expect(tempFrame[33] == rawType, "raw type byte must survive, not coerce to 0x01") #expect(tempFrame[35] == 0x00, "zero-hop direct out_path_len") await session.stop() diff --git a/MeshCore/Tests/MeshCoreTests/Protocol/UpdateContactTests.swift b/MeshCore/Tests/MeshCoreTests/Protocol/UpdateContactTests.swift index c39f90b72e..3bb73c5c1f 100644 --- a/MeshCore/Tests/MeshCoreTests/Protocol/UpdateContactTests.swift +++ b/MeshCore/Tests/MeshCoreTests/Protocol/UpdateContactTests.swift @@ -4,6 +4,14 @@ import Testing @Suite("UpdateContact") struct UpdateContactTests { + @Test + func `sensor is recognized without changing its wire type`() throws { + let sensor = try #require(ContactType(rawValue: 0x04)) + #expect(sensor.rawValue == 0x04) + #expect(sensor != .chat) + #expect(ContactType(rawValue: 0x7F) == nil) + } + @Test func `updateContact correct layout`() throws { let pubkey = Data(repeating: 0xAA, count: 32) diff --git a/MeshCore/Tests/MeshCoreTests/Validation/DiscoverResponseParsingTests.swift b/MeshCore/Tests/MeshCoreTests/Validation/DiscoverResponseParsingTests.swift index 7bf4f871dd..59d80d04d6 100644 --- a/MeshCore/Tests/MeshCoreTests/Validation/DiscoverResponseParsingTests.swift +++ b/MeshCore/Tests/MeshCoreTests/Validation/DiscoverResponseParsingTests.swift @@ -4,6 +4,23 @@ import Testing @Suite("DiscoverResponse Parsing") struct DiscoverResponseParsingTests { + @Test(arguments: [8, 32]) + func `sensor fixture preserves signed metrics and key length`(keyLength: Int) { + var payload = Data([0x0C, 0xBA, 0x00, 0x94, 0xF8, 0x78, 0x56, 0x34, 0x12]) + payload.append(Data(repeating: 0xAB, count: keyLength)) + guard case let .discoverResponse(response) = Parsers.ControlData.parse(payload) else { + Issue.record("Expected sensor discover response") + return + } + #expect(response.nodeType == 4) + #expect(response.snrIn == -2) + #expect(response.snr == 3) + #expect(response.rssi == -70) + #expect(response.pathLength == 0) + #expect(response.publicKey.count == keyLength) + #expect(response.tag == Data([0x78, 0x56, 0x34, 0x12])) + } + @Test func `controlData parses discover response`() { // Control data format: [snr:1][rssi:1][pathLen:1][payloadType:1][payload...] From 1011e5b3b3598ef9b70049aefcb1a4c4cb2ce70c Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Wed, 4 Nov 2026 12:55:34 -0800 Subject: [PATCH 07/66] fix: restore connected radio menu behavior Put Change Device above Disconnect and restore the red Disconnect styling. Keep Stop Reconnecting first during recovery so it stays visible at large text sizes. --- .../Components/BLEStatusIndicatorView.swift | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/MC1/Views/Components/BLEStatusIndicatorView.swift b/MC1/Views/Components/BLEStatusIndicatorView.swift index 078a55d5da..f91af14a91 100644 --- a/MC1/Views/Components/BLEStatusIndicatorView.swift +++ b/MC1/Views/Components/BLEStatusIndicatorView.swift @@ -55,6 +55,7 @@ struct BLEStatusIndicatorView: View { @ViewBuilder private var menuContent: some View { if let activity = appState.connectionManager.connectionActivity { + let isConnected = appState.connectionState.isConnected Section(activity.accessibilityValue) { if let device = appState.connectedDevice { if device.clientRepeat { @@ -73,7 +74,11 @@ struct BLEStatusIndicatorView: View { } } - Button { + if isConnected { + changeDeviceButton + } + + Button(role: isConnected ? .destructive : nil) { logger.info("Disconnect tapped in BLE status menu") Task { await appState.disconnect(requestID: activity.requestID, reason: .statusMenuDisconnectTap) @@ -81,11 +86,10 @@ struct BLEStatusIndicatorView: View { } label: { Label(activity.stopTitle, systemImage: "eject") } + .tint(isConnected ? Color(.systemRed) : nil) - Button { - showingDeviceSelection = true - } label: { - Label(L10n.Settings.BleStatus.changeDevice, systemImage: "flipphone") + if !isConnected { + changeDeviceButton } } @@ -125,6 +129,14 @@ struct BLEStatusIndicatorView: View { } } + 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) From 9569b6db954947e29b8d33d3f36d04a1adff95ff Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:17:37 -0800 Subject: [PATCH 08/66] feat: show retained telemetry on device info - Keep the connected radio's telemetry so Device Info can show the last reading after a reload fails. - Store that history with the radio and include it in backups, with a warning that GPS coordinates may be exported. --- MC1/Resources/Generated/L10n.swift | 8 +- .../Localization/de.lproj/Settings.strings | 8 +- .../Localization/en.lproj/Settings.strings | 8 +- .../Localization/es.lproj/Settings.strings | 8 +- .../Localization/fr.lproj/Settings.strings | 8 +- .../Localization/it.lproj/Settings.strings | 8 +- .../Localization/ko.lproj/Settings.strings | 8 +- .../Localization/nl.lproj/Settings.strings | 8 +- .../Localization/pl.lproj/Settings.strings | 8 +- .../Localization/pt.lproj/Settings.strings | 8 +- .../Localization/ru.lproj/Settings.strings | 8 +- .../Localization/uk.lproj/Settings.strings | 8 +- .../zh-Hans.lproj/Settings.strings | 8 +- MC1/Views/RemoteNodes/NodeStatusRoute.swift | 37 +- .../RemoteNodes/NodeStatusViewModel.swift | 58 +-- .../RemoteNodes/SharedNodeStatusViews.swift | 176 +++++-- MC1/Views/RemoteNodes/TelemetryReading.swift | 34 ++ .../DeviceInfoTelemetryViewModel.swift | 198 +++++++ MC1/Views/Settings/DeviceInfoView.swift | 75 ++- MC1/Views/Settings/SettingsSubpage.swift | 17 + MC1/Views/Settings/SettingsView.swift | 7 + .../Models/NodeStatusSnapshot.swift | 18 +- .../Persistence/NodeSnapshotPersisting.swift | 15 + .../Services/AppBackupEnvelope.swift | 6 +- .../Services/AppBackupService.swift | 2 + .../Services/NodeSnapshotService.swift | 36 ++ .../PersistenceStore+BackupBatchInsert.swift | 45 +- .../PersistenceStore+BackupHelpers.swift | 14 +- .../PersistenceStore+BackupImport.swift | 26 +- .../Services/PersistenceStore+Devices.swift | 34 +- .../PersistenceStore+Diagnostics.swift | 152 ++++-- .../Services/PersistenceStore.swift | 2 + .../Simulator/SimulatorConnectionMode.swift | 6 +- .../AppBackupServiceTests.swift | 51 +- .../BackupIntegrationTests.swift | 263 +++++++++- .../Helpers/AppBackupEnvelope+Testing.swift | 2 + .../NodeStatusSnapshotDTO+Testing.swift | 2 + .../Mocks/MockPersistenceStore.swift | 17 + .../PersistenceStoreTests.swift | 331 ++++++++++++ .../Services/InlineImagePrefetcherTests.swift | 17 + MC1Tests/Services/LinkPreviewCacheTests.swift | 17 + .../DeviceInfoTelemetryViewModelTests.swift | 485 ++++++++++++++++++ .../LineOfSightViewModelTests.swift | 17 + .../ViewModels/NodeLocationCaptureTests.swift | 17 + .../Chats/ChatViewModelAdmissionTests.swift | 17 + .../Views/SettingsRouteAdmissionTests.swift | 24 + .../Tools/CLI/CLIToolViewModelTests.swift | 18 + 47 files changed, 2127 insertions(+), 213 deletions(-) create mode 100644 MC1/Views/RemoteNodes/TelemetryReading.swift create mode 100644 MC1/Views/Settings/DeviceInfoTelemetryViewModel.swift create mode 100644 MC1Tests/ViewModels/DeviceInfoTelemetryViewModelTests.swift diff --git a/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index 344a845a44..ac8649ec5c 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -4978,6 +4978,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 @@ -5024,6 +5026,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 @@ -5990,7 +5996,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") } diff --git a/MC1/Resources/Localization/de.lproj/Settings.strings b/MC1/Resources/Localization/de.lproj/Settings.strings index 0b29548b81..84aaf33c93 100644 --- a/MC1/Resources/Localization/de.lproj/Settings.strings +++ b/MC1/Resources/Localization/de.lproj/Settings.strings @@ -111,6 +111,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"; @@ -2035,7 +2041,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/en.lproj/Settings.strings b/MC1/Resources/Localization/en.lproj/Settings.strings index eb98ec5322..fabf402729 100644 --- a/MC1/Resources/Localization/en.lproj/Settings.strings +++ b/MC1/Resources/Localization/en.lproj/Settings.strings @@ -111,6 +111,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"; @@ -2040,7 +2046,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/es.lproj/Settings.strings b/MC1/Resources/Localization/es.lproj/Settings.strings index d06e85343b..991c6b8253 100644 --- a/MC1/Resources/Localization/es.lproj/Settings.strings +++ b/MC1/Resources/Localization/es.lproj/Settings.strings @@ -111,6 +111,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"; @@ -2035,7 +2041,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/fr.lproj/Settings.strings b/MC1/Resources/Localization/fr.lproj/Settings.strings index af84832b1b..1bc115d976 100644 --- a/MC1/Resources/Localization/fr.lproj/Settings.strings +++ b/MC1/Resources/Localization/fr.lproj/Settings.strings @@ -111,6 +111,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"; @@ -2035,7 +2041,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/it.lproj/Settings.strings b/MC1/Resources/Localization/it.lproj/Settings.strings index 21916da317..21b836cc39 100644 --- a/MC1/Resources/Localization/it.lproj/Settings.strings +++ b/MC1/Resources/Localization/it.lproj/Settings.strings @@ -111,6 +111,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"; @@ -2033,7 +2039,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/ko.lproj/Settings.strings b/MC1/Resources/Localization/ko.lproj/Settings.strings index 11a2f849ae..b0d4e99fdd 100644 --- a/MC1/Resources/Localization/ko.lproj/Settings.strings +++ b/MC1/Resources/Localization/ko.lproj/Settings.strings @@ -111,6 +111,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" = "공개 키"; @@ -2040,7 +2046,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/nl.lproj/Settings.strings b/MC1/Resources/Localization/nl.lproj/Settings.strings index c3ef2cd025..d2c6b1127d 100644 --- a/MC1/Resources/Localization/nl.lproj/Settings.strings +++ b/MC1/Resources/Localization/nl.lproj/Settings.strings @@ -111,6 +111,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"; @@ -2035,7 +2041,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/pl.lproj/Settings.strings b/MC1/Resources/Localization/pl.lproj/Settings.strings index 6c491a8f4f..6dd30a4b56 100644 --- a/MC1/Resources/Localization/pl.lproj/Settings.strings +++ b/MC1/Resources/Localization/pl.lproj/Settings.strings @@ -111,6 +111,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"; @@ -2035,7 +2041,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/pt.lproj/Settings.strings b/MC1/Resources/Localization/pt.lproj/Settings.strings index 306875cb7f..0c5ac39bb4 100644 --- a/MC1/Resources/Localization/pt.lproj/Settings.strings +++ b/MC1/Resources/Localization/pt.lproj/Settings.strings @@ -111,6 +111,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"; @@ -2033,7 +2039,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/ru.lproj/Settings.strings b/MC1/Resources/Localization/ru.lproj/Settings.strings index 863a9cc6d5..63abe22a73 100644 --- a/MC1/Resources/Localization/ru.lproj/Settings.strings +++ b/MC1/Resources/Localization/ru.lproj/Settings.strings @@ -111,6 +111,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" = "Публичный ключ"; @@ -2035,7 +2041,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/Settings.strings b/MC1/Resources/Localization/uk.lproj/Settings.strings index 805a11a751..47de6a044b 100644 --- a/MC1/Resources/Localization/uk.lproj/Settings.strings +++ b/MC1/Resources/Localization/uk.lproj/Settings.strings @@ -111,6 +111,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" = "Публічний ключ"; @@ -2035,7 +2041,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/zh-Hans.lproj/Settings.strings b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings index fd3ccd0b3c..e49ed2eb1d 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings @@ -111,6 +111,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" = "查看公钥"; @@ -2035,7 +2041,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/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/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/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/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..3a43d6f0a6 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 { @@ -100,6 +101,8 @@ struct DeviceInfoView: View { } .themedRowBackground(theme) + telemetrySection(for: device) + // Battery and storage Section { if let battery = appState.batteryMonitor.deviceBattery { @@ -213,13 +216,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 +243,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/SettingsSubpage.swift b/MC1/Views/Settings/SettingsSubpage.swift index fbeeb209e4..d9da533e66 100644 --- a/MC1/Views/Settings/SettingsSubpage.swift +++ b/MC1/Views/Settings/SettingsSubpage.swift @@ -17,6 +17,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,6 +26,10 @@ 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: @@ -58,6 +64,7 @@ private enum SettingsSubpageContext { case radio(PresetLocationSession) case advanced(RegionDiscoveryState, SettingsEditorPresentation.RegionRequest, NodeConfigImportViewModel) case connection(RadioWiFiViewModel) + case deviceInfo(DeviceInfoTelemetryViewModel) } extension View { @@ -80,6 +87,10 @@ extension View { 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. @@ -137,6 +148,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 e72ce3933f..40a6c2839c 100644 --- a/MC1/Views/Settings/SettingsView.swift +++ b/MC1/Views/Settings/SettingsView.swift @@ -159,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() } 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/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/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/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/PersistenceStore+BackupBatchInsert.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift index 82a4e61e67..d0b53b3cd7 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift @@ -449,8 +449,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, @@ -638,14 +637,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..010ca0b8b3 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 diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift index 7be09ac9a2..6176a92f0f 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 { @@ -319,10 +331,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) diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Devices.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Devices.swift index 39c02efd7d..009c989bb7 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Devices.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Devices.swift @@ -344,7 +344,11 @@ public extension PersistenceStore { ghostDescriptor.fetchLimit = 1 guard let ghost = try modelContext.fetch(ghostDescriptor).first, !ghost.connectionMethods.contains(where: \.isBluetooth) else { return nil } + let departingRadioID = current.radioID let newRadioID = ghost.radioID + if departingRadioID != newRadioID { + try reassignSelfTelemetrySnapshots(from: departingRadioID, to: newRadioID) + } current.radioID = newRadioID current.publicKey = newPublicKey current.connectionMethods = ConnectionMethod.canonicalized(current.connectionMethods) @@ -383,6 +387,8 @@ public extension PersistenceStore { } let targetRadioID = device.radioID + try deleteSelfTelemetrySnapshots(radioID: targetRadioID) + // Delete reactions (references messages via messageID) let reactionPredicate = #Predicate { reaction in reaction.radioID == targetRadioID @@ -413,7 +419,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 @@ -421,11 +427,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) } } @@ -519,6 +525,22 @@ 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 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.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift index 626ed5700b..8529d737d4 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift @@ -177,6 +177,8 @@ 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 NodeStatusSnapshot.selfRadioID (UUID?, default nil). Existing rows + /// stay remote history. Self telemetry rows store the Device's radioID. public static func createContainer(inMemory: Bool = false) throws -> ModelContainer { if !inMemory { let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! 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/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/BackupIntegrationTests.swift b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift index a83ace02d3..b3621efafc 100644 --- a/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift @@ -2458,6 +2458,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 { @@ -3771,12 +4014,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) @@ -3830,12 +4073,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) } @@ -3855,12 +4098,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) } @@ -4243,9 +4486,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) @@ -4276,9 +4519,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/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/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/Mocks/MockPersistenceStore.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift index bdbb5b5784..d822b75ae1 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift @@ -2579,6 +2579,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) { diff --git a/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift b/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift index bb2f7197e7..31d5aa5677 100644 --- a/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift @@ -4359,4 +4359,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/MC1Tests/Services/InlineImagePrefetcherTests.swift b/MC1Tests/Services/InlineImagePrefetcherTests.swift index ed6543f0d5..8fb5f6f4aa 100644 --- a/MC1Tests/Services/InlineImagePrefetcherTests.swift +++ b/MC1Tests/Services/InlineImagePrefetcherTests.swift @@ -778,6 +778,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 1e4d645561..d9a5266916 100644 --- a/MC1Tests/Services/LinkPreviewCacheTests.swift +++ b/MC1Tests/Services/LinkPreviewCacheTests.swift @@ -751,6 +751,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/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/LineOfSightViewModelTests.swift b/MC1Tests/ViewModels/LineOfSightViewModelTests.swift index 105226fae6..305678d3b8 100644 --- a/MC1Tests/ViewModels/LineOfSightViewModelTests.swift +++ b/MC1Tests/ViewModels/LineOfSightViewModelTests.swift @@ -620,6 +620,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/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/Views/Chats/ChatViewModelAdmissionTests.swift b/MC1Tests/Views/Chats/ChatViewModelAdmissionTests.swift index 9cad93aeb3..7a4e3436a6 100644 --- a/MC1Tests/Views/Chats/ChatViewModelAdmissionTests.swift +++ b/MC1Tests/Views/Chats/ChatViewModelAdmissionTests.swift @@ -1097,6 +1097,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/SettingsRouteAdmissionTests.swift b/MC1Tests/Views/SettingsRouteAdmissionTests.swift index 6cee2f2ea0..29708c8121 100644 --- a/MC1Tests/Views/SettingsRouteAdmissionTests.swift +++ b/MC1Tests/Views/SettingsRouteAdmissionTests.swift @@ -73,6 +73,30 @@ struct SettingsRouteAdmissionTests { #expect(SettingsSubpage.admitted(path, for: .radio, device: makeDevice(firmware: 11, clientRepeat: true)).isEmpty) #expect(SettingsSubpage.admitted(path, for: nil, device: device).isEmpty) } + + @Test + func `device info telemetry routes stay with the matching key`() { + let device = makeDevice(firmware: 11, clientRepeat: false) + let fix = NodeLocationFix(latitude: 47.6, longitude: -122.3, altitude: 12) + let history = SettingsSubpage.deviceInfoTelemetryHistory(publicKey: device.publicKey) + let map = SettingsSubpage.deviceInfoLocationMap(publicKey: device.publicKey, fix: fix, name: "Relay") + let otherKey = Data(repeating: 0x22, count: ProtocolLimits.publicKeySize) + let wrongHistory = SettingsSubpage.deviceInfoTelemetryHistory(publicKey: otherKey) + let wrongMap = SettingsSubpage.deviceInfoLocationMap(publicKey: otherKey, fix: fix, name: "Other") + + #expect(history.isAdmitted(for: .deviceInfo, device: device)) + #expect(map.isAdmitted(for: .deviceInfo, device: device)) + #expect(!history.isAdmitted(for: .advanced, device: device)) + #expect(!map.isAdmitted(for: .maps, device: device)) + #expect(!history.isAdmitted(for: .deviceInfo, device: nil)) + #expect(!map.isAdmitted(for: .deviceInfo, device: nil)) + #expect(!wrongHistory.isAdmitted(for: .deviceInfo, device: device)) + #expect(!wrongMap.isAdmitted(for: .deviceInfo, device: device)) + + let path: [SettingsSubpage] = [history, map, wrongHistory, wrongMap, .offlineMaps] + #expect(SettingsSubpage.admitted(path, for: .deviceInfo, device: device) == [history, map]) + #expect(SettingsSubpage.admitted(path, for: .maps, device: device) == [.offlineMaps]) + } } private func makeDevice(firmware: UInt8, clientRepeat: Bool) -> DeviceDTO { diff --git a/MC1Tests/Views/Tools/CLI/CLIToolViewModelTests.swift b/MC1Tests/Views/Tools/CLI/CLIToolViewModelTests.swift index ac3f72ab41..7d56a29010 100644 --- a/MC1Tests/Views/Tools/CLI/CLIToolViewModelTests.swift +++ b/MC1Tests/Views/Tools/CLI/CLIToolViewModelTests.swift @@ -996,6 +996,24 @@ actor ParkingContactStore: 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 From 62c12cba1a2c966e4094f56ef141f41983897bbe Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:21:35 -0800 Subject: [PATCH 09/66] ui: remove device info connection section - Drop the Connection section because Device Info only appears for an already connected radio and the row always showed Connected. - Remove the strings that existed only for that section. --- MC1/Resources/Generated/L10n.swift | 8 ------- .../Localization/de.lproj/Settings.strings | 9 -------- .../Localization/en.lproj/Settings.strings | 9 -------- .../Localization/es.lproj/Settings.strings | 9 -------- .../Localization/fr.lproj/Settings.strings | 9 -------- .../Localization/it.lproj/Settings.strings | 9 -------- .../Localization/ko.lproj/Settings.strings | 9 -------- .../Localization/nl.lproj/Settings.strings | 9 -------- .../Localization/pl.lproj/Settings.strings | 9 -------- .../Localization/pt.lproj/Settings.strings | 9 -------- .../Localization/ru.lproj/Settings.strings | 9 -------- .../Localization/uk.lproj/Settings.strings | 9 -------- .../zh-Hans.lproj/Settings.strings | 9 -------- MC1/Views/Settings/DeviceInfoView.swift | 21 ------------------- 14 files changed, 137 deletions(-) diff --git a/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index ac8649ec5c..748129e929 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -4928,8 +4928,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 @@ -5006,12 +5004,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") diff --git a/MC1/Resources/Localization/de.lproj/Settings.strings b/MC1/Resources/Localization/de.lproj/Settings.strings index 84aaf33c93..4a77e95e41 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"; diff --git a/MC1/Resources/Localization/en.lproj/Settings.strings b/MC1/Resources/Localization/en.lproj/Settings.strings index fabf402729..4e885c7015 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"; diff --git a/MC1/Resources/Localization/es.lproj/Settings.strings b/MC1/Resources/Localization/es.lproj/Settings.strings index 991c6b8253..ab4cab8d1d 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"; diff --git a/MC1/Resources/Localization/fr.lproj/Settings.strings b/MC1/Resources/Localization/fr.lproj/Settings.strings index 1bc115d976..6bd7df8070 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"; diff --git a/MC1/Resources/Localization/it.lproj/Settings.strings b/MC1/Resources/Localization/it.lproj/Settings.strings index 21b836cc39..8d27fcdf87 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"; diff --git a/MC1/Resources/Localization/ko.lproj/Settings.strings b/MC1/Resources/Localization/ko.lproj/Settings.strings index b0d4e99fdd..5e40350e76 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" = "전원 및 저장 공간"; diff --git a/MC1/Resources/Localization/nl.lproj/Settings.strings b/MC1/Resources/Localization/nl.lproj/Settings.strings index d2c6b1127d..d3556ae957 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"; diff --git a/MC1/Resources/Localization/pl.lproj/Settings.strings b/MC1/Resources/Localization/pl.lproj/Settings.strings index 6dd30a4b56..999623b153 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ęć"; diff --git a/MC1/Resources/Localization/pt.lproj/Settings.strings b/MC1/Resources/Localization/pt.lproj/Settings.strings index 0c5ac39bb4..105fd6b445 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"; diff --git a/MC1/Resources/Localization/ru.lproj/Settings.strings b/MC1/Resources/Localization/ru.lproj/Settings.strings index 63abe22a73..a8be1bbf4f 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" = "Питание и память"; diff --git a/MC1/Resources/Localization/uk.lproj/Settings.strings b/MC1/Resources/Localization/uk.lproj/Settings.strings index 47de6a044b..54cacb7303 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" = "Живлення та пам'ять"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings index e49ed2eb1d..e77a6e9933 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" = "电源和存储"; diff --git a/MC1/Views/Settings/DeviceInfoView.swift b/MC1/Views/Settings/DeviceInfoView.swift index 3a43d6f0a6..c4b59fa901 100644 --- a/MC1/Views/Settings/DeviceInfoView.swift +++ b/MC1/Views/Settings/DeviceInfoView.swift @@ -80,27 +80,6 @@ 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 From 83822aed574cf5240c4f83be1767bc6e567adfc2 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Thu, 5 Nov 2026 09:10:32 -0800 Subject: [PATCH 10/66] feat: add message retry settings - Add DM retry settings with four initial attempts and four fallback attempts by default. - Use one DM retry budget and shared room send handling to keep retry behavior consistent. - Wait for command issuance and ACK tracking before admitting another DM or room post. - Persist quick replies for recovery and include retry preferences in backups. --- MC1/Resources/Generated/L10n.swift | 6 + .../Localization/de.lproj/Settings.strings | 9 + .../Localization/en.lproj/Settings.strings | 9 + .../Localization/es.lproj/Settings.strings | 9 + .../Localization/fr.lproj/Settings.strings | 9 + .../Localization/it.lproj/Settings.strings | 9 + .../Localization/ko.lproj/Settings.strings | 9 + .../Localization/nl.lproj/Settings.strings | 9 + .../Localization/pl.lproj/Settings.strings | 9 + .../Localization/pt.lproj/Settings.strings | 9 + .../Localization/ru.lproj/Settings.strings | 9 + .../Localization/uk.lproj/Settings.strings | 9 + .../zh-Hans.lproj/Settings.strings | 9 + .../DirectMessagesSettingsSection.swift | 35 ++- .../Models/DirectMessageEnvelope.swift | 16 +- .../MC1Services/Models/PendingSend.swift | 100 ++---- .../Models/PendingSendEnvelope.swift | 41 +-- .../MC1Services/ServiceContainer.swift | 16 +- .../MC1Services/Services/AckCodeBuilder.swift | 41 +-- .../MC1Services/Services/AppStorageKey.swift | 6 + .../Services/BackupUserDefaults.swift | 43 ++- .../Services/ChatSendQueueService.swift | 56 ++-- .../MC1Services/Services/DMSendBudget.swift | 47 +++ .../Services/MessageService+ACKRecovery.swift | 19 +- .../MessageService+PlainTextLease.swift | 28 ++ .../Services/MessageService+SendDM.swift | 291 ++++++++---------- .../Services/MessageService+SendHelpers.swift | 2 +- .../MC1Services/Services/MessageService.swift | 9 +- .../Services/MessageServiceConfig.swift | 18 -- .../MC1Services/Services/PendingAck.swift | 4 +- .../PersistenceStore+PendingSends.swift | 1 + .../Services/PlainTextSendGate.swift | 130 ++++++++ .../Services/RoomServerService.swift | 203 +++++------- .../MC1Services/Services/SendQueue.swift | 4 + .../AppBackupEnvelopeTests.swift | 60 ++++ ...grationTests+PendingAcknowledgements.swift | 4 +- .../BackupIntegrationTests.swift | 38 +++ .../BackupUserDefaultsCoverageTests.swift | 5 +- .../Mocks/MockPersistenceStore.swift | 28 +- .../PendingSendPersistenceTests.swift | 30 ++ .../Services/AckCodeBuilderTests.swift | 15 +- .../ChatSendQueueServiceReconnectTests.swift | 3 +- .../Services/DMSendBudgetTests.swift | 53 ++++ .../MessageServiceACKRecoveryTests.swift | 55 +++- .../Services/MessageServiceConfigTests.swift | 18 -- .../MessageServiceDMBudgetTests.swift | 154 +++++++++ ...MessageServiceSendDMBookkeepingTests.swift | 2 +- .../Services/MessageServiceSendTests.swift | 153 +-------- .../Services/MessageServiceTests.swift | 9 - .../PlainTextSendGateTests+Inline.swift | 99 ++++++ .../PlainTextSendGateTests+Queue.swift | 165 ++++++++++ .../PlainTextSendGateTests+RadioHarness.swift | 131 ++++++++ .../PlainTextSendGateTests+RadioScript.swift | 60 ++++ .../PlainTextSendGateTests+Recovery.swift | 205 ++++++++++++ .../PlainTextSendGateTests+Rooms.swift | 172 +++++++++++ .../Services/PlainTextSendGateTests.swift | 148 +++++++++ docs/Architecture.md | 4 +- docs/User_Guide.md | 4 +- docs/api/MC1Services.md | 17 +- docs/guides/Messaging.md | 52 ++-- 60 files changed, 2189 insertions(+), 719 deletions(-) create mode 100644 MC1Services/Sources/MC1Services/Services/DMSendBudget.swift create mode 100644 MC1Services/Sources/MC1Services/Services/MessageService+PlainTextLease.swift create mode 100644 MC1Services/Sources/MC1Services/Services/PlainTextSendGate.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/DMSendBudgetTests.swift delete mode 100644 MC1Services/Tests/MC1ServicesTests/Services/MessageServiceConfigTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/MessageServiceDMBudgetTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+Inline.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+Queue.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+RadioHarness.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+RadioScript.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+Recovery.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+Rooms.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests.swift diff --git a/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index 748129e929..80f579dc40 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -5134,6 +5134,12 @@ public enum L10n { public enum DirectMessages { /// Picker label for number of acknowledgments public static let acknowledgments = L10n.tr("Settings", "directMessages.acknowledgments", fallback: "Acknowledgments") + /// Footer explaining the initial and fallback attempt pickers + public static let attemptsFooter = L10n.tr("Settings", "directMessages.attemptsFooter", fallback: "Initial attempts use Flood if the contact has no out path. Flood fallback tries to clear the out path before retrying. Set Flood Fallback Attempts to zero to skip the reset and extra attempts.") + /// Picker label for attempts before resetting the contact's out path + public static let directAttempts = L10n.tr("Settings", "directMessages.directAttempts", fallback: "Initial Attempts") + /// Picker label for extra attempts after the contact's out path reset + public static let floodAttempts = L10n.tr("Settings", "directMessages.floodAttempts", fallback: "Flood Fallback 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 diff --git a/MC1/Resources/Localization/de.lproj/Settings.strings b/MC1/Resources/Localization/de.lproj/Settings.strings index 4a77e95e41..caefa22a3f 100644 --- a/MC1/Resources/Localization/de.lproj/Settings.strings +++ b/MC1/Resources/Localization/de.lproj/Settings.strings @@ -1169,6 +1169,15 @@ /* 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."; +/* Picker label for attempts before resetting the contact's out path */ +"directMessages.directAttempts" = "Erste Versuche"; + +/* Picker label for extra attempts after the contact's out path reset */ +"directMessages.floodAttempts" = "Flood-Fallback-Versuche"; + +/* Footer explaining the initial and fallback attempt pickers */ +"directMessages.attemptsFooter" = "Die ersten Versuche verwenden Flood, wenn der Kontakt keinen ausgehenden Pfad hat. Der Flood-Fallback versucht, den ausgehenden Pfad zurückzusetzen, bevor erneut gesendet wird. Stelle die Flood-Fallback-Versuche auf 0, um das Zurücksetzen und die zusätzlichen Versuche zu überspringen."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ diff --git a/MC1/Resources/Localization/en.lproj/Settings.strings b/MC1/Resources/Localization/en.lproj/Settings.strings index 4e885c7015..9280dd2ef3 100644 --- a/MC1/Resources/Localization/en.lproj/Settings.strings +++ b/MC1/Resources/Localization/en.lproj/Settings.strings @@ -1208,6 +1208,15 @@ /* Footer explaining the acknowledgments setting */ "directMessages.footer" = "Number of acknowledgments sent per direct message. Use 2 for better delivery confirmation over unreliable links."; +/* Picker label for attempts before resetting the contact's out path */ +"directMessages.directAttempts" = "Initial Attempts"; + +/* Picker label for extra attempts after the contact's out path reset */ +"directMessages.floodAttempts" = "Flood Fallback Attempts"; + +/* Footer explaining the initial and fallback attempt pickers */ +"directMessages.attemptsFooter" = "Initial attempts use Flood if the contact has no out path. Flood fallback tries to clear the out path before retrying. Set Flood Fallback Attempts to zero to skip the reset and extra attempts."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ diff --git a/MC1/Resources/Localization/es.lproj/Settings.strings b/MC1/Resources/Localization/es.lproj/Settings.strings index ab4cab8d1d..42675c572c 100644 --- a/MC1/Resources/Localization/es.lproj/Settings.strings +++ b/MC1/Resources/Localization/es.lproj/Settings.strings @@ -1169,6 +1169,15 @@ /* 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."; +/* Picker label for attempts before resetting the contact's out path */ +"directMessages.directAttempts" = "Intentos iniciales"; + +/* Picker label for extra attempts after the contact's out path reset */ +"directMessages.floodAttempts" = "Intentos de reserva Flood"; + +/* Footer explaining the initial and fallback attempt pickers */ +"directMessages.attemptsFooter" = "Los intentos iniciales usan Flood si el contacto no tiene ruta de salida. Con los intentos de reserva Flood se intenta restablecer la ruta de salida antes de los intentos adicionales. Usa 0 en Intentos de reserva Flood para omitir el restablecimiento y los intentos adicionales."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ diff --git a/MC1/Resources/Localization/fr.lproj/Settings.strings b/MC1/Resources/Localization/fr.lproj/Settings.strings index 6bd7df8070..1a4c6bdfa6 100644 --- a/MC1/Resources/Localization/fr.lproj/Settings.strings +++ b/MC1/Resources/Localization/fr.lproj/Settings.strings @@ -1169,6 +1169,15 @@ /* 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."; +/* Picker label for attempts before resetting the contact's out path */ +"directMessages.directAttempts" = "Tentatives initiales"; + +/* Picker label for extra attempts after the contact's out path reset */ +"directMessages.floodAttempts" = "Tentatives de repli Flood"; + +/* Footer explaining the initial and fallback attempt pickers */ +"directMessages.attemptsFooter" = "Les tentatives initiales utilisent Flood si le contact n'a pas de chemin sortant. Le repli Flood tente de réinitialiser le chemin sortant avant les tentatives supplémentaires. Réglez les tentatives de repli Flood sur zéro pour ignorer la réinitialisation et les tentatives supplémentaires."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ diff --git a/MC1/Resources/Localization/it.lproj/Settings.strings b/MC1/Resources/Localization/it.lproj/Settings.strings index 8d27fcdf87..aae42f46b2 100644 --- a/MC1/Resources/Localization/it.lproj/Settings.strings +++ b/MC1/Resources/Localization/it.lproj/Settings.strings @@ -1219,6 +1219,15 @@ /* 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."; +/* Picker label for attempts before resetting the contact's out path */ +"directMessages.directAttempts" = "Tentativi iniziali"; + +/* Picker label for extra attempts after the contact's out path reset */ +"directMessages.floodAttempts" = "Tentativi di ripiego flood"; + +/* Footer explaining the initial and fallback attempt pickers */ +"directMessages.attemptsFooter" = "I tentativi iniziali usano l’instradamento flood se il contatto non ha un percorso in uscita. Il ripiego flood prova a reimpostare il percorso in uscita prima dei tentativi extra. Imposta Tentativi di ripiego flood a zero per saltare la reimpostazione del percorso in uscita e i tentativi extra."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ diff --git a/MC1/Resources/Localization/ko.lproj/Settings.strings b/MC1/Resources/Localization/ko.lproj/Settings.strings index 5e40350e76..cae2d8a78f 100644 --- a/MC1/Resources/Localization/ko.lproj/Settings.strings +++ b/MC1/Resources/Localization/ko.lproj/Settings.strings @@ -1209,6 +1209,15 @@ /* Footer explaining the acknowledgments setting */ "directMessages.footer" = "다이렉트 메시지당 보내는 확인 응답 수입니다. 불안정한 링크에서 전달 확인을 개선하려면 2를 사용하십시오."; +/* Picker label for attempts before resetting the contact's out path */ +"directMessages.directAttempts" = "초기 시도"; + +/* Picker label for extra attempts after the contact's out path reset */ +"directMessages.floodAttempts" = "플러드 대체 시도"; + +/* Footer explaining the initial and fallback attempt pickers */ +"directMessages.attemptsFooter" = "초기 시도는 연락처에 발신 경로가 없으면 플러드 라우팅을 사용합니다. 플러드 대체는 추가 시도 전에 발신 경로를 재설정하려고 합니다. 경로 재설정과 추가 시도를 건너뛰려면 플러드 대체 시도를 0으로 설정하십시오."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ diff --git a/MC1/Resources/Localization/nl.lproj/Settings.strings b/MC1/Resources/Localization/nl.lproj/Settings.strings index d3556ae957..10c56ed886 100644 --- a/MC1/Resources/Localization/nl.lproj/Settings.strings +++ b/MC1/Resources/Localization/nl.lproj/Settings.strings @@ -1169,6 +1169,15 @@ /* Footer explaining the acknowledgments setting */ "directMessages.footer" = "Aantal bevestigingen dat per direct bericht wordt verstuurd. Gebruik 2 voor betere afleverbevestiging via onbetrouwbare verbindingen."; +/* Picker label for attempts before resetting the contact's out path */ +"directMessages.directAttempts" = "Eerste pogingen"; + +/* Picker label for extra attempts after the contact's out path reset */ +"directMessages.floodAttempts" = "Flood-terugvalpogingen"; + +/* Footer explaining the initial and fallback attempt pickers */ +"directMessages.attemptsFooter" = "De eerste pogingen gebruiken Flood als het contact geen uitgaand pad heeft. De Flood-terugval probeert het uitgaande pad te resetten voordat de extra pogingen beginnen. Zet Flood-terugvalpogingen op nul om het resetten van het uitgaande pad en de extra pogingen over te slaan."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ diff --git a/MC1/Resources/Localization/pl.lproj/Settings.strings b/MC1/Resources/Localization/pl.lproj/Settings.strings index 999623b153..975e1f1173 100644 --- a/MC1/Resources/Localization/pl.lproj/Settings.strings +++ b/MC1/Resources/Localization/pl.lproj/Settings.strings @@ -1169,6 +1169,15 @@ /* 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."; +/* Picker label for attempts before resetting the contact's out path */ +"directMessages.directAttempts" = "Próby początkowe"; + +/* Picker label for extra attempts after the contact's out path reset */ +"directMessages.floodAttempts" = "Próby zapasowe Flood"; + +/* Footer explaining the initial and fallback attempt pickers */ +"directMessages.attemptsFooter" = "Próby początkowe używają Flood, gdy kontakt nie ma ścieżki wychodzącej. Przed dodatkowymi próbami zapasowy Flood próbuje zresetować ścieżkę wychodzącą. Ustaw próby zapasowe Flood na 0, aby pominąć resetowanie ścieżki wychodzącej i dodatkowe próby."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ diff --git a/MC1/Resources/Localization/pt.lproj/Settings.strings b/MC1/Resources/Localization/pt.lproj/Settings.strings index 105fd6b445..4fb1171078 100644 --- a/MC1/Resources/Localization/pt.lproj/Settings.strings +++ b/MC1/Resources/Localization/pt.lproj/Settings.strings @@ -1219,6 +1219,15 @@ /* 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."; +/* Picker label for attempts before resetting the contact's out path */ +"directMessages.directAttempts" = "Tentativas iniciais"; + +/* Picker label for extra attempts after the contact's out path reset */ +"directMessages.floodAttempts" = "Tentativas de recurso por difusão"; + +/* Footer explaining the initial and fallback attempt pickers */ +"directMessages.attemptsFooter" = "As tentativas iniciais usam a difusão se o contacto não tiver rota de saída. Com a opção «Tentativas de recurso por difusão», a app tenta repor a rota de saída antes de tentar novamente. Use 0 nessa opção para não repor a rota de saída nem fazer as tentativas extra."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ diff --git a/MC1/Resources/Localization/ru.lproj/Settings.strings b/MC1/Resources/Localization/ru.lproj/Settings.strings index a8be1bbf4f..fe3aa8caac 100644 --- a/MC1/Resources/Localization/ru.lproj/Settings.strings +++ b/MC1/Resources/Localization/ru.lproj/Settings.strings @@ -1169,6 +1169,15 @@ /* Footer explaining the acknowledgments setting */ "directMessages.footer" = "Количество подтверждений, отправляемых на каждое прямое сообщение. Используйте 2 для лучшего подтверждения доставки по ненадёжным каналам."; +/* Picker label for attempts before resetting the contact's out path */ +"directMessages.directAttempts" = "Начальные попытки"; + +/* Picker label for extra attempts after the contact's out path reset */ +"directMessages.floodAttempts" = "Запасные попытки Flood"; + +/* Footer explaining the initial and fallback attempt pickers */ +"directMessages.attemptsFooter" = "Начальные попытки используют Flood, если у контакта нет исходящего пути. Исходящий путь пытаются сбросить перед запасными попытками Flood. Установите «Запасные попытки Flood» на 0, чтобы пропустить сброс и дополнительные попытки."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ diff --git a/MC1/Resources/Localization/uk.lproj/Settings.strings b/MC1/Resources/Localization/uk.lproj/Settings.strings index 54cacb7303..b26d02b0db 100644 --- a/MC1/Resources/Localization/uk.lproj/Settings.strings +++ b/MC1/Resources/Localization/uk.lproj/Settings.strings @@ -1169,6 +1169,15 @@ /* Footer explaining the acknowledgments setting */ "directMessages.footer" = "Кількість підтверджень, що надсилаються на кожне особисте повідомлення. Використовуйте 2 для кращого підтвердження доставки через ненадійні з'єднання."; +/* Picker label for attempts before resetting the contact's out path */ +"directMessages.directAttempts" = "Початкові спроби"; + +/* Picker label for extra attempts after the contact's out path reset */ +"directMessages.floodAttempts" = "Запасні спроби Flood"; + +/* Footer explaining the initial and fallback attempt pickers */ +"directMessages.attemptsFooter" = "Початкові спроби використовують Flood, якщо контакт не має вихідного шляху. Робиться спроба скинути вихідний шлях перед запасними спробами Flood. Встановіть «Запасні спроби Flood» на нуль, щоб пропустити скидання вихідного шляху та запасні спроби."; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings index e77a6e9933..44432be9a0 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings @@ -1204,6 +1204,15 @@ /* Footer explaining the acknowledgments setting */ "directMessages.footer" = "每条私信发送的确认数量。在不可靠的链路上使用 2 以获得更好的送达确认。"; +/* Picker label for attempts before resetting the contact's out path */ +"directMessages.directAttempts" = "初始尝试"; + +/* Picker label for extra attempts after the contact's out path reset */ +"directMessages.floodAttempts" = "泛洪回退尝试"; + +/* Footer explaining the initial and fallback attempt pickers */ +"directMessages.attemptsFooter" = "初始尝试在联系人没有出站路径时使用泛洪。泛洪回退将先尝试重置出站路径,再进行额外尝试。将“泛洪回退尝试”设为 0 以跳过重置出站路径和额外尝试。"; + // MARK: - BLE Status Indicator /* Menu item to send a zero-hop advertisement */ diff --git a/MC1/Views/Settings/Sections/DirectMessagesSettingsSection.swift b/MC1/Views/Settings/Sections/DirectMessagesSettingsSection.swift index 88b389c9cf..661f465e12 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 @@ -22,10 +25,24 @@ struct DirectMessagesSettingsSection: View { } .pickerStyle(.menu) .radioDisabled(for: appState.connectionState, or: isSaving) + + Picker(L10n.Settings.DirectMessages.directAttempts, selection: directAttemptsBinding) { + ForEach(Array(DMSendBudget.directRange), id: \.self) { count in + Text(String(count)).tag(count) + } + } + .pickerStyle(.menu) + + Picker(L10n.Settings.DirectMessages.floodAttempts, selection: floodAttemptsBinding) { + ForEach(Array(DMSendBudget.floodRange), id: \.self) { count in + Text(String(count)).tag(count) + } + } + .pickerStyle(.menu) } header: { Text(L10n.Settings.DirectMessages.header) } footer: { - Text(L10n.Settings.DirectMessages.footer) + Text(L10n.Settings.DirectMessages.footer + "\n\n" + L10n.Settings.DirectMessages.attemptsFooter) } .themedRowBackground(theme) .errorAlert($errorMessage) @@ -34,6 +51,20 @@ struct DirectMessagesSettingsSection: View { // MARK: - Binding + private var directAttemptsBinding: Binding { + Binding( + get: { DMSendBudget.clampedDirectAttempts(storedDirectAttempts) }, + set: { storedDirectAttempts = DMSendBudget.clampedDirectAttempts($0) } + ) + } + + private var floodAttemptsBinding: Binding { + Binding( + get: { DMSendBudget.clampedFloodAttempts(storedFloodAttempts) }, + set: { storedFloodAttempts = DMSendBudget.clampedFloodAttempts($0) } + ) + } + private var acksBinding: Binding { Binding( get: { Int(device?.multiAcks ?? 0) + 1 }, 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/PendingSend.swift b/MC1Services/Sources/MC1Services/Models/PendingSend.swift index b7076bcefa..49314ae918 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,29 +27,10 @@ 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. For queued rows, 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? /// Non-nil ACK metadata changes this row from queued work to delivery tracking without retransmission. @@ -104,7 +54,8 @@ public final class PendingSend { attemptCount: Int? = nil, ackCodes: [Data]? = nil, ackSentAt: Date? = nil, - ackDeadline: Date? = nil + ackDeadline: Date? = nil, + isSingleAttempt: Bool = false ) { self.id = id self.radioID = radioID @@ -113,6 +64,7 @@ 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 @@ -129,25 +81,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 @@ -156,15 +96,13 @@ 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? public let ackCodes: [Data]? public let ackSentAt: Date? @@ -186,7 +124,8 @@ public struct PendingSendDTO: Sendable, Hashable, Identifiable { attemptCount: Int? = 0, ackCodes: [Data]? = nil, ackSentAt: Date? = nil, - ackDeadline: Date? = nil + ackDeadline: Date? = nil, + isSingleAttempt: Bool = false ) { self.id = id self.radioID = radioID @@ -195,6 +134,7 @@ 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 @@ -225,7 +165,8 @@ public extension PendingSend { attemptCount: dto.attemptCount, ackCodes: dto.ackCodes, ackSentAt: dto.ackSentAt, - ackDeadline: dto.ackDeadline + ackDeadline: dto.ackDeadline, + isSingleAttempt: dto.isSingleAttempt ) } @@ -246,7 +187,8 @@ public extension PendingSend { attemptCount: attemptCount, ackCodes: ackCodes, ackSentAt: ackSentAt, - ackDeadline: ackDeadline + ackDeadline: ackDeadline, + isSingleAttempt: isSingleAttempt ) } } diff --git a/MC1Services/Sources/MC1Services/Models/PendingSendEnvelope.swift b/MC1Services/Sources/MC1Services/Models/PendingSendEnvelope.swift index d410d2b115..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, ackDeadline == nil, let contactID else { return nil } - return DirectMessageEnvelope(messageID: messageID, contactID: contactID, isResend: isResend) + return DirectMessageEnvelope( + messageID: messageID, contactID: contactID, isResend: isResend, isSingleAttempt: isSingleAttempt + ) } func channelMessageEnvelope() -> ChannelMessageEnvelope? { @@ -23,15 +22,7 @@ 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(), @@ -42,15 +33,7 @@ public extension PendingSendDTO { 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, @@ -66,7 +49,8 @@ public extension PendingSendDTO { enqueuedAt: enqueuedAt, ackCodes: ackCodes, ackSentAt: ackSentAt, - ackDeadline: ackDeadline + ackDeadline: ackDeadline, + isSingleAttempt: envelope.isSingleAttempt ) } @@ -76,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/ServiceContainer.swift b/MC1Services/Sources/MC1Services/ServiceContainer.swift index 3dfd06fcab..61b39ec967 100644 --- a/MC1Services/Sources/MC1Services/ServiceContainer.swift +++ b/MC1Services/Sources/MC1Services/ServiceContainer.swift @@ -98,6 +98,8 @@ public final class ServiceContainer { /// 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 @@ -198,12 +200,16 @@ public final class ServiceContainer { cleanupCoordinator: cleanupCoordinator ) contactRadioOwner.bind(contactService) + let plainTextSendGate = PlainTextSendGate() + self.plainTextSendGate = plainTextSendGate messageService = MessageService( session: session, dataStore: dataStore, contactService: contactService, config: messageConfig, - ackEvents: ackEvents + ackEvents: ackEvents, + dmSendBudget: { DMSendBudget.current() }, + plainTextSendGate: plainTextSendGate ) channelService = ChannelService( session: session, @@ -252,7 +258,8 @@ public final class ServiceContainer { session: session, remoteNodeService: remoteNodeService, dataStore: dataStore, - radioID: radioID + radioID: radioID, + plainTextSendGate: plainTextSendGate ) chatSendQueueService = ChatSendQueueService( @@ -260,7 +267,8 @@ public final class ServiceContainer { dataStore: dataStore, messageService: messageService, channelService: channelService, - reactionService: reactionService + reactionService: reactionService, + plainTextSendGate: plainTextSendGate ) notificationActionHandler = NotificationActionHandler( dataStore: dataStore, @@ -419,6 +427,7 @@ public final class ServiceContainer { } private func performTearDown() async { + await plainTextSendGate.invalidate() await remoteNodeService.beginRetirement() await messageService.retireInlineSends() await messageService.waitForAcknowledgementSaves() @@ -459,6 +468,7 @@ public final class ServiceContainer { func prepareForIdentityImport() async { isTornDown = true + await plainTextSendGate.invalidate() await messageService.retireInlineSends() await remoteNodeService.retire() await chatSendQueueService.shutdown() diff --git a/MC1Services/Sources/MC1Services/Services/AckCodeBuilder.swift b/MC1Services/Sources/MC1Services/Services/AckCodeBuilder.swift index aff48310de..9857003e9e 100644 --- a/MC1Services/Sources/MC1Services/Services/AckCodeBuilder.swift +++ b/MC1Services/Sources/MC1Services/Services/AckCodeBuilder.swift @@ -4,38 +4,11 @@ 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 { static func expectedAck( timestamp: UInt32, @@ -44,8 +17,8 @@ enum AckCodeBuilder { senderPublicKey: Data ) -> 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 < 8, + "DM attempt bytes run 0...7; 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/AppStorageKey.swift b/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift index 1db97245a3..c32c8c668d 100644 --- a/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift +++ b/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift @@ -54,6 +54,10 @@ 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 case lastStaleCleanupDate case frequentEmojis case recentReactionEmojis @@ -105,6 +109,8 @@ 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 /// `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/BackupUserDefaults.swift b/MC1Services/Sources/MC1Services/Services/BackupUserDefaults.swift index 21741b50d7..58c733be30 100644 --- a/MC1Services/Sources/MC1Services/Services/BackupUserDefaults.swift +++ b/MC1Services/Sources/MC1Services/Services/BackupUserDefaults.swift @@ -27,6 +27,8 @@ 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 discoverySortOrder: String? public var nodesSortOrder: String? public var tracePathViewMode: String? @@ -58,19 +60,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" @@ -168,6 +168,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 +199,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 +242,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/ChatSendQueueService.swift b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift index 7ad94e7837..10a8026a0b 100644 --- a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift +++ b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift @@ -100,7 +100,8 @@ public final class ChatSendQueueService { messageService: MessageService, channelService: ChannelService, reactionService: ReactionService, - config: ChatSendQueueConfig = .default + config: ChatSendQueueConfig = .default, + plainTextSendGate: PlainTextSendGate? = nil ) { self.radioID = radioID self.config = config @@ -138,17 +139,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, @@ -158,10 +171,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( @@ -170,11 +181,14 @@ 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, @@ -185,21 +199,15 @@ public final class ChatSendQueueService { } do { - let message: MessageDTO = if envelope.isResend { - try await messageServiceRef.resendDirectMessage( - messageID: envelope.messageID, - to: contact, - preserveTimestamp: preserveTimestamp, - pendingSendID: pendingSendID - ) - } else { - try await messageServiceRef.sendPendingDirectMessage( - messageID: envelope.messageID, - to: contact, - preserveTimestamp: preserveTimestamp, - pendingSendID: pendingSendID - ) - } + 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 != .sent, let pendingSendID { try? await dataStoreRef.deletePendingSend(id: pendingSendID) } @@ -230,6 +238,8 @@ 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 { @@ -766,6 +776,10 @@ public final class ChatSendQueueService { 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() diff --git a/MC1Services/Sources/MC1Services/Services/DMSendBudget.swift b/MC1Services/Sources/MC1Services/Services/DMSendBudget.swift new file mode 100644 index 0000000000..0da24044ed --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/DMSendBudget.swift @@ -0,0 +1,47 @@ +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 + + 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/MessageService+ACKRecovery.swift b/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift index 57cc701c3e..955fb45d0f 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift @@ -8,6 +8,7 @@ enum PendingAcknowledgementCommit { 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 } @@ -16,12 +17,21 @@ extension MessageService { try await dataStore.deletePendingSend(id: row.id) continue } - pendingAcks[row.messageID] = PendingAck( + restored[row.messageID] = PendingAck( messageID: row.messageID, contactID: contactID, ackCodes: Set(codes), sentAt: sentAt, timeout: deadline.timeIntervalSince(sentAt), pendingSendID: row.id, deadline: deadline ) } + let now = Date() + for (id, tracking) in restored { + if let deadline = tracking.deadline, deadline > now { + restored[id]?.sendLeaseID = tracking.pendingSendID + } + } + // Reserve recovered ACK owners before hydration can admit another send. + await plainTextSendGate?.reserveRestoredAcks(Set(restored.values.compactMap(\.sendLeaseID))) + pendingAcks.merge(restored) { _, restored in restored } } func persistAcknowledgement( @@ -48,7 +58,9 @@ extension MessageService { } noteAcknowledgementSaveCommitted(messageID) guard saved else { - removePendingAckIfCurrent(tracking) + if removePendingAckIfCurrent(tracking) { + await settlePlainTextLease(tracking.sendLeaseID) + } return false } #if DEBUG @@ -85,12 +97,14 @@ extension MessageService { return .waitingForOwner } let status: MessageStatus = current.matchedAckCode == nil ? .failed : .delivered + let leaseID = current.sendLeaseID let updated = try await writeTerminalAcknowledgement(current, status: status) guard pendingAcks[messageID]?.sentAt == sentAt else { return updated ? .committed(status) : .unchanged } guard updated else { pendingAcks.removeValue(forKey: messageID) + await settlePlainTextLease(leaseID) return .unchanged } pendingAcks[messageID]?.isDelivered = true @@ -103,6 +117,7 @@ extension MessageService { } let tripTime = pendingAcks[messageID]?.matchedTripTime pendingAcks.removeValue(forKey: messageID) + await settlePlainTextLease(leaseID) switch status { case .delivered: statusEventBroadcaster.yield(.statusResolved(messageID: messageID, status: .delivered, roundTripTime: tripTime)) 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+SendDM.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift index 360c9b868c..0850caef23 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift @@ -3,35 +3,9 @@ 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, @@ -57,13 +31,51 @@ 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) } + var ackOwnerCommitted = false + defer { + if !ackOwnerCommitted { + // 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.incrementPendingSendAttemptCount(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 } @@ -73,15 +85,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. + // Keep speculative tracking alive until the command returns its ACK timeout. 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) { @@ -92,7 +104,7 @@ extension MessageService { ) } } catch { - pendingAcks.removeValue(forKey: messageID) + await discardTrackedAck(messageID: messageID) throw error } } catch { @@ -114,19 +126,22 @@ extension MessageService { messageID: messageID, contactID: contact.id, ackCode: sentInfo.expectedAck, - timeout: ackTimeout + timeout: ackTimeout, + sendLeaseID: sendLease?.id ) } else { pendingAcks[messageID]?.timeout = ackTimeout pendingAcks[messageID]?.sentAt = Date() } - // 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. + // The radio accepted the send; bookkeeping errors must leave terminal status + // to the end-to-end ACK or expiry checker. do { - _ = try await persistAcknowledgement(messageID: messageID, radioID: contact.radioID, pendingSendID: nil) + if try await persistAcknowledgement( + messageID: messageID, radioID: contact.radioID, pendingSendID: pendingSendID + ) { + ackOwnerCommitted = true + } // updateMessageAck preserves `.delivered`, so writing `.sent` here // is a no-op when the listener already won the race. try await dataStore.updateMessageAck( @@ -148,46 +163,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, @@ -196,6 +174,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) @@ -228,7 +208,9 @@ extension MessageService { text: text, timestamp: Date(timeIntervalSince1970: TimeInterval(timestamp)), timestampRaw: timestamp, - timeout: timeout > 0 ? timeout : nil + timeout: timeout > 0 ? timeout : nil, + budget: dmSendBudgetProvider(), + sendLease: sendLease ) return try await finalizeSend( @@ -257,7 +239,7 @@ extension MessageService { /// - replyToID: Optional ID of message being replied to /// /// - Returns: The created message DTO with pending status - public func createPendingMessage( + func createPendingMessage( text: String, to contact: ContactDTO, textType: TextType = .plain, @@ -293,7 +275,7 @@ extension MessageService { /// 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( + func sendPendingDirectMessage( messageID: UUID, to contact: ContactDTO, preserveTimestamp: Bool = false, @@ -304,7 +286,9 @@ extension MessageService { to: contact, preserveTimestamp: preserveTimestamp, isResend: false, - pendingSendID: pendingSendID + isSingleAttempt: false, + pendingSendID: pendingSendID, + sendLease: nil ) } @@ -316,7 +300,7 @@ extension MessageService { /// 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( + func resendDirectMessage( messageID: UUID, to contact: ContactDTO, preserveTimestamp: Bool = false, @@ -327,17 +311,24 @@ extension MessageService { to: contact, preserveTimestamp: preserveTimestamp, isResend: true, - pendingSendID: pendingSendID + isSingleAttempt: false, + pendingSendID: pendingSendID, + sendLease: nil ) } - private func performQueuedDirectMessageSend( + internal func performQueuedDirectMessageSend( messageID: UUID, to contact: ContactDTO, preserveTimestamp: Bool, isResend: Bool, - pendingSendID: UUID? + 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") @@ -351,6 +342,9 @@ 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 @@ -377,7 +371,9 @@ extension MessageService { text: existingMessage.text, timestamp: wireTimestamp, timestampRaw: wireTimestampRaw, - timeout: nil + timeout: nil, + budget: isSingleAttempt ? .singleAttempt : dmSendBudgetProvider(), + sendLease: sendLease ) // Bump only on a confirmed successful resend so sendCount counts @@ -413,7 +409,7 @@ 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() } if case MessageServiceError.persistenceError = error { throw error } @@ -423,31 +419,6 @@ extension MessageService { // 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( messageID: UUID, contactID: UUID, @@ -456,32 +427,33 @@ extension MessageService { text: String, timestamp: Date, timestampRaw: UInt32, - timeout: TimeInterval? + timeout: TimeInterval?, + budget: DMSendBudget, + sendLease: PlainTextSendGate.Lease? ) async throws -> MessageSentInfo? { - var attempts = 0 - var floodAttempts = 0 - var isFloodMode = false + let maxRetryAttempts = budget.totalAttempts - 1 - while attempts < config.maxAttempts, !isFloodMode || floodAttempts < config.maxFloodAttempts { - // Check for task cancellation + for attemptIndex in 0.. 0 { + if attemptIndex > 0 { try await dataStore.updateMessageRetryStatus( id: messageID, status: .retrying, - retryAttempt: attempts - 1, - maxRetryAttempts: config.maxAttempts - 1 + retryAttempt: attemptIndex - 1, + maxRetryAttempts: maxRetryAttempts ) - statusEventBroadcaster.yield(.retrying(messageID: messageID, attempt: attempts - 1, maxAttempts: config.maxAttempts - 1)) + statusEventBroadcaster.yield(.retrying( + messageID: messageID, + attempt: attemptIndex - 1, + maxAttempts: maxRetryAttempts + )) } - // Switch to flood routing after floodAfter direct attempts - if attempts == config.floodAfter, !isFloodMode { - logger.info("Resetting path to flood after \(attempts) failed attempts") + if attemptIndex == budget.directAttempts { + logger.info("Resetting path to flood after \(attemptIndex) failed attempts") do { if let contactService { try await contactService.resetPath(radioID: radioID, publicKey: publicKey) @@ -494,20 +466,16 @@ extension MessageService { 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)") + if attemptIndex > 0 { + logger.info("Retry sending message: attempt \(attemptIndex + 1)/\(budget.totalAttempts)") } // Precompute the expected ACK CRC before the send so the persistent @@ -518,7 +486,7 @@ extension MessageService { let predictedAck = AckCodeBuilder.expectedAck( timestamp: timestampRaw, - attempt: UInt8(attempts), + attempt: UInt8(attemptIndex), text: text, senderPublicKey: senderPublicKey ) @@ -532,8 +500,10 @@ extension MessageService { messageID: messageID, contactID: contactID, ackCode: predictedAck, - timeout: preSendTimeout + timeout: preSendTimeout, + sendLeaseID: sendLease?.id ) + await notePlainTextLease(sendLease) let sentInfo: MessageSentInfo do { @@ -542,14 +512,14 @@ extension MessageService { to: publicKey.prefix(6), text: text, timestamp: timestamp, - attempt: UInt8(attempts) + attempt: UInt8(attemptIndex) ) } } 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) + await discardTrackedAck(messageID: messageID) throw error } @@ -569,13 +539,14 @@ extension MessageService { if sentInfo.expectedAck != predictedAck { logger.warning( - "expectedAck mismatch for \(messageID) attempt \(attempts): predicted \(predictedAck.uppercaseHexString()) vs firmware \(sentInfo.expectedAck.uppercaseHexString()); merging firmware code" + "expectedAck mismatch for \(messageID) attempt \(attemptIndex): predicted \(predictedAck.uppercaseHexString()) vs firmware \(sentInfo.expectedAck.uppercaseHexString()); merging firmware code" ) trackPendingAck( messageID: messageID, contactID: contactID, ackCode: sentInfo.expectedAck, - timeout: ackTimeout + timeout: ackTimeout, + sendLeaseID: sendLease?.id ) } else { // Re-stamp sentAt so checkExpiredAcks measures timeout from @@ -590,7 +561,7 @@ extension MessageService { ) if ackEvent != nil { - logger.info("Message acknowledged on attempt \(attempts + 1)") + logger.info("Message acknowledged on attempt \(attemptIndex + 1)") return sentInfo } @@ -600,15 +571,9 @@ extension MessageService { 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") + logger.warning("Message delivery failed after \(budget.totalAttempts) attempts") return nil } @@ -662,7 +627,13 @@ extension MessageService { /// 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) { + internal func trackPendingAck( + messageID: UUID, + contactID: UUID, + ackCode: Data, + timeout: TimeInterval, + sendLeaseID: UUID? = nil + ) { // 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 @@ -677,6 +648,9 @@ extension MessageService { existing.timeout = timeout existing.pendingSendID = nil existing.deadline = nil + if let sendLeaseID { + existing.sendLeaseID = sendLeaseID + } pendingAcks[messageID] = existing } else { pendingAcks[messageID] = PendingAck( @@ -684,7 +658,8 @@ extension MessageService { contactID: contactID, ackCodes: [ackCode], sentAt: Date(), - timeout: timeout + timeout: timeout, + sendLeaseID: sendLeaseID ) } } @@ -694,7 +669,7 @@ extension MessageService { guard text.utf8.count <= ProtocolLimits.maxDirectMessageLength else { throw MessageServiceError.messageTooLong } } - func finalizeSend( + internal func finalizeSend( messageID: UUID, contactID: UUID, radioID: UUID, @@ -713,11 +688,15 @@ extension MessageService { let tracking = pendingAcks[messageID] if tracking == nil || tracking?.isDelivered == true { + let leaseID = tracking?.sendLeaseID pendingAcks.removeValue(forKey: messageID) + await settlePlainTextLease(leaseID) } else if let sentInfo { // The retry loop's waitForEvent matched the ACK. Take ownership and // record the legitimate `.sent` -> `.delivered` upgrade. + let leaseID = tracking?.sendLeaseID pendingAcks.removeValue(forKey: messageID) + await settlePlainTextLease(leaseID) try await dataStore.updateMessageAck( id: messageID, ackCode: sentInfo.expectedAck.ackCodeUInt32, diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+SendHelpers.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendHelpers.swift index 521e2ff6f8..4f611fc3cb 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendHelpers.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendHelpers.swift @@ -39,7 +39,7 @@ func withPoolBackoff( extension MessageService { func failMessageAndRethrow(_ error: Error, messageID: UUID, pendingSendID: UUID? = nil) async throws -> Never { - pendingAcks.removeValue(forKey: messageID) + 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 diff --git a/MC1Services/Sources/MC1Services/Services/MessageService.swift b/MC1Services/Sources/MC1Services/Services/MessageService.swift index b10f57e728..b5adc164df 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. @@ -132,12 +135,16 @@ public actor MessageService { dataStore: any PersistenceStoreProtocol, contactService: ContactService?, config: MessageServiceConfig = .default, - ackEvents: AsyncStream? = nil + 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 } diff --git a/MC1Services/Sources/MC1Services/Services/MessageServiceConfig.swift b/MC1Services/Sources/MC1Services/Services/MessageServiceConfig.swift index ebfbaa0043..150a245e31 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageServiceConfig.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageServiceConfig.swift @@ -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/PendingAck.swift b/MC1Services/Sources/MC1Services/Services/PendingAck.swift index b98e534f47..b40be2d6b2 100644 --- a/MC1Services/Sources/MC1Services/Services/PendingAck.swift +++ b/MC1Services/Sources/MC1Services/Services/PendingAck.swift @@ -6,7 +6,7 @@ import Foundation /// 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. +/// Only DMs are tracked here. `RoomServerService` waits for room post ACKs separately. struct PendingAck { let messageID: UUID let contactID: UUID @@ -22,4 +22,6 @@ struct PendingAck { /// Set when an acknowledgement matches and kept until the terminal save commits. var matchedAckCode: UInt32? var matchedTripTime: UInt32? + /// Admission lease for this ACK. A restored live ACK uses its persisted owner ID. + var sendLeaseID: UUID? } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+PendingSends.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+PendingSends.swift index b4d447318b..aeb6534445 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+PendingSends.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+PendingSends.swift @@ -30,6 +30,7 @@ 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 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/RoomServerService.swift b/MC1Services/Sources/MC1Services/Services/RoomServerService.swift index 2e4a9fbd1a..b7eb0b8010 100644 --- a/MC1Services/Sources/MC1Services/Services/RoomServerService.swift +++ b/MC1Services/Sources/MC1Services/Services/RoomServerService.swift @@ -44,8 +44,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,6 +55,9 @@ 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( @@ -60,13 +65,13 @@ public actor RoomServerService { remoteNodeService: RemoteNodeService, dataStore: any PersistenceStoreProtocol, radioID: UUID, - config: MessageServiceConfig = MessageServiceConfig() + plainTextSendGate: PlainTextSendGate? = nil ) { self.session = session self.remoteNodeService = remoteNodeService self.dataStore = dataStore self.radioID = radioID - self.config = config + self.plainTextSendGate = plainTextSendGate } /// Set self public key prefix from SelfInfo. @@ -194,13 +199,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 +214,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 +226,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 +254,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 +262,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 +308,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 diff --git a/MC1Services/Sources/MC1Services/Services/SendQueue.swift b/MC1Services/Sources/MC1Services/Services/SendQueue.swift index 42f38e903f..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 diff --git a/MC1Services/Tests/MC1ServicesTests/AppBackupEnvelopeTests.swift b/MC1Services/Tests/MC1ServicesTests/AppBackupEnvelopeTests.swift index e01d665725..2b1459258b 100644 --- a/MC1Services/Tests/MC1ServicesTests/AppBackupEnvelopeTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/AppBackupEnvelopeTests.swift @@ -307,6 +307,66 @@ 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 `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/BackupIntegrationTests+PendingAcknowledgements.swift b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests+PendingAcknowledgements.swift index 058611c021..1a69a81813 100644 --- a/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests+PendingAcknowledgements.swift +++ b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests+PendingAcknowledgements.swift @@ -13,7 +13,7 @@ extension BackupIntegrationTests { try await source.saveMessage(message) let sentAt = Date() let owner = PendingSendDTO( - envelope: DirectMessageEnvelope(messageID: message.id, contactID: contact.id), radioID: radioID, + 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)) @@ -25,6 +25,7 @@ extension BackupIntegrationTests { #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)) @@ -32,5 +33,6 @@ extension BackupIntegrationTests { #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 b3621efafc..c407d73de9 100644 --- a/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift @@ -4128,6 +4128,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 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/Mocks/MockPersistenceStore.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift index d822b75ae1..2e541a52b1 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift @@ -2654,7 +2654,8 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { attemptCount: dto.attemptCount, ackCodes: dto.ackCodes, ackSentAt: dto.ackSentAt, - ackDeadline: dto.ackDeadline + ackDeadline: dto.ackDeadline, + isSingleAttempt: dto.isSingleAttempt ) pendingSends[dto.id] = assigned return nextSequence @@ -2665,10 +2666,30 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { 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, + 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 } - pendingSends[dto.id] = dto message.status = .sent messages[dto.messageID] = message return true @@ -2728,7 +2749,8 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { attemptCount: nextCount, ackCodes: row.ackCodes, ackSentAt: row.ackSentAt, - ackDeadline: row.ackDeadline + ackDeadline: row.ackDeadline, + isSingleAttempt: row.isSingleAttempt ) return (row.id, nextCount) } diff --git a/MC1Services/Tests/MC1ServicesTests/PendingSendPersistenceTests.swift b/MC1Services/Tests/MC1ServicesTests/PendingSendPersistenceTests.swift index 32e4783628..518b484236 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() 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/ChatSendQueueServiceReconnectTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceReconnectTests.swift index aa83e85ae3..d0064eef9d 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceReconnectTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceReconnectTests.swift @@ -109,7 +109,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/DMSendBudgetTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/DMSendBudgetTests.swift new file mode 100644 index 0000000000..0398208884 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/DMSendBudgetTests.swift @@ -0,0 +1,53 @@ +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) + } + + 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/MessageServiceACKRecoveryTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKRecoveryTests.swift index 84a4879d1d..6e5f22cea9 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKRecoveryTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKRecoveryTests.swift @@ -31,7 +31,7 @@ struct MessageServiceACKRecoveryTests { await original.services.chatSendQueueService.awaitDrainCompletion() let exhausted = try #require(await originalStore.fetchMessage(id: message.id)) #expect(exhausted.status == .sent) - #expect(await original.radio.sendCount == 5) + #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") @@ -59,6 +59,55 @@ struct MessageServiceACKRecoveryTests { 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 @@ -115,7 +164,7 @@ struct MessageServiceACKRecoveryTests { DirectMessageEnvelope(messageID: message.id, contactID: contact.id) ) try await waitUntil("queued owner save is held") { gate.isParked } - #expect(await original.radio.sendCount == 5) + #expect(await original.radio.sendCount == 8) let successor = try await successorAfterHeldSave( original: original, store: store, radioID: radioID, gate: gate ) @@ -183,7 +232,7 @@ struct MessageServiceACKRecoveryTests { #expect(message.status == .sent) await successor.services.messageService.stopAckExpiryChecking() let row = try #require(await store.fetchPendingSends(radioID: radioID).first) - #expect(row.attemptCount == 0) + #expect(row.attemptCount == 1) #expect(row.ackDeadline != nil) return HeldInlineSave( store: store, radioID: radioID, original: original, successor: successor, messageID: messageID diff --git a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceConfigTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceConfigTests.swift deleted file mode 100644 index de625426f7..0000000000 --- a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceConfigTests.swift +++ /dev/null @@ -1,18 +0,0 @@ -import Foundation -@testable import MC1Services -import Testing - -/// MessageServiceConfig guards against `maxAttempts > 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..e0d5c09a5f --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceDMBudgetTests.swift @@ -0,0 +1,154 @@ +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) + + @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 `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] + } + + 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 func answerCommands(on transport: MockTransport, after answered: Int, resetPathFails: Bool) 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])) + 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 4fb89dcd69..f43bf74602 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendDMBookkeepingTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendDMBookkeepingTests.swift @@ -86,7 +86,7 @@ struct MessageServiceSendDMBookkeepingTests { #expect(owner.messageID == accepted.id) #expect(owner.ackCodes?.contains(code) == true) #expect(owner.ackDeadline != nil) - #expect(owner.attemptCount == 0) + #expect(owner.attemptCount == 1) await store.setStubbedUpdateMessageStatusError(nil) await service.handleAcknowledgement(code: code, tripTime: 123) diff --git a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendTests.swift index 912f1d8103..4e34448d06 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendTests.swift @@ -771,12 +771,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 +884,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 +955,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 +999,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[.. 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.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..b471abb3d4 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+RadioHarness.swift @@ -0,0 +1,131 @@ +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) async throws { + 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(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), + 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(), + 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 = 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() } + } + + 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..bbbcfc5303 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+RadioScript.swift @@ -0,0 +1,60 @@ +import Foundation +import MeshCore +import MeshCoreTestSupport +import os + +extension PlainTextSendGateTests { + final class RadioScript: @unchecked Sendable { + private let hold = OSAllocatedUnfairLock(initialState: false) + private let table = OSAllocatedUnfairLock(initialState: [Data]()) + + func holdSendMessages(_ held: Bool) { + hold.withLock { $0 = held } + } + + func codes() -> [Data] { + table.withLock { $0 } + } + + func answer(_ transport: MockTransport) async { + var responded = 1 + 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 + let code = table.withLock { slots -> Data in + let sequence = UInt8(truncatingIfNeeded: slots.count) + let ack = 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: UInt32(10).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)) } + } + } + } +} 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/docs/Architecture.md b/docs/Architecture.md index 0ccbd4e380..1449a723d9 100644 --- a/docs/Architecture.md +++ b/docs/Architecture.md @@ -336,9 +336,9 @@ The service-layer packages use `nonisolated(unsafe)` only where Swift's isolatio 1. **User Action**: User types message in `ChatConversationView` and taps send. 2. **Service Call**: `MessageService.sendMessageWithRetry()` is called. 3. **Queue**: Message is saved to `PersistenceStore` with status `.pending`. -4. **Retry Loop**: `MessageService.sendMessageWithRetry()` attempts delivery using `MessageServiceConfig.default` (up to 5 attempts: 4 direct, switching to flood routing after 4 failed direct attempts, then 1 flood attempt). +4. **Retry Loop**: `MessageService.sendMessageWithRetry()` reads `DMSendBudget` once (default 4 attempts on the current out path, then one `resetPath` and 4 fallback attempts; the counter runs `1/7` through `7/7`). The radio chooses the route on every send. A queued send waits while the previous DM can still receive a late ACK. `RoomServerService` owns fixed room-post limits of 4 initial attempts and 1 fallback. 5. **ACK Tracking**: Each send attempt waits inline for ACK using `waitForEvent()` with configurable timeout. -6. **Completion**: ACK received -> `.delivered`, or all attempts exhausted -> `.failed`. +6. **Completion**: ACK received -> `.delivered`; exhausted attempts leave the DM `.sent` until an ACK arrives or the give-up deadline marks it `.failed`. --- diff --git a/docs/User_Guide.md b/docs/User_Guide.md index 81e4ce8eb8..5a074cd63f 100644 --- a/docs/User_Guide.md +++ b/docs/User_Guide.md @@ -111,8 +111,8 @@ Block unwanted contacts to prevent receiving messages from them: If a message fails to deliver: 1. Tap the **Retry** button that appears below the failed message. -2. The app re-attempts direct routing first, then falls back to flood routing (broadcast to all nearby nodes) only after the direct attempts are exhausted (by default, 4 direct attempts followed by 1 flood attempt). -3. You'll see retry progress: "Retrying 1/4...", "Retrying 2/4...", etc. +2. By default the app tries four times on the contact's current out path, then resets the out path and tries four more. The radio uses Flood when the contact has no out path. Set Flood Fallback Attempts to zero in Settings to skip the reset and extra attempts. A retry waits if another DM can still receive an ACK. +3. You'll see retry progress from "Retrying 1/7..." through "Retrying 7/7...". ### Group Channels diff --git a/docs/api/MC1Services.md b/docs/api/MC1Services.md index aeb949ab75..858df2a6fd 100644 --- a/docs/api/MC1Services.md +++ b/docs/api/MC1Services.md @@ -106,13 +106,10 @@ Handles message sending with automatic retry logic, flood routing fallback, and ### Configuration ```swift -struct MessageServiceConfig: Sendable { // internal; defined in MessageServiceConfig.swift - let floodFallbackOnRetry: Bool // Use flood on manual retry (default: true) - let maxAttempts: Int // Total attempts (default: 5; capped at 5 = 4 direct + 1 flood) - let maxFloodAttempts: Int // Max flood attempts (default: 1) - let floodAfter: Int // Switch to flood after N direct attempts (default: 4) +struct MessageServiceConfig { // internal; defined in MessageServiceConfig.swift + let floodFallbackOnRetry: Bool // Currently unused (default: true) let minTimeout: TimeInterval // Minimum timeout seconds (default: 0) - let triggerPathDiscoveryAfterFlood: Bool // Trigger path discovery after a successful flood + let triggerPathDiscoveryAfterFlood: Bool // Currently unused (default: true) let ackGiveUpWindow: TimeInterval // Give-up floor for the ACK deadline on fast presets let poolBackoff: PoolBackoffConfig // In-loop pool-exhaustion backoff tuning } @@ -158,10 +155,10 @@ The `ContactService` used for path management during retry is injected via `Mess ### Retry Flow -1. Direct routing for the first `floodAfter` attempts (using the contact's outbound path) -2. Flood routing thereafter (broadcast to all nearby nodes), up to `maxAttempts` (capped at 5 = 4 direct + 1 flood) -3. Returns immediately when ACK received -4. Marks failed if all attempts exhausted +1. DM loops read `DMSendBudget` once. The default is 4 attempts on the contact's current out path, then one `resetPath` and 4 fallback attempts. The counter runs `1/7` through `7/7`. Setting Flood Fallback Attempts to zero skips `resetPath`. +2. The fallback count is not the radio's routing mode. The radio chooses Direct or Flood on every send. `DMSendBudget.totalAttempts` is the sum of its bounded initial and fallback counts. Room posts use fixed limits owned by `RoomServerService` (4 initial attempts and 1 fallback). +3. Returns immediately when an ACK is received. A queued plain-text send waits while the previous one can still receive a late ACK. +4. On exhaustion a DM stays `.sent` until that ACK arrives or the give-up window ends. --- diff --git a/docs/guides/Messaging.md b/docs/guides/Messaging.md index 7a2515a35a..1a1ad3960b 100644 --- a/docs/guides/Messaging.md +++ b/docs/guides/Messaging.md @@ -23,8 +23,11 @@ This guide covers the message lifecycle, delivery states, retry logic, and ACK h │ SEND │ │ MessageService.sendMessageWithRetry() runs the │ │ app-layer retry loop (sendDirectMessageWithRetryLoop)│ -│ • Attempts 1-4: Direct routing │ -│ • Attempt 5: Flood routing (after floodAfter) │ +│ • Default: 4 on the current out path, then 4 │ +│ after one resetPath (counter 1/7 through 7/7) │ +│ • The radio chooses the route on every send │ +│ • A queued send waits while the previous DM can │ +│ still receive a late ACK │ │ • Message status: .sent, then .retrying per retry │ └──────────────────────────────────────────────────────┘ │ @@ -34,7 +37,7 @@ This guide covers the message lifecycle, delivery states, retry logic, and ACK h │ ACK RECEIVED │ │ ALL ATTEMPTS │ │ │ │ EXHAUSTED │ │ • Status: .delivered │ │ │ -│ • RTT recorded │ │ • Status: .failed │ +│ • RTT recorded │ │ • .sent, then .failed │ │ • UI updated │ │ • User can retry │ └─────────────────────────┘ └────────────────────────┘ ``` @@ -57,25 +60,29 @@ This guide covers the message lifecycle, delivery states, retry logic, and ACK h ### Automatic Retry (sendMessageWithRetry) -**File:** `MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift` (config in `MessageServiceConfig.swift`) +**File:** `MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift` (attempt counts in `DMSendBudget.swift`, timing in `MessageServiceConfig.swift`) -Default configuration (`MessageServiceConfig`): -- `floodFallbackOnRetry: true` - Currently unused; no send/retry code reads it. Both automatic and manual retries switch to flood after `floodAfter` direct attempts -- `maxAttempts: 5` - Total send attempts (capped at 5 = 4 direct + 1 flood) -- `maxFloodAttempts: 1` - Maximum flood attempts -- `floodAfter: 4` - Switch to flood after 4 direct attempts -- `minTimeout: 0` - Minimum timeout seconds -- `triggerPathDiscoveryAfterFlood: true` - Trigger path discovery after flood +A DM loop reads `DMSendBudget` once. The default is 4 attempts on the contact's current out path, then one `resetPath` and 4 fallback attempts. The bubble counter runs `1/7` through `7/7`. Setting Flood Fallback Attempts to zero leaves only the initial attempts and skips `resetPath`. The radio chooses Direct or Flood on every send. Initial attempts can use Flood when the contact has no out path, and later attempts can use Direct if the radio learns an out path after `resetPath`. + +`DMSendBudget` bounds initial attempts to 1...4 and fallback attempts to 0...4. Its total is the sum of those counts. Room posts use fixed limits owned by `RoomServerService`: 4 initial attempts and 1 fallback attempt, independent of the DM preference. + +`MessageServiceConfig` controls timing: + +- `floodFallbackOnRetry: true` - Currently unused; no send/retry code reads it +- `minTimeout: 0` - Minimum timeout seconds. DM loops still read this from `config` +- `triggerPathDiscoveryAfterFlood: true` - Currently unused; no send/retry code reads it - `ackGiveUpWindow: 30` - Floor and post-loop grace for the give-up deadline +Room posts share plain-text send admission with DMs. After admission, the app checks that the post still exists and the room still allows posting. Within a connection, distinct posts to the same room get increasing whole-second wire timestamps. Automatic retries reuse the post's wire timestamp. + ``` -Attempts 1-4: Direct routing (use contact's outPath) +Attempts 1-4: contact's current out path │ - ▼ Timeout, no ACK -Attempt 5: Flood routing (broadcast to all) + ▼ Timeout, no ACK, Flood Fallback Attempts > 0 +resetPath, then attempts 5-8 │ ▼ Timeout, no ACK -FAILED +Stays .sent until the ACK window ends ``` ### Direct vs Flood Routing @@ -93,14 +100,13 @@ FAILED ### Path Reset During Retry -When switching from direct to flood routing: +When Flood Fallback Attempts is greater than 0, the loop calls `resetPath` once before the fallback attempts: ```swift -// Reset path before flood attempt try await session.resetPath(publicKey: contact.publicKey) ``` -This clears the contact's cached routing path, forcing the mesh to rediscover the route. +This clears the contact's cached out path. The radio chooses the route for every later send. ### Automatic vs Manual Retry @@ -109,12 +115,12 @@ This clears the contact's cached routing path, forcing the mesh to rediscover th - The retry loop runs at the app layer in `sendDirectMessageWithRetryLoop`, not inside `MeshCoreSession`, so each attempt can emit UI feedback - After the first attempt fails, status moves to `.retrying` and a `.retrying` event is broadcast per subsequent attempt - No user interaction required -- If all attempts fail, status changes to `.failed` +- If the budget is spent with no ACK, the message stays `.sent` until the ACK window ends, then becomes `.failed` **Manual Retry:** - Triggered when user taps "Retry" button on a failed message - The UI's `retryMessage` replaces the `PendingSend` row (`replacePendingSendForRetry`), sets status to `.pending`, and signals the persistent send queue; it does not set `.retrying` immediately -- The queue drain later runs the same retry loop as an automatic send, which switches to flood after `floodAfter` (4) direct attempts; `.retrying` is only set by the loop after the first attempt fails +- The queue drain later runs the same retry loop as an automatic send. It reads `DMSendBudget` once after admission, so a picker change while the row is waiting applies to that loop. `.retrying` is only set by the loop after the first attempt fails. The row stays `.pending` with no counter until it is admitted, including while an earlier DM can still receive a late ACK - Retry button disappears while `.retrying` status is active ### Manual Retry Details @@ -133,7 +139,7 @@ coordinator?.applyStatusUpdate( try await signalDMEnqueued(envelope) ``` -The queue drain then calls `sendPendingDirectMessage` (or `resendDirectMessage` when the envelope is `isResend`), which runs `sendDirectMessageWithRetryLoop`. That loop marks `.retrying` via `updateMessageRetryStatus` only after the first attempt fails, and switches to flood after `floodAfter` (4) direct attempts; the same code path serves automatic and manual retries. +The queue drain calls `performQueuedDirectMessageSend`, which runs `sendDirectMessageWithRetryLoop`. That loop marks `.retrying` via `updateMessageRetryStatus` only after the first attempt fails. With the default budget it sends 4 attempts on the current out path, calls `resetPath` once, then sends 4 fallback attempts. The radio chooses the route on every send. The same code path serves automatic and manual retries. A queued send waits while the previous plain-text send can still receive a late ACK. The UI shows: - "Retrying %d/%d" text (current attempt / max attempts) with a spinner icon when `maxRetryAttempts > 0`, falling back to plain "Retrying..." only when `maxRetryAttempts == 0` @@ -156,6 +162,10 @@ struct PendingAck: Sendable { Keyed on `messageID`, not `ackCode`, so a late ACK from any retry attempt can still resolve the message. The `MessageService` persistent listener (`startEventMonitoring`) subscribes via `session.events(filter: .anyAcknowledgement)` so the dispatcher's ring buffer only holds matching events. +On reconnect, unexpired ACK owners recovered from `PendingSend` hold admission before the queue hydrates. Each reservation ends when its ACK is resolved or its deadline expires. + +Quick replies and DM reactions persist their single-attempt policy before waiting for admission. Recovery sends them once even when the configured DM budget allows more attempts. The attempt count is saved before the command, so recovery preserves the wire timestamp if transmission may have started. Delivered or failed inline sends are removed from the queue without another send. + ### ACK Flow ``` From 1150ba5667bdc2037ab31446d9fc482f41e8c56e Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Thu, 5 Nov 2026 10:52:38 -0800 Subject: [PATCH 11/66] bump SwiftFormat to 0.64.5 --- .github/workflows/lint.yml | 2 +- .swiftformat | 1 + MC1/Services/LocationService.swift | 14 ++++++-------- MC1/Views/Settings/PresetLocationPolicy.swift | 16 ++++++++-------- .../Services/ContactCleanupCoordinator.swift | 18 ++++++++---------- .../Transport/BLEStateMachine.swift | 10 +++++----- .../ConnectionManager+BLERecoveryTesting.swift | 4 +--- ...ChatSendQueueServiceAttemptCountTests.swift | 2 +- MC1Tests/Models/WhatsNewVersionTests.swift | 2 +- .../Utilities/MalwareDomainFilterTests.swift | 8 ++++---- .../NodeSettingsLateRecoveryTests.swift | 2 +- MC1Tests/Views/AdaptiveNavigationTests.swift | 2 +- .../Validation/RoundTripTests.swift | 4 ++-- 13 files changed, 40 insertions(+), 45 deletions(-) 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/.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/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/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/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/Transport/BLEStateMachine.swift b/MC1Services/Sources/MC1Services/Transport/BLEStateMachine.swift index 1ddf1a0f4b..c41e089d7c 100644 --- a/MC1Services/Sources/MC1Services/Transport/BLEStateMachine.swift +++ b/MC1Services/Sources/MC1Services/Transport/BLEStateMachine.swift @@ -25,11 +25,11 @@ 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))" } } diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManager+BLERecoveryTesting.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManager+BLERecoveryTesting.swift index 3c40baa716..a2ed3973fc 100644 --- a/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManager+BLERecoveryTesting.swift +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManager+BLERecoveryTesting.swift @@ -1,8 +1,8 @@ import Foundation @testable import MC1Services +@MainActor extension ConnectionManager { - @MainActor @discardableResult func seedBLERecoveryRequest(deviceID: UUID = UUID()) -> ConnectionRequest { if let desiredRequest, desiredRequest.target != .disconnected { return desiredRequest } @@ -14,7 +14,6 @@ extension ConnectionManager { return request } - @MainActor func finishSeededBLERecovery() async { let request = seedBLERecoveryRequest() guard let deviceID = request.target.deviceID else { return } @@ -25,7 +24,6 @@ extension ConnectionManager { if reconnectionCoordinator.isCurrent(cycle) { reconnectionCoordinator.clear() } } - @MainActor func acceptSeededBLELoss(deviceID: UUID? = nil, error: BLEError? = nil) async { let request = seedBLERecoveryRequest(deviceID: deviceID ?? connectedDevice?.id ?? UUID()) let origin = BLELifecycleOrigin( diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceAttemptCountTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceAttemptCountTests.swift index 9bc59c308a..29f11ef514 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceAttemptCountTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceAttemptCountTests.swift @@ -125,7 +125,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 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/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/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/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/MeshCore/Tests/MeshCoreTests/Validation/RoundTripTests.swift b/MeshCore/Tests/MeshCoreTests/Validation/RoundTripTests.swift index 0f3a139620..efe13e9eb1 100644 --- a/MeshCore/Tests/MeshCoreTests/Validation/RoundTripTests.swift +++ b/MeshCore/Tests/MeshCoreTests/Validation/RoundTripTests.swift @@ -11,7 +11,7 @@ struct RoundTripTests { // MARK: - Contact Round-Trip @Test - func `Contact round trip`() { + func `Contact round trip`() throws { // Build a 147-byte contact response packet var data = Data() let publicKey = Data(repeating: 0xAA, count: 32) @@ -19,7 +19,7 @@ struct RoundTripTests { let flags: UInt8 = 0x02 let pathLen: Int8 = 3 let pathBytes = Data([0x11, 0x22, 0x33]) + Data(repeating: 0, count: 61) // 64 bytes total - let nameBytes = "TestContact".data(using: .utf8)!.prefix(32) + let nameBytes = try #require("TestContact".data(using: .utf8)?.prefix(32)) let namePadded = nameBytes + Data(repeating: 0, count: 32 - nameBytes.count) let lastAdvert: UInt32 = 1_704_067_200 let lat: Int32 = 37_774_900 // 37.7749 * 1e6 From 82c611ab4d14195befff2697564e92abc37aed41 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Thu, 5 Nov 2026 16:03:06 -0800 Subject: [PATCH 12/66] fix: restore flood scope after channel sends - Clear temporary scope before the next command so it uses the radio default. - Wait for pending host replies before changing scope. - Replace the session if cleanup cannot be confirmed and keep accepted sends marked Sent. --- MC1/State/AppState+ChatPrefetch.swift | 14 +- MC1/State/AppState.swift | 2 + .../ChannelJoinFloodScopeApplier.swift | 5 +- MC1/Views/Chats/ChatConversationType.swift | 18 +- MC1/Views/Chats/ChatsListModifiers.swift | 1 - MC1/Views/Chats/Sheets/ChannelInfoSheet.swift | 15 - .../ViewModel/ChatViewModel+Channels.swift | 55 +- MC1/Views/Chats/ViewModel/ChatViewModel.swift | 15 - .../ConnectionManager+Connect.swift | 1 + .../ConnectionManager+Preparation.swift | 30 +- .../ConnectionManager+Requests.swift | 5 +- ...onnectionManager+ResourcePreparation.swift | 33 ++ .../Services/ChannelFloodScopeResolver.swift | 25 +- .../MessageService+ChannelScope.swift | 1 - .../Services/MessageService+SendChannel.swift | 19 +- .../ChannelFloodScopeResolverTests.swift | 85 --- .../ConnectionManagerMembershipTests.swift | 47 ++ .../FloodScopeConnectionTests.swift | 280 ++++++++++ .../Helpers/ChannelScopeTestTransport.swift | 21 +- .../ConnectionManagerRadioTestHarness.swift | 9 +- .../ConnectionRadioHandoffHarness.swift | 3 +- .../IdentityImportTransportFailureTests.swift | 18 +- .../ChannelInlineSendRetirementTests.swift | 66 +++ .../ChannelMessageFloodScopeTests.swift | 57 +- .../Transport/BLETransportHarness.swift | 2 + ...ChatCoordinatorRegistrySurvivalTests.swift | 60 +++ .../State/ChatPrewarmRefresherTests.swift | 1 - .../ChatViewModelPreviewSeedTests.swift | 1 - .../Views/Chats/ChatPinInfoSheetTests.swift | 1 - .../ChatViewModelConversationTests.swift | 1 - .../ChatViewModelDependencies+Testing.swift | 2 - .../MeshCore/Models/ResolvedFloodScope.swift | 8 +- .../Protocols/MessagingSessionOps.swift | 6 +- .../MeshCoreSession+BinaryProtocol.swift | 162 +++++- .../MeshCoreSession+ChannelSending.swift | 251 +++++++-- .../Session/MeshCoreSession+Channels.swift | 15 +- .../Session/MeshCoreSession+Messaging.swift | 2 +- .../Session/MeshCoreSession+Regions.swift | 2 +- .../MeshCoreSession+TransportWrites.swift | 28 +- .../MeshCore/Session/MeshCoreSession.swift | 22 + .../MeshCore/Session/RequestContext.swift | 18 +- .../ChannelFloodScopeLifetimeTests.swift | 506 ++++++++++++++++++ .../ChannelSendSerializationTests.swift | 35 +- ...shCoreSessionCommandCorrelationTests.swift | 160 ++++++ ...erifiedChannelSendSerializationTests.swift | 14 +- docs/api/MeshCore.md | 13 +- docs/guides/Messaging.md | 6 +- 47 files changed, 1788 insertions(+), 353 deletions(-) delete mode 100644 MC1Services/Tests/MC1ServicesTests/ChannelFloodScopeResolverTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/FloodScopeConnectionTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/ChannelInlineSendRetirementTests.swift create mode 100644 MeshCore/Tests/MeshCoreTests/Session/ChannelFloodScopeLifetimeTests.swift diff --git a/MC1/State/AppState+ChatPrefetch.swift b/MC1/State/AppState+ChatPrefetch.swift index 431c3be2cc..a0c51de03a 100644 --- a/MC1/State/AppState+ChatPrefetch.swift +++ b/MC1/State/AppState+ChatPrefetch.swift @@ -29,7 +29,6 @@ extension AppState { connectionState: { self.connectionState }, connectedDevice: { self.connectionSnapshot(for: radioID)?.device }, currentRadioID: { self.currentRadioID }, - session: { self.connectionSnapshot(for: radioID)?.services.session }, reactionService: { self.connectionSnapshot(for: radioID)?.services.reactionService }, chatSendQueueService: { self.connectionSnapshot(for: radioID)?.services.chatSendQueueService }, inlineImageDimensionsStore: { self.connectionSnapshot(for: radioID)?.services.inlineImageDimensionsStore }, @@ -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.swift b/MC1/State/AppState.swift index 213a23a3e1..5a53f7a91c 100644 --- a/MC1/State/AppState.swift +++ b/MC1/State/AppState.swift @@ -729,6 +729,8 @@ final class AppState { 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 } 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/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/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/Sheets/ChannelInfoSheet.swift b/MC1/Views/Chats/Sheets/ChannelInfoSheet.swift index d52bef832b..1e66eae31c 100644 --- a/MC1/Views/Chats/Sheets/ChannelInfoSheet.swift +++ b/MC1/Views/Chats/Sheets/ChannelInfoSheet.swift @@ -310,21 +310,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) - } } } diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+Channels.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+Channels.swift index f0ab08b9a7..7ccb9e2797 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. 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/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Connect.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Connect.swift index 6818cad6bd..58dabdc8cd 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Connect.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Connect.swift @@ -108,6 +108,7 @@ public extension ConnectionManager { ) 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, diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Preparation.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Preparation.swift index 767b06c5b5..e617fea9d1 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Preparation.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Preparation.swift @@ -129,6 +129,10 @@ extension ConnectionManager { // 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, @@ -138,7 +142,7 @@ extension ConnectionManager { attempt.ackEvents = await session.events(filter: .anyAcknowledgement) } do { - try await withTimeout(.seconds(10), operationName: "session.start") { + try await withTimeout(Self.sessionInitializationTimeout, operationName: "session.start") { try await session.start(disconnectTransportOnFailure: false) } } catch { @@ -155,15 +159,35 @@ extension ConnectionManager { guard let request = desiredRequest else { throw CancellationError() } try requireAttemptOwnership(request, attempt) } + let capabilities: DeviceCapabilities do { - let capabilities = try await withTimeout(.seconds(10), operationName: "queryDevice") { + capabilities = try await withTimeout(Self.sessionInitializationTimeout, operationName: "queryDevice") { try await session.queryDevice() } - return (selfInfo, capabilities) } 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 diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Requests.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Requests.swift index a71a2a1068..3f11f764a1 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Requests.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Requests.swift @@ -57,7 +57,10 @@ extension ConnectionManager { connectionState.isOperational { return .operational(link.snapshot) } - if let request = desiredRequest, request.target == targets.first, + // 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) { diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+ResourcePreparation.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+ResourcePreparation.swift index b61b45057e..8678309d45 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+ResourcePreparation.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+ResourcePreparation.swift @@ -37,6 +37,7 @@ extension ConnectionManager { 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) @@ -51,4 +52,36 @@ extension ConnectionManager { 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/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/MessageService+ChannelScope.swift b/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift index 944b0aa883..71c733cefd 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift @@ -15,7 +15,6 @@ 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 ) diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift index e3d4ea700f..908ddd8102 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,7 +84,7 @@ 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) 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/ConnectionManagerMembershipTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerMembershipTests.swift index a9dad1ed28..3829c4d785 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionManagerMembershipTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionManagerMembershipTests.swift @@ -147,6 +147,53 @@ struct ConnectionManagerMembershipTests { } } + @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/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/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/ConnectionManagerRadioTestHarness.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManagerRadioTestHarness.swift index 5276c7c0b8..16669cc109 100644 --- a/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManagerRadioTestHarness.swift +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionManagerRadioTestHarness.swift @@ -21,13 +21,16 @@ final class ConnectionManagerRadioTestHarness { sameRadio: Bool = true, publicKey: Data = Data(repeating: 1, count: 32), clock: TestClock? = nil, - sessionClock: 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) - let wifi = ConnectionTestRadioTransport(publicKey: sameRadio ? publicKey : Data(repeating: 2, count: 32)) + 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)) diff --git a/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionRadioHandoffHarness.swift b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionRadioHandoffHarness.swift index ca92937103..9bfc0273e2 100644 --- a/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionRadioHandoffHarness.swift +++ b/MC1Services/Tests/MC1ServicesTests/Helpers/ConnectionRadioHandoffHarness.swift @@ -70,7 +70,8 @@ final class ConnectionRadioHandoffHarness { func addMembership(radioID: UUID, connected: Bool) async throws -> RemoteNodeSessionDTO { let key = Data(UUID().uuidString.utf8.prefix(ProtocolLimits.publicKeySize)) nodeKeys.append(key) - try await KeychainService.shared.storePassword("synthetic-handoff", forNodeKey: 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 ) diff --git a/MC1Services/Tests/MC1ServicesTests/IdentityImportTransportFailureTests.swift b/MC1Services/Tests/MC1ServicesTests/IdentityImportTransportFailureTests.swift index e0aafa8467..e8216116f8 100644 --- a/MC1Services/Tests/MC1ServicesTests/IdentityImportTransportFailureTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/IdentityImportTransportFailureTests.swift @@ -36,6 +36,7 @@ struct IdentityImportTransportFailureTests { 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 { @@ -46,12 +47,15 @@ struct IdentityImportTransportFailureTests { var importing: Task? do { try await waitUntil("the ordinary scope exchange must have its own outstanding response") { - await harness.bluetooth.sentData.contains { $0.first == CommandCode.setFloodScope.rawValue } + 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() - await #expect(throws: CancellationError.self) { try await ordinary.value } + // 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 } @@ -115,6 +119,7 @@ struct IdentityImportTransportFailureTests { } 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( @@ -135,7 +140,9 @@ struct IdentityImportTransportFailureTests { try await source.services.chatSendQueueService.enqueueChannel(envelope(pending)) } try await waitUntil("the actual channel operation should hold its scope ACK") { - await radio.sentData.contains { $0.first == CommandCode.setFloodScope.rawValue } + 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) @@ -148,7 +155,7 @@ struct IdentityImportTransportFailureTests { #expect(await radio.isConnected) if let ordinary { ordinary.cancel() - await #expect(throws: CancellationError.self) { try await ordinary.value } + // The caller stays suspended until the submitted write settles. #expect(await radio.sendCompletionIsHeld) } if oldReplyWasOK { await radio.rejectNext(.importPrivateKey) } @@ -175,6 +182,9 @@ struct IdentityImportTransportFailureTests { #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 } 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/Transport/BLETransportHarness.swift b/MC1Services/Tests/MC1ServicesTests/Transport/BLETransportHarness.swift index 75c25c333f..9863eaead6 100644 --- a/MC1Services/Tests/MC1ServicesTests/Transport/BLETransportHarness.swift +++ b/MC1Services/Tests/MC1ServicesTests/Transport/BLETransportHarness.swift @@ -173,6 +173,8 @@ final class BLETransportHarness: @unchecked Sendable { 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])] } diff --git a/MC1Tests/AppState/ChatCoordinatorRegistrySurvivalTests.swift b/MC1Tests/AppState/ChatCoordinatorRegistrySurvivalTests.swift index 939dcf545f..89d9d3dc0d 100644 --- a/MC1Tests/AppState/ChatCoordinatorRegistrySurvivalTests.swift +++ b/MC1Tests/AppState/ChatCoordinatorRegistrySurvivalTests.swift @@ -41,6 +41,66 @@ struct ChatCoordinatorRegistrySurvivalTests { #expect(appState.chatCoordinatorRegistry?.existingCoordinator(for: conversationID) === original) } + @Test + 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() } + 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())" 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/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/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/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/MeshCore/Sources/MeshCore/Models/ResolvedFloodScope.swift b/MeshCore/Sources/MeshCore/Models/ResolvedFloodScope.swift index 8b46ee077d..a8c30bf81f 100644 --- a/MeshCore/Sources/MeshCore/Models/ResolvedFloodScope.swift +++ b/MeshCore/Sources/MeshCore/Models/ResolvedFloodScope.swift @@ -1,8 +1,8 @@ -/// A zero-key ``FloodScope/disabled`` uses the radio's persisted default. -/// ``unscoped`` overrides that default so packets carry no region. +/// A flood scope for a channel send. The send restores the radio baseline before the next command. +/// A zero-key ``FloodScope/disabled`` selects the radio's persisted default. public enum ResolvedFloodScope: Sendable, Equatable { - /// Force unscoped floods, overriding the radio's default. Requires firmware v12+. + /// Force unscoped floods, overriding the radio's default. Requires protocol capability 12+. case unscoped - /// Set the session's flood scope, or reset it with ``FloodScope/disabled``. + /// Set the session's flood scope, or select the persisted default with ``FloodScope/disabled``. case scope(FloodScope) } diff --git a/MeshCore/Sources/MeshCore/Protocols/MessagingSessionOps.swift b/MeshCore/Sources/MeshCore/Protocols/MessagingSessionOps.swift index ad058e75e6..030165f1e2 100644 --- a/MeshCore/Sources/MeshCore/Protocols/MessagingSessionOps.swift +++ b/MeshCore/Sources/MeshCore/Protocols/MessagingSessionOps.swift @@ -36,8 +36,8 @@ public protocol MessagingSessionOps: Actor { timestamp: Date ) async throws - /// Applies the channel's flood scope and sends without another command - /// changing the scope between the two exchanges. + /// Sends with a temporary flood scope and restores the radio baseline before the next command. + /// If restoration fails, the session blocks further commands and preserves any accepted send. func sendChannelMessage( channel: UInt8, text: String, @@ -45,7 +45,7 @@ public protocol MessagingSessionOps: Actor { floodScope: ResolvedFloodScope ) async throws - /// Verifies the slot secret and sends under the same command-response serialization. + /// Verifies the slot secret and sends under one command slot, applying a temporary scope when provided. func sendVerifiedChannelMessage( channel: UInt8, text: String, diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+BinaryProtocol.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+BinaryProtocol.swift index 835f38bae5..1a962d121b 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+BinaryProtocol.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+BinaryProtocol.swift @@ -17,7 +17,7 @@ public extension MeshCoreSession { /// ``MeshCoreError/invalidResponse`` if an unexpected response is received. func requestStatus(from publicKey: Data) async throws -> StatusResponse { try requireFullPublicKey(publicKey, operation: "requestStatus") - return try await requestResponseSerializer.withSerialization { [self] in + return try await withSerializedBinaryRequest { [self] in try await performStatusRequest(from: publicKey, layout: .repeater) } } @@ -37,7 +37,7 @@ public extension MeshCoreSession { ) async throws -> StatusResponse { try requireFullPublicKey(publicKey, operation: "requestStatus") let layout: StatusResponse.Layout = type == .room ? .roomServer : .repeater - return try await requestResponseSerializer.withSerialization { [self] in + return try await withSerializedBinaryRequest { [self] in try await performStatusRequest(from: publicKey, layout: layout) } } @@ -140,12 +140,26 @@ public extension MeshCoreSession { /// ``MeshCoreError/invalidResponse`` if unexpected response received. func requestTelemetry(from publicKey: Data) async throws -> TelemetryResponse { try requireFullPublicKey(publicKey, operation: "requestTelemetry") - // Serialize binary requests to prevent messageSent race conditions - return try await requestResponseSerializer.withSerialization { [self] in + return try await withSerializedBinaryRequest { [self] in try await performTelemetryRequest(from: publicKey) } } + /// Binary exchanges settle host replies before releasing serialization. + /// Unwrap the RF result afterward so an RF timeout does not mark host replies uncertain. + internal func withSerializedBinaryRequest( + _ operation: @escaping @Sendable () async throws -> Response + ) async throws -> Response { + let outcome: Result = try await requestResponseSerializer.withSerialization { + do { + return try await .success(operation()) + } catch { + return .failure(error) + } + } + return try outcome.get() + } + /// Send `request` and resolve the first matching `.binaryResponse` or /// `matchRoutedEvent` hit. Retransmits the same frame until a reply arrives or /// `binaryRequestOverallTimeout` elapses (`nil` retransmit interval disables @@ -173,18 +187,76 @@ public extension MeshCoreSession { let startTime = ContinuousClock.now let overallTimeout = configuration.binaryRequestOverallTimeout let retransmitFloor = configuration.binaryRequestRetransmitInterval - let cadence = BinaryExchangeCadence(minimumSeconds: retransmitFloor ?? 0) + let state = BinaryExchangeState(minimumSeconds: retransmitFloor ?? 0) let floorDesc = retransmitFloor.map { String(format: "%.1f", $0) } ?? "off" logger.info( "\(operation) request to \(prefixHex): sending (overall=\(String(format: "%.1f", overallTimeout))s, retransmitFloor=\(floorDesc)s)" ) - // Subscribe before sending to avoid the race where the response arrives - // before the consumer is listening. - let events = await dispatcher.subscribe() - try await sendSessionData(request) + // The host reply stream survives RF completion and cancellation of the RF listener. + let (hostID, hostReplies) = await dispatcher.subscribeTracked { event in + switch event { + case .messageSent, .error: true + default: false + } + } + let (rfID, rfEvents) = await dispatcher.subscribeTracked() + let (progress, updates) = AsyncStream.makeStream(of: Int.self, bufferingPolicy: .bufferingNewest(1)) + let hostCollector = Task { + var received = 0 + for await _ in hostReplies { + received += 1 + updates.yield(received) + } + updates.finish() + return received + } + + do { + try await sendSessionData(request) + } catch { + await dispatcher.finishSubscription(id: rfID) + await dispatcher.finishSubscription(id: hostID) + _ = await hostCollector.value + throw error + } + + let outcome: Result + let waitForLateHostReplies: Bool + do { + outcome = try await .success(waitForBinaryResponse( + request: request, events: rfEvents, state: state, prefixHex: prefixHex, + operation: operation, startTime: startTime, matchRoutedEvent: matchRoutedEvent, parseResponse: parseResponse + )) + waitForLateHostReplies = true + } catch MeshCoreError.timeout { + outcome = .failure(MeshCoreError.timeout) + waitForLateHostReplies = false + } catch { + outcome = .failure(error) + waitForLateHostReplies = true + } + await dispatcher.finishSubscription(id: rfID) + await settleBinaryHostReplies( + progress, collector: hostCollector, id: hostID, expectedCount: state.submittedCount, + waitForLateReplies: waitForLateHostReplies && sessionIsRunning + ) + return try outcome.get() + } + + private func waitForBinaryResponse( + request: Data, + events: AsyncStream, + state: BinaryExchangeState, + prefixHex: String, + operation: String, + startTime: ContinuousClock.Instant, + matchRoutedEvent: (@Sendable (MeshEvent) -> Response?)?, + parseResponse: @escaping @Sendable (_ payload: Data, _ tag: Data) throws -> Response? + ) async throws -> Response { + let overallTimeout = configuration.binaryRequestOverallTimeout return try await withThrowingTaskGroup(of: BinaryExchangeSignal.self) { group in group.addTask { [self, logger] in // From firmware v14 a reply to a replaced tag still arrives, so keep every tag this exchange sent. @@ -199,7 +271,7 @@ public extension MeshCoreSession { case let .messageSent(info): sentTags.insert(info.expectedAck) acceptedMessageSent = true - await cadence.applySuggestedTimeoutMs(info.suggestedTimeoutMs) + await state.applySuggestedTimeoutMs(info.suggestedTimeoutMs) let tagHex = info.expectedAck.map { String(format: "%02x", $0) }.joined() logger.info( "\(operation) request to \(prefixHex): messageSent #\(sendCount) tag=\(tagHex) suggestedTimeoutMs=\(info.suggestedTimeoutMs)" @@ -258,11 +330,11 @@ public extension MeshCoreSession { return .timedOut } - if retransmitFloor != nil { + if configuration.binaryRequestRetransmitInterval != nil { group.addTask { [self, logger, clock = self.clock] in var attempt = 1 while !Task.isCancelled { - let delay = await cadence.waitForInterval() + let delay = await state.waitForInterval() do { try await clock.sleep(for: .seconds(delay)) } catch is CancellationError { @@ -271,12 +343,13 @@ public extension MeshCoreSession { guard !Task.isCancelled else { break } guard await self.sessionIsRunning else { return .stopped } attempt += 1 - let interval = await cadence.currentSeconds() + let interval = await state.currentSeconds() logger.info( "\(operation) request to \(prefixHex): retransmit #\(attempt) (interval=\(String(format: "%.1f", interval))s)" ) do { - try await self.sendSessionData(request) + try await self.submitBinaryRetry(request) + await state.recordSubmission() } catch is CancellationError { return .idle } catch { @@ -318,6 +391,45 @@ public extension MeshCoreSession { } } + /// Once admitted on the session actor, the write outlives cancellation of the RF wait. + private func submitBinaryRetry(_ request: Data) async throws { + try Task.checkCancellation() + try await Task { try await sendSessionData(request) }.value + } + + /// Drain one host reply per submitted request, even if an earlier attempt answered over RF. + private func settleBinaryHostReplies( + _ progress: AsyncStream, + collector: Task, + id: UUID, + expectedCount: Int, + waitForLateReplies: Bool + ) async { + if waitForLateReplies { + let timeout = configuration.defaultTimeout + await withTaskGroup(of: Void.self) { group in + group.addTask { [clock, dispatcher] in + do { + try await clock.sleep(for: .seconds(timeout)) + } catch { + return + } + await dispatcher.finishSubscription(id: id) + } + for await received in progress { + if received >= expectedCount { break } + } + group.cancelAll() + } + } + + // At the RF deadline, account for buffered replies without extending that deadline. + await dispatcher.finishSubscription(id: id) + if await collector.value < expectedCount { + await requestResponseSerializer.noteUncertainResponseHistory() + } + } + /// Internal implementation of telemetry request, called within serialization. private func performTelemetryRequest(from publicKey: Data) async throws -> TelemetryResponse { let publicKeyPrefix = Data(publicKey.prefix(6)) @@ -357,7 +469,7 @@ public extension MeshCoreSession { /// - Throws: ``MeshCoreError/timeout`` if no response within timeout period. func requestOwnerInfo(from publicKey: Data) async throws -> OwnerInfoResponse { try requireFullPublicKey(publicKey, operation: "requestOwnerInfo") - return try await requestResponseSerializer.withSerialization { [self] in + return try await withSerializedBinaryRequest { [self] in try await performOwnerInfoRequest(from: publicKey) } } @@ -395,7 +507,7 @@ public extension MeshCoreSession { /// ``MeshCoreError/deviceError(code:)`` if the device rejects the request. func requestMMA(from publicKey: Data, start: Date, end: Date) async throws -> MMAResponse { try requireFullPublicKey(publicKey, operation: "requestMMA") - return try await requestResponseSerializer.withSerialization { [self] in + return try await withSerializedBinaryRequest { [self] in try await performMMARequest(from: publicKey, start: start, end: end) } } @@ -439,7 +551,7 @@ public extension MeshCoreSession { /// ``MeshCoreError/deviceError(code:)`` if the device rejects the request. func requestACL(from publicKey: Data) async throws -> ACLResponse { try requireFullPublicKey(publicKey, operation: "requestACL") - return try await requestResponseSerializer.withSerialization { [self] in + return try await withSerializedBinaryRequest { [self] in try await performACLRequest(from: publicKey) } } @@ -478,7 +590,7 @@ public extension MeshCoreSession { pubkeyPrefixLength: UInt8 = 4 ) async throws -> NeighboursResponse { try requireFullPublicKey(publicKey, operation: "requestNeighbours") - return try await requestResponseSerializer.withSerialization { [self] in + return try await withSerializedBinaryRequest { [self] in try await performNeighboursRequest( from: publicKey, count: count, @@ -562,11 +674,11 @@ private enum BinaryExchangeSignal: Sendable { case idle } -/// Live retransmit spacing shared from `messageSent` into the resend loop. -/// Floor starts at the config minimum; rises to -/// `suggestedTimeoutMs × binaryRetransmitRTTHeadroom` so multi-hop waits cover -/// a full return trip before another copy. -private actor BinaryExchangeCadence { +/// Tracks submitted writes and adjusts retry spacing from `messageSent` to allow a full return trip. +private actor BinaryExchangeState { + /// The first write completed before the retransmit loop starts. + private(set) var submittedCount = 1 + private var seconds: TimeInterval private var hasSuggested = false private var waiters: [CheckedContinuation] = [] @@ -608,6 +720,10 @@ private actor BinaryExchangeCadence { } } + func recordSubmission() { + submittedCount += 1 + } + func currentSeconds() -> TimeInterval { seconds } diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+ChannelSending.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+ChannelSending.swift index 0f058db91d..ffb154b7f8 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+ChannelSending.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+ChannelSending.swift @@ -1,5 +1,5 @@ import Foundation -import os +import Synchronization public extension MeshCoreSession { /// Sends a message to a channel. @@ -19,7 +19,7 @@ public extension MeshCoreSession { try await performChannelSend(channel: channel, text: text, timestamp: timestamp, floodScope: nil, expectedSecret: nil) } - /// Applies a channel's flood scope and sends while holding one command-response slot. + /// Applies a temporary flood scope, sends, and restores the baseline before releasing the slot. func sendChannelMessage( channel: UInt8, text: String, @@ -53,41 +53,24 @@ public extension MeshCoreSession { floodScope: ResolvedFloodScope?, expectedSecret: Data? ) async throws { - var commands: [Data] = [] - if let floodScope { - let scopeCommand = switch floodScope { - case .unscoped: - PacketBuilder.setFloodScopeUnscoped() - case let .scope(scope): - PacketBuilder.setFloodScope(scope.scopeKey()) - } - commands.append(scopeCommand) - } - commands.append(PacketBuilder.sendChannelMessage(channel: channel, text: text, timestamp: timestamp)) - let cancelled = OSAllocatedUnfairLock(initialState: false) - + let cancelled = Mutex(false) + let isCancelled: @Sendable () -> Bool = { cancelled.withLock { $0 } } + let message = PacketBuilder.sendChannelMessage(channel: channel, text: text, timestamp: timestamp) try await withTaskCancellationHandler { - try await requestResponseSerializer.withSerialization { [self, commands] in - if let expectedSecret { - let _: Bool = try await sendAndMatchHoldingSerialization(PacketBuilder.getChannel(index: channel), beforeSend: { - if cancelled.withLock({ $0 }) { throw CancellationError() } - }) { event in - if case let .error(code) = event, code == ErrorCode.notFound.rawValue { - return .failure(Self.channelOccupancyMismatch) - } - if let error = Self.deviceErrorMatcher(event) { return .failure(error) } - guard case let .channelInfo(info) = event, info.index == channel else { return .ignore } - guard info.secret == expectedSecret, - !info.name.isEmpty || info.secret.contains(where: { $0 != Self.unconfiguredChannelSecretByte }) else { - return .failure(Self.channelOccupancyMismatch) - } - return .success(true) - } + if let floodScope { + try await requestResponseSerializer.withSerialization(resumeCallerOnCancel: false) { [self] in + try await self.sendWithTemporaryFloodScope( + channel: channel, message: message, floodScope: floodScope, + expectedSecret: expectedSecret, isCancelled: isCancelled + ) } - for command in commands { - // Cancellation still drains the current response, but prevents the next write. - let _: Bool = try await sendAndMatchHoldingSerialization(command, beforeSend: { - if cancelled.withLock({ $0 }) { throw CancellationError() } + } else { + try await requestResponseSerializer.withSerialization { [self] in + if let expectedSecret { + try await validateChannelOccupancy(channel: channel, expectedSecret: expectedSecret, isCancelled: isCancelled) + } + let _: Bool = try await sendAndMatchHoldingSerialization(message, beforeSend: { + if isCancelled() { throw CancellationError() } }) { event in if let error = Self.deviceErrorMatcher(event) { return .failure(error) } if case .ok(nil) = event { return .success(true) } @@ -99,4 +82,202 @@ public extension MeshCoreSession { cancelled.withLock { $0 = true } } } + + /// Keep the slot through restoration so no other command can inherit the override. + /// An acknowledged `03` stays accepted through cancellation or cleanup failure. + private func sendWithTemporaryFloodScope( + channel: UInt8, + message: Data, + floodScope: ResolvedFloodScope, + expectedSecret: Data?, + isCancelled: @escaping @Sendable () -> Bool + ) async throws { + defer { notifyFloodScopeRecoveryIfNeeded() } + if floodScopeRecoveryRequired { throw CancellationError() } + if await requestResponseSerializer.responseAttributionIsUncertain() { + markFloodScopeRecoveryRequired() + throw MeshCoreError.timeout + } + if let expectedSecret { + do { + try await validateChannelOccupancy(channel: channel, expectedSecret: expectedSecret, isCancelled: isCancelled) + } catch { + if Self.channelWriteFailureRequiresFence(error, isCancelled: isCancelled) { + markFloodScopeRecoveryRequired() + } + throw error + } + } + if isCancelled() { throw CancellationError() } + + let setup = Self.temporaryScopeCommand(floodScope) + switch await settleChannelCommand(setup.command, isCancelled: isCancelled) { + case .replied(.accepted): + break + case let .replied(.rejected(error)), let .uncertain(.rejected(error)?, _): + throw error + case let .notSubmitted(error), let .uncertain(_, error): + throw error + } + if isCancelled() { + await restoreTemporaryScope(needed: setup.restoresBaseline) + throw CancellationError() + } + + switch await settleChannelCommand(message, isCancelled: isCancelled) { + case let .replied(reply): + await restoreTemporaryScope(needed: setup.restoresBaseline) + if case let .rejected(error) = reply { throw error } + case let .notSubmitted(error): + await restoreTemporaryScope(needed: setup.restoresBaseline) + throw error + case .uncertain(.accepted?, _): + // The owned OK confirms acceptance, but a reset cannot use the uncertain reply stream. + return + case let .uncertain(.rejected(error)?, _): + throw error + case let .uncertain(nil, error): + throw error + } + } + + private func restoreTemporaryScope(needed: Bool) async { + guard needed else { return } + let reset = await settleChannelCommand(Self.floodScopeBaselineCommand) + guard case .replied(.accepted) = reset else { + markFloodScopeRecoveryRequired() + return + } + } + + private static let floodScopeBaselineCommand = PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey()) + + private static func temporaryScopeCommand(_ floodScope: ResolvedFloodScope) -> (command: Data, restoresBaseline: Bool) { + switch floodScope { + case .unscoped: + return (PacketBuilder.setFloodScopeUnscoped(), true) + case let .scope(scope): + let key = scope.scopeKey() + return (PacketBuilder.setFloodScope(key), key != FloodScope.disabled.scopeKey()) + } + } + + private func validateChannelOccupancy( + channel: UInt8, + expectedSecret: Data, + isCancelled: @escaping @Sendable () -> Bool + ) async throws { + let _: Bool = try await sendAndMatchHoldingSerialization(PacketBuilder.getChannel(index: channel), beforeSend: { + if isCancelled() { throw CancellationError() } + }) { event in + if case let .error(code) = event, code == ErrorCode.notFound.rawValue { + return .failure(Self.channelOccupancyMismatch) + } + if let error = Self.deviceErrorMatcher(event) { return .failure(error) } + guard case let .channelInfo(info) = event, info.index == channel else { return .ignore } + guard info.secret == expectedSecret, + !info.name.isEmpty || info.secret.contains(where: { $0 != Self.unconfiguredChannelSecretByte }) else { + return .failure(Self.channelOccupancyMismatch) + } + return .success(true) + } + } + + private static func channelWriteFailureRequiresFence( + _ error: Error, + isCancelled: @Sendable () -> Bool + ) -> Bool { + if let failure = error as? MeshCoreError { + if case .timeout = failure { return true } + return false + } + if error is CancellationError, isCancelled() { return false } + return true + } + + /// Retain the first terminal reply even if the write fails, then close the subscription before the next command. + private func settleChannelCommand( + _ data: Data, + isCancelled: @Sendable () -> Bool = { false } + ) async -> ChannelCommandSettlement { + let (subscriptionID, events) = await dispatcher.subscribeTracked(filter: Self.isTerminalCommandReply) + let collector = Task { () -> ChannelCommandSettlement.Reply? in + for await event in events { + if let reply = Self.channelCommandReply(event) { return reply } + } + return nil + } + + let uncertainBeforeWrite = await requestResponseSerializer.responseAttributionIsUncertain() + let writeError: Error? + do { + try await sendSessionData(data, beforeSend: { + if isCancelled() { throw CancellationError() } + }) + writeError = nil + } catch { + writeError = error + } + + if let writeError { + let writeAttempted = await requestResponseSerializer.responseAttributionIsUncertain() && !uncertainBeforeWrite + if writeAttempted { + // Give the receive loop a chance to publish a buffered reply before closing the subscription. + await Task.yield() + } + await dispatcher.finishSubscription(id: subscriptionID) + let reply = await collector.value + if !writeAttempted { + if !sessionIsRunning { markFloodScopeRecoveryRequired() } + return .notSubmitted(writeError) + } + markFloodScopeRecoveryRequired() + return .uncertain(reply, writeError) + } + + let timeout = configuration.defaultTimeout + await withTaskGroup(of: Void.self) { group in + group.addTask { _ = await collector.value } + group.addTask { [clock] in + try? await clock.sleep(for: .seconds(timeout)) + } + _ = await group.next() + // Close the stream before joining the collector so a timeout can release the slot. + await dispatcher.finishSubscription(id: subscriptionID) + group.cancelAll() + } + if let reply = await collector.value { + return .replied(reply) + } + markFloodScopeRecoveryRequired() + await requestResponseSerializer.noteUncertainResponseHistory() + if !sessionIsRunning { + return .uncertain(nil, CancellationError()) + } + return .uncertain(nil, MeshCoreError.timeout) + } + + private static func isTerminalCommandReply(_ event: MeshEvent) -> Bool { + switch event { + case .ok, .error: true + default: false + } + } + + private static func channelCommandReply(_ event: MeshEvent) -> ChannelCommandSettlement.Reply? { + if let error = deviceErrorMatcher(event) { return .rejected(error) } + if case .ok(nil) = event { return .accepted } + return nil + } + + private enum ChannelCommandSettlement { + enum Reply: Sendable { + case accepted + case rejected(MeshCoreError) + } + + case notSubmitted(Error) + case replied(Reply) + case uncertain(Reply?, Error) + } } diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Channels.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Channels.swift index d01b53b75e..9e6630a1e2 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Channels.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Channels.swift @@ -14,12 +14,17 @@ public extension MeshCoreSession { /// /// - Parameter index: Channel index (0-255). /// - Returns: Channel information including name and secret. - /// - Throws: ``MeshCoreError/timeout`` if the device doesn't emit configuration for the requested channel. + /// - Throws: ``MeshCoreError/timeout`` if the device doesn't emit configuration, or + /// ``MeshCoreError/deviceError(code:)`` when the radio rejects the read. func getChannel(index: UInt8) async throws -> ChannelInfo { - try await sendAndWait(PacketBuilder.getChannel(index: index)) { event in - if case let .channelInfo(info) = event, info.index == index { return info } - return nil - } + try await sendAndWaitWithError( + PacketBuilder.getChannel(index: index), + matching: { event in + if case let .channelInfo(info) = event, info.index == index { return info } + return nil + }, + errorMatcher: Self.deviceErrorMatcher + ) } /// Reads multiple channels in a single bounded-window pipeline of unacknowledged requests, diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift index 919a40ae01..784eeffc37 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift @@ -468,7 +468,7 @@ public extension MeshCoreSession { /// /// The flood scope limits broadcast flooding to nodes with matching scope. /// - /// - Parameter scopeKey: The 32-byte scope key. + /// - Parameter scopeKey: The 16-byte scope key. A zero key clears the RAM override. /// - Throws: ``MeshCoreError/timeout`` or ``MeshCoreError/deviceError(code:)`` on failure. func setFloodScope(scopeKey: Data) async throws { try await sendSimpleCommand(PacketBuilder.setFloodScope(scopeKey)) diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Regions.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Regions.swift index 9db6b998da..0d7da65d47 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Regions.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Regions.swift @@ -38,7 +38,7 @@ extension MeshCoreSession { ) try await sendSimpleCommand(PacketBuilder.updateContact(directContact)) } - let result = try await requestResponseSerializer.withSerialization { [self] in + let result = try await withSerializedBinaryRequest { [self] in try await performRegionsRequest(from: contact) } if isFloodRouted { diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+TransportWrites.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+TransportWrites.swift index 641b1e8ae8..76befad362 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+TransportWrites.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+TransportWrites.swift @@ -8,28 +8,48 @@ extension MeshCoreSession { identityImport: Bool = false ) async throws { guard !identityImportInProgress || identityImport else { throw CancellationError() } - guard sessionIsRunning else { throw CancellationError() } + guard sessionIsRunning, !floodScopeRecoveryRequired else { throw CancellationError() } try beforeSend() do { try await transport.send(data) } catch MeshTransportError.cancelledBeforeSubmission { throw CancellationError() } catch { - await requestResponseSerializer.noteUncertainResponseHistory() + if !Self.linkRejectedWriteBeforeSubmission(error) { + await requestResponseSerializer.noteUncertainResponseHistory() + } throw error } } func sendSessionDataWithoutResponse(_ data: Data) async throws { guard !identityImportInProgress else { throw CancellationError() } - guard sessionIsRunning else { throw CancellationError() } + guard sessionIsRunning, !floodScopeRecoveryRequired else { throw CancellationError() } do { try await transport.sendWithoutResponse(data) } catch MeshTransportError.cancelledBeforeSubmission { throw CancellationError() } catch { - await requestResponseSerializer.noteUncertainResponseHistory() + if !Self.linkRejectedWriteBeforeSubmission(error) { + await requestResponseSerializer.noteUncertainResponseHistory() + } throw error } } + + /// A frame rejected before submission cannot leave a pending host reply. + static func linkRejectedWriteBeforeSubmission(_ error: Error) -> Bool { + switch error { + case MeshTransportError.notConnected, + MeshCoreError.notConnected, + MeshCoreError.bluetoothUnavailable, + MeshCoreError.bluetoothUnauthorized, + MeshCoreError.bluetoothPoweredOff, + MeshCoreError.sessionNotStarted: + return true + default: + if case MeshCoreError.connectionLost = error { return true } + return false + } + } } diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift index 4e9ae3710f..e4b973fd03 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift @@ -124,6 +124,28 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { isRunning } + /// Blocks further writes when the session cannot confirm that its temporary scope is clear. + var floodScopeRecoveryRequired = false + private var floodScopeRecoveryNotified = false + private var floodScopeRecoveryHandler: (@Sendable () -> Void)? + + /// Called at most once on the session actor after the send outcome is known. + /// Schedule retirement without waiting because `stop()` joins the occupied command slot. + public func setFloodScopeRecoveryHandler(_ handler: (@Sendable () -> Void)?) { + floodScopeRecoveryHandler = handler + } + + func markFloodScopeRecoveryRequired() { + floodScopeRecoveryRequired = true + } + + func notifyFloodScopeRecoveryIfNeeded() { + guard floodScopeRecoveryRequired, !floodScopeRecoveryNotified, sessionIsRunning else { return } + floodScopeRecoveryNotified = true + logger.warning("Flood scope recovery required; refusing further commands on this session") + floodScopeRecoveryHandler?() + } + private var receiveTask: Task? private var autoMessageFetchTask: Task? private var autoMessageDrainTask: Task? diff --git a/MeshCore/Sources/MeshCore/Session/RequestContext.swift b/MeshCore/Sources/MeshCore/Session/RequestContext.swift index b433fb53f7..c2fd270970 100644 --- a/MeshCore/Sources/MeshCore/Session/RequestContext.swift +++ b/MeshCore/Sources/MeshCore/Session/RequestContext.swift @@ -72,16 +72,15 @@ public actor RequestResponseSerializer { await withCheckedContinuation { settlementWaiters.append($0) } } - /// Executes a request/response operation while holding the serializer. - /// - /// The slot is held until the wire exchange the operation owns actually terminates — - /// a matching response is consumed or the command's own timeout elapses — even after - /// the caller has been resumed. If the caller's task is cancelled mid-flight, it is - /// resumed immediately with `CancellationError`, but the operation keeps running so a - /// late (orphaned) response is drained here under the held slot instead of leaking to - /// the next command, which would otherwise consume it as its own. A command cancelled - /// before its exchange begins releases the slot without writing. + func responseAttributionIsUncertain() -> Bool { + hasUncertainResponseHistory + } + + /// Holds the slot through reply or timeout so a cancelled caller cannot leave a reply for the next command. + /// Pass `resumeCallerOnCancel: false` to wait for settlement when acceptance must survive cancellation. + /// Cancellation before the exchange starts prevents the write. public func withSerialization( + resumeCallerOnCancel: Bool = true, _ operation: @escaping @Sendable () async throws -> T ) async throws -> T { await acquire() @@ -127,6 +126,7 @@ public actor RequestResponseSerializer { } } } onCancel: { + guard resumeCallerOnCancel else { return } let waiting = pending.withLock { stored -> CheckedContinuation? in let continuation = stored stored = nil diff --git a/MeshCore/Tests/MeshCoreTests/Session/ChannelFloodScopeLifetimeTests.swift b/MeshCore/Tests/MeshCoreTests/Session/ChannelFloodScopeLifetimeTests.swift new file mode 100644 index 0000000000..69ec2df143 --- /dev/null +++ b/MeshCore/Tests/MeshCoreTests/Session/ChannelFloodScopeLifetimeTests.swift @@ -0,0 +1,506 @@ +import Foundation +@testable import MeshCore +import MeshCoreTestSupport +import Synchronization +import Testing + +@Suite("Channel flood scope lifetime") +struct ChannelFloodScopeLifetimeTests { + private static let timestamp = Date(timeIntervalSince1970: 1_700_000_000) + private static let channel: UInt8 = 1 + private static let namedScope = FloodScope.region("Alpha") + private static let contactKey = Data(repeating: 0x11, count: 32) + private static let commandTimeout: TimeInterval = 5 + private static let restoreCases: [(scope: ResolvedFloodScope, command: QueuedCommand)] = [ + (.scope(namedScope), .login), + (.scope(namedScope), .directMessage), + (.scope(namedScope), .telemetry), + (.unscoped, .login) + ] + + @Test(arguments: restoreCases) + func `scoped send restores the baseline before a queued contact command`( + testCase: (scope: ResolvedFloodScope, command: QueuedCommand) + ) async throws { + let (scope, command) = testCase + let harness = try await Harness.started() + defer { Task { await harness.session.stop() } } + let setupFrame = switch scope { + case .unscoped: PacketBuilder.setFloodScopeUnscoped() + case let .scope(floodScope): Self.scopeKey(floodScope) + } + let send = harness.send(scope: scope) + try await harness.ack(setupFrame) + try await harness.ack(Self.channelMessage) + let queued = command.start(harness.session) + try await harness.waitForWaiters(1) + #expect(await harness.transport.sentData.allSatisfy { $0.first != command.code }) + try await harness.ack(Self.baselineReset) + try await send.value + try await harness.expectFrame(command.code) + await harness.transport.simulateReceive(Self.messageSent) + _ = try await queued.value + #expect(await harness.session.floodScopeRecoveryRequired == false) + #expect(harness.recoveries.count() == 0) + #expect(await Self.channelSendCount(harness.transport.sentData) == 1) + } + + @Test + func `a zero-key setup is the baseline and has no trailing reset`() async throws { + let harness = try await Harness.started() + defer { Task { await harness.session.stop() } } + let send = harness.send(scope: .scope(.disabled)) + try await harness.ack(Self.baselineReset) + let queued = QueuedCommand.login.start(harness.session) + try await harness.waitForWaiters(1) + #expect(await harness.transport.sentData.allSatisfy { $0.first != CommandCode.sendLogin.rawValue }) + let scopeFramesBeforeSend = await harness.transport.sentData.filter { $0.first == CommandCode.setFloodScope.rawValue } + #expect(scopeFramesBeforeSend == [Self.baselineReset]) + try await harness.ack(Self.channelMessage) + try await send.value + try await harness.expectFrame(CommandCode.sendLogin.rawValue) + let scopeFrames = await harness.transport.sentData.filter { $0.first == CommandCode.setFloodScope.rawValue } + #expect(scopeFrames == [Self.baselineReset]) + await harness.transport.simulateReceive(Self.messageSent) + _ = try await queued.value + } + + @Test + func `a raw channel send does not change flood scope`() async throws { + let harness = try await Harness.started() + defer { Task { await harness.session.stop() } } + let send = Task { + try await harness.session.sendChannelMessage(channel: Self.channel, text: "hello", timestamp: Self.timestamp) + } + try await harness.ack(Self.channelMessage) + try await send.value + #expect(await harness.transport.sentData.allSatisfy { $0.first != CommandCode.setFloodScope.rawValue }) + #expect(await harness.session.floodScopeRecoveryRequired == false) + } + + @Test + func `a raw occupancy timeout still allows a room login`() async throws { + let harness = try await Harness.started(clock: true) + defer { Task { await harness.session.stop() } } + let send = Task { + try await harness.session.sendVerifiedChannelMessage( + channel: Self.channel, text: "hello", timestamp: Self.timestamp, + floodScope: nil, expectedSecret: Data(repeating: 0xAA, count: 16) + ) + } + try await harness.waitForFrames(2) + #expect(await harness.transport.sentData[1] == PacketBuilder.getChannel(index: Self.channel)) + try await harness.advanceCommandTimeout() + await #expect { + try await send.value + } throws: { error in + guard let error = error as? MeshCoreError, case .timeout = error else { return false } + return true + } + + let login = QueuedCommand.login.start(harness.session) + try await harness.expectFrame(CommandCode.sendLogin.rawValue) + await harness.transport.simulateReceive(Self.messageSent) + try await login.value + #expect(harness.recoveries.count() == 0) + #expect(await harness.transport.sentData.count == 3) + } + + @Test + func `cancellation during reset keeps the accepted send when the reset is confirmed`() async throws { + let harness = try await Harness.started() + defer { Task { await harness.session.stop() } } + let send = harness.send(scope: .scope(Self.namedScope)) + try await harness.ack(Self.scopeKey(Self.namedScope)) + try await harness.ack(Self.channelMessage) + try await harness.waitForFrames(4) + #expect(await harness.transport.sentData[3] == Self.baselineReset) + send.cancel() + let queued = QueuedCommand.telemetry.start(harness.session) + try await harness.waitForWaiters(1) + #expect(await harness.transport.sentData.count == 4) + try await harness.ack(Self.baselineReset) + try await send.value + try await harness.expectFrame(CommandCode.getSelfTelemetry.rawValue) + await harness.transport.simulateReceive(Self.messageSent) + _ = try await queued.value + #expect(await harness.session.floodScopeRecoveryRequired == false) + #expect(await Self.channelSendCount(harness.transport.sentData) == 1) + } + + @Test + func `a rejected channel send restores an active override`() async throws { + let harness = try await Harness.started() + defer { Task { await harness.session.stop() } } + let send = harness.send(scope: .scope(Self.namedScope)) + try await harness.ack(Self.scopeKey(Self.namedScope)) + try await harness.waitForFrames(3) + let rejected: UInt8 = 9 + await harness.transport.simulateError(code: rejected) + try await harness.waitForFrames(4) + #expect(await harness.transport.sentData[3] == Self.baselineReset) + try await harness.ack(Self.baselineReset) + let error = await #expect(throws: MeshCoreError.self) { try await send.value } + guard case let .deviceError(code)? = error else { + Issue.record("Expected the channel rejection, got \(String(describing: error))") + return + } + #expect(code == rejected) + #expect(await harness.session.floodScopeRecoveryRequired == false) + let queued = QueuedCommand.login.start(harness.session) + try await harness.expectFrame(CommandCode.sendLogin.rawValue) + await harness.transport.simulateReceive(Self.messageSent) + _ = try await queued.value + } + + @Test + func `reset rejection preserves the accepted send and fences the session`() async throws { + let harness = try await Harness.started() + defer { Task { await harness.session.stop() } } + let send = harness.send(scope: .unscoped) + try await harness.ack(PacketBuilder.setFloodScopeUnscoped()) + try await harness.ack(Self.channelMessage) + try await harness.waitForFrames(4) + await harness.transport.simulateError(code: 3) + try await send.value + #expect(await harness.session.floodScopeRecoveryRequired) + #expect(harness.recoveries.count() == 1) + #expect(await Self.channelSendCount(harness.transport.sentData) == 1) + let queued = QueuedCommand.directMessage.start(harness.session) + await #expect(throws: CancellationError.self) { try await queued.value } + #expect(await Self.channelSendCount(harness.transport.sentData) == 1) + #expect(await harness.transport.sentData.allSatisfy { $0.first != CommandCode.sendMessage.rawValue }) + } + + @Test + func `reset timeout preserves the accepted send and a late OK cannot clear the fence`() async throws { + let harness = try await Harness.started(clock: true) + defer { Task { await harness.session.stop() } } + let send = harness.send(scope: .scope(Self.namedScope)) + try await harness.ack(Self.scopeKey(Self.namedScope)) + try await harness.ack(Self.channelMessage) + try await harness.waitForFrames(4) + let queued = QueuedCommand.login.start(harness.session) + try await harness.waitForWaiters(1) + try await harness.advanceCommandTimeout() + try await harness.waitUntilSubscribers(0) + await harness.transport.simulateOK() + try await send.value + #expect(await harness.session.floodScopeRecoveryRequired) + #expect(harness.recoveries.count() == 1) + await #expect(throws: CancellationError.self) { try await queued.value } + #expect(await harness.transport.sentData.count == 4) + #expect(await Self.channelSendCount(harness.transport.sentData) == 1) + } + + @Test + func `channel command timeout fences before another command and ignores a late OK`() async throws { + let harness = try await Harness.started(clock: true) + defer { Task { await harness.session.stop() } } + let send = harness.send(scope: .scope(Self.namedScope)) + try await harness.ack(Self.scopeKey(Self.namedScope)) + try await harness.waitForFrames(3) + let queued = QueuedCommand.telemetry.start(harness.session) + try await harness.waitForWaiters(1) + try await harness.advanceCommandTimeout() + try await harness.waitUntilSubscribers(0) + await harness.transport.simulateOK() + await #expect { + try await send.value + } throws: { error in + guard let error = error as? MeshCoreError, case .timeout = error else { return false } + return true + } + #expect(await harness.session.floodScopeRecoveryRequired) + #expect(harness.recoveries.count() == 1) + await #expect(throws: CancellationError.self) { try await queued.value } + #expect(await harness.transport.sentData.count == 3) + #expect(await harness.transport.sentData.allSatisfy { $0 != Self.baselineReset }) + } + + @Test + func `preexisting response uncertainty fences the channel send before its first write`() async throws { + let harness = try await Harness.started(clock: true) + defer { Task { await harness.session.stop() } } + let stuck = Task { try await harness.session.setFloodScope(.region("Gamma")) } + try await harness.waitForFrames(2) + try await harness.advanceCommandTimeout() + await #expect { + try await stuck.value + } throws: { error in + guard let error = error as? MeshCoreError, case .timeout = error else { return false } + return true + } + #expect(await harness.session.floodScopeRecoveryRequired == false) + let send = harness.send(scope: .scope(Self.namedScope)) + await #expect { + try await send.value + } throws: { error in + guard let error = error as? MeshCoreError, case .timeout = error else { return false } + return true + } + #expect(await harness.transport.sentData.count == 2) + #expect(await harness.session.floodScopeRecoveryRequired) + #expect(harness.recoveries.count() == 1) + let queued = QueuedCommand.login.start(harness.session) + await #expect(throws: CancellationError.self) { try await queued.value } + #expect(await harness.transport.sentData.count == 2) + } + + @Test + func `an OK buffered before write completion confirms the send and still restores`() async throws { + let harness = try await Harness.started() + defer { Task { await harness.session.stop() } } + let send = harness.send(scope: .scope(Self.namedScope)) + try await harness.waitForFrames(2) + await harness.transport.holdNextSend() + try await harness.ack(Self.scopeKey(Self.namedScope)) + try await waitUntil("channel write should park") { await harness.transport.sendIsWaiting } + try await harness.waitUntilSubscribers(1) + await harness.session.dispatchForTesting(.ok(value: nil)) + await harness.transport.releaseHeldSend() + try await harness.ack(Self.baselineReset) + try await send.value + #expect(await harness.session.floodScopeRecoveryRequired == false) + #expect(await Self.channelSendCount(harness.transport.sentData) == 1) + } + + @Test + func `a failed write keeps a buffered channel OK and does not start a reset`() async throws { + let harness = try await Harness.started() + defer { Task { await harness.session.stop() } } + let send = harness.send(scope: .scope(Self.namedScope)) + try await harness.waitForFrames(2) + await harness.transport.holdNextSend() + await harness.transport.failHeldSend() + try await harness.ack(Self.scopeKey(Self.namedScope)) + try await waitUntil("channel write should park") { await harness.transport.sendIsWaiting } + try await harness.waitUntilSubscribers(1) + await harness.session.dispatchForTesting(.ok(value: nil)) + await harness.transport.releaseHeldSend() + try await send.value + #expect(await harness.session.floodScopeRecoveryRequired) + #expect(harness.recoveries.count() == 1) + #expect(await Self.channelSendCount(harness.transport.sentData) == 1) + #expect(await harness.transport.sentData.allSatisfy { $0 != Self.baselineReset }) + let queued = QueuedCommand.telemetry.start(harness.session) + await #expect(throws: CancellationError.self) { try await queued.value } + #expect(await harness.transport.sentData.count == 3) + } + + @Test(arguments: [true, false]) + func `a buffered rejection takes precedence over a failed scope or channel write`(duringSetup: Bool) async throws { + let harness = try await Harness.started() + defer { Task { await harness.session.stop() } } + if duringSetup { + await harness.transport.holdNextSend() + } + let send = harness.send(scope: .scope(Self.namedScope)) + if !duringSetup { + try await harness.waitForFrames(2) + await harness.transport.holdNextSend() + try await harness.ack(Self.scopeKey(Self.namedScope)) + } + try await waitUntil("scope or channel write should park") { await harness.transport.sendIsWaiting } + await harness.transport.failHeldSend() + let queued = QueuedCommand.login.start(harness.session) + try await harness.waitForWaiters(1) + try await harness.waitUntilSubscribers(1) + let rejectedCode = ErrorCode.badState.rawValue + await harness.session.dispatchForTesting(.error(code: rejectedCode)) + await harness.transport.releaseHeldSend() + + let error = await #expect(throws: MeshCoreError.self) { try await send.value } + guard case let .deviceError(code)? = error else { + Issue.record("Expected the radio rejection, got \(String(describing: error))") + return + } + #expect(code == rejectedCode) + #expect(await harness.session.floodScopeRecoveryRequired) + #expect(harness.recoveries.count() == 1) + await #expect(throws: CancellationError.self) { try await queued.value } + let frames = await harness.transport.sentData + #expect(frames.count == (duringSetup ? 2 : 3)) + #expect(Self.channelSendCount(frames) == (duringSetup ? 0 : 1)) + #expect(frames.allSatisfy { $0 != Self.baselineReset }) + #expect(frames.allSatisfy { $0.first != CommandCode.sendLogin.rawValue }) + } + + @Test + func `a buffered setup OK with a failed write fences before sending the channel message`() async throws { + let harness = try await Harness.started() + defer { Task { await harness.session.stop() } } + await harness.transport.holdNextSend() + let send = harness.send(scope: .scope(Self.namedScope)) + try await waitUntil("scope write should park") { await harness.transport.sendIsWaiting } + await harness.transport.failHeldSend() + let queued = QueuedCommand.login.start(harness.session) + try await harness.waitForWaiters(1) + try await harness.waitUntilSubscribers(1) + await harness.session.dispatchForTesting(.ok(value: nil)) + await harness.transport.releaseHeldSend() + + let error = await #expect(throws: MeshTransportError.self) { try await send.value } + guard case .sendFailed? = error else { + Issue.record("Expected the write failure, got \(String(describing: error))") + return + } + #expect(await harness.session.floodScopeRecoveryRequired) + #expect(harness.recoveries.count() == 1) + await #expect(throws: CancellationError.self) { try await queued.value } + let frames = await harness.transport.sentData + #expect(frames.count == 2) + #expect(Self.channelSendCount(frames) == 0) + #expect(frames.allSatisfy { $0 != Self.baselineReset }) + #expect(frames.allSatisfy { $0.first != CommandCode.sendLogin.rawValue }) + } + + @Test + func `stopping the session does not deliver flood scope recovery`() async throws { + let harness = try await Harness.started() + let send = harness.send(scope: .scope(Self.namedScope)) + try await harness.waitForFrames(2) + await harness.session.stop() + await #expect(throws: CancellationError.self) { try await send.value } + #expect(harness.recoveries.count() == 0) + } + + private static func scopeKey(_ scope: FloodScope) -> Data { + PacketBuilder.setFloodScope(scope.scopeKey()) + } + + private static var baselineReset: Data { + PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey()) + } + + private static var channelMessage: Data { + PacketBuilder.sendChannelMessage(channel: channel, text: "hello", timestamp: timestamp) + } + + private static var messageSent: Data { + Data([ResponseCode.messageSent.rawValue, 1, 2, 3, 4, 5, 50, 0, 0, 0]) + } + + private static func channelSendCount(_ frames: [Data]) -> Int { + frames.filter { $0.first == CommandCode.sendChannelMessage.rawValue }.count + } + + enum QueuedCommand { + case login, directMessage, telemetry + + var code: UInt8 { + switch self { + case .login: CommandCode.sendLogin.rawValue + case .directMessage: CommandCode.sendMessage.rawValue + case .telemetry: CommandCode.getSelfTelemetry.rawValue + } + } + + func start(_ session: MeshCoreSession) -> Task { + let key = ChannelFloodScopeLifetimeTests.contactKey + let timestamp = ChannelFloodScopeLifetimeTests.timestamp + return Task { + switch self { + case .login: + _ = try await session.sendLogin(to: key, password: "room") + case .directMessage: + _ = try await session.sendMessage(to: key, text: "dm", timestamp: timestamp) + case .telemetry: + _ = try await session.sendTelemetryRequest(to: key) + } + } + } + } + + private final class RecoveryNotifications: Sendable { + private let value = Mutex(0) + func record() { + value.withLock { $0 += 1 } + } + + func count() -> Int { + value.withLock { $0 } + } + } + + private struct Harness { + let session: MeshCoreSession + let transport: MockTransport + let clock: TestClock? + let recoveries: RecoveryNotifications + + static func started(clock useClock: Bool = false) async throws -> Harness { + let transport = MockTransport() + let clock = useClock ? TestClock() : nil + let session = MeshCoreSession( + transport: transport, + configuration: SessionConfiguration(defaultTimeout: commandTimeout, clientIdentifier: "MCTst"), + clock: clock + ) + let recoveries = RecoveryNotifications() + await session.setFloodScopeRecoveryHandler { recoveries.record() } + let harness = Harness(session: session, transport: transport, clock: clock, recoveries: recoveries) + let start = Task { try await session.start() } + try await harness.waitForFrames(1) + await transport.simulateReceive(selfInfo) + try await start.value + return harness + } + + func send(scope: ResolvedFloodScope) -> Task { + Task { + try await session.sendChannelMessage( + channel: ChannelFloodScopeLifetimeTests.channel, text: "hello", + timestamp: ChannelFloodScopeLifetimeTests.timestamp, floodScope: scope + ) + } + } + + func ack(_ expected: Data) async throws { + try await waitUntil("Expected \(expected.count)-byte frame") { + await transport.sentData.last == expected + } + try await waitUntilSubscribers(1) + await transport.simulateOK() + } + + func expectFrame(_ code: UInt8) async throws { + try await waitUntil("Expected command \(code)") { + await transport.sentData.contains { $0.first == code } + } + } + + func waitForFrames(_ count: Int) async throws { + try await waitUntil("Expected \(count) frames") { await transport.sentData.count >= count } + } + + func waitForWaiters(_ count: Int) async throws { + try await waitUntil("Expected \(count) waiting commands") { + await session.requestResponseSerializer.waiterCountForTest == count + } + } + + func waitUntilSubscribers(_ count: Int) async throws { + try await waitUntil("Expected \(count) event subscribers") { + await session.subscriberCountForTest == count + } + } + + func advanceCommandTimeout() async throws { + let clock = try #require(clock) + try await waitUntil("command timeout should park on the test clock") { clock.sleeperCount == 1 } + clock.advance(by: .seconds(ChannelFloodScopeLifetimeTests.commandTimeout)) + } + } +} + +private let selfInfo: Data = { + var packet = Data([ResponseCode.selfInfo.rawValue, 1, 22, 22]) + packet.append(Data(repeating: 1, count: 32)) + packet.append(Data(repeating: 0, count: 12)) + packet.append(contentsOf: withUnsafeBytes(of: UInt32(915_000).littleEndian) { Array($0) }) + packet.append(contentsOf: withUnsafeBytes(of: UInt32(125_000).littleEndian) { Array($0) }) + packet.append(contentsOf: [7, 5]) + packet.append(contentsOf: "Test".utf8) + return packet +}() diff --git a/MeshCore/Tests/MeshCoreTests/Session/ChannelSendSerializationTests.swift b/MeshCore/Tests/MeshCoreTests/Session/ChannelSendSerializationTests.swift index 87271489eb..83edd461af 100644 --- a/MeshCore/Tests/MeshCoreTests/Session/ChannelSendSerializationTests.swift +++ b/MeshCore/Tests/MeshCoreTests/Session/ChannelSendSerializationTests.swift @@ -12,7 +12,7 @@ struct ChannelSendSerializationTests { private static let selectedScope = FloodScope.region("Gamma") @Test - func `concurrent channels and UI scope changes cannot split a scope and send pair`() async throws { + func `concurrent channel sends and scope writes keep each send together`() async throws { let (session, transport) = try await startSession() let first = Task { try await session.sendChannelMessage( @@ -39,11 +39,15 @@ struct ChannelSendSerializationTests { channel: Self.firstChannel, text: "first", timestamp: Self.timestamp )) await transport.simulateOK() + try await waitForFrameCount(4, transport: transport) + #expect(await transport.sentData[3] == PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey())) + let framesBeforeRest = await transport.sentData.count + await transport.simulateOK() try await first.value - // Either waiter may acquire first, but Beta must stay next to its channel send. - for count in 4...6 { - try await waitForFrameCount(count, transport: transport) + // Waiters can arrive in either order. The second channel send still owns its setup and reset. + for offset in 1...4 { + try await waitForFrameCount(framesBeforeRest + offset, transport: transport) await transport.simulateOK() } try await second.value @@ -55,6 +59,7 @@ struct ChannelSendSerializationTests { #expect(frames[secondScopeIndex + 1] == PacketBuilder.sendChannelMessage( channel: Self.secondChannel, text: "second", timestamp: Self.timestamp )) + #expect(frames[secondScopeIndex + 2] == PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey())) #expect(frames.filter { $0.first == CommandCode.sendChannelMessage.rawValue }.count == 2) await session.stop() } @@ -135,29 +140,37 @@ struct ChannelSendSerializationTests { } let outstandingCount = afterScopeACK ? 3 : 2 send.cancel() - await #expect(throws: CancellationError.self) { - try await send.value - } let following = Task { try await session.setFloodScope(Self.selectedScope) } try await waitForSerializerWaiters(1, session: session) #expect(await transport.sentData.count == outstandingCount) await transport.simulateOK() - try await waitForFrameCount(outstandingCount + 1, transport: transport) - #expect(await transport.sentData[outstandingCount] == PacketBuilder.setFloodScope(Self.selectedScope.scopeKey())) + let resetCount = outstandingCount + 1 + try await waitForFrameCount(resetCount, transport: transport) + #expect(await transport.sentData[outstandingCount] == PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey())) + await transport.simulateOK() + if afterScopeACK { + try await send.value + } else { + await #expect(throws: CancellationError.self) { try await send.value } + } + + try await waitForFrameCount(resetCount + 1, transport: transport) + #expect(await transport.sentData[resetCount] == PacketBuilder.setFloodScope(Self.selectedScope.scopeKey())) let advertisement = Task { try await session.sendAdvertisement(flood: true) } try await waitForSerializerWaiters(1, session: session) - #expect(await transport.sentData.count == outstandingCount + 1, + #expect(await transport.sentData.count == resetCount + 1, "The scope change must still wait for its own ACK") await transport.simulateOK() - try await waitForFrameCount(outstandingCount + 2, transport: transport) + try await waitForFrameCount(resetCount + 2, transport: transport) #expect(await transport.sentData.last?.first == CommandCode.sendAdvertisement.rawValue) await transport.simulateOK() try await following.value try await advertisement.value let messageCount = await transport.sentData.filter { $0.first == CommandCode.sendChannelMessage.rawValue }.count #expect(messageCount == (afterScopeACK ? 1 : 0)) + #expect(await session.floodScopeRecoveryRequired == false) await session.stop() } diff --git a/MeshCore/Tests/MeshCoreTests/Session/MeshCoreSessionCommandCorrelationTests.swift b/MeshCore/Tests/MeshCoreTests/Session/MeshCoreSessionCommandCorrelationTests.swift index 5a26d0f6a3..4f0eac2bb2 100644 --- a/MeshCore/Tests/MeshCoreTests/Session/MeshCoreSessionCommandCorrelationTests.swift +++ b/MeshCore/Tests/MeshCoreTests/Session/MeshCoreSessionCommandCorrelationTests.swift @@ -1,5 +1,6 @@ import Foundation @testable import MeshCore +import MeshCoreTestSupport import Testing @Suite("MeshCoreSession command correlation") @@ -766,6 +767,144 @@ struct MeshCoreSessionCommandCorrelationTests { await session.stop() } + @Test(arguments: [true, false]) + func `status settlement owns the last retry host reply before a channel scope write`(replyArrives: Bool) async throws { + let transport = MockTransport() + let clock = TestClock() + let session = MeshCoreSession( + transport: CancellationSensitiveTransport(base: transport), + configuration: SessionConfiguration( + defaultTimeout: 5, binaryRequestOverallTimeout: 10, binaryRequestRetransmitInterval: 0.1 + ), + clock: clock + ) + try await startSession(session, transport: transport) + defer { + Task { + await transport.releaseHeldSend() + await session.stop() + } + } + + let target = Data(repeating: 0x31, count: 32) + let requestFrame = PacketBuilder.sendStatusRequest(to: target) + let status = Task { try await session.requestStatus(from: target) } + try await waitUntil("initial status request") { await transport.sentData.count == 2 } + await transport.simulateReceive(makeMessageSentPacket(expectedAck: Data([1, 2, 3, 4]), timeoutMs: 50)) + try await waitUntil("retry timer starts") { clock.sleeperCount == 2 } + await transport.holdNextSend() + clock.advanceToNextSleep() + try await waitUntil("status retry is submitted and its write is pending") { await transport.sendIsWaiting } + + let timestamp = Date(timeIntervalSince1970: 1_700_000_000) + let scope = FloodScope.region("Alpha") + let channel = Task { + try await session.sendChannelMessage(channel: 1, text: "hello", timestamp: timestamp, floodScope: .scope(scope)) + } + try await waitUntil("channel waits for status slot") { + await session.requestResponseSerializer.waiterCountForTest == 1 + } + await transport.simulateReceive(makeStatusResponsePacket(publicKeyPrefix: Data(target.prefix(6)), battery: 2200)) + try await waitUntil("the RF deadline is cancelled while the retry write is pending") { + clock.sleeperCount == 0 + } + await transport.releaseHeldSend() + try await waitUntil("only the local host-reply timer remains") { + clock.sleeperCount == 1 && clock.nextSleepDuration == .seconds(5) + } + try #require(await Array(transport.sentData.dropFirst()) == [requestFrame, requestFrame]) + + if replyArrives { + await transport.simulateError(code: ErrorCode.tableFull.rawValue) + try await acknowledgeChannelFrames(on: transport, after: 3, scope: scope, timestamp: timestamp) + try await channel.value + } else { + clock.advanceToNextSleep() + await #expect { + try await channel.value + } throws: { error in + if case MeshCoreError.timeout = error { return true } + return false + } + #expect(await transport.sentData.count == 3) + } + #expect(try await status.value.battery == 2200) + } + + @Test(arguments: [true, false]) + func `telemetry timeout leaves channel replies attributable only when the host replied`(hostReplied: Bool) async throws { + let transport = MockTransport() + let clock = TestClock() + let session = MeshCoreSession( + transport: transport, + configuration: SessionConfiguration(binaryRequestOverallTimeout: 1, binaryRequestRetransmitInterval: nil), + clock: clock + ) + try await startSession(session, transport: transport) + defer { Task { await session.stop() } } + + let target = Data(repeating: 0x31, count: 32) + let telemetry = Task { try await session.requestTelemetry(from: target) } + try await waitUntil("telemetry is submitted and waiting") { + await transport.sentData.count == 2 && clock.nextSleepDuration == .seconds(1) + } + if hostReplied { + await session.dispatchForTesting(.messageSent(MessageSentInfo( + route: 1, expectedAck: Data([1, 2, 3, 4]), suggestedTimeoutMs: 500 + ))) + } + clock.advanceToNextSleep() + await #expect { + try await telemetry.value + } throws: { error in + if case MeshCoreError.timeout = error { return true } + return false + } + + let timestamp = Date(timeIntervalSince1970: 1_700_000_000) + let scope = FloodScope.region("Alpha") + let channel = Task { + try await session.sendChannelMessage(channel: 1, text: "hello", timestamp: timestamp, floodScope: .scope(scope)) + } + if hostReplied { + try await acknowledgeChannelFrames(on: transport, after: 2, scope: scope, timestamp: timestamp) + try await channel.value + } else { + await #expect { + try await channel.value + } throws: { error in + if case MeshCoreError.timeout = error { return true } + return false + } + #expect(await transport.sentData.count == 2) + } + } + + private struct CancellationSensitiveTransport: MeshTransport { + let base: MockTransport + + var receivedData: AsyncStream { + get async { await base.receivedData } + } + + var isConnected: Bool { + get async { await base.isConnected } + } + + func connect() async throws { + try await base.connect() + } + + func disconnect() async { + await base.disconnect() + } + + func send(_ data: Data) async throws { + try await base.send(data) + if Task.isCancelled { throw MeshTransportError.sendFailed("cancelled after submission") } + } + } + @Test(arguments: ["", " KD7ABC\nch 31\n"], [Data(), Data(repeating: 0, count: 8)]) func `owner info stops at the null terminator and preserves text`(ownerInfo: String, padding: Data) async throws { let transport = MockTransport() @@ -1361,6 +1500,27 @@ struct MeshCoreSessionCommandCorrelationTests { } } +private func acknowledgeChannelFrames( + on transport: MockTransport, + after priorFrameCount: Int, + scope: FloodScope, + timestamp: Date +) async throws { + let frames = [ + PacketBuilder.setFloodScope(scope.scopeKey()), + PacketBuilder.sendChannelMessage(channel: 1, text: "hello", timestamp: timestamp), + PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey()) + ] + for (offset, frame) in frames.enumerated() { + let index = priorFrameCount + offset + try await waitUntil("channel scope, message and reset must be sent in order") { + await transport.sentData.count > index + } + try #require(await transport.sentData[index] == frame) + await transport.simulateOK() + } +} + private func startSession( _ session: MeshCoreSession, transport: MockTransport, diff --git a/MeshCore/Tests/MeshCoreTests/Session/VerifiedChannelSendSerializationTests.swift b/MeshCore/Tests/MeshCoreTests/Session/VerifiedChannelSendSerializationTests.swift index ed795e6be1..2eba63d54e 100644 --- a/MeshCore/Tests/MeshCoreTests/Session/VerifiedChannelSendSerializationTests.swift +++ b/MeshCore/Tests/MeshCoreTests/Session/VerifiedChannelSendSerializationTests.swift @@ -29,6 +29,7 @@ struct VerifiedChannelSendSerializationTests { await expectOccupancyMismatch(send) #expect(await transport.sentData.allSatisfy { $0.first != CommandCode.sendChannelMessage.rawValue }) #expect(await transport.sentData.allSatisfy { $0.first != CommandCode.setFloodScope.rawValue }) + #expect(await session.floodScopeRecoveryRequired == false) await session.stop() } @@ -56,9 +57,16 @@ struct VerifiedChannelSendSerializationTests { )) #expect(await transport.sentData.allSatisfy { $0.first != CommandCode.setChannel.rawValue }) await transport.simulateOK() + let replacementIndex = sendFrameCount + if scoped { + try await waitForFrames(sendFrameCount + 1, transport: transport) + #expect(await transport.sentData[sendFrameCount] == PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey())) + await transport.simulateOK() + } + let channelWriteIndex = scoped ? replacementIndex + 1 : replacementIndex try await send.value - try await waitForFrames(sendFrameCount + 1, transport: transport) - #expect(await transport.sentData[sendFrameCount] == PacketBuilder.setChannel( + try await waitForFrames(channelWriteIndex + 1, transport: transport) + #expect(await transport.sentData[channelWriteIndex] == PacketBuilder.setChannel( index: Self.index, name: "B", secret: Self.secretB )) await transport.simulateOK() @@ -73,7 +81,6 @@ struct VerifiedChannelSendSerializationTests { let send = verifiedSend(session, scoped: scoped) try await waitForFrames(2, transport: transport) send.cancel() - await #expect(throws: CancellationError.self) { try await send.value } let following = Task { try await session.setChannel(index: Self.index, name: "B", secret: Self.secretB) } try await waitForWaiters(1, session: session) #expect(await transport.sentData.count == 2) @@ -84,6 +91,7 @@ struct VerifiedChannelSendSerializationTests { #expect(await transport.sentData.allSatisfy { $0.first != CommandCode.setFloodScope.rawValue }) await transport.simulateOK() try await following.value + await #expect(throws: CancellationError.self) { try await send.value } await session.stop() } diff --git a/docs/api/MeshCore.md b/docs/api/MeshCore.md index d21ed78802..d1f593e2a1 100644 --- a/docs/api/MeshCore.md +++ b/docs/api/MeshCore.md @@ -52,7 +52,9 @@ The primary entry point for communicating with a MeshCore device. Serializes all |--------|-------------| | `sendMessage(to:text:timestamp:) async throws -> MessageSentInfo` | Sends a direct message to a contact (6-byte public key prefix or `Destination`) | | `sendMessageWithRetry(to:text:timestamp:maxAttempts:floodAfter:maxFloodAttempts:timeout:) async throws -> MessageSentInfo?` | Sends with automatic retry and flood fallback (requires 32-byte key) | -| `sendChannelMessage(channel:text:timestamp:) async throws` | Broadcasts to a channel slot (0-15) | +| `sendChannelMessage(channel:text:timestamp:) async throws` | Broadcasts to a channel slot (0-15) without changing flood scope | +| `sendChannelMessage(channel:text:timestamp:floodScope:) async throws` | Broadcasts with a temporary `ResolvedFloodScope`, then restores the baseline before the next command | +| `sendVerifiedChannelMessage(channel:text:timestamp:floodScope:expectedSecret:) async throws` | Checks the slot secret and broadcasts under the same temporary-scope rules when `floodScope` is non-nil | | `sendCommand(to:command:timestamp:) async throws -> MessageSentInfo` | Sends a command message to a remote node | | `sendAdvertisement(flood:) async throws` | Sends an advertisement broadcast, optionally using flood routing | | `sendLogin(to:password:) async throws -> MessageSentInfo` | Sends a login request to a remote node (accepts `Data` or `Destination`) | @@ -144,8 +146,9 @@ The primary entry point for communicating with a MeshCore device. Serializes all | `getChannel(index:) async throws -> ChannelInfo` | Retrieves configuration for a channel (index 0-15) | | `setChannel(index:name:secret:) async throws` | Configures a channel with name and PSK secret data (16 bytes) | | `setChannel(index:name:secret:) async throws` | Configures a channel with automatic secret derivation (accepts `ChannelSecret`, default: `.deriveFromName`) | -| `setFloodScope(scopeKey:) async throws` | Sets the flood scope using a raw 32-byte scope key | -| `setFloodScope(_:) async throws` | Sets the flood scope using a `FloodScope` enum | +| `setFloodScope(scopeKey:) async throws` | Sticky flood scope from a 16-byte key. A zero key clears the RAM override and selects the radio's persisted default | +| `setFloodScope(_:) async throws` | Sticky flood scope from a `FloodScope`. Unlike a channel send, this is not restored after the next command | +| `setFloodScopeUnscoped() async throws` | Sticky `36 01` override. Requires protocol capability 12 or newer | ### Signing @@ -504,7 +507,7 @@ Defines the scope for flood routing in the mesh network. | Case | Payload | Description | |------|---------|-------------| -| `.disabled` | - | Flood routing is disabled | +| `.disabled` | - | 16-byte zero key. With `setFloodScope`, clears the temporary override and uses the radio's persisted default | | `.channelName(String)` | Channel name | Scope derived from channel name hash | | `.rawKey(Data)` | 16-byte key | Scope using explicit key | | `.region(String)` | Region name | Scope from `SHA256("#" + name).prefix(16)`; `#` prefix added automatically | @@ -512,6 +515,8 @@ Defines the scope for flood routing in the mesh network. **Methods:** - `scopeKey() -> Data` - Generates a 16-byte scope key +`ResolvedFloodScope` (`MeshCore/Sources/MeshCore/Models/ResolvedFloodScope.swift`) is the channel-send value. `.scope(.disabled)` is the 16-byte zero key and selects the radio's persisted default. `.unscoped` forces no region (`36 01`) and requires protocol capability 12 or newer. A send with `ResolvedFloodScope` confirms restoration before releasing the command slot or fences the session. The nil-scope verified send only checks occupancy and sends. `setFloodScope` is the sticky API. + ### ChannelSecret (public, enum) **File:** `MeshCore/Sources/MeshCore/Models/Destination.swift` diff --git a/docs/guides/Messaging.md b/docs/guides/Messaging.md index 1a1ad3960b..837a3547a2 100644 --- a/docs/guides/Messaging.md +++ b/docs/guides/Messaging.md @@ -282,8 +282,10 @@ The SHA256 hash ensures that: - Broadcast to a channel slot (0..<(device.maxChannels)) - Encrypted with shared channel secret (SHA-256 of passphrase) -- No ACK support (broadcast, not point-to-point) -- Use `sendChannelMessage()` +- No end-to-end ACK. `.sent` means the radio accepted `03` with `RES_CODE_OK` (queued for TX) +- Use `sendChannelMessage()`. A `ResolvedFloodScope` on that send is temporary: a 16-byte named key or `36 01` is restored with zero-key `36 00` before the next app command. A zero key is the baseline and has no trailing reset. `setFloodScope` stays sticky +- `ChannelFloodScopeResolver` resolves transmission preferences. Inheritance selects the radio's persisted default; the channel header uses the cached default name only for display +- An accepted `03` stays `.sent` if cleanup fails. The session fences further messaging commands while the connection owner arranges replacement. Retirement joins the Sent write for queued sends and inline quick replies before the conversation reloads ```swift // Channel message format: "NodeName: message text" From 6125af2611107106d6014d70a67c924cd6aa0966 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Fri, 6 Nov 2026 07:07:05 -0800 Subject: [PATCH 13/66] fix: stop restarting dm sends after acceptance - End the send pass when a later command times out or exhausts TABLE_FULL retries, and keep waiting for eligible ACKs. - Retry failed ACK owner writes through the ACK checker. --- .../Services/ChatSendQueueService.swift | 2 +- .../Services/MessageService+ACK.swift | 5 +- .../Services/MessageService+ACKRecovery.swift | 151 +++++------ .../Services/MessageService+DMRetry.swift | 200 ++++++++++++++ .../Services/MessageService+SendDM.swift | 245 ++---------------- .../MC1Services/Services/MessageService.swift | 13 +- .../Services/MessageServiceConfig.swift | 2 +- .../MC1Services/Services/PendingAck.swift | 26 +- .../PersistenceStore+Acknowledgements.swift | 9 + .../Services/PersistenceStore.swift | 1 + ...ndingAcknowledgementPersistenceTests.swift | 5 +- .../MessageServiceACKRecoveryTests.swift | 2 +- .../Services/MessageServiceACKTests.swift | 32 +-- ...MessageServiceSendDMBookkeepingTests.swift | 56 ++-- .../Services/MessageServiceSendTests.swift | 45 ++-- .../PlainTextSendGateTests+PartialSend.swift | 101 ++++++++ ...SendGateTests+PartialSendPersistence.swift | 100 +++++++ .../PlainTextSendGateTests+Queue.swift | 2 +- .../PlainTextSendGateTests+RadioHarness.swift | 23 +- .../PlainTextSendGateTests+RadioScript.swift | 63 ++++- docs/guides/Messaging.md | 66 +++-- 21 files changed, 707 insertions(+), 442 deletions(-) create mode 100644 MC1Services/Sources/MC1Services/Services/MessageService+DMRetry.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+PartialSend.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+PartialSendPersistence.swift diff --git a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift index 10a8026a0b..639484f5ae 100644 --- a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift +++ b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift @@ -208,7 +208,7 @@ public final class ChatSendQueueService { pendingSendID: pendingSendID, sendLease: sendLease ) - if message.status != .sent, let pendingSendID { + if message.status == .delivered || message.status == .failed, let pendingSendID { try? await dataStoreRef.deletePendingSend(id: pendingSendID) } osLoggerRef.debug("DM drain success messageID=\(envelope.messageID)") diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+ACK.swift b/MC1Services/Sources/MC1Services/Services/MessageService+ACK.swift index 49bd43c930..b88b0737a5 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+ACK.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+ACK.swift @@ -69,12 +69,13 @@ 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 > (tracking.deadline ?? tracking.sentAt.addingTimeInterval(max(window, tracking.timeout))) + now > tracking.expiresAt(giveUpWindow: window) } for (messageID, tracking) in expiredEntries { @@ -86,7 +87,7 @@ public extension MessageService { guard let current = pendingAcks[messageID], !current.isDelivered, current.sentAt == tracking.sentAt, - now > (current.deadline ?? current.sentAt.addingTimeInterval(max(window, current.timeout))) else { continue } + now > current.expiresAt(giveUpWindow: window) else { continue } let result: PendingAcknowledgementCommit do { diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift b/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift index 955fb45d0f..7026d4ff7d 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift @@ -3,7 +3,6 @@ import Foundation enum PendingAcknowledgementCommit { case committed(MessageStatus) case unchanged - case waitingForOwner } extension MessageService { @@ -20,13 +19,13 @@ extension MessageService { restored[row.messageID] = PendingAck( messageID: row.messageID, contactID: contactID, ackCodes: Set(codes), sentAt: sentAt, timeout: deadline.timeIntervalSince(sentAt), - pendingSendID: row.id, deadline: deadline + owner: .init(id: row.id, radioID: radioID, deadline: deadline, phase: .saved) ) } let now = Date() for (id, tracking) in restored { - if let deadline = tracking.deadline, deadline > now { - restored[id]?.sendLeaseID = tracking.pendingSendID + if let owner = tracking.owner, owner.deadline > now { + restored[id]?.sendLeaseID = owner.id } } // Reserve recovered ACK owners before hydration can admit another send. @@ -34,56 +33,77 @@ extension MessageService { pendingAcks.merge(restored) { _, restored in restored } } - func persistAcknowledgement( - messageID: UUID, radioID: UUID, pendingSendID: UUID? - ) async throws -> Bool { - beginAcknowledgementSave(messageID) - defer { endAcknowledgementSave(messageID) } + @discardableResult + func persistAcknowledgement(messageID: UUID, radioID: UUID, pendingSendID: UUID?) async -> Bool { guard let tracking = pendingAcks[messageID], !tracking.isDelivered else { return false } + if tracking.owner == nil { + pendingAcks[messageID]?.owner = .init( + id: pendingSendID ?? UUID(), + radioID: radioID, + deadline: tracking.expiresAt(giveUpWindow: config.ackGiveUpWindow), + phase: pendingSendID == nil ? .insert : .convert + ) + } + return await saveAcknowledgementOwner(messageID: messageID) + } + + private func saveAcknowledgementOwner(messageID: UUID) async -> Bool { + guard let tracking = pendingAcks[messageID], !tracking.isDelivered, + let owner = tracking.owner, owner.phase != .saved, + acknowledgementSavesInFlight.insert(messageID).inserted else { return false } + 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 ownerID = pendingSendID ?? UUID() - let deadline = tracking.sentAt.addingTimeInterval(max(config.ackGiveUpWindow, tracking.timeout)) - let row = PendingSendDTO( - id: ownerID, envelope: DirectMessageEnvelope(messageID: messageID, contactID: tracking.contactID), - radioID: radioID, enqueuedAt: tracking.sentAt, - ackCodes: Array(tracking.ackCodes), ackSentAt: tracking.sentAt, ackDeadline: deadline - ) let saved: Bool do { - saved = try await dataStore.savePendingAcknowledgement(row, replacingPendingSendID: pendingSendID) + saved = try await dataStore.savePendingAcknowledgement( + row, replacingPendingSendID: owner.phase == .convert ? owner.id : nil + ) } catch { - throw MessageServiceError.persistenceError(error) + logger.warning("ACK owner save deferred messageID=\(messageID): \(String(describing: error))") + return false } - noteAcknowledgementSaveCommitted(messageID) - guard saved else { - if removePendingAckIfCurrent(tracking) { - await settlePlainTextLease(tracking.sendLeaseID) + + guard let current = pendingAcks[messageID], current.owner == owner, + current.sentAt == tracking.sentAt, !current.isDelivered else { + if saved { + await cleanUpStaleAcknowledgementOwner(tracking, owner: owner) } return false } - #if DEBUG - if let gate = acknowledgementInstallGateForTesting { await gate() } - #endif - if let current = pendingAcks[messageID] { - if current.sentAt == tracking.sentAt, !current.isDelivered { - pendingAcks[messageID]?.pendingSendID = ownerID - pendingAcks[messageID]?.deadline = deadline - if current.matchedAckCode != nil { - _ = try await commitPendingAcknowledgement(messageID: messageID, sentAt: current.sentAt) - } - } else if current.sentAt != tracking.sentAt { - try await dataStore.deletePendingSend(id: ownerID) - } else { - try await resolveFinishedOwner(messageID: messageID, ownerID: ownerID, deadline: deadline) + guard saved else { + await discardTrackedAck(messageID: messageID) + return false + } + + pendingAcks[messageID]?.owner?.phase = .saved + 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 } - } else { - try await resolveFinishedOwner(messageID: messageID, ownerID: ownerID, deadline: deadline) } return true } + func retryPendingAcknowledgementSaves() async { + for messageID in pendingAcks.keys { + if await saveAcknowledgementOwner(messageID: messageID) { + statusEventBroadcaster.yield(.statusResolved(messageID: messageID, status: .sent, roundTripTime: nil)) + } + } + } + func waitForAcknowledgementSaves() async { guard !acknowledgementSavesInFlight.isEmpty else { return } await withCheckedContinuation { continuation in @@ -93,9 +113,7 @@ extension MessageService { func commitPendingAcknowledgement(messageID: UUID, sentAt: Date) async throws -> PendingAcknowledgementCommit { guard let current = pendingAcks[messageID], current.sentAt == sentAt else { return .unchanged } - if uncommittedAcknowledgementSaves.contains(messageID), current.pendingSendID == nil { - return .waitingForOwner - } + if let owner = current.owner, owner.phase != .saved { return .unchanged } let status: MessageStatus = current.matchedAckCode == nil ? .failed : .delivered let leaseID = current.sendLeaseID let updated = try await writeTerminalAcknowledgement(current, status: status) @@ -129,23 +147,8 @@ extension MessageService { return .committed(status) } - private func beginAcknowledgementSave(_ messageID: UUID) { - acknowledgementSavesInFlight[messageID, default: 0] += 1 - uncommittedAcknowledgementSaves.insert(messageID) - } - - private func noteAcknowledgementSaveCommitted(_ messageID: UUID) { - uncommittedAcknowledgementSaves.remove(messageID) - } - private func endAcknowledgementSave(_ messageID: UUID) { - uncommittedAcknowledgementSaves.remove(messageID) - let remaining = (acknowledgementSavesInFlight[messageID] ?? 1) - 1 - if remaining > 0 { - acknowledgementSavesInFlight[messageID] = remaining - } else { - acknowledgementSavesInFlight.removeValue(forKey: messageID) - } + acknowledgementSavesInFlight.remove(messageID) guard acknowledgementSavesInFlight.isEmpty else { return } let waiters = acknowledgementSaveWaiters acknowledgementSaveWaiters.removeAll() @@ -155,9 +158,9 @@ extension MessageService { } private func writeTerminalAcknowledgement(_ current: PendingAck, status: MessageStatus) async throws -> Bool { - if let ownerID = current.pendingSendID { + if let owner = current.owner { return try await dataStore.resolvePendingAcknowledgement( - id: ownerID, expectedDeadline: current.deadline, status: status, + id: owner.id, expectedDeadline: owner.deadline, status: status, ackCode: current.matchedAckCode, roundTripTime: current.matchedTripTime ) } @@ -172,20 +175,20 @@ extension MessageService { return try await dataStore.updateMessageStatusUnlessDelivered(id: current.messageID, status: .failed) } - private func resolveFinishedOwner(messageID: UUID, ownerID: UUID, deadline: Date) async throws { - let message = try await dataStore.fetchMessage(id: messageID) - guard message == nil || message?.status == .delivered || message?.status == .failed else { return } - _ = try await dataStore.resolvePendingAcknowledgement( - id: ownerID, expectedDeadline: deadline, status: message?.status ?? .failed, - ackCode: message?.ackCode, roundTripTime: message?.roundTripTime - ) - } - - @discardableResult - func removePendingAckIfCurrent(_ tracking: PendingAck) -> Bool { - guard let current = pendingAcks[tracking.messageID], current.sentAt == tracking.sentAt, - current.pendingSendID == tracking.pendingSendID else { return false } - pendingAcks.removeValue(forKey: tracking.messageID) - return true + 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+DMRetry.swift b/MC1Services/Sources/MC1Services/Services/MessageService+DMRetry.swift new file mode 100644 index 0000000000..e5a7a8863d --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/MessageService+DMRetry.swift @@ -0,0 +1,200 @@ +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? + ) async throws -> Data? { + let maxRetryAttempts = budget.totalAttempts - 1 + let sendDate = Date(timeIntervalSince1970: TimeInterval(timestamp)) + var lastExpectedAck: Data? + + for attemptIndex in 0.. 0 { + try await dataStore.updateMessageRetryStatus( + id: messageID, + status: .retrying, + retryAttempt: attemptIndex - 1, + maxRetryAttempts: maxRetryAttempts + ) + statusEventBroadcaster.yield(.retrying( + messageID: messageID, + attempt: attemptIndex - 1, + maxAttempts: maxRetryAttempts + )) + } + + if attemptIndex == budget.directAttempts { + logger.info("Resetting path to flood after \(attemptIndex) failed attempts") + 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 attemptIndex > 0 { + logger.info("Retry sending message: attempt \(attemptIndex + 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 lastExpectedAck != nil, pendingAcks[messageID]?.isAwaitingAck != true { return lastExpectedAck } + let previousAck = pendingAcks[messageID] + + let predictedAck = AckCodeBuilder.expectedAck( + timestamp: timestamp, + attempt: UInt8(attemptIndex), + 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) + trackPendingAck( + messageID: messageID, + contactID: contact.id, + ackCode: predictedAck, + timeout: preSendTimeout, + sendLeaseID: sendLease?.id + ) + await notePlainTextLease(sendLease) + + let sentInfo: MessageSentInfo? + 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: UInt8(attemptIndex) + ) + } + } catch { + if lastExpectedAck != nil, !Task.isCancelled, + retainAcceptedDMAfterCommandFailure( + error, messageID: messageID, previousAck: previousAck, sendLeaseID: sendLease?.id + ) { + logger.warning("DM command issuance ended messageID=\(messageID) attempt=\(attemptIndex): \(String(describing: error))") + return pendingAcks[messageID]?.isAwaitingAck == true ? nil : lastExpectedAck + } + await discardTrackedAck(messageID: messageID) + throw error + } + 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)) + + recordDMCommandAcceptance( + messageID: messageID, sentInfo: sentInfo, predictedAck: predictedAck, timeout: ackTimeout + ) + + let ackEvent = await session.waitForEvent( + filter: .acknowledgement(code: sentInfo.expectedAck), + timeout: ackTimeout + ) + + if ackEvent != nil || pendingAcks[messageID]?.isAwaitingAck != true { + return lastExpectedAck + } + } + + logger.info("DM retry budget spent messageID=\(messageID) attempts=\(budget.totalAttempts)") + return nil + } + + private func submitDMCommand( + messageID: UUID, publicKey: Data, text: String, timestamp: Date, attempt: UInt8 + ) async throws -> MessageSentInfo? { + 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() + return try await session.sendMessage(to: publicKey.prefix(6), text: text, timestamp: timestamp, attempt: attempt) + } + + func recordDMCommandAcceptance(messageID: UUID, sentInfo: MessageSentInfo, predictedAck: Data, timeout: TimeInterval) { + guard let tracking = pendingAcks[messageID], tracking.isAwaitingAck else { return } + if sentInfo.expectedAck != predictedAck { + logger.warning("DM expected ACK differs from prediction messageID=\(messageID)") + 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 } + if rejected { + // Restore accepted codes and timing without overwriting an ACK matched during the command. + 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 + } +} diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift index 0850caef23..041898eb15 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift @@ -48,9 +48,8 @@ public extension MessageService { var sendLease: PlainTextSendGate.Lease? defer { await stopPlainTextLease(sendLease) } - var ackOwnerCommitted = false defer { - if !ackOwnerCommitted { + 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) { @@ -116,32 +115,18 @@ public extension MessageService { if let gate = inlineSendAcceptedGateForTesting { await gate() } #endif - let ackTimeout = TimeInterval(sentInfo.suggestedTimeoutMs) / 1000.0 * 1.2 + let ackTimeout = dmAckTimeout(for: sentInfo) - 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, - sendLeaseID: sendLease?.id - ) - } else { - pendingAcks[messageID]?.timeout = ackTimeout - pendingAcks[messageID]?.sentAt = Date() - } + recordDMCommandAcceptance( + messageID: messageID, sentInfo: sentInfo, predictedAck: predictedAck, timeout: ackTimeout + ) // The radio accepted the send; bookkeeping errors must leave terminal status // to the end-to-end ACK or expiry checker. do { - if try await persistAcknowledgement( + await persistAcknowledgement( messageID: messageID, radioID: contact.radioID, pendingSendID: pendingSendID - ) { - ackOwnerCommitted = true - } + ) // updateMessageAck preserves `.delivered`, so writing `.sent` here // is a no-op when the listener already won the race. try await dataStore.updateMessageAck( @@ -200,14 +185,11 @@ public 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, + timestamp: timestamp, timeout: timeout > 0 ? timeout : nil, budget: dmSendBudgetProvider(), sendLease: sendLease @@ -218,7 +200,7 @@ public extension MessageService { contactID: contact.id, radioID: contact.radioID, publicKey: contact.publicKey, - sentInfo: sentInfo, + acknowledgedCode: acknowledgedCode, initialPathLength: initialPathLength ) } catch { @@ -351,26 +333,17 @@ public extension MessageService { // 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 - if preserveTimestamp { - wireTimestampRaw = existingMessage.timestamp - wireTimestamp = Date(timeIntervalSince1970: TimeInterval(wireTimestampRaw)) - } else { - wireTimestamp = Date() - wireTimestampRaw = UInt32(wireTimestamp.timeIntervalSince1970) - try await dataStore.updateMessageTimestamp(id: messageID, timestamp: wireTimestampRaw) + let wireTimestamp = preserveTimestamp ? existingMessage.timestamp : UInt32(Date().timeIntervalSince1970) + if !preserveTimestamp { + try await dataStore.updateMessageTimestamp(id: messageID, timestamp: wireTimestamp) } 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, budget: isSingleAttempt ? .singleAttempt : dmSendBudgetProvider(), sendLease: sendLease @@ -380,7 +353,7 @@ public extension MessageService { // 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 { @@ -393,14 +366,14 @@ public extension MessageService { contactID: contact.id, radioID: contact.radioID, publicKey: contact.publicKey, - sentInfo: sentInfo, + 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)) } @@ -417,166 +390,6 @@ public extension MessageService { } } - // MARK: - Direct Message Retry Loop - - private func sendDirectMessageWithRetryLoop( - messageID: UUID, - contactID: UUID, - radioID: UUID, - publicKey: Data, - text: String, - timestamp: Date, - timestampRaw: UInt32, - timeout: TimeInterval?, - budget: DMSendBudget, - sendLease: PlainTextSendGate.Lease? - ) async throws -> MessageSentInfo? { - let maxRetryAttempts = budget.totalAttempts - 1 - - for attemptIndex in 0.. 0 { - try await dataStore.updateMessageRetryStatus( - id: messageID, - status: .retrying, - retryAttempt: attemptIndex - 1, - maxRetryAttempts: maxRetryAttempts - ) - statusEventBroadcaster.yield(.retrying( - messageID: messageID, - attempt: attemptIndex - 1, - maxAttempts: maxRetryAttempts - )) - } - - if attemptIndex == budget.directAttempts { - logger.info("Resetting path to flood after \(attemptIndex) 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() - ) - } - 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...") - } - } - - if attemptIndex > 0 { - logger.info("Retry sending message: attempt \(attemptIndex + 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 - } - - let predictedAck = AckCodeBuilder.expectedAck( - timestamp: timestampRaw, - attempt: UInt8(attemptIndex), - 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) - trackPendingAck( - messageID: messageID, - contactID: contactID, - ackCode: predictedAck, - timeout: preSendTimeout, - sendLeaseID: sendLease?.id - ) - await notePlainTextLease(sendLease) - - 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(attemptIndex) - ) - } - } 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. - await discardTrackedAck(messageID: 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 \(attemptIndex): predicted \(predictedAck.uppercaseHexString()) vs firmware \(sentInfo.expectedAck.uppercaseHexString()); merging firmware code" - ) - trackPendingAck( - messageID: messageID, - contactID: contactID, - ackCode: sentInfo.expectedAck, - timeout: ackTimeout, - sendLeaseID: sendLease?.id - ) - } 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 \(attemptIndex + 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 - } - } - - logger.warning("Message delivery failed after \(budget.totalAttempts) attempts") - return nil - } - // MARK: - Routing Change Detection /// Checks if contact routing changed and broadcasts `.routingChanged` if so. @@ -646,8 +459,7 @@ public extension MessageService { existing.ackCodes.insert(ackCode) existing.sentAt = Date() existing.timeout = timeout - existing.pendingSendID = nil - existing.deadline = nil + existing.owner = nil if let sendLeaseID { existing.sendLeaseID = sendLeaseID } @@ -674,7 +486,7 @@ public extension MessageService { contactID: UUID, radioID: UUID, publicKey: Data, - sentInfo: MessageSentInfo?, + acknowledgedCode: Data?, initialPathLength: UInt8, pendingSendID: UUID? = nil ) async throws -> MessageDTO { @@ -691,7 +503,7 @@ public extension MessageService { let leaseID = tracking?.sendLeaseID pendingAcks.removeValue(forKey: messageID) await settlePlainTextLease(leaseID) - } else if let sentInfo { + } else if let acknowledgedCode, tracking?.matchedAckCode == nil { // The retry loop's waitForEvent matched the ACK. Take ownership and // record the legitimate `.sent` -> `.delivered` upgrade. let leaseID = tracking?.sendLeaseID @@ -699,20 +511,15 @@ public extension MessageService { await settlePlainTextLease(leaseID) try await dataStore.updateMessageAck( id: messageID, - ackCode: sentInfo.expectedAck.ackCodeUInt32, + ackCode: acknowledgedCode.ackCodeUInt32, status: .delivered ) try await dataStore.updateContactLastMessage(contactID: contactID, date: Date()) statusEventBroadcaster.yield(.statusResolved(messageID: messageID, status: .delivered, roundTripTime: nil)) } 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. - // The original PendingSend becomes a durable ACK owner in the same - // transaction that clears `.retrying`; a replacement or terminal row - // cannot be adopted by this send. - let movedToSent = try await persistAcknowledgement( + // Command issuance ended; durable ACK ownership preserves late matches + // and retries a failed owner save without submitting another command. + let movedToSent = await persistAcknowledgement( messageID: messageID, radioID: radioID, pendingSendID: pendingSendID ) if movedToSent { diff --git a/MC1Services/Sources/MC1Services/Services/MessageService.swift b/MC1Services/Sources/MC1Services/Services/MessageService.swift index b5adc164df..c84eae6296 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService.swift @@ -55,11 +55,8 @@ 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] = [:] - - /// Owner saves inside `persistAcknowledgement`, keyed by message. - var acknowledgementSavesInFlight: [UUID: Int] = [:] - /// Saves whose store commit has not returned. A nil-owner status write waits for that commit. - var uncommittedAcknowledgementSaves: Set = [] + /// Keeps teardown waiting for store writes even if their trackers disappear. + var acknowledgementSavesInFlight: Set = [] var inlineSendsInFlight = 0 var inlineSendAdmissionClosed = false var inlineSendWaiters: [CheckedContinuation] = [] @@ -73,8 +70,6 @@ public actor MessageService { var inlineSendAcceptedGateForTesting: (@Sendable () async -> Void)? /// Runs after an owner save is entered and before its store commit. var acknowledgementSaveGateForTesting: (@Sendable () async -> Void)? - /// Runs after the owner row commits and before `pendingSendID` is attached. - var acknowledgementInstallGateForTesting: (@Sendable () async -> Void)? func setAckExpiryWriteGateForTesting(_ gate: (@Sendable (UUID) async -> Void)?) { ackExpiryWriteGateForTesting = gate @@ -88,10 +83,6 @@ public actor MessageService { acknowledgementSaveGateForTesting = gate } - func setAcknowledgementInstallGateForTesting(_ gate: (@Sendable () async -> Void)?) { - acknowledgementInstallGateForTesting = gate - } - var acknowledgementSaveWaiterCountForTesting: Int { acknowledgementSaveWaiters.count } diff --git a/MC1Services/Sources/MC1Services/Services/MessageServiceConfig.swift b/MC1Services/Sources/MC1Services/Services/MessageServiceConfig.swift index 150a245e31..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 diff --git a/MC1Services/Sources/MC1Services/Services/PendingAck.swift b/MC1Services/Sources/MC1Services/Services/PendingAck.swift index b40be2d6b2..fd512a71c5 100644 --- a/MC1Services/Sources/MC1Services/Services/PendingAck.swift +++ b/MC1Services/Sources/MC1Services/Services/PendingAck.swift @@ -2,12 +2,21 @@ 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. +/// All attempts for the same message share one entry and may add ACK codes. /// /// Only DMs are tracked here. `RoomServerService` waits for room post ACKs separately. struct PendingAck { + struct Owner: Equatable { + enum Phase { + case insert, convert, saved + } + + let id: UUID + let radioID: UUID + let deadline: Date + var phase: Phase + } + let messageID: UUID let contactID: UUID var ackCodes: Set @@ -17,11 +26,18 @@ struct PendingAck { /// so a slow high-spreading-factor round-trip is not failed while still in flight. var timeout: TimeInterval var isDelivered: Bool = false - var pendingSendID: UUID? - var deadline: Date? + var owner: Owner? /// Set when an acknowledgement matches and kept until the terminal save commits. var matchedAckCode: UInt32? var matchedTripTime: UInt32? /// Admission lease for this ACK. A restored live ACK uses its persisted owner ID. var sendLeaseID: UUID? + + var isAwaitingAck: Bool { + !isDelivered && matchedAckCode == nil + } + + 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 index ff2896feec..5abf311de9 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Acknowledgements.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Acknowledgements.swift @@ -37,6 +37,9 @@ public extension PersistenceStore { row.ackDeadline = dto.ackDeadline message.status = .sent do { + #if DEBUG + try savePendingAcknowledgementFaultInjection?() + #endif try modelContext.save() } catch { modelContext.rollback() @@ -72,4 +75,10 @@ public extension PersistenceStore { } return shouldUpdate } + + #if DEBUG + func setSavePendingAcknowledgementFaultInjection(_ hook: (@Sendable () throws -> Void)?) { + savePendingAcknowledgementFaultInjection = hook + } + #endif } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift index 8529d737d4..dd6a6cb5e2 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift @@ -126,6 +126,7 @@ public actor PersistenceStore: ModelActor, PersistenceStoreProtocol { var fetchContactIDsFaultInjection: (@Sendable () throws -> Void)? var updateContactLastMessageFaultInjection: (@Sendable () throws -> Void)? + var savePendingAcknowledgementFaultInjection: (@Sendable () throws -> Void)? func setDeleteContactsFaultInjection(_ hook: (@Sendable () throws -> Void)?) { deleteContactsFaultInjection = hook diff --git a/MC1Services/Tests/MC1ServicesTests/PendingAcknowledgementPersistenceTests.swift b/MC1Services/Tests/MC1ServicesTests/PendingAcknowledgementPersistenceTests.swift index 9440f7e13c..e2069793cd 100644 --- a/MC1Services/Tests/MC1ServicesTests/PendingAcknowledgementPersistenceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/PendingAcknowledgementPersistenceTests.swift @@ -156,14 +156,13 @@ struct PendingAcknowledgementPersistenceTests { 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) - await live.service.setPendingAckForTest(PendingAck( + try await live.service.setPendingAckForTest(PendingAck( messageID: live.message.id, contactID: live.contact.id, ackCodes: Set(saved.ackCodes ?? []), sentAt: saved.ackSentAt ?? Date(), timeout: 1, - pendingSendID: saved.id, - deadline: saved.ackDeadline + 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) diff --git a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKRecoveryTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKRecoveryTests.swift index 6e5f22cea9..8aae69fb11 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKRecoveryTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKRecoveryTests.swift @@ -174,7 +174,7 @@ struct MessageServiceACKRecoveryTests { #expect(row.ackDeadline != nil) #expect(row.ackSentAt != nil) #expect(row.attemptCount == 1) - #expect(await successor.services.messageService.pendingAckForTest(message.id)?.pendingSendID == row.id) + #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() diff --git a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKTests.swift index 65ebe31d0c..ed3803b742 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKTests.swift @@ -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,18 @@ 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). + // Seed a non-delivered pendingAcks entry so finalizeSend's acknowledged-code + // branch is taken. 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 ) @@ -828,7 +818,7 @@ struct MessageServiceACKTests { contactID: contactID, radioID: radioID, publicKey: Data((0.. deadline - } - try await harness.service.checkExpiredAcks() - - #expect(try await harness.store.fetchMessage(id: messageID)?.status == .sent) - #expect(await harness.service.pendingAckForTest(messageID)?.isDelivered == false) - #expect(await harness.service.pendingAckForTest(messageID)?.matchedAckCode == code.ackCodeUInt32) - #expect(await harness.service.pendingAckForTest(messageID)?.pendingSendID == nil) - #expect(try await harness.store.fetchPendingSends(radioID: harness.contact.radioID).count == 1) - #expect(await harness.store.updatedMessageAcks.map(\.status) == [.delivered, .delivered]) - #expect(await harness.store.updatedMessageStatuses.isEmpty) + #expect(try await harness.store.fetchMessage(id: messageID)?.status == .pending) - await harness.store.setStubbedUpdateMessageStatusError(nil) gate.release() let accepted = try await send.value - #expect(accepted.status == .delivered) - #expect(accepted.roundTripTime == 77) + #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) } @@ -154,7 +142,7 @@ struct MessageServiceSendDMBookkeepingTests { 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)?.pendingSendID != nil) + #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) @@ -172,11 +160,11 @@ struct MessageServiceSendDMBookkeepingTests { 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)?.pendingSendID != 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.deadline ?? tracking.sentAt + let deadline = tracking.owner?.deadline ?? tracking.sentAt return Date() > deadline } try await harness.service.checkExpiredAcks() @@ -194,18 +182,18 @@ struct MessageServiceSendDMBookkeepingTests { 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)?.pendingSendID != nil) + #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)?.isDelivered == false) #expect(await harness.service.pendingAckForTest(accepted.id)?.matchedAckCode == code.ackCodeUInt32) - #expect(await harness.service.pendingAckForTest(accepted.id)?.pendingSendID != nil) + #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.deadline ?? tracking.sentAt + let deadline = tracking.owner?.deadline ?? tracking.sentAt return Date() > deadline } try await harness.service.checkExpiredAcks() diff --git a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendTests.swift index 4e34448d06..c90ad535b5 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") } @@ -742,7 +729,7 @@ struct MessageServiceSendTests { contactID: contactID, radioID: radioID, publicKey: publicKey, - sentInfo: nil, + acknowledgedCode: nil, initialPathLength: 0 ) 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 index a96044c9d4..e9fb0c286f 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+Queue.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+Queue.swift @@ -48,7 +48,7 @@ extension PlainTextSendGateTests { } 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.deadline ?? tracking.sentAt + let deadline = tracking.owner?.deadline ?? tracking.sentAt return Date() > deadline } try await harness.service.checkExpiredAcks() diff --git a/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+RadioHarness.swift b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+RadioHarness.swift index b471abb3d4..74409196b4 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+RadioHarness.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+RadioHarness.swift @@ -19,9 +19,17 @@ extension PlainTextSendGateTests { let script: RadioScript private let responder: Task - init(budget: DMSendBudget, senderKey: Data, ackGiveUpWindow: TimeInterval = 30) async throws { + 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: 10)) + 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)) @@ -35,7 +43,7 @@ extension PlainTextSendGateTests { session: session, dataStore: store, contactService: nil, - config: MessageServiceConfig(minTimeout: 0, ackGiveUpWindow: ackGiveUpWindow), + config: MessageServiceConfig(minTimeout: 0, ackGiveUpWindow: ackGiveUpWindow, poolBackoff: poolBackoff), dmSendBudget: { budget }, plainTextSendGate: gate ) @@ -46,6 +54,7 @@ extension PlainTextSendGateTests { messageService: service, channelService: channelService, reactionService: ReactionService(), + config: ChatSendQueueConfig(transportWaitTimeout: transportWaitTimeout), plainTextSendGate: gate ) let remote = RemoteNodeService( @@ -60,7 +69,7 @@ extension PlainTextSendGateTests { radioID: radioID, plainTextSendGate: gate ) - let script = RadioScript() + let script = script ?? RadioScript() self.transport = transport self.session = session self.store = store @@ -77,7 +86,11 @@ extension PlainTextSendGateTests { func stop() { responder.cancel() - Task { await session.stop() } + Task { + await session.stop() + await queue.shutdown() + await service.stopEventMonitoring() + } } func contact(byte: UInt8) async throws -> ContactDTO { diff --git a/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+RadioScript.swift b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+RadioScript.swift index bbbcfc5303..1674e5a551 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+RadioScript.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/PlainTextSendGateTests+RadioScript.swift @@ -1,12 +1,32 @@ 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 } @@ -18,6 +38,7 @@ extension PlainTextSendGateTests { 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 { @@ -34,17 +55,28 @@ extension PlainTextSendGateTests { switch packet.first { case CommandCode.sendMessage.rawValue: let attempt = packet.count > 2 ? packet[2] : 0 - let code = table.withLock { slots -> Data in - let sequence = UInt8(truncatingIfNeeded: slots.count) - let ack = Data([attempt, sequence, 0x22, 0x33]) - if slots.count == 8 { slots.removeFirst() } - slots.append(ack) - return ack + 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) } - var frame = Data([ResponseCode.messageSent.rawValue, 0]) - frame.append(code) - frame.append(contentsOf: withUnsafeBytes(of: UInt32(10).littleEndian) { Array($0) }) - await transport.simulateReceive(frame) case CommandCode.getContactByKey.rawValue: await transport.simulateReceive(Data([ResponseCode.error.rawValue])) default: @@ -56,5 +88,16 @@ extension PlainTextSendGateTests { 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/docs/guides/Messaging.md b/docs/guides/Messaging.md index 837a3547a2..e568463128 100644 --- a/docs/guides/Messaging.md +++ b/docs/guides/Messaging.md @@ -34,8 +34,8 @@ This guide covers the message lifecycle, delivery states, retry logic, and ACK h ┌─────────────┴─────────────┐ ▼ ▼ ┌─────────────────────────┐ ┌────────────────────────┐ -│ ACK RECEIVED │ │ ALL ATTEMPTS │ -│ │ │ EXHAUSTED │ +│ ACK RECEIVED │ │ SEND PASS ENDED │ +│ │ │ WITHOUT AN ACK │ │ • Status: .delivered │ │ │ │ • RTT recorded │ │ • .sent, then .failed │ │ • UI updated │ │ • User can retry │ @@ -51,7 +51,7 @@ This guide covers the message lifecycle, delivery states, retry logic, and ACK h | `.sent` (DM) | Radio queued the packet, awaiting end-to-end ACK | "Sending..." text (rendered as in-progress so the user never sees a settled "Sent" that later becomes "Failed") | | `.sent` (channel) | Radio queued the broadcast; no ACK, terminal success | "Sent" text | | `.delivered` | ACK received from recipient | "Delivered" text | -| `.failed` | All attempts exhausted | "Failed" text + red exclamation icon + red bubble background | +| `.failed` | No end-to-end ACK by the give-up deadline, or a terminal send failure | "Failed" text + red exclamation icon + red bubble background | | `.retrying` | Retry in progress | "Retrying %d/%d" text (current attempt / max attempts when `maxRetryAttempts > 0`, falling back to "Retrying..." when `maxRetryAttempts == 0`) + spinner | **Note:** The retry button only appears for messages with `.failed` status. During `.retrying`, the button is replaced with a spinner to indicate the retry is in progress. @@ -60,7 +60,7 @@ This guide covers the message lifecycle, delivery states, retry logic, and ACK h ### Automatic Retry (sendMessageWithRetry) -**File:** `MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift` (attempt counts in `DMSendBudget.swift`, timing in `MessageServiceConfig.swift`) +**Files:** `MC1Services/Sources/MC1Services/Services/MessageService+DMRetry.swift` owns the retry loop; `MessageService+SendDM.swift` owns send entry and finalization. Attempt counts live in `DMSendBudget.swift`, timing in `MessageServiceConfig.swift`. A DM loop reads `DMSendBudget` once. The default is 4 attempts on the contact's current out path, then one `resetPath` and 4 fallback attempts. The bubble counter runs `1/7` through `7/7`. Setting Flood Fallback Attempts to zero leaves only the initial attempts and skips `resetPath`. The radio chooses Direct or Flood on every send. Initial attempts can use Flood when the contact has no out path, and later attempts can use Direct if the radio learns an out path after `resetPath`. @@ -85,6 +85,34 @@ resetPath, then attempts 5-8 Stays .sent until the ACK window ends ``` +### Command Failure After Acceptance + +`RESP_CODE_SENT` means the radio accepted a DM command for transmission. It does not mean the recipient received the packet. After at least one command in a pass is accepted, exhausted local `TABLE_FULL` backoff or a missing host command response ends command issuance for that pass. The original message retains its ACK obligation and reaches `.delivered` on an eligible ACK or `.failed` at its give-up deadline. The queue does not restart that accepted prefix at attempt zero on the same link. + +An explicit `TABLE_FULL` rejection retains earlier accepted ACK codes and their deadline. Waiting through local backoff does not extend that deadline. A command-response timeout has an uncertain send outcome, so tracking also retains that command's predicted ACK and a window that covers the preceding accepted deadline. Firmware ACK codes repeat every four attempts: rejecting attempt 5 must preserve the code already accepted for attempt 1. + +An ACK during local pool backoff stops further command submissions. The current command, if one is in flight, still owns its completion before the next sender can be admitted. A recipient ACK timeout alone continues through the configured attempt budget. + +Failures before any command is accepted retain the existing queue recovery policy. Genuine cancellation, session retirement, and transport loss retain reconnect replay with the original wire timestamp. Those recovery paths are separate from ending a partially accepted pass on the same link. + +```mermaid +flowchart TD + Send[Submit DM command] --> Response{Host response} + Response -->|RESP_CODE_SENT| Wait[Wait for recipient ACK] + Wait -->|ACK timeout and attempts remain| Send + Wait -->|budget spent| Handoff[End commands and retain ACK obligation] + Response -->|TABLE_FULL| Backoff[Bounded local pool backoff] + Backoff -->|no matched ACK and retries remain| Send + Backoff -->|retries exhausted| Accepted{Earlier command accepted?} + Response -->|command-response timeout| Accepted + Accepted -->|yes| Handoff + Accepted -->|no| Recover[Existing queue recovery] + Wait -->|ACK| Delivered[Persist Delivered] + Backoff -->|ACK| Delivered + Handoff -->|late ACK| Delivered + Handoff -->|give-up deadline| Failed[Persist Failed] +``` + ### Direct vs Flood Routing **Direct Routing:** @@ -115,7 +143,7 @@ This clears the contact's cached out path. The radio chooses the route for every - The retry loop runs at the app layer in `sendDirectMessageWithRetryLoop`, not inside `MeshCoreSession`, so each attempt can emit UI feedback - After the first attempt fails, status moves to `.retrying` and a `.retrying` event is broadcast per subsequent attempt - No user interaction required -- If the budget is spent with no ACK, the message stays `.sent` until the ACK window ends, then becomes `.failed` +- If the budget is spent with no ACK, or a later command fails after prior acceptance, command issuance ends and ACK tracking owns the remaining delivery outcome **Manual Retry:** - Triggered when user taps "Retry" button on a failed message @@ -149,34 +177,22 @@ The UI shows: ### PendingAck Structure -```swift -struct PendingAck: Sendable { - let messageID: UUID - let contactID: UUID - var ackCodes: Set // One per retry attempt - var sentAt: Date - var timeout: TimeInterval - var isDelivered: Bool = false -} -``` - -Keyed on `messageID`, not `ackCode`, so a late ACK from any retry attempt can still resolve the message. The `MessageService` persistent listener (`startEventMonitoring`) subscribes via `session.events(filter: .anyAcknowledgement)` so the dispatcher's ring buffer only holds matching events. +`MessageService` keeps one `PendingAck` per message ID. Each entry holds the eligible ACK codes, send time, timeout, and optional `PendingSend` owner. The persistent listener (`startEventMonitoring`) subscribes via `session.events(filter: .anyAcknowledgement)`. A late ACK from an earlier accepted attempt can still resolve the message. On reconnect, unexpired ACK owners recovered from `PendingSend` hold admission before the queue hydrates. Each reservation ends when its ACK is resolved or its deadline expires. +At the end of an accepted send pass, the owner on `PendingAck` records the row ID, radio ID, deadline, and whether persistence needs to insert a row or convert the original queued `PendingSend`. If the write fails, the ACK checker uses the same owner and tracked ACK codes and send time for the next save. A successful write advances the owner to its saved phase. A recorded ACK or elapsed deadline then resolves the message and consumes that row. Row identity and terminal-state guards protect a later user retry from stale completion. The ACK checker also retries terminal writes for saved owners. + Quick replies and DM reactions persist their single-attempt policy before waiting for admission. Recovery sends them once even when the configured DM budget allows more attempts. The attempt count is saved before the command, so recovery preserves the wire timestamp if transmission may have started. Delivered or failed inline sends are removed from the queue without another send. ### ACK Flow ``` -Message sent - │ - ▼ ACK code predicted + PendingAck tracked - │ - ├───── ACK received ─────────► handleAcknowledgement: mark .delivered - │ - └───── Timeout (5s check) ───► checkExpiredAcks: mark .failed - (give-up deadline = max(ackGiveUpWindow, PendingAck.timeout)) +Predict the ACK code and start tracking before command submission + ├─ ACK matched during issuance → resolve delivery + └─ Accepted pass ends with ACK tracking active → save PendingAck owner + ├─ Save fails → ACK checker retries the owner write + └─ Save succeeds → resolve delivery on a matching ACK, or fail at the deadline ``` An end-to-end ACK that arrives after its `PendingAck` entry is gone (failed and removed, or duplicate) has no live entry to match; `handleAcknowledgement` logs it as an unmatched ACK and returns without changing status. From f92bdad899efb3082682a10c804434f8978fdc43 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Fri, 6 Nov 2026 08:09:40 -0800 Subject: [PATCH 14/66] fix: count initial send in dm retry progress - Show 2/8 on the first retry and 8/8 on the last with the default limit. Use the same counts for VoiceOver. --- .../Chats/Components/BubbleFooterRow.swift | 18 ++-- .../Components/MessageStatusTextTests.swift | 88 +++++++++---------- docs/Architecture.md | 2 +- docs/User_Guide.md | 2 +- docs/api/MC1Services.md | 2 +- docs/guides/Messaging.md | 8 +- 6 files changed, 61 insertions(+), 59 deletions(-) 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/MC1Tests/Views/Chats/Components/MessageStatusTextTests.swift b/MC1Tests/Views/Chats/Components/MessageStatusTextTests.swift index df146ebbc5..22ab8371fd 100644 --- a/MC1Tests/Views/Chats/Components/MessageStatusTextTests.swift +++ b/MC1Tests/Views/Chats/Components/MessageStatusTextTests.swift @@ -1,53 +1,29 @@ -import Foundation @testable import MC1 @testable import MC1Services import Testing @Suite("Message status text") struct MessageStatusTextTests { - private func makeItem( + private func makeFooter( status: MessageStatus, isChannelMessage: Bool, - heardRepeats: Int = 0, - sendCount: Int = 1 - ) -> MessageItem { - MessageItem( - id: UUID(), - envelope: MessageEnvelope( - messageID: UUID(), - isOutgoing: true, - senderName: "me", - senderResolution: NodeNameResolution(displayName: "me", matchKind: .exact), - status: status, - date: Date(timeIntervalSince1970: 1_700_000_000), - hasFailed: status == .failed, - containsSelfMention: false, - mentionSeen: false, - incomingAvatar: nil - ), - content: [], - footer: MessageFooter( - showHop: false, - hopCount: 0, - formattedPath: nil, - regionToShow: nil, - sendTimeToShow: nil, - sendTimeWasCorrected: false, - showStatusRow: true, - status: status, - isChannelMessage: isChannelMessage, - heardRepeats: heardRepeats, - retryAttempt: 0, - maxRetryAttempts: 0, - sendCount: sendCount - ), - grouping: GroupingFlags( - showTimestamp: false, - showDirectionGap: false, - showSenderName: false, - showNewMessagesDivider: false - ), - shouldRequestPreviewFetch: false + retryAttempt: Int = 0, + maxRetryAttempts: Int = 0 + ) -> MessageFooter { + MessageFooter( + showHop: false, + hopCount: 0, + formattedPath: nil, + regionToShow: nil, + sendTimeToShow: nil, + sendTimeWasCorrected: false, + showStatusRow: true, + status: status, + isChannelMessage: isChannelMessage, + heardRepeats: 0, + retryAttempt: retryAttempt, + maxRetryAttempts: maxRetryAttempts, + sendCount: 1 ) } @@ -55,26 +31,46 @@ struct MessageStatusTextTests { /// in-progress so the user never sees a settled "Sent" that later fails. @Test func `DM .sent renders as Sending`() { - let text = MessageStatusText.text(for: makeItem(status: .sent, isChannelMessage: false).footer) + let text = MessageStatusText.text(for: makeFooter(status: .sent, isChannelMessage: false)) #expect(text == L10n.Chats.Chats.Message.Status.sending) } /// A channel broadcast has no ACK, so `.sent` is its terminal success state. @Test func `Channel .sent renders as Sent`() { - let text = MessageStatusText.text(for: makeItem(status: .sent, isChannelMessage: true).footer) + let text = MessageStatusText.text(for: makeFooter(status: .sent, isChannelMessage: true)) #expect(text == L10n.Chats.Chats.Message.Status.sent) } @Test func `DM .delivered still renders as Delivered`() { - let text = MessageStatusText.text(for: makeItem(status: .delivered, isChannelMessage: false).footer) + let text = MessageStatusText.text(for: makeFooter(status: .delivered, isChannelMessage: false)) #expect(text == L10n.Chats.Chats.Message.Status.delivered) } @Test func `DM .failed still renders as Failed`() { - let text = MessageStatusText.text(for: makeItem(status: .failed, isChannelMessage: false).footer) + let text = MessageStatusText.text(for: makeFooter(status: .failed, isChannelMessage: false)) #expect(text == L10n.Chats.Chats.Message.Status.failed) } + + @Test(arguments: [ + (0, 7, 2, 8), + (6, 7, 8, 8), + (1, 2, 3, 3), + ]) + func `DM retry progress includes the initial send in both counts`( + retryAttempt: Int, + maxRetryAttempts: Int, + attempt: Int, + total: Int + ) { + let footer = makeFooter( + status: .retrying, + isChannelMessage: false, + retryAttempt: retryAttempt, + maxRetryAttempts: maxRetryAttempts + ) + #expect(MessageStatusText.text(for: footer) == L10n.Chats.Chats.Message.Status.retryingAttempt(attempt, total)) + } } diff --git a/docs/Architecture.md b/docs/Architecture.md index 1449a723d9..3fb5a9fc5e 100644 --- a/docs/Architecture.md +++ b/docs/Architecture.md @@ -336,7 +336,7 @@ The service-layer packages use `nonisolated(unsafe)` only where Swift's isolatio 1. **User Action**: User types message in `ChatConversationView` and taps send. 2. **Service Call**: `MessageService.sendMessageWithRetry()` is called. 3. **Queue**: Message is saved to `PersistenceStore` with status `.pending`. -4. **Retry Loop**: `MessageService.sendMessageWithRetry()` reads `DMSendBudget` once (default 4 attempts on the current out path, then one `resetPath` and 4 fallback attempts; the counter runs `1/7` through `7/7`). The radio chooses the route on every send. A queued send waits while the previous DM can still receive a late ACK. `RoomServerService` owns fixed room-post limits of 4 initial attempts and 1 fallback. +4. **Retry Loop**: `MessageService.sendMessageWithRetry()` reads `DMSendBudget` once (default 4 attempts on the current out path, then one `resetPath` and 4 fallback attempts). The first attempt shows a spinner. The counter starts at `2/8` on the first retry and can reach `8/8` by default. The radio chooses the route on every send. A queued send waits while the previous DM can still receive a late ACK. `RoomServerService` owns fixed room-post limits of 4 initial attempts and 1 fallback. 5. **ACK Tracking**: Each send attempt waits inline for ACK using `waitForEvent()` with configurable timeout. 6. **Completion**: ACK received -> `.delivered`; exhausted attempts leave the DM `.sent` until an ACK arrives or the give-up deadline marks it `.failed`. diff --git a/docs/User_Guide.md b/docs/User_Guide.md index 5a074cd63f..bcc75f398a 100644 --- a/docs/User_Guide.md +++ b/docs/User_Guide.md @@ -112,7 +112,7 @@ If a message fails to deliver: 1. Tap the **Retry** button that appears below the failed message. 2. By default the app tries four times on the contact's current out path, then resets the out path and tries four more. The radio uses Flood when the contact has no out path. Set Flood Fallback Attempts to zero in Settings to skip the reset and extra attempts. A retry waits if another DM can still receive an ACK. -3. You'll see retry progress from "Retrying 1/7..." through "Retrying 7/7...". +3. The first attempt shows a spinner. If the app retries, the counter starts at `2/8` and can reach `8/8` with the default settings. The total follows your configured attempt counts. ### Group Channels diff --git a/docs/api/MC1Services.md b/docs/api/MC1Services.md index 858df2a6fd..6f35ddf64d 100644 --- a/docs/api/MC1Services.md +++ b/docs/api/MC1Services.md @@ -155,7 +155,7 @@ The `ContactService` used for path management during retry is injected via `Mess ### Retry Flow -1. DM loops read `DMSendBudget` once. The default is 4 attempts on the contact's current out path, then one `resetPath` and 4 fallback attempts. The counter runs `1/7` through `7/7`. Setting Flood Fallback Attempts to zero skips `resetPath`. +1. DM loops read `DMSendBudget` once. The default is 4 attempts on the contact's current out path, then one `resetPath` and 4 fallback attempts. The first attempt shows a spinner. The counter starts at `2/8` on the first retry and can reach `8/8` by default. Setting Flood Fallback Attempts to zero skips `resetPath`. 2. The fallback count is not the radio's routing mode. The radio chooses Direct or Flood on every send. `DMSendBudget.totalAttempts` is the sum of its bounded initial and fallback counts. Room posts use fixed limits owned by `RoomServerService` (4 initial attempts and 1 fallback). 3. Returns immediately when an ACK is received. A queued plain-text send waits while the previous one can still receive a late ACK. 4. On exhaustion a DM stays `.sent` until that ACK arrives or the give-up window ends. diff --git a/docs/guides/Messaging.md b/docs/guides/Messaging.md index e568463128..a8911c6259 100644 --- a/docs/guides/Messaging.md +++ b/docs/guides/Messaging.md @@ -24,7 +24,7 @@ This guide covers the message lifecycle, delivery states, retry logic, and ACK h │ MessageService.sendMessageWithRetry() runs the │ │ app-layer retry loop (sendDirectMessageWithRetryLoop)│ │ • Default: 4 on the current out path, then 4 │ -│ after one resetPath (counter 1/7 through 7/7) │ +│ after one resetPath (counter 2/8 through 8/8) │ │ • The radio chooses the route on every send │ │ • A queued send waits while the previous DM can │ │ still receive a late ACK │ @@ -52,7 +52,7 @@ This guide covers the message lifecycle, delivery states, retry logic, and ACK h | `.sent` (channel) | Radio queued the broadcast; no ACK, terminal success | "Sent" text | | `.delivered` | ACK received from recipient | "Delivered" text | | `.failed` | No end-to-end ACK by the give-up deadline, or a terminal send failure | "Failed" text + red exclamation icon + red bubble background | -| `.retrying` | Retry in progress | "Retrying %d/%d" text (current attempt / max attempts when `maxRetryAttempts > 0`, falling back to "Retrying..." when `maxRetryAttempts == 0`) + spinner | +| `.retrying` | Retry in progress | Spinner plus the current send attempt / total allowed attempts when `maxRetryAttempts > 0`. VoiceOver announces the same attempt counts. | **Note:** The retry button only appears for messages with `.failed` status. During `.retrying`, the button is replaced with a spinner to indicate the retry is in progress. @@ -62,7 +62,7 @@ This guide covers the message lifecycle, delivery states, retry logic, and ACK h **Files:** `MC1Services/Sources/MC1Services/Services/MessageService+DMRetry.swift` owns the retry loop; `MessageService+SendDM.swift` owns send entry and finalization. Attempt counts live in `DMSendBudget.swift`, timing in `MessageServiceConfig.swift`. -A DM loop reads `DMSendBudget` once. The default is 4 attempts on the contact's current out path, then one `resetPath` and 4 fallback attempts. The bubble counter runs `1/7` through `7/7`. Setting Flood Fallback Attempts to zero leaves only the initial attempts and skips `resetPath`. The radio chooses Direct or Flood on every send. Initial attempts can use Flood when the contact has no out path, and later attempts can use Direct if the radio learns an out path after `resetPath`. +A DM loop reads `DMSendBudget` once. The default is 4 attempts on the contact's current out path, then one `resetPath` and 4 fallback attempts. The first attempt shows a spinner. The counter includes the initial send and uses the configured total, so by default it starts at `2/8` and can reach `8/8`. Setting Flood Fallback Attempts to zero leaves only the initial attempts and skips `resetPath`. The radio chooses Direct or Flood on every send. Initial attempts can use Flood when the contact has no out path, and later attempts can use Direct if the radio learns an out path after `resetPath`. `DMSendBudget` bounds initial attempts to 1...4 and fallback attempts to 0...4. Its total is the sum of those counts. Room posts use fixed limits owned by `RoomServerService`: 4 initial attempts and 1 fallback attempt, independent of the DM preference. @@ -170,7 +170,7 @@ try await signalDMEnqueued(envelope) The queue drain calls `performQueuedDirectMessageSend`, which runs `sendDirectMessageWithRetryLoop`. That loop marks `.retrying` via `updateMessageRetryStatus` only after the first attempt fails. With the default budget it sends 4 attempts on the current out path, calls `resetPath` once, then sends 4 fallback attempts. The radio chooses the route on every send. The same code path serves automatic and manual retries. A queued send waits while the previous plain-text send can still receive a late ACK. The UI shows: -- "Retrying %d/%d" text (current attempt / max attempts) with a spinner icon when `maxRetryAttempts > 0`, falling back to plain "Retrying..." only when `maxRetryAttempts == 0` +- A spinner without a counter on the first attempt, then the current send attempt / total allowed attempts when `maxRetryAttempts > 0` (`2/8` through `8/8` by default). VoiceOver announces the same attempt counts. - The retry button is hidden while in `.retrying` status ## ACK Tracking From 2b66930a0464356e9893fae8f35c0667748e9c24 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Fri, 6 Nov 2026 09:52:50 -0800 Subject: [PATCH 15/66] Add Text Rules for incoming messages (#485) * feat: add block/filter text rules for incoming messages - Filter channel, DM, and room messages using local rules. - Keep matches in Recently Blocked for review. - Handle missed room posts and interrupted radio cleanup. --- MC1/Resources/Generated/L10n.swift | 138 ++++++ .../Localization/de.lproj/Settings.strings | 61 +++ .../Localization/en.lproj/Settings.strings | 59 +++ .../Localization/es.lproj/Settings.strings | 61 +++ .../Localization/fr.lproj/Settings.strings | 61 +++ .../Localization/it.lproj/Settings.strings | 61 +++ .../Localization/ko.lproj/Settings.strings | 61 +++ .../Localization/nl.lproj/Settings.strings | 61 +++ .../Localization/pl.lproj/Settings.strings | 61 +++ .../Localization/pt.lproj/Settings.strings | 61 +++ .../Localization/ru.lproj/Settings.strings | 61 +++ .../Localization/uk.lproj/Settings.strings | 61 +++ .../zh-Hans.lproj/Settings.strings | 61 +++ MC1/State/AppState+Wiring.swift | 8 +- MC1/State/AppState.swift | 8 + MC1/State/MessageEvent.swift | 8 +- MC1/State/MessageEventDispatcher.swift | 28 +- MC1/Views/Chats/ChatConversationView.swift | 2 +- .../ViewModel/ChatTimelinePopulator.swift | 11 +- .../ViewModel/ChatViewModel+EventStream.swift | 10 +- MC1/Views/Contacts/ContactDetailContent.swift | 3 +- .../Rooms/RoomConversationView.swift | 13 + .../Rooms/RoomConversationViewModel.swift | 22 +- .../BlocksAndFiltersSettingsView.swift | 136 ++++++ MC1/Views/Settings/ChatSettingsView.swift | 3 +- .../Settings/Sections/BlockingSection.swift | 28 +- .../Sections/DangerZoneViewModel.swift | 25 +- .../Settings/Sections/NewTextRuleSheet.swift | 109 +++++ .../Sections/RadioCleanupSection.swift | 43 ++ .../Sections/RecentlyBlockedRow.swift | 85 ++++ .../Sections/RecentlyBlockedView.swift | 121 ++++++ .../Settings/Sections/TextRuleChatsView.swift | 107 +++++ .../Sections/TextRulesLoadNotice.swift | 20 + MC1/Views/Settings/SettingsDetail.swift | 3 +- MC1/Views/Settings/SettingsDetailView.swift | 2 + MC1/Views/Settings/SettingsListContent.swift | 4 + MC1/Views/Settings/SettingsSubpage.swift | 10 +- .../ConnectionManager+Connect.swift | 3 +- .../ConnectionManager+Lifecycle.swift | 8 +- .../ConnectionManager+Pairing.swift | 36 +- .../ConnectionManager+Preparation.swift | 7 +- .../ConnectionManager+RadioErase.swift | 221 ++++++++++ .../ConnectionManager+Removal.swift | 6 +- .../ConnectionManager+TextRules.swift | 46 ++ .../Connection/ConnectionManager.swift | 11 +- .../Sources/MC1Services/Models/Channel.swift | 108 ++--- .../Sources/MC1Services/Models/Contact.swift | 80 ++-- .../Sources/MC1Services/Models/Message.swift | 6 +- .../Models/PendingRadioErase.swift | 50 +++ .../MC1Services/Models/ReceiveScope.swift | 38 ++ .../Models/RecentlyBlockedMessage.swift | 52 +++ .../Models/RecentlyBlockedMessageDTO.swift | 72 ++++ .../Models/RemoteNodeSession.swift | 46 +- .../Models/TextRulesPreference.swift | 238 +++++++++++ .../MessagePollingServiceProtocol.swift | 6 +- .../Persistence/ContactPersisting.swift | 52 ++- .../Persistence/MessagePersisting.swift | 56 +++ .../Persistence/ReactionPersisting.swift | 15 + .../Persistence/RoomPersisting.swift | 8 + .../MC1Services/ServiceContainer.swift | 22 +- .../Services/AdvertisementEvent.swift | 2 +- .../AdvertisementService+DeltaSync.swift | 23 +- .../Services/AdvertisementService.swift | 38 +- .../Services/DirectMessageAdmission.swift | 8 + .../Services/MessagePollingService.swift | 120 ++++-- .../Services/NotificationService.swift | 24 +- .../PersistenceStore+BackupBatchInsert.swift | 3 + .../PersistenceStore+BackupImport.swift | 5 +- .../PersistenceStore+ChannelReceive.swift | 50 +++ .../Services/PersistenceStore+Channels.swift | 2 + .../PersistenceStore+Connection.swift | 4 + .../Services/PersistenceStore+Contacts.swift | 22 +- .../Services/PersistenceStore+Devices.swift | 104 +++-- ...ersistenceStore+DirectMessageReceive.swift | 179 ++++++++ .../Services/PersistenceStore+Messages.swift | 10 + .../PersistenceStore+RadioErase.swift | 115 +++++ .../PersistenceStore+RecentlyBlocked.swift | 75 ++++ ...stenceStore+RecentlyBlockedOwnership.swift | 69 +++ .../PersistenceStore+RoomReceive.swift | 105 +++++ .../Services/PersistenceStore+Rooms.swift | 42 +- ...sistenceStore+TextRulesConversations.swift | 172 ++++++++ .../Services/PersistenceStore.swift | 22 +- .../Services/ReactionService.swift | 18 +- .../Services/RemoteNodeService+Login.swift | 31 +- .../RemoteNodeService+RoomKeepAlive.swift | 121 ++++++ .../Services/RemoteNodeService.swift | 28 +- .../Services/RoomServerService.swift | 108 +++-- .../MC1Services/Services/RxLogService.swift | 5 +- .../Sync/SyncCoordinator+HandlerHelpers.swift | 99 +++-- .../SyncCoordinator+MessageHandlers.swift | 400 +++++++++--------- .../SyncCoordinator+ReactionHandlers.swift | 44 +- .../MC1Services/Sync/SyncCoordinator.swift | 5 +- .../MC1Services/Sync/SyncDataEvent.swift | 12 +- .../Utilities/ChannelMessageFormat.swift | 9 + .../AdvertisementServiceTests.swift | 43 +- .../BackupIntegrationTests.swift | 43 ++ .../ConnectionManagerMembershipTests.swift | 9 +- .../ConnectionManagerPairingTests.swift | 213 +++++++++- .../ConnectionRemovalConfirmationTests.swift | 16 +- .../ConnectionRemovalDrainTests.swift | 52 ++- .../Mocks/MockAccessorySetupKitService.swift | 6 + .../Mocks/MockMeshCoreSession.swift | 24 +- .../Mocks/MockMessagePollingService.swift | 12 +- .../Services/ChannelServiceTests.swift | 24 +- .../MessagePollingServiceTextTypeTests.swift | 2 +- .../Services/RoomKeepAliveRecoveryTests.swift | 398 +++++++++++++++++ .../Services/RoomPostTextRulesTests.swift | 140 ++++++ .../Services/StockChannelTextRulesTests.swift | 135 ++++++ ...SyncCoordinatorBackgroundUnreadTests.swift | 22 +- .../SyncCoordinatorMessageHandlerTests.swift | 248 ++++++++++- .../SyncCoordinatorTests.swift | 6 +- .../TextRulesOwnershipTests.swift | 160 +++++++ .../TextRulesPreferenceTests.swift | 142 +++++++ .../ConnectionStatusLifecycleTests.swift | 6 +- MC1Tests/AppState/RadioEraseDiskTests.swift | 82 ++++ .../RecentlyBlockedPersistenceTests.swift | 156 +++++++ .../ChatViewModelPaginationTests.swift | 3 +- .../ChatChannelInfoPresentationTests.swift | 45 +- .../Chats/ChatReconnectPopulateTests.swift | 11 +- .../Chats/ChatViewModelFailedSendTests.swift | 10 +- .../Views/OfflineMapSettingsErrorTests.swift | 2 +- .../Settings/RecentlyBlockedRowTests.swift | 94 ++++ MC1Tests/Views/SettingsDestination.swift | 16 + MC1Tests/Views/SettingsRoot.swift | 6 + .../Views/SettingsRouteAdmissionTests.swift | 10 +- .../Views/SettingsTabHarness+Actions.swift | 4 +- .../SettingsTabNavigationTests+Helpers.swift | 2 +- .../Views/SettingsTabNavigationTests.swift | 25 +- .../Protocols/MessageFetchSessionOps.swift | 6 + .../Protocols/RemoteAccessSessionOps.swift | 18 +- .../Protocols/SessionEventStreaming.swift | 6 + .../Session/MeshCoreSession+Messaging.swift | 53 +-- .../MeshCore/Session/MeshCoreSession.swift | 33 +- 133 files changed, 6329 insertions(+), 892 deletions(-) create mode 100644 MC1/Views/Settings/BlocksAndFiltersSettingsView.swift create mode 100644 MC1/Views/Settings/Sections/NewTextRuleSheet.swift create mode 100644 MC1/Views/Settings/Sections/RadioCleanupSection.swift create mode 100644 MC1/Views/Settings/Sections/RecentlyBlockedRow.swift create mode 100644 MC1/Views/Settings/Sections/RecentlyBlockedView.swift create mode 100644 MC1/Views/Settings/Sections/TextRuleChatsView.swift create mode 100644 MC1/Views/Settings/Sections/TextRulesLoadNotice.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+RadioErase.swift create mode 100644 MC1Services/Sources/MC1Services/Connection/ConnectionManager+TextRules.swift create mode 100644 MC1Services/Sources/MC1Services/Models/PendingRadioErase.swift create mode 100644 MC1Services/Sources/MC1Services/Models/ReceiveScope.swift create mode 100644 MC1Services/Sources/MC1Services/Models/RecentlyBlockedMessage.swift create mode 100644 MC1Services/Sources/MC1Services/Models/RecentlyBlockedMessageDTO.swift create mode 100644 MC1Services/Sources/MC1Services/Models/TextRulesPreference.swift create mode 100644 MC1Services/Sources/MC1Services/Services/DirectMessageAdmission.swift create mode 100644 MC1Services/Sources/MC1Services/Services/PersistenceStore+ChannelReceive.swift create mode 100644 MC1Services/Sources/MC1Services/Services/PersistenceStore+DirectMessageReceive.swift create mode 100644 MC1Services/Sources/MC1Services/Services/PersistenceStore+RadioErase.swift create mode 100644 MC1Services/Sources/MC1Services/Services/PersistenceStore+RecentlyBlocked.swift create mode 100644 MC1Services/Sources/MC1Services/Services/PersistenceStore+RecentlyBlockedOwnership.swift create mode 100644 MC1Services/Sources/MC1Services/Services/PersistenceStore+RoomReceive.swift create mode 100644 MC1Services/Sources/MC1Services/Services/PersistenceStore+TextRulesConversations.swift create mode 100644 MC1Services/Sources/MC1Services/Services/RemoteNodeService+RoomKeepAlive.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/RoomKeepAliveRecoveryTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/RoomPostTextRulesTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/StockChannelTextRulesTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/TextRulesOwnershipTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/TextRulesPreferenceTests.swift create mode 100644 MC1Tests/AppState/RadioEraseDiskTests.swift create mode 100644 MC1Tests/AppState/RecentlyBlockedPersistenceTests.swift create mode 100644 MC1Tests/Views/Settings/RecentlyBlockedRowTests.swift diff --git a/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index 80f579dc40..fecaae3042 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -4549,6 +4549,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") @@ -5631,6 +5635,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") @@ -6163,6 +6181,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") diff --git a/MC1/Resources/Localization/de.lproj/Settings.strings b/MC1/Resources/Localization/de.lproj/Settings.strings index caefa22a3f..07ebff0f92 100644 --- a/MC1/Resources/Localization/de.lproj/Settings.strings +++ b/MC1/Resources/Localization/de.lproj/Settings.strings @@ -769,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 */ @@ -1497,6 +1499,65 @@ /* 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 + +/* TODO: translate Text Rules strings */ +"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" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"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" = "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" = "Ist er eingeschaltet, gilt er für jeden Chat dieses Typs, auch für Chats, denen du später beitrittst."; +"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“ gilt auch für Chats, denen du später beitrittst."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"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" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate radio Cleanup strings */ +"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 */ diff --git a/MC1/Resources/Localization/en.lproj/Settings.strings b/MC1/Resources/Localization/en.lproj/Settings.strings index 9280dd2ef3..3bfeb10306 100644 --- a/MC1/Resources/Localization/en.lproj/Settings.strings +++ b/MC1/Resources/Localization/en.lproj/Settings.strings @@ -758,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 */ @@ -1484,6 +1486,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 */ diff --git a/MC1/Resources/Localization/es.lproj/Settings.strings b/MC1/Resources/Localization/es.lproj/Settings.strings index 42675c572c..d4595ad3b1 100644 --- a/MC1/Resources/Localization/es.lproj/Settings.strings +++ b/MC1/Resources/Localization/es.lproj/Settings.strings @@ -769,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 */ @@ -1497,6 +1499,65 @@ /* 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 + +/* TODO: translate Text Rules strings */ +"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" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"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" = "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" = "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" = "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 incluye los chats a los que te unas más tarde."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"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" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate radio Cleanup strings */ +"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 */ diff --git a/MC1/Resources/Localization/fr.lproj/Settings.strings b/MC1/Resources/Localization/fr.lproj/Settings.strings index 1a4c6bdfa6..b30d9e7c26 100644 --- a/MC1/Resources/Localization/fr.lproj/Settings.strings +++ b/MC1/Resources/Localization/fr.lproj/Settings.strings @@ -769,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 */ @@ -1497,6 +1499,65 @@ /* 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 + +/* TODO: translate Text Rules strings */ +"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" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"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" = "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" = "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" = "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 inclut les discussions que vous rejoignez plus tard."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"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" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate radio Cleanup strings */ +"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 */ diff --git a/MC1/Resources/Localization/it.lproj/Settings.strings b/MC1/Resources/Localization/it.lproj/Settings.strings index aae42f46b2..30aa4feb8d 100644 --- a/MC1/Resources/Localization/it.lproj/Settings.strings +++ b/MC1/Resources/Localization/it.lproj/Settings.strings @@ -768,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 */ @@ -1495,6 +1497,65 @@ /* Validation error: no empty channel slot left (param: channel name) */ "configImport.error.noAvailableChannelSlot" = "Nessuno slot canale libero disponibile per “%@”"; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"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" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"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" = "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" = "Se attivo, include tutte le chat di quel tipo, anche quelle a cui ti unisci in seguito."; +"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” include le chat a cui ti unisci in seguito."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"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" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate radio Cleanup strings */ +"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 */ diff --git a/MC1/Resources/Localization/ko.lproj/Settings.strings b/MC1/Resources/Localization/ko.lproj/Settings.strings index cae2d8a78f..ca44a91b41 100644 --- a/MC1/Resources/Localization/ko.lproj/Settings.strings +++ b/MC1/Resources/Localization/ko.lproj/Settings.strings @@ -758,6 +758,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "채팅"; +"blocksAndFilters.title" = "차단 및 필터"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -1485,6 +1487,65 @@ /* Validation error: no empty channel slot left (param: channel name) */ "configImport.error.noAvailableChannelSlot" = "\"%@\"에 사용할 빈 채널 슬롯이 없습니다"; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"textRules.rules" = "필터 규칙"; +"textRules.empty" = "필터 규칙 없음"; +"textRules.loading" = "필터 규칙을 불러오는 중…"; +"textRules.loadFailed" = "필터 규칙을 불러올 수 없습니다. 불러올 수 있을 때까지 새 메시지는 필터 규칙을 사용하지 않습니다."; +"textRules.retryAccessibility" = "필터 규칙 다시 불러오기"; +"textRules.saveFailed" = "필터 규칙을 저장할 수 없습니다. 다시 시도하십시오."; +"textRules.new.title" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"textRules.new.containsMessageFooter" = "메시지 어디에서든, 단어 안에서도 일치합니다."; +"textRules.new.wholeMessageFooter" = "메시지 전체가 이 문구일 때만 일치합니다."; +"textRules.new.containsSenderFooter" = "발신자 이름 어디에서든, 단어 안에서도 일치합니다. 그 발신자의 반응도 숨겨집니다."; +"textRules.new.wholeNameFooter" = "발신자 이름이 정확히 이 문구일 때만 일치합니다. 그 발신자의 반응도 숨겨집니다."; +"textRules.new.containsMessageOrSenderFooter" = "메시지 또는 발신자 이름 어디에서든, 단어 안에서도 일치합니다. 일치하는 발신자의 반응도 숨겨집니다."; +"textRules.new.wholeMessageOrSenderFooter" = "메시지 전체 또는 발신자 이름 전체가 이 문구일 때만 일치합니다. 일치하는 발신자의 반응도 숨겨집니다."; +"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" = "켜면 해당 유형의 모든 채팅이 포함됩니다. 나중에 참여하는 채팅도 포함됩니다."; +"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은 나중에 참여하는 채팅도 포함합니다."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"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" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate radio Cleanup strings */ +"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 */ diff --git a/MC1/Resources/Localization/nl.lproj/Settings.strings b/MC1/Resources/Localization/nl.lproj/Settings.strings index 10c56ed886..8eb6ea82f2 100644 --- a/MC1/Resources/Localization/nl.lproj/Settings.strings +++ b/MC1/Resources/Localization/nl.lproj/Settings.strings @@ -769,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 */ @@ -1497,6 +1499,65 @@ /* 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 + +/* TODO: translate Text Rules strings */ +"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" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"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" = "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" = "Staat de schakelaar aan, dan geldt die voor elk gesprek van dat type, ook voor gesprekken waaraan je later deelneemt."; +"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 geldt ook voor gesprekken waaraan je later deelneemt."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"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" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate radio Cleanup strings */ +"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 */ diff --git a/MC1/Resources/Localization/pl.lproj/Settings.strings b/MC1/Resources/Localization/pl.lproj/Settings.strings index 975e1f1173..b76e7265f4 100644 --- a/MC1/Resources/Localization/pl.lproj/Settings.strings +++ b/MC1/Resources/Localization/pl.lproj/Settings.strings @@ -769,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 */ @@ -1497,6 +1499,65 @@ /* 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 + +/* TODO: translate Text Rules strings */ +"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" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"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" = "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" = "Włączenie obejmuje wszystkie czaty tego typu, w tym te, do których dołączysz później."; +"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 obejmuje czaty, do których dołączysz później."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"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" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate radio Cleanup strings */ +"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 */ diff --git a/MC1/Resources/Localization/pt.lproj/Settings.strings b/MC1/Resources/Localization/pt.lproj/Settings.strings index 4fb1171078..828247d7c7 100644 --- a/MC1/Resources/Localization/pt.lproj/Settings.strings +++ b/MC1/Resources/Localization/pt.lproj/Settings.strings @@ -768,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 */ @@ -1495,6 +1497,65 @@ /* Validation error: no empty channel slot left (param: channel name) */ "configImport.error.noAvailableChannelSlot" = "Nenhum slot de canal vazio disponível para \"%@\""; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"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" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"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" = "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" = "Quando ativado, inclui todas as conversas desse tipo, incluindo as conversas a que aderir mais tarde."; +"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 inclui as conversas a que aderir mais tarde."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"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" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate radio Cleanup strings */ +"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 */ diff --git a/MC1/Resources/Localization/ru.lproj/Settings.strings b/MC1/Resources/Localization/ru.lproj/Settings.strings index fe3aa8caac..5d211fda42 100644 --- a/MC1/Resources/Localization/ru.lproj/Settings.strings +++ b/MC1/Resources/Localization/ru.lproj/Settings.strings @@ -769,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Чаты"; +"blocksAndFilters.title" = "Блокировка и фильтры"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -1497,6 +1499,65 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "Отображение миниатюр карты загружает плитки для координаты со стороннего сервера, что может раскрыть ваш IP-адрес."; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"textRules.rules" = "Правила фильтрации"; +"textRules.empty" = "Нет правил фильтрации"; +"textRules.loading" = "Загрузка правил фильтрации…"; +"textRules.loadFailed" = "Не удалось загрузить правила фильтрации. Новые сообщения не будут использовать эти правила, пока их не удастся загрузить."; +"textRules.retryAccessibility" = "Попробовать загрузить правила фильтрации ещё раз"; +"textRules.saveFailed" = "Не удалось сохранить правила фильтрации. Попробуй ещё раз."; +"textRules.new.title" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"textRules.new.containsMessageFooter" = "Совпадает в любом месте сообщения, в том числе внутри слова."; +"textRules.new.wholeMessageFooter" = "Совпадает, только если всё сообщение равно этой фразе."; +"textRules.new.containsSenderFooter" = "Совпадает в любом месте имени отправителя, в том числе внутри слова. Реакции от этого отправителя тоже скрыты."; +"textRules.new.wholeNameFooter" = "Совпадает, только если имя отправителя в точности такое. Реакции от этого отправителя тоже скрыты."; +"textRules.new.containsMessageOrSenderFooter" = "Совпадает в любом месте сообщения или имени отправителя, в том числе внутри слова. Если совпало имя, реакции этого отправителя тоже скрыты."; +"textRules.new.wholeMessageOrSenderFooter" = "Совпадает, только если всё сообщение или всё имя отправителя равно этой фразе. Если совпало имя, реакции этого отправителя тоже скрыты."; +"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" = "Включённый переключатель охватывает все чаты этого типа, включая те, к которым ты присоединишься позже."; +"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» включает чаты, к которым ты присоединишься позже."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"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" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate radio Cleanup strings */ +"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 */ diff --git a/MC1/Resources/Localization/uk.lproj/Settings.strings b/MC1/Resources/Localization/uk.lproj/Settings.strings index b26d02b0db..a811fb7785 100644 --- a/MC1/Resources/Localization/uk.lproj/Settings.strings +++ b/MC1/Resources/Localization/uk.lproj/Settings.strings @@ -769,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "Чати"; +"blocksAndFilters.title" = "Блокування та фільтри"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -1497,6 +1499,65 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "Відображення мініатюр карти завантажує плитки для координати зі стороннього сервера, що може розкрити вашу IP-адресу."; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"textRules.rules" = "Правила фільтрації"; +"textRules.empty" = "Немає правил фільтрації"; +"textRules.loading" = "Завантаження правил фільтрації…"; +"textRules.loadFailed" = "Не вдалося завантажити правила фільтрації. Нові повідомлення не використовуватимуть правила фільтрації, доки їх не вдасться завантажити."; +"textRules.retryAccessibility" = "Спробувати завантажити правила фільтрації ще раз"; +"textRules.saveFailed" = "Не вдалося зберегти правила фільтрації. Спробуй ще раз."; +"textRules.new.title" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"textRules.new.containsMessageFooter" = "Збігається будь-де в повідомленні, зокрема всередині слова."; +"textRules.new.wholeMessageFooter" = "Збігається лише тоді, коли все повідомлення — ця фраза."; +"textRules.new.containsSenderFooter" = "Збігається будь-де в імені відправника, зокрема всередині слова. Реакції від цього відправника також приховано."; +"textRules.new.wholeNameFooter" = "Збігається лише тоді, коли ім'я відправника — точно ця фраза. Реакції від цього відправника також приховано."; +"textRules.new.containsMessageOrSenderFooter" = "Збігається будь-де в повідомленні або в імені відправника, зокрема всередині слова. Якщо збігається ім'я, реакції від цього відправника також приховано."; +"textRules.new.wholeMessageOrSenderFooter" = "Збігається лише тоді, коли все повідомлення або все ім'я відправника — ця фраза. Якщо збігається ім'я, реакції від цього відправника також приховано."; +"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" = "Коли увімкнено, це охоплює всі чати цього типу, зокрема ті, до яких ти приєднаєшся пізніше."; +"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» охоплює чати, до яких ти приєднаєшся пізніше."; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"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" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate radio Cleanup strings */ +"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 */ diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings index 44432be9a0..f619039877 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Settings.strings @@ -769,6 +769,8 @@ /* Navigation title for chat settings page */ "chatSettings.title" = "聊天"; +"blocksAndFilters.title" = "屏蔽与过滤"; + // MARK: - Link Preview Settings Section /* Section header for link content settings */ @@ -1497,6 +1499,65 @@ /* AI-translated - please verify with native speakers. */ "mapPreviews.footer" = "显示地图缩略图会从第三方服务器获取该坐标的地图图块,可能会暴露您的IP地址。"; +// MARK: - Text Rules + +/* TODO: translate Text Rules strings */ +"textRules.rules" = "过滤规则"; +"textRules.empty" = "没有过滤规则"; +"textRules.loading" = "正在加载过滤规则…"; +"textRules.loadFailed" = "无法加载过滤规则。在过滤规则加载成功之前,新消息不会使用过滤规则。"; +"textRules.retryAccessibility" = "重新加载过滤规则"; +"textRules.saveFailed" = "无法保存过滤规则。请重试。"; +"textRules.new.title" = "New Rule"; +"textRules.new.phrase" = "Word or phrase"; +"textRules.new.lookIn" = "Look In"; +"textRules.new.match" = "Match"; +"textRules.new.containsMessageFooter" = "只要在消息中出现就会匹配,包括某个词的一部分。"; +"textRules.new.wholeMessageFooter" = "仅当整条消息就是这段文字时才会匹配。"; +"textRules.new.containsSenderFooter" = "只要在发送者名称中出现就会匹配,包括某个词的一部分。该发送者的表情反应也会被隐藏。"; +"textRules.new.wholeNameFooter" = "仅当发送者名称正好是这段文字时才会匹配。该发送者的表情反应也会被隐藏。"; +"textRules.new.containsMessageOrSenderFooter" = "只要在消息或发送者名称中出现就会匹配,包括某个词的一部分。发送者名称匹配时,其表情反应也会被隐藏。"; +"textRules.new.wholeMessageOrSenderFooter" = "仅当整条消息或发送者的整个名称就是这段文字时才会匹配。发送者名称匹配时,其表情反应也会被隐藏。"; +"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" = "开启后,该类型的所有聊天都会包括在内,包括您之后加入的聊天。"; +"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”会包括您之后加入的聊天。"; +"textRules.archive.title" = "Recently Blocked"; +"textRules.archive.empty" = "No Hidden Messages"; +"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" = "Unknown Conversation"; +"textRules.archive.unknownRadio" = "Unknown Radio"; + +/* TODO: translate radio Cleanup strings */ +"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 */ diff --git a/MC1/State/AppState+Wiring.swift b/MC1/State/AppState+Wiring.swift index feea27925d..517183b509 100644 --- a/MC1/State/AppState+Wiring.swift +++ b/MC1/State/AppState+Wiring.swift @@ -112,7 +112,13 @@ extension AppState { for await event in advertisementEvents { 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)") diff --git a/MC1/State/AppState.swift b/MC1/State/AppState.swift index 5a53f7a91c..f99cda33ff 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? { 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 e4050bea29..2981f17ea4 100644 --- a/MC1/State/MessageEventDispatcher.swift +++ b/MC1/State/MessageEventDispatcher.swift @@ -59,20 +59,34 @@ final class MessageEventDispatcher { 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)) + 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) case .contactsChanged, .conversationsChanged: diff --git a/MC1/Views/Chats/ChatConversationView.swift b/MC1/Views/Chats/ChatConversationView.swift index b0eacb8858..d8809cbb76 100644 --- a/MC1/Views/Chats/ChatConversationView.swift +++ b/MC1/Views/Chats/ChatConversationView.swift @@ -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() diff --git a/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift b/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift index caaa6d23d5..2035dbfd61 100644 --- a/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift +++ b/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift @@ -161,7 +161,7 @@ enum ChatTimelinePopulator { channelIndex: channel.index, senderName: senderName, text: message.text, - timestamp: message.timestamp + timestamp: message.reactionTimestamp ) for pending in pendingMatches { @@ -206,7 +206,8 @@ enum ChatTimelinePopulator { reactionDTO, reactionService: reactionService, dataStore: dataStore, - writer: writer + writer: writer, + directMessage: pending.directMessage ) } } @@ -217,7 +218,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 +230,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+EventStream.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift index e57951e0e9..390df9b75c 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) diff --git a/MC1/Views/Contacts/ContactDetailContent.swift b/MC1/Views/Contacts/ContactDetailContent.swift index c794b517ee..05bcb14bbe 100644 --- a/MC1/Views/Contacts/ContactDetailContent.swift +++ b/MC1/Views/Contacts/ContactDetailContent.swift @@ -159,8 +159,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/RemoteNodes/Rooms/RoomConversationView.swift b/MC1/Views/RemoteNodes/Rooms/RoomConversationView.swift index 1a878760fe..65259e722e 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") { @@ -161,6 +173,7 @@ struct RoomConversationView: View { .task(id: appState.servicesVersion) { // Reassert the active room when servicesVersion changes because reconnect replaces NotificationService. appState.connectionSnapshot(for: session.radioID)?.services.notificationService.setActiveConversation(roomSessionID: session.id) + await startSessionKeepAlive() } .task { for await event in appState.messageEventStream.events() { 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/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/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/DangerZoneViewModel.swift b/MC1/Views/Settings/Sections/DangerZoneViewModel.swift index 421cbd7d70..9a44a4f190 100644 --- a/MC1/Views/Settings/Sections/DangerZoneViewModel.swift +++ b/MC1/Views/Settings/Sections/DangerZoneViewModel.swift @@ -32,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) @@ -72,7 +70,7 @@ 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, + guard settingsService != nil, connectedDevice != nil, let connectionManager, let context = connectionManager.captureCurrentRemoval() else { @@ -84,21 +82,22 @@ final class DangerZoneViewModel { removalOperationID = operationID isResetting = true defer { - if removalOperationID == operationID { isResetting = false; removalOperationID = nil } + 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 } - - let result = await connectionManager.forgetDeviceAfterReset(context) - guard removalOperationID == operationID, case let .removed(receipt) = result else { return false } - return connectionManager.isCurrent(receipt) } func fetchUnfavoritedCount() async { 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/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/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/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 96aeb9b062..c4ad520f9c 100644 --- a/MC1/Views/Settings/SettingsDetailView.swift +++ b/MC1/Views/Settings/SettingsDetailView.swift @@ -28,6 +28,8 @@ struct SettingsDetailView: View { 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 b61e5adc10..ccdff2019e 100644 --- a/MC1/Views/Settings/SettingsListContent.swift +++ b/MC1/Views/Settings/SettingsListContent.swift @@ -88,6 +88,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 d9da533e66..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 @@ -34,8 +36,8 @@ enum SettingsSubpage: Hashable { 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: @@ -119,6 +121,10 @@ private struct SettingsSubpageDestination: View { NodeConfigImportView(viewModel: configImport) .onAppear { configImport.beginImport() } } + case let .textRuleChats(kind): + TextRuleChatsView(kind: kind) + case .recentlyBlocked: + RecentlyBlockedView() case .blockedChannelSenders: BlockedChannelSendersView() case .blockedContacts: diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Connect.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Connect.swift index 58dabdc8cd..6bc2314842 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Connect.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Connect.swift @@ -113,7 +113,8 @@ public extension ConnectionManager { session: session, dataStore: persistenceStore, radioID: MockDataProvider.simulatorDeviceID, appStateProvider: appStateProvider, connectionStateEvents: connectionStateEvents, initialConnectionState: .connected, radioWiFiState: radioWiFiState(for: MockDataProvider.simulatorDeviceID), - notificationService: notificationServiceForTesting() + notificationService: notificationServiceForTesting(), + textRulesPreference: { [weak self] in await self?.textRulesPreference } ) attempt.preparedServices = container try await simulatorMode.seedDataStore(persistenceStore) diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Lifecycle.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Lifecycle.swift index 409cfbec54..b548feb505 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Lifecycle.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Lifecycle.swift @@ -103,6 +103,8 @@ 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 @@ -177,8 +179,10 @@ public extension ConnectionManager { 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() @@ -187,6 +191,7 @@ public extension ConnectionManager { } #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") @@ -211,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 diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Pairing.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Pairing.swift index 39fc7c7948..764a2ff489 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Pairing.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Pairing.swift @@ -205,20 +205,22 @@ public extension ConnectionManager { @discardableResult func forgetDevice(_ context: ConnectionRemovalContext, deleteData: Bool) async throws -> ConnectionRemovalResult { - try await removeDevice( - context, policy: .wholeDevice(deleteData: deleteData), reason: .forgetDevice, systemPolicy: .required - ) - } - - @discardableResult - func forgetDeviceAfterReset(_ context: ConnectionRemovalContext) async -> ConnectionRemovalResult { - do { + if !deleteData { return try await removeDevice( - context, policy: .wholeDevice(deleteData: true), reason: .factoryReset, systemPolicy: .bestEffort + context, policy: .wholeDevice(deleteData: false), reason: .forgetDevice, systemPolicy: .required ) - } catch { - logger.warning("Reset cleanup failed: \(error.localizedDescription)") - return .superseded + } + 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) + } + guard let device, ownsRemovalSource(context) else { return .superseded } + do { + return try await startRadioErase(device, context: context) + } catch DevicePairingError.cancelled { + return .cancelled } } @@ -413,15 +415,21 @@ public extension ConnectionManager { extension ConnectionManager: DevicePairingDelegate { public func devicePairing(_ service: any DevicePairingService, didRemoveDeviceWithID bluetoothID: UUID) { - guard removalDeviceID != bluetoothID else { return } + guard !isRemovingPairing(bluetoothID) else { return } handleRegistryRemoval(bluetoothID, pairingFailed: false) } public func devicePairing(_ service: any DevicePairingService, didFailPairingForDeviceWithID bluetoothID: UUID) { - guard removalDeviceID != bluetoothID else { return } + guard !isRemovingPairing(bluetoothID) else { return } handleRegistryRemoval(bluetoothID, pairingFailed: true) } + private func isRemovingPairing(_ bluetoothID: UUID) -> Bool { + removalDeviceID == bluetoothID || radioCleanup.values.contains { + $0.target.pairingID == bluetoothID && radioEraseTasks[$0.target.radioID] != nil + } + } + private func handleRegistryRemoval(_ id: UUID, pairingFailed: Bool) { let identity: ConnectionDeviceIdentity = if let device = connectedDevice, device.id == id { ConnectionDeviceIdentity(device) diff --git a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Preparation.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Preparation.swift index e617fea9d1..e48bf94cc7 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Preparation.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Preparation.swift @@ -62,7 +62,9 @@ extension ConnectionManager { )) let bluetoothPeripheralID = attempt.target.deviceID let registration = enqueueMetadata { store in - try await store.registerConnectionDevice(observation, bluetoothPeripheralID: bluetoothPeripheralID) + 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) @@ -88,7 +90,8 @@ extension ConnectionManager { session: resource.session, dataStore: persistenceStore, radioID: device.radioID, appStateProvider: appStateProvider, connectionStateEvents: connectionStateEvents, initialConnectionState: .connected, radioWiFiState: wifiState, - notificationService: notificationServiceForTesting(), ackEvents: attempt.ackEvents + notificationService: notificationServiceForTesting(), ackEvents: attempt.ackEvents, + textRulesPreference: { [weak self] in await self?.textRulesPreference } ) attempt.preparedServices = container await wireCleanChannelSyncCallback(on: container) 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+Removal.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Removal.swift index e55bf2eb44..946cb1f804 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Removal.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager+Removal.swift @@ -62,7 +62,7 @@ extension ConnectionManager { removalOperationID == operationID && ownsRemovalSource(context) } - private func ownsRemovalSource(_ context: ConnectionRemovalContext) -> Bool { + func ownsRemovalSource(_ context: ConnectionRemovalContext) -> Bool { desiredRequest?.id == context.requestID && (context.generation == nil || desiredRequest?.committedGeneration == context.generation) } @@ -143,7 +143,7 @@ extension ConnectionManager { } } - private func removalMatchesCurrent(_ context: ConnectionRemovalContext, policy: RemovalPolicy) -> Bool { + func removalMatchesCurrent(_ context: ConnectionRemovalContext, policy: RemovalPolicy) -> Bool { switch policy { case .wholeDevice: if let device = connectedDevice, context.identity.matches(ConnectionDeviceIdentity(device)) { return true } @@ -155,7 +155,7 @@ extension ConnectionManager { } } - private func resolveRemovalDevice( + func resolveRemovalDevice( _ identity: ConnectionDeviceIdentity, store: PersistenceStore ) async throws -> DeviceDTO? { if let id = identity.deviceID, let device = try await store.fetchDevice(id: id) { return device } 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.swift b/MC1Services/Sources/MC1Services/Connection/ConnectionManager.swift index fd04e4f4ed..de6e6e499e 100644 --- a/MC1Services/Sources/MC1Services/Connection/ConnectionManager.swift +++ b/MC1Services/Sources/MC1Services/Connection/ConnectionManager.swift @@ -162,6 +162,10 @@ 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 private(set) var wifiTransport: (any WiFiMeshTransport)? private(set) var session: MeshCoreSession? { @@ -281,6 +285,9 @@ 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? @@ -617,7 +624,8 @@ public final class ConnectionManager { transport: (any iOSMeshTransport)? = nil, pairing: (any DevicePairingService)? = nil, reconnectionClock: (any Clock)? = nil, - makeWiFiTransport: @escaping @Sendable () -> any WiFiMeshTransport = { WiFiTransport() } + makeWiFiTransport: @escaping @Sendable () -> any WiFiMeshTransport = { WiFiTransport() }, + textRulesURL: URL? = nil ) { self.modelContainer = modelContainer self.makeWiFiTransport = makeWiFiTransport @@ -627,6 +635,7 @@ public final class ConnectionManager { 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 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/Message.swift b/MC1Services/Sources/MC1Services/Models/Message.swift index 27caa780e5..e1df8f899e 100644 --- a/MC1Services/Sources/MC1Services/Models/Message.swift +++ b/MC1Services/Sources/MC1Services/Models/Message.swift @@ -26,10 +26,13 @@ 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], [\.deduplicationKey] ) @@ -723,8 +726,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/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/ReceiveScope.swift b/MC1Services/Sources/MC1Services/Models/ReceiveScope.swift new file mode 100644 index 0000000000..485efbaa58 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Models/ReceiveScope.swift @@ -0,0 +1,38 @@ +import Foundation +import Synchronization + +/// Authority captured before receive can suspend. Link teardown and partition retirement +/// invalidate the same authority at both the store and the buffered event consumer. +public struct ReceiveScope: Sendable, Equatable { + public final class Lifetime: Sendable { + private let active = Mutex(true) + + public init() {} + + public var isCurrent: Bool { + active.withLock { $0 } + } + + func retire() { + active.withLock { $0 = false } + } + } + + public let radioID: UUID + private let link: Lifetime + private let partition: Lifetime + + init(radioID: UUID, link: Lifetime, partition: Lifetime) { + self.radioID = radioID + self.link = link + self.partition = partition + } + + public static func == (lhs: Self, rhs: Self) -> 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 ec92b861b2..c39b77235e 100644 --- a/MC1Services/Sources/MC1Services/Models/RemoteNodeSession.swift +++ b/MC1Services/Sources/MC1Services/Models/RemoteNodeSession.swift @@ -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 @@ -246,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 @@ -258,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 { @@ -335,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 @@ -411,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 { 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/MessagePersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift index f7f4a4f2ae..2957e47766 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,9 @@ public protocol MessagePersisting: Actor { /// Save a new message func saveMessage(_ dto: MessageDTO) async throws + /// 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? @@ -200,3 +223,36 @@ extension MessagePersisting { nil } } + +public extension MessagePersisting { + 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/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 61b39ec967..fd55a18070 100644 --- a/MC1Services/Sources/MC1Services/ServiceContainer.swift +++ b/MC1Services/Sources/MC1Services/ServiceContainer.swift @@ -14,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. @@ -160,7 +161,8 @@ public final class ServiceContainer { radioWiFiState: RadioWiFiState? = nil, notificationService suppliedNotificationService: NotificationService? = nil, ackEvents: AsyncStream? = nil, - messageConfig: MessageServiceConfig = .default + messageConfig: MessageServiceConfig = .default, + textRulesPreference: @escaping @Sendable () async -> TextRulesPreference? = { nil } ) { self.session = session self.appStateProvider = appStateProvider @@ -184,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, @@ -225,7 +230,13 @@ public final class ServiceContainer { appStateProvider: appStateProvider, notificationService: self.notificationService ) - messagePollingService = MessagePollingService(session: session, dataStore: dataStore) + messagePollingService = MessagePollingService( + session: session, + dataStore: dataStore, + radioID: radioID, + textRulesPreference: textRulesPreference, + receiveLifetime: receiveLifetime + ) binaryProtocolService = BinaryProtocolService( session: session, radioID: radioID, @@ -259,7 +270,9 @@ public final class ServiceContainer { remoteNodeService: remoteNodeService, dataStore: dataStore, radioID: radioID, - plainTextSendGate: plainTextSendGate + plainTextSendGate: plainTextSendGate, + textRulesPreference: textRulesPreference, + receiveLifetime: receiveLifetime ) chatSendQueueService = ChatSendQueueService( @@ -416,6 +429,7 @@ 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 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 44696693ca..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)") } @@ -397,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) } @@ -485,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 a2ef456fbf..f68aefa8ea 100644 --- a/MC1Services/Sources/MC1Services/Services/AdvertisementService.swift +++ b/MC1Services/Sources/MC1Services/Services/AdvertisementService.swift @@ -300,7 +300,7 @@ public actor AdvertisementService { 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) @@ -380,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 } @@ -393,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)" - ) - } - do { - _ = try await dataStore.upsertDiscoveredNode(radioID: radioID, from: frame) - } catch { - logger.error( - "materialize pending advert Discover upsert 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)) } - eventBroadcaster.yield(.contactUpdated) - return try await dataStore.fetchContact(id: saveResult.id) + return contact } catch { logger.error( "materialize pending advert failed key=\(pubKeyHex): \(error.localizedDescription)" @@ -566,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") @@ -589,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 { 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/MessagePollingService.swift b/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift index 4edd4ba406..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 } @@ -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,16 +294,19 @@ 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) } } @@ -271,6 +314,7 @@ actor MessagePollingService { private func stopEventMonitoring() async { let eventMonitorTaskToStop = eventMonitorTask eventMonitorTask = nil + eventSubscription = nil eventMonitorTaskToStop?.cancel() await eventMonitorTaskToStop?.value } @@ -301,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/NotificationService.swift b/MC1Services/Sources/MC1Services/Services/NotificationService.swift index cb42c02905..e1e8345990 100644 --- a/MC1Services/Sources/MC1Services/Services/NotificationService.swift +++ b/MC1Services/Sources/MC1Services/Services/NotificationService.swift @@ -304,10 +304,10 @@ public final class NotificationService: NSObject { 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 } @@ -361,11 +361,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 } @@ -421,10 +420,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 } @@ -459,6 +458,7 @@ public final class NotificationService: NSObject { trigger: nil ) + guard scope?.isCurrent != false else { return } do { try await UNUserNotificationCenter.current().add(request) } catch { @@ -597,9 +597,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/PersistenceStore+BackupBatchInsert.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift index d0b53b3cd7..41452567c8 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift @@ -125,6 +125,9 @@ extension PersistenceStore { inserted += 1 } + for radioID in Set(dtos.map(\.radioID)) { + try bindRecentlyBlockedContacts(radioID: radioID) + } return (inserted, skipped, merged, contactIDsByKey) } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift index 6176a92f0f..7fbd4a33b9 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift @@ -142,9 +142,7 @@ public extension PersistenceStore { modelContext.autosaveEnabled = false defer { - if !didCommit { - modelContext.rollback() - } + if !didCommit { modelContext.rollback() } modelContext.autosaveEnabled = originalAutosaveEnabled } @@ -365,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..083d8d06bf 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Channels.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Channels.swift @@ -334,6 +334,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 index 3464226908..ff824960bb 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Connection.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Connection.swift @@ -13,6 +13,9 @@ extension PersistenceStore { /// 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 @@ -71,6 +74,7 @@ extension PersistenceStore { /// 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 } 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 009c989bb7..55e90adae1 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Devices.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Devices.swift @@ -193,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. @@ -263,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` @@ -299,11 +313,17 @@ 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) else { return nil } + guard let current = try identityDevice(id: currentDeviceID), + try !isRadioErasePending(current.radioID) else { return nil } try commitPendingRxLogEntries() - guard let radioID = try stageGhostIdentity(current: current, newPublicKey: newPublicKey) else { return nil } - try saveIdentityChanges() - return radioID + 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. @@ -312,13 +332,14 @@ public extension PersistenceStore { ) throws -> DeviceDTO? { guard let current = try identityDevice(id: deviceID), current.radioID == expectedRadioID, current.publicKey == expectedPublicKey, - !current.connectionMethods.isEmpty else { return nil } + !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)) - _ = try stageGhostIdentity(current: current, newPublicKey: selfInfo.publicKey) - try saveIdentityChanges() + let adoption = try stageGhostIdentity(current: current, newPublicKey: selfInfo.publicKey) + try saveIdentityChanges(retiring: adoption?.abandonedRadioID) return DeviceDTO(from: current) } catch { modelContext.rollback() @@ -334,7 +355,9 @@ public extension PersistenceStore { return try modelContext.fetch(descriptor).first } - private func stageGhostIdentity(current: Device, newPublicKey: Data) throws -> UUID? { + private func stageGhostIdentity( + current: Device, newPublicKey: Data + ) throws -> (radioID: UUID, abandonedRadioID: UUID?)? { let lookupKey = newPublicKey let lookupID = current.id let ghostPredicate = #Predicate { device in @@ -346,9 +369,17 @@ public extension PersistenceStore { !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 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) + } current.radioID = newRadioID current.publicKey = newPublicKey current.connectionMethods = ConnectionMethod.canonicalized(current.connectionMethods) @@ -358,34 +389,23 @@ public extension PersistenceStore { current.connectionMethods.insert(wifi, at: 0) } modelContext.delete(ghost) - return newRadioID + return (newRadioID, abandoned ? departingRadioID : nil) } - private func saveIdentityChanges() throws { - do { - #if DEBUG - try identityReconciliationFaultInjection?() - #endif - try modelContext.save() - } catch { - modelContext.rollback() - throw error + private func saveIdentityChanges(retiring abandonedRadioID: UUID?) throws { + #if DEBUG + try identityReconciliationFaultInjection?() + #endif + try modelContext.save() + if let abandonedRadioID { + retireReceiveScope(radioID: abandonedRadioID) + publishRecentlyBlockedChange() } } - /// 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 - } - 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) diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+DirectMessageReceive.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+DirectMessageReceive.swift new file mode 100644 index 0000000000..b008bc0289 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+DirectMessageReceive.swift @@ -0,0 +1,179 @@ +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 + + 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 + } + 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 + } + 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 d65ec3add3..c4357799e9 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift @@ -397,6 +397,16 @@ 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 { let targetID = id 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 dd6a6cb5e2..55e0f18cfe 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? @@ -122,9 +128,18 @@ public actor PersistenceStore: ModelActor, PersistenceStoreProtocol { /// 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 savePendingAcknowledgementFaultInjection: (@Sendable () throws -> Void)? @@ -151,7 +166,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. @@ -178,7 +195,8 @@ 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 NodeStatusSnapshot.selfRadioID (UUID?, default nil). Existing rows + /// - 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. public static func createContainer(inMemory: Bool = false) throws -> ModelContainer { if !inMemory { 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/RemoteNodeService+Login.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift index b399fc3733..e1bb25514d 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift @@ -282,7 +282,7 @@ public extension RemoteNodeService { ) async -> (shouldContinue: Bool, consecutiveFailures: Int) { var failures = consecutiveFailures do { - try await sendKeepAliveIfDirectRouted(sessionID: sessionID, publicKey: publicKey) + try await sendScheduledKeepAlive(sessionID: sessionID, publicKey: publicKey) KeepAliveRetryPolicy.recordSuccess(consecutiveFailures: &failures) return (shouldContinue: true, consecutiveFailures: failures) } catch { @@ -316,30 +316,27 @@ public extension RemoteNodeService { retiredKeepAliveTasks.append(worker) } - /// 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 + /// 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 + } - // Check contact's routing status + let publicKey = remoteSession.publicKey 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 - } + guard !contact.isFloodRouted else { throw RemoteNodeError.floodRouted } - // Log keep-alive - let targetType: CommandAuditLogger.Target = CommandAuditLogger.target(for: remoteSession.role) - await auditLogger.logKeepAlive(target: targetType, publicKey: publicKey) + await auditLogger.logKeepAlive(target: .repeater, 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 { @@ -347,14 +344,6 @@ public extension RemoteNodeService { } } - /// 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) 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.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift index 9efdc17bf0..0a93fa850a 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift @@ -20,6 +20,9 @@ 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 logger = PersistentLogger(subsystem: "com.mc1", category: "RemoteNode") let auditLogger = CommandAuditLogger() @@ -82,6 +85,17 @@ public actor RemoteNodeService { 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] = [:] @@ -135,12 +149,18 @@ 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 ) { self.session = session self.dataStore = dataStore self.keychainService = keychainService self.contactRadioOwner = contactRadioOwner + self.textRulesPreference = textRulesPreference + self.receiveLifetime = receiveLifetime + self.radioID = radioID } deinit { @@ -343,6 +363,12 @@ public actor RemoteNodeService { 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. diff --git a/MC1Services/Sources/MC1Services/Services/RoomServerService.swift b/MC1Services/Sources/MC1Services/Services/RoomServerService.swift index b7eb0b8010..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() @@ -63,15 +65,19 @@ public actor RoomServerService { init( session: any RemoteAccessSessionOps, remoteNodeService: RemoteNodeService, - dataStore: any PersistenceStoreProtocol, + dataStore: PersistenceStore, radioID: UUID, - plainTextSendGate: PlainTextSendGate? = nil + 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.plainTextSendGate = plainTextSendGate + self.textRulesPreference = textRulesPreference + self.receiveLifetime = receiveLifetime } /// Set self public key prefix from SelfInfo. @@ -187,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. @@ -379,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 @@ -486,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 d81448e000..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() @@ -275,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/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 ebf44facbf..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,59 +357,89 @@ extension SyncCoordinator { ) { return } - } - - do { - await runTestBeforeMessageSave(messageDTO) - 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)") } } @@ -426,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 @@ -482,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, @@ -516,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 ) } } @@ -540,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)") } 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.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator.swift index 6b8fd4a9bc..a48c5e9f76 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator.swift @@ -379,7 +379,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/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[...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,12 +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) - let context = try await manager.captureRemoval(id: deviceID) - await manager.forgetDeviceAfterReset(context) + 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) @@ -420,8 +616,9 @@ struct ConnectionManagerPairingTests { let lastConnected = UUID() manager.persistConnection(deviceID: lastConnected, radioID: UUID(), deviceName: "Radio") - let context = try await manager.captureRemoval(id: UUID()) - await manager.forgetDeviceAfterReset(context) + 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/ConnectionRemovalConfirmationTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalConfirmationTests.swift index 77cbd17946..0b1a1501c3 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalConfirmationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalConfirmationTests.swift @@ -10,7 +10,7 @@ import Testing @MainActor struct ConnectionRemovalConfirmationTests { @Test - func `reset cleanup retains its best effort system removal policy`() async throws { + func `reset cleanup persists across declined system removal`() async throws { let env = try ConnectionManagerRadioTestHarness() do { _ = try await env.connect(.bluetooth) @@ -19,12 +19,14 @@ struct ConnectionRemovalConfirmationTests { env.pairing.isSessionActive = true env.pairing.setPairedAccessories([ASAccessory(bluetoothIdentifier: device.id, displayName: "Reset radio")]) env.pairing.removeAccessoryError = DevicePairingError.cancelled - let result = await env.manager.forgetDeviceAfterReset(context) - if case let .removed(receipt) = result { - #expect(env.manager.isCurrent(receipt)) - } else { - Issue.record("After a submitted factory reset, local cleanup remains best effort across system removal failure") - } + 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) diff --git a/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalDrainTests.swift b/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalDrainTests.swift index c2943b98b0..8479158952 100644 --- a/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalDrainTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/ConnectionRemovalDrainTests.swift @@ -1,6 +1,6 @@ import Foundation @testable import MC1Services -import MeshCore +@testable import MeshCore import Testing @Suite("Destructive removal drains admitted writers") @@ -23,10 +23,11 @@ struct ConnectionRemovalDrainTests { finished = true return result } - try await waitUntil("forget must park in retirement while the admitted save is held") { - fixture.env.manager.connectionTeardownCount > 0 + try await waitUntil("forget must suspend new reads while the admitted save is held") { + await fixture.env.manager.session?.isMessageFetchingSuspended == true } - try await fixture.observeDeletionStillPending() + #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() @@ -44,16 +45,20 @@ struct ConnectionRemovalDrainTests { @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") { - fixture.env.manager.connectionTeardownCount > 0 + 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") { @@ -63,7 +68,7 @@ struct ConnectionRemovalDrainTests { #expect(await fixture.env.wifi.connectCount == dialsBefore) #expect(fixture.env.manager.currentConnection == nil) let messageID = try #require(fixture.gate.messageID) - fixture.gate.release() + retirement.release() _ = try await removal?.value let connected = try await #require(successor).value #expect(fixture.env.manager.isCurrent(connected)) @@ -75,6 +80,7 @@ struct ConnectionRemovalDrainTests { try await fixture.expectUnrelatedDataRemains() await fixture.finish() } catch { + retirement.release() await fixture.stop(removal, successor) throw error } @@ -83,11 +89,14 @@ struct ConnectionRemovalDrainTests { @Test func `accepted confirmation after supersession still drains the captured retirement`() async throws { let fixture = try await Fixture.make(sameRadio: false) - let confirmation = ConfirmationGate() + 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()) @@ -95,9 +104,9 @@ struct ConnectionRemovalDrainTests { 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 retirement must park on the admitted writer") { + try await waitUntil("successor must park on retirement") { let dials = await fixture.env.wifi.connectCount - return fixture.env.manager.connectionRequestID != previousRequest && fixture.env.manager.connectionTeardownCount > 0 + return fixture.env.manager.connectionRequestID != previousRequest && retirement.entered && dials == 0 } let successorRequest = fixture.env.manager.connectionRequestID @@ -112,7 +121,7 @@ struct ConnectionRemovalDrainTests { #expect(fixture.losses.count == lossesBefore) #expect(await fixture.env.wifi.connectCount == 0) let messageID = try #require(fixture.gate.messageID) - fixture.gate.release() + 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 @@ -123,6 +132,7 @@ struct ConnectionRemovalDrainTests { await fixture.finish() } catch { confirmation.release() + retirement.release() await fixture.stop(removal, successor) throw error } @@ -131,11 +141,14 @@ struct ConnectionRemovalDrainTests { @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 = ConfirmationGate() + 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()) @@ -143,10 +156,10 @@ struct ConnectionRemovalDrainTests { 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 && fixture.env.manager.connectionTeardownCount > 0 + fixture.env.manager.connectionRequestID != context.requestID && retirement.entered } confirmation.release() - try await waitUntil("accepted confirmation must queue removal while the admitted save is held") { + 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() @@ -154,15 +167,17 @@ struct ConnectionRemovalDrainTests { ASAccessory(bluetoothIdentifier: device.id, displayName: "Renewed association") ]) #expect(fixture.env.manager.pairing.isDeviceConnectable(device.id)) - fixture.gate.release() + 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 } @@ -315,12 +330,16 @@ struct ConnectionRemovalDrainTests { #expect(try await env.manager.persistenceStore.fetchDevice(radioID: radioID) != nil) } - func armConfirmation(_ confirmation: ConfirmationGate, accessoryID: UUID) { + 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) @@ -343,6 +362,7 @@ struct ConnectionRemovalDrainTests { func finish() async { gate.release() + env.manager.testConnectionTeardownHandler = nil if let coordinator { await coordinator.setTestBeforeMessageSave(nil) } @@ -413,7 +433,7 @@ struct ConnectionRemovalDrainTests { } @MainActor - private final class ConfirmationGate { + private final class Gate { private(set) var entered = false private var released = false private var continuation: CheckedContinuation? diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockAccessorySetupKitService.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockAccessorySetupKitService.swift index 34ee9b613f..114df0d956 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockAccessorySetupKitService.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockAccessorySetupKitService.swift @@ -44,6 +44,7 @@ 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() {} @@ -85,6 +86,11 @@ 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/MockMeshCoreSession.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift index 4d9ebfea36..ff0218dc93 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift @@ -32,14 +32,22 @@ 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).stream + } + + public func eventsTracked(filter: EventFilter) async -> (id: UUID, stream: AsyncStream) { makeEventStream(filter: filter) } - private func makeEventStream(filter: EventFilter?) -> AsyncStream { + 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 +55,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) { @@ -785,6 +793,10 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps startAutoMessageFetchingCallCount += 1 } + public func suspendMessageFetching() async throws {} + + public func resumeMessageFetching() {} + public func stopAutoMessageFetching() { stopAutoMessageFetchingCallCount += 1 } @@ -844,7 +856,11 @@ extension MockMeshCoreSession: RemoteAccessSessionOps { } } - 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") } 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/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/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/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/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/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/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..0df020b756 100644 --- a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorTests.swift @@ -2326,11 +2326,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) {} } 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/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift b/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift index 8f81916030..08a24f9ba9 100644 --- a/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift +++ b/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift @@ -270,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/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/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/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/ChatReconnectPopulateTests.swift b/MC1Tests/Views/Chats/ChatReconnectPopulateTests.swift index 2676dd593d..8e9d4e7210 100644 --- a/MC1Tests/Views/Chats/ChatReconnectPopulateTests.swift +++ b/MC1Tests/Views/Chats/ChatReconnectPopulateTests.swift @@ -169,12 +169,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/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/OfflineMapSettingsErrorTests.swift b/MC1Tests/Views/OfflineMapSettingsErrorTests.swift index abaf1ed5bb..c9a28d2c47 100644 --- a/MC1Tests/Views/OfflineMapSettingsErrorTests.swift +++ b/MC1Tests/Views/OfflineMapSettingsErrorTests.swift @@ -26,7 +26,7 @@ struct OfflineMapSettingsErrorTests { try #require(try await harness.waitUntil { harness.appState.offlineMapService.errorMessage == message }) let destination = SettingsDestination.offlineMaps - try #require(try await harness.openChild( + try #require(try await harness.openRow( row: destination.row, title: destination.title, markers: [message], detail: maps.detail )) try #require(try await harness.waitUntil { harness.controller.presentedViewController is UIAlertController }) diff --git a/MC1Tests/Views/Settings/RecentlyBlockedRowTests.swift b/MC1Tests/Views/Settings/RecentlyBlockedRowTests.swift new file mode 100644 index 0000000000..8b2a0ba3d6 --- /dev/null +++ b/MC1Tests/Views/Settings/RecentlyBlockedRowTests.swift @@ -0,0 +1,94 @@ +import Foundation +@testable import MC1 +import MC1Services +import Testing + +@Suite("Recently Blocked rows") +@MainActor +struct RecentlyBlockedRowTests { + @Test + func `caption names the chat, the phrase, and the rule`() { + let caption = RecentlyBlockedRow.caption( + conversationName: "Dock", + phrase: "spare", + summary: "Contains · Message" + ) + #expect(caption == "Dock · “spare” · Contains · Message") + } + + @Test + func `caption omits a missing chat`() { + let caption = RecentlyBlockedRow.caption( + conversationName: nil, + phrase: "spare", + summary: "Contains · Message" + ) + #expect(caption == "“spare” · Contains · Message") + } + + @Test + func `several radios keep the newest radio first`() throws { + let home = UUID() + let field = UUID() + let rows = try [ + makeEntry(body: "home-new", radioName: nil, radioID: home, phrase: "home-new", arrivedAt: date(3)), + makeEntry(body: "field", radioName: nil, radioID: field, phrase: "field", arrivedAt: date(2)), + makeEntry(body: "home-old", radioName: "Home", radioID: home, phrase: "home-old", arrivedAt: date(1)), + ] + let groups = RecentlyBlockedView.radioGroups(in: rows) + #expect(groups.map(\.radioID) == [home, field]) + #expect(groups.map(\.radioName) == ["Home", nil] as [String?]) + #expect(groups[0].entries.map(\.body) == ["home-new", "home-old"]) + #expect(groups[1].entries.map(\.body) == ["field"]) + } + + @Test + func `voiceover skips a missing sender and chat`() throws { + let missing = try makeEntry(body: "bring the spare", sender: nil, conversationName: nil, phrase: "spare") + let label = RecentlyBlockedRow.accessibilityLabel(for: missing) + let rule = L10n.Settings.TextRules.ruleSummary(missing.match.rule.phrase, missing.match.rule.summary) + #expect(!label.contains(L10n.Settings.TextRules.Archive.labelPrefix(L10n.Settings.TextRules.Field.sender))) + #expect(!label.contains(L10n.Settings.TextRules.Archive.labelPrefix(L10n.Settings.TextRules.Archive.chat))) + #expect(label.contains(labeled(L10n.Settings.TextRules.Field.message, "bring the spare"))) + #expect(label.contains(labeled(L10n.Settings.TextRules.Archive.rule, rule))) + #expect(label.contains(L10n.Settings.TextRules.Archive.labelPrefix(L10n.Settings.TextRules.Archive.time))) + } + + private func labeled(_ label: String, _ value: String) -> String { + L10n.Settings.TextRules.Archive.labelPrefix(label) + value + } + + private func date(_ index: Int) -> Date { + Date(timeIntervalSince1970: Double(index)) + } + + private func makeEntry( + body: String, + sender: String? = "Ada", + conversationName: String? = "Dock", + radioName: String? = "Home", + radioID: UUID = UUID(), + phrase: String = "spare", + arrivedAt: Date = Date(timeIntervalSince1970: 1_700_000_000) + ) throws -> RecentlyBlockedMessageDTO { + var preference = TextRulesPreference() + preference.append(.init(phrase: phrase, lookIn: .message, match: .contains)) + let match = try #require(preference.firstMatch(body: body, sender: sender)) + return RecentlyBlockedMessageDTO( + identity: .init( + radioID: radioID, + conversationID: UUID(), + senderPrefix: nil, + senderTimestamp: 1, + textType: 0, + wireText: Data(body.utf8) + ), + arrivedAt: arrivedAt, + body: body, + sender: sender, + conversationName: conversationName, + radioName: radioName, + match: match + ) + } +} diff --git a/MC1Tests/Views/SettingsDestination.swift b/MC1Tests/Views/SettingsDestination.swift index 46db0e8c68..ef7b8253cf 100644 --- a/MC1Tests/Views/SettingsDestination.swift +++ b/MC1Tests/Views/SettingsDestination.swift @@ -2,12 +2,16 @@ import Testing enum SettingsDestination: CaseIterable, Sendable, CustomTestStringConvertible { + case recentlyBlocked + case blockedChannelSenders + case blockedContacts case translateInto case offlineMaps case manageRegions var root: SettingsRoot { switch self { + case .recentlyBlocked, .blockedChannelSenders, .blockedContacts: .blocksAndFilters case .translateInto: .language case .offlineMaps: .maps case .manageRegions: .advanced @@ -20,6 +24,9 @@ enum SettingsDestination: CaseIterable, Sendable, CustomTestStringConvertible { var row: String { switch self { + case .recentlyBlocked: L10n.Settings.TextRules.Archive.title + case .blockedChannelSenders: L10n.Settings.Blocking.channelSenders + case .blockedContacts: L10n.Settings.Blocking.contacts case .translateInto: L10n.Settings.Language.TranslateInto.header case .offlineMaps: L10n.Settings.OfflineMaps.title case .manageRegions: L10n.Chats.Chats.ChannelInfo.Region.manageRegions @@ -28,6 +35,9 @@ enum SettingsDestination: CaseIterable, Sendable, CustomTestStringConvertible { var title: String { switch self { + case .recentlyBlocked: L10n.Settings.TextRules.Archive.title + case .blockedChannelSenders: L10n.Settings.Blocking.ChannelSenders.title + case .blockedContacts: L10n.Contacts.Contacts.Blocked.title case .translateInto: L10n.Settings.Language.TranslateInto.header case .offlineMaps: L10n.Settings.OfflineMaps.title case .manageRegions: L10n.Chats.Chats.ChannelInfo.Region.manage @@ -36,6 +46,9 @@ enum SettingsDestination: CaseIterable, Sendable, CustomTestStringConvertible { var markers: [String] { switch self { + case .recentlyBlocked: [L10n.Settings.TextRules.Archive.empty] + case .blockedChannelSenders: [L10n.Settings.Blocking.ChannelSenders.Empty.title] + case .blockedContacts: [L10n.Contacts.Contacts.Blocked.Empty.title] case .translateInto: [L10n.Settings.Language.matchAppLanguage] case .offlineMaps: [L10n.Settings.OfflineMaps.emptyTitle, L10n.Settings.OfflineMaps.storageUsed] case .manageRegions: [L10n.Chats.Chats.ChannelInfo.Region.addManually] @@ -44,6 +57,9 @@ enum SettingsDestination: CaseIterable, Sendable, CustomTestStringConvertible { var testDescription: String { switch self { + case .recentlyBlocked: "recentlyBlocked" + case .blockedChannelSenders: "blockedChannelSenders" + case .blockedContacts: "blockedContacts" case .translateInto: "translateInto" case .offlineMaps: "offlineMaps" case .manageRegions: "manageRegions" diff --git a/MC1Tests/Views/SettingsRoot.swift b/MC1Tests/Views/SettingsRoot.swift index aeecf965e3..fd58fe8f62 100644 --- a/MC1Tests/Views/SettingsRoot.swift +++ b/MC1Tests/Views/SettingsRoot.swift @@ -9,6 +9,7 @@ enum SettingsRoot: CaseIterable, Sendable, CustomTestStringConvertible { case advanced case notifications case chats + case blocksAndFilters case appearance case maps case language @@ -25,6 +26,7 @@ enum SettingsRoot: CaseIterable, Sendable, CustomTestStringConvertible { case .advanced: .advanced case .notifications: .notifications case .chats: .chats + case .blocksAndFilters: .blocksAndFilters case .appearance: .appearance case .maps: .maps case .language: .language @@ -47,6 +49,7 @@ enum SettingsRoot: CaseIterable, Sendable, CustomTestStringConvertible { case .advanced: L10n.Settings.AdvancedSettings.title case .notifications: L10n.Settings.Notifications.header case .chats: L10n.Settings.ChatSettings.title + case .blocksAndFilters: L10n.Settings.BlocksAndFilters.title case .appearance: L10n.Settings.Appearance.title case .maps: L10n.Settings.Maps.title case .language: L10n.Settings.Language.title @@ -72,6 +75,8 @@ enum SettingsRoot: CaseIterable, Sendable, CustomTestStringConvertible { [L10n.Settings.Notifications.enable, L10n.Settings.Notifications.disabled, L10n.Settings.Notifications.contactMessages] case .chats: [L10n.Settings.ReplyWithQuote.toggle] + case .blocksAndFilters: + [L10n.Settings.Blocking.channelSenders] case .appearance: [L10n.Settings.Appearance.Scheme.header] case .maps: @@ -96,6 +101,7 @@ enum SettingsRoot: CaseIterable, Sendable, CustomTestStringConvertible { case .advanced: "advanced" case .notifications: "notifications" case .chats: "chats" + case .blocksAndFilters: "blocksAndFilters" case .appearance: "appearance" case .maps: "maps" case .language: "language" diff --git a/MC1Tests/Views/SettingsRouteAdmissionTests.swift b/MC1Tests/Views/SettingsRouteAdmissionTests.swift index 29708c8121..7a960c67c3 100644 --- a/MC1Tests/Views/SettingsRouteAdmissionTests.swift +++ b/MC1Tests/Views/SettingsRouteAdmissionTests.swift @@ -13,8 +13,6 @@ struct SettingsRouteAdmissionTests { #expect(SettingsSubpage.publicKey(key).isAdmitted(for: .deviceInfo, device: device)) #expect(SettingsSubpage.configExport.isAdmitted(for: .advanced, device: device)) #expect(SettingsSubpage.configImport.isAdmitted(for: .advanced, device: device)) - #expect(SettingsSubpage.blockedChannelSenders.isAdmitted(for: .chats, device: device)) - #expect(SettingsSubpage.blockedContacts.isAdmitted(for: .chats, device: device)) #expect(SettingsSubpage.trustedContacts.isAdmitted(for: .advanced, device: device)) #expect(!SettingsSubpage.remoteCLIContacts.isAdmitted(for: .advanced, device: device)) #expect(SettingsSubpage.translateIntoLanguage.isAdmitted(for: .language, device: device)) @@ -35,6 +33,14 @@ struct SettingsRouteAdmissionTests { #expect(!SettingsSubpage.manageRegions.isAdmitted(for: .maps, device: device)) } + @Test + func `blocks and filters routes belong to their own settings page while disconnected`() { + let path: [SettingsSubpage] = [.recentlyBlocked, .blockedChannelSenders, .blockedContacts, .textRuleChats(.room)] + + #expect(SettingsSubpage.admitted(path, for: .blocksAndFilters, device: nil) == path) + #expect(SettingsSubpage.admitted(path, for: .chats, device: nil).isEmpty) + } + @Test func `capability rules drop preset location and regions`() { let repeating = makeDevice(firmware: 11, clientRepeat: true) diff --git a/MC1Tests/Views/SettingsTabHarness+Actions.swift b/MC1Tests/Views/SettingsTabHarness+Actions.swift index cc0abca280..6b769cb69d 100644 --- a/MC1Tests/Views/SettingsTabHarness+Actions.swift +++ b/MC1Tests/Views/SettingsTabHarness+Actions.swift @@ -21,8 +21,8 @@ extension SettingsTabHarness { } @discardableResult - func openChild(row: String, title: String, markers: [String], detail: SettingsDetail) async throws -> Bool { - note = "open child \(row)" + func openRow(row: String, title: String, markers: [String], detail: SettingsDetail) async throws -> Bool { + note = "open row \(row)" guard try await activateRow(row) else { return false } return try await waitUntil { navigation.selectedSetting == detail && showsPage(title: title, markers: markers) diff --git a/MC1Tests/Views/SettingsTabNavigationTests+Helpers.swift b/MC1Tests/Views/SettingsTabNavigationTests+Helpers.swift index 3a9b855ddd..70e08344ed 100644 --- a/MC1Tests/Views/SettingsTabNavigationTests+Helpers.swift +++ b/MC1Tests/Views/SettingsTabNavigationTests+Helpers.swift @@ -15,7 +15,7 @@ extension SettingsTabNavigationTests { func requireChild(_ destination: SettingsDestination, on harness: SettingsTabHarness) async throws { try await requireRoot(destination.root, on: harness) try #require( - try await harness.openChild(row: destination.row, title: destination.title, markers: destination.markers, detail: destination.root.detail), + try await harness.openRow(row: destination.row, title: destination.title, markers: destination.markers, detail: destination.root.detail), "\(harness.describe())" ) } diff --git a/MC1Tests/Views/SettingsTabNavigationTests.swift b/MC1Tests/Views/SettingsTabNavigationTests.swift index c9a8e90780..f4b25eddea 100644 --- a/MC1Tests/Views/SettingsTabNavigationTests.swift +++ b/MC1Tests/Views/SettingsTabNavigationTests.swift @@ -18,9 +18,8 @@ struct SettingsTabNavigationTests { #expect(try await harness.waitUntil { harness.tabControlsAreOnScreen() }, "\(harness.describe())") } - @Test - func `Regular back keeps the selected detail`() async throws { - let destination = SettingsDestination.manageRegions + @Test(arguments: [SettingsDestination.manageRegions, .recentlyBlocked, .blockedChannelSenders, .blockedContacts]) + func `Regular back keeps the selected detail`(_ destination: SettingsDestination) async throws { let harness = try mounted(destination.root) defer { harness.tearDown() } try await requireChild(destination, on: harness) @@ -66,7 +65,7 @@ struct SettingsTabNavigationTests { "\(harness.describe())" ) - try #require(try await harness.openChild(row: destination.row, title: destination.title, markers: destination.markers, detail: destination.root.detail), "\(harness.describe())") + try #require(try await harness.openRow(row: destination.row, title: destination.title, markers: destination.markers, detail: destination.root.detail), "\(harness.describe())") harness.selectTab(.chats) try #require(try await harness.waitUntil { harness.showsSelectedTab(.chats) }, "\(harness.describe())") harness.navigation.navigateToSetting(.backup) @@ -162,6 +161,24 @@ struct SettingsTabNavigationTests { #expect(try await harness.waitUntil { harness.tabControlsAreOnScreen() }, "\(harness.describe())") } + @Test + func `Blocks and Filters has its own row immediately after Chats`() async throws { + let harness = try SettingsTabHarness.make(connected: false) + defer { harness.tearDown() } + let chats = SettingsRoot.chats + let blocksAndFilters = SettingsRoot.blocksAndFilters + + try #require(try await harness.showSettingsList(), "\(harness.describe())") + let chatsRow = try #require(harness.cell(matching: chats.title, in: harness.visibleCollectionViews())) + let filtersRow = try #require(harness.cell(matching: blocksAndFilters.title, in: [chatsRow.list])) + #expect(filtersRow.indexPath.section == chatsRow.indexPath.section) + #expect(filtersRow.indexPath.item == chatsRow.indexPath.item + 1) + + try #require(try await harness.openRow( + row: blocksAndFilters.title, title: blocksAndFilters.title, markers: blocksAndFilters.markers, detail: blocksAndFilters.detail + ), "\(harness.describe())") + } + @Test(arguments: SettingsRoot.allCases) func `Compact root keeps tab controls on screen`(_ root: SettingsRoot) async throws { let harness = try mounted(root) diff --git a/MeshCore/Sources/MeshCore/Protocols/MessageFetchSessionOps.swift b/MeshCore/Sources/MeshCore/Protocols/MessageFetchSessionOps.swift index b8446c671b..de168c7695 100644 --- a/MeshCore/Sources/MeshCore/Protocols/MessageFetchSessionOps.swift +++ b/MeshCore/Sources/MeshCore/Protocols/MessageFetchSessionOps.swift @@ -15,6 +15,12 @@ public protocol MessageFetchSessionOps: Actor { /// Stops the automatic fetching started by ``startAutoMessageFetching()``. func stopAutoMessageFetching() + + /// Blocks new queue reads and lets an already-issued read finish. + func suspendMessageFetching() async throws + + /// Allows queue reads and drains any backlog when auto-fetch is enabled. + func resumeMessageFetching() } // MARK: - Default Implementations diff --git a/MeshCore/Sources/MeshCore/Protocols/RemoteAccessSessionOps.swift b/MeshCore/Sources/MeshCore/Protocols/RemoteAccessSessionOps.swift index 54b2bb094e..92b7efbac9 100644 --- a/MeshCore/Sources/MeshCore/Protocols/RemoteAccessSessionOps.swift +++ b/MeshCore/Sources/MeshCore/Protocols/RemoteAccessSessionOps.swift @@ -34,14 +34,12 @@ public protocol RemoteAccessSessionOps: Actor { timestamp: Date ) async throws -> MessageSentInfo - /// Sends a keep-alive request to a room server with the client's sync watermark. - /// - /// - Parameters: - /// - publicKey: The full 32-byte public key of the room server. - /// - syncSince: The client's last-received message timestamp. - /// - Returns: Information about the sent message. - /// - Throws: `MeshCoreError` if the device doesn't respond. - func sendKeepAlive(to publicKey: Data, syncSince: UInt32) async throws -> MessageSentInfo + /// Resolves the room bookmark after serializing the request and checks ownership just before sending. + func sendKeepAlive( + to publicKey: Data, + syncSince: @escaping @Sendable () async throws -> UInt32, + beforeSend: @escaping @Sendable () throws -> Void + ) async throws -> MessageSentInfo /// Requests owner information from a repeater using the binary protocol. /// @@ -127,6 +125,10 @@ public protocol RemoteAccessSessionOps: Actor { // MARK: - Default Implementations public extension RemoteAccessSessionOps { + func sendKeepAlive(to publicKey: Data, syncSince: UInt32) async throws -> MessageSentInfo { + try await sendKeepAlive(to: publicKey, syncSince: { syncSince }, beforeSend: {}) + } + /// Sends a command message stamped with the current time. func sendCommand( to destination: Data, diff --git a/MeshCore/Sources/MeshCore/Protocols/SessionEventStreaming.swift b/MeshCore/Sources/MeshCore/Protocols/SessionEventStreaming.swift index 5766385b4b..9e7f6d246a 100644 --- a/MeshCore/Sources/MeshCore/Protocols/SessionEventStreaming.swift +++ b/MeshCore/Sources/MeshCore/Protocols/SessionEventStreaming.swift @@ -25,6 +25,12 @@ public protocol SessionEventStreaming: Actor { /// - Returns: An async stream yielding only events that pass `filter`. func events(filter: EventFilter) async -> AsyncStream + /// Subscribes to filtered events with a handle for finishing the stream. + func eventsTracked(filter: EventFilter) async -> (id: UUID, stream: AsyncStream) + + /// Finishes a tracked stream, letting its consumer drain buffered events. + func finishEvents(id: UUID) async + /// Waits for an event matching an ``EventFilter`` with timeout. /// /// - Parameters: diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift index 784eeffc37..8b22e25494 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift @@ -182,6 +182,7 @@ public extension MeshCoreSession { /// channel datagram (firmware v11+), or ``MessageResult/noMoreMessages``. /// - Throws: ``MeshCoreError`` if the fetch fails. func getMessage(timeout: TimeInterval? = nil) async throws -> MessageResult { + guard !isMessageFetchingSuspended else { throw CancellationError() } getMessageCallerCountForTest += 1 defer { getMessageCallerCountForTest -= 1 } @@ -566,32 +567,32 @@ public extension MeshCoreSession { // MARK: - Keep-Alive - /// Sends a keep-alive request to a room server with the client's sync watermark. - /// - /// The companion radio passes the payload through to the mesh layer, producing: - /// `[tag(4)][REQ_TYPE_KEEP_ALIVE(1)][sync_since(4)]` — 9 bytes total. - /// - /// The room server uses `sync_since` as a force-resync hint to update the client's - /// message watermark. The normal push-and-ACK cycle also advances `sync_since` - /// independently, so this serves as a correction mechanism. - /// - /// - Parameters: - /// - publicKey: The full 32-byte public key of the room server. - /// - syncSince: The client's last-received message timestamp (little-endian on wire). - /// - Returns: Information about the sent message. - /// - Throws: ``MeshCoreError/timeout`` if the device doesn't respond. - func sendKeepAlive(to publicKey: Data, syncSince: UInt32) async throws -> MessageSentInfo { + /// Sends the room bookmark as a four-byte little-endian value. + /// A zero bookmark preserves the server’s replay cursor. + func sendKeepAlive( + to publicKey: Data, + syncSince: @escaping @Sendable () async throws -> UInt32, + beforeSend: @escaping @Sendable () throws -> Void + ) async throws -> MessageSentInfo { try requireFullPublicKey(publicKey, operation: "sendKeepAlive") - var syncSinceLE = syncSince.littleEndian - let payload = withUnsafeBytes(of: &syncSinceLE) { Data($0) } - let data = PacketBuilder.binaryRequest(to: publicKey, type: .keepAlive, payload: payload) - return try await sendAndWaitWithError( - data, - matching: { event in - if case let .messageSent(info) = event { return info } - return nil - }, - errorMatcher: Self.deviceErrorMatcher - ) + let cancelled = OSAllocatedUnfairLock(initialState: false) + + return try await withTaskCancellationHandler { + try await requestResponseSerializer.withSerialization { [self] in + var watermark = try await syncSince().littleEndian + let payload = withUnsafeBytes(of: &watermark) { Data($0) } + let data = PacketBuilder.binaryRequest(to: publicKey, type: .keepAlive, payload: payload) + return try await sendAndMatchHoldingSerialization(data, beforeSend: { + if cancelled.withLock({ $0 }) { throw CancellationError() } + try beforeSend() + }) { event in + if let error = Self.deviceErrorMatcher(event) { return .failure(error) } + if case let .messageSent(info) = event { return .success(info) } + return .ignore + } + } + } onCancel: { + cancelled.withLock { $0 = true } + } } } diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift index e4b973fd03..75c01def4e 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift @@ -151,6 +151,7 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { private var autoMessageDrainTask: Task? private var autoContactRefreshTask: Task? private var isAutoFetchingMessages = false + private(set) var isMessageFetchingSuspended = false private var autoMessageDrainRequested = false private var autoContactRefreshRequested = false var inFlightGetMessage: Task? @@ -247,6 +248,7 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { isStarting = true defer { isStarting = false } + isMessageFetchingSuspended = false logger.info("Starting MeshCore session...") if let reconnectingAttempt { updateConnectionState(.reconnecting(attempt: max(1, reconnectingAttempt))) @@ -392,9 +394,12 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { await dispatcher.subscribeTracked() } - /// Finishes a subscription created via ``eventsTracked()``. - /// - /// Causes the corresponding `for await` loop to exit. Safe to call with an unknown id. + public func eventsTracked(filter: EventFilter) async -> (id: UUID, stream: AsyncStream) { + await dispatcher.subscribeTracked(filter: filter.matches) + } + + /// Finishes a tracked subscription so its consumer exits after draining buffered events. + /// Unknown subscription IDs are ignored. public func finishEvents(id: UUID) async { await dispatcher.finishSubscription(id: id) } @@ -437,6 +442,25 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { autoMessageDrainTask = nil } + public func suspendMessageFetching() async throws { + isMessageFetchingSuspended = true + autoMessageDrainRequested = false + do { + _ = try await inFlightGetMessage?.value + } catch { + resumeMessageFetching() + throw error + } + await autoMessageDrainTask?.value + } + + public func resumeMessageFetching() { + isMessageFetchingSuspended = false + if isAutoFetchingMessages { + requestAutoMessageDrain() + } + } + private func autoMessageFetchLoop(events: AsyncStream) async { for await event in events { guard isAutoFetchingMessages else { break } @@ -449,6 +473,7 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { } private func requestAutoMessageDrain() { + guard !isMessageFetchingSuspended else { return } autoMessageDrainRequested = true guard autoMessageDrainTask == nil else { return } @@ -465,7 +490,7 @@ public actor MeshCoreSession: MeshCoreSessionProtocol { autoMessageDrainRequested = false do { - while isAutoFetchingMessages, !Task.isCancelled { + while isAutoFetchingMessages, !isMessageFetchingSuspended, !Task.isCancelled { let result = try await getMessage() if case .noMoreMessages = result { break } try await Task.sleep(for: .milliseconds(100)) From 6cd70b58c98004e590644404ea712810d9ca3fb7 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:07:44 -0800 Subject: [PATCH 16/66] fix: filter dm replay lookups by body - Avoid loading unrelated DMs when a sender repeats a timestamp. - Keep the exact UTF-8 check for replay. --- .../Services/PersistenceStore+DirectMessageReceive.swift | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+DirectMessageReceive.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+DirectMessageReceive.swift index b008bc0289..b56cd3d0a9 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+DirectMessageReceive.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+DirectMessageReceive.swift @@ -150,6 +150,7 @@ private extension PersistenceStore { 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), @@ -162,12 +163,14 @@ private extension PersistenceStore { let corrected = #Predicate { $0.radioID == radioID && $0.senderKeyPrefix == senderPrefix && $0.senderTimestamp == senderTimestamp && - $0.directionRawValue == incomingDirection && $0.channelIndex == nil && $0.textTypeRawValue == type + $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.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) }) { From faf9357fad855ae6123e6f83c7a362050154f3d1 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:36:38 -0800 Subject: [PATCH 17/66] refactor: model remote login attempts - Keep the worker and continuation on one attempt so replies, timeouts, and cancellation can claim completion only once. - Test early and duplicate replies, replacement attempts, and cancellation during persistence. --- .../Services/RemoteLoginAttempt.swift | 68 ++++ .../Services/RemoteNodeService+Login.swift | 369 +++++------------- .../RemoteNodeService+SessionManagement.swift | 186 +++++++++ .../Services/RemoteNodeService.swift | 35 +- .../Mocks/MockMeshCoreSession.swift | 12 +- .../Mocks/MockPersistenceStore.swift | 6 + .../RemoteNodeLoginLifecycleTests.swift | 258 ++++++++++++ .../Services/RemoteNodeSensorTests.swift | 2 +- 8 files changed, 631 insertions(+), 305 deletions(-) create mode 100644 MC1Services/Sources/MC1Services/Services/RemoteLoginAttempt.swift create mode 100644 MC1Services/Sources/MC1Services/Services/RemoteNodeService+SessionManagement.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeLoginLifecycleTests.swift 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+Login.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift index e1bb25514d..24ebf5113e 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+Login.swift @@ -1,6 +1,8 @@ import Foundation import MeshCore +private let loginPublicKeyPrefixLength = 6 + public extension RemoteNodeService { // MARK: - Login @@ -36,102 +38,34 @@ public extension RemoteNodeService { 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(6)) + let prefix = Data(remoteSession.publicKey.prefix(loginPublicKeyPrefixLength)) cancelPendingLogin(for: prefix) - let attemptID = UUID() - loginAttemptIDs[prefix] = attemptID + let attempt = RemoteLoginAttempt(sessionID: sessionID) + let attemptID = attempt.id + loginAttempts[prefix] = attempt defer { - if loginAttemptIDs[prefix] == attemptID { loginAttemptIDs[prefix] = nil } + if loginAttempts[prefix]?.id == attemptID { loginAttempts[prefix] = nil } } - // Log login request 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 - guard !Task.isCancelled, loginAttemptIDs[prefix] == attemptID, !isRetired else { + guard !Task.isCancelled, loginAttempts[prefix]?.id == attemptID, !isRetired else { continuation.resume(throwing: RemoteNodeError.cancelled) return } - pendingLogins[prefix] = PendingLogin(id: attemptID, 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, loginAttemptIDs[prefix] == attemptID, !isRetired 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 - } - - guard !Task.isCancelled, loginAttemptIDs[prefix] == attemptID, !isRetired else { 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)) + // 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, loginAttemptIDs[prefix] == attemptID, !isRetired 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, loginAttemptIDs[prefix] == attemptID, !isRetired 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 @@ -140,6 +74,73 @@ public extension RemoteNodeService { } } + 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 /// copy (flood-routed) and retries once. A contact can be in the app database but absent on the /// radio after a backup restore or a radio swap, which the firmware answers with notFound (0x02). @@ -192,233 +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 do { - guard loginAttemptIDs[prefix] == pending.id, !isRetired else { throw RemoteNodeError.cancelled } - guard let remoteSession = try await dataStore.fetchRemoteNodeSession(id: pending.sessionID) else { + guard !isRetired else { throw RemoteNodeError.cancelled } + guard let remoteSession = try await dataStore.fetchRemoteNodeSession(id: completion.sessionID) else { throw RemoteNodeError.sessionNotFound } - guard loginAttemptIDs[prefix] == pending.id, !isRetired else { throw RemoteNodeError.cancelled } + 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") } await auditLogger.logLoginSuccess(target: target, publicKey: prefix, isAdmin: result.isAdmin) - guard loginAttemptIDs[prefix] == pending.id, !isRetired else { throw RemoteNodeError.cancelled } + 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 loginAttemptIDs[prefix] == pending.id, !isRetired else { + 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 loginAttemptIDs[prefix] == nil { try? await dataStore.markSessionDisconnected(remoteSession.id) } + if loginAttempts[prefix] == nil { try? await dataStore.markSessionDisconnected(remoteSession.id) } throw RemoteNodeError.cancelled } eventBroadcaster.yield(.sessionStateChanged(sessionID: remoteSession.id, isConnected: true)) if remoteSession.isRoom { keepAliveIntervals[remoteSession.id] = Self.defaultKeepAliveInterval } - continuation.resume(returning: result) - } catch { - continuation.resume(throwing: error) - } - } - - // 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) + completion.continuation.resume(returning: result) } catch { - // Ignore errors - we're disconnecting anyway - logger.info("Logout send failed (ignoring): \(error)") + completion.continuation.resume(throwing: 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+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.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift index 0a93fa850a..d6b9acdac2 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift @@ -27,24 +27,10 @@ public actor RemoteNodeService { let auditLogger = CommandAuditLogger() var isRetired = false - var loginAttemptIDs: [Data: UUID] = [:] + /// Login ownership keyed by the public key prefix carried in login responses. + var loginAttempts: [Data: RemoteLoginAttempt] = [:] var sensorConnectAttempts: [UUID: UUID] = [:] - struct PendingLogin { - let id: UUID - /// 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 @@ -293,12 +279,10 @@ public actor RemoteNodeService { } func cancelPendingLogin(for prefix: Data, attemptID: UUID? = nil) { - if let attemptID, loginAttemptIDs[prefix] != attemptID { return } - loginAttemptIDs[prefix] = nil - pendingLoginTimeoutTasks.removeValue(forKey: prefix)?.cancel() - if let pending = pendingLogins.removeValue(forKey: prefix) { - pending.continuation.resume(throwing: RemoteNodeError.cancelled) - } + 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) } func cancelPendingCLIRequest(for prefix: Data, requestID: UUID) { @@ -411,16 +395,13 @@ public actor RemoteNodeService { /// Stop all keep-alive timers and resume any parked login continuations (call on app termination) public func stopAllKeepAlives() { - loginAttemptIDs.removeAll() 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) } } @@ -461,6 +442,6 @@ public actor RemoteNodeService { /// Number of login continuations currently parked. Exposed for teardown tests. var pendingLoginCount: Int { - pendingLogins.count + loginAttempts.values.count(where: \.isAwaitingResult) } } diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift index ff0218dc93..74bcce275d 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift @@ -217,6 +217,7 @@ 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. @@ -297,6 +298,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] = [] @@ -373,6 +375,10 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps 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 @@ -814,6 +820,7 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps getContactPublicKeys = [] addContactInvocations = [] sendLoginInvocations = [] + completedSendLoginCount = 0 sendCommandInvocations = [] removeContactPublicKeys = [] resetPathPublicKeys = [] @@ -832,8 +839,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 } diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift index 2e541a52b1..2e6f9e3af8 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift @@ -2011,6 +2011,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] @@ -2087,6 +2092,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, 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/RemoteNodeSensorTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeSensorTests.swift index 288796c31a..546534db9c 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeSensorTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeSensorTests.swift @@ -253,7 +253,7 @@ extension RemoteNodeSensorTests { 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.loginAttemptIDs[prefix]) + 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) From e86127168800ae865d75c427d0b1c686c2c6a17e Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Fri, 6 Nov 2026 23:22:12 -0800 Subject: [PATCH 18/66] fix: keep trace completion tied to its request - Store submission and wait state together so late send completion cannot replace a result. - Save the submitted path and hash size when the editor changes. --- .../Tools/TracePath/TracePathViewModel.swift | 280 ++++++------------ .../TracePath/TraceRequestState+Input.swift | 12 + .../TraceRequestState+Submission.swift | 10 + .../TracePath/TraceRequestState+Wait.swift | 9 + .../Tools/TracePath/TraceRequestState.swift | 30 ++ MC1Tests/ViewModels/BatchTraceTests.swift | 2 +- .../TracePathExecutionCancellationTests.swift | 158 +++++++++- .../ViewModels/TracePathListenerTests.swift | 4 +- .../TracePathSaveSnapshotTests.swift | 106 +++++++ .../ViewModels/TracePathViewModelTests.swift | 43 ++- 10 files changed, 439 insertions(+), 215 deletions(-) create mode 100644 MC1/Views/Tools/TracePath/TraceRequestState+Input.swift create mode 100644 MC1/Views/Tools/TracePath/TraceRequestState+Submission.swift create mode 100644 MC1/Views/Tools/TracePath/TraceRequestState+Wait.swift create mode 100644 MC1/Views/Tools/TracePath/TraceRequestState.swift create mode 100644 MC1Tests/ViewModels/TracePathSaveSnapshotTests.swift diff --git a/MC1/Views/Tools/TracePath/TracePathViewModel.swift b/MC1/Views/Tools/TracePath/TracePathViewModel.swift index e666b9da72..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() { @@ -276,7 +263,6 @@ final class TracePathViewModel { completedResults.removeAll() clearBatchState() activeSavedPath = nil - responseDeadline = nil presentedSuccessID = nil resultDismissedWhileVisible = false clearError() @@ -377,10 +363,10 @@ final class TracePathViewModel { var canSavePath: Bool { if batchEnabled { guard !completedResults.isEmpty, let firstSuccess = successfulResults.first else { return false } - return fullPathBytes == firstSuccess.tracedPathBytes + 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 } } @@ -537,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 } @@ -561,7 +546,6 @@ final class TracePathViewModel { return hop } activeSavedPath = nil - pendingPathHash = nil result = nil } @@ -586,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() } @@ -600,7 +583,6 @@ final class TracePathViewModel { guard outboundPath.indices.contains(index) else { return } outboundPath.remove(at: index) activeSavedPath = nil - pendingPathHash = nil result = nil } @@ -609,7 +591,6 @@ final class TracePathViewModel { clearError() outboundPath.move(fromOffsets: source, toOffset: destination) activeSavedPath = nil - pendingPathHash = nil result = nil } @@ -665,7 +646,7 @@ final class TracePathViewModel { radioID: radioID, name: name, pathBytes: Data(firstSuccess.tracedPathBytes), - hashSize: hashSize, + hashSize: firstSuccess.hashSize, initialRun: initialRun ) @@ -712,7 +693,7 @@ final class TracePathViewModel { radioID: radioID, name: name, pathBytes: Data(result.tracedPathBytes), - hashSize: hashSize, + hashSize: result.hashSize, initialRun: initialRun ) activeSavedPath = savedPath @@ -753,7 +734,6 @@ final class TracePathViewModel { func loadSavedPath(_ savedPath: SavedTracePathDTO) { outboundPath.removeAll() result = nil - pendingPathHash = nil let fullPath = savedPath.pathBytes let size = savedPath.hashSize @@ -799,7 +779,6 @@ final class TracePathViewModel { activeSavedPath = nil outboundPath.removeAll() result = nil - pendingPathHash = nil traceHashMode = nil } @@ -863,9 +842,6 @@ 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() @@ -878,14 +854,7 @@ final class TracePathViewModel { 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 @@ -956,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 { @@ -1024,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 { @@ -1089,69 +1045,51 @@ 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), 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), let savedPath = activeSavedPath else { return } @@ -1198,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 @@ -1214,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. @@ -1308,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() @@ -1322,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 @@ -1342,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") @@ -1366,7 +1284,7 @@ final class TracePathViewModel { } var timeoutTaskForTesting: Task? { - timeoutTask + traceRequest.timeoutTask } var errorAutoClearTaskForTesting: Task? { @@ -1374,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/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/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 { From 3da34dca9a9dfe154d1eeb5d110959e6e4159592 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Fri, 6 Nov 2026 23:52:57 -0800 Subject: [PATCH 19/66] refactor: make pairing ownership explicit - Keep native picker ownership until dismissal so cancellation cannot admit a replacement picker. - Model pairing work and its single foreground retry with explicit phases. --- MC1/State/AppState+DeviceActions.swift | 230 +--------------- MC1/State/AppState+FreshPairing.swift | 224 ++++++++++++++++ MC1/State/AppState.swift | 23 +- MC1/State/ConnectionUIState.swift | 4 - MC1/State/FreshPairingOperation+Attempt.swift | 6 + MC1/State/FreshPairingOperation+Phase.swift | 7 + MC1/State/FreshPairingOperation+Source.swift | 7 + MC1/State/FreshPairingOperation.swift | 23 ++ .../AccessoryPickerState+Attempt.swift | 11 + .../AccessoryPickerState+Outcome.swift | 14 + ...soryPickerState+SelectionDisposition.swift | 8 + .../Services/AccessoryPickerState.swift | 171 ++++++++++++ .../Services/AccessorySetupKitService.swift | 229 ++++++---------- .../Services/AccessoryPickerStateTests.swift | 251 ++++++++++++++++++ .../PairingRecoveryOwnershipTests.swift | 12 +- .../SystemPairingSetupAppStateTests.swift | 99 ++++++- 16 files changed, 914 insertions(+), 405 deletions(-) create mode 100644 MC1/State/AppState+FreshPairing.swift create mode 100644 MC1/State/FreshPairingOperation+Attempt.swift create mode 100644 MC1/State/FreshPairingOperation+Phase.swift create mode 100644 MC1/State/FreshPairingOperation+Source.swift create mode 100644 MC1/State/FreshPairingOperation.swift create mode 100644 MC1Services/Sources/MC1Services/Services/AccessoryPickerState+Attempt.swift create mode 100644 MC1Services/Sources/MC1Services/Services/AccessoryPickerState+Outcome.swift create mode 100644 MC1Services/Sources/MC1Services/Services/AccessoryPickerState+SelectionDisposition.swift create mode 100644 MC1Services/Sources/MC1Services/Services/AccessoryPickerState.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/AccessoryPickerStateTests.swift diff --git a/MC1/State/AppState+DeviceActions.swift b/MC1/State/AppState+DeviceActions.swift index dc092e0998..bd916d5762 100644 --- a/MC1/State/AppState+DeviceActions.swift +++ b/MC1/State/AppState+DeviceActions.swift @@ -5,162 +5,6 @@ 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() { - guard !isRecoveringPairing else { return } - let (operation, previous) = beginFreshPairingOperation(source: .explicitSwitch) - connectionUI.hideDisconnectedPill() - connectionUI.failedPairingDeviceID = nil - freshPairingTask = Task { - defer { finishFreshPairingWork(operation.actionID) } - await withPairingFlowErrorHandling(actionID: operation.actionID) { - let pending = try await connectionManager.systemAccessoriesMissingDeviceRecord() - guard ownsFreshPairingOperation(operation.actionID), - operation.requestID == connectionManager.connectionRequestID else { return } - if !pending.isEmpty { - 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 !isConfirmingSystemPairingSetup, 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) } - 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 - connectionUI.shouldCompleteFreshPairingOnForeground = false - isFreshPairingForegroundRetry = false - isConfirmingSystemPairingSetup = source == .systemPairingSetup - connectionManager.isPairingFlowActive = true - return (operation, previous) - } - - private func ownsFreshPairingOperation(_ actionID: UUID) -> Bool { - freshPairingOperation?.actionID == actionID && connectionUI.isCurrentConnectionAction(actionID) - } - - private func finishFreshPairingWork(_ actionID: UUID) { - guard freshPairingOperation?.actionID == actionID else { return } - isConfirmingSystemPairingSetup = false - if isFreshPairingForegroundRetry { return } - if ownsFreshPairingOperation(actionID), - connectionUI.shouldCompleteFreshPairingOnForeground || connectionUI.pendingSystemPairingSetup != nil { - connectionUI.isBusy = false - return - } - finishFreshPairingOperation(actionID) - } - - private func finishFreshPairingOperation(_ actionID: UUID) { - guard freshPairingOperation?.actionID == actionID else { return } - freshPairingOperation = nil - freshPairingForegroundRetryTask?.cancel() - freshPairingForegroundRetryTask = nil - connectionUI.shouldCompleteFreshPairingOnForeground = false - isFreshPairingForegroundRetry = false - isConfirmingSystemPairingSetup = false - connectionManager.isPairingFlowActive = false - connectionUI.finishConnectionAction(actionID) - } - - func cancelFreshPairingOperation() { - freshPairingTask?.cancel() - freshPairingForegroundRetryTask?.cancel() - if let operation = freshPairingOperation { - finishFreshPairingOperation(operation.actionID) - } else { - connectionUI.shouldCompleteFreshPairingOnForeground = false - isFreshPairingForegroundRetry = false - connectionManager.isPairingFlowActive = false - } - } - - 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 isFreshPairingForegroundRetry { - 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) - } - } - } - func currentConnectionFailure(_ error: any Error) -> (any Error)? { if error is CancellationError { return nil } if let failure = error as? ConnectionRequestFailure { @@ -170,78 +14,6 @@ extension AppState { return error } - private func scheduleFreshPairingOnForeground(actionID: UUID) { - guard ownsFreshPairingOperation(actionID), - freshPairingOperation?.requestID == connectionManager.connectionRequestID else { return } - connectionUI.shouldCompleteFreshPairingOnForeground = true - freshPairingForegroundRetryTask?.cancel() - freshPairingForegroundRetryTask = Task { - try? await Task.sleep(for: Self.freshPairingForegroundRetryDelay) - guard !Task.isCancelled, freshPairingOperation?.actionID == actionID else { return } - resumeFreshPairingIfNeeded() - } - } - - private func resumeFreshPairingIfNeeded() { - guard connectionUI.shouldCompleteFreshPairingOnForeground, let operation = freshPairingOperation else { return } - connectionUI.shouldCompleteFreshPairingOnForeground = false - guard ownsFreshPairingOperation(operation.actionID), - operation.requestID == connectionManager.connectionRequestID else { - finishFreshPairingOperation(operation.actionID) - return - } - freshPairingForegroundRetryTask?.cancel() - freshPairingForegroundRetryTask = nil - let previous = freshPairingTask - connectionUI.isBusy = true - isFreshPairingForegroundRetry = true - freshPairingTask = Task { - await previous?.value - defer { - if freshPairingOperation?.actionID == operation.actionID { isFreshPairingForegroundRetry = false } - finishFreshPairingWork(operation.actionID) - } - 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) } - 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 - } - /// Retry connecting to the device that just failed without removing the bond. /// Used for transient pairing failures where the bond is still good — radio out of range, /// brief BLE flap, etc. Auth-failure paths route through `removeFailedPairingAndRetry` @@ -282,7 +54,7 @@ extension AppState { // from the foreground reconnect instead of staying silenced from background. connectionManager.clearSurfacedAuthenticationFailure() - if connectionUI.shouldCompleteFreshPairingOnForeground { + if shouldCompleteFreshPairingOnForeground { resumeFreshPairingIfNeeded() return } diff --git a/MC1/State/AppState+FreshPairing.swift b/MC1/State/AppState+FreshPairing.swift new file mode 100644 index 0000000000..e92a1d78f4 --- /dev/null +++ b/MC1/State/AppState+FreshPairing.swift @@ -0,0 +1,224 @@ +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 + } + } + + 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.swift b/MC1/State/AppState.swift index f99cda33ff..8c5e5d320a 100644 --- a/MC1/State/AppState.swift +++ b/MC1/State/AppState.swift @@ -299,29 +299,14 @@ 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 - - /// True while the foreground retry of `completeFreshPairing` is running, so a - /// second `pickerUnavailable` is presented instead of rescheduled. - var isFreshPairingForegroundRetry = false - - struct FreshPairingOperation { - enum Source { - case explicitSwitch - case systemPairingSetup - case bondLossRecovery - } - - let actionID: UUID - let source: Source - var requestID: UUID? - } - var freshPairingOperation: FreshPairingOperation? var freshPairingTask: Task? var freshPairingForegroundRetryTask: Task? + var shouldCompleteFreshPairingOnForeground: Bool { + freshPairingOperation?.phase == .awaitingForegroundRetry + } + var isRecoveringPairing: Bool { freshPairingOperation?.source == .bondLossRecovery } diff --git a/MC1/State/ConnectionUIState.swift b/MC1/State/ConnectionUIState.swift index 1228afe0ff..8c8eda533d 100644 --- a/MC1/State/ConnectionUIState.swift +++ b/MC1/State/ConnectionUIState.swift @@ -99,10 +99,6 @@ final class ConnectionUIState { /// Re-subscribed per connection in `wireCallbacks`; cancelled on disconnect. private var nodeDeletedEventsTask: Task? - /// 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? 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/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/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/MC1Tests/AppState/PairingRecoveryOwnershipTests.swift b/MC1Tests/AppState/PairingRecoveryOwnershipTests.swift index 2be2e99f34..d36bd0eab3 100644 --- a/MC1Tests/AppState/PairingRecoveryOwnershipTests.swift +++ b/MC1Tests/AppState/PairingRecoveryOwnershipTests.swift @@ -50,7 +50,7 @@ struct PairingRecoveryOwnershipTests { env.picker.setPickerResult(.failure(AccessorySetupKitError.pickerRestricted)) let operation = try #require(env.app.removeFailedPairingAndRetry()) await operation.value - #expect(env.app.connectionUI.shouldCompleteFreshPairingOnForeground) + #expect(env.app.shouldCompleteFreshPairingOnForeground) #expect(!env.app.connectionUI.isBusy) #expect(env.app.isRecoveringPairing) #expect(env.manager.isPairingFlowActive) @@ -64,7 +64,7 @@ struct PairingRecoveryOwnershipTests { #expect(!env.app.isRecoveringPairing) #expect(!env.manager.isPairingFlowActive) #expect(!env.app.connectionUI.isBusy) - #expect(!env.app.connectionUI.shouldCompleteFreshPairingOnForeground) + #expect(!env.app.shouldCompleteFreshPairingOnForeground) #expect(env.picker.showPickerCallCount == 1) #expect(env.manager.isCurrent(result)) } @@ -102,7 +102,7 @@ struct PairingRecoveryOwnershipTests { env.picker.setPickerResult(.failure(AccessorySetupKitError.pickerRestricted)) env.app.startDeviceScan() try await waitUntil("picker rejection must arm its scoped retry") { - env.app.connectionUI.shouldCompleteFreshPairingOnForeground && !env.app.connectionUI.isBusy + 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 { @@ -111,7 +111,7 @@ struct PairingRecoveryOwnershipTests { } env.app.handleBecameActive() try await waitUntil("the obsolete foreground flow must settle") { - !env.app.connectionUI.shouldCompleteFreshPairingOnForeground && !env.app.connectionUI.isBusy + !env.app.shouldCompleteFreshPairingOnForeground && !env.app.connectionUI.isBusy } #expect(env.picker.showPickerCallCount == 1) @@ -168,7 +168,7 @@ struct PairingRecoveryOwnershipTests { env.picker.setPickerResult(.failure(AccessorySetupKitError.pickerRestricted)) env.app.startDeviceScan() try await waitUntil("the first picker must leave a pending retry") { - env.app.connectionUI.shouldCompleteFreshPairingOnForeground && !env.app.connectionUI.isBusy + env.app.shouldCompleteFreshPairingOnForeground && !env.app.connectionUI.isBusy } let next = env.app.connectionUI.beginConnectionAction() defer { env.app.connectionUI.finishConnectionAction(next) } @@ -177,7 +177,7 @@ struct PairingRecoveryOwnershipTests { } #expect(env.app.connectionUI.isCurrentConnectionAction(next)) #expect(env.app.connectionUI.isBusy) - #expect(!env.app.connectionUI.shouldCompleteFreshPairingOnForeground) + #expect(!env.app.shouldCompleteFreshPairingOnForeground) #expect(env.picker.showPickerCallCount == 1) } } diff --git a/MC1Tests/State/SystemPairingSetupAppStateTests.swift b/MC1Tests/State/SystemPairingSetupAppStateTests.swift index d7df8c493f..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) @@ -338,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() From 20294465486ad5855a39e884c5413f386c632c95 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Sat, 7 Nov 2026 08:54:37 -0800 Subject: [PATCH 20/66] fix: serialize durable ack settlement - Keep one terminal writer so competing ACKs preserve delivery events and send admission. - Retain matched ACKs after failed saves and clean up owners installed during delivery. - Use the same settlement path for waiter and listener ACKs. --- .../Services/MessageService+ACK.swift | 6 +- .../Services/MessageService+ACKRecovery.swift | 68 ++++--- .../Services/MessageService+DMRetry.swift | 3 +- .../Services/MessageService+SendDM.swift | 45 ++--- .../MC1Services/Services/MessageService.swift | 5 +- .../MC1Services/Services/PendingAck.swift | 133 ++++++++++-- .../Mocks/MockMeshCoreSession.swift | 4 + .../Mocks/MockPersistenceStore.swift | 20 ++ .../MessageServiceACKFinalizationTests.swift | 191 ++++++++++++++++++ .../MessageServiceACKSettlementTests.swift | 191 ++++++++++++++++++ .../Services/MessageServiceACKTests.swift | 4 +- ...MessageServiceSendDMBookkeepingTests.swift | 2 +- .../Services/MessageServiceSendTests.swift | 4 +- 13 files changed, 587 insertions(+), 89 deletions(-) create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKFinalizationTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/MessageServiceACKSettlementTests.swift diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+ACK.swift b/MC1Services/Sources/MC1Services/Services/MessageService+ACK.swift index b88b0737a5..a8ea1b693c 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+ACK.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+ACK.swift @@ -74,7 +74,7 @@ public extension MessageService { let window = config.ackGiveUpWindow let expiredEntries = pendingAcks.filter { _, tracking in - !tracking.isDelivered && + !tracking.isResolved && now > tracking.expiresAt(giveUpWindow: window) } @@ -85,7 +85,7 @@ public extension MessageService { } #endif guard let current = pendingAcks[messageID], - !current.isDelivered, + !current.isResolved, current.sentAt == tracking.sentAt, now > current.expiresAt(giveUpWindow: window) else { continue } @@ -112,7 +112,7 @@ public extension MessageService { let pending = Array(pendingAcks) for (messageID, tracking) in pending { - guard pendingAcks[messageID]?.sentAt == tracking.sentAt, pendingAcks[messageID]?.isDelivered == false else { continue } + guard pendingAcks[messageID]?.sentAt == tracking.sentAt, pendingAcks[messageID]?.isResolved == false else { continue } do { _ = try await commitPendingAcknowledgement(messageID: messageID, sentAt: tracking.sentAt) } catch { diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift b/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift index 7026d4ff7d..d029634d9f 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift @@ -35,22 +35,26 @@ extension MessageService { @discardableResult func persistAcknowledgement(messageID: UUID, radioID: UUID, pendingSendID: UUID?) async -> Bool { - guard let tracking = pendingAcks[messageID], !tracking.isDelivered else { return false } - if tracking.owner == nil { - pendingAcks[messageID]?.owner = .init( - id: pendingSendID ?? UUID(), - radioID: radioID, - deadline: tracking.expiresAt(giveUpWindow: config.ackGiveUpWindow), - phase: pendingSendID == nil ? .insert : .convert - ) + 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 let tracking = pendingAcks[messageID], !tracking.isDelivered, - let owner = tracking.owner, owner.phase != .saved, - acknowledgementSavesInFlight.insert(messageID).inserted else { return false } + 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( @@ -64,15 +68,18 @@ extension MessageService { let saved: Bool do { saved = try await dataStore.savePendingAcknowledgement( - row, replacingPendingSendID: owner.phase == .convert ? owner.id : nil + row, replacingPendingSendID: owner.phase == .saving(.convert) ? owner.id : nil ) } 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.isDelivered else { + current.sentAt == tracking.sentAt, !current.isResolved else { if saved { await cleanUpStaleAcknowledgementOwner(tracking, owner: owner) } @@ -83,7 +90,7 @@ extension MessageService { return false } - pendingAcks[messageID]?.owner?.phase = .saved + pendingAcks[messageID]?.finishOwnerSave(succeeded: true) if current.matchedAckCode != nil { do { _ = try await commitPendingAcknowledgement(messageID: messageID, sentAt: current.sentAt) @@ -112,30 +119,39 @@ extension MessageService { } func commitPendingAcknowledgement(messageID: UUID, sentAt: Date) async throws -> PendingAcknowledgementCommit { - guard let current = pendingAcks[messageID], current.sentAt == sentAt else { return .unchanged } - if let owner = current.owner, owner.phase != .saved { return .unchanged } - let status: MessageStatus = current.matchedAckCode == nil ? .failed : .delivered + guard pendingAcks[messageID]?.sentAt == sentAt, + let status = pendingAcks[messageID]?.beginResolution(), + let current = pendingAcks[messageID] else { return .unchanged } let leaseID = current.sendLeaseID - let updated = try await writeTerminalAcknowledgement(current, status: status) + 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 } - guard updated else { - pendingAcks.removeValue(forKey: messageID) - await settlePlainTextLease(leaseID) - return .unchanged + pendingAcks[messageID]?.resolutionSaveSucceeded() + if current.owner == nil, let installedOwner = pendingAcks[messageID]?.owner { + await cleanUpStaleAcknowledgementOwner(current, owner: installedOwner) } - pendingAcks[messageID]?.isDelivered = true - if status == .delivered { + 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 = pendingAcks[messageID]?.matchedTripTime - pendingAcks.removeValue(forKey: messageID) + 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: statusEventBroadcaster.yield(.statusResolved(messageID: messageID, status: .delivered, roundTripTime: tripTime)) diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+DMRetry.swift b/MC1Services/Sources/MC1Services/Services/MessageService+DMRetry.swift index e5a7a8863d..ab17fa17f4 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+DMRetry.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+DMRetry.swift @@ -185,8 +185,9 @@ extension MessageService { } guard let previousAck, let current = pendingAcks[messageID], current.sendLeaseID == sendLeaseID else { return true } + guard current.isAwaitingAck else { return true } if rejected { - // Restore accepted codes and timing without overwriting an ACK matched during the command. + // 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 diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift index 041898eb15..fc415405c3 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift @@ -434,12 +434,8 @@ public 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. + /// 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, @@ -447,19 +443,17 @@ public extension MessageService { timeout: TimeInterval, sendLeaseID: UUID? = nil ) { - // 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. + // 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.owner = nil + existing.resetOwner() if let sendLeaseID { existing.sendLeaseID = sendLeaseID } @@ -490,33 +484,18 @@ public extension MessageService { 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 { - let leaseID = tracking?.sendLeaseID - pendingAcks.removeValue(forKey: messageID) - await settlePlainTextLease(leaseID) - } else if let acknowledgedCode, tracking?.matchedAckCode == nil { - // 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) await settlePlainTextLease(leaseID) - try await dataStore.updateMessageAck( - id: messageID, - ackCode: acknowledgedCode.ackCodeUInt32, - status: .delivered - ) - try await dataStore.updateContactLastMessage(contactID: contactID, date: Date()) - statusEventBroadcaster.yield(.statusResolved(messageID: messageID, status: .delivered, roundTripTime: nil)) } else { + 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 movedToSent = await persistAcknowledgement( diff --git a/MC1Services/Sources/MC1Services/Services/MessageService.swift b/MC1Services/Sources/MC1Services/Services/MessageService.swift index c84eae6296..d7f8e77ed0 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService.swift @@ -206,7 +206,7 @@ public actor MessageService { /// succeeds, so a thrown write can be retried with the same code. func handleAcknowledgement(code: Data, tripTime: UInt32?) async { guard let (messageID, tracking) = pendingAcks.first(where: { - $0.value.ackCodes.contains(code) && !$0.value.isDelivered + $0.value.ackCodes.contains(code) && !$0.value.isResolved }) 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 @@ -220,8 +220,7 @@ public actor MessageService { return } - pendingAcks[messageID]?.matchedAckCode = code.ackCodeUInt32 - pendingAcks[messageID]?.matchedTripTime = tripTime + pendingAcks[messageID]?.recordAcknowledgement(code: code.ackCodeUInt32, tripTime: tripTime) do { _ = try await commitPendingAcknowledgement(messageID: messageID, sentAt: tracking.sentAt) } catch { diff --git a/MC1Services/Sources/MC1Services/Services/PendingAck.swift b/MC1Services/Sources/MC1Services/Services/PendingAck.swift index fd512a71c5..70f3f5d779 100644 --- a/MC1Services/Sources/MC1Services/Services/PendingAck.swift +++ b/MC1Services/Sources/MC1Services/Services/PendingAck.swift @@ -1,40 +1,139 @@ import Foundation -/// Tracks pending ACKs for a single outgoing direct message across retry attempts. -/// -/// All attempts for the same message share one entry and may add ACK codes. -/// -/// Only DMs are tracked here. `RoomServerService` waits for room post ACKs separately. +/// Tracks a DM's ACK codes across retry attempts. +/// `RoomServerService` waits for Room post ACKs separately. struct PendingAck { struct Owner: Equatable { - enum Phase { - case insert, convert, saved + 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 - var phase: Phase + 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 - var owner: Owner? - /// Set when an acknowledgement matches and kept until the terminal save commits. - var matchedAckCode: UInt32? - var matchedTripTime: UInt32? + 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? var isAwaitingAck: Bool { - !isDelivered && matchedAckCode == nil + 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 { diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift index 74bcce275d..0c0ad680f7 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift @@ -358,6 +358,10 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps sendMessageObserver = observer } + public func setWaitForEventResult(_ event: MeshEvent?) { + stubbedWaitForEventResult = event + } + public func setSendChannelMessageError(_ error: Error?) { stubbedSendChannelMessageError = error } diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift index 2e6f9e3af8..88d176feff 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift @@ -42,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 @@ -57,6 +61,18 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { 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 } @@ -365,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 } @@ -2704,6 +2721,8 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { 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 } @@ -2713,6 +2732,7 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { if let ackCode { message.ackCode = ackCode } if let roundTripTime { message.roundTripTime = roundTripTime } messages[row.messageID] = message + await resolvePendingAcknowledgementCompletionObserver?() return true } 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/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 ed3803b742..00cb154336 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 ) } @@ -660,8 +660,6 @@ struct MessageServiceACKTests { let statusEvents = service.statusEvents() - // Seed a non-delivered pendingAcks entry so finalizeSend's acknowledged-code - // branch is taken. await service.setPendingAckForTest( makePending(messageID: messageID, contactID: contactID, ackCodes: [ackCode]) ) diff --git a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendDMBookkeepingTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendDMBookkeepingTests.swift index a60041dcc0..71dab6e651 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendDMBookkeepingTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendDMBookkeepingTests.swift @@ -186,7 +186,7 @@ struct MessageServiceSendDMBookkeepingTests { 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)?.isDelivered == false) + #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) diff --git a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendTests.swift index c90ad535b5..03c25d0bdb 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessageServiceSendTests.swift @@ -679,7 +679,7 @@ struct MessageServiceSendTests { ackCodes: [ackCode], sentAt: Date(), timeout: 30, - isDelivered: true + resolution: .resolved ) ) @@ -720,7 +720,7 @@ struct MessageServiceSendTests { ackCodes: [ackCode], sentAt: Date(), timeout: 30, - isDelivered: false + resolution: .awaitingAck ) ) From 443332ca4953e3424c2948262af932149c428768 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Sat, 7 Nov 2026 16:58:01 -0800 Subject: [PATCH 21/66] fix: bind node config import to its operation - Keep confirmed input and progress with each import. - Prevent old previews and success cleanup from changing new input. --- .../NodeConfigImportState+Application.swift | 10 + .../NodeConfigImportState+Confirmation.swift | 21 ++ .../NodeConfigImportState+Input.swift | 11 + .../NodeConfigImportState+Preview.swift | 11 + .../NodeConfig/NodeConfigImportState.swift | 50 ++++ ...odeConfigImportViewModel+Application.swift | 117 ++++++++++ .../NodeConfigImportViewModel+FileInput.swift | 55 ++--- ...deConfigImportViewModel+Presentation.swift | 144 ++++++++++++ .../NodeConfigImportViewModel+Recovery.swift | 56 ++--- .../NodeConfigImportViewModel.swift | 218 +----------------- .../CanonicalIdentityCallerTests.swift | 6 +- .../NodeConfigImportOperationTests.swift | 198 ++++++++++++++++ .../NodeConfigImportRecoveryTests.swift | 42 +++- .../NodeConfigImportViewModelTests.swift | 34 +-- .../SettingsRefreshPropagationTests.swift | 4 +- ...ioWiFiContractManagerProvenanceTests.swift | 2 +- 16 files changed, 662 insertions(+), 317 deletions(-) create mode 100644 MC1/Views/Settings/NodeConfig/NodeConfigImportState+Application.swift create mode 100644 MC1/Views/Settings/NodeConfig/NodeConfigImportState+Confirmation.swift create mode 100644 MC1/Views/Settings/NodeConfig/NodeConfigImportState+Input.swift create mode 100644 MC1/Views/Settings/NodeConfig/NodeConfigImportState+Preview.swift create mode 100644 MC1/Views/Settings/NodeConfig/NodeConfigImportState.swift create mode 100644 MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+Application.swift create mode 100644 MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+Presentation.swift create mode 100644 MC1Tests/ViewModels/NodeConfigImportOperationTests.swift 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/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 index ce606051d1..630af92af4 100644 --- a/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+FileInput.swift +++ b/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+FileInput.swift @@ -6,9 +6,8 @@ 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 } - parseTask?.cancel() - cancelConfirmation() - isParsing = true + retireInputWork() + state = state.editable errorMessage = nil let taskID = UUID() currentParseID = taskID @@ -37,10 +36,19 @@ extension NodeConfigImportViewModel { _ config: MeshCoreNodeConfig, for taskID: UUID, recovery: IdentityImportRecovery?, source: ImportSource? ) { guard currentParseID == taskID, self.recovery?.receiptID == recovery?.receiptID else { return } - isParsing = false - importedConfig = config - inputReceiptID = recovery?.receiptID - inputSource = source + 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 @@ -52,7 +60,7 @@ extension NodeConfigImportViewModel { private func applyParseFailure(_ error: Error, for taskID: UUID) { guard currentParseID == taskID else { return } - isParsing = false + currentParseID = nil errorMessage = error.userFacingMessage logger.error("Failed to parse config: \(error.localizedDescription)") } @@ -72,14 +80,8 @@ extension NodeConfigImportViewModel { } func handleDismissal() { - parseTask?.cancel() - currentParseID = nil - previewTask?.cancel() - currentPreviewID = nil - isParsing = false - isPreparingConfirmation = false + retireInputWork() showFilePicker = false - cancelConfirmation() guard !isApplying else { return } if let inputReceiptID, connectionManager?.identityImportRecoveries.contains(where: { $0.receiptID == inputReceiptID }) == true { @@ -88,23 +90,22 @@ extension NodeConfigImportViewModel { resetToFileSelection() } + func retireInputWork() { + currentParseID = nil + parseTask?.cancel() + if case .preparing = state { state = state.editable } + previewTask?.cancel() + cancelConfirmation() + } + func resetToFileSelection() { - importedConfig = nil + guard !isApplying else { return } + retireInputWork() + state = .selectingFile 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 - recovery = nil - identityRecoveryComplete = false } } 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 index 9af78dafc1..bb56572fd6 100644 --- a/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+Recovery.swift +++ b/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel+Recovery.swift @@ -8,7 +8,6 @@ extension NodeConfigImportViewModel { if recovery != nil || inputSource != source { resetToFileSelection() } - recovery = nil } @discardableResult @@ -16,16 +15,11 @@ extension NodeConfigImportViewModel { guard !isApplying, let current = connectionManager?.prepareIdentityImportRecovery(receiptID: summary.receiptID) else { return false } - parseTask?.cancel() - currentParseID = nil - previewTask?.cancel() - currentPreviewID = nil - cancelConfirmation() + retireInputWork() if inputReceiptID != current.receiptID { resetToFileSelection() } - recovery = current - identityRecoveryComplete = false + state = .recovery(current, input: state.input) errorMessage = L10n.Settings.ConfigImport.identityOutcomeUnknown(current.sourceName) return true } @@ -33,13 +27,12 @@ extension NodeConfigImportViewModel { func prepareRecoveryConfirmation() { guard let recovery, let manager = connectionManager, let current = manager.prepareIdentityImportRecovery(receiptID: recovery.receiptID) else { return } - guard inputReceiptID == current.receiptID, validatedRecoveryKey != nil else { + guard inputReceiptID == current.receiptID, let input = state.input, let key = validatedRecoveryKey else { errorMessage = L10n.Settings.ConfigImport.identityRecoveryKeyRequired showFilePicker = true return } - self.recovery = current - confirmation = .recovery(current, inputID: inputID) + state = .confirming(.recovery(current, input: input, privateKey: key)) showConfirmation = true } @@ -49,30 +42,29 @@ extension NodeConfigImportViewModel { return key } - func applyIdentityRecovery(_ summary: IdentityImportRecovery, selectedInputID: UUID) { - guard inputID == selectedInputID, inputReceiptID == summary.receiptID, - recovery?.receiptID == summary.receiptID, let manager = connectionManager, - manager.prepareIdentityImportRecovery(receiptID: summary.receiptID) == summary, - let key = validatedRecoveryKey else { return } - isApplying = true + 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 - identityRecoveryComplete = false - importComplete = false importTask = Task { do { - let result = try await manager.retryIdentityImport(confirmation: summary, privateKey: key) - guard inputID == selectedInputID, recovery?.receiptID == summary.receiptID else { return } - isApplying = false + 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) { - identityRecoveryComplete = true - } else if manager.identityImportRecoveries.contains(where: { $0.receiptID == summary.receiptID }) { - errorMessage = L10n.Settings.ConfigImport.identityOutcomeUnknown(summary.sourceName) + 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 inputID == selectedInputID, recovery?.receiptID == summary.receiptID else { return } - isApplying = false + guard case let .applying(current) = state, current.id == application.id else { return } + state = .failed(current) if let interrupted = error as? IdentityImportRecoveryRequired { - retainInterruptedInput(interrupted.recovery, selectedInputID: selectedInputID) + retainInterruptedInput(interrupted.recovery, application: current) } else if error is CancellationError { errorMessage = L10n.Settings.ConfigImport.identityOutcomeUnknown(summary.sourceName) } else { @@ -82,11 +74,9 @@ extension NodeConfigImportViewModel { } } - func retainInterruptedInput(_ summary: IdentityImportRecovery, selectedInputID: UUID) { - guard inputID == selectedInputID else { return } - inputReceiptID = summary.receiptID - recovery = summary - importComplete = false + 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 7cc83f372a..a56a551ca1 100644 --- a/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel.swift +++ b/MC1/Views/Settings/NodeConfig/NodeConfigImportViewModel.swift @@ -22,47 +22,19 @@ final class NodeConfigImportViewModel { } } - enum Confirmation { - case config(ImportSource, inputID: UUID, sections: ConfigSections) - case recovery(IdentityImportRecovery, inputID: UUID) - } - - var importedConfig: MeshCoreNodeConfig? { - didSet { - inputID = UUID() - inputSource = nil - inputReceiptID = nil - cancelConfirmation() - } - } - + var state: NodeConfigImportState = .selectingFile var errorMessage: String? var showFilePicker = false - var isParsing = false + // Alert dismissal can precede its action; apply and cancel consume the confirmation payload. + var showConfirmation = false var sections = ConfigSections() var currentName: String? var currentRadio: MeshCoreNodeConfig.RadioSettings? var currentPosition: MeshCoreNodeConfig.PositionSettings? - var isApplying = false - var applyProgress: Double = 0 - var applyStepDescription = "" - var importComplete = false - var showConfirmation = false - var isPreparingConfirmation = false - var recovery: IdentityImportRecovery? - var identityRecoveryComplete = false - - var channelsWouldOverwrite = false - var didApplyAnyWrite = false var importTask: Task? var parseTask: Task? var currentParseID: UUID? var previewTask: Task? - var currentPreviewID: UUID? - var inputID = UUID() - var inputSource: ImportSource? - var inputReceiptID: UUID? - var confirmation: Confirmation? var connectionManager: ConnectionManager? let logger = Logger(subsystem: "com.mc1", category: "NodeConfigImportVM") @@ -92,188 +64,4 @@ final class NodeConfigImportViewModel { connectedDeviceProvider = connectedDevice self.connectionManager = connectionManager } - - 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 { - 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(source, _, _) = confirmation else { return "" } - switch (hasOverwriteSections, hasAdditiveSections) { - case (false, true): return L10n.Settings.ConfigImport.confirmMessageAdd(source.name) - case (true, false): return L10n.Settings.ConfigImport.confirmMessageOverwrite(source.name) - case (true, true): return L10n.Settings.ConfigImport.confirmMessageMixed(source.name) - default: return L10n.Settings.ConfigImport.confirmMessage(source.name) - } - } - - func prepareConfirmation() { - guard !isPreparingConfirmation, !isApplying, !isParsing else { return } - if recovery != nil { - prepareRecoveryConfirmation() - return - } - guard let config = importedConfig, let service = nodeConfigService, - let snapshot = connectionManager?.currentConnection, - connectedDevice?.id == snapshot.device.id else { return } - let source = ImportSource(snapshot) - guard inputSource == nil || inputSource == source else { return } - inputSource = source - let selectedInputID = inputID - let selectedSections = sections - let previewID = UUID() - currentPreviewID = previewID - errorMessage = nil - isPreparingConfirmation = true - previewTask = Task { - defer { - if currentPreviewID == previewID { isPreparingConfirmation = false } - } - do { - let preview = try await service.previewImport(config, sections: selectedSections) - guard !Task.isCancelled, currentPreviewID == previewID, inputID == selectedInputID, - connectionManager?.isCurrent(generation: source.generation, requestID: source.requestID) == true else { return } - channelsWouldOverwrite = preview.channelsOverwriteExisting - confirmation = .config(source, inputID: selectedInputID, sections: selectedSections) - showConfirmation = true - } catch is CancellationError { - return - } catch { - guard currentPreviewID == previewID else { return } - errorMessage = error.userFacingMessage - logger.error("Import preview failed: \(error.localizedDescription)") - } - } - } - - func cancelConfirmation() { - confirmation = nil - showConfirmation = false - } - - func applyConfig() { - guard !isApplying, let confirmation else { return } - cancelConfirmation() - switch confirmation { - case let .recovery(summary, selectedInputID): - applyIdentityRecovery(summary, selectedInputID: selectedInputID) - case let .config(source, selectedInputID, selectedSections): - guard inputID == selectedInputID, sections == selectedSections, - connectionManager?.isCurrent(generation: source.generation, requestID: source.requestID) == true, - let config = importedConfig, let service = nodeConfigService else { return } - applyConfiguration(config, service: service, source: source, selectedSections: selectedSections) - } - } - - private func applyConfiguration( - _ config: MeshCoreNodeConfig, service: NodeConfigService, source: ImportSource, selectedSections: ConfigSections - ) { - isApplying = true - applyProgress = 0 - errorMessage = nil - importComplete = false - didApplyAnyWrite = false - let selectedInputID = inputID - importTask = Task { - 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: selectedSections, radioID: source.radioID) { - progressContinuation.yield($0) - } - progressContinuation.finish() - await consumer.value - if connectedDevice?.id == source.deviceID, let settingsService { - try? await settingsService.refreshDeviceInfo() - } - isApplying = false - importComplete = true - try? await Task.sleep(for: Timing.resultDisplay) - guard !Task.isCancelled, inputID == selectedInputID else { return } - resetToFileSelection() - } catch { - progressContinuation.finish() - await consumer.value - isApplying = false - if let interrupted = error as? IdentityImportRecoveryRequired { - retainInterruptedInput(interrupted.recovery, selectedInputID: selectedInputID) - } 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) - } - - 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/MC1Tests/AppState/CanonicalIdentityCallerTests.swift b/MC1Tests/AppState/CanonicalIdentityCallerTests.swift index 111eabb39b..92d045313d 100644 --- a/MC1Tests/AppState/CanonicalIdentityCallerTests.swift +++ b/MC1Tests/AppState/CanonicalIdentityCallerTests.swift @@ -25,7 +25,7 @@ struct CanonicalIdentityCallerTests { privateKey: "7065e18fd9fabb70c1ed90dca19907de698c88b709ea146eafd93d9b830c7b60" + "c4681193c79bbc39945ba8064104bb618f8fd7a84a0af6f57033d6e8ddcd6471" ) - model.importedConfig = config + model.acceptInput(config, source: nil) model.sections = ConfigSections(nodeIdentity: true) model.prepareConfirmation() try await waitUntil { model.showConfirmation || model.errorMessage != nil } @@ -93,13 +93,13 @@ struct CanonicalIdentityCallerTests { _ = 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.importedConfig = MeshCoreNodeConfig( + 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 } 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 index aab4b02c80..349e4da072 100644 --- a/MC1Tests/ViewModels/NodeConfigImportRecoveryTests.swift +++ b/MC1Tests/ViewModels/NodeConfigImportRecoveryTests.swift @@ -55,9 +55,9 @@ struct NodeConfigImportRecoveryTests { #expect(model.recovery == nil) model.beginImport() - model.importedConfig = MeshCoreNodeConfig( + 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 } @@ -134,6 +134,40 @@ struct NodeConfigImportRecoveryTests { } } + @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 @@ -215,10 +249,10 @@ struct NodeConfigImportRecoveryTests { let model = NodeConfigImportViewModel() configure(model, environment: env) do { - model.importedConfig = MeshCoreNodeConfig( + 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 } diff --git a/MC1Tests/ViewModels/NodeConfigImportViewModelTests.swift b/MC1Tests/ViewModels/NodeConfigImportViewModelTests.swift index 7aae431fab..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" }) @@ -144,7 +114,7 @@ struct NodeConfigImportViewModelTests { return nil } let viewModel = NodeConfigImportViewModel() - viewModel.importedConfig = MeshCoreNodeConfig( + viewModel.acceptInput(MeshCoreNodeConfig( privateKey: String(repeating: "ab", count: 64), radioSettings: .init( frequency: eu.frequencyKHz, @@ -153,7 +123,7 @@ struct NodeConfigImportViewModelTests { codingRate: eu.codingRate, txPower: Device.Defaults.txPower ) - ) + ), source: nil) viewModel.sections.nodeIdentity = true viewModel.sections.radioSettings = true diff --git a/MC1Tests/ViewModels/SettingsRefreshPropagationTests.swift b/MC1Tests/ViewModels/SettingsRefreshPropagationTests.swift index 214a8675a2..3a48550577 100644 --- a/MC1Tests/ViewModels/SettingsRefreshPropagationTests.swift +++ b/MC1Tests/ViewModels/SettingsRefreshPropagationTests.swift @@ -240,13 +240,13 @@ struct SettingsRefreshPropagationTests { await radio.setIdentityImportPublicKey(importedKey) await env.appState.wireServicesIfConnected() let source = try #require(env.manager.currentConnection) - viewModel.importedConfig = MeshCoreNodeConfig( + 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 }, diff --git a/MC1Tests/Views/Settings/RadioWiFiContractManagerProvenanceTests.swift b/MC1Tests/Views/Settings/RadioWiFiContractManagerProvenanceTests.swift index 117280042b..08ad342a88 100644 --- a/MC1Tests/Views/Settings/RadioWiFiContractManagerProvenanceTests.swift +++ b/MC1Tests/Views/Settings/RadioWiFiContractManagerProvenanceTests.swift @@ -83,7 +83,7 @@ struct RadioWiFiContractManagerProvenanceTests { } try await env.manager.persistenceStore.saveDevice(ghost) await env.bluetooth.setPublicKey(Self.canonicalKey, for: env.device.id) - importer.importedConfig = MeshCoreNodeConfig(privateKey: Self.privateKey) + importer.acceptInput(MeshCoreNodeConfig(privateKey: Self.privateKey), source: nil) importer.sections = ConfigSections(nodeIdentity: true, channels: false, contacts: false) importer.prepareConfirmation() try await waitUntil("the real identity import caller presents confirmation") { From 9f0069c7320adedf5eb835476dff2bd53fdbc254 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Sat, 7 Nov 2026 17:44:15 -0800 Subject: [PATCH 22/66] refactor: make sync claim ownership explicit - Replace paired guard flags with a typed claim to prevent inconsistent states. - Keep manual refresh inhibition independent of full sync. - Share gated contact fixtures and combine overlapping tests. --- .../Services/AdvertisementService.swift | 2 +- .../MC1Services/Services/ContactService.swift | 21 +- .../Sources/MC1Services/Sync/SyncClaim.swift | 4 + .../Sync/SyncCoordinator+Claims.swift | 110 +++++++++ .../Sync/SyncCoordinator+Sync.swift | 214 +++--------------- .../MC1Services/Sync/SyncCoordinator.swift | 17 +- .../Helpers/GatedContactService.swift | 32 +++ .../Services/ContactServiceSyncTests.swift | 37 +-- .../SyncCoordinatorClaimTests.swift | 129 +++++++++++ .../SyncCoordinatorTests.swift | 153 +------------ 10 files changed, 320 insertions(+), 399 deletions(-) create mode 100644 MC1Services/Sources/MC1Services/Sync/SyncClaim.swift create mode 100644 MC1Services/Sources/MC1Services/Sync/SyncCoordinator+Claims.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Helpers/GatedContactService.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/SyncCoordinatorClaimTests.swift diff --git a/MC1Services/Sources/MC1Services/Services/AdvertisementService.swift b/MC1Services/Sources/MC1Services/Services/AdvertisementService.swift index f68aefa8ea..5ec3d88933 100644 --- a/MC1Services/Sources/MC1Services/Services/AdvertisementService.swift +++ b/MC1Services/Sources/MC1Services/Services/AdvertisementService.swift @@ -64,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. 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/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+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 a48c5e9f76..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. 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/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/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/SyncCoordinatorTests.swift b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorTests.swift index 0df020b756..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 @@ -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 From c3b1491c265ee7947bf86b3cf912cee7f49899eb Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Sat, 7 Nov 2026 18:33:33 -0800 Subject: [PATCH 23/66] refactor: model remote cli slot ownership - Keep each destination's queue and active request under one owner. - Preserve FIFO order across retries and reject work after retirement. --- .../MC1Services/Services/RemoteCLISlot.swift | 91 +++++++ .../Services/RemoteNodeService+CLI.swift | 199 ++------------ .../RemoteNodeService+CLIExchange.swift | 171 ++++++++++++ .../Services/RemoteNodeService.swift | 87 +------ .../Mocks/MockMeshCoreSession.swift | 9 +- .../RemoteNodeCLICancellationTests.swift | 2 +- .../RemoteNodeCLICorrelationTests.swift | 32 --- .../RemoteNodeCLILifecycleTests.swift | 246 ++++++++++++++++++ .../Services/RemoteNodeSensorTests.swift | 2 +- 9 files changed, 547 insertions(+), 292 deletions(-) create mode 100644 MC1Services/Sources/MC1Services/Services/RemoteCLISlot.swift create mode 100644 MC1Services/Sources/MC1Services/Services/RemoteNodeService+CLIExchange.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeCLILifecycleTests.swift 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/RemoteNodeService+CLI.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService+CLI.swift index 90987d20b0..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, @@ -74,22 +60,22 @@ extension RemoteNodeService { : 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: 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( @@ -106,7 +92,7 @@ extension RemoteNodeService { return try await performCLIExchange( publicKey: remoteSession.publicKey, destinationPrefix: destinationPrefix, command: command, acceptsAnyResponse: true, timeout: timeout, - requestID: requestID, textType: .cliData + ownerID: ownerID, textType: .cliData ) } @@ -118,7 +104,7 @@ extension RemoteNodeService { command: command, acceptsAnyResponse: acceptsAnyResponse, timeout: timeout, - requestID: requestID, + ownerID: ownerID, textType: .cliData ) } @@ -134,7 +120,7 @@ extension RemoteNodeService { command: command, acceptsAnyResponse: acceptsAnyResponse, timeout: timeout, - requestID: requestID, + ownerID: ownerID, textType: .cliData ) } @@ -142,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( @@ -161,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.swift b/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift index d6b9acdac2..df02eb80ef 100644 --- a/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift +++ b/MC1Services/Sources/MC1Services/Services/RemoteNodeService.swift @@ -31,41 +31,13 @@ public actor RemoteNodeService { var loginAttempts: [Data: RemoteLoginAttempt] = [:] var sensorConnectAttempts: [UUID: UUID] = [:] - /// 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? - } - - /// 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] = [] @@ -230,43 +202,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 } @@ -285,11 +220,6 @@ public actor RemoteNodeService { attempt.claimCompletion()?.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()) - } - // MARK: - Session Management /// Create a new session for a remote node. @@ -411,13 +341,10 @@ public actor RemoteNodeService { isRetired = true sensorConnectAttempts.removeAll() stopAllKeepAlives() - for (prefix, pending) in pendingCLIRequests { - cancelPendingCLIRequest(for: prefix, requestID: pending.id) - } - let waiters = cliSlotWaiters.values.flatMap(\.self) - cliSlotWaiters.removeAll() - for waiter in waiters { - waiter.continuation.resume(throwing: CancellationError()) + let slots = cliSlots.values + cliSlots.removeAll() + for var slot in slots { + slot.cancelAll() } } diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift index 0c0ad680f7..e543648be1 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMeshCoreSession.swift @@ -224,11 +224,16 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps 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")) @@ -864,7 +869,9 @@ 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 } 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/RemoteNodeSensorTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeSensorTests.swift index 546534db9c..e79c2c8134 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeSensorTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/RemoteNodeSensorTests.swift @@ -216,7 +216,7 @@ extension RemoteNodeSensorTests { 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.cliSlotWaiters.isEmpty } + 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") From b498ff06cd21b14ce14fdc31ec49bb40dba24f2f Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Sat, 7 Nov 2026 20:10:26 -0800 Subject: [PATCH 24/66] refactor: centralize chat open anchor state - Keep Populate completion and Anchor consumption in ChatOpenAnchorState so completion cannot replay the Anchor. - Derive divider readiness from the current Bake to avoid positioning on cached rows from a previous open. --- .../ChatConversationMessagesContent.swift | 2 +- .../Components/ChatInitialScrollPolicy.swift | 36 ----- .../Chats/Timeline/ChatOpenAnchorState.swift | 56 +++++++ .../Chats/Timeline/ChatTimeline+Paging.swift | 40 ++--- MC1/Views/Chats/Timeline/ChatTimeline.swift | 101 ++++--------- .../Chats/ChatOpenAnchorStateTests.swift | 81 ++++++++++ .../ChatOpenAtDividerCompositionTests.swift | 140 +++--------------- .../Chats/ChatReconnectPopulateTests.swift | 4 +- ...ChatTimelineOpeningCancellationTests.swift | 91 +++++++++++- .../ChatInitialScrollPolicyTests.swift | 89 ----------- .../ChatNativeSplitLayoutTests.swift | 2 +- 11 files changed, 293 insertions(+), 349 deletions(-) delete mode 100644 MC1/Views/Chats/Components/ChatInitialScrollPolicy.swift create mode 100644 MC1/Views/Chats/Timeline/ChatOpenAnchorState.swift create mode 100644 MC1Tests/Views/Chats/ChatOpenAnchorStateTests.swift delete mode 100644 MC1Tests/Views/Chats/Components/ChatInitialScrollPolicyTests.swift diff --git a/MC1/Views/Chats/ChatConversationMessagesContent.swift b/MC1/Views/Chats/ChatConversationMessagesContent.swift index f421d412d2..8882912c69 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. 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/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..85cdee7f56 100644 --- a/MC1/Views/Chats/Timeline/ChatTimeline+Paging.swift +++ b/MC1/Views/Chats/Timeline/ChatTimeline+Paging.swift @@ -4,9 +4,8 @@ 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?, @@ -14,24 +13,20 @@ extension ChatTimeline { ) 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 - defer { - if shouldSettleInitialLoad { initialLoadSettled = true } - } - 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 { + var outcome = ChatTimelinePopulator.Outcome.unavailable + defer { completePopulate(outcome) } + guard let writer 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,13 +36,12 @@ 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. + // 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 @@ -67,13 +61,9 @@ extension ChatTimeline { ) } } 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/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/ChatReconnectPopulateTests.swift b/MC1Tests/Views/Chats/ChatReconnectPopulateTests.swift index 8e9d4e7210..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 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/Components/ChatInitialScrollPolicyTests.swift b/MC1Tests/Views/Chats/Components/ChatInitialScrollPolicyTests.swift deleted file mode 100644 index 0a45086f49..0000000000 --- a/MC1Tests/Views/Chats/Components/ChatInitialScrollPolicyTests.swift +++ /dev/null @@ -1,89 +0,0 @@ -import Foundation -@testable import MC1 -import Testing - -/// Covers the pure first-snapshot decision table: divider-row-on-screen -/// gating, the consume-once latch, and the settled-load escape hatch. -@Suite("ChatInitialScrollPolicy") -struct ChatInitialScrollPolicyTests { - @Test - func `divider target presents when its baked row is on screen`() { - let divider = UUID() - #expect(ChatInitialScrollPolicy.firstSnapshotDecision( - hasConsumed: false, - unreadCount: 3, - initialLoadSettled: true, - dividerMessageID: divider, - dividerRowOnScreen: true - ) == .present(target: divider)) - } - - @Test - func `an unresolved divider target withholds, even after the load settles`() { - #expect(ChatInitialScrollPolicy.firstSnapshotDecision( - hasConsumed: false, - unreadCount: 3, - initialLoadSettled: true, - dividerMessageID: UUID(), - dividerRowOnScreen: false - ) == .withhold) - } - - @Test - func `a resolved divider target whose item lacks the divider row withholds`() { - let divider = UUID() - #expect(ChatInitialScrollPolicy.firstSnapshotDecision( - hasConsumed: false, - unreadCount: 3, - initialLoadSettled: true, - dividerMessageID: divider, - dividerRowOnScreen: false - ) == .withhold) - } - - @Test - func `no divider target withholds until the load settles`() { - #expect(ChatInitialScrollPolicy.firstSnapshotDecision( - hasConsumed: false, - unreadCount: 3, - initialLoadSettled: false, - dividerMessageID: nil, - dividerRowOnScreen: false - ) == .withhold) - } - - @Test - func `a settled load with no divider target presents at the bottom`() { - #expect(ChatInitialScrollPolicy.firstSnapshotDecision( - hasConsumed: false, - unreadCount: 3, - initialLoadSettled: true, - dividerMessageID: nil, - dividerRowOnScreen: false - ) == .present(target: nil)) - } - - @Test - func `the target is retired once consumed`() { - let divider = UUID() - #expect(ChatInitialScrollPolicy.firstSnapshotDecision( - hasConsumed: true, - unreadCount: 3, - initialLoadSettled: true, - dividerMessageID: divider, - dividerRowOnScreen: true - ) == .present(target: nil)) - } - - @Test - func `no unread backlog presents immediately with no target`() { - let divider = UUID() - #expect(ChatInitialScrollPolicy.firstSnapshotDecision( - hasConsumed: false, - unreadCount: 0, - initialLoadSettled: false, - dividerMessageID: divider, - dividerRowOnScreen: true - ) == .present(target: nil)) - } -} diff --git a/MC1Tests/Views/Chats/Components/ChatNativeSplitLayoutTests.swift b/MC1Tests/Views/Chats/Components/ChatNativeSplitLayoutTests.swift index ebd1463c6f..72252e3027 100644 --- a/MC1Tests/Views/Chats/Components/ChatNativeSplitLayoutTests.swift +++ b/MC1Tests/Views/Chats/Components/ChatNativeSplitLayoutTests.swift @@ -867,7 +867,7 @@ private final class ChatNativeSplitHarnessModel { var consumedAnchorCount = 0 var displayEpoch = 0 var timelineItems: [MessageItem] = [] - var firstSnapshotDecision: ChatInitialScrollPolicy.FirstSnapshotDecision = .present(target: nil) + var firstSnapshotDecision: ChatOpenAnchorState.FirstSnapshotDecision = .present(target: nil) var selectedMessageForActions: MessageDTO? var imageViewerData: ImageViewerData? From 4d4f02a7fa25b8d5f9312022aedf9afb3fb62a9d Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:42:11 -0800 Subject: [PATCH 25/66] feat: persist queued reaction sends - Save reaction Messages and PendingSend rows together so reconnects retain queued work. - Persist badges after radio acceptance and keep reaction metadata consistent during deletion and backup. --- MC1/State/MessageEventDispatcher.swift | 2 + .../Chats/Timeline/ChatTimeline+Paging.swift | 17 +- .../ViewModel/ChatTimelinePopulator.swift | 4 +- .../ViewModel/ChatViewModel+EventStream.swift | 58 +++- .../ChatViewModel+MessageActions.swift | 26 +- .../ViewModel/ChatViewModel+Reactions.swift | 154 +-------- .../Sources/MC1Services/Models/Message.swift | 24 +- .../Persistence/MessagePersisting.swift | 14 + .../Services/ChatCoordinator+Mutations.swift | 12 + .../Services/ChatCoordinator+Reload.swift | 1 + .../Services/ChatSendQueueService.swift | 39 +++ .../Services/MessageService+ACKRecovery.swift | 2 + .../Services/MessageService+DMRetry.swift | 5 +- .../Services/MessageService+Reactions.swift | 25 ++ .../Services/MessageService+SendChannel.swift | 70 +++-- .../Services/MessageService+SendDM.swift | 13 +- .../MC1Services/Services/MessageService.swift | 2 + .../Services/MessageStatusEvent.swift | 1 + .../PersistenceStore+Acknowledgements.swift | 4 +- .../PersistenceStore+BackupBatchInsert.swift | 24 +- .../PersistenceStore+BackupHelpers.swift | 13 + .../PersistenceStore+BackupImport.swift | 2 +- .../Services/PersistenceStore+Messages.swift | 56 +++- .../PersistenceStore+OutgoingReactions.swift | 143 +++++++++ .../PersistenceStore+PendingSends.swift | 7 +- .../Services/PersistenceStore.swift | 1 + ...rationTests+OutgoingReactionMetadata.swift | 63 ++++ .../BackupIntegrationTests.swift | 121 ++++++++ .../OutgoingReactionPersistenceTests.swift | 235 ++++++++++++++ .../ChatSendQueueReactionRecoveryTests.swift | 113 +++++++ .../Services/ChatSendQueueReactionTests.swift | 265 ++++++++++++++++ .../State/ChatTimelineFreshnessTests.swift | 6 +- .../ChatViewModelReactionDeleteTests.swift | 135 ++++++++ ...atViewModelReactionFailureOrderTests.swift | 255 +++++++++++++++ .../ChatViewModelReactionSendTests.swift | 292 ++++++++++++++++++ 35 files changed, 1994 insertions(+), 210 deletions(-) create mode 100644 MC1Services/Sources/MC1Services/Services/MessageService+Reactions.swift create mode 100644 MC1Services/Sources/MC1Services/Services/PersistenceStore+OutgoingReactions.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests+OutgoingReactionMetadata.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/OutgoingReactionPersistenceTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueReactionRecoveryTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueReactionTests.swift create mode 100644 MC1Tests/Views/Chats/ChatViewModelReactionDeleteTests.swift create mode 100644 MC1Tests/Views/Chats/ChatViewModelReactionFailureOrderTests.swift create mode 100644 MC1Tests/Views/Chats/ChatViewModelReactionSendTests.swift diff --git a/MC1/State/MessageEventDispatcher.swift b/MC1/State/MessageEventDispatcher.swift index 2981f17ea4..bcc37cedc5 100644 --- a/MC1/State/MessageEventDispatcher.swift +++ b/MC1/State/MessageEventDispatcher.swift @@ -175,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/Views/Chats/Timeline/ChatTimeline+Paging.swift b/MC1/Views/Chats/Timeline/ChatTimeline+Paging.swift index 85cdee7f56..2635853c10 100644 --- a/MC1/Views/Chats/Timeline/ChatTimeline+Paging.swift +++ b/MC1/Views/Chats/Timeline/ChatTimeline+Paging.swift @@ -9,13 +9,17 @@ extension ChatTimeline { 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 + let boundWriter = writer var outcome = ChatTimelinePopulator.Outcome.unavailable - defer { completePopulate(outcome) } - guard let writer else { return outcome } + defer { + if self.writer === boundWriter { completePopulate(outcome) } + } + 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 { @@ -40,14 +44,14 @@ extension ChatTimeline { do { outcome = try await writer.performWindowOperation { try Task.checkCancellation() + 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, @@ -57,7 +61,8 @@ extension ChatTimeline { envInputs: envInputs, senderTables: senderTablesProvider, postApply: postApply, - anchorSortDate: anchorSortDate + anchorSortDate: anchorSortDate, + isCurrent: { self.writer === writer && self.coordinator === coordinator && writer.isCurrent } ) } } catch is CancellationError { diff --git a/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift b/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift index 2035dbfd61..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 diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift index 390df9b75c..e37cf7398d 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+EventStream.swift @@ -50,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, _): @@ -77,25 +77,59 @@ 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 local 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) 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 d2b9d83d9c..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 @@ -28,7 +30,10 @@ extension ChatViewModel { 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 { @@ -88,7 +93,10 @@ extension ChatViewModel { 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 } 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/MC1Services/Sources/MC1Services/Models/Message.swift b/MC1Services/Sources/MC1Services/Models/Message.swift index e1df8f899e..e2b366f6bd 100644 --- a/MC1Services/Sources/MC1Services/Models/Message.swift +++ b/MC1Services/Sources/MC1Services/Models/Message.swift @@ -33,6 +33,7 @@ public final class Message { [\.radioID, \.channelIndex, \.containsSelfMention, \.mentionSeen], [\.radioID, \.senderKeyPrefix, \.senderTimestamp], [\.radioID, \.senderKeyPrefix, \.timestamp], + [\.reactionTargetMessageID], [\.deduplicationKey] ) @@ -153,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 @@ -206,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] = [] @@ -246,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 @@ -293,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 @@ -380,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. @@ -396,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 } @@ -439,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. @@ -491,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 @@ -535,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] = [] @@ -575,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 diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift index 2957e47766..25c59778f7 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift @@ -39,6 +39,12 @@ 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 @@ -225,6 +231,14 @@ extension MessagePersisting { } 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) 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/ChatSendQueueService.swift b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift index 639484f5ae..78d48af32e 100644 --- a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift +++ b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift @@ -447,6 +447,45 @@ public final class ChatSendQueueService { 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 diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift b/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift index d029634d9f..7900c53815 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+ACKRecovery.swift @@ -106,6 +106,7 @@ extension MessageService { func retryPendingAcknowledgementSaves() async { for messageID in pendingAcks.keys { if await saveAcknowledgementOwner(messageID: messageID) { + await notifyOutgoingReactionAccepted(messageID: messageID) statusEventBroadcaster.yield(.statusResolved(messageID: messageID, status: .sent, roundTripTime: nil)) } } @@ -154,6 +155,7 @@ extension MessageService { 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)) diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+DMRetry.swift b/MC1Services/Sources/MC1Services/Services/MessageService+DMRetry.swift index ab17fa17f4..370d86bf98 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+DMRetry.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+DMRetry.swift @@ -14,7 +14,8 @@ extension MessageService { timestamp: UInt32, timeout: TimeInterval?, budget: DMSendBudget, - sendLease: PlainTextSendGate.Lease? + sendLease: PlainTextSendGate.Lease?, + waitForAcknowledgement: Bool ) async throws -> Data? { let maxRetryAttempts = budget.totalAttempts - 1 let sendDate = Date(timeIntervalSince1970: TimeInterval(timestamp)) @@ -130,6 +131,8 @@ extension MessageService { messageID: messageID, sentInfo: sentInfo, predictedAck: predictedAck, timeout: ackTimeout ) + if !waitForAcknowledgement { return nil } + let ackEvent = await session.waitForEvent( filter: .acknowledgement(code: sentInfo.expectedAck), timeout: ackTimeout 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 908ddd8102..105b78bbb8 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift @@ -158,17 +158,32 @@ 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)), - expectedChannelSecret: expectedChannelSecret - ) + 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)), + expectedChannelSecret: expectedChannelSecret + ) + } + 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) } @@ -241,18 +256,35 @@ public extension MessageService { if !preserveTimestamp { try await dataStore.updateMessageTimestamp(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, - expectedChannelSecret: expectedChannelSecret - ) + 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, + expectedChannelSecret: expectedChannelSecret + ) + } + 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) } @@ -299,7 +331,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 fc415405c3..032f848fc4 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift @@ -192,7 +192,8 @@ public extension MessageService { timestamp: timestamp, timeout: timeout > 0 ? timeout : nil, budget: dmSendBudgetProvider(), - sendLease: sendLease + sendLease: sendLease, + waitForAcknowledgement: true ) return try await finalizeSend( @@ -345,8 +346,9 @@ public extension MessageService { text: existingMessage.text, timestamp: wireTimestamp, timeout: nil, - budget: isSingleAttempt ? .singleAttempt : dmSendBudgetProvider(), - sendLease: sendLease + budget: isSingleAttempt || existingMessage.reactionTargetMessageID != nil ? .singleAttempt : dmSendBudgetProvider(), + sendLease: sendLease, + waitForAcknowledgement: existingMessage.reactionTargetMessageID == nil ) // Bump only on a confirmed successful resend so sendCount counts @@ -470,7 +472,7 @@ public extension MessageService { } } - private func validateDirectMessage(text: String, to contact: ContactDTO) throws { + 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 } } @@ -514,6 +516,9 @@ public 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.swift b/MC1Services/Sources/MC1Services/Services/MessageService.swift index d7f8e77ed0..dffa48ca4a 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService.swift @@ -111,6 +111,8 @@ public actor MessageService { /// 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 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/PersistenceStore+Acknowledgements.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Acknowledgements.swift index 5abf311de9..154e4524b1 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Acknowledgements.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Acknowledgements.swift @@ -37,6 +37,7 @@ public extension PersistenceStore { row.ackDeadline = dto.ackDeadline message.status = .sent do { + _ = try stageOutgoingReaction(message) #if DEBUG try savePendingAcknowledgementFaultInjection?() #endif @@ -66,8 +67,9 @@ public extension PersistenceStore { if let ackCode { message.ackCode = ackCode } if let roundTripTime { message.roundTripTime = roundTripTime } } - if row.ackDeadline != nil { modelContext.delete(row) } do { + if let message { _ = try stageOutgoingReaction(message) } + if row.ackDeadline != nil { modelContext.delete(row) } try modelContext.save() } catch { modelContext.rollback() diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift index 41452567c8..93b344946d 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift @@ -307,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)] ) { @@ -317,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, @@ -334,6 +335,8 @@ extension PersistenceStore { } if dto.direction == .incoming { skippedIncomingParents.append((localMessageID: winning ?? dto.id, dto: dto)) + } else { + skippedOutgoingMessages.append(dto) } skipped += 1 continue @@ -355,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 ) diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupHelpers.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupHelpers.swift index 010ca0b8b3..24e28d94b1 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupHelpers.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupHelpers.swift @@ -183,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 7fbd4a33b9..8328458574 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupImport.swift @@ -267,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 }) diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift index c4357799e9..0424f7bb6e 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift @@ -409,6 +409,7 @@ public extension PersistenceStore { /// Update message status func updateMessageStatus(id: UUID, status: MessageStatus) throws { + try commitPendingRxLogEntries() let targetID = id let predicate = #Predicate { message in message.id == targetID @@ -421,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 + } } } @@ -448,6 +458,7 @@ public extension PersistenceStore { } message.status = status do { + _ = try stageOutgoingReaction(message) try modelContext.save() } catch { modelContext.rollback() @@ -464,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 @@ -477,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 } @@ -549,6 +567,7 @@ public extension PersistenceStore { message.status = status message.roundTripTime = roundTripTime do { + _ = try stageOutgoingReaction(message) try modelContext.save() } catch { modelContext.rollback() @@ -630,7 +649,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: @@ -658,8 +687,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. @@ -678,6 +709,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 @@ -944,6 +976,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) @@ -958,15 +1002,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 aeb6534445..05a7f45be9 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+PendingSends.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+PendingSends.swift @@ -60,6 +60,12 @@ public extension PersistenceStore { #if DEBUG 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 @@ -75,7 +81,6 @@ public extension PersistenceStore { let inserted = PendingSend(dto: dto) inserted.sequence = assignedSequence modelContext.insert(inserted) - try modelContext.save() return assignedSequence } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift index 55e0f18cfe..2d511ee364 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore.swift @@ -141,6 +141,7 @@ public actor PersistenceStore: ModelActor, PersistenceStoreProtocol { } var updateContactLastMessageFaultInjection: (@Sendable () throws -> Void)? + var updateMessageStatusFaultInjection: (@Sendable (UUID, MessageStatus) throws -> Void)? var savePendingAcknowledgementFaultInjection: (@Sendable () throws -> Void)? func setDeleteContactsFaultInjection(_ hook: (@Sendable () throws -> Void)?) { 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.swift b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift index 47a5c92fff..30f23455bb 100644 --- a/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift @@ -4509,6 +4509,8 @@ struct BackupIntegrationTests { timestampCorrected: true, senderTimestamp: 1_699_999_999, reactionSummary: "👍:3,❤️:2", + reactionTargetMessageID: UUID(), + reactionSenderName: "Nate", routeType: .tcDirect, regionScope: "Germany" ) @@ -4554,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 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/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..a3c62513b6 --- /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 `a reassigned channel slot rejects the reaction without a badge`() 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 == .failed) + #expect(try await env.manager.persistenceStore.fetchReactions(for: target.id).isEmpty) + #expect(try await !env.manager.persistenceStore.hasPendingSend(messageID: outgoing.id)) + #expect(await sendCount(env, command: .sendChannelMessage) == 0) + } 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/MC1Tests/State/ChatTimelineFreshnessTests.swift b/MC1Tests/State/ChatTimelineFreshnessTests.swift index a2c57d6ff8..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") 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..