@mentra/bluetooth-sdk 3.3.0-dev.944 → 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 (174) hide show
  1. package/MIGRATION.md +61 -0
  2. package/README.md +111 -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 +89 -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 +159 -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 +2 -1
  13. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  14. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +35 -2
  15. package/android/src/main/java/com/mentra/bluetoothsdk/TouchGesture.kt +19 -0
  16. package/android/src/main/java/com/mentra/bluetoothsdk/connection/ConnectionModels.kt +5 -0
  17. package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
  18. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicy.kt +64 -0
  19. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +1002 -157
  20. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +227 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisement.kt +19 -0
  22. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicy.kt +94 -0
  23. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachine.kt +411 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateStore.kt +124 -0
  25. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +54 -59
  26. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +5 -32
  27. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasEncoder.kt +8 -1
  28. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +3 -10
  29. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
  30. package/android/src/main/java/com/mentra/bluetoothsdk/status/DeviceStatus.kt +50 -0
  31. package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
  32. package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
  33. package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
  34. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
  35. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
  36. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
  37. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
  38. package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
  39. package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
  40. package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
  41. package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
  42. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
  43. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
  44. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
  45. package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
  46. package/android/src/test/java/com/mentra/bluetoothsdk/DeviceManagerOwnerLossTest.kt +146 -0
  47. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusAudioSetupTest.kt +51 -0
  48. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusClassicAudioTest.kt +2 -0
  49. package/android/src/test/java/com/mentra/bluetoothsdk/TouchGestureCommandTest.kt +112 -0
  50. package/android/src/test/java/com/mentra/bluetoothsdk/WifiAdbPeerIntentTest.kt +19 -0
  51. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicyTest.kt +65 -0
  52. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveAudioSetupReadinessTest.kt +231 -0
  53. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +141 -0
  54. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
  55. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +368 -0
  56. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisementParserTest.kt +20 -0
  57. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicyTest.kt +136 -0
  58. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachineTest.kt +346 -0
  59. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveRgbLedResponseTest.kt +76 -0
  60. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
  61. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
  62. package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
  63. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
  64. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
  65. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
  66. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
  67. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
  68. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
  69. package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
  70. package/build/BluetoothSdk.types.d.ts +207 -2
  71. package/build/BluetoothSdk.types.d.ts.map +1 -1
  72. package/build/BluetoothSdk.types.js.map +1 -1
  73. package/build/_private/BluetoothSdkModule.d.ts +45 -6
  74. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  75. package/build/_private/BluetoothSdkModule.js +2 -0
  76. package/build/_private/BluetoothSdkModule.js.map +1 -1
  77. package/build/generated/changelogCatalog.d.ts +4 -1
  78. package/build/generated/changelogCatalog.d.ts.map +1 -1
  79. package/build/generated/changelogCatalog.js +5 -1
  80. package/build/generated/changelogCatalog.js.map +1 -1
  81. package/build/generated/releaseMetadata.js +6 -6
  82. package/build/generated/releaseMetadata.js.map +1 -1
  83. package/build/index.d.ts +1 -1
  84. package/build/index.d.ts.map +1 -1
  85. package/build/index.js +10 -0
  86. package/build/index.js.map +1 -1
  87. package/ios/BluetoothSdkModule.swift +84 -12
  88. package/ios/MentraBluetoothSDK.podspec +4 -0
  89. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  90. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  91. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  92. package/ios/Source/BluetoothSdkDefaults.swift +2 -2
  93. package/ios/Source/Bridge.swift +11 -3
  94. package/ios/Source/DeviceManager.swift +135 -18
  95. package/ios/Source/DeviceStore.swift +27 -0
  96. package/ios/Source/GeneratedChangelogCatalog.swift +2 -1
  97. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  98. package/ios/Source/MentraBluetoothSDK.swift +51 -5
  99. package/ios/Source/TouchGesture.swift +13 -0
  100. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  101. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  102. package/ios/Source/audio/SpeechActivity.swift +277 -0
  103. package/ios/Source/errors/BluetoothSdkError.swift +5 -1
  104. package/ios/Source/events/BluetoothEvents.swift +45 -0
  105. package/ios/Source/internal/BleTraceLogger.swift +9 -6
  106. package/ios/Source/internal/BluetoothAvailability.swift +15 -5
  107. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +186 -0
  108. package/ios/Source/sgcs/MentraLive.swift +1366 -212
  109. package/ios/Source/sgcs/MentraLivePairingAdvertisement.swift +260 -1
  110. package/ios/Source/sgcs/MentraLivePairingStateMachine.swift +385 -0
  111. package/ios/Source/sgcs/MentraLivePairingStateStore.swift +121 -0
  112. package/ios/Source/sgcs/Nimo.swift +10 -3
  113. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +39 -9
  114. package/ios/Source/sgcs/SGCManager.swift +13 -0
  115. package/ios/Source/sgcs/Simulated.swift +2 -0
  116. package/ios/Source/status/DeviceStatus.swift +35 -0
  117. package/ios/Source/stt/STTTools.swift +13 -31
  118. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  119. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  120. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  121. package/ios/Source/types/DeviceModels.swift +8 -1
  122. package/ios/Source/utils/AudioSessionMonitor.swift +158 -5
  123. package/ios/Source/utils/BoundedWait.swift +44 -0
  124. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  125. package/ios/Source/utils/SttModelTraits.swift +62 -0
  126. package/ios/Tests/BesCrashReportTests.swift +142 -0
  127. package/ios/Tests/BluetoothAudioRouteTests.swift +82 -0
  128. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  129. package/ios/Tests/DeviceManagerReconnectTests.swift +4 -2
  130. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +197 -0
  131. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  132. package/ios/Tests/MentraLiveAudioSetupTests.swift +209 -0
  133. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  134. package/ios/Tests/MentraLiveConnectionOptionsTests.swift +55 -0
  135. package/ios/Tests/MentraLivePairingAdvertisementTests.swift +327 -0
  136. package/ios/Tests/MentraLivePairingStateMachineTests.swift +402 -0
  137. package/ios/Tests/MentraLiveSessionReadinessTests.swift +497 -26
  138. package/ios/Tests/NimoCanvasTransportTests.swift +58 -0
  139. package/ios/Tests/PcmStreamTests.swift +299 -0
  140. package/ios/Tests/SpeechActivityTests.swift +238 -0
  141. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  142. package/ios/Tests/TouchGestureCommandTests.swift +87 -0
  143. package/ios/Tests/WifiAdbDispatchTests.swift +118 -0
  144. package/package.json +3 -2
  145. package/plugin/build/withAndroid.js +9 -11
  146. package/plugin/build/withKotlinVersion.d.ts +2 -0
  147. package/plugin/build/withKotlinVersion.js +46 -0
  148. package/src/BluetoothSdk.types.ts +216 -1
  149. package/src/_private/BluetoothSdkModule.ts +49 -5
  150. package/src/generated/changelogCatalog.ts +5 -1
  151. package/src/generated/releaseMetadata.ts +6 -6
  152. package/src/index.ts +24 -0
  153. package/android/silero/LICENSE.md +0 -17
  154. package/android/silero/build.gradle +0 -50
  155. package/android/silero/proguard-rules.pro +0 -24
  156. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  157. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  158. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  159. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  160. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  161. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  162. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  163. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  164. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  165. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  166. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
  167. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
  168. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  169. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
  170. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
  171. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
  172. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -288
  173. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  174. /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()
944
1022
 
945
- if self.pairingYieldAwaitingReclaim, Self.isPairingAuthFailure(error) {
946
- self.clearSavedGlassesAfterOwnerLoss(reason: "ios_auth_fail")
1023
+ if self.stopAfterConnectFailure(error) {
1024
+ return
1025
+ }
1026
+
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
@@ -1345,6 +1507,7 @@ class MentraLive: NSObject, SGCManager {
1345
1507
  if state == ConnTypes.DISCONNECTED {
1346
1508
  resetPendingAckState(reason: "BLE session ended")
1347
1509
  resetWireNegotiationState()
1510
+ resetReadinessExchange()
1348
1511
  resetAncsRelayState()
1349
1512
  // Queued writes are session-bound: transmitting them into the NEXT session
1350
1513
  // (e.g. a stale handshake whose reply activates v2 before the new session
@@ -1354,6 +1517,7 @@ class MentraLive: NSObject, SGCManager {
1354
1517
  DeviceStore.shared.apply("glasses", "signalStrength", -1)
1355
1518
  DeviceStore.shared.apply("glasses", "signalStrengthUpdatedAt", 0)
1356
1519
  resetOtaCache()
1520
+ endAudioSetupSession()
1357
1521
  }
1358
1522
  }
1359
1523
 
@@ -1386,11 +1550,17 @@ class MentraLive: NSObject, SGCManager {
1386
1550
  func dbg1() {}
1387
1551
  func dbg2() {}
1388
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
+
1389
1560
  func forget() {
1390
1561
  Bridge.log("LIVE: Forgetting Mentra Live glasses")
1391
-
1392
- // Clear saved device name so the pairing filter is not bypassed on rescan
1393
- UserDefaults.standard.removeObject(forKey: PREFS_DEVICE_NAME)
1562
+ Self.clearSavedPeripheral()
1563
+ pairFlow("forget", "cleared_saved_peripheral")
1394
1564
 
1395
1565
  // Stop scanning first
1396
1566
  if isScanning {
@@ -1413,6 +1583,9 @@ class MentraLive: NSObject, SGCManager {
1413
1583
 
1414
1584
  var type = "Mentra Live"
1415
1585
  var hasMic = true
1586
+ var publishesAudioSetup: Bool {
1587
+ true
1588
+ }
1416
1589
 
1417
1590
  func setMicEnabled(_ enabled: Bool) {
1418
1591
  Bridge.log("LIVE: 🎤 Microphone state change requested: \(enabled)")
@@ -1476,7 +1649,11 @@ class MentraLive: NSObject, SGCManager {
1476
1649
  private var fileWriteCharacteristic: CBCharacteristic?
1477
1650
  private var activeFileTransfers = [String: MentraLiveFileTransferSession]()
1478
1651
  private var blePhotoTransfers = [String: BlePhotoTransfer]()
1479
- 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 }
1480
1657
  private var l2capFileChannel: MentraLiveL2capChannel?
1481
1658
  private var l2capFileChannelId: UUID?
1482
1659
  private var l2capFileChannelOpening = false
@@ -1519,7 +1696,10 @@ class MentraLive: NSObject, SGCManager {
1519
1696
  private let SIGNIFICANT_BLE_TRACE_QUEUE_SIZE = 5
1520
1697
 
1521
1698
  /// Device Settings Keys
1522
- 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
1523
1703
 
1524
1704
  // MARK: - Properties
1525
1705
 
@@ -1530,7 +1710,9 @@ class MentraLive: NSObject, SGCManager {
1530
1710
  /// BLE Properties
1531
1711
  private var centralManager: CBCentralManager?
1532
1712
 
1533
- private var connectedPeripheral: CBPeripheral?
1713
+ private var connectedPeripheral: CBPeripheral? {
1714
+ didSet { _ = beginBleNotificationSession(source: connectedPeripheral) }
1715
+ }
1534
1716
  /// Peripheral for the in-flight connect; used to ignore stale disconnect/fail callbacks.
1535
1717
  private var connectingPeripheral: CBPeripheral?
1536
1718
  private var txCharacteristic: CBCharacteristic?
@@ -1543,10 +1725,49 @@ class MentraLive: NSObject, SGCManager {
1543
1725
  private var manualDiscoveryActive = false
1544
1726
  private var isConnecting = false
1545
1727
  private var isKilled = false
1546
- /// Glasses opened pairing window — stand down without forgetting identity/bonds.
1547
- private var pairingYieldActive = false
1548
- private var pairingYieldAwaitingReclaim = false
1549
- 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() }
1550
1771
  /// Hold GATT teardown until the unpair write can leave the phone.
1551
1772
  private var unpairFlushPending = false
1552
1773
  private var unpairFlushWorkItem: DispatchWorkItem?
@@ -1603,6 +1824,13 @@ class MentraLive: NSObject, SGCManager {
1603
1824
  // the physical connection — so a first-seen sid after an upgrade OTA cannot be
1604
1825
  // mistaken for a fresh pairing just because a not-ready heartbeat slipped in first.
1605
1826
  private var readinessCompletedThisBleSession = false
1827
+ /// Readiness exchange the phone is waiting on. Every phone_ready carries it until the
1828
+ /// matching glasses_ready arrives, so retries and the copies the BES buffers while the
1829
+ /// glasses boot are one exchange: the glasses reset their transport once for it and answer
1830
+ /// later copies without resetting. Both exchange fields are scoped to the BLE session.
1831
+ private var pendingReadyId: String?
1832
+ /// `sid` of the glasses process whose glasses_ready this BLE session last handled.
1833
+ private var readyGlassesSessionId: String?
1606
1834
  private var globalMessageId = 0
1607
1835
  private var lastReceivedMessageId = 0
1608
1836
  private var bleWriteTraceSequence = 0
@@ -1666,6 +1894,10 @@ class MentraLive: NSObject, SGCManager {
1666
1894
  private var pendingReconnectSettleWorkItem: DispatchWorkItem?
1667
1895
  private var reconnectionWorkItem: DispatchWorkItem?
1668
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
1669
1901
 
1670
1902
  // MARK: - Initialization
1671
1903
 
@@ -1685,6 +1917,10 @@ class MentraLive: NSObject, SGCManager {
1685
1917
  } else {
1686
1918
  Bridge.log("LIVE: 🎵 Phone audio monitor disabled (BLOCK_AUDIO_DUPLEX=false)")
1687
1919
  }
1920
+
1921
+ UserDefaults.standard.removeObject(forKey: Self.retiredSecurePairingNamesKey)
1922
+ restorePairingState()
1923
+ observeAudioSetupInputs()
1688
1924
  }
1689
1925
 
1690
1926
  deinit {
@@ -1705,12 +1941,15 @@ class MentraLive: NSObject, SGCManager {
1705
1941
  // MARK: - React Native Interface
1706
1942
 
1707
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>()
1708
1947
  /// Last advertisement pairing trailer for a discovered name. Re-emits (already-
1709
1948
  /// connected / scan replay) must not drop these flags: omitting them makes a
1710
1949
  /// secure idle unit look like pairable legacy firmware.
1711
1950
  private var discoveredAdvPairing = [String: CachedAdvPairing]()
1712
1951
 
1713
- private struct CachedAdvPairing {
1952
+ private struct CachedAdvPairing: Equatable {
1714
1953
  let pairingMode: Bool
1715
1954
  let pairingCode: String?
1716
1955
  let securePairingCapable: Bool
@@ -1739,20 +1978,67 @@ class MentraLive: NSObject, SGCManager {
1739
1978
  }
1740
1979
  }
1741
1980
 
1742
- func isPairingYieldActive() -> Bool {
1743
- 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()
1744
1985
  }
1745
1986
 
1746
- private func enterPairingYield(windowMs: Int) {
1747
- cancelPendingReconnect(reason: "pairing_yield")
1748
- pairingYieldActive = true
1749
- pairingYieldAwaitingReclaim = false
1750
- pairingYieldEndWorkItem?.cancel()
1751
- if isScanning {
1752
- stopScan()
1753
- }
1754
- // Publish disconnect immediately for Phone A UI. didDisconnectPeripheral may lag
1755
- // 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.
1756
2042
  isConnecting = false
1757
2043
  clearPhysicalReadiness()
1758
2044
  connected = false
@@ -1760,6 +2046,9 @@ class MentraLive: NSObject, SGCManager {
1760
2046
  streamControlVersion = 0
1761
2047
  readinessCompletedThisBleSession = false
1762
2048
  rgbLedAuthorityClaimed = false
2049
+ lastSentMicTuningBody = nil
2050
+ wearTuningQueriedThisLink = false
2051
+ resetSecurePairingSession()
1763
2052
  stopAllTimers()
1764
2053
  closeL2capFileChannel()
1765
2054
  txCharacteristic = nil
@@ -1770,66 +2059,282 @@ class MentraLive: NSObject, SGCManager {
1770
2059
  }
1771
2060
  connectedPeripheral = nil
1772
2061
  connectingPeripheral = nil
1773
- // Stand down for the whole window. Probing GATT during yield races the new
1774
- // phone for the single BLE slot and is exactly what entering_pairing_mode forbids.
2062
+ }
1775
2063
 
2064
+ private func armPairingPauseTimer() {
2065
+ cancelPairingPauseTimer()
2066
+ guard pairingStore.isPaused else { return }
2067
+ let remaining = pairingStore.remainingPauseMs()
1776
2068
  let work = DispatchWorkItem { [weak self] in
1777
2069
  guard let self else { return }
1778
- Bridge.log("LIVE: Pairing yield ended — resume reconnect if still owned")
1779
- self.pairingYieldActive = false
1780
- self.pairingYieldAwaitingReclaim = true
1781
- self.pairingYieldEndWorkItem = nil
1782
- if !self.isKilled, self.connectedPeripheral == nil {
1783
- self.handleReconnection()
2070
+ self.pairingPauseWorkItem = nil
2071
+ let transition = self.pairingStore.update("pause_deadline") {
2072
+ $0.onTick(nowMs: MentraLivePairingStateStore.nowMs())
2073
+ }
2074
+ if transition.effect == .none, self.pairingStore.isPaused {
2075
+ self.armPairingPauseTimer()
2076
+ return
1784
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
2098
+ }
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())")
2111
+ }
2112
+
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")
1785
2125
  }
1786
- pairingYieldEndWorkItem = work
1787
- DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(windowMs), execute: work)
2126
+ applyPairingTransition(transition)
1788
2127
  }
1789
2128
 
1790
- /// Pairing/auth failures after yield — CoreBluetooth codes, not localized strings.
1791
- /// Connection timeouts are not owner-loss.
1792
- private static func isPairingAuthFailure(_ error: Error?) -> Bool {
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 {
1793
2179
  guard let error = error as NSError? else { return false }
1794
2180
  if error.domain == CBATTErrorDomain {
1795
2181
  return error.code == CBATTError.insufficientAuthentication.rawValue
1796
2182
  || error.code == CBATTError.insufficientEncryption.rawValue
1797
2183
  }
1798
2184
  if error.domain == CBErrorDomain {
1799
- return error.code == CBError.peerRemovedPairingInformation.rawValue
2185
+ return Self.isPeerRemovedPairingInformation(error)
1800
2186
  }
1801
2187
  return false
1802
2188
  }
1803
2189
 
1804
- private func clearSavedGlassesAfterOwnerLoss(reason: String) {
1805
- Bridge.log("LIVE: Owner loss (\(reason)) — clearing saved glasses")
1806
- pairingYieldAwaitingReclaim = false
1807
- pairingYieldActive = false
1808
- pairingYieldEndWorkItem?.cancel()
1809
- pairingYieldEndWorkItem = nil
1810
- 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 }
1811
2272
  Task { @MainActor in
1812
- DeviceStore.shared.apply("bluetooth", "default_wearable", "")
1813
- DeviceStore.shared.apply("bluetooth", "device_name", "")
1814
- 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")
1815
2310
  }
1816
- Bridge.saveSetting("default_wearable", "")
1817
- Bridge.saveSetting("device_name", "")
1818
- Bridge.saveSetting("device_address", "")
1819
- Bridge.sendTypedMessage("owner_replaced", body: ["reason": reason])
1820
2311
  }
1821
2312
 
1822
2313
  func connectById(_ deviceName: String) {
1823
- if pairingYieldActive {
1824
- 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)")
2317
+ return
2318
+ }
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
+ }
1825
2331
  return
1826
2332
  }
1827
- Bridge.log("connectById: \(deviceName)")
2333
+ pairFlow("connect_by_id", "name=\(deviceName)")
1828
2334
  cancelPendingReconnect(reason: "connect_by_id")
1829
2335
  // Save the device name for future reconnection
1830
2336
  UserDefaults.standard.set(deviceName, forKey: PREFS_DEVICE_NAME)
1831
2337
 
1832
- // Start scanning to find this specific device
1833
2338
  if centralManager == nil {
1834
2339
  centralManager = CBCentralManager(
1835
2340
  delegate: self, queue: bluetoothQueue,
@@ -1837,37 +2342,111 @@ class MentraLive: NSObject, SGCManager {
1837
2342
  )
1838
2343
  }
1839
2344
 
1840
- // Check for already-connected peripherals first
1841
- let connectedPeripherals = centralManager!.retrieveConnectedPeripherals(withServices: [
1842
- SERVICE_UUID,
1843
- ])
1844
- for peripheral in connectedPeripherals {
1845
- Bridge.log("Found already-connected peripheral: \(peripheral.name ?? "Unknown")")
1846
- if let name = peripheral.name,
1847
- name == "Xy_A" || name.hasPrefix("XyBLE_") || name.hasPrefix("MENTRA_LIVE_BLE")
1848
- || 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
1849
2388
  {
1850
- Bridge.log("Found already-connected peripheral: \(name)")
1851
- discoveredPeripherals[name] = peripheral
1852
- 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
+ }
1853
2411
 
1854
- // Check if this is the device we want
1855
- if let savedDeviceName = UserDefaults.standard.string(
1856
- forKey: PREFS_DEVICE_NAME
1857
- ),
1858
- savedDeviceName == name
1859
- {
1860
- Bridge.log(
1861
- "Found our remembered device already connected, connecting: \(name)"
1862
- )
1863
- connectToDevice(peripheral)
1864
- return
1865
- }
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
1866
2443
  }
1867
2444
  }
2445
+ return nil
2446
+ }
1868
2447
 
1869
- // Will connect when found during scan
1870
- startScan()
2448
+ private func pairFlow(_ event: String, _ detail: String) {
2449
+ Bridge.log("PAIRFLOW: \(event) \(detail)")
1871
2450
  }
1872
2451
 
1873
2452
  func getConnectedBluetoothName() -> String? {
@@ -1879,7 +2458,10 @@ class MentraLive: NSObject, SGCManager {
1879
2458
  Bridge.log("LIVE: disconnect deferred — waiting for unpair write")
1880
2459
  return
1881
2460
  }
1882
- 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
+ )
1883
2465
 
1884
2466
  // if rgbLedAuthorityClaimed {
1885
2467
  // sendRgbLedControlAuthority(false)
@@ -2193,31 +2775,50 @@ class MentraLive: NSObject, SGCManager {
2193
2775
  return commands.removeFirst()
2194
2776
  }
2195
2777
 
2778
+ var count: Int { commands.count }
2779
+
2780
+ /// Discards the run of writes from earlier wire-session generations at the head of
2781
+ /// the queue in one pass and dequeues the first current one. Stale writes are never
2782
+ /// sent, so they must not each cost a drain tick: a burst of epoch resets would
2783
+ /// otherwise park every current write behind seconds of dead entries.
2784
+ func dequeue(currentGeneration: Int) -> (command: PendingMessage?, staleIds: [String]) {
2785
+ let firstCurrent = commands.firstIndex { $0.generation == currentGeneration } ?? commands.endIndex
2786
+ let staleIds = commands[..<firstCurrent].map(\.id)
2787
+ commands.removeSubrange(..<firstCurrent)
2788
+ return (commands.isEmpty ? nil : commands.removeFirst(), staleIds)
2789
+ }
2790
+
2196
2791
  func removeAll() {
2197
2792
  commands.removeAll()
2198
2793
  }
2199
2794
  }
2200
2795
 
2796
+ var pendingBleCommandCount: Int { commandQueue.count }
2797
+
2201
2798
  private func setupCommandQueue() {
2202
2799
  Task.detached { [weak self] in
2203
2800
  guard let self else { return }
2204
2801
  while true {
2205
2802
  let pendingIsNil = await MainActor.run { self.pending == nil }
2206
- if pendingIsNil {
2207
- if let command = await self.commandQueue.dequeue() {
2208
- let currentGeneration = await MainActor.run { self.wireSessionGeneration }
2209
- if command.generation != currentGeneration {
2210
- Bridge.log("LIVE: Dropping stale queued write from a previous session epoch (id: \(command.id))")
2211
- } else {
2212
- await self.processSendQueue(command)
2213
- }
2214
- }
2803
+ if pendingIsNil, let command = await self.dequeueCurrentGenerationWrite() {
2804
+ await self.processSendQueue(command)
2215
2805
  }
2216
2806
  try? await Task.sleep(nanoseconds: 100_000_000) // 100ms
2217
2807
  }
2218
2808
  }
2219
2809
  }
2220
2810
 
2811
+ private func dequeueCurrentGenerationWrite() -> PendingMessage? {
2812
+ let next = commandQueue.dequeue(currentGeneration: wireSessionGeneration)
2813
+ if !next.staleIds.isEmpty {
2814
+ Bridge.log(
2815
+ "LIVE: Dropping \(next.staleIds.count) stale queued write(s) from a previous session epoch " +
2816
+ "(ids: \(next.staleIds.joined(separator: ", ")))"
2817
+ )
2818
+ }
2819
+ return next.command
2820
+ }
2821
+
2221
2822
  private func processSendQueue(_ message: PendingMessage) async {
2222
2823
  guard let peripheral = connectedPeripheral,
2223
2824
  let txChar = txCharacteristic
@@ -2308,25 +2909,26 @@ class MentraLive: NSObject, SGCManager {
2308
2909
 
2309
2910
  // MARK: - BLE Scanning
2310
2911
 
2311
- private func startScan() {
2312
- if pairingYieldActive {
2313
- Bridge.log("LIVE: startScan blocked — pairing yield active")
2314
- return
2315
- }
2316
-
2912
+ private func startScan(reason: String = "scan") {
2317
2913
  guard centralManager!.state == .poweredOn else {
2318
- 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)")
2319
2915
  return
2320
2916
  }
2321
2917
 
2322
- Bridge.log("Starting BLE scan for Mentra Live glasses")
2918
+ pairFlow("scan", "start trigger=\(reason) target=\(UserDefaults.standard.string(forKey: PREFS_DEVICE_NAME) ?? "-")")
2323
2919
  discoveredAdvPairing.removeAll()
2920
+ loggedUnnamedDiscoveries.removeAll()
2324
2921
  isScanning = true
2922
+ pairingWatchScanActive = false
2325
2923
 
2326
2924
  startReadinessCheckLoop()
2327
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.
2328
2930
  let scanOptions: [String: Any] = [
2329
- CBCentralManagerScanOptionAllowDuplicatesKey: false,
2931
+ CBCentralManagerScanOptionAllowDuplicatesKey: manualDiscoveryActive,
2330
2932
  ]
2331
2933
 
2332
2934
  // let knownPeripherals = centralManager?.retrieveConnectedPeripherals(withServices: [SERVICE_UUID])
@@ -2360,18 +2962,24 @@ class MentraLive: NSObject, SGCManager {
2360
2962
  centralManager?.stopScan()
2361
2963
  isScanning = false
2362
2964
  DeviceStore.shared.apply(ObservableStore.bluetoothCategory, "searching", false)
2363
- Bridge.log("LIVE: BLE scan stopped")
2965
+ pairFlow("scan", "stop")
2364
2966
  }
2365
2967
 
2366
2968
  // MARK: - Connection Management
2367
2969
 
2368
2970
  private func connectToDevice(_ peripheral: CBPeripheral) {
2369
- if pairingYieldActive {
2370
- 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
+ )
2371
2976
  isConnecting = false
2372
2977
  return
2373
2978
  }
2374
- 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
+ )
2375
2983
 
2376
2984
  // A timed attempt supersedes any pending reconnect: withdraw one aimed at other
2377
2985
  // glasses, and drop tracking for this one so its settle timer cannot touch this attempt.
@@ -2402,7 +3010,8 @@ class MentraLive: NSObject, SGCManager {
2402
3010
  guard let centralManager,
2403
3011
  MentraLiveConnectionAttemptPolicy.shouldReconnectDirectly(
2404
3012
  isKilled: isKilled,
2405
- pairingYieldActive: pairingYieldActive,
3013
+ // A window just ended: scan first so its advertisement is read.
3014
+ pairingYieldActive: automaticConnectBlocked() || pairingStore.awaitingTakeoverCheck,
2406
3015
  bluetoothPoweredOn: centralManager.state == .poweredOn,
2407
3016
  peripheralName: peripheral.name,
2408
3017
  savedDeviceName: UserDefaults.standard.string(forKey: PREFS_DEVICE_NAME)
@@ -2433,9 +3042,13 @@ class MentraLive: NSObject, SGCManager {
2433
3042
  // The default requirement lets the system complete that authorization flow
2434
3043
  // before the glasses subscribe; apps that do not relay notifications can opt out.
2435
3044
  Bridge.log("LIVE: ANCS connection requirement \(requiresAncs ? "enabled" : "disabled")")
3045
+ Bridge.log("LIVE: Transport bridging \(Self.enableTransportBridging ? "enabled" : "disabled")")
2436
3046
  centralManager?.connect(
2437
3047
  peripheral,
2438
- options: MentraLiveConnectionOptions.coreBluetoothOptions(requiresAncs: requiresAncs)
3048
+ options: MentraLiveConnectionOptions.coreBluetoothOptions(
3049
+ requiresAncs: requiresAncs,
3050
+ enableTransportBridging: Self.enableTransportBridging
3051
+ )
2439
3052
  )
2440
3053
  #endif
2441
3054
  }
@@ -2523,8 +3136,11 @@ class MentraLive: NSObject, SGCManager {
2523
3136
  return
2524
3137
  }
2525
3138
 
2526
- if pairingYieldActive {
2527
- 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
+ }
2528
3144
  return
2529
3145
  }
2530
3146
 
@@ -2561,8 +3177,8 @@ class MentraLive: NSObject, SGCManager {
2561
3177
  guard let self = self else { return }
2562
3178
 
2563
3179
  // Use peripheral presence, not connectionState: we stay CONNECTING during backoff until scan/connect.
2564
- if self.pairingYieldActive {
2565
- Bridge.log("LIVE: Reconnection aborted - pairing yield active")
3180
+ if self.automaticConnectBlocked() {
3181
+ Bridge.log("LIVE: Reconnection aborted - pairing state \(self.pairingStore.describe())")
2566
3182
  return
2567
3183
  }
2568
3184
  if self.connectedPeripheral == nil, !self.isKilled {
@@ -2611,6 +3227,7 @@ class MentraLive: NSObject, SGCManager {
2611
3227
  private func attachL2capFileChannel(_ channel: CBL2CAPChannel) {
2612
3228
  closeL2capFileChannel()
2613
3229
 
3230
+ guard let peer = connectedPeripheral, let token = notificationIngress.capture(peer) else { return }
2614
3231
  let channelId = UUID()
2615
3232
  l2capFileChannelId = channelId
2616
3233
  let reader = MentraLiveL2capChannel(
@@ -2620,7 +3237,7 @@ class MentraLive: NSObject, SGCManager {
2620
3237
  // while the existing transfer state remains serialized on the main actor.
2621
3238
  DispatchQueue.main.async {
2622
3239
  guard let self, self.l2capFileChannelId == channelId else { return }
2623
- self.processReceivedData(frame)
3240
+ self.receiveBleNotification(frame, token: token)
2624
3241
  }
2625
3242
  },
2626
3243
  onClose: { [weak self] in
@@ -2796,28 +3413,34 @@ class MentraLive: NSObject, SGCManager {
2796
3413
 
2797
3414
  switch type {
2798
3415
  case "glasses_ready":
2799
- // A queued glasses_ready from the connection we just cancelled for yield
2800
- // must not close the pairing window. Only accept readiness on a live GATT.
2801
- if pairingYieldActive && connectedPeripheral == nil {
2802
- 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")
3420
+ return
3421
+ }
3422
+ let sid = (json["sid"] as? String).flatMap { $0.isEmpty ? nil : $0 }
3423
+ let readyId = (json["readyId"] as? String).flatMap { $0.isEmpty ? nil : $0 }
3424
+ if let readyId, isRepeatedGlassesReady(readyId: readyId, sid: sid) {
3425
+ Bridge.log("LIVE: Ignoring repeated glasses_ready for readiness exchange \(readyId) - the glasses did not reset for it")
2803
3426
  return
2804
3427
  }
3428
+ if readyId != nil, readyId == pendingReadyId {
3429
+ pendingReadyId = nil
3430
+ }
3431
+ readyGlassesSessionId = sid
2805
3432
  // glasses_ready is a REMOTE wire-session reset: the glasses ran
2806
3433
  // onTransportReset() before sending it, so their side is back on legacy
2807
3434
  // framing regardless of what this side negotiated earlier. Start a fresh
2808
3435
  // wire epoch (clears v2-active state that would otherwise gate the
2809
3436
  // handshake off), then negotiate from the caps this message advertises.
2810
- pairingYieldAwaitingReclaim = false
2811
- pairingYieldActive = false
2812
- pairingYieldEndWorkItem?.cancel()
2813
- pairingYieldEndWorkItem = nil
2814
3437
  resetWireNegotiationState()
2815
3438
  parsePeerWireCaps(json)
2816
3439
  maybeSendWireHandshake()
2817
3440
  // Record the session id BEFORE marking ready: an unsolicited glasses_ready
2818
3441
  // already runs this full remote-reset flow, so recording (not re-triggering)
2819
3442
  // is correct here; version_info detection covers the restart case.
2820
- glassesSessionId = (json["sid"] as? String).flatMap { $0.isEmpty ? nil : $0 }
3443
+ glassesSessionId = sid
2821
3444
  streamControlVersion = json["streamControlVersion"] as? Int ?? 0
2822
3445
  Bridge.sendTypedMessage(
2823
3446
  "wifi_protocol_session_ready",
@@ -3006,25 +3629,113 @@ class MentraLive: NSObject, SGCManager {
3006
3629
  Bridge.log("LIVE: Received pong response - connection healthy")
3007
3630
 
3008
3631
  case "entering_pairing_mode":
3009
- let windowMs = max(5000, min(180_000, json["window_ms"] as? Int ?? 120_000))
3010
- Bridge.log("LIVE: Glasses entering pairing mode — yield \(windowMs)ms (no forget)")
3011
- enterPairingYield(windowMs: windowMs)
3012
- let body: [String: Any] = [
3013
- "window_ms": windowMs,
3014
- "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,
3015
3643
  ]
3016
- 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)
3017
3671
 
3018
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() }
3019
3711
  Bridge.sendPairingInfo(
3020
3712
  hadPreviousBond: json["had_previous_bond"] as? Bool ?? false,
3021
3713
  pairingCode: json["pairing_code"] as? String,
3022
3714
  classicBondReady: json["classic_bond_ready"] as? Bool ?? false,
3023
- // Legacy firmware that omits this field is not secure-capable.
3024
- securePairingCapable: json["secure_pairing_capable"] as? Bool ?? false,
3025
- 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
3026
3720
  )
3027
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
+
3028
3739
  case "imu_response", "imu_stream_response", "imu_gesture_response",
3029
3740
  "imu_gesture_subscribed", "imu_ack", "imu_error":
3030
3741
  // Handle IMU-related responses
@@ -3065,6 +3776,11 @@ class MentraLive: NSObject, SGCManager {
3065
3776
  Bridge.log("LIVE: 📱 Received ota_start_ack from glasses")
3066
3777
  Bridge.sendOtaStartAck()
3067
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
+
3068
3784
  case "ota_status":
3069
3785
  // Short keys (sid/ts/cs/st/sq/sp/op/err) are used by new firmware to keep BLE payload small.
3070
3786
  // Verbose keys (session_id/total_steps/…) are the fallback for older firmware.
@@ -3204,6 +3920,7 @@ class MentraLive: NSObject, SGCManager {
3204
3920
  )
3205
3921
  }
3206
3922
  if let bluetoothMacAddress = nonEmptyStringValue(fields, "bt_mac_address") {
3923
+ recordWifiAdbPeerIdentity(bluetoothMacAddress)
3207
3924
  DeviceStore.shared.apply("glasses", "bluetoothMacAddress", bluetoothMacAddress)
3208
3925
  }
3209
3926
  if let wifiMacAddress = nonEmptyStringValue(fields, "wifi_mac_address") {
@@ -3341,6 +4058,11 @@ class MentraLive: NSObject, SGCManager {
3341
4058
  processAncsRelay(body)
3342
4059
  }
3343
4060
 
4061
+ case "sr_tpdef":
4062
+ if let body = k900ParseBody(json["B"]), body["setting"] as? String == "touch_gesture_default" {
4063
+ emitSettingsAck(body)
4064
+ }
4065
+
3344
4066
  case "sr_hrt":
3345
4067
  if let bodyObj = json["B"] as? [String: Any] {
3346
4068
  let readyResponse = bodyObj["ready"] as? Int ?? 0
@@ -3383,12 +4105,7 @@ class MentraLive: NSObject, SGCManager {
3383
4105
  // This prevents re-initialization on every heartbeat after initial connection
3384
4106
  // The ready flag is reset on disconnect/reconnect, so this won't prevent proper reconnection
3385
4107
  if !fullyBooted {
3386
- let readyMsg: [String: Any] = [
3387
- "type": "phone_ready",
3388
- "timestamp": Int64(Date().timeIntervalSince1970 * 1000),
3389
- ]
3390
- // Send it through our data channel
3391
- sendJson(readyMsg, wakeUp: true)
4108
+ sendPhoneReady(reason: "SOC ready")
3392
4109
  }
3393
4110
  }
3394
4111
  }
@@ -3685,6 +4402,66 @@ class MentraLive: NSObject, SGCManager {
3685
4402
  sendJson(json, wakeUp: true)
3686
4403
  }
3687
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
+
3688
4465
  func sendWifiAdbState(_ enabled: Bool) {
3689
4466
  Bridge.log("LIVE: 🔧 Sending Wi-Fi ADB state: \(enabled)")
3690
4467
 
@@ -3745,12 +4522,14 @@ class MentraLive: NSObject, SGCManager {
3745
4522
  }
3746
4523
  let bKey = MentraLive.incidentBleFileBase(incidentId: incidentId, prefix: "B")
3747
4524
  let lKey = MentraLive.incidentBleFileBase(incidentId: incidentId, prefix: "L")
3748
- bleIncidentLogRelays[bKey] = BleIncidentLogRelayEntry(
3749
- 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
3750
4528
  )
3751
- bleIncidentLogRelays[lKey] = BleIncidentLogRelayEntry(
3752
- fileBaseKey: lKey, incidentId: incidentId, apiBaseUrl: base, kind: .logcat
4529
+ let lRelay = BleIncidentLogRelayEntry(
4530
+ fileBaseKey: lKey, incidentId: incidentId, apiBaseUrl: base, kind: .logcat, reservedAt: now
3753
4531
  )
4532
+ try reserveIncidentRelays([bRelay, lRelay], now: now)
3754
4533
 
3755
4534
  let auth: [String: Any] = [
3756
4535
  "type": "auth_token", "coreToken": coreToken,
@@ -3761,13 +4540,56 @@ class MentraLive: NSObject, SGCManager {
3761
4540
  sendJson(["type": "upload_incident_logs", "incidentId": incidentId, "apiBaseUrl": base],
3762
4541
  wakeUp: true, requireAck: true, bridgeLogging: true)
3763
4542
  else {
3764
- bleIncidentLogRelays.removeValue(forKey: bKey)
3765
- bleIncidentLogRelays.removeValue(forKey: lKey)
4543
+ releaseIncidentRelay(bRelay)
4544
+ releaseIncidentRelay(lRelay)
3766
4545
  throw BluetoothSdkError(code: "incident_dispatch_failed", message: "Could not queue the glasses incident-log request.")
3767
4546
  }
3768
4547
  Bridge.log("LIVE: Queued incidentId to glasses for log upload: \(incidentId) (BLE relay \(bKey), \(lKey))")
3769
4548
  }
3770
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
+
3771
4593
  private static func incidentBleFileBase(incidentId: String, prefix: Character) -> String {
3772
4594
  var compact = incidentId.replacingOccurrences(of: "-", with: "").lowercased()
3773
4595
  if compact.count < 15 {
@@ -3850,6 +4672,25 @@ class MentraLive: NSObject, SGCManager {
3850
4672
  sendJson(json, wakeUp: true)
3851
4673
  }
3852
4674
 
4675
+ func sendTouchGestureDefaultBehaviorEnabled(requestId: String, gesture: TouchGesture, enabled: Bool) throws {
4676
+ guard connectedPeripheral != nil, txCharacteristic != nil else {
4677
+ throw BluetoothSdkError(code: "not_connected", message: "Mentra Live glasses are not connected.")
4678
+ }
4679
+ try sendTouchGestureDefaultCommand(requestId: requestId, gesture: gesture, enabled: enabled)
4680
+ }
4681
+
4682
+ /// Kept separate from readiness admission so tests can replay the real K900 wire exchange.
4683
+ func sendTouchGestureDefaultCommand(requestId: String, gesture: TouchGesture, enabled: Bool) throws {
4684
+ let body = try JSONSerialization.data(withJSONObject: [
4685
+ "request_id": requestId, "gesture": gesture.rawValue, "enabled": enabled,
4686
+ ])
4687
+ guard let bodyString = String(data: body, encoding: .utf8),
4688
+ sendRawK900Command(["C": "cs_tpdef", "V": 1, "B": bodyString])
4689
+ else {
4690
+ throw BluetoothSdkError(code: "command_send_failed", message: "Could not encode the touch gesture setting.")
4691
+ }
4692
+ }
4693
+
3853
4694
  func sendGalleryServerEnabled(requestId: String, enabled: Bool) {
3854
4695
  sendJson([
3855
4696
  "type": "set_gallery_server_enabled",
@@ -3920,7 +4761,25 @@ class MentraLive: NSObject, SGCManager {
3920
4761
 
3921
4762
  // MARK: - Message Handlers
3922
4763
 
4764
+ /// A glasses_ready that echoes a readyId answers a phone_ready exchange. The answer to the
4765
+ /// exchange the phone is waiting on, and any answer from a glasses process other than the
4766
+ /// one this link last handled (an asg restart resets for every exchange it first sees),
4767
+ /// followed a transport reset. Any other answer repeats an exchange that process already
4768
+ /// reset for, or one superseded by the pending exchange, whose answer is still to come.
4769
+ private func isRepeatedGlassesReady(readyId: String, sid: String?) -> Bool {
4770
+ readyId != pendingReadyId && sid == readyGlassesSessionId
4771
+ }
4772
+
4773
+ private func resetReadinessExchange() {
4774
+ pendingReadyId = nil
4775
+ readyGlassesSessionId = nil
4776
+ }
4777
+
3923
4778
  private func handleGlassesReady() {
4779
+ pairFlow(
4780
+ "glasses_ready",
4781
+ "id=\(connectedPeripheral?.identifier.uuidString ?? "-") name=\(connectedPeripheral?.name ?? "-") gatt=\(txCharacteristic != nil)"
4782
+ )
3924
4783
  Bridge.log("LIVE: 🎉 Received glasses_ready message - SOC is booted and ready!")
3925
4784
 
3926
4785
  stopReadinessCheckLoop()
@@ -3978,11 +4837,142 @@ class MentraLive: NSObject, SGCManager {
3978
4837
  }
3979
4838
  }
3980
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)
3981
4879
  fullyBooted = true
3982
4880
  connected = true
3983
4881
  updateConnectionState(ConnTypes.CONNECTED)
3984
4882
  }
3985
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
+
3986
4976
  private func handleWifiScanResult(_ json: [String: Any]) {
3987
4977
  var networks: [[String: Any]] = []
3988
4978
 
@@ -4019,6 +5009,7 @@ class MentraLive: NSObject, SGCManager {
4019
5009
  DeviceStore.shared.apply("glasses", "otaVersionUrl", otaVersionUrl)
4020
5010
  DeviceStore.shared.apply("glasses", "firmwareVersion", firmwareVersion)
4021
5011
  if let bluetoothMacAddress {
5012
+ recordWifiAdbPeerIdentity(bluetoothMacAddress)
4022
5013
  DeviceStore.shared.apply("glasses", "bluetoothMacAddress", bluetoothMacAddress)
4023
5014
  }
4024
5015
  if let serialNumber {
@@ -4426,6 +5417,15 @@ class MentraLive: NSObject, SGCManager {
4426
5417
  if sess.isComplete {
4427
5418
  Bridge.log("LIVE: 📦 File transfer complete: \(packetInfo.fileName)")
4428
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
+
4429
5429
  if let fileData = sess.assembleFile() {
4430
5430
  saveReceivedFile(
4431
5431
  fileName: packetInfo.fileName, fileData: fileData,
@@ -4527,7 +5527,7 @@ class MentraLive: NSObject, SGCManager {
4527
5527
  ]
4528
5528
  }
4529
5529
 
4530
- private func uploadBleIncidentLogRelay(
5530
+ func uploadBleIncidentLogRelay(
4531
5531
  relay: BleIncidentLogRelayEntry, fileName: String, data: Data
4532
5532
  ) {
4533
5533
  let token = DeviceStore.shared.get("bluetooth", "core_token") as? String ?? ""
@@ -4578,14 +5578,24 @@ class MentraLive: NSObject, SGCManager {
4578
5578
  statusCode = nil
4579
5579
  }
4580
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
+ }
4581
5587
  if ok {
4582
5588
  Bridge.log("LIVE: ✅ Incident log BLE relay uploaded (\(relay.kind))")
4583
- self.bleIncidentLogRelays.removeValue(forKey: relay.fileBaseKey)
4584
5589
  } else if let existing = self.bleIncidentLogRelays[relay.fileBaseKey] {
4585
5590
  // Keep relay entry for glasses retry after transfer_complete:false.
4586
5591
  existing.session = nil
4587
5592
  }
4588
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
+ }
4589
5599
  }
4590
5600
  }.resume()
4591
5601
  }
@@ -4701,6 +5711,10 @@ class MentraLive: NSObject, SGCManager {
4701
5711
  }
4702
5712
 
4703
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
+ }
4704
5718
  let significantQueueSize = SIGNIFICANT_BLE_TRACE_QUEUE_SIZE
4705
5719
  // Insert synchronously on MainActor so fragments and dependent commands retain call order.
4706
5720
  let generation = wireSessionGeneration
@@ -4805,7 +5819,8 @@ class MentraLive: NSObject, SGCManager {
4805
5819
  }
4806
5820
  }
4807
5821
 
4808
- 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)
4809
5824
  }
4810
5825
 
4811
5826
  private func bleTraceWarningReason(stage: String, extra: [String: Any?]) -> String? {
@@ -5135,7 +6150,8 @@ class MentraLive: NSObject, SGCManager {
5135
6150
  direction: "phone_to_glasses",
5136
6151
  layer: "sdk_ble_command",
5137
6152
  payload: json,
5138
- bytes: jsonData.count
6153
+ bytes: jsonData.count,
6154
+ forwardToBridge: bridgeLogging
5139
6155
  )
5140
6156
 
5141
6157
  if useBinaryWireProtocol, isNewVersion {
@@ -5747,7 +6763,10 @@ class MentraLive: NSObject, SGCManager {
5747
6763
  private var readinessCheckDispatchTimer: DispatchSourceTimer?
5748
6764
 
5749
6765
  private func startReadinessCheckLoop() {
5750
- Bridge.log("LIVE: startReadinessCheckLoop()")
6766
+ pairFlow(
6767
+ "readiness",
6768
+ "start gatt=\(txCharacteristic != nil) id=\(connectedPeripheral?.identifier.uuidString ?? "-") name=\(connectedPeripheral?.name ?? "-")"
6769
+ )
5751
6770
  stopReadinessCheckLoop()
5752
6771
 
5753
6772
  readinessCheckCounter = 0
@@ -5767,17 +6786,25 @@ class MentraLive: NSObject, SGCManager {
5767
6786
  guard let self else { return }
5768
6787
 
5769
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
+ }
5770
6796
  Bridge.log(
5771
- "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)"
5772
6798
  )
5773
6799
  // requestReadyK900()
5774
6800
 
5775
- let readyMsg: [String: Any] = [
5776
- "type": "phone_ready",
5777
- "timestamp": Int64(Date().timeIntervalSince1970 * 1000),
5778
- ]
5779
- // Send it through our data channel
5780
- sendJson(readyMsg, wakeUp: true)
6801
+ // The timer fires on bluetoothQueue; the pending readiness exchange is main-actor state.
6802
+ // A tick queued just before glasses_ready stopped the loop must not start a new exchange.
6803
+ let check = self.readinessCheckCounter
6804
+ DispatchQueue.main.async { [weak self] in
6805
+ guard let self, self.readinessCheckDispatchTimer != nil else { return }
6806
+ self.sendPhoneReady(reason: "readiness check #\(check)")
6807
+ }
5781
6808
  }
5782
6809
 
5783
6810
  readinessCheckDispatchTimer!.resume()
@@ -5799,8 +6826,15 @@ class MentraLive: NSObject, SGCManager {
5799
6826
  }
5800
6827
 
5801
6828
  private func stopReadinessCheckLoop() {
6829
+ let wasRunning = readinessCheckDispatchTimer != nil
5802
6830
  readinessCheckDispatchTimer?.cancel()
5803
6831
  readinessCheckDispatchTimer = nil
6832
+ if wasRunning {
6833
+ pairFlow(
6834
+ "readiness",
6835
+ "stop n=\(readinessCheckCounter) gatt=\(txCharacteristic != nil) id=\(connectedPeripheral?.identifier.uuidString ?? "-")"
6836
+ )
6837
+ }
5804
6838
  Bridge.log("LIVE: 🔄 Stopped glasses SOC readiness check loop")
5805
6839
  }
5806
6840
 
@@ -5812,6 +6846,10 @@ class MentraLive: NSObject, SGCManager {
5812
6846
  guard let self else { return }
5813
6847
 
5814
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
+ )
5815
6853
  Bridge.log("LIVE: Connection timeout - closing GATT connection")
5816
6854
  self.isConnecting = false
5817
6855
 
@@ -5846,7 +6884,7 @@ class MentraLive: NSObject, SGCManager {
5846
6884
  /// promotes it to the default device. Re-emit only that explicit pending target; an
5847
6885
  /// established owner's connected glasses have no pending identity and remain hidden.
5848
6886
  private func emitConnectedPendingDeviceForPairingScan() {
5849
- guard manualDiscoveryActive, !pairingYieldActive, let peripheral = connectedPeripheral,
6887
+ guard manualDiscoveryActive, let peripheral = connectedPeripheral,
5850
6888
  let name = peripheral.name,
5851
6889
  MentraLivePendingPairingTarget.shouldRecover(
5852
6890
  isConnected: peripheral.state == .connected,
@@ -5872,17 +6910,35 @@ class MentraLive: NSObject, SGCManager {
5872
6910
  )
5873
6911
  }
5874
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
5875
6926
  private func cacheAdvPairing(
5876
6927
  _ name: String,
5877
6928
  pairingMode: Bool,
5878
6929
  pairingCode: String?,
5879
6930
  securePairingCapable: Bool
5880
- ) {
5881
- discoveredAdvPairing[name] = CachedAdvPairing(
6931
+ ) -> Bool {
6932
+ let next = CachedAdvPairing(
5882
6933
  pairingMode: pairingMode,
5883
6934
  pairingCode: pairingCode,
5884
6935
  securePairingCapable: securePairingCapable
5885
6936
  )
6937
+ if discoveredAdvPairing[name] == next {
6938
+ return false
6939
+ }
6940
+ discoveredAdvPairing[name] = next
6941
+ return true
5886
6942
  }
5887
6943
 
5888
6944
  private func emitDiscoveredDeviceFromCache(
@@ -6003,9 +7059,14 @@ class MentraLive: NSObject, SGCManager {
6003
7059
  // MARK: - Cleanup
6004
7060
 
6005
7061
  private func destroy() {
6006
- Bridge.log("Destroying MentraLiveManager")
7062
+ pairFlow(
7063
+ "destroy",
7064
+ "name=\(connectedPeripheral?.name ?? "-") id=\(connectedPeripheral?.identifier.uuidString ?? "-") scanning=\(isScanning)"
7065
+ )
6007
7066
 
6008
7067
  isKilled = true
7068
+ // The pairing state outlives the manager; only its timer belongs to this instance.
7069
+ cancelPairingPauseTimer()
6009
7070
  unpairFlushWorkItem?.cancel()
6010
7071
  unpairFlushWorkItem = nil
6011
7072
  unpairFlushPending = false
@@ -6023,6 +7084,7 @@ class MentraLive: NSObject, SGCManager {
6023
7084
  // Stop all timers
6024
7085
  stopAllTimers()
6025
7086
  resetWireNegotiationState()
7087
+ resetReadinessExchange()
6026
7088
  commandQueue.removeAll() // stale writes die with the session
6027
7089
  closeL2capFileChannel()
6028
7090
 
@@ -6049,6 +7111,92 @@ class MentraLive: NSObject, SGCManager {
6049
7111
  centralManager = nil
6050
7112
 
6051
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
+ )
6052
7200
  }
6053
7201
  }
6054
7202
 
@@ -6152,10 +7300,16 @@ extension MentraLive {
6152
7300
 
6153
7301
  /// Sends phone_ready to (re)start the glasses-driven readiness flow.
6154
7302
  private func sendPhoneReady(reason: String) {
6155
- Bridge.log("LIVE: 📱 Sending phone_ready to glasses (\(reason)) - waiting for glasses_ready response")
7303
+ let readyId = pendingReadyId ?? UUID().uuidString
7304
+ pendingReadyId = readyId
7305
+ pairFlow("phone_ready", "reason=\(reason) gatt=\(txCharacteristic != nil) id=\(connectedPeripheral?.identifier.uuidString ?? "-")")
7306
+ Bridge.log(
7307
+ "LIVE: 📱 Sending phone_ready to glasses (\(reason), exchange \(readyId)) - waiting for glasses_ready response"
7308
+ )
6156
7309
  let readyMsg: [String: Any] = [
6157
7310
  "type": "phone_ready",
6158
7311
  "timestamp": Int64(Date().timeIntervalSince1970 * 1000),
7312
+ "readyId": readyId,
6159
7313
  ]
6160
7314
  sendJson(readyMsg, wakeUp: true)
6161
7315
  }