@mentra/bluetooth-sdk 3.3.0 → 3.4.0-beta.1237

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/MIGRATION.md +61 -0
  2. package/README.md +80 -11
  3. package/android/build.gradle +60 -51
  4. package/android/gradle.properties +3 -0
  5. package/android/settings.gradle +47 -3
  6. package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -2
  8. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +85 -6
  9. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +35 -1
  10. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +154 -110
  11. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceStore.kt +21 -0
  12. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +1 -0
  13. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  14. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +27 -2
  15. package/android/src/main/java/com/mentra/bluetoothsdk/connection/ConnectionModels.kt +5 -0
  16. package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
  17. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicy.kt +64 -0
  18. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +925 -155
  19. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +227 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisement.kt +19 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicy.kt +94 -0
  22. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachine.kt +411 -0
  23. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateStore.kt +124 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +54 -59
  25. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +5 -32
  26. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasEncoder.kt +8 -1
  27. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +3 -10
  28. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
  29. package/android/src/main/java/com/mentra/bluetoothsdk/status/DeviceStatus.kt +50 -0
  30. package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
  31. package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
  32. package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
  33. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
  34. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
  35. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
  36. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
  37. package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
  38. package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
  39. package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
  40. package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
  41. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
  42. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
  43. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
  44. package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
  45. package/android/src/test/java/com/mentra/bluetoothsdk/DeviceManagerOwnerLossTest.kt +146 -0
  46. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusAudioSetupTest.kt +51 -0
  47. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusClassicAudioTest.kt +2 -0
  48. package/android/src/test/java/com/mentra/bluetoothsdk/WifiAdbPeerIntentTest.kt +19 -0
  49. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicyTest.kt +65 -0
  50. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveAudioSetupReadinessTest.kt +231 -0
  51. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +5 -1
  52. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
  53. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +368 -0
  54. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisementParserTest.kt +20 -0
  55. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicyTest.kt +136 -0
  56. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachineTest.kt +346 -0
  57. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
  58. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
  59. package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
  60. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
  61. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
  62. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
  63. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
  64. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
  65. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
  66. package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
  67. package/build/BluetoothSdk.types.d.ts +201 -1
  68. package/build/BluetoothSdk.types.d.ts.map +1 -1
  69. package/build/BluetoothSdk.types.js.map +1 -1
  70. package/build/_private/BluetoothSdkModule.d.ts +43 -5
  71. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  72. package/build/_private/BluetoothSdkModule.js +2 -0
  73. package/build/_private/BluetoothSdkModule.js.map +1 -1
  74. package/build/generated/changelogCatalog.d.ts +3 -0
  75. package/build/generated/changelogCatalog.d.ts.map +1 -1
  76. package/build/generated/changelogCatalog.js +4 -0
  77. package/build/generated/changelogCatalog.js.map +1 -1
  78. package/build/generated/releaseMetadata.js +6 -6
  79. package/build/generated/releaseMetadata.js.map +1 -1
  80. package/build/index.d.ts +1 -1
  81. package/build/index.d.ts.map +1 -1
  82. package/build/index.js +9 -0
  83. package/build/index.js.map +1 -1
  84. package/ios/BluetoothSdkModule.swift +76 -12
  85. package/ios/MentraBluetoothSDK.podspec +4 -0
  86. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  87. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  88. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  89. package/ios/Source/BluetoothSdkDefaults.swift +2 -2
  90. package/ios/Source/Bridge.swift +11 -3
  91. package/ios/Source/DeviceManager.swift +131 -18
  92. package/ios/Source/DeviceStore.swift +27 -0
  93. package/ios/Source/GeneratedChangelogCatalog.swift +1 -0
  94. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  95. package/ios/Source/MentraBluetoothSDK.swift +40 -5
  96. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  97. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  98. package/ios/Source/audio/SpeechActivity.swift +277 -0
  99. package/ios/Source/errors/BluetoothSdkError.swift +5 -1
  100. package/ios/Source/events/BluetoothEvents.swift +41 -0
  101. package/ios/Source/internal/BleTraceLogger.swift +9 -6
  102. package/ios/Source/internal/BluetoothAvailability.swift +15 -5
  103. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +186 -0
  104. package/ios/Source/sgcs/MentraLive.swift +1270 -189
  105. package/ios/Source/sgcs/MentraLivePairingAdvertisement.swift +260 -1
  106. package/ios/Source/sgcs/MentraLivePairingStateMachine.swift +385 -0
  107. package/ios/Source/sgcs/MentraLivePairingStateStore.swift +121 -0
  108. package/ios/Source/sgcs/Nimo.swift +10 -3
  109. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +39 -9
  110. package/ios/Source/sgcs/SGCManager.swift +13 -0
  111. package/ios/Source/sgcs/Simulated.swift +2 -0
  112. package/ios/Source/status/DeviceStatus.swift +35 -0
  113. package/ios/Source/stt/STTTools.swift +13 -31
  114. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  115. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  116. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  117. package/ios/Source/types/DeviceModels.swift +8 -1
  118. package/ios/Source/utils/AudioSessionMonitor.swift +158 -5
  119. package/ios/Source/utils/BoundedWait.swift +44 -0
  120. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  121. package/ios/Source/utils/SttModelTraits.swift +62 -0
  122. package/ios/Tests/BesCrashReportTests.swift +142 -0
  123. package/ios/Tests/BluetoothAudioRouteTests.swift +82 -0
  124. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  125. package/ios/Tests/DeviceManagerReconnectTests.swift +4 -2
  126. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +197 -0
  127. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  128. package/ios/Tests/MentraLiveAudioSetupTests.swift +209 -0
  129. package/ios/Tests/MentraLiveConnectionOptionsTests.swift +55 -0
  130. package/ios/Tests/MentraLivePairingAdvertisementTests.swift +327 -0
  131. package/ios/Tests/MentraLivePairingStateMachineTests.swift +402 -0
  132. package/ios/Tests/MentraLiveSessionReadinessTests.swift +368 -26
  133. package/ios/Tests/NimoCanvasTransportTests.swift +58 -0
  134. package/ios/Tests/PcmStreamTests.swift +299 -0
  135. package/ios/Tests/SpeechActivityTests.swift +238 -0
  136. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  137. package/ios/Tests/WifiAdbDispatchTests.swift +118 -0
  138. package/package.json +3 -2
  139. package/plugin/build/withAndroid.js +9 -11
  140. package/plugin/build/withKotlinVersion.d.ts +2 -0
  141. package/plugin/build/withKotlinVersion.js +46 -0
  142. package/src/BluetoothSdk.types.ts +201 -1
  143. package/src/_private/BluetoothSdkModule.ts +47 -5
  144. package/src/generated/changelogCatalog.ts +4 -0
  145. package/src/generated/releaseMetadata.ts +6 -6
  146. package/src/index.ts +22 -0
  147. package/android/silero/LICENSE.md +0 -17
  148. package/android/silero/build.gradle +0 -50
  149. package/android/silero/proguard-rules.pro +0 -24
  150. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  151. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  152. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  153. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  154. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  155. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  156. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  157. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  158. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  159. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  160. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
  161. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
  162. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  163. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
  164. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
  165. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
  166. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -288
  167. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  168. /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
@@ -696,25 +696,28 @@ private struct BlePhotoTransfer {
696
696
  }
697
697
  }
698
698
 
699
- private enum BleIncidentLogRelayKind {
699
+ enum BleIncidentLogRelayKind {
700
700
  case firmware
701
701
  case logcat
702
702
  }
703
703
 
704
- private final class BleIncidentLogRelayEntry {
704
+ final class BleIncidentLogRelayEntry {
705
705
  let fileBaseKey: String
706
706
  let incidentId: String
707
707
  let apiBaseUrl: String
708
708
  let kind: BleIncidentLogRelayKind
709
+ let reservedAt: TimeInterval
709
710
  var session: MentraLiveFileTransferSession?
710
711
 
711
712
  init(
712
- fileBaseKey: String, incidentId: String, apiBaseUrl: String, kind: BleIncidentLogRelayKind
713
+ fileBaseKey: String, incidentId: String, apiBaseUrl: String, kind: BleIncidentLogRelayKind,
714
+ reservedAt: TimeInterval
713
715
  ) {
714
716
  self.fileBaseKey = fileBaseKey
715
717
  self.incidentId = incidentId
716
718
  self.apiBaseUrl = apiBaseUrl
717
719
  self.kind = kind
720
+ self.reservedAt = reservedAt
718
721
  }
719
722
  }
720
723
 
@@ -728,28 +731,30 @@ extension MentraLive: CBCentralManagerDelegate {
728
731
  guard let self else { return }
729
732
  switch state {
730
733
  case .poweredOn:
731
- Bridge.log("LIVE: Bluetooth powered on")
732
- // If we have a saved device, try to reconnect
733
- if let savedDeviceName = UserDefaults.standard.string(forKey: PREFS_DEVICE_NAME),
734
- !savedDeviceName.isEmpty
734
+ self.pairFlow("central", "state=powered_on")
735
+ if self.pairingStore.isPaused {
736
+ self.startPairingWatchScan(reason: "powered_on")
737
+ } else if !self.automaticConnectBlocked(),
738
+ let savedDeviceName = UserDefaults.standard.string(forKey: PREFS_DEVICE_NAME),
739
+ !savedDeviceName.isEmpty
735
740
  {
736
- self.startScan()
741
+ self.attachKnownOrScan(savedDeviceName)
737
742
  }
738
743
 
739
744
  case .poweredOff:
740
- Bridge.log("LIVE: Bluetooth is powered off")
745
+ self.pairFlow("central", "state=powered_off")
741
746
  self.updateConnectionState(ConnTypes.DISCONNECTED)
742
747
 
743
748
  case .unauthorized:
744
- Bridge.log("LIVE: Bluetooth is unauthorized")
749
+ self.pairFlow("central", "state=unauthorized")
745
750
  self.updateConnectionState(ConnTypes.DISCONNECTED)
746
751
 
747
752
  case .unsupported:
748
- Bridge.log("LIVE: Bluetooth is unsupported")
753
+ self.pairFlow("central", "state=unsupported")
749
754
  self.updateConnectionState(ConnTypes.DISCONNECTED)
750
755
 
751
756
  default:
752
- Bridge.log("LIVE: Bluetooth state: \(state.rawValue)")
757
+ self.pairFlow("central", "state=\(state.rawValue)")
753
758
  }
754
759
  }
755
760
  }
@@ -759,7 +764,14 @@ extension MentraLive: CBCentralManagerDelegate {
759
764
  advertisementData: [String: Any] = [:],
760
765
  rssi: NSNumber? = nil
761
766
  ) {
762
- guard let name = peripheral.name else { return }
767
+ // The first iOS advertisement often has the name only in the packet, not on
768
+ // CBPeripheral. Dropping that packet hides glasses that are already in pairing mode.
769
+ guard let name = discoveredAdvertisementName(peripheral, advertisementData: advertisementData) else {
770
+ if manualDiscoveryActive, loggedUnnamedDiscoveries.insert(peripheral.identifier).inserted {
771
+ pairFlow("discover", "unnamed id=\(peripheral.identifier.uuidString)")
772
+ }
773
+ return
774
+ }
763
775
 
764
776
  // Check for compatible device names
765
777
  if name == "Xy_A" || name.hasPrefix("XyBLE_") || name.hasPrefix("MENTRA_LIVE_BLE")
@@ -767,60 +779,112 @@ extension MentraLive: CBCentralManagerDelegate {
767
779
  {
768
780
  let savedDeviceName = UserDefaults.standard.string(forKey: PREFS_DEVICE_NAME)
769
781
  let isReconnectTarget = savedDeviceName != nil && savedDeviceName == name
782
+ let discoveredAtMs = Self.monotonicNowMs()
783
+ if advertisesPairingFlag(advertisementData) {
784
+ Self.secureTrailerMemory.recordSecureTrailer(peripheral.identifier, nowMs: discoveredAtMs)
785
+ }
770
786
  if !isReconnectTarget && advertisesPairingFlag(advertisementData)
771
787
  && !isPairingDiscoverable(advertisementData)
772
788
  {
773
789
  // Keep nearby secure units visible with pairing-mode guidance, while RN blocks
774
790
  // the connection until a pairable advertisement arrives.
775
- Bridge.log(
776
- "LIVE: Nearby \(name) is secure firmware not in pairing mode — exposing as non-pairable"
791
+ pairFlow(
792
+ "discover",
793
+ "name=\(name) id=\(peripheral.identifier.uuidString) saved=\(savedDeviceName ?? "-") pairingMode=false secure=true connect=false"
777
794
  )
778
795
  discoveredPeripherals[name] = peripheral
779
- cacheAdvPairing(
796
+ rememberPeripheral(peripheral, name: name)
797
+ if cacheAdvPairing(
780
798
  name,
781
799
  pairingMode: false,
782
800
  pairingCode: nil,
783
801
  securePairingCapable: true
784
- )
785
- emitDiscoveredDeviceFromCache(
786
- name,
787
- identifier: peripheral.identifier.uuidString,
788
- rssi: rssi?.intValue
789
- )
802
+ ) {
803
+ emitDiscoveredDeviceFromCache(
804
+ name,
805
+ identifier: peripheral.identifier.uuidString,
806
+ rssi: rssi?.intValue
807
+ )
808
+ }
790
809
  return
791
810
  }
792
811
 
793
812
  let glassType = name == "Xy_A" ? "Standard" : "K900"
794
813
  let trailer = parseSecurePairingTrailer(advertisementData)
814
+ // A packet without the trailer from a peripheral that just showed it is a partial
815
+ // advertisement, not legacy firmware. Do not publish it: the scan list would show a
816
+ // secure unit that is not in pairing mode as pairable, with no caption.
817
+ let partialAdvertisement = Self.secureTrailerMemory.isPartialAdvertisement(
818
+ peripheral.identifier,
819
+ secureCapable: trailer.secureCapable,
820
+ nowMs: discoveredAtMs
821
+ )
795
822
  Bridge.log(
796
823
  trailer.secureCapable
797
824
  ? "Found compatible \(glassType) glasses device: \(name) (pairingMode=\(trailer.pairingMode))"
798
- : "Found compatible \(glassType) glasses device: \(name) (legacy firmware, pairable)"
825
+ : partialAdvertisement
826
+ ? "Found compatible \(glassType) glasses device: \(name) (partial advertisement, secure trailer seen recently)"
827
+ : "Found compatible \(glassType) glasses device: \(name) (legacy firmware, pairable)"
799
828
  )
800
829
 
801
830
  // Store the peripheral
802
831
  discoveredPeripherals[name] = peripheral
832
+ rememberPeripheral(peripheral, name: name)
803
833
 
804
- cacheAdvPairing(
834
+ if !partialAdvertisement, cacheAdvPairing(
805
835
  name,
806
836
  // Field firmware has no pairing flag. Treat it as pairable so the
807
837
  // new Mentra App can still find old glasses.
808
838
  pairingMode: trailer.secureCapable ? trailer.pairingMode : true,
809
839
  pairingCode: trailer.pairingCode,
810
840
  securePairingCapable: trailer.secureCapable
841
+ ) {
842
+ emitDiscoveredDeviceFromCache(
843
+ name,
844
+ identifier: peripheral.identifier.uuidString,
845
+ rssi: rssi?.intValue
846
+ )
847
+ }
848
+
849
+ let isSavedGlasses = savedDeviceName == name
850
+ if isSavedGlasses, trailer.secureCapable {
851
+ observeSavedGlassesAdvertisement(trailer)
852
+ }
853
+ if isSavedGlasses, automaticConnectBlocked() {
854
+ // Paused for a pairing window or rejected: observe only. The watch scan keeps
855
+ // reading the advertisement so a cleared pairing flag can end the pause.
856
+ if !pairingWatchScanActive {
857
+ pairFlow(
858
+ "discover",
859
+ "name=\(name) id=\(peripheral.identifier.uuidString) action=wait state=\(pairingStore.describe())"
860
+ )
861
+ }
862
+ return
863
+ }
864
+ let waitForWindow = MentraLiveConnectionAttemptPolicy.shouldStandDownInsteadOfReconnect(
865
+ pairingMode: trailer.secureCapable && trailer.pairingMode,
866
+ savedGlasses: isSavedGlasses,
867
+ explicitPairing: isExplicitPairingAttempt()
811
868
  )
812
- emitDiscoveredDeviceFromCache(
813
- name,
814
- identifier: peripheral.identifier.uuidString,
815
- rssi: rssi?.intValue
869
+ if waitForWindow {
870
+ // The saved glasses are in a pairing window this phone never heard about.
871
+ // Connecting would race the new phone for the single BLE slot; keep watching
872
+ // and connect once the flag clears.
873
+ if !pairingWatchScanActive {
874
+ pairFlow(
875
+ "discover",
876
+ "name=\(name) id=\(peripheral.identifier.uuidString) action=wait_pairing_mode"
877
+ )
878
+ }
879
+ startPairingWatchScan(reason: "saved_glasses_pairing_mode")
880
+ return
881
+ }
882
+ let willConnect = isSavedGlasses
883
+ pairFlow(
884
+ "discover",
885
+ "name=\(name) id=\(peripheral.identifier.uuidString) saved=\(savedDeviceName ?? "-") pairingMode=\(trailer.pairingMode) secure=\(trailer.secureCapable) connect=\(willConnect)"
816
886
  )
817
-
818
- // Check if this is the device we want to connect to
819
- if let savedDeviceName = UserDefaults.standard.string(forKey: PREFS_DEVICE_NAME),
820
- savedDeviceName == name
821
- {
822
- Bridge.log("Found our remembered device by name, connecting: \(name)")
823
- // stopScan()
887
+ if willConnect {
824
888
  centralManager?.stopScan()
825
889
  isScanning = false
826
890
  connectToDevice(peripheral)
@@ -842,7 +906,7 @@ extension MentraLive: CBCentralManagerDelegate {
842
906
  guard let self else { return }
843
907
  let matchesActiveAttempt = self.connectingPeripheral === peripheral
844
908
  guard MentraLiveConnectionAttemptPolicy.shouldAcceptDidConnect(
845
- pairingYieldActive: self.pairingYieldActive,
909
+ pairingYieldActive: self.automaticConnectBlocked(),
846
910
  matchesActiveAttempt: matchesActiveAttempt
847
911
  ) else {
848
912
  Bridge.log(
@@ -859,7 +923,11 @@ extension MentraLive: CBCentralManagerDelegate {
859
923
  self.centralManager?.cancelPeripheralConnection(peripheral)
860
924
  return
861
925
  }
862
- Bridge.log("Connected to GATT server, discovering services...")
926
+ self.pairFlow(
927
+ "gatt_connect",
928
+ "id=\(peripheral.identifier.uuidString) name=\(peripheral.name ?? "-")"
929
+ )
930
+ Self.clearStaleIosBondPrompt()
863
931
 
864
932
  self.stopConnectionTimeout()
865
933
  self.clearPendingReconnectTracking()
@@ -913,11 +981,19 @@ extension MentraLive: CBCentralManagerDelegate {
913
981
  let isCurrent =
914
982
  self.connectedPeripheral === peripheral || self.connectingPeripheral === peripheral
915
983
  if !isCurrent {
916
- Bridge.log("LIVE: Ignoring stale disconnect for \(peripheral.identifier)")
984
+ self.pairFlow("gatt_disconnect", "ignored id=\(peripheral.identifier.uuidString)")
917
985
  return
918
986
  }
919
987
  self.connectingPeripheral = nil
920
988
  self.clearPendingReconnectTracking()
989
+ let nsError = error as NSError?
990
+ self.pairFlow(
991
+ "gatt_disconnect",
992
+ "id=\(peripheral.identifier.uuidString) name=\(peripheral.name ?? "-") domain=\(nsError?.domain ?? "-") code=\(nsError?.code ?? 0)"
993
+ )
994
+ Bridge.log(
995
+ "PAIRFLOW: ble_disconnect id=\(peripheral.identifier.uuidString) domain=\(nsError?.domain ?? "none") code=\(nsError?.code ?? 0) killed=\(self.isKilled) explicitPairing=\(self.isExplicitPairingAttempt())"
996
+ )
921
997
  Bridge.log("LIVE: Disconnected from GATT server")
922
998
 
923
999
  self.isConnecting = false
@@ -941,9 +1017,18 @@ extension MentraLive: CBCentralManagerDelegate {
941
1017
  // Clean up characteristics
942
1018
  self.txCharacteristic = nil
943
1019
  self.rxCharacteristic = nil
1020
+ let waitingForOwnerCommit = self.awaitingSecurePairingConfirmation
1021
+ self.resetSecurePairingSession()
1022
+
1023
+ if self.stopAfterConnectFailure(error) {
1024
+ return
1025
+ }
944
1026
 
945
- if self.pairingYieldAwaitingReclaim, Self.isPairingAuthFailure(error) {
946
- self.clearSavedGlassesAfterOwnerLoss(reason: "ios_auth_fail")
1027
+ // The system pairing sheet was dismissed, or the bond never finished.
1028
+ // Reconnecting would leave the loading screen up with no failure.
1029
+ if waitingForOwnerCommit && self.isExplicitPairingAttempt() {
1030
+ Bridge.log("LIVE: secure pairing link dropped before owner commit")
1031
+ Bridge.sendPairFailureEvent("errors:pairingCouldNotStart")
947
1032
  return
948
1033
  }
949
1034
 
@@ -962,11 +1047,15 @@ extension MentraLive: CBCentralManagerDelegate {
962
1047
  let isCurrent =
963
1048
  self.connectedPeripheral === peripheral || self.connectingPeripheral === peripheral
964
1049
  if !isCurrent {
965
- Bridge.log("LIVE: Ignoring stale connect failure for \(peripheral.identifier)")
1050
+ self.pairFlow("gatt_connect_fail", "ignored id=\(peripheral.identifier.uuidString)")
966
1051
  return
967
1052
  }
968
1053
  self.connectingPeripheral = nil
969
- Bridge.log("LIVE: Failed to connect to peripheral: \(errorDescription)")
1054
+ let nsError = error as NSError?
1055
+ self.pairFlow(
1056
+ "gatt_connect_fail",
1057
+ "id=\(peripheral.identifier.uuidString) name=\(peripheral.name ?? "-") domain=\(nsError?.domain ?? "-") code=\(nsError?.code ?? 0) \(errorDescription)"
1058
+ )
970
1059
 
971
1060
  self.stopConnectionTimeout()
972
1061
  self.clearPendingReconnectTracking()
@@ -975,8 +1064,7 @@ extension MentraLive: CBCentralManagerDelegate {
975
1064
  self.connectedPeripheral = nil
976
1065
  self.updateConnectionState(ConnTypes.DISCONNECTED)
977
1066
 
978
- if self.pairingYieldAwaitingReclaim, Self.isPairingAuthFailure(error) {
979
- self.clearSavedGlassesAfterOwnerLoss(reason: "ios_auth_fail")
1067
+ if self.stopAfterConnectFailure(error) {
980
1068
  return
981
1069
  }
982
1070
 
@@ -1078,7 +1166,10 @@ extension MentraLive: CBPeripheralDelegate {
1078
1166
 
1079
1167
  // Check if we have both characteristics
1080
1168
  if self.txCharacteristic != nil, let rx = self.rxCharacteristic {
1081
- Bridge.log("LIVE: ✅ Both TX and RX characteristics found - BLE connection ready")
1169
+ self.pairFlow(
1170
+ "gatt_ready",
1171
+ "id=\(peripheral.identifier.uuidString) name=\(peripheral.name ?? "-") mtu=\(max(23, min(peripheral.maximumWriteValueLength(for: .withResponse) + 3, peripheral.maximumWriteValueLength(for: .withoutResponse) + 3)))"
1172
+ )
1082
1173
  Bridge.log("LIVE: 🔄 Waiting for glasses SOC to become ready...")
1083
1174
 
1084
1175
  // Don't set connected=true here - wait for SOC to be ready (fullyBooted=true)
@@ -1152,13 +1243,14 @@ extension MentraLive: CBPeripheralDelegate {
1152
1243
  }
1153
1244
 
1154
1245
  nonisolated func peripheral(
1155
- _: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?
1246
+ _ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?
1156
1247
  ) {
1248
+ guard let token = notificationIngress.capture(peripheral) else { return }
1157
1249
  let uuid = characteristic.uuid
1158
1250
  let data = characteristic.value
1159
1251
  let errorDescription = error?.localizedDescription
1160
1252
  DispatchQueue.main.async { [weak self] in
1161
- guard let self else { return }
1253
+ guard let self, self.connectedPeripheral === peripheral, self.notificationIngress.current(token) else { return }
1162
1254
  // Bridge.log("LIVE: DEBUG: didUpdateValueFor CALLED - characteristic: \(uuid), dataSize: \(data?.count ?? 0)")
1163
1255
  // Log raw hex for debugging glasses_ready issue
1164
1256
  if let data {
@@ -1195,7 +1287,7 @@ extension MentraLive: CBPeripheralDelegate {
1195
1287
  }
1196
1288
 
1197
1289
  // Handle regular data (JSON messages, file transfers, etc.)
1198
- self.processReceivedData(data)
1290
+ self.receiveBleNotification(data, token: token)
1199
1291
  }
1200
1292
  }
1201
1293
 
@@ -1221,16 +1313,25 @@ extension MentraLive: CBPeripheralDelegate {
1221
1313
  let uuid = characteristic.uuid
1222
1314
  let isNotifying = characteristic.isNotifying
1223
1315
  let errorDescription = error?.localizedDescription
1316
+ let notifyError = error
1224
1317
  DispatchQueue.main.async { [weak self] in
1225
1318
  guard let self else { return }
1226
1319
  if let errorDescription {
1227
1320
  Bridge.log("LIVE: Error updating notification state: \(errorDescription)")
1321
+ // Insufficient authentication/encryption on the RX subscribe is the glasses
1322
+ // refusing this phone's keys.
1323
+ if uuid == self.RX_CHAR_UUID, Self.isPairingAuthFailure(notifyError),
1324
+ self.recordAuthRejection(reason: "ios_notify_auth_\((notifyError as NSError?)?.code ?? 0)")
1325
+ {
1326
+ return
1327
+ }
1228
1328
  } else {
1229
1329
  Bridge.log("Notification state updated for \(uuid): \(isNotifying ? "ON" : "OFF")")
1230
1330
 
1231
1331
  if uuid == self.RX_CHAR_UUID, isNotifying {
1232
1332
  Bridge.log("LIVE: 🔔 Ready to receive data via notifications")
1233
1333
  self.enableAncsRelayIfAuthorized()
1334
+ self.sendPairingSessionMessages(reason: "gatt_ready")
1234
1335
  }
1235
1336
  }
1236
1337
  }
@@ -1263,12 +1364,25 @@ enum MentraLiveConnectionState {
1263
1364
  }
1264
1365
 
1265
1366
  enum MentraLiveConnectionOptions {
1266
- static func coreBluetoothOptions(requiresAncs: Bool) -> [String: Any]? {
1367
+ /// `enableTransportBridging` asks iOS to bring up the Classic profiles (A2DP/HFP)
1368
+ /// after the BLE link is up (CBConnectPeripheralOptionEnableTransportBridgingKey,
1369
+ /// iOS 13+). The product default is on; this helper still omits the key unless
1370
+ /// the caller passes true.
1371
+ static func coreBluetoothOptions(
1372
+ requiresAncs: Bool,
1373
+ enableTransportBridging: Bool = false
1374
+ ) -> [String: Any]? {
1267
1375
  #if os(macOS)
1268
1376
  return nil
1269
1377
  #else
1270
- guard requiresAncs else { return nil }
1271
- return [CBConnectPeripheralOptionRequiresANCS: true]
1378
+ var options = [String: Any]()
1379
+ if requiresAncs {
1380
+ options[CBConnectPeripheralOptionRequiresANCS] = true
1381
+ }
1382
+ if enableTransportBridging {
1383
+ options[CBConnectPeripheralOptionEnableTransportBridgingKey] = true
1384
+ }
1385
+ return options.isEmpty ? nil : options
1272
1386
  #endif
1273
1387
  }
1274
1388
  }
@@ -1278,6 +1392,29 @@ typealias JSONObject = [String: Any]
1278
1392
 
1279
1393
  // MARK: - Main Manager Class
1280
1394
 
1395
+ /// Captures CoreBluetooth callback provenance before its MainActor hop.
1396
+ final class MentraLiveNotificationIngress: @unchecked Sendable {
1397
+ struct Token: Equatable, Sendable { let source: ObjectIdentifier; let epoch: UInt64 }
1398
+ private let lock = NSLock()
1399
+ private var epoch: UInt64 = 0
1400
+ private var source: ObjectIdentifier?
1401
+ func begin(_ peer: AnyObject?) -> Token? {
1402
+ lock.lock(); defer { lock.unlock() }
1403
+ epoch &+= 1
1404
+ source = peer.map(ObjectIdentifier.init)
1405
+ return source.map { Token(source: $0, epoch: epoch) }
1406
+ }
1407
+ func capture(_ peer: AnyObject) -> Token? {
1408
+ lock.lock(); defer { lock.unlock() }
1409
+ guard source == ObjectIdentifier(peer) else { return nil }
1410
+ return Token(source: ObjectIdentifier(peer), epoch: epoch)
1411
+ }
1412
+ func current(_ token: Token) -> Bool {
1413
+ lock.lock(); defer { lock.unlock() }
1414
+ return source == token.source && epoch == token.epoch
1415
+ }
1416
+ }
1417
+
1281
1418
  @MainActor
1282
1419
  class MentraLive: NSObject, SGCManager {
1283
1420
  // Feature Flags
@@ -1304,16 +1441,23 @@ class MentraLive: NSObject, SGCManager {
1304
1441
  let pairingMode: Bool
1305
1442
  let pairingCode: String?
1306
1443
  let secureCapable: Bool
1444
+ let pairingGeneration: Int?
1445
+ let ownerChanged: Bool
1307
1446
  }
1308
1447
 
1309
1448
  private func parseSecurePairingTrailer(_ advertisementData: [String: Any]) -> SecurePairingTrailer {
1310
1449
  guard let advertisement = pairingAdvertisement(advertisementData) else {
1311
- return SecurePairingTrailer(pairingMode: false, pairingCode: nil, secureCapable: false)
1450
+ return SecurePairingTrailer(
1451
+ pairingMode: false, pairingCode: nil, secureCapable: false, pairingGeneration: nil,
1452
+ ownerChanged: false
1453
+ )
1312
1454
  }
1313
1455
  return SecurePairingTrailer(
1314
1456
  pairingMode: advertisement.pairingMode,
1315
1457
  pairingCode: advertisement.pairingCode,
1316
- secureCapable: true
1458
+ secureCapable: true,
1459
+ pairingGeneration: advertisement.pairingGeneration,
1460
+ ownerChanged: advertisement.ownerChanged
1317
1461
  )
1318
1462
  }
1319
1463
 
@@ -1321,11 +1465,25 @@ class MentraLive: NSObject, SGCManager {
1321
1465
  pairingAdvertisement(advertisementData) != nil
1322
1466
  }
1323
1467
 
1468
+ private nonisolated let notificationIngress = MentraLiveNotificationIngress()
1469
+ private var receivingNotification: MentraLiveNotificationIngress.Token?
1470
+ private var wifiAdbPeerIdentity: (mac: String, token: MentraLiveNotificationIngress.Token)?
1471
+ private final class WifiAdbAdmission {
1472
+ let identity: (mac: String, token: MentraLiveNotificationIngress.Token)
1473
+ let wireEpoch: Int
1474
+ var queued = 0
1475
+ var refused = false
1476
+ init(identity: (mac: String, token: MentraLiveNotificationIngress.Token), wireEpoch: Int) {
1477
+ self.identity = identity; self.wireEpoch = wireEpoch
1478
+ }
1479
+ }
1480
+ private var wifiAdbAdmission: WifiAdbAdmission?
1324
1481
  var connectionState: String = ConnTypes.DISCONNECTED
1325
1482
 
1326
1483
  /// Mirrors Android `updateConnectionState` — RN home reads `glasses.connectionState` for reconnecting UI.
1327
1484
  private func updateConnectionState(_ state: String) {
1328
1485
  if state == ConnTypes.DISCONNECTED {
1486
+ endBleNotificationSession()
1329
1487
  // Device identity is session-bound. Clear it on disconnect so a previous pair's
1330
1488
  // identifiers cannot be associated with the next connection. Connect must NOT clear
1331
1489
  // them: DeviceManager.disconnect already wipes them before any new connection, and
@@ -1338,6 +1496,10 @@ class MentraLive: NSObject, SGCManager {
1338
1496
  DeviceStore.shared.apply("glasses", "hotspotOtaVersion", 0)
1339
1497
  }
1340
1498
  connectionState = state
1499
+ pairFlow(
1500
+ "conn_state",
1501
+ "state=\(state) gatt=\(txCharacteristic != nil) connecting=\(isConnecting) killed=\(isKilled) scanning=\(isScanning) id=\(connectedPeripheral?.identifier.uuidString ?? connectingPeripheral?.identifier.uuidString ?? "-") name=\(connectedPeripheral?.name ?? connectingPeripheral?.name ?? "-")"
1502
+ )
1341
1503
  DeviceStore.shared.apply("glasses", "connectionState", state)
1342
1504
  // Drop OTA caches when fully disconnected — avoids leaking session/step state from
1343
1505
  // a previous pairing into the next one (would otherwise surface as wrong overall_percent
@@ -1355,6 +1517,7 @@ class MentraLive: NSObject, SGCManager {
1355
1517
  DeviceStore.shared.apply("glasses", "signalStrength", -1)
1356
1518
  DeviceStore.shared.apply("glasses", "signalStrengthUpdatedAt", 0)
1357
1519
  resetOtaCache()
1520
+ endAudioSetupSession()
1358
1521
  }
1359
1522
  }
1360
1523
 
@@ -1387,11 +1550,17 @@ class MentraLive: NSObject, SGCManager {
1387
1550
  func dbg1() {}
1388
1551
  func dbg2() {}
1389
1552
 
1553
+ /// Clear the saved device name so the pairing filter is not bypassed on rescan.
1554
+ static func clearSavedPeripheral() {
1555
+ secureTrailerMemory.clear()
1556
+ UserDefaults.standard.removeObject(forKey: prefsDeviceName)
1557
+ UserDefaults.standard.removeObject(forKey: prefsPeripheralIds)
1558
+ }
1559
+
1390
1560
  func forget() {
1391
1561
  Bridge.log("LIVE: Forgetting Mentra Live glasses")
1392
-
1393
- // Clear saved device name so the pairing filter is not bypassed on rescan
1394
- UserDefaults.standard.removeObject(forKey: PREFS_DEVICE_NAME)
1562
+ Self.clearSavedPeripheral()
1563
+ pairFlow("forget", "cleared_saved_peripheral")
1395
1564
 
1396
1565
  // Stop scanning first
1397
1566
  if isScanning {
@@ -1414,6 +1583,9 @@ class MentraLive: NSObject, SGCManager {
1414
1583
 
1415
1584
  var type = "Mentra Live"
1416
1585
  var hasMic = true
1586
+ var publishesAudioSetup: Bool {
1587
+ true
1588
+ }
1417
1589
 
1418
1590
  func setMicEnabled(_ enabled: Bool) {
1419
1591
  Bridge.log("LIVE: 🎤 Microphone state change requested: \(enabled)")
@@ -1477,7 +1649,11 @@ class MentraLive: NSObject, SGCManager {
1477
1649
  private var fileWriteCharacteristic: CBCharacteristic?
1478
1650
  private var activeFileTransfers = [String: MentraLiveFileTransferSession]()
1479
1651
  private var blePhotoTransfers = [String: BlePhotoTransfer]()
1480
- private var bleIncidentLogRelays = [String: BleIncidentLogRelayEntry]()
1652
+ private(set) var bleIncidentLogRelays = [String: BleIncidentLogRelayEntry]()
1653
+ // Longer than the glasses' bounded relay of one report (BES logs, two file transfers, the
1654
+ // phone POST), so an unreleased name cannot be reused while its report is in flight.
1655
+ static let incidentRelayOwnershipSeconds: TimeInterval = 600
1656
+ var incidentRelayClock: () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }
1481
1657
  private var l2capFileChannel: MentraLiveL2capChannel?
1482
1658
  private var l2capFileChannelId: UUID?
1483
1659
  private var l2capFileChannelOpening = false
@@ -1520,7 +1696,10 @@ class MentraLive: NSObject, SGCManager {
1520
1696
  private let SIGNIFICANT_BLE_TRACE_QUEUE_SIZE = 5
1521
1697
 
1522
1698
  /// Device Settings Keys
1523
- private let PREFS_DEVICE_NAME = "MentraLiveLastConnectedDeviceName"
1699
+ private static let prefsDeviceName = "MentraLiveLastConnectedDeviceName"
1700
+ private static let prefsPeripheralIds = "MentraLivePeripheralIds"
1701
+ private let PREFS_DEVICE_NAME = MentraLive.prefsDeviceName
1702
+ private let PREFS_PERIPHERAL_IDS = MentraLive.prefsPeripheralIds
1524
1703
 
1525
1704
  // MARK: - Properties
1526
1705
 
@@ -1531,7 +1710,9 @@ class MentraLive: NSObject, SGCManager {
1531
1710
  /// BLE Properties
1532
1711
  private var centralManager: CBCentralManager?
1533
1712
 
1534
- private var connectedPeripheral: CBPeripheral?
1713
+ private var connectedPeripheral: CBPeripheral? {
1714
+ didSet { _ = beginBleNotificationSession(source: connectedPeripheral) }
1715
+ }
1535
1716
  /// Peripheral for the in-flight connect; used to ignore stale disconnect/fail callbacks.
1536
1717
  private var connectingPeripheral: CBPeripheral?
1537
1718
  private var txCharacteristic: CBCharacteristic?
@@ -1544,10 +1725,49 @@ class MentraLive: NSObject, SGCManager {
1544
1725
  private var manualDiscoveryActive = false
1545
1726
  private var isConnecting = false
1546
1727
  private var isKilled = false
1547
- /// Glasses opened pairing window — stand down without forgetting identity/bonds.
1548
- private var pairingYieldActive = false
1549
- private var pairingYieldAwaitingReclaim = false
1550
- private var pairingYieldEndWorkItem: DispatchWorkItem?
1728
+ /// Pairing protocol this phone speaks (`phone_hello.pairing_protocol`). The glasses send
1729
+ /// window notices only to phones that announced protocol 4 or later.
1730
+ static let pairingProtocolVersion = 4
1731
+ /// Pause, takeover and rejection state for the saved glasses. Outlives this manager.
1732
+ private let pairingStore = MentraLivePairingStateStore.shared
1733
+ /// Ends the pairing-mode pause at its deadline.
1734
+ private var pairingPauseWorkItem: DispatchWorkItem?
1735
+ /// The running scan is the duplicate-reporting watch scan, not a connect scan.
1736
+ private var pairingWatchScanActive = false
1737
+ private var phoneHelloSentThisSession = false
1738
+ private var pairSelectSentThisSession = false
1739
+ /// `pairing_info` arrived on this BLE session, so the glasses run secure firmware.
1740
+ private var pairingInfoSeenThisSession = false
1741
+ /// `pairing_info.auto_audio` on this BLE session. Old firmware never sends it.
1742
+ private var pairingInfoAutoAudio = false
1743
+ /// Peripherals that advertised the secure-pairing trailer in the last few seconds.
1744
+ /// CoreBluetooth sometimes reports an advertisement without the manufacturer data that
1745
+ /// carries the trailer, so a packet without it right after one with it is partial, not
1746
+ /// legacy firmware. Nothing is persisted: glasses rolled back to legacy firmware must list
1747
+ /// as legacy again.
1748
+ private static var secureTrailerMemory = MentraLiveSecureTrailerMemory()
1749
+ /// Retired persisted name set that hid rolled-back glasses for good. Removed on startup.
1750
+ private static let retiredSecurePairingNamesKey = "mentra_live_secure_pairing_names"
1751
+ /// glasses_ready arrived for a secure pairing target before pairing_info confirmed the bond.
1752
+ private var awaitingSecurePairingConfirmation = false
1753
+ /// pairing_info from secure firmware arrived on this BLE session.
1754
+ private var securePairingConfirmed = false
1755
+ private var securePairingWaitWorkItem: DispatchWorkItem?
1756
+ /// glasses_ready arrived for an explicit pair whose capability is unknown; waiting for
1757
+ /// pairing_info to tell secure from legacy firmware.
1758
+ private var awaitingPairingInfoForUnknownCapability = false
1759
+ private var unknownCapabilityWaitWorkItem: DispatchWorkItem?
1760
+ /// Marks the saved glasses as legacy firmware when a ready session gets no pairing_info.
1761
+ private var secureFirmwareRefreshWorkItem: DispatchWorkItem?
1762
+ /// Internal so tests can shorten the waits.
1763
+ var unknownCapabilityPairingInfoWaitMs = MentraLiveConnectionAttemptPolicy.unknownCapabilityPairingInfoWaitMs
1764
+ var secureFirmwareRefreshMs = MentraLiveConnectionAttemptPolicy.secureFirmwareRefreshMs
1765
+ /// `GlassesStatus.audioSetup` for this driver (see `GlassesAudioSetupPolicy`).
1766
+ private var audioSetup = GlassesAudioSetupTracker()
1767
+ private var audioSetupDeadlineWorkItem: DispatchWorkItem?
1768
+ private var audioSetupStoreListenerId: String?
1769
+ /// Monotonic milliseconds. Internal so tests can drive the audio-setup clock.
1770
+ var audioSetupNowMs: () -> Int = { MentraLive.monotonicNowMs() }
1551
1771
  /// Hold GATT teardown until the unpair write can leave the phone.
1552
1772
  private var unpairFlushPending = false
1553
1773
  private var unpairFlushWorkItem: DispatchWorkItem?
@@ -1674,6 +1894,10 @@ class MentraLive: NSObject, SGCManager {
1674
1894
  private var pendingReconnectSettleWorkItem: DispatchWorkItem?
1675
1895
  private var reconnectionWorkItem: DispatchWorkItem?
1676
1896
  private var requiresAncs = true
1897
+ /// Experimental iOS transport bridging (Classic profiles after BLE connect). Off by default.
1898
+ /// Static so it can be set from `ConnectOptions` without threading a parameter
1899
+ /// through `DeviceManager`; it applies to every connect issued after it is set.
1900
+ static var enableTransportBridging = true
1677
1901
 
1678
1902
  // MARK: - Initialization
1679
1903
 
@@ -1693,6 +1917,10 @@ class MentraLive: NSObject, SGCManager {
1693
1917
  } else {
1694
1918
  Bridge.log("LIVE: 🎵 Phone audio monitor disabled (BLOCK_AUDIO_DUPLEX=false)")
1695
1919
  }
1920
+
1921
+ UserDefaults.standard.removeObject(forKey: Self.retiredSecurePairingNamesKey)
1922
+ restorePairingState()
1923
+ observeAudioSetupInputs()
1696
1924
  }
1697
1925
 
1698
1926
  deinit {
@@ -1713,12 +1941,15 @@ class MentraLive: NSObject, SGCManager {
1713
1941
  // MARK: - React Native Interface
1714
1942
 
1715
1943
  private var discoveredPeripherals = [String: CBPeripheral]() // name -> peripheral
1944
+ /// Advertisements that arrived with no name. Logged once so a pairing scan that
1945
+ /// sees the glasses but cannot list them is visible in the phone log.
1946
+ private var loggedUnnamedDiscoveries = Set<UUID>()
1716
1947
  /// Last advertisement pairing trailer for a discovered name. Re-emits (already-
1717
1948
  /// connected / scan replay) must not drop these flags: omitting them makes a
1718
1949
  /// secure idle unit look like pairable legacy firmware.
1719
1950
  private var discoveredAdvPairing = [String: CachedAdvPairing]()
1720
1951
 
1721
- private struct CachedAdvPairing {
1952
+ private struct CachedAdvPairing: Equatable {
1722
1953
  let pairingMode: Bool
1723
1954
  let pairingCode: String?
1724
1955
  let securePairingCapable: Bool
@@ -1747,20 +1978,67 @@ class MentraLive: NSObject, SGCManager {
1747
1978
  }
1748
1979
  }
1749
1980
 
1750
- func isPairingYieldActive() -> Bool {
1751
- pairingYieldActive
1981
+ /// Automatic connects wait: the saved glasses are in a pairing window or no longer accept
1982
+ /// this phone. An explicit pair is never blocked.
1983
+ private func automaticConnectBlocked() -> Bool {
1984
+ !pairingStore.allowsAutomaticReconnect && !isExplicitPairingAttempt()
1752
1985
  }
1753
1986
 
1754
- private func enterPairingYield(windowMs: Int) {
1755
- cancelPendingReconnect(reason: "pairing_yield")
1756
- pairingYieldActive = true
1757
- pairingYieldAwaitingReclaim = false
1758
- pairingYieldEndWorkItem?.cancel()
1759
- if isScanning {
1760
- stopScan()
1761
- }
1762
- // Publish disconnect immediately for Phone A UI. didDisconnectPeripheral may lag
1763
- // or race with cancelPeripheralConnection; do not wait on it for stand-down.
1987
+ private func applyPairingTransition(_ transition: MentraLivePairingTransition) {
1988
+ switch transition.effect {
1989
+ case .none:
1990
+ break
1991
+ case .pause:
1992
+ enterPairingPause()
1993
+ case .resume:
1994
+ resumeAfterPairingPause()
1995
+ case .reject:
1996
+ stopAfterPairingRejected()
1997
+ }
1998
+ }
1999
+
2000
+ /// The glasses opened a pairing window. Leave the link, keep the saved glasses and the bonds,
2001
+ /// and make no automatic connection until the window ends. Probing GATT during the window
2002
+ /// races the new phone for the single BLE slot. The watch scan only reads the advertisement.
2003
+ private func enterPairingPause() {
2004
+ leaveGlassesLink(reason: "pairing_mode")
2005
+ armPairingPauseTimer()
2006
+ startPairingWatchScan(reason: "pairing_pause")
2007
+ }
2008
+
2009
+ /// The window is over. Reconnect through a scan so the post-window advertisement
2010
+ /// (`OWNER_CHANGED`) is read before any GATT connect.
2011
+ private func resumeAfterPairingPause() {
2012
+ cancelPairingPauseTimer()
2013
+ if isScanning, !manualDiscoveryActive {
2014
+ centralManager?.stopScan()
2015
+ isScanning = false
2016
+ }
2017
+ guard !isKilled, connectedPeripheral == nil else { return }
2018
+ Bridge.log("LIVE: Pairing pause ended — resuming reconnect to saved glasses")
2019
+ reconnectAttempts = 0
2020
+ handleReconnection()
2021
+ }
2022
+
2023
+ /// The glasses no longer accept this phone. Stop reconnecting, keep the saved glasses so the
2024
+ /// app can offer Pair again or forget. The manager stays alive; every automatic path checks
2025
+ /// the pairing state.
2026
+ private func stopAfterPairingRejected() {
2027
+ cancelPairingPauseTimer()
2028
+ if isExplicitPairingAttempt() { return }
2029
+ leaveGlassesLink(reason: "pairing_rejected")
2030
+ }
2031
+
2032
+ /// Drop the BLE link and every session flag without destroying the manager.
2033
+ private func leaveGlassesLink(reason: String) {
2034
+ cancelPendingReconnect(reason: reason)
2035
+ cancelSecurePairingWait()
2036
+ if isScanning, !manualDiscoveryActive {
2037
+ centralManager?.stopScan()
2038
+ isScanning = false
2039
+ }
2040
+ // Publish the disconnect immediately. didDisconnectPeripheral may lag or race with
2041
+ // cancelPeripheralConnection, and is ignored once connectedPeripheral is nil.
1764
2042
  isConnecting = false
1765
2043
  clearPhysicalReadiness()
1766
2044
  connected = false
@@ -1768,6 +2046,9 @@ class MentraLive: NSObject, SGCManager {
1768
2046
  streamControlVersion = 0
1769
2047
  readinessCompletedThisBleSession = false
1770
2048
  rgbLedAuthorityClaimed = false
2049
+ lastSentMicTuningBody = nil
2050
+ wearTuningQueriedThisLink = false
2051
+ resetSecurePairingSession()
1771
2052
  stopAllTimers()
1772
2053
  closeL2capFileChannel()
1773
2054
  txCharacteristic = nil
@@ -1778,66 +2059,282 @@ class MentraLive: NSObject, SGCManager {
1778
2059
  }
1779
2060
  connectedPeripheral = nil
1780
2061
  connectingPeripheral = nil
1781
- // Stand down for the whole window. Probing GATT during yield races the new
1782
- // phone for the single BLE slot and is exactly what entering_pairing_mode forbids.
2062
+ }
1783
2063
 
2064
+ private func armPairingPauseTimer() {
2065
+ cancelPairingPauseTimer()
2066
+ guard pairingStore.isPaused else { return }
2067
+ let remaining = pairingStore.remainingPauseMs()
1784
2068
  let work = DispatchWorkItem { [weak self] in
1785
2069
  guard let self else { return }
1786
- Bridge.log("LIVE: Pairing yield ended — resume reconnect if still owned")
1787
- self.pairingYieldActive = false
1788
- self.pairingYieldAwaitingReclaim = true
1789
- self.pairingYieldEndWorkItem = nil
1790
- if !self.isKilled, self.connectedPeripheral == nil {
1791
- self.handleReconnection()
2070
+ self.pairingPauseWorkItem = nil
2071
+ let transition = self.pairingStore.update("pause_deadline") {
2072
+ $0.onTick(nowMs: MentraLivePairingStateStore.nowMs())
1792
2073
  }
2074
+ if transition.effect == .none, self.pairingStore.isPaused {
2075
+ self.armPairingPauseTimer()
2076
+ return
2077
+ }
2078
+ self.applyPairingTransition(transition)
2079
+ }
2080
+ pairingPauseWorkItem = work
2081
+ DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(max(remaining, 0)), execute: work)
2082
+ }
2083
+
2084
+ private func cancelPairingPauseTimer() {
2085
+ pairingPauseWorkItem?.cancel()
2086
+ pairingPauseWorkItem = nil
2087
+ }
2088
+
2089
+ /// Duplicate-reporting scan that only observes the saved glasses' advertisement, so a
2090
+ /// cleared pairing flag is seen while the phone waits.
2091
+ private func startPairingWatchScan(reason: String) {
2092
+ if centralManager == nil {
2093
+ centralManager = CBCentralManager(
2094
+ delegate: self, queue: bluetoothQueue,
2095
+ options: ["CBCentralManagerOptionShowPowerAlertKey": 0]
2096
+ )
2097
+ return
1793
2098
  }
1794
- pairingYieldEndWorkItem = work
1795
- DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(windowMs), execute: work)
2099
+ guard !isKilled, let central = centralManager, central.state == .poweredOn else { return }
2100
+ if isScanning, pairingWatchScanActive { return }
2101
+ if isScanning {
2102
+ central.stopScan()
2103
+ }
2104
+ isScanning = true
2105
+ pairingWatchScanActive = true
2106
+ central.scanForPeripherals(
2107
+ withServices: nil,
2108
+ options: [CBCentralManagerScanOptionAllowDuplicatesKey: true]
2109
+ )
2110
+ pairFlow("scan", "start trigger=pairing_watch reason=\(reason) state=\(pairingStore.describe())")
1796
2111
  }
1797
2112
 
1798
- /// Pairing/auth failures after yield — CoreBluetooth codes, not localized strings.
1799
- /// Connection timeouts are not owner-loss.
1800
- private static func isPairingAuthFailure(_ error: Error?) -> Bool {
2113
+ private func observeSavedGlassesAdvertisement(_ trailer: SecurePairingTrailer) {
2114
+ let wasArmed = pairingStore.verificationArmed
2115
+ let transition = pairingStore.update("advert") {
2116
+ $0.onAdvertisement(
2117
+ pairingMode: trailer.pairingMode,
2118
+ ownerChanged: trailer.ownerChanged,
2119
+ generation: trailer.pairingGeneration,
2120
+ nowMs: MentraLivePairingStateStore.nowMs()
2121
+ )
2122
+ }
2123
+ if !wasArmed, pairingStore.verificationArmed {
2124
+ pairFlow("takeover_check", "owner_changed window=\(trailer.pairingGeneration ?? -1) action=verify_once")
2125
+ }
2126
+ applyPairingTransition(transition)
2127
+ }
2128
+
2129
+ /// `phone_hello` on every secure session (the glasses send window notices only to protocol
2130
+ /// 4 phones) and `pair_select` once on an explicit attempt, as soon as GATT is ready. Both
2131
+ /// callers run on a live link: the RX subscribe and a received `pairing_info`.
2132
+ private func sendPairingSessionMessages(reason: String) {
2133
+ let secureTarget = isSecurePairingTarget()
2134
+ // A trailer this scan just saw is a hint to speak the protocol at all; pair_select below
2135
+ // follows only the selected target.
2136
+ let recentSecureTrailer = connectedPeripheral.map {
2137
+ Self.secureTrailerMemory.hasRecentSecureTrailer($0.identifier, nowMs: Self.monotonicNowMs())
2138
+ } ?? false
2139
+ guard secureTarget || isSavedGlassesSecureFirmware() || pairingInfoSeenThisSession || recentSecureTrailer
2140
+ else { return }
2141
+ if !phoneHelloSentThisSession {
2142
+ phoneHelloSentThisSession = true
2143
+ pairFlow("phone_hello", "protocol=\(Self.pairingProtocolVersion) trigger=\(reason)")
2144
+ sendJson(["type": "phone_hello", "pairing_protocol": Self.pairingProtocolVersion], wakeUp: false, requireAck: false)
2145
+ }
2146
+ if !pairSelectSentThisSession,
2147
+ MentraLiveConnectionAttemptPolicy.shouldSendPairSelect(
2148
+ explicitPairing: isExplicitPairingAttempt(),
2149
+ securePairingTarget: secureTarget
2150
+ )
2151
+ {
2152
+ pairSelectSentThisSession = true
2153
+ pairFlow("pair_select", "trigger=\(reason)")
2154
+ sendJson(["type": "pair_select"], wakeUp: false, requireAck: false)
2155
+ }
2156
+ }
2157
+
2158
+ private func resetSecurePairingSession() {
2159
+ securePairingConfirmed = false
2160
+ awaitingSecurePairingConfirmation = false
2161
+ cancelSecurePairingWait()
2162
+ cancelUnknownCapabilityWait()
2163
+ cancelSecureFirmwareRefresh()
2164
+ phoneHelloSentThisSession = false
2165
+ pairSelectSentThisSession = false
2166
+ pairingInfoSeenThisSession = false
2167
+ pairingInfoAutoAudio = false
2168
+ }
2169
+
2170
+ /// Owner-loss destroy marks the manager dead. A later connect must build a new one.
2171
+ /// A live manager already holds the peripheral found during the pairing scan.
2172
+ var isManagerKilled: Bool {
2173
+ isKilled
2174
+ }
2175
+
2176
+ /// Pairing/auth failures: CBError 14 or insufficient authentication/encryption.
2177
+ /// Connection timeouts and the glasses' 0x14 refusal are not.
2178
+ nonisolated static func isPairingAuthFailure(_ error: Error?) -> Bool {
1801
2179
  guard let error = error as NSError? else { return false }
1802
2180
  if error.domain == CBATTErrorDomain {
1803
2181
  return error.code == CBATTError.insufficientAuthentication.rawValue
1804
2182
  || error.code == CBATTError.insufficientEncryption.rawValue
1805
2183
  }
1806
2184
  if error.domain == CBErrorDomain {
1807
- return error.code == CBError.peerRemovedPairingInformation.rawValue
2185
+ return Self.isPeerRemovedPairingInformation(error)
1808
2186
  }
1809
2187
  return false
1810
2188
  }
1811
2189
 
1812
- private func clearSavedGlassesAfterOwnerLoss(reason: String) {
1813
- Bridge.log("LIVE: Owner loss (\(reason)) — clearing saved glasses")
1814
- pairingYieldAwaitingReclaim = false
1815
- pairingYieldActive = false
1816
- pairingYieldEndWorkItem?.cancel()
1817
- pairingYieldEndWorkItem = nil
1818
- forget()
2190
+ nonisolated static func isPeerRemovedPairingInformation(_ error: Error?) -> Bool {
2191
+ guard let error = error as NSError?, error.domain == CBErrorDomain else { return false }
2192
+ return error.code == CBError.peerRemovedPairingInformation.rawValue
2193
+ }
2194
+
2195
+ static let staleIosBondPromptedAtKey = "mentra_live_stale_ios_bond_prompted_at"
2196
+
2197
+ /// A new pairing attempt should be allowed to show the prompt again if it still fails.
2198
+ static func clearStaleIosBondPrompt() {
2199
+ UserDefaults.standard.removeObject(forKey: staleIosBondPromptedAtKey)
2200
+ }
2201
+
2202
+ /// What a connect or link failure means for the next attempt.
2203
+ private enum ConnectFailureOutcome {
2204
+ /// Not a pairing failure: retry as usual.
2205
+ case retry
2206
+ /// An auth failure that did not settle anything yet: retry through the scan backoff,
2207
+ /// because a pending direct connect would repeat the failure without delay.
2208
+ case backoff
2209
+ /// Stop: the user must act, or the glasses rejected this phone.
2210
+ case stop
2211
+ }
2212
+
2213
+ private func classifyConnectFailure(_ error: Error?) -> ConnectFailureOutcome {
2214
+ // iOS keeps keys the glasses no longer have. On an explicit attempt only the user can
2215
+ // fix that, in Settings > Bluetooth.
2216
+ if Self.isPeerRemovedPairingInformation(error), isExplicitPairingAttempt() {
2217
+ promptToForgetStaleIosBond()
2218
+ return .stop
2219
+ }
2220
+ if Self.isPairingAuthFailure(error) {
2221
+ let code = (error as NSError?)?.code ?? 0
2222
+ return recordAuthRejection(reason: "ios_auth_\(code)") ? .stop : .backoff
2223
+ }
2224
+ pairingStore.update("connect_failed") { $0.onConnectAttemptFailed() }
2225
+ return .retry
2226
+ }
2227
+
2228
+ /// Internal so native tests can feed CoreBluetooth errors.
2229
+ /// - Returns: true when the caller must not reconnect.
2230
+ func stopAfterConnectFailure(_ error: Error?) -> Bool {
2231
+ switch classifyConnectFailure(error) {
2232
+ case .retry:
2233
+ return false
2234
+ case .backoff:
2235
+ if !isKilled { handleReconnection() }
2236
+ return true
2237
+ case .stop:
2238
+ return true
2239
+ }
2240
+ }
2241
+
2242
+ /// Error 14 on an explicit attempt: show the forget-in-Settings screen once per attempt.
2243
+ private func promptToForgetStaleIosBond() {
2244
+ cancelPendingReconnect(reason: "stale_ios_bond")
2245
+ let now = Date().timeIntervalSince1970
2246
+ let promptedAt = UserDefaults.standard.double(forKey: Self.staleIosBondPromptedAtKey)
2247
+ guard MentraLiveConnectionAttemptPolicy.shouldPromptToForgetStaleIosBond(
2248
+ peerRemovedPairingInformation: true,
2249
+ promptedAt: promptedAt,
2250
+ now: now
2251
+ ) else {
2252
+ pairFlow("stale_ios_bond", "prompt=suppressed")
2253
+ return
2254
+ }
2255
+ UserDefaults.standard.set(now, forKey: Self.staleIosBondPromptedAtKey)
2256
+ pairFlow("stale_ios_bond", "prompt=forget_bluetooth code=\(MentraLiveConnectionAttemptPolicy.iosForgetPairingCode)")
2257
+ Bridge.sendPairFailureEvent(
2258
+ "errors:pairingCouldNotStart",
2259
+ code: MentraLiveConnectionAttemptPolicy.iosForgetPairingCode
2260
+ )
2261
+ }
2262
+
2263
+ /// The saved glasses run secure-pairing firmware, learned from their last `pairing_info`.
2264
+ /// Legacy firmware never rejects a non-owner on purpose, so its failures are not owner loss.
2265
+ private func isSavedGlassesSecureFirmware() -> Bool {
2266
+ DeviceStore.shared.get("bluetooth", "mentra_live_secure_firmware") as? Bool == true
2267
+ }
2268
+
2269
+ /// Remember what the connected glasses reported so later rejections can be read correctly.
2270
+ private func rememberSecureFirmware(_ secure: Bool) {
2271
+ guard isSavedGlassesSecureFirmware() != secure else { return }
1819
2272
  Task { @MainActor in
1820
- DeviceStore.shared.apply("bluetooth", "default_wearable", "")
1821
- DeviceStore.shared.apply("bluetooth", "device_name", "")
1822
- DeviceStore.shared.apply("bluetooth", "device_address", "")
2273
+ DeviceStore.shared.apply("bluetooth", "mentra_live_secure_firmware", secure)
2274
+ }
2275
+ Bridge.saveSetting("mentra_live_secure_firmware", secure)
2276
+ }
2277
+
2278
+ /// One authentication-type failure. The state machine decides whether it settles a takeover
2279
+ /// (the one verification after `OWNER_CHANGED`) or completes the 3-strike streak.
2280
+ /// - Returns: true when this phone is now `pairing_rejected`.
2281
+ @discardableResult
2282
+ private func recordAuthRejection(reason: String) -> Bool {
2283
+ let explicitAttempt = isExplicitPairingAttempt()
2284
+ let secureFirmware = isSavedGlassesSecureFirmware()
2285
+ let transition = pairingStore.update(reason) {
2286
+ $0.onAuthRejection(
2287
+ secureFirmware: secureFirmware,
2288
+ explicitAttempt: explicitAttempt,
2289
+ nowMs: MentraLivePairingStateStore.nowMs()
2290
+ )
2291
+ }
2292
+ Bridge.log("LIVE: Auth rejection (\(reason)) — \(transition.note)")
2293
+ applyPairingTransition(transition)
2294
+ return transition.effect == .reject
2295
+ }
2296
+
2297
+ /// A restarted app keeps the pause until its deadline and keeps a rejection.
2298
+ private func restorePairingState() {
2299
+ let savedName = UserDefaults.standard.string(forKey: PREFS_DEVICE_NAME) ?? ""
2300
+ guard let transition = pairingStore.ensureRestored(savedDeviceId: savedName) else {
2301
+ if pairingStore.isPaused {
2302
+ armPairingPauseTimer()
2303
+ startPairingWatchScan(reason: "manager_init")
2304
+ }
2305
+ return
2306
+ }
2307
+ if transition.effect == .pause {
2308
+ armPairingPauseTimer()
2309
+ startPairingWatchScan(reason: "restored_pause")
1823
2310
  }
1824
- Bridge.saveSetting("default_wearable", "")
1825
- Bridge.saveSetting("device_name", "")
1826
- Bridge.saveSetting("device_address", "")
1827
- Bridge.sendTypedMessage("owner_replaced", body: ["reason": reason])
1828
2311
  }
1829
2312
 
1830
2313
  func connectById(_ deviceName: String) {
1831
- if pairingYieldActive {
1832
- Bridge.log("LIVE: connectById blocked — pairing yield active")
2314
+ // A destroyed manager stays inert; DeviceManager builds a new one for the next connect.
2315
+ if isKilled {
2316
+ pairFlow("connect_by_id", "blocked reason=manager_killed name=\(deviceName)")
1833
2317
  return
1834
2318
  }
1835
- Bridge.log("connectById: \(deviceName)")
2319
+ if !isExplicitPairingAttempt() {
2320
+ pairingStore.update("connect_by_id") { $0.bindDevice(deviceName) }
2321
+ }
2322
+ if automaticConnectBlocked() {
2323
+ // Paused for a pairing window or rejected. Keep the saved glasses; a pause watches
2324
+ // the advertisement and resumes on its own, a rejection waits for Pair again.
2325
+ UserDefaults.standard.set(deviceName, forKey: PREFS_DEVICE_NAME)
2326
+ pairFlow("connect_by_id", "deferred state=\(pairingStore.describe()) name=\(deviceName)")
2327
+ if pairingStore.isPaused {
2328
+ armPairingPauseTimer()
2329
+ startPairingWatchScan(reason: "connect_by_id")
2330
+ }
2331
+ return
2332
+ }
2333
+ pairFlow("connect_by_id", "name=\(deviceName)")
1836
2334
  cancelPendingReconnect(reason: "connect_by_id")
1837
2335
  // Save the device name for future reconnection
1838
2336
  UserDefaults.standard.set(deviceName, forKey: PREFS_DEVICE_NAME)
1839
2337
 
1840
- // Start scanning to find this specific device
1841
2338
  if centralManager == nil {
1842
2339
  centralManager = CBCentralManager(
1843
2340
  delegate: self, queue: bluetoothQueue,
@@ -1845,37 +2342,111 @@ class MentraLive: NSObject, SGCManager {
1845
2342
  )
1846
2343
  }
1847
2344
 
1848
- // Check for already-connected peripherals first
1849
- let connectedPeripherals = centralManager!.retrieveConnectedPeripherals(withServices: [
1850
- SERVICE_UUID,
1851
- ])
1852
- for peripheral in connectedPeripherals {
1853
- Bridge.log("Found already-connected peripheral: \(peripheral.name ?? "Unknown")")
1854
- if let name = peripheral.name,
1855
- name == "Xy_A" || name.hasPrefix("XyBLE_") || name.hasPrefix("MENTRA_LIVE_BLE")
1856
- || name.hasPrefix("MENTRA_LIVE_BT") || name.lowercased().hasPrefix("mentra_live")
2345
+ attachKnownOrScan(deviceName)
2346
+ }
2347
+
2348
+ /// Connect the peripheral this phone already found. After the BLE bond the
2349
+ /// glasses stop general advertising, so a new name scan never sees them.
2350
+ private func attachKnownOrScan(_ deviceName: String) {
2351
+ if isConnecting {
2352
+ pairFlow("attach", "decision=already_connecting name=\(deviceName)")
2353
+ return
2354
+ }
2355
+ if txCharacteristic != nil, connectedPeripheral?.name == deviceName {
2356
+ pairFlow(
2357
+ "attach",
2358
+ "decision=live_gatt id=\(connectedPeripheral?.identifier.uuidString ?? "-") name=\(deviceName)"
2359
+ )
2360
+ return
2361
+ }
2362
+
2363
+ let poweredOn = centralManager?.state == .poweredOn
2364
+ let cached = discoveredPeripherals[deviceName]
2365
+ let savedId = savedPeripheralId(for: deviceName)
2366
+ let systemMatch = poweredOn ? systemConnectedPeripheral(deviceName: deviceName, savedId: savedId) : nil
2367
+ let route = MentraLiveKnownConnectRoute.decide(
2368
+ bluetoothPoweredOn: poweredOn,
2369
+ hasCachedPeripheral: cached != nil,
2370
+ hasSavedIdentifier: savedId != nil,
2371
+ systemConnectedMatch: systemMatch != nil
2372
+ )
2373
+ pairFlow(
2374
+ "attach",
2375
+ "decision=\(route.rawValue) name=\(deviceName) cached=\(cached != nil) savedId=\(savedId?.uuidString ?? "-") system=\(systemMatch?.identifier.uuidString ?? "-") central=\(centralManager?.state.rawValue ?? -1)"
2376
+ )
2377
+
2378
+ switch route {
2379
+ case .waitForPower:
2380
+ return
2381
+ case .cachedPeripheral:
2382
+ if let cached {
2383
+ connectToDevice(cached)
2384
+ }
2385
+ case .savedIdentifier:
2386
+ if let savedId,
2387
+ let peripheral = centralManager?.retrievePeripherals(withIdentifiers: [savedId]).first
1857
2388
  {
1858
- Bridge.log("Found already-connected peripheral: \(name)")
1859
- discoveredPeripherals[name] = peripheral
1860
- emitDiscoveredDeviceFromCache(name)
2389
+ rememberPeripheral(peripheral, name: deviceName)
2390
+ discoveredPeripherals[deviceName] = peripheral
2391
+ connectToDevice(peripheral)
2392
+ } else {
2393
+ pairFlow("attach", "decision=saved_identifier_missing id=\(savedId?.uuidString ?? "-") fallback=scan")
2394
+ startScan(reason: "saved_identifier_missing")
2395
+ }
2396
+ case .alreadyConnected:
2397
+ if let systemMatch {
2398
+ let matchedName = systemMatch.name ?? deviceName
2399
+ discoveredPeripherals[matchedName] = systemMatch
2400
+ rememberPeripheral(systemMatch, name: deviceName)
2401
+ connectToDevice(systemMatch)
2402
+ }
2403
+ case .scan:
2404
+ if isScanning {
2405
+ pairFlow("attach", "decision=already_scanning name=\(deviceName)")
2406
+ return
2407
+ }
2408
+ startScan(reason: "no_known_peripheral")
2409
+ }
2410
+ }
1861
2411
 
1862
- // Check if this is the device we want
1863
- if let savedDeviceName = UserDefaults.standard.string(
1864
- forKey: PREFS_DEVICE_NAME
1865
- ),
1866
- savedDeviceName == name
1867
- {
1868
- Bridge.log(
1869
- "Found our remembered device already connected, connecting: \(name)"
1870
- )
1871
- connectToDevice(peripheral)
1872
- return
1873
- }
2412
+ private func savedPeripheralId(for name: String) -> UUID? {
2413
+ let map = UserDefaults.standard.dictionary(forKey: PREFS_PERIPHERAL_IDS) as? [String: String]
2414
+ guard let raw = map?[name] else {
2415
+ return nil
2416
+ }
2417
+ return UUID(uuidString: raw)
2418
+ }
2419
+
2420
+ private func rememberPeripheral(_ peripheral: CBPeripheral, name: String) {
2421
+ var map = UserDefaults.standard.dictionary(forKey: PREFS_PERIPHERAL_IDS) as? [String: String] ?? [:]
2422
+ map[name] = peripheral.identifier.uuidString
2423
+ UserDefaults.standard.set(map, forKey: PREFS_PERIPHERAL_IDS)
2424
+ }
2425
+
2426
+ private func systemConnectedPeripheral(deviceName: String, savedId: UUID?) -> CBPeripheral? {
2427
+ let connected = centralManager?.retrieveConnectedPeripherals(withServices: [SERVICE_UUID]) ?? []
2428
+ pairFlow("system_connected", "count=\(connected.count)")
2429
+ for peripheral in connected {
2430
+ let name = peripheral.name ?? "-"
2431
+ let matches = MentraLivePendingPairingTarget.matches(
2432
+ connectedName: peripheral.name ?? "",
2433
+ connectedIdentifier: peripheral.identifier.uuidString,
2434
+ pendingName: deviceName,
2435
+ pendingIdentifier: savedId?.uuidString ?? ""
2436
+ )
2437
+ pairFlow(
2438
+ "system_connected",
2439
+ "name=\(name) id=\(peripheral.identifier.uuidString) match=\(matches)"
2440
+ )
2441
+ if matches {
2442
+ return peripheral
1874
2443
  }
1875
2444
  }
2445
+ return nil
2446
+ }
1876
2447
 
1877
- // Will connect when found during scan
1878
- startScan()
2448
+ private func pairFlow(_ event: String, _ detail: String) {
2449
+ Bridge.log("PAIRFLOW: \(event) \(detail)")
1879
2450
  }
1880
2451
 
1881
2452
  func getConnectedBluetoothName() -> String? {
@@ -1887,7 +2458,10 @@ class MentraLive: NSObject, SGCManager {
1887
2458
  Bridge.log("LIVE: disconnect deferred — waiting for unpair write")
1888
2459
  return
1889
2460
  }
1890
- Bridge.log("LIVE: disconnect() -Disconnecting from Mentra Live glasses")
2461
+ pairFlow(
2462
+ "disconnect",
2463
+ "name=\(connectedPeripheral?.name ?? "-") id=\(connectedPeripheral?.identifier.uuidString ?? "-") scanning=\(isScanning) connecting=\(isConnecting)"
2464
+ )
1891
2465
 
1892
2466
  // if rgbLedAuthorityClaimed {
1893
2467
  // sendRgbLedControlAuthority(false)
@@ -2201,6 +2775,8 @@ class MentraLive: NSObject, SGCManager {
2201
2775
  return commands.removeFirst()
2202
2776
  }
2203
2777
 
2778
+ var count: Int { commands.count }
2779
+
2204
2780
  /// Discards the run of writes from earlier wire-session generations at the head of
2205
2781
  /// the queue in one pass and dequeues the first current one. Stale writes are never
2206
2782
  /// sent, so they must not each cost a drain tick: a burst of epoch resets would
@@ -2217,6 +2793,8 @@ class MentraLive: NSObject, SGCManager {
2217
2793
  }
2218
2794
  }
2219
2795
 
2796
+ var pendingBleCommandCount: Int { commandQueue.count }
2797
+
2220
2798
  private func setupCommandQueue() {
2221
2799
  Task.detached { [weak self] in
2222
2800
  guard let self else { return }
@@ -2331,25 +2909,26 @@ class MentraLive: NSObject, SGCManager {
2331
2909
 
2332
2910
  // MARK: - BLE Scanning
2333
2911
 
2334
- private func startScan() {
2335
- if pairingYieldActive {
2336
- Bridge.log("LIVE: startScan blocked — pairing yield active")
2337
- return
2338
- }
2339
-
2912
+ private func startScan(reason: String = "scan") {
2340
2913
  guard centralManager!.state == .poweredOn else {
2341
- Bridge.log("Attempting to scan but bluetooth is not powered on.")
2914
+ pairFlow("scan", "blocked reason=bluetooth_off trigger=\(reason) central=\(centralManager?.state.rawValue ?? -1)")
2342
2915
  return
2343
2916
  }
2344
2917
 
2345
- Bridge.log("Starting BLE scan for Mentra Live glasses")
2918
+ pairFlow("scan", "start trigger=\(reason) target=\(UserDefaults.standard.string(forKey: PREFS_DEVICE_NAME) ?? "-")")
2346
2919
  discoveredAdvPairing.removeAll()
2920
+ loggedUnnamedDiscoveries.removeAll()
2347
2921
  isScanning = true
2922
+ pairingWatchScanActive = false
2348
2923
 
2349
2924
  startReadinessCheckLoop()
2350
2925
 
2926
+ // The choose-glasses scan has to hear a later advertisement when the glasses
2927
+ // enter pairing mode. iOS reports each peripheral once unless duplicates are
2928
+ // allowed, so the row would stay "Not in pairing mode". Reconnect scans stay
2929
+ // duplicate-free so a saved glasses advertisement cannot start another connect.
2351
2930
  let scanOptions: [String: Any] = [
2352
- CBCentralManagerScanOptionAllowDuplicatesKey: false,
2931
+ CBCentralManagerScanOptionAllowDuplicatesKey: manualDiscoveryActive,
2353
2932
  ]
2354
2933
 
2355
2934
  // let knownPeripherals = centralManager?.retrieveConnectedPeripherals(withServices: [SERVICE_UUID])
@@ -2383,18 +2962,24 @@ class MentraLive: NSObject, SGCManager {
2383
2962
  centralManager?.stopScan()
2384
2963
  isScanning = false
2385
2964
  DeviceStore.shared.apply(ObservableStore.bluetoothCategory, "searching", false)
2386
- Bridge.log("LIVE: BLE scan stopped")
2965
+ pairFlow("scan", "stop")
2387
2966
  }
2388
2967
 
2389
2968
  // MARK: - Connection Management
2390
2969
 
2391
2970
  private func connectToDevice(_ peripheral: CBPeripheral) {
2392
- if pairingYieldActive {
2393
- Bridge.log("LIVE: connectToDevice blocked — pairing yield active")
2971
+ if automaticConnectBlocked() {
2972
+ pairFlow(
2973
+ "connect_device",
2974
+ "blocked state=\(pairingStore.describe()) id=\(peripheral.identifier.uuidString)"
2975
+ )
2394
2976
  isConnecting = false
2395
2977
  return
2396
2978
  }
2397
- Bridge.log("LIVE: Connecting to device: \(peripheral.identifier.uuidString)")
2979
+ pairFlow(
2980
+ "connect_device",
2981
+ "id=\(peripheral.identifier.uuidString) name=\(peripheral.name ?? "-") state=\(peripheral.state.rawValue)"
2982
+ )
2398
2983
 
2399
2984
  // A timed attempt supersedes any pending reconnect: withdraw one aimed at other
2400
2985
  // glasses, and drop tracking for this one so its settle timer cannot touch this attempt.
@@ -2425,7 +3010,8 @@ class MentraLive: NSObject, SGCManager {
2425
3010
  guard let centralManager,
2426
3011
  MentraLiveConnectionAttemptPolicy.shouldReconnectDirectly(
2427
3012
  isKilled: isKilled,
2428
- pairingYieldActive: pairingYieldActive,
3013
+ // A window just ended: scan first so its advertisement is read.
3014
+ pairingYieldActive: automaticConnectBlocked() || pairingStore.awaitingTakeoverCheck,
2429
3015
  bluetoothPoweredOn: centralManager.state == .poweredOn,
2430
3016
  peripheralName: peripheral.name,
2431
3017
  savedDeviceName: UserDefaults.standard.string(forKey: PREFS_DEVICE_NAME)
@@ -2456,9 +3042,13 @@ class MentraLive: NSObject, SGCManager {
2456
3042
  // The default requirement lets the system complete that authorization flow
2457
3043
  // before the glasses subscribe; apps that do not relay notifications can opt out.
2458
3044
  Bridge.log("LIVE: ANCS connection requirement \(requiresAncs ? "enabled" : "disabled")")
3045
+ Bridge.log("LIVE: Transport bridging \(Self.enableTransportBridging ? "enabled" : "disabled")")
2459
3046
  centralManager?.connect(
2460
3047
  peripheral,
2461
- options: MentraLiveConnectionOptions.coreBluetoothOptions(requiresAncs: requiresAncs)
3048
+ options: MentraLiveConnectionOptions.coreBluetoothOptions(
3049
+ requiresAncs: requiresAncs,
3050
+ enableTransportBridging: Self.enableTransportBridging
3051
+ )
2462
3052
  )
2463
3053
  #endif
2464
3054
  }
@@ -2546,8 +3136,11 @@ class MentraLive: NSObject, SGCManager {
2546
3136
  return
2547
3137
  }
2548
3138
 
2549
- if pairingYieldActive {
2550
- Bridge.log("LIVE: Reconnection aborted - pairing yield active")
3139
+ if automaticConnectBlocked() {
3140
+ Bridge.log("LIVE: Reconnection aborted - pairing state \(pairingStore.describe())")
3141
+ if pairingStore.isPaused {
3142
+ startPairingWatchScan(reason: "reconnect_while_paused")
3143
+ }
2551
3144
  return
2552
3145
  }
2553
3146
 
@@ -2584,8 +3177,8 @@ class MentraLive: NSObject, SGCManager {
2584
3177
  guard let self = self else { return }
2585
3178
 
2586
3179
  // Use peripheral presence, not connectionState: we stay CONNECTING during backoff until scan/connect.
2587
- if self.pairingYieldActive {
2588
- Bridge.log("LIVE: Reconnection aborted - pairing yield active")
3180
+ if self.automaticConnectBlocked() {
3181
+ Bridge.log("LIVE: Reconnection aborted - pairing state \(self.pairingStore.describe())")
2589
3182
  return
2590
3183
  }
2591
3184
  if self.connectedPeripheral == nil, !self.isKilled {
@@ -2634,6 +3227,7 @@ class MentraLive: NSObject, SGCManager {
2634
3227
  private func attachL2capFileChannel(_ channel: CBL2CAPChannel) {
2635
3228
  closeL2capFileChannel()
2636
3229
 
3230
+ guard let peer = connectedPeripheral, let token = notificationIngress.capture(peer) else { return }
2637
3231
  let channelId = UUID()
2638
3232
  l2capFileChannelId = channelId
2639
3233
  let reader = MentraLiveL2capChannel(
@@ -2643,7 +3237,7 @@ class MentraLive: NSObject, SGCManager {
2643
3237
  // while the existing transfer state remains serialized on the main actor.
2644
3238
  DispatchQueue.main.async {
2645
3239
  guard let self, self.l2capFileChannelId == channelId else { return }
2646
- self.processReceivedData(frame)
3240
+ self.receiveBleNotification(frame, token: token)
2647
3241
  }
2648
3242
  },
2649
3243
  onClose: { [weak self] in
@@ -2819,10 +3413,10 @@ class MentraLive: NSObject, SGCManager {
2819
3413
 
2820
3414
  switch type {
2821
3415
  case "glasses_ready":
2822
- // A queued glasses_ready from the connection we just cancelled for yield
2823
- // must not close the pairing window. Only accept readiness on a live GATT.
2824
- if pairingYieldActive && connectedPeripheral == nil {
2825
- Bridge.log("LIVE: Ignoring stale glasses_ready during pairing yield")
3416
+ // A queued glasses_ready from the connection just left for a pairing window
3417
+ // must not count as a session. Only accept readiness on a live GATT.
3418
+ if pairingStore.isPaused && connectedPeripheral == nil {
3419
+ Bridge.log("LIVE: Ignoring stale glasses_ready during pairing pause")
2826
3420
  return
2827
3421
  }
2828
3422
  let sid = (json["sid"] as? String).flatMap { $0.isEmpty ? nil : $0 }
@@ -2840,10 +3434,6 @@ class MentraLive: NSObject, SGCManager {
2840
3434
  // framing regardless of what this side negotiated earlier. Start a fresh
2841
3435
  // wire epoch (clears v2-active state that would otherwise gate the
2842
3436
  // handshake off), then negotiate from the caps this message advertises.
2843
- pairingYieldAwaitingReclaim = false
2844
- pairingYieldActive = false
2845
- pairingYieldEndWorkItem?.cancel()
2846
- pairingYieldEndWorkItem = nil
2847
3437
  resetWireNegotiationState()
2848
3438
  parsePeerWireCaps(json)
2849
3439
  maybeSendWireHandshake()
@@ -3039,25 +3629,113 @@ class MentraLive: NSObject, SGCManager {
3039
3629
  Bridge.log("LIVE: Received pong response - connection healthy")
3040
3630
 
3041
3631
  case "entering_pairing_mode":
3042
- let windowMs = max(5000, min(180_000, json["window_ms"] as? Int ?? 120_000))
3043
- Bridge.log("LIVE: Glasses entering pairing mode — yield \(windowMs)ms (no forget)")
3044
- enterPairingYield(windowMs: windowMs)
3045
- let body: [String: Any] = [
3046
- "window_ms": windowMs,
3047
- "reason": json["reason"] as? String ?? "user_gesture",
3632
+ let windowMs = json["window_ms"] as? Int
3633
+ let windowId = json["window_id"] as? Int
3634
+ let ownerRetained = json["owner_retained"] as? Bool ?? false
3635
+ let enterReason = json["reason"] as? String ?? "user_gesture"
3636
+ Bridge.log(
3637
+ "PAIRFLOW: entering_pairing_mode reason=\(enterReason) window_ms=\(windowMs ?? -1) window_id=\(windowId ?? -1) owner_retained=\(ownerRetained)"
3638
+ )
3639
+ var enterBody: [String: Any] = [
3640
+ "window_ms": windowMs ?? MentraLiveConnectionAttemptPolicy.defaultPairingWindowMs,
3641
+ "reason": enterReason,
3642
+ "owner_retained": ownerRetained,
3048
3643
  ]
3049
- Bridge.sendTypedMessage("entering_pairing_mode", body: body)
3644
+ if let windowId { enterBody["window_id"] = windowId }
3645
+ Bridge.sendTypedMessage("entering_pairing_mode", body: enterBody)
3646
+ let explicitAttempt = isExplicitPairingAttempt()
3647
+ let deviceId = connectedPeripheral?.name ?? UserDefaults.standard.string(forKey: PREFS_DEVICE_NAME) ?? ""
3648
+ let enterTransition = pairingStore.update("entering_pairing_mode") {
3649
+ $0.onEnteringPairingMode(
3650
+ windowMs: windowMs,
3651
+ windowId: windowId,
3652
+ ownerRetained: ownerRetained,
3653
+ explicitAttempt: explicitAttempt,
3654
+ deviceId: deviceId,
3655
+ nowMs: MentraLivePairingStateStore.nowMs()
3656
+ )
3657
+ }
3658
+ applyPairingTransition(enterTransition)
3659
+
3660
+ case "pairing_mode_ended":
3661
+ let endedReason = json["reason"] as? String
3662
+ let endedWindowId = json["window_id"] as? Int
3663
+ Bridge.log("PAIRFLOW: pairing_mode_ended reason=\(endedReason ?? "-") window_id=\(endedWindowId ?? -1)")
3664
+ var endedBody: [String: Any] = ["reason": endedReason ?? ""]
3665
+ if let endedWindowId { endedBody["window_id"] = endedWindowId }
3666
+ Bridge.sendTypedMessage("pairing_mode_ended", body: endedBody)
3667
+ let endedTransition = pairingStore.update("pairing_mode_ended") {
3668
+ $0.onPairingModeEnded(reason: endedReason, windowId: endedWindowId)
3669
+ }
3670
+ applyPairingTransition(endedTransition)
3050
3671
 
3051
3672
  case "pairing_info":
3673
+ Bridge.log(
3674
+ "PAIRFLOW: pairing_info secure=\(json["secure_pairing_capable"] as? Bool ?? false) classic_ready=\(json["classic_bond_ready"] as? Bool ?? false) had_previous=\(json["had_previous_bond"] as? Bool ?? false) transfer=\(json["ownership_transfer"] as? Bool ?? false) owner_committed=\(json["owner_committed"] as? Bool ?? false) auto_audio=\(json["auto_audio"] as? Bool ?? false) code=<redacted>"
3675
+ )
3676
+ let ownerCommitted = json["owner_committed"] as? Bool == true
3677
+ // Legacy firmware that omits this field is not secure-capable.
3678
+ let securePairingCapable = json["secure_pairing_capable"] as? Bool ?? false
3679
+ // Read before any readiness below: the audio wait of a pairing depends on it.
3680
+ pairingInfoAutoAudio = json["auto_audio"] as? Bool ?? false
3681
+ rememberSecureFirmware(securePairingCapable)
3682
+ if securePairingCapable {
3683
+ pairingInfoSeenThisSession = true
3684
+ cancelSecureFirmwareRefresh()
3685
+ sendPairingSessionMessages(reason: "pairing_info")
3686
+ }
3687
+ // Readiness parked on an unknown capability: this pairing_info decides the rule.
3688
+ var legacyReadiness = false
3689
+ if awaitingPairingInfoForUnknownCapability {
3690
+ cancelUnknownCapabilityWait()
3691
+ if securePairingCapable {
3692
+ pairFlow("readiness", "capability=unknown pairing_info=secure action=await_owner_commit")
3693
+ awaitingSecurePairingConfirmation = true
3694
+ if !ownerCommitted { armSecurePairingWait() }
3695
+ } else {
3696
+ pairFlow("readiness", "capability=unknown pairing_info=legacy action=ready")
3697
+ legacyReadiness = true
3698
+ }
3699
+ }
3700
+ // Only owner_committed proves the bond. secure_pairing_capable is a capability flag
3701
+ // readable on the unencrypted window session.
3702
+ if MentraLiveConnectionAttemptPolicy.pairingInfoConfirmsOwner(ownerCommitted: ownerCommitted) {
3703
+ securePairingConfirmed = true
3704
+ cancelSecurePairingWait()
3705
+ if awaitingSecurePairingConfirmation {
3706
+ Bridge.log("LIVE: pairing_info owner_committed — reporting ready")
3707
+ markFullyBooted()
3708
+ }
3709
+ }
3710
+ if legacyReadiness { markFullyBooted() }
3052
3711
  Bridge.sendPairingInfo(
3053
3712
  hadPreviousBond: json["had_previous_bond"] as? Bool ?? false,
3054
3713
  pairingCode: json["pairing_code"] as? String,
3055
3714
  classicBondReady: json["classic_bond_ready"] as? Bool ?? false,
3056
- // Legacy firmware that omits this field is not secure-capable.
3057
- securePairingCapable: json["secure_pairing_capable"] as? Bool ?? false,
3058
- protocolVersion: json["protocol_version"] as? Int ?? 1
3715
+ securePairingCapable: securePairingCapable,
3716
+ protocolVersion: json["protocol_version"] as? Int ?? 1,
3717
+ ownershipTransfer: json["ownership_transfer"] as? Bool ?? false,
3718
+ ownerCommitted: ownerCommitted,
3719
+ autoAudio: json["auto_audio"] as? Bool
3059
3720
  )
3060
3721
 
3722
+ case "classic_link":
3723
+ // The glasses' own view of the phone's A2DP and HFP links to them. Preferred over
3724
+ // the phone's audio route, which another Bluetooth audio device can hold.
3725
+ let a2dp = json["a2dp"] as? Bool ?? false
3726
+ let hfp = json["hfp"] as? Bool ?? false
3727
+ pairFlow("classic_link", "a2dp=\(a2dp) hfp=\(hfp)")
3728
+ audioSetup.classicLink(a2dp: a2dp, hfp: hfp)
3729
+ refreshAudioSetup(trigger: "classic_link")
3730
+ #if !os(macOS)
3731
+ if !AudioSessionMonitor.glassesReportClassicLink {
3732
+ // From now on the phone signals come from passive route observation, never
3733
+ // from the category probe. Re-read them that way.
3734
+ AudioSessionMonitor.glassesReportClassicLink = true
3735
+ DeviceManager.shared.checkCurrentAudioDevice()
3736
+ }
3737
+ #endif
3738
+
3061
3739
  case "imu_response", "imu_stream_response", "imu_gesture_response",
3062
3740
  "imu_gesture_subscribed", "imu_ack", "imu_error":
3063
3741
  // Handle IMU-related responses
@@ -3098,6 +3776,11 @@ class MentraLive: NSObject, SGCManager {
3098
3776
  Bridge.log("LIVE: 📱 Received ota_start_ack from glasses")
3099
3777
  Bridge.sendOtaStartAck()
3100
3778
 
3779
+ case "bes_crash_detected", "bes_crash_reported_ack":
3780
+ let ok = json["ok"].map { "\($0)" } ?? "-"
3781
+ Bridge.log("LIVE: \(type) incidentKey=\(json["incidentKey"] as? String ?? "") state=\(json["state"] as? String ?? "-") ok=\(ok)")
3782
+ Bridge.sendTypedMessage(type, body: json)
3783
+
3101
3784
  case "ota_status":
3102
3785
  // Short keys (sid/ts/cs/st/sq/sp/op/err) are used by new firmware to keep BLE payload small.
3103
3786
  // Verbose keys (session_id/total_steps/…) are the fallback for older firmware.
@@ -3237,6 +3920,7 @@ class MentraLive: NSObject, SGCManager {
3237
3920
  )
3238
3921
  }
3239
3922
  if let bluetoothMacAddress = nonEmptyStringValue(fields, "bt_mac_address") {
3923
+ recordWifiAdbPeerIdentity(bluetoothMacAddress)
3240
3924
  DeviceStore.shared.apply("glasses", "bluetoothMacAddress", bluetoothMacAddress)
3241
3925
  }
3242
3926
  if let wifiMacAddress = nonEmptyStringValue(fields, "wifi_mac_address") {
@@ -3718,6 +4402,66 @@ class MentraLive: NSObject, SGCManager {
3718
4402
  sendJson(json, wakeUp: true)
3719
4403
  }
3720
4404
 
4405
+ @discardableResult func beginBleNotificationSession(source: AnyObject?) -> MentraLiveNotificationIngress.Token? {
4406
+ wifiAdbPeerIdentity = nil
4407
+ incomingChunkReassembler.clear()
4408
+ resetWireNegotiationState()
4409
+ commandQueue.removeAll()
4410
+ return notificationIngress.begin(source)
4411
+ }
4412
+
4413
+ func endBleNotificationSession() {
4414
+ wifiAdbPeerIdentity = nil
4415
+ incomingChunkReassembler.clear()
4416
+ resetWireNegotiationState()
4417
+ commandQueue.removeAll()
4418
+ _ = notificationIngress.begin(nil)
4419
+ }
4420
+
4421
+ func receiveBleNotification(_ data: Data, token: MentraLiveNotificationIngress.Token) {
4422
+ guard notificationIngress.current(token) else { return }
4423
+ let previous = receivingNotification
4424
+ receivingNotification = token
4425
+ defer { receivingNotification = previous }
4426
+ processReceivedData(data)
4427
+ }
4428
+
4429
+ private func recordWifiAdbPeerIdentity(_ mac: String) {
4430
+ guard let token = receivingNotification, notificationIngress.current(token) else { return }
4431
+ wifiAdbPeerIdentity = (mac, token)
4432
+ }
4433
+
4434
+ private func currentWifiAdbAdmission(_ admission: WifiAdbAdmission) -> Bool {
4435
+ notificationIngress.current(admission.identity.token) && wireSessionGeneration == admission.wireEpoch &&
4436
+ wifiAdbPeerIdentity?.mac == admission.identity.mac && wifiAdbLinkReady
4437
+ }
4438
+
4439
+ var wifiAdbLinkReady: Bool {
4440
+ connectionState == ConnTypes.CONNECTED && connectedPeripheral?.state == .connected && txCharacteristic != nil
4441
+ }
4442
+
4443
+ func enqueueWifiAdbState(_ enabled: Bool) -> Bool {
4444
+ // Match Wi-Fi forget: public log delegates must not reenter between validation and enqueue.
4445
+ sendJson(["type": "set_wifi_adb_state", "enabled": enabled], wakeUp: true, requireAck: true, bridgeLogging: false)
4446
+ }
4447
+
4448
+ /// MainActor performs identity validation and queue insertion without suspension.
4449
+ func sendWifiAdbState(_ enabled: Bool, expectedBluetoothMac: String) throws {
4450
+ guard expectedBluetoothMac.range(of: "^(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$", options: .regularExpression) != nil,
4451
+ let identity = wifiAdbPeerIdentity,
4452
+ identity.mac.caseInsensitiveCompare(expectedBluetoothMac) == .orderedSame,
4453
+ notificationIngress.current(identity.token), wifiAdbLinkReady else {
4454
+ throw BluetoothSdkError(code: "device_identity_changed", message: "The selected glasses identity or connection changed.")
4455
+ }
4456
+ let admission = WifiAdbAdmission(identity: identity, wireEpoch: wireSessionGeneration)
4457
+ wifiAdbAdmission = admission
4458
+ defer { wifiAdbAdmission = nil }
4459
+ guard enqueueWifiAdbState(enabled), !admission.refused, admission.queued > 0,
4460
+ currentWifiAdbAdmission(admission) else {
4461
+ throw BluetoothSdkError(code: "command_send_failed", message: "Could not queue Wi-Fi debugging for the selected glasses.")
4462
+ }
4463
+ }
4464
+
3721
4465
  func sendWifiAdbState(_ enabled: Bool) {
3722
4466
  Bridge.log("LIVE: 🔧 Sending Wi-Fi ADB state: \(enabled)")
3723
4467
 
@@ -3778,12 +4522,14 @@ class MentraLive: NSObject, SGCManager {
3778
4522
  }
3779
4523
  let bKey = MentraLive.incidentBleFileBase(incidentId: incidentId, prefix: "B")
3780
4524
  let lKey = MentraLive.incidentBleFileBase(incidentId: incidentId, prefix: "L")
3781
- bleIncidentLogRelays[bKey] = BleIncidentLogRelayEntry(
3782
- fileBaseKey: bKey, incidentId: incidentId, apiBaseUrl: base, kind: .firmware
4525
+ let now = incidentRelayClock()
4526
+ let bRelay = BleIncidentLogRelayEntry(
4527
+ fileBaseKey: bKey, incidentId: incidentId, apiBaseUrl: base, kind: .firmware, reservedAt: now
3783
4528
  )
3784
- bleIncidentLogRelays[lKey] = BleIncidentLogRelayEntry(
3785
- fileBaseKey: lKey, incidentId: incidentId, apiBaseUrl: base, kind: .logcat
4529
+ let lRelay = BleIncidentLogRelayEntry(
4530
+ fileBaseKey: lKey, incidentId: incidentId, apiBaseUrl: base, kind: .logcat, reservedAt: now
3786
4531
  )
4532
+ try reserveIncidentRelays([bRelay, lRelay], now: now)
3787
4533
 
3788
4534
  let auth: [String: Any] = [
3789
4535
  "type": "auth_token", "coreToken": coreToken,
@@ -3794,13 +4540,56 @@ class MentraLive: NSObject, SGCManager {
3794
4540
  sendJson(["type": "upload_incident_logs", "incidentId": incidentId, "apiBaseUrl": base],
3795
4541
  wakeUp: true, requireAck: true, bridgeLogging: true)
3796
4542
  else {
3797
- bleIncidentLogRelays.removeValue(forKey: bKey)
3798
- bleIncidentLogRelays.removeValue(forKey: lKey)
4543
+ releaseIncidentRelay(bRelay)
4544
+ releaseIncidentRelay(lRelay)
3799
4545
  throw BluetoothSdkError(code: "incident_dispatch_failed", message: "Could not queue the glasses incident-log request.")
3800
4546
  }
3801
4547
  Bridge.log("LIVE: Queued incidentId to glasses for log upload: \(incidentId) (BLE relay \(bKey), \(lKey))")
3802
4548
  }
3803
4549
 
4550
+ /// The 16-character relay file names keep only 15 characters of the report id, so two reports
4551
+ /// can share them. A received file goes to the report registered under its name; refuse a
4552
+ /// second report until the owner's Cloud POST is confirmed or its ownership expires.
4553
+ private func reserveIncidentRelays(_ relays: [BleIncidentLogRelayEntry], now: TimeInterval) throws {
4554
+ for relay in relays {
4555
+ if let owner = bleIncidentLogRelays[relay.fileBaseKey],
4556
+ owner.incidentId != relay.incidentId,
4557
+ now - owner.reservedAt < MentraLive.incidentRelayOwnershipSeconds
4558
+ {
4559
+ throw BluetoothSdkError(
4560
+ code: "incident_relay_busy",
4561
+ message: "BLE relay \(relay.fileBaseKey) is still owned by report \(owner.incidentId)."
4562
+ )
4563
+ }
4564
+ }
4565
+ for relay in relays {
4566
+ bleIncidentLogRelays[relay.fileBaseKey] = relay
4567
+ }
4568
+ }
4569
+
4570
+ private func releaseIncidentRelay(_ relay: BleIncidentLogRelayEntry) {
4571
+ if bleIncidentLogRelays[relay.fileBaseKey] === relay {
4572
+ bleIncidentLogRelays.removeValue(forKey: relay.fileBaseKey)
4573
+ }
4574
+ }
4575
+
4576
+ func sendBesCrashReported(incidentKey: String, reportId: String) throws {
4577
+ guard incidentLogTransportReady else {
4578
+ throw BluetoothSdkError(code: "glasses_not_connected", message: "Cannot report the BES crash because the glasses BLE link is not ready.")
4579
+ }
4580
+ guard sendJson(["type": "bes_crash_reported", "incidentKey": incidentKey, "reportId": reportId],
4581
+ wakeUp: true, requireAck: true, bridgeLogging: true)
4582
+ else {
4583
+ throw BluetoothSdkError(code: "bes_crash_dispatch_failed", message: "Could not queue bes_crash_reported to the glasses.")
4584
+ }
4585
+ Bridge.log("LIVE: Queued bes_crash_reported incidentKey=\(incidentKey) reportId=\(reportId)")
4586
+ }
4587
+
4588
+ static func isIncidentRelayFileName(_ fileName: String) -> Bool {
4589
+ guard fileName.count == 16, let first = fileName.first, first == "B" || first == "L" else { return false }
4590
+ return fileName.dropFirst().allSatisfy { ("a" ... "z").contains($0) || ("0" ... "9").contains($0) || $0 == "_" }
4591
+ }
4592
+
3804
4593
  private static func incidentBleFileBase(incidentId: String, prefix: Character) -> String {
3805
4594
  var compact = incidentId.replacingOccurrences(of: "-", with: "").lowercased()
3806
4595
  if compact.count < 15 {
@@ -3987,6 +4776,10 @@ class MentraLive: NSObject, SGCManager {
3987
4776
  }
3988
4777
 
3989
4778
  private func handleGlassesReady() {
4779
+ pairFlow(
4780
+ "glasses_ready",
4781
+ "id=\(connectedPeripheral?.identifier.uuidString ?? "-") name=\(connectedPeripheral?.name ?? "-") gatt=\(txCharacteristic != nil)"
4782
+ )
3990
4783
  Bridge.log("LIVE: 🎉 Received glasses_ready message - SOC is booted and ready!")
3991
4784
 
3992
4785
  stopReadinessCheckLoop()
@@ -4044,11 +4837,142 @@ class MentraLive: NSObject, SGCManager {
4044
4837
  }
4045
4838
  }
4046
4839
 
4840
+ // handleDeviceReady promotes the pairing target to the default device. Secure glasses
4841
+ // own a phone only after a BLE bond and announce it with pairing_info; GATT works
4842
+ // unencrypted inside the open window, so readiness alone is not a pairing.
4843
+ let readiness = MentraLiveConnectionAttemptPolicy.readinessAtGlassesReady(
4844
+ explicitPairing: isExplicitPairingAttempt(),
4845
+ selectedCapability: selectedTargetSecureCapability(),
4846
+ securePairingInfoThisSession: pairingInfoSeenThisSession,
4847
+ securePairingConfirmed: securePairingConfirmed
4848
+ )
4849
+ switch readiness {
4850
+ case .ready:
4851
+ markFullyBooted()
4852
+ case .awaitOwnerCommit:
4853
+ Bridge.log("LIVE: glasses_ready before owner commit — waiting for pairing_info")
4854
+ awaitingSecurePairingConfirmation = true
4855
+ armSecurePairingWait()
4856
+ case .awaitPairingInfo:
4857
+ pairFlow("readiness", "capability=unknown action=await_pairing_info waitMs=\(unknownCapabilityPairingInfoWaitMs)")
4858
+ armUnknownCapabilityWait()
4859
+ }
4860
+ }
4861
+
4862
+ private func markFullyBooted() {
4863
+ // A session that reached ready means the glasses still admit this phone. Read the
4864
+ // attempt kind first: setting fullyBooted runs handleDeviceReady, which clears pending.
4865
+ let explicitAttempt = isExplicitPairingAttempt()
4866
+ pairingStore.update("session_ready") { $0.onSessionReady(explicitAttempt: explicitAttempt) }
4867
+ awaitingSecurePairingConfirmation = false
4868
+ cancelSecurePairingWait()
4869
+ cancelUnknownCapabilityWait()
4870
+ armSecureFirmwareRefresh()
4871
+ if !fullyBooted {
4872
+ audioSetup.startPhase(
4873
+ explicitAttempt ? .pairing(autoAudio: pairingInfoAutoAudio) : .reconnect,
4874
+ nowMs: audioSetupNowMs()
4875
+ )
4876
+ }
4877
+ // Publish audioSetup before readiness so the ready update never carries a stale idle.
4878
+ refreshAudioSetup(trigger: "session_ready", sessionReady: true)
4047
4879
  fullyBooted = true
4048
4880
  connected = true
4049
4881
  updateConnectionState(ConnTypes.CONNECTED)
4050
4882
  }
4051
4883
 
4884
+ /// The selected scan row's capability (`pending_device_secure_pairing_capable`); nil when
4885
+ /// unknown, for example a target re-listed from saved state.
4886
+ private func selectedTargetSecureCapability() -> Bool? {
4887
+ DeviceStore.shared.get("bluetooth", "pending_device_secure_pairing_capable") as? Bool
4888
+ }
4889
+
4890
+ /// Unknown capability: a secure pairing_info within the wait switches to the secure rule,
4891
+ /// none means legacy firmware and the glasses are reported ready.
4892
+ private func armUnknownCapabilityWait() {
4893
+ cancelUnknownCapabilityWait()
4894
+ awaitingPairingInfoForUnknownCapability = true
4895
+ let work = DispatchWorkItem { [weak self] in
4896
+ guard let self, self.awaitingPairingInfoForUnknownCapability else { return }
4897
+ self.unknownCapabilityWaitWorkItem = nil
4898
+ self.awaitingPairingInfoForUnknownCapability = false
4899
+ self.pairFlow("readiness", "capability=unknown pairing_info=none action=ready_legacy")
4900
+ self.markFullyBooted()
4901
+ }
4902
+ unknownCapabilityWaitWorkItem = work
4903
+ DispatchQueue.main.asyncAfter(
4904
+ deadline: .now() + .milliseconds(max(unknownCapabilityPairingInfoWaitMs, 0)),
4905
+ execute: work
4906
+ )
4907
+ }
4908
+
4909
+ private func cancelUnknownCapabilityWait() {
4910
+ awaitingPairingInfoForUnknownCapability = false
4911
+ unknownCapabilityWaitWorkItem?.cancel()
4912
+ unknownCapabilityWaitWorkItem = nil
4913
+ }
4914
+
4915
+ /// `mentra_live_secure_firmware` follows the current glasses: a ready session that gets no
4916
+ /// pairing_info runs legacy firmware (for example after a rollback).
4917
+ private func armSecureFirmwareRefresh() {
4918
+ guard secureFirmwareRefreshWorkItem == nil, !pairingInfoSeenThisSession else { return }
4919
+ let work = DispatchWorkItem { [weak self] in
4920
+ guard let self else { return }
4921
+ self.secureFirmwareRefreshWorkItem = nil
4922
+ guard !self.pairingInfoSeenThisSession else { return }
4923
+ self.pairFlow("secure_firmware", "pairing_info=none afterMs=\(self.secureFirmwareRefreshMs) secure=false")
4924
+ self.rememberSecureFirmware(false)
4925
+ }
4926
+ secureFirmwareRefreshWorkItem = work
4927
+ DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(max(secureFirmwareRefreshMs, 0)), execute: work)
4928
+ }
4929
+
4930
+ private func cancelSecureFirmwareRefresh() {
4931
+ secureFirmwareRefreshWorkItem?.cancel()
4932
+ secureFirmwareRefreshWorkItem = nil
4933
+ }
4934
+
4935
+ /// Bond confirmation has to arrive on its own. A dismissed pairing sheet, or a bond that
4936
+ /// never finishes, must fail the attempt instead of leaving the loading screen up.
4937
+ private func armSecurePairingWait() {
4938
+ cancelSecurePairingWait()
4939
+ // Every parked secure readiness gets this deadline, so the pair can never hang.
4940
+ guard MentraLiveConnectionAttemptPolicy.shouldRunSecurePairingWait(
4941
+ explicitPairing: isExplicitPairingAttempt(),
4942
+ securePairingTarget: isSecurePairingTarget()
4943
+ ) else { return }
4944
+ let work = DispatchWorkItem { [weak self] in
4945
+ guard let self else { return }
4946
+ guard self.awaitingSecurePairingConfirmation, self.isExplicitPairingAttempt(),
4947
+ !self.securePairingConfirmed
4948
+ else { return }
4949
+ self.awaitingSecurePairingConfirmation = false
4950
+ Bridge.log("LIVE: secure pairing bond wait expired")
4951
+ Bridge.sendPairFailureEvent("errors:pairingCouldNotStart")
4952
+ }
4953
+ securePairingWaitWorkItem = work
4954
+ DispatchQueue.main.asyncAfter(deadline: .now() + 40, execute: work)
4955
+ }
4956
+
4957
+ private func cancelSecurePairingWait() {
4958
+ securePairingWaitWorkItem?.cancel()
4959
+ securePairingWaitWorkItem = nil
4960
+ }
4961
+
4962
+ private func isSecurePairingTarget() -> Bool {
4963
+ MentraLiveConnectionAttemptPolicy.isSecurePairingTarget(
4964
+ selectedCapability: selectedTargetSecureCapability(),
4965
+ securePairingInfoThisSession: pairingInfoSeenThisSession
4966
+ )
4967
+ }
4968
+
4969
+ /// The user is pairing from the scan screen rather than reconnecting a saved owner.
4970
+ private func isExplicitPairingAttempt() -> Bool {
4971
+ let pendingName = DeviceStore.shared.get("bluetooth", "pending_device_name") as? String ?? ""
4972
+ let pendingAddress = DeviceStore.shared.get("bluetooth", "pending_device_address") as? String ?? ""
4973
+ return manualDiscoveryActive || !pendingName.isEmpty || !pendingAddress.isEmpty
4974
+ }
4975
+
4052
4976
  private func handleWifiScanResult(_ json: [String: Any]) {
4053
4977
  var networks: [[String: Any]] = []
4054
4978
 
@@ -4085,6 +5009,7 @@ class MentraLive: NSObject, SGCManager {
4085
5009
  DeviceStore.shared.apply("glasses", "otaVersionUrl", otaVersionUrl)
4086
5010
  DeviceStore.shared.apply("glasses", "firmwareVersion", firmwareVersion)
4087
5011
  if let bluetoothMacAddress {
5012
+ recordWifiAdbPeerIdentity(bluetoothMacAddress)
4088
5013
  DeviceStore.shared.apply("glasses", "bluetoothMacAddress", bluetoothMacAddress)
4089
5014
  }
4090
5015
  if let serialNumber {
@@ -4492,6 +5417,15 @@ class MentraLive: NSObject, SGCManager {
4492
5417
  if sess.isComplete {
4493
5418
  Bridge.log("LIVE: 📦 File transfer complete: \(packetInfo.fileName)")
4494
5419
 
5420
+ if Self.isIncidentRelayFileName(packetInfo.fileName) {
5421
+ // No relay registered (e.g. the app restarted mid-relay): nothing reached
5422
+ // Cloud, so success would make the glasses mark the incident uploaded.
5423
+ Bridge.log("LIVE: Incident log relay without a registered report: \(packetInfo.fileName)")
5424
+ sendTransferCompleteConfirmation(fileName: packetInfo.fileName, success: false)
5425
+ activeFileTransfers.removeValue(forKey: packetInfo.fileName)
5426
+ return
5427
+ }
5428
+
4495
5429
  if let fileData = sess.assembleFile() {
4496
5430
  saveReceivedFile(
4497
5431
  fileName: packetInfo.fileName, fileData: fileData,
@@ -4593,7 +5527,7 @@ class MentraLive: NSObject, SGCManager {
4593
5527
  ]
4594
5528
  }
4595
5529
 
4596
- private func uploadBleIncidentLogRelay(
5530
+ func uploadBleIncidentLogRelay(
4597
5531
  relay: BleIncidentLogRelayEntry, fileName: String, data: Data
4598
5532
  ) {
4599
5533
  let token = DeviceStore.shared.get("bluetooth", "core_token") as? String ?? ""
@@ -4644,14 +5578,24 @@ class MentraLive: NSObject, SGCManager {
4644
5578
  statusCode = nil
4645
5579
  }
4646
5580
  DispatchQueue.main.async {
5581
+ // A different report now owns this name (it was admitted after our owner finished),
5582
+ // so a completion here would mark ITS file done. Drop the stale callback.
5583
+ if let owner = self.bleIncidentLogRelays[relay.fileBaseKey], owner.incidentId != relay.incidentId {
5584
+ Bridge.log("LIVE: Dropping stale incident relay callback for \(relay.fileBaseKey)")
5585
+ return
5586
+ }
4647
5587
  if ok {
4648
5588
  Bridge.log("LIVE: ✅ Incident log BLE relay uploaded (\(relay.kind))")
4649
- self.bleIncidentLogRelays.removeValue(forKey: relay.fileBaseKey)
4650
5589
  } else if let existing = self.bleIncidentLogRelays[relay.fileBaseKey] {
4651
5590
  // Keep relay entry for glasses retry after transfer_complete:false.
4652
5591
  existing.session = nil
4653
5592
  }
4654
5593
  self.sendTransferCompleteConfirmation(fileName: fileName, success: ok)
5594
+ // Release only after the glasses' confirmation is queued, so a report that reuses
5595
+ // this name is ordered behind the owner's completion.
5596
+ if ok {
5597
+ self.releaseIncidentRelay(relay)
5598
+ }
4655
5599
  }
4656
5600
  }.resume()
4657
5601
  }
@@ -4767,6 +5711,10 @@ class MentraLive: NSObject, SGCManager {
4767
5711
  }
4768
5712
 
4769
5713
  func queueSend(_ data: Data, id: String, trace: BleWriteTrace?) {
5714
+ if let admission = wifiAdbAdmission {
5715
+ guard currentWifiAdbAdmission(admission) else { admission.refused = true; return }
5716
+ admission.queued += 1
5717
+ }
4770
5718
  let significantQueueSize = SIGNIFICANT_BLE_TRACE_QUEUE_SIZE
4771
5719
  // Insert synchronously on MainActor so fragments and dependent commands retain call order.
4772
5720
  let generation = wireSessionGeneration
@@ -4871,7 +5819,8 @@ class MentraLive: NSObject, SGCManager {
4871
5819
  }
4872
5820
  }
4873
5821
 
4874
- BleTraceLogger.logMap(direction: "phone_to_glasses", layer: layer, type: trace.commandType, payload: payload)
5822
+ BleTraceLogger.logMap(direction: "phone_to_glasses", layer: layer, type: trace.commandType, payload: payload,
5823
+ forwardToBridge: wifiAdbAdmission == nil)
4875
5824
  }
4876
5825
 
4877
5826
  private func bleTraceWarningReason(stage: String, extra: [String: Any?]) -> String? {
@@ -5201,7 +6150,8 @@ class MentraLive: NSObject, SGCManager {
5201
6150
  direction: "phone_to_glasses",
5202
6151
  layer: "sdk_ble_command",
5203
6152
  payload: json,
5204
- bytes: jsonData.count
6153
+ bytes: jsonData.count,
6154
+ forwardToBridge: bridgeLogging
5205
6155
  )
5206
6156
 
5207
6157
  if useBinaryWireProtocol, isNewVersion {
@@ -5813,7 +6763,10 @@ class MentraLive: NSObject, SGCManager {
5813
6763
  private var readinessCheckDispatchTimer: DispatchSourceTimer?
5814
6764
 
5815
6765
  private func startReadinessCheckLoop() {
5816
- Bridge.log("LIVE: startReadinessCheckLoop()")
6766
+ pairFlow(
6767
+ "readiness",
6768
+ "start gatt=\(txCharacteristic != nil) id=\(connectedPeripheral?.identifier.uuidString ?? "-") name=\(connectedPeripheral?.name ?? "-")"
6769
+ )
5817
6770
  stopReadinessCheckLoop()
5818
6771
 
5819
6772
  readinessCheckCounter = 0
@@ -5833,8 +6786,15 @@ class MentraLive: NSObject, SGCManager {
5833
6786
  guard let self else { return }
5834
6787
 
5835
6788
  self.readinessCheckCounter += 1
6789
+ let gattReady = self.txCharacteristic != nil
6790
+ if self.readinessCheckCounter == 1 || self.readinessCheckCounter % 4 == 0 {
6791
+ self.pairFlow(
6792
+ "readiness",
6793
+ "n=\(self.readinessCheckCounter) gatt=\(gattReady) id=\(self.connectedPeripheral?.identifier.uuidString ?? "-")"
6794
+ )
6795
+ }
5836
6796
  Bridge.log(
5837
- "LIVE: 🔄 Readiness check #\(self.readinessCheckCounter): waiting for glasses SOC to boot"
6797
+ "LIVE: 🔄 Readiness check #\(self.readinessCheckCounter): waiting for glasses SOC to boot gatt=\(gattReady)"
5838
6798
  )
5839
6799
  // requestReadyK900()
5840
6800
 
@@ -5866,8 +6826,15 @@ class MentraLive: NSObject, SGCManager {
5866
6826
  }
5867
6827
 
5868
6828
  private func stopReadinessCheckLoop() {
6829
+ let wasRunning = readinessCheckDispatchTimer != nil
5869
6830
  readinessCheckDispatchTimer?.cancel()
5870
6831
  readinessCheckDispatchTimer = nil
6832
+ if wasRunning {
6833
+ pairFlow(
6834
+ "readiness",
6835
+ "stop n=\(readinessCheckCounter) gatt=\(txCharacteristic != nil) id=\(connectedPeripheral?.identifier.uuidString ?? "-")"
6836
+ )
6837
+ }
5871
6838
  Bridge.log("LIVE: 🔄 Stopped glasses SOC readiness check loop")
5872
6839
  }
5873
6840
 
@@ -5879,6 +6846,10 @@ class MentraLive: NSObject, SGCManager {
5879
6846
  guard let self else { return }
5880
6847
 
5881
6848
  if self.isConnecting, self.connectionState != ConnTypes.CONNECTED {
6849
+ self.pairFlow(
6850
+ "connect_timeout",
6851
+ "id=\(self.connectedPeripheral?.identifier.uuidString ?? "-") name=\(self.connectedPeripheral?.name ?? "-") state=\(self.connectionState)"
6852
+ )
5882
6853
  Bridge.log("LIVE: Connection timeout - closing GATT connection")
5883
6854
  self.isConnecting = false
5884
6855
 
@@ -5913,7 +6884,7 @@ class MentraLive: NSObject, SGCManager {
5913
6884
  /// promotes it to the default device. Re-emit only that explicit pending target; an
5914
6885
  /// established owner's connected glasses have no pending identity and remain hidden.
5915
6886
  private func emitConnectedPendingDeviceForPairingScan() {
5916
- guard manualDiscoveryActive, !pairingYieldActive, let peripheral = connectedPeripheral,
6887
+ guard manualDiscoveryActive, let peripheral = connectedPeripheral,
5917
6888
  let name = peripheral.name,
5918
6889
  MentraLivePendingPairingTarget.shouldRecover(
5919
6890
  isConnected: peripheral.state == .connected,
@@ -5939,17 +6910,35 @@ class MentraLive: NSObject, SGCManager {
5939
6910
  )
5940
6911
  }
5941
6912
 
6913
+ private func discoveredAdvertisementName(
6914
+ _ peripheral: CBPeripheral,
6915
+ advertisementData: [String: Any]
6916
+ ) -> String? {
6917
+ if let name = peripheral.name, !name.isEmpty { return name }
6918
+ if let name = advertisementData[CBAdvertisementDataLocalNameKey] as? String, !name.isEmpty {
6919
+ return name
6920
+ }
6921
+ return nil
6922
+ }
6923
+
6924
+ /// Returns true when this advertisement changed the row the scan screen is showing.
6925
+ @discardableResult
5942
6926
  private func cacheAdvPairing(
5943
6927
  _ name: String,
5944
6928
  pairingMode: Bool,
5945
6929
  pairingCode: String?,
5946
6930
  securePairingCapable: Bool
5947
- ) {
5948
- discoveredAdvPairing[name] = CachedAdvPairing(
6931
+ ) -> Bool {
6932
+ let next = CachedAdvPairing(
5949
6933
  pairingMode: pairingMode,
5950
6934
  pairingCode: pairingCode,
5951
6935
  securePairingCapable: securePairingCapable
5952
6936
  )
6937
+ if discoveredAdvPairing[name] == next {
6938
+ return false
6939
+ }
6940
+ discoveredAdvPairing[name] = next
6941
+ return true
5953
6942
  }
5954
6943
 
5955
6944
  private func emitDiscoveredDeviceFromCache(
@@ -6070,9 +7059,14 @@ class MentraLive: NSObject, SGCManager {
6070
7059
  // MARK: - Cleanup
6071
7060
 
6072
7061
  private func destroy() {
6073
- Bridge.log("Destroying MentraLiveManager")
7062
+ pairFlow(
7063
+ "destroy",
7064
+ "name=\(connectedPeripheral?.name ?? "-") id=\(connectedPeripheral?.identifier.uuidString ?? "-") scanning=\(isScanning)"
7065
+ )
6074
7066
 
6075
7067
  isKilled = true
7068
+ // The pairing state outlives the manager; only its timer belongs to this instance.
7069
+ cancelPairingPauseTimer()
6076
7070
  unpairFlushWorkItem?.cancel()
6077
7071
  unpairFlushWorkItem = nil
6078
7072
  unpairFlushPending = false
@@ -6117,6 +7111,92 @@ class MentraLive: NSObject, SGCManager {
6117
7111
  centralManager = nil
6118
7112
 
6119
7113
  updateConnectionState(ConnTypes.DISCONNECTED)
7114
+ resetSecurePairingSession()
7115
+ stopObservingAudioSetupInputs()
7116
+ }
7117
+ }
7118
+
7119
+ // MARK: - Audio setup
7120
+
7121
+ extension MentraLive {
7122
+ nonisolated static func monotonicNowMs() -> Int {
7123
+ Int(ProcessInfo.processInfo.systemUptime * 1000)
7124
+ }
7125
+
7126
+ private static let audioSetupInputKeys: Set<String> = [
7127
+ "fullyBooted", "bluetoothClassicConnected", "bluetoothClassicProfilesConnected", "bluetoothAudioRouted",
7128
+ ]
7129
+
7130
+ /// Readiness (from any writer, including `sr_hrt ready=0`) and the phone's three audio
7131
+ /// signals re-evaluate the state in the same update that changed them.
7132
+ fileprivate func observeAudioSetupInputs() {
7133
+ guard audioSetupStoreListenerId == nil else { return }
7134
+ audioSetup.startPhase(.reconnect, nowMs: audioSetupNowMs())
7135
+ audioSetupStoreListenerId = DeviceStore.shared.store.addListener { [weak self] category, changes in
7136
+ MainActor.assumeIsolated {
7137
+ guard category == "glasses",
7138
+ changes.keys.contains(where: { MentraLive.audioSetupInputKeys.contains($0) })
7139
+ else { return }
7140
+ self?.refreshAudioSetup(trigger: "status")
7141
+ }
7142
+ }
7143
+ refreshAudioSetup(trigger: "init")
7144
+ }
7145
+
7146
+ fileprivate func stopObservingAudioSetupInputs() {
7147
+ if let id = audioSetupStoreListenerId {
7148
+ DeviceStore.shared.store.removeListener(id)
7149
+ audioSetupStoreListenerId = nil
7150
+ }
7151
+ audioSetupDeadlineWorkItem?.cancel()
7152
+ audioSetupDeadlineWorkItem = nil
7153
+ }
7154
+
7155
+ /// The phone's view: the Classic bond, a connected HFP input or a matching Bluetooth output.
7156
+ private func phoneAudioUp() -> Bool {
7157
+ ["bluetoothClassicConnected", "bluetoothClassicProfilesConnected", "bluetoothAudioRouted"].contains {
7158
+ DeviceStore.shared.get("glasses", $0) as? Bool == true
7159
+ }
7160
+ }
7161
+
7162
+ /// The BLE session ended. Its `classic_link` report no longer applies.
7163
+ fileprivate func endAudioSetupSession() {
7164
+ audioSetup.endSession()
7165
+ #if !os(macOS)
7166
+ AudioSessionMonitor.glassesReportClassicLink = false
7167
+ #endif
7168
+ refreshAudioSetup(trigger: "disconnect")
7169
+ }
7170
+
7171
+ /// Feeds `GlassesAudioSetupPolicy`, arms one timer for its next deadline and publishes on change.
7172
+ /// Only the active driver publishes; a manager being created or torn down stays quiet.
7173
+ fileprivate func refreshAudioSetup(trigger: String, sessionReady: Bool? = nil) {
7174
+ guard (DeviceManager.shared.sgc as AnyObject?) === self else {
7175
+ audioSetupDeadlineWorkItem?.cancel()
7176
+ audioSetupDeadlineWorkItem = nil
7177
+ return
7178
+ }
7179
+ let nowMs = audioSetupNowMs()
7180
+ let decision = audioSetup.evaluate(
7181
+ sessionReady: sessionReady ?? fullyBooted,
7182
+ phoneAudioUp: phoneAudioUp(),
7183
+ nowMs: nowMs
7184
+ )
7185
+ audioSetupDeadlineWorkItem?.cancel()
7186
+ audioSetupDeadlineWorkItem = nil
7187
+ if let deadlineMs = decision.nextDeadlineMs {
7188
+ let work = DispatchWorkItem { [weak self] in
7189
+ guard let self else { return }
7190
+ self.audioSetupDeadlineWorkItem = nil
7191
+ self.refreshAudioSetup(trigger: "deadline")
7192
+ }
7193
+ audioSetupDeadlineWorkItem = work
7194
+ DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(max(deadlineMs - nowMs, 0)), execute: work)
7195
+ }
7196
+ guard DeviceStore.shared.publishAudioSetup(decision.state) else { return }
7197
+ Bridge.log(
7198
+ "PAIRFLOW: audio_setup state=\(decision.state.name) phase=\(audioSetup.phase.logName) afterMs=\(nowMs - audioSetup.phaseStartedAtMs) trigger=\(trigger) glassesReport=\(audioSetup.glassesReportsClassicLink ? "a2dp:\(audioSetup.glassesA2dp),hfp:\(audioSetup.glassesHfp)" : "none") phoneAudio=\(phoneAudioUp())"
7199
+ )
6120
7200
  }
6121
7201
  }
6122
7202
 
@@ -6222,6 +7302,7 @@ extension MentraLive {
6222
7302
  private func sendPhoneReady(reason: String) {
6223
7303
  let readyId = pendingReadyId ?? UUID().uuidString
6224
7304
  pendingReadyId = readyId
7305
+ pairFlow("phone_ready", "reason=\(reason) gatt=\(txCharacteristic != nil) id=\(connectedPeripheral?.identifier.uuidString ?? "-")")
6225
7306
  Bridge.log(
6226
7307
  "LIVE: 📱 Sending phone_ready to glasses (\(reason), exchange \(readyId)) - waiting for glasses_ready response"
6227
7308
  )