@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
@@ -40,6 +40,7 @@ import com.mentra.bluetoothsdk.DeviceManager
40
40
  import com.mentra.bluetoothsdk.PhotoRequest
41
41
  import com.mentra.bluetoothsdk.PhotoSize
42
42
  import com.mentra.bluetoothsdk.PhotoMode
43
+ import com.mentra.bluetoothsdk.TouchGesture
43
44
  import com.mentra.bluetoothsdk.DeviceStore
44
45
  import com.mentra.bluetoothsdk.ObservableStore
45
46
  import com.mentra.bluetoothsdk.incomingGlassesMessageAckId
@@ -131,6 +132,10 @@ class MentraLive : SGCManager() {
131
132
  private val besOtaHeartbeatGuard = BesOtaHeartbeatGuard()
132
133
 
133
134
  companion object {
135
+ internal fun wifiAdbPeerMatches(expected: String, identity: Pair<Long, String>?, generation: Long, connected: Boolean): Boolean =
136
+ connected && expected.matches(Regex("^(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$")) &&
137
+ identity != null && identity.first == generation && identity.second.equals(expected, ignoreCase = true)
138
+
134
139
  private const val TAG = "Live"
135
140
 
136
141
  // Feature Flags
@@ -150,6 +155,9 @@ class MentraLive : SGCManager() {
150
155
  private const val A2DP_CONNECT_MAX_ATTEMPTS = 5
151
156
  private const val A2DP_CONNECT_RETRY_MS = 800L
152
157
  private const val UNPAIR_FLUSH_MS = 400L
158
+ // Longer than the glasses' bounded relay of one report (BES logs, two file transfers,
159
+ // the phone POST), so an unreleased name cannot be reused while its report is in flight.
160
+ internal const val INCIDENT_RELAY_OWNERSHIP_MS = 10 * 60_000L
153
161
  private const val GATT_DISCONNECT_TIMEOUT_MS = 2_000L
154
162
  private const val MTU_CALLBACK_TIMEOUT_MS = 3_000L
155
163
  private val gattTeardownBarrier = MentraLiveGattTeardownBarrier()
@@ -198,6 +206,8 @@ class MentraLive : SGCManager() {
198
206
  10_000L // 10s before first scan after shutdown
199
207
 
200
208
  private const val MENTRA_MANUFACTURER_ID = 0xB822
209
+ /** `phone_hello.pairing_protocol`: this SDK speaks ownership transfer v4. */
210
+ private const val PAIRING_PROTOCOL_VERSION = 4
201
211
 
202
212
  private fun manufacturerData(result: ScanResult): ByteArray? {
203
213
  return result.scanRecord?.getManufacturerSpecificData(MENTRA_MANUFACTURER_ID)
@@ -216,9 +226,16 @@ class MentraLive : SGCManager() {
216
226
  val advertisement =
217
227
  MentraLivePairingAdvertisementParser.parse(manufacturerData(result))
218
228
  ?: return Triple(false, null, false)
229
+ result.device?.address?.let { secureTrailerScanMemory.noteSecureTrailer(it) }
219
230
  return Triple(advertisement.pairingMode, advertisement.pairingCode, true)
220
231
  }
221
232
 
233
+ /**
234
+ * Addresses advertising the secure-pairing trailer in the current scan; survives SGC
235
+ * recreation and clears at each [startScan].
236
+ */
237
+ private val secureTrailerScanMemory = MentraLiveSecureTrailerScanMemory()
238
+
222
239
  fun isMentraLiveBluetoothName(name: String?): Boolean {
223
240
  if (name.isNullOrEmpty()) {
224
241
  return false
@@ -443,6 +460,22 @@ class MentraLive : SGCManager() {
443
460
  }
444
461
  }
445
462
 
463
+ /** The one Mentra Live this phone is bonded with. Null when there is none, several, or no permission to read bonds. */
464
+ fun soleBondedMentraLive(context: Context?): BluetoothDevice? {
465
+ val adapter =
466
+ (context?.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)
467
+ ?.adapter
468
+ ?: return null
469
+ return try {
470
+ adapter.bondedDevices
471
+ ?.filter { isMentraLiveBluetoothName(safeBondedDeviceName(it)) }
472
+ ?.singleOrNull()
473
+ } catch (e: Exception) {
474
+ Bridge.log("LIVE: Unable to read bonded devices: " + e.message)
475
+ null
476
+ }
477
+ }
478
+
446
479
  private const val SHUTDOWN_RECENT_MS = 45_000L // Consider "recent shutdown" for 45s
447
480
 
448
481
  // Keep-alive parameters
@@ -465,9 +498,9 @@ class MentraLive : SGCManager() {
465
498
  private const val PREFS_NAME = "MentraLivePrefs"
466
499
  private const val PREF_DEVICE_NAME = "LastConnectedDeviceName"
467
500
 
468
- // Auth settings
469
- private const val AUTH_PREFS_NAME = "augmentos_auth_prefs"
470
- private const val KEY_CORE_TOKEN = "core_token"
501
+ // A Core token older builds kept in plain SharedPreferences. Deleted, never read.
502
+ private const val LEGACY_AUTH_PREFS_NAME = "augmentos_auth_prefs"
503
+ private const val LEGACY_KEY_CORE_TOKEN = "core_token"
471
504
 
472
505
  private const val MAX_BONDING_RETRIES = 3
473
506
  private const val BONDING_RETRY_DELAY_MS =
@@ -565,6 +598,13 @@ class MentraLive : SGCManager() {
565
598
  // the physical connection (never on heartbeat readiness flaps), so a first-seen sid
566
599
  // after an upgrade OTA is always detected as a restart.
567
600
  private var readinessCompletedThisBleSession = false
601
+ // Readiness exchange the phone is waiting on. Every phone_ready carries it until the
602
+ // matching glasses_ready arrives, so retries and the copies the BES buffers while the
603
+ // glasses boot are one exchange: the glasses reset their transport once for it and answer
604
+ // later copies without resetting. Both exchange fields are scoped to the BLE session.
605
+ private var pendingReadyId: String? = null
606
+ // `sid` of the glasses process whose glasses_ready this BLE session last handled.
607
+ private var readyGlassesSessionId: String? = null
568
608
  // Note: appVersion, buildNumber, deviceModel, androidVersion
569
609
  // are inherited from SGCManager parent class
570
610
 
@@ -617,11 +657,41 @@ class MentraLive : SGCManager() {
617
657
  private var isConnecting = false
618
658
  private var isKilled = false
619
659
 
620
- /** Glasses opened a pairing window — stop reconnect without forgetting identity/bonds. */
621
- private var pairingYieldActive = false
622
- private var pairingYieldEndRunnable: Runnable? = null
623
- /** After yield ends, auth/not-owner failures may clear saved glasses. */
624
- private var pairingYieldAwaitingReclaim = false
660
+ /**
661
+ * Ends the pairing-mode pause at its deadline. The pause itself lives in
662
+ * [MentraLivePairingStateStore] so it survives this instance.
663
+ */
664
+ private var pairingPauseEndRunnable: Runnable? = null
665
+ /** `phone_hello` / `pair_select` went out on this GATT session. */
666
+ @Volatile private var phoneHelloSentThisSession = false
667
+ @Volatile private var pairSelectSentThisSession = false
668
+ /** Fails an explicit secure pair if bonding never reaches a terminal state. */
669
+ private var secureBondWaitRunnable: Runnable? = null
670
+ /**
671
+ * glasses_ready arrived during an explicit secure pair but readiness is parked until the
672
+ * glasses report `owner_committed` (and the BLE bond exists). Mirrors iOS
673
+ * `awaitingSecurePairingConfirmation`.
674
+ */
675
+ @Volatile private var awaitingSecurePairingConfirmation = false
676
+ /** The glasses' `pairing_info` reported `owner_committed` on this GATT session. */
677
+ @Volatile private var securePairingConfirmed = false
678
+ /** `secure_pairing_capable` from this GATT session's `pairing_info`; null before one arrives. */
679
+ @Volatile private var sessionPairingInfoSecure: Boolean? = null
680
+ /** `pairing_info` has arrived on this GATT session. CTKD waits for it on an explicit secure pair. */
681
+ private val pairingInfoSeen: Boolean
682
+ get() = sessionPairingInfoSecure != null
683
+ /**
684
+ * glasses_ready arrived during an explicit pair whose target's secure capability is unknown;
685
+ * readiness is parked until `pairing_info` arrives or the unknown-capability wait ends.
686
+ */
687
+ @Volatile private var awaitingPairingInfoForReadiness = false
688
+ /** The unknown-capability wait ran out on this GATT session: the target counts as legacy. */
689
+ @Volatile private var unknownCapabilityWaitExpired = false
690
+ private var unknownCapabilityWaitRunnable: Runnable? = null
691
+ /** Clears `mentra_live_secure_firmware` when a ready session never sends `pairing_info`. */
692
+ private var secureFirmwareRefreshRunnable: Runnable? = null
693
+ /** elapsedRealtime of the last GATT link that was not an explicit pairing attempt. */
694
+ private var lastAutoReconnectLinkAt: Long? = null
625
695
  /** Hold GATT teardown until the unpair write can leave the phone. */
626
696
  private var unpairFlushPending = false
627
697
  private var unpairFlushRunnable: Runnable? = null
@@ -718,6 +788,7 @@ class MentraLive : SGCManager() {
718
788
 
719
789
  // Local state tracking (not in parent SGCManager)
720
790
  private var isCharging = false // Charging status (batteryLevel is in parent)
791
+ @Volatile private var wifiAdbPeerIdentity: Pair<Long, String>? = null
721
792
  private var isConnected = false
722
793
 
723
794
  // File transfer management
@@ -778,6 +849,7 @@ class MentraLive : SGCManager() {
778
849
  val apiBaseUrl: String,
779
850
  val kind: BleIncidentLogKind
780
851
  ) {
852
+ val reservedAtMs: Long = SystemClock.elapsedRealtime()
781
853
  var session: FileTransferSession? = null
782
854
  }
783
855
 
@@ -1033,6 +1105,7 @@ class MentraLive : SGCManager() {
1033
1105
  this.type = DeviceTypes.LIVE
1034
1106
  this.hasMic = true
1035
1107
  this.context = Bridge.getContext()
1108
+ forgetLegacyCoreToken()
1036
1109
 
1037
1110
  // Initialize bluetooth adapter
1038
1111
  val bluetoothManager =
@@ -1136,6 +1209,8 @@ class MentraLive : SGCManager() {
1136
1209
  } else {
1137
1210
  Bridge.log("LIVE: 🎵 Phone audio monitor disabled (BLOCK_AUDIO_DUPLEX=false)")
1138
1211
  }
1212
+
1213
+ restorePairingState()
1139
1214
  }
1140
1215
 
1141
1216
  override fun cleanup() {
@@ -1186,6 +1261,7 @@ class MentraLive : SGCManager() {
1186
1261
 
1187
1262
  private fun updateConnectionState(state: String) {
1188
1263
  if (state == ConnTypes.DISCONNECTED) {
1264
+ wifiAdbPeerIdentity = null
1189
1265
  DeviceStore.apply("glasses", "hotspotOtaVersion", 0)
1190
1266
  }
1191
1267
  val isEqual = state == connectionState
@@ -1193,6 +1269,7 @@ class MentraLive : SGCManager() {
1193
1269
  if (state == ConnTypes.DISCONNECTED) {
1194
1270
  resetWireNegotiationState()
1195
1271
  resetPendingAckState()
1272
+ resetReadinessExchange()
1196
1273
  // Queued writes are session-bound: transmitting them into the NEXT session
1197
1274
  // (e.g. a stale handshake whose reply activates v2 before the new session
1198
1275
  // negotiated) is the bug class this clear removes. Higher layers re-send
@@ -1217,8 +1294,18 @@ class MentraLive : SGCManager() {
1217
1294
  DeviceStore.apply("glasses", "connectionState", state)
1218
1295
 
1219
1296
  if (state == ConnTypes.CONNECTED) {
1297
+ // A session that reached ready means the glasses still admit this phone. An explicit
1298
+ // pair already cleared a rejection in DeviceManager.handleDeviceReady.
1299
+ MentraLivePairingStateStore.update("session_ready") {
1300
+ it.onSessionReady(explicitAttempt = false)
1301
+ }
1220
1302
  DeviceStore.apply("glasses", "connected", true)
1221
- if (glassesReadyReceived) {
1303
+ // A ready report parked for the owner commit or for pairing_info must not be
1304
+ // promoted by this path.
1305
+ if (glassesReadyReceived &&
1306
+ !awaitingSecurePairingConfirmation &&
1307
+ !awaitingPairingInfoForReadiness
1308
+ ) {
1222
1309
  DeviceStore.apply("glasses", "fullyBooted", true)
1223
1310
  }
1224
1311
  // Drop cached version fields from the previous BLE session so the next version_info
@@ -1248,6 +1335,7 @@ class MentraLive : SGCManager() {
1248
1335
  DeviceStore.apply("glasses", "signalStrengthUpdatedAt", 0L)
1249
1336
  resetWireNegotiationState()
1250
1337
  resetPendingAckState()
1338
+ resetReadinessExchange()
1251
1339
  // The glasses reset mic and wear tuning on BLE disconnect, so the
1252
1340
  // next link must be allowed to send them again.
1253
1341
  lastSentMicTuningBody = null
@@ -1294,10 +1382,8 @@ class MentraLive : SGCManager() {
1294
1382
  /** Starts BLE scanning for Mentra Live glasses */
1295
1383
  private fun startScan() {
1296
1384
  if (postGattLifecycle { startScan() }) return
1297
- if (pairingYieldActive) {
1298
- Bridge.log("LIVE: startScan blocked — pairing yield active")
1299
- return
1300
- }
1385
+ // A pause or rejection still scans: the callback never auto-connects then, and the
1386
+ // saved glasses' advertisement is what ends a pause early.
1301
1387
  if (bluetoothAdapter == null || isScanning) {
1302
1388
  return
1303
1389
  }
@@ -1357,6 +1443,8 @@ class MentraLive : SGCManager() {
1357
1443
  }
1358
1444
 
1359
1445
  val generation = ++scanGeneration
1446
+ // A unit rolled back to old firmware must not keep counting as secure.
1447
+ secureTrailerScanMemory.onScanStart()
1360
1448
  isScanning = true
1361
1449
  scanCallback = createScanCallback(generation)
1362
1450
  bluetoothScanner!!.startScan(filters, settings, scanCallback)
@@ -1397,6 +1485,8 @@ class MentraLive : SGCManager() {
1397
1485
  "LIVE: 🔌 ⏰ Reconnect scan timed out - scheduling next reconnect attempt"
1398
1486
  )
1399
1487
  handleReconnection()
1488
+ } else {
1489
+ startPairingWatchScan()
1400
1490
  }
1401
1491
  }
1402
1492
  }
@@ -1448,7 +1538,7 @@ class MentraLive : SGCManager() {
1448
1538
  * an established owner's connected glasses have no pending name/address and stay hidden.
1449
1539
  */
1450
1540
  private fun emitConnectedPendingDeviceForPairingScan() {
1451
- if (!manualDiscoveryActive || isReconnecting || pairingYieldActive) return
1541
+ if (!manualDiscoveryActive || isReconnecting) return
1452
1542
  val device = connectedDevice ?: bluetoothGatt?.device ?: return
1453
1543
  val name = safeBondedDeviceName(device)
1454
1544
  if (!isMentraLiveBluetoothName(name)) return
@@ -1543,17 +1633,21 @@ class MentraLive : SGCManager() {
1543
1633
  // Connect-by-name only when reconnecting OR connectById() asked for
1544
1634
  // this name. A discovery-only pairing scan must not auto-connect just
1545
1635
  // because savedDeviceName still matches (spoof risk).
1636
+ val isSavedGlasses =
1637
+ savedDeviceName.isNotEmpty() && savedDeviceName == deviceName
1546
1638
  val isNamedConnectTarget =
1547
- savedDeviceName.isNotEmpty() &&
1548
- savedDeviceName == deviceName &&
1549
- (isReconnecting || explicitConnectByName)
1550
- if (!isReconnecting &&
1551
- advertisesPairingFlag(result) &&
1552
- !isPairingDiscoverable(result)
1639
+ isSavedGlasses && (isReconnecting || explicitConnectByName)
1640
+ if (MentraLiveOwnerLossPolicy.shouldExposeAsNonPairable(
1641
+ savedGlasses = isSavedGlasses,
1642
+ reconnectScan = isReconnecting,
1643
+ secureTrailer = advertisesPairingFlag(result),
1644
+ pairingDiscoverable = isPairingDiscoverable(result),
1645
+ )
1553
1646
  ) {
1554
- // Tell RN a nearby unit is advertising but not pairable. The scan
1555
- // screen keeps it visible with pairing-mode guidance but blocks the
1556
- // connection until a pairable advertisement arrives.
1647
+ // Other secure units stay visible with pairing-mode guidance, and
1648
+ // the scan screen blocks the connection until they are pairable.
1649
+ // The saved glasses fall through so the pause watch scan can see
1650
+ // the pairing flag clear and reconnect.
1557
1651
  Bridge.log(
1558
1652
  "LIVE: Nearby $deviceName is secure firmware not in pairing mode — exposing as non-pairable"
1559
1653
  )
@@ -1590,8 +1684,28 @@ class MentraLive : SGCManager() {
1590
1684
  securePairingCapable = secureCapable,
1591
1685
  )
1592
1686
 
1687
+ if (savedDeviceName.isNotEmpty() && savedDeviceName == deviceName) {
1688
+ observeSavedGlassesAdvertisement(result)
1689
+ }
1690
+
1691
+ if (isNamedConnectTarget && automaticConnectBlocked()) {
1692
+ return
1693
+ }
1694
+
1593
1695
  // connectById / reconnect: user (or reconnect) asked for this name —
1594
1696
  // GATT-connect. Discovery-only scans never set explicitConnectByName.
1697
+ // While the saved glasses advertise pairing mode an automatic reconnect
1698
+ // waits instead of racing the new phone for the single BLE slot.
1699
+ if (isNamedConnectTarget &&
1700
+ MentraLiveOwnerLossPolicy.shouldStandDownInsteadOfReconnect(
1701
+ pairingMode = secureCapable && pairingMode,
1702
+ savedGlasses = true,
1703
+ explicitPairing = isExplicitPairingAttempt(),
1704
+ )
1705
+ ) {
1706
+ return
1707
+ }
1708
+
1595
1709
  if (isNamedConnectTarget) {
1596
1710
  Log.i(
1597
1711
  TAG,
@@ -1611,7 +1725,7 @@ class MentraLive : SGCManager() {
1611
1725
  else " (connectById)")
1612
1726
  )
1613
1727
  synchronized(connectionLock) {
1614
- if (pairingYieldActive || isConnected || isConnecting) {
1728
+ if (automaticConnectBlocked() || isConnected || isConnecting) {
1615
1729
  return
1616
1730
  }
1617
1731
  isConnecting = true
@@ -1712,6 +1826,7 @@ class MentraLive : SGCManager() {
1712
1826
  streamControlVersion = 0
1713
1827
  readinessCompletedThisBleSession = false
1714
1828
  glassesReadyReceived = false
1829
+ resetSecurePairingConfirmation()
1715
1830
  ctkdInitiatedThisGattSession = false
1716
1831
  classicAudioServiceDiscovery.cancel()
1717
1832
  audioConnected = false
@@ -1832,8 +1947,10 @@ class MentraLive : SGCManager() {
1832
1947
  if (device == null) {
1833
1948
  return
1834
1949
  }
1835
- if (isKilled || pairingYieldActive) {
1836
- Bridge.log("LIVE: connectToDevice blocked — pairing yield active")
1950
+ if (isKilled || automaticConnectBlocked()) {
1951
+ Bridge.log(
1952
+ "LIVE: connectToDevice blocked — pairing state ${MentraLivePairingStateStore.describe()}"
1953
+ )
1837
1954
  isConnecting = false
1838
1955
  isReconnecting = false
1839
1956
  return
@@ -1842,7 +1959,7 @@ class MentraLive : SGCManager() {
1842
1959
  // Never replace a still-open GATT. Its disconnect/close must finish first.
1843
1960
  bluetoothGatt?.let { beginGattTeardown(it) }
1844
1961
  gattTeardownBarrier.runWhenIdle {
1845
- if (requestEpoch == connectionRequestEpoch && !isKilled && !pairingYieldActive) {
1962
+ if (requestEpoch == connectionRequestEpoch && !isKilled && !automaticConnectBlocked()) {
1846
1963
  connectToDeviceWhenIdle(device)
1847
1964
  }
1848
1965
  }
@@ -1957,87 +2074,253 @@ class MentraLive : SGCManager() {
1957
2074
  // }
1958
2075
  // }
1959
2076
 
1960
- private fun enterPairingYield(windowMs: Long) {
1961
- if (postGattLifecycle { enterPairingYield(windowMs) }) return
2077
+ /**
2078
+ * Automatic connection attempts wait while the glasses run a pairing window for another
2079
+ * phone or after they rejected this phone. An explicit pair (scan screen, Pair Again) is
2080
+ * never blocked.
2081
+ */
2082
+ private fun automaticConnectBlocked(): Boolean =
2083
+ !MentraLivePairingStateStore.allowsAutomaticReconnect && !isExplicitPairingAttempt()
2084
+
2085
+ /** Carry out what a pairing-state input decided. */
2086
+ private fun applyPairingTransition(transition: MentraLivePairingTransition) {
2087
+ when (transition.effect) {
2088
+ MentraLivePairingEffect.NONE -> Unit
2089
+ MentraLivePairingEffect.PAUSE -> enterPairingPause()
2090
+ MentraLivePairingEffect.RESUME -> resumeAfterPairingPause()
2091
+ MentraLivePairingEffect.REJECT -> stopAfterPairingRejected()
2092
+ }
2093
+ }
2094
+
2095
+ /**
2096
+ * The glasses opened a pairing window. Leave the link without forgetting the saved glasses
2097
+ * or any bond, make no automatic connection until the window ends, and keep a passive scan
2098
+ * so a cleared pairing flag can end the pause early.
2099
+ */
2100
+ private fun enterPairingPause() {
2101
+ if (postGattLifecycle { enterPairingPause() }) return
2102
+ if (isKilled) return
2103
+ leaveGlassesLink()
2104
+ armPairingPauseTimer()
2105
+ startPairingWatchScan()
2106
+ }
2107
+
2108
+ /** Pause over (`pairing_mode_ended`, flag cleared, or deadline): reconnect right away. */
2109
+ private fun resumeAfterPairingPause() {
2110
+ if (postGattLifecycle { resumeAfterPairingPause() }) return
2111
+ cancelPairingPauseTimer()
2112
+ if (isKilled || isConnected || isConnecting) return
2113
+ if (isScanning && !isReconnecting && !manualDiscoveryActive) {
2114
+ stopScan()
2115
+ emitStopScanEvent()
2116
+ }
2117
+ reconnectAttempts = 0
2118
+ isReconnecting = false
2119
+ handleReconnection()
2120
+ }
2121
+
2122
+ /**
2123
+ * The glasses belong to another phone. Stop every automatic attempt but keep the saved
2124
+ * glasses and bonds; only an explicit pair or a forget clears this (see
2125
+ * [MentraLivePairingStateStore]).
2126
+ */
2127
+ private fun stopAfterPairingRejected() {
2128
+ if (postGattLifecycle { stopAfterPairingRejected() }) return
2129
+ cancelPairingPauseTimer()
2130
+ if (isKilled) return
2131
+ if (isExplicitPairingAttempt()) return
2132
+ leaveGlassesLink()
2133
+ }
2134
+
2135
+ /** Drop the link and every pending automatic attempt. Bonds and saved identity stay. */
2136
+ private fun leaveGlassesLink() {
1962
2137
  connectionRequestEpoch++
1963
- pairingYieldActive = true
1964
- pairingYieldAwaitingReclaim = false
2138
+ // Invalidate delayed reconnect callbacks already on the handler.
2139
+ reconnectGeneration++
1965
2140
  isReconnecting = false
1966
2141
  isConnecting = false
1967
- pairingYieldEndRunnable?.let { handler.removeCallbacks(it) }
2142
+ cancelSecureBondWait()
1968
2143
  if (connectionTimeoutRunnable != null) {
1969
2144
  connectionTimeoutHandler.removeCallbacks(connectionTimeoutRunnable!!)
1970
2145
  connectionTimeoutRunnable = null
1971
2146
  }
1972
- // Stop scans/reconnect work; keep default_wearable / Classic bond.
1973
- if (isScanning) {
2147
+ if (isScanning && !manualDiscoveryActive) {
1974
2148
  stopScan()
1975
2149
  emitStopScanEvent()
1976
2150
  }
1977
- // Drop A2DP/HFP (keep the Classic bond) so glasses can advertise for reclaim.
1978
- // Do this before nulling connectedDevice — disconnectClassicProfiles needs it.
1979
- val yieldingDevice = connectedDevice
1980
- disconnectClassicProfiles(yieldingDevice)
1981
- // closeGattQuietly nulls bluetoothGatt before the disconnect callback, so
1982
- // onConnectionStateChange treats it as stale and never publishes DISCONNECTED.
1983
- // Mirror a real disconnect for UI + session state, then tear GATT down.
1984
- isConnected = false
1985
- connectedDevice = null
1986
- glassesReady = false
1987
- glassesSessionId = null
1988
- streamControlVersion = 0
1989
- readinessCompletedThisBleSession = false
1990
- glassesReadyReceived = false
1991
- ctkdInitiatedThisGattSession = false
1992
- classicAudioServiceDiscovery.cancel()
2151
+ // Drop A2DP/HFP (keep the Classic bond) so the glasses can serve the new phone.
2152
+ // Capture the device first: GATT teardown nulls connectedDevice.
2153
+ val leavingDevice = connectedDevice
2154
+ val hadLink = bluetoothGatt != null || isConnected
2155
+ if (leavingDevice != null) disconnectClassicProfiles(leavingDevice)
1993
2156
  audioConnected = false
1994
- notificationsEnabled = false
1995
- processSendQueueRunnable?.let { handler.removeCallbacks(it) }
1996
- stopReadinessCheckLoop()
1997
- stopHeartbeat()
1998
- stopSignalStrengthPolling()
1999
- stopMicBeat()
2000
- closeL2capFileChannel()
2001
- fileProcessingHandler.removeCallbacksAndMessages(null)
2002
- clearFilePacketBuffer()
2003
- updateConnectionState(ConnTypes.DISCONNECTED)
2004
- closeGattQuietly(true)
2005
- // Stand down for the whole window. Probing GATT during yield races the new
2006
- // phone for BLE_CONNECTION_MAX=1 and is exactly what entering_pairing_mode forbids.
2007
- val end =
2008
- Runnable {
2009
- Bridge.log("LIVE: Pairing yield ended — resume reconnect if still owned")
2010
- pairingYieldActive = false
2011
- pairingYieldAwaitingReclaim = true
2012
- pairingYieldEndRunnable = null
2013
- if (!isKilled && !isConnected && !isConnecting) {
2014
- handleReconnection()
2157
+ if (hadLink) {
2158
+ // beginGattTeardown resets the session state and publishes DISCONNECTED.
2159
+ closeGattQuietly(true)
2160
+ updateConnectionState(ConnTypes.DISCONNECTED)
2161
+ }
2162
+ }
2163
+
2164
+ private fun armPairingPauseTimer() {
2165
+ cancelPairingPauseTimer()
2166
+ val remaining = MentraLivePairingStateStore.remainingPauseMs()
2167
+ if (remaining <= 0L) return
2168
+ val end = Runnable {
2169
+ pairingPauseEndRunnable = null
2170
+ applyPairingTransition(
2171
+ MentraLivePairingStateStore.update("pause_deadline") {
2172
+ it.onTick(System.currentTimeMillis())
2015
2173
  }
2016
- }
2017
- pairingYieldEndRunnable = end
2018
- handler.postDelayed(end, windowMs)
2174
+ )
2175
+ }
2176
+ pairingPauseEndRunnable = end
2177
+ handler.postDelayed(end, remaining + 50L)
2019
2178
  }
2020
2179
 
2021
- fun isPairingYieldActive(): Boolean = pairingYieldActive
2180
+ private fun cancelPairingPauseTimer() {
2181
+ pairingPauseEndRunnable?.let { handler.removeCallbacks(it) }
2182
+ pairingPauseEndRunnable = null
2183
+ }
2022
2184
 
2023
- private fun clearSavedGlassesAfterOwnerLoss(reason: String) {
2024
- Bridge.log("LIVE: Owner loss ($reason) — clearing saved glasses (not generic GATT)")
2025
- pairingYieldAwaitingReclaim = false
2026
- pairingYieldActive = false
2027
- pairingYieldEndRunnable?.let { handler.removeCallbacks(it) }
2028
- pairingYieldEndRunnable = null
2185
+ /**
2186
+ * Observation-only scan during a pause: the scan callback never connects while paused, it
2187
+ * only reads the saved glasses' advertisement. Restarted when the default scan times out.
2188
+ */
2189
+ private fun startPairingWatchScan() {
2190
+ if (isKilled || !MentraLivePairingStateStore.isPaused) return
2029
2191
  try {
2030
- forget()
2031
- } catch (e: Exception) {
2032
- Bridge.log("LIVE: forget after owner loss failed: ${e.message}")
2192
+ if (!isScanning) startScan()
2193
+ } catch (e: SecurityException) {
2194
+ Bridge.log("LIVE: pairing watch scan blocked — ${e.message}")
2195
+ }
2196
+ }
2197
+
2198
+ /** The saved glasses' secure trailer feeds the pause and takeover checks. */
2199
+ private fun observeSavedGlassesAdvertisement(result: ScanResult) {
2200
+ val advertisement =
2201
+ MentraLivePairingAdvertisementParser.parse(manufacturerData(result)) ?: return
2202
+ applyPairingTransition(
2203
+ MentraLivePairingStateStore.update("advertisement") {
2204
+ it.onAdvertisement(
2205
+ advertisement.pairingMode,
2206
+ advertisement.ownerChanged,
2207
+ advertisement.pairingGeneration,
2208
+ System.currentTimeMillis(),
2209
+ )
2210
+ }
2211
+ )
2212
+ }
2213
+
2214
+ /**
2215
+ * Pairing-protocol messages for this GATT session: `phone_hello` so v4 glasses send window
2216
+ * events to this phone, and `pair_select` only when the user chose these glasses.
2217
+ */
2218
+ private fun sendPairingSessionMessages(reason: String) {
2219
+ if (isKilled || !isConnected) return
2220
+ // The scan's trailer is a hint for speaking the protocol at all; pair_select below uses
2221
+ // only the selected target's capability.
2222
+ val secure = isSecurePairingTarget() || isSavedGlassesSecureFirmware() ||
2223
+ pairingInfoSeen || secureTrailerScanMemory.contains(connectedDevice?.address)
2224
+ if (!secure) return
2225
+ if (!phoneHelloSentThisSession) {
2226
+ phoneHelloSentThisSession = true
2227
+ val hello = JSONObject()
2228
+ hello.put("type", "phone_hello")
2229
+ hello.put("pairing_protocol", PAIRING_PROTOCOL_VERSION)
2230
+ Bridge.log("PAIRFLOW: phone_hello sent ($reason)")
2231
+ sendJsonWithoutAck(hello)
2232
+ }
2233
+ if (!pairSelectSentThisSession &&
2234
+ MentraLiveOwnerLossPolicy.shouldSendPairSelect(
2235
+ isExplicitPairingAttempt(),
2236
+ isSecurePairingTarget(),
2237
+ )
2238
+ ) {
2239
+ pairSelectSentThisSession = true
2240
+ val select = JSONObject()
2241
+ select.put("type", "pair_select")
2242
+ Bridge.log("PAIRFLOW: pair_select sent ($reason)")
2243
+ sendJsonWithoutAck(select)
2244
+ }
2245
+ }
2246
+
2247
+ /** The selected scan row's secure capability; null when the row did not know it. */
2248
+ private fun selectedTargetSecureCapability(): Boolean? =
2249
+ DeviceStore.get("bluetooth", "pending_device_secure_pairing_capable") as? Boolean
2250
+
2251
+ /**
2252
+ * The explicit pairing target runs secure-pairing firmware. Only the selected scan row's
2253
+ * capability counts, never an address seen in an earlier scan; when the row did not know it,
2254
+ * this session's `pairing_info` decides.
2255
+ */
2256
+ private fun isSecurePairingTarget(): Boolean =
2257
+ MentraLivePairingReadinessPolicy.isSecurePairingTarget(
2258
+ selectedTargetSecureCapability(),
2259
+ sessionPairingInfoSecure,
2260
+ )
2261
+
2262
+ /** When glasses_ready may report this session ready (see [MentraLivePairingReadinessPolicy]). */
2263
+ private fun pairingReadiness(device: BluetoothDevice?): MentraLivePairingReadinessPolicy.Readiness =
2264
+ MentraLivePairingReadinessPolicy.readiness(
2265
+ explicitPairing = isExplicitPairingAttempt(),
2266
+ selectedCapability = selectedTargetSecureCapability(),
2267
+ sessionPairingInfoSecure = sessionPairingInfoSecure,
2268
+ unknownCapabilityWaitExpired = unknownCapabilityWaitExpired,
2269
+ bondState = device?.bondState,
2270
+ ownerCommitted = securePairingConfirmed,
2271
+ )
2272
+
2273
+ /** The user is pairing glasses from the scan screen rather than reconnecting a saved owner. */
2274
+ private fun isExplicitPairingAttempt(): Boolean {
2275
+ val pendingName = DeviceStore.get("bluetooth", "pending_device_name") as? String ?: ""
2276
+ val pendingAddress = DeviceStore.get("bluetooth", "pending_device_address") as? String ?: ""
2277
+ return manualDiscoveryActive || pendingName.isNotEmpty() || pendingAddress.isNotEmpty()
2278
+ }
2279
+
2280
+ /**
2281
+ * The saved glasses run secure-pairing firmware, learned from their last `pairing_info`.
2282
+ * Legacy firmware never rejects a non-owner on purpose, so its failures are not owner loss.
2283
+ */
2284
+ private fun isSavedGlassesSecureFirmware(): Boolean =
2285
+ DeviceStore.get("bluetooth", "mentra_live_secure_firmware") as? Boolean == true
2286
+
2287
+ /** Remember what the connected glasses reported so later rejections can be read correctly. */
2288
+ private fun rememberSecureFirmware(secure: Boolean) {
2289
+ if (isSavedGlassesSecureFirmware() == secure) return
2290
+ DeviceStore.apply("bluetooth", "mentra_live_secure_firmware", secure)
2291
+ Bridge.saveSetting("mentra_live_secure_firmware", secure)
2292
+ }
2293
+
2294
+ /**
2295
+ * One authentication rejection (HCI 0x05/0x0F or a bond the glasses dropped). The machine
2296
+ * ignores it during a pause, while the glasses advertise pairing mode, and on legacy
2297
+ * firmware; it rejects after the `OWNER_CHANGED` verification fails or the streak fills.
2298
+ * @return true when this phone is now rejected
2299
+ */
2300
+ private fun recordAuthRejection(reason: String): Boolean {
2301
+ val transition =
2302
+ MentraLivePairingStateStore.update("auth_rejection:$reason") {
2303
+ it.onAuthRejection(
2304
+ isSavedGlassesSecureFirmware(),
2305
+ isExplicitPairingAttempt(),
2306
+ System.currentTimeMillis(),
2307
+ )
2308
+ }
2309
+ Bridge.log("LIVE: Auth rejection ($reason) — ${transition.note}")
2310
+ applyPairingTransition(transition)
2311
+ return transition.effect == MentraLivePairingEffect.REJECT
2312
+ }
2313
+
2314
+ /** Restore the pairing record once per process and act on it. */
2315
+ private fun restorePairingState() {
2316
+ val transition = MentraLivePairingStateStore.ensureRestored(savedDeviceName) ?: run {
2317
+ if (MentraLivePairingStateStore.isPaused) {
2318
+ armPairingPauseTimer()
2319
+ startPairingWatchScan()
2320
+ }
2321
+ return
2033
2322
  }
2034
- DeviceStore.apply("bluetooth", "default_wearable", "")
2035
- DeviceStore.apply("bluetooth", "device_name", "")
2036
- DeviceStore.apply("bluetooth", "device_address", "")
2037
- Bridge.saveSetting("default_wearable", "")
2038
- Bridge.saveSetting("device_name", "")
2039
- Bridge.saveSetting("device_address", "")
2040
- Bridge.sendTypedMessage("owner_replaced", mapOf("reason" to reason))
2323
+ applyPairingTransition(transition)
2041
2324
  }
2042
2325
 
2043
2326
  /** Handle reconnection with exponential backoff */
@@ -2058,9 +2341,12 @@ class MentraLive : SGCManager() {
2058
2341
  return
2059
2342
  }
2060
2343
 
2061
- if (pairingYieldActive) {
2062
- Bridge.log("LIVE: 🔌 RECONNECT ABORTED - pairing yield active (glasses in pairing mode)")
2344
+ if (!MentraLivePairingStateStore.allowsAutomaticReconnect) {
2345
+ Bridge.log(
2346
+ "LIVE: 🔌 RECONNECT ABORTED - pairing state ${MentraLivePairingStateStore.describe()}"
2347
+ )
2063
2348
  isReconnecting = false
2349
+ if (MentraLivePairingStateStore.isPaused) startPairingWatchScan()
2064
2350
  return
2065
2351
  }
2066
2352
 
@@ -2147,20 +2433,23 @@ class MentraLive : SGCManager() {
2147
2433
  )
2148
2434
  return
2149
2435
  }
2150
- if (pairingYieldActive) {
2436
+ if (!MentraLivePairingStateStore.allowsAutomaticReconnect) {
2151
2437
  isReconnecting = false
2152
2438
  Bridge.log(
2153
- "LIVE: 🔌 RECONNECT ABORTED - pairing yield active (glasses in pairing mode)"
2439
+ "LIVE: 🔌 RECONNECT ABORTED - pairing state ${MentraLivePairingStateStore.describe()}"
2154
2440
  )
2155
2441
  return
2156
2442
  }
2157
2443
  if (!isConnected && !isConnecting && !isKilled) {
2158
2444
  // Prefer saved MAC for direct GATT connect (faster and more reliable
2159
2445
  // than scanning).
2160
- // Falls back to name-based scan if no address is saved.
2446
+ // Falls back to name-based scan if no address is saved. Right after a
2447
+ // pairing window the scan comes first so the advertisement's
2448
+ // OWNER_CHANGED bit is read before the first attempt.
2161
2449
  val lastDeviceAddress =
2162
2450
  selectedConnectionAddress()
2163
2451
  if (lastDeviceAddress != null &&
2452
+ !MentraLivePairingStateStore.awaitingTakeoverCheck &&
2164
2453
  !lastDeviceAddress.isEmpty() &&
2165
2454
  bluetoothAdapter != null
2166
2455
  ) {
@@ -2321,6 +2610,9 @@ class MentraLive : SGCManager() {
2321
2610
  "LIVE: 🔌 🔗 BLE GATT link connected - validating services/characteristics..."
2322
2611
  )
2323
2612
  markPairingTiming("gatt_connected")
2613
+ lastAutoReconnectLinkAt =
2614
+ if (isExplicitPairingAttempt()) null
2615
+ else SystemClock.elapsedRealtime()
2324
2616
  isConnecting = false
2325
2617
  isConnected = true
2326
2618
  connectedDevice = gatt.device
@@ -2358,6 +2650,8 @@ class MentraLive : SGCManager() {
2358
2650
  bondingRetryCount = 0
2359
2651
  ctkdInitiatedThisGattSession = false
2360
2652
  classicAudioServiceDiscovery.cancel()
2653
+ // A new GATT link has not heard the glasses' owner commit yet.
2654
+ resetSecurePairingConfirmation()
2361
2655
  Bridge.log(
2362
2656
  "LIVE: CTKD: BLE GATT up - deferring Classic/A2DP until notifications ready"
2363
2657
  )
@@ -2405,6 +2699,7 @@ class MentraLive : SGCManager() {
2405
2699
 
2406
2700
  // Reset audio pairing flags
2407
2701
  glassesReadyReceived = false
2702
+ resetSecurePairingConfirmation()
2408
2703
  ctkdInitiatedThisGattSession = false
2409
2704
  classicAudioServiceDiscovery.cancel()
2410
2705
  audioConnected = false
@@ -2467,6 +2762,7 @@ class MentraLive : SGCManager() {
2467
2762
  streamControlVersion = 0
2468
2763
  readinessCompletedThisBleSession = false
2469
2764
  glassesReadyReceived = false
2765
+ resetSecurePairingConfirmation()
2470
2766
  audioConnected = false
2471
2767
  ctkdInitiatedThisGattSession = false
2472
2768
  classicAudioServiceDiscovery.cancel()
@@ -2493,17 +2789,22 @@ class MentraLive : SGCManager() {
2493
2789
  // Clean up resources
2494
2790
  closeGattQuietly(false)
2495
2791
 
2496
- // Auth/not-owner after pairing yield — not a generic RF blip.
2497
- // GATT 8 / 0x08 is connection timeout; a reclaim RF timeout must
2498
- // not wipe the saved owner.
2499
- if (pairingYieldAwaitingReclaim &&
2500
- (status == 5 ||
2501
- status == 15 ||
2502
- status == 0x05 ||
2503
- status == 0x0F)
2792
+ // Secure glasses reject a non-owner at connect time with HCI
2793
+ // Authentication Failure. One rejection can also be a glasses reboot or
2794
+ // a stale bond, so the pairing state machine decides: one failed
2795
+ // OWNER_CHANGED verification, or a repeating streak. GATT 8 (timeout),
2796
+ // 19 (remote terminated) and the window's 0x14 refusal never count.
2797
+ if (MentraLiveOwnerLossPolicy.isOwnerRejectionOnGattError(
2798
+ status,
2799
+ isExplicitPairingAttempt(),
2800
+ isSavedGlassesSecureFirmware(),
2801
+ )
2504
2802
  ) {
2505
- clearSavedGlassesAfterOwnerLoss("gatt_auth_status_$status")
2506
- return
2803
+ if (recordAuthRejection("gatt_auth_status_$status")) return
2804
+ } else {
2805
+ MentraLivePairingStateStore.update("connect_failed_$status") {
2806
+ it.onConnectAttemptFailed()
2807
+ }
2507
2808
  }
2508
2809
 
2509
2810
  // Attempt reconnection if not killed
@@ -2968,6 +3269,7 @@ class MentraLive : SGCManager() {
2968
3269
  Bridge.log("LIVE: Starting send queue and readiness check loop")
2969
3270
  startSignalStrengthPolling()
2970
3271
  handler.post(processSendQueueRunnable!!)
3272
+ sendPairingSessionMessages("gatt_ready")
2971
3273
  startReadinessCheckLoop()
2972
3274
  // Classic/A2DP after BLE is armed — avoids GATT 19 when dual-mode stacks
2973
3275
  // collide during service discovery / descriptor writes.
@@ -4163,23 +4465,93 @@ class MentraLive : SGCManager() {
4163
4465
  // Process heartbeat pong response
4164
4466
  Bridge.log("LIVE: Received pong response - connection healthy")
4165
4467
  "entering_pairing_mode" -> {
4166
- val windowMs = json.optLong("window_ms", 120_000L).coerceIn(5_000L, 180_000L)
4167
- Bridge.log("LIVE: Glasses entering pairing mode — yield ${windowMs}ms (no forget)")
4168
- enterPairingYield(windowMs)
4468
+ val ownerRetained = json.optBoolean("owner_retained", false)
4469
+ val windowMs =
4470
+ json.optLong("window_ms", MentraLiveOwnerLossPolicy.DEFAULT_PAIRING_WINDOW_MS)
4471
+ val windowId = if (json.has("window_id")) json.optInt("window_id") else null
4472
+ val transition =
4473
+ MentraLivePairingStateStore.update("entering_pairing_mode") {
4474
+ it.onEnteringPairingMode(
4475
+ windowMs = windowMs,
4476
+ windowId = windowId,
4477
+ ownerRetained = ownerRetained,
4478
+ explicitAttempt = isExplicitPairingAttempt(),
4479
+ deviceId = savedDeviceName,
4480
+ nowMs = System.currentTimeMillis(),
4481
+ )
4482
+ }
4483
+ Bridge.log(
4484
+ "PAIRFLOW: entering_pairing_mode window_id=${windowId ?: ""} " +
4485
+ "window_ms=$windowMs owner_retained=$ownerRetained " +
4486
+ "effect=${transition.effect} (${transition.note})"
4487
+ )
4169
4488
  val body = HashMap<String, Any>()
4170
4489
  body["window_ms"] = windowMs
4490
+ if (windowId != null) body["window_id"] = windowId
4171
4491
  body["reason"] = json.optString("reason", "user_gesture")
4492
+ body["owner_retained"] = ownerRetained
4172
4493
  Bridge.sendTypedMessage("entering_pairing_mode", body)
4173
- }
4174
- "pairing_info" ->
4175
- Bridge.sendPairingInfo(
4176
- json.optBoolean("had_previous_bond", false),
4177
- jsonNullableString(json, "pairing_code"),
4178
- json.optBoolean("classic_bond_ready", false),
4179
- // Legacy firmware that omits this field is not secure-capable.
4180
- json.optBoolean("secure_pairing_capable", false),
4181
- json.optInt("protocol_version", 1),
4494
+ applyPairingTransition(transition)
4495
+ }
4496
+ "pairing_mode_ended" -> {
4497
+ val reason = jsonNullableString(json, "reason")
4498
+ val windowId = if (json.has("window_id")) json.optInt("window_id") else null
4499
+ val transition =
4500
+ MentraLivePairingStateStore.update("pairing_mode_ended") {
4501
+ it.onPairingModeEnded(reason, windowId)
4502
+ }
4503
+ Bridge.log(
4504
+ "PAIRFLOW: pairing_mode_ended reason=${reason ?: ""} window_id=${windowId ?: ""} " +
4505
+ "effect=${transition.effect} (${transition.note})"
4506
+ )
4507
+ val body = HashMap<String, Any>()
4508
+ body["reason"] = reason ?: ""
4509
+ if (windowId != null) body["window_id"] = windowId
4510
+ Bridge.sendTypedMessage("pairing_mode_ended", body)
4511
+ applyPairingTransition(transition)
4512
+ }
4513
+ "pairing_info" -> {
4514
+ // Legacy firmware that omits this field is not secure-capable.
4515
+ val secureCapable = json.optBoolean("secure_pairing_capable", false)
4516
+ rememberSecureFirmware(secureCapable)
4517
+ cancelSecureFirmwareRefresh()
4518
+ // Decides the capability of a pairing target the scan row did not know.
4519
+ sessionPairingInfoSecure = secureCapable
4520
+ // Ownership is the separate owner_committed bit, set after the BLE bond.
4521
+ val ownerCommitted = json.optBoolean("owner_committed", false)
4522
+ if (MentraLiveOwnerLossPolicy.pairingInfoConfirmsOwner(ownerCommitted)) {
4523
+ securePairingConfirmed = true
4524
+ if (awaitingSecurePairingConfirmation) {
4525
+ Bridge.log("LIVE: pairing_info owner_committed — finishing parked readiness")
4526
+ completeSecurePairingReadiness("pairing_info_owner_committed")
4527
+ }
4528
+ }
4529
+ if (secureCapable) sendPairingSessionMessages("pairing_info")
4530
+ if (awaitingPairingInfoForReadiness) {
4531
+ Bridge.log(
4532
+ "LIVE: pairing_info secure_pairing_capable=$secureCapable for a " +
4533
+ "pairing target of unknown capability"
4182
4534
  )
4535
+ resolveUnknownCapabilityReadiness("pairing_info")
4536
+ }
4537
+ maybeInitiateCtkdAudioAfterBleReady()
4538
+ Bridge.sendPairingInfo(
4539
+ json.optBoolean("had_previous_bond", false),
4540
+ jsonNullableString(json, "pairing_code"),
4541
+ json.optBoolean("classic_bond_ready", false),
4542
+ secureCapable,
4543
+ json.optInt("protocol_version", 1),
4544
+ json.optBoolean("ownership_transfer", false),
4545
+ ownerCommitted,
4546
+ json.optBoolean("auto_audio", false),
4547
+ )
4548
+ }
4549
+ "classic_link" -> {
4550
+ // Android attaches Classic audio from the bond, so audioSetup stays
4551
+ // not_applicable here; the report only matters to iOS.
4552
+ val link = MentraLiveClassicLink.parse(json)
4553
+ Log.d(TAG, "LIVE: classic_link a2dp=${link.a2dp} hfp=${link.hfp}")
4554
+ }
4183
4555
  "imu_response",
4184
4556
  "imu_stream_response",
4185
4557
  "imu_gesture_response",
@@ -4430,6 +4802,16 @@ class MentraLive : SGCManager() {
4430
4802
  if (json.has("bytes_downloaded")) json.optLong("bytes_downloaded", 0) else null
4431
4803
  )
4432
4804
  }
4805
+ "bes_crash_detected", "bes_crash_reported_ack" ->
4806
+ try {
4807
+ Bridge.log(
4808
+ "LIVE: $type incidentKey=${json.optString("incidentKey")} " +
4809
+ "state=${json.optString("state")} ok=${json.opt("ok")}"
4810
+ )
4811
+ Bridge.sendTypedMessage(type, jsonObjectToMap(json))
4812
+ } catch (e: JSONException) {
4813
+ Log.e(TAG, "Error converting $type to Map", e)
4814
+ }
4433
4815
  "ota_progress" -> {
4434
4816
  // Legacy glasses firmware: map to unified ota_status so JS has a single path
4435
4817
  // (Mantle / progress UI).
@@ -4601,21 +4983,40 @@ class MentraLive : SGCManager() {
4601
4983
 
4602
4984
  handleSwitchStatus(switchType, switchValue, switchTimestamp)
4603
4985
  }
4986
+ "rgb_led_control_response" -> {
4987
+ // Settles the sendRgbLedControl request this reply echoes (matches iOS).
4988
+ val requestId = json.optString("requestId", "")
4989
+ val success =
4990
+ json.optString("state", "") == "success" ||
4991
+ json.optBoolean("success", false)
4992
+ val error =
4993
+ json.optString("errorCode", "").ifEmpty { json.optString("error", "") }
4994
+ Bridge.sendRgbLedControlResponse(requestId, success, error.ifEmpty { null })
4995
+ }
4604
4996
  "sensor_data" -> {
4605
4997
  // Process sensor data
4606
4998
  // ...
4607
4999
  }
4608
5000
  "glasses_ready" -> {
4609
5001
  // Glasses SOC has booted and is ready for communication
4610
- if (pairingYieldActive && !isConnected) {
4611
- Bridge.log("LIVE: Ignoring stale glasses_ready during pairing yield")
5002
+ if (!isConnected) {
5003
+ Bridge.log("LIVE: Ignoring stale glasses_ready without a link")
5004
+ return
5005
+ }
5006
+ val sid = json.optString("sid", "").takeIf { it.isNotEmpty() }
5007
+ val readyId = json.optString("readyId", "").takeIf { it.isNotEmpty() }
5008
+ if (readyId != null && isRepeatedGlassesReady(readyId, sid)) {
5009
+ Bridge.log(
5010
+ "LIVE: Ignoring repeated glasses_ready for readiness exchange $readyId - " +
5011
+ "the glasses did not reset for it"
5012
+ )
4612
5013
  return
4613
5014
  }
5015
+ if (readyId != null && readyId == pendingReadyId) {
5016
+ pendingReadyId = null
5017
+ }
5018
+ readyGlassesSessionId = sid
4614
5019
  Bridge.log("LIVE: 🎉 Received glasses_ready message - SOC is booted and ready!")
4615
- pairingYieldAwaitingReclaim = false
4616
- pairingYieldActive = false
4617
- pairingYieldEndRunnable?.let { handler.removeCallbacks(it) }
4618
- pairingYieldEndRunnable = null
4619
5020
  markPairingTiming(
4620
5021
  "glasses_ready",
4621
5022
  "audioConnected=$audioConnected queueSize=${sendQueue.size}"
@@ -4632,7 +5033,7 @@ class MentraLive : SGCManager() {
4632
5033
  // Record the session id BEFORE marking ready: an unsolicited glasses_ready
4633
5034
  // already runs this full remote-reset flow, so recording (not re-triggering)
4634
5035
  // is correct here; version_info detection covers the restart case.
4635
- glassesSessionId = json.optString("sid", "").takeIf { it.isNotEmpty() }
5036
+ glassesSessionId = sid
4636
5037
  streamControlVersion = json.optInt("streamControlVersion", 0)
4637
5038
  Bridge.sendTypedMessage(
4638
5039
  "wifi_protocol_session_ready",
@@ -4647,6 +5048,7 @@ class MentraLive : SGCManager() {
4647
5048
  // Set the ready flag to stop any future readiness checks
4648
5049
  glassesReady = true
4649
5050
  glassesReadyReceived = true
5051
+ armSecureFirmwareRefresh()
4650
5052
  // Match iOS MentraLive.handleGlassesReady: BLE/SOC ready is enough for
4651
5053
  // fullyBooted + CONNECTED. CTKD Classic bonding continues in the background
4652
5054
  // for SCO/A2DP and must not gate the pairing success UI (~9s on some phones).
@@ -4769,8 +5171,42 @@ class MentraLive : SGCManager() {
4769
5171
  Bridge.log("LIVE: ⚠️ glasses_ready: mic restore threw: " + t)
4770
5172
  }
4771
5173
 
4772
- // Pairing UI / DeviceManager.handleDeviceReady gate on fullyBooted.
4773
- // Do not wait for CTKD here — iOS already marks ready on glasses_ready alone.
5174
+ // Pairing UI / DeviceManager.handleDeviceReady gate on fullyBooted, and
5175
+ // handleDeviceReady promotes the pairing target to the default device.
5176
+ // Classic CTKD is not awaited, but secure glasses own a phone only once the
5177
+ // BLE bond exists; the BOND_BONDED handler finishes readiness. A target whose
5178
+ // capability the scan row did not know first waits, bounded, for pairing_info.
5179
+ when (pairingReadiness(connectedDevice)) {
5180
+ MentraLivePairingReadinessPolicy.Readiness.AWAIT_PAIRING_INFO -> {
5181
+ Bridge.log(
5182
+ "LIVE: glasses_ready for a pairing target of unknown capability — " +
5183
+ "waiting up to " +
5184
+ "${MentraLivePairingReadinessPolicy.UNKNOWN_CAPABILITY_PAIRING_INFO_WAIT_MS}ms " +
5185
+ "for pairing_info"
5186
+ )
5187
+ markPairingTiming("waiting_pairing_info", "queueSize=${sendQueue.size}")
5188
+ awaitingPairingInfoForReadiness = true
5189
+ armUnknownCapabilityPairingInfoWait()
5190
+ return
5191
+ }
5192
+ MentraLivePairingReadinessPolicy.Readiness.AWAIT_OWNER_COMMIT -> {
5193
+ Bridge.log(
5194
+ "LIVE: glasses_ready before BLE bond / owner commit — waiting " +
5195
+ "(bond=${connectedDevice?.bondState} ownerCommitted=$securePairingConfirmed)"
5196
+ )
5197
+ markPairingTiming(
5198
+ "waiting_ble_bond",
5199
+ "queueSize=${sendQueue.size} ownerCommitted=$securePairingConfirmed"
5200
+ )
5201
+ awaitingSecurePairingConfirmation = true
5202
+ armSecureBondWait()
5203
+ return
5204
+ }
5205
+ MentraLivePairingReadinessPolicy.Readiness.READY -> Unit
5206
+ }
5207
+ awaitingSecurePairingConfirmation = false
5208
+ awaitingPairingInfoForReadiness = false
5209
+ cancelUnknownCapabilityPairingInfoWait()
4774
5210
  endPairingTiming(
4775
5211
  "fully_connected",
4776
5212
  "via=glasses_ready audioConnected=$audioConnected queueSize=${sendQueue.size}"
@@ -4828,6 +5264,7 @@ class MentraLive : SGCManager() {
4828
5264
  )
4829
5265
  DeviceStore.apply("glasses", "firmwareVersion", firmwareVersionLegacy)
4830
5266
  btMacAddressLegacy.trim().takeIf { it.isNotEmpty() }?.let {
5267
+ wifiAdbPeerIdentity = bleSessionGeneration.get() to it
4831
5268
  DeviceStore.apply("glasses", "bluetoothMacAddress", it)
4832
5269
  }
4833
5270
  serialNumberLegacy.trim().takeIf { it.isNotEmpty() }?.let {
@@ -5100,6 +5537,7 @@ class MentraLive : SGCManager() {
5100
5537
  )
5101
5538
  }
5102
5539
  (fields["bt_mac_address"] as? String)?.trim()?.takeIf { it.isNotEmpty() }?.let {
5540
+ wifiAdbPeerIdentity = bleSessionGeneration.get() to it
5103
5541
  DeviceStore.apply("glasses", "bluetoothMacAddress", it)
5104
5542
  }
5105
5543
  (fields["wifi_mac_address"] as? String)?.trim()?.takeIf { it.isNotEmpty() }?.let {
@@ -5470,6 +5908,14 @@ class MentraLive : SGCManager() {
5470
5908
  // Bridge.log("LIVE: Processing K900 command: " + command);
5471
5909
 
5472
5910
  when (command) {
5911
+ "sr_tpdef" -> {
5912
+ val body = when (val value = json.opt("B")) {
5913
+ is JSONObject -> value
5914
+ is String -> runCatching { JSONObject(value) }.getOrNull()
5915
+ else -> null
5916
+ }
5917
+ if (body != null && body.optString("setting") == "touch_gesture_default") emitSettingsAck(body)
5918
+ }
5473
5919
  "sr_hrt" -> {
5474
5920
  try {
5475
5921
  val bodyObj = json.optJSONObject("B")
@@ -5638,6 +6084,7 @@ class MentraLive : SGCManager() {
5638
6084
  updateConnectionState(ConnTypes.DISCONNECTED)
5639
6085
  glassesReady = false
5640
6086
  glassesReadyReceived = false
6087
+ resetSecurePairingConfirmation()
5641
6088
  glassesSessionId = null
5642
6089
  streamControlVersion = 0
5643
6090
  readinessCompletedThisBleSession = false
@@ -6086,6 +6533,30 @@ class MentraLive : SGCManager() {
6086
6533
  }
6087
6534
  }
6088
6535
 
6536
+ /**
6537
+ * The 16-character relay file names keep only 15 characters of the report id, so two reports
6538
+ * can share them. The phone routes a received file to the report registered under its name;
6539
+ * refuse a second report until the owner's Cloud POST is confirmed or its ownership expires.
6540
+ */
6541
+ private fun reserveIncidentRelays(vararg relays: BleIncidentLogRelay) {
6542
+ synchronized(bleIncidentLogRelays) {
6543
+ val now = SystemClock.elapsedRealtime()
6544
+ for (relay in relays) {
6545
+ val owner = bleIncidentLogRelays[relay.fileBaseKey] ?: continue
6546
+ if (owner.incidentId != relay.incidentId &&
6547
+ now - owner.reservedAtMs < INCIDENT_RELAY_OWNERSHIP_MS) {
6548
+ throw BluetoothSdkException(
6549
+ "incident_relay_busy",
6550
+ "BLE relay ${relay.fileBaseKey} is still owned by report ${owner.incidentId}.",
6551
+ )
6552
+ }
6553
+ }
6554
+ for (relay in relays) {
6555
+ bleIncidentLogRelays[relay.fileBaseKey] = relay
6556
+ }
6557
+ }
6558
+ }
6559
+
6089
6560
  override fun sendIncidentId(incidentId: String, apiBaseUrl: String?) {
6090
6561
  if (!isConnected || bluetoothGatt == null || txCharacteristic == null) {
6091
6562
  throw BluetoothSdkException(
@@ -6105,10 +6576,9 @@ class MentraLive : SGCManager() {
6105
6576
  }
6106
6577
  val bKey = IncidentLogBleRelayNaming.bleFileBaseName(incidentId, 'B')
6107
6578
  val lKey = IncidentLogBleRelayNaming.bleFileBaseName(incidentId, 'L')
6108
- bleIncidentLogRelays[bKey] =
6109
- BleIncidentLogRelay(bKey, incidentId, base, BleIncidentLogKind.FIRMWARE)
6110
- bleIncidentLogRelays[lKey] =
6111
- BleIncidentLogRelay(lKey, incidentId, base, BleIncidentLogKind.LOGCAT)
6579
+ val bRelay = BleIncidentLogRelay(bKey, incidentId, base, BleIncidentLogKind.FIRMWARE)
6580
+ val lRelay = BleIncidentLogRelay(lKey, incidentId, base, BleIncidentLogKind.LOGCAT)
6581
+ reserveIncidentRelays(bRelay, lRelay)
6112
6582
 
6113
6583
  val auth = JSONObject()
6114
6584
  auth.put("type", "auth_token")
@@ -6123,8 +6593,8 @@ class MentraLive : SGCManager() {
6123
6593
  sessionGeneration != bleSessionGeneration.get() ||
6124
6594
  !isConnected || bluetoothGatt == null || txCharacteristic == null ||
6125
6595
  !sendJson(json, true, true, sessionGeneration) || sessionGeneration != bleSessionGeneration.get()) {
6126
- bleIncidentLogRelays.remove(bKey)
6127
- bleIncidentLogRelays.remove(lKey)
6596
+ bleIncidentLogRelays.remove(bKey, bRelay)
6597
+ bleIncidentLogRelays.remove(lKey, lRelay)
6128
6598
  throw BluetoothSdkException("incident_dispatch_failed", "Could not queue the glasses incident-log request.")
6129
6599
  }
6130
6600
  Bridge.log(
@@ -6141,6 +6611,27 @@ class MentraLive : SGCManager() {
6141
6611
  }
6142
6612
  }
6143
6613
 
6614
+ override fun sendBesCrashReported(incidentKey: String, reportId: String) {
6615
+ if (!isConnected || bluetoothGatt == null || txCharacteristic == null) {
6616
+ throw BluetoothSdkException(
6617
+ "glasses_not_connected", "Cannot report the BES crash because the glasses BLE link is not ready.",
6618
+ )
6619
+ }
6620
+ val sessionGeneration = bleSessionGeneration.get()
6621
+ try {
6622
+ val json = JSONObject()
6623
+ json.put("type", "bes_crash_reported")
6624
+ json.put("incidentKey", incidentKey)
6625
+ json.put("reportId", reportId)
6626
+ if (!sendJson(json, true, true, sessionGeneration) || sessionGeneration != bleSessionGeneration.get()) {
6627
+ throw BluetoothSdkException("bes_crash_dispatch_failed", "Could not queue bes_crash_reported to the glasses.")
6628
+ }
6629
+ Bridge.log("LIVE: Queued bes_crash_reported incidentKey=$incidentKey reportId=$reportId")
6630
+ } catch (e: JSONException) {
6631
+ throw BluetoothSdkException("bes_crash_dispatch_failed", "Could not create bes_crash_reported.", e)
6632
+ }
6633
+ }
6634
+
6144
6635
  /** Query gallery status from the glasses */
6145
6636
  override fun queryGalleryStatus() {
6146
6637
  try {
@@ -6210,6 +6701,19 @@ class MentraLive : SGCManager() {
6210
6701
  }
6211
6702
  }
6212
6703
 
6704
+ fun sendTouchGestureDefaultBehaviorEnabled(requestId: String, gesture: TouchGesture, enabled: Boolean) {
6705
+ val sessionGeneration = bleSessionGeneration.get()
6706
+ if (!isConnected) throw BluetoothSdkException("not_connected", "Mentra Live glasses are not connected.")
6707
+ val body = JSONObject().put("request_id", requestId).put("gesture", gesture.wireName).put("enabled", enabled)
6708
+ val command = JSONObject().put("C", "cs_tpdef").put("V", 1).put("B", body.toString())
6709
+ val packet = K900ProtocolUtils.packDataToK900(
6710
+ command.toString().toByteArray(StandardCharsets.UTF_8),
6711
+ K900ProtocolUtils.CMD_TYPE_STRING,
6712
+ k900LengthEndian(),
6713
+ ) ?: throw BluetoothSdkException("command_send_failed", "Could not encode the touch gesture setting.")
6714
+ queueData(packet, sessionGeneration = sessionGeneration)
6715
+ }
6716
+
6213
6717
  fun sendGalleryServerEnabled(requestId: String, enabled: Boolean) {
6214
6718
  val json = JSONObject()
6215
6719
  .put("type", "set_gallery_server_enabled")
@@ -6550,8 +7054,19 @@ class MentraLive : SGCManager() {
6550
7054
 
6551
7055
  override fun connectById(id: String) {
6552
7056
  if (postGattLifecycle { connectById(id) }) return
6553
- if (pairingYieldActive) {
6554
- Bridge.log("LIVE: connectById blocked — pairing yield active")
7057
+ if (!isExplicitPairingAttempt()) {
7058
+ // An automatic connect names the saved glasses; a record for other glasses ends.
7059
+ MentraLivePairingStateStore.update("connect_by_id") { it.bindDevice(id) }
7060
+ }
7061
+ if (automaticConnectBlocked()) {
7062
+ Bridge.log(
7063
+ "LIVE: connectById deferred — pairing state ${MentraLivePairingStateStore.describe()}"
7064
+ )
7065
+ savedDeviceName = id
7066
+ if (MentraLivePairingStateStore.isPaused) {
7067
+ armPairingPauseTimer()
7068
+ startPairingWatchScan()
7069
+ }
6555
7070
  return
6556
7071
  }
6557
7072
  reconnectGeneration++
@@ -6675,8 +7190,10 @@ class MentraLive : SGCManager() {
6675
7190
 
6676
7191
  fun connectToSmartGlasses() {
6677
7192
  if (postGattLifecycle { connectToSmartGlasses() }) return
6678
- if (pairingYieldActive) {
6679
- Bridge.log("LIVE: connectToSmartGlasses blocked — pairing yield active")
7193
+ if (automaticConnectBlocked()) {
7194
+ Bridge.log(
7195
+ "LIVE: connectToSmartGlasses blocked — pairing state ${MentraLivePairingStateStore.describe()}"
7196
+ )
6680
7197
  return
6681
7198
  }
6682
7199
  Bridge.log("LIVE: Connecting to Mentra Live glasses")
@@ -7257,6 +7774,12 @@ class MentraLive : SGCManager() {
7257
7774
  }
7258
7775
  bondingRetryCount =
7259
7776
  0 // Reset retry counter on success
7777
+ // During an explicit secure pair the bond alone is
7778
+ // not ownership: keep the failure timeout armed
7779
+ // until pairing_info reports owner_committed.
7780
+ if (!shouldGateReadyOnOwnerCommit(device)) {
7781
+ cancelSecureBondWait()
7782
+ }
7260
7783
  // Bond != audio profile. Explicitly open A2DP
7261
7784
  // after createBond() completes (already-bonded
7262
7785
  // path does this at GATT connect).
@@ -7273,10 +7796,34 @@ class MentraLive : SGCManager() {
7273
7796
  "fullyBooted"
7274
7797
  ) as? Boolean
7275
7798
  ?: false
7276
- if (!alreadyBooted) {
7799
+ if (!alreadyBooted &&
7800
+ awaitingPairingInfoForReadiness
7801
+ ) {
7802
+ // Unknown capability: pairing_info or
7803
+ // its bounded wait decides readiness.
7804
+ Bridge.log(
7805
+ "LIVE: CTKD bonded; readiness still waiting for pairing_info"
7806
+ )
7807
+ } else if (!alreadyBooted &&
7808
+ shouldGateReadyOnOwnerCommit(device)
7809
+ ) {
7810
+ // Bonded, but the glasses have not
7811
+ // reported owner_committed. pairing_info
7812
+ // finishes readiness (or the wait fails).
7813
+ Bridge.log(
7814
+ "LIVE: CTKD bonded; glasses_ready received but owner not committed yet — waiting for pairing_info"
7815
+ )
7816
+ markPairingTiming(
7817
+ "waiting_owner_commit",
7818
+ "queueSize=${sendQueue.size}"
7819
+ )
7820
+ awaitingSecurePairingConfirmation = true
7821
+ armSecureBondWait()
7822
+ } else if (!alreadyBooted) {
7277
7823
  Bridge.log(
7278
7824
  "LIVE: Audio: CTKD bonded; catching up fullyBooted (glasses_ready already received)"
7279
7825
  )
7826
+ awaitingSecurePairingConfirmation = false
7280
7827
  endPairingTiming(
7281
7828
  "fully_connected",
7282
7829
  "via=ctkd_bond+glasses_ready queueSize=${sendQueue.size}"
@@ -7303,6 +7850,22 @@ class MentraLive : SGCManager() {
7303
7850
  Bridge.log(
7304
7851
  "LIVE: CTKD: ❌ Bonding failed or removed for device"
7305
7852
  )
7853
+ val sinceReconnect =
7854
+ lastAutoReconnectLinkAt?.let {
7855
+ SystemClock.elapsedRealtime() - it
7856
+ }
7857
+ if (MentraLiveOwnerLossPolicy.isOwnerRejectionOnBondRemoved(
7858
+ previousBondState,
7859
+ bondState,
7860
+ isKilled,
7861
+ unpairFlushPending,
7862
+ isExplicitPairingAttempt(),
7863
+ sinceReconnect,
7864
+ isSavedGlassesSecureFirmware(),
7865
+ ) && recordAuthRejection("bond_removed_by_glasses")
7866
+ ) {
7867
+ return
7868
+ }
7306
7869
  markPairingTiming(
7307
7870
  "ctkd_bond_none",
7308
7871
  "prev=$previousBondState queueSize=${sendQueue.size}"
@@ -7318,7 +7881,20 @@ class MentraLive : SGCManager() {
7318
7881
  classicAudioConnectionTracker.clear(device.address)
7319
7882
  }
7320
7883
  audioConnected = false
7321
- if (previousBondState == BluetoothDevice.BOND_BONDING) {
7884
+ if (previousBondState == BluetoothDevice.BOND_BONDING &&
7885
+ isExplicitPairingAttempt() &&
7886
+ isSecurePairingTarget()
7887
+ ) {
7888
+ // Secure glasses own a phone only through this bond.
7889
+ // Re-prompting after a decline only repeats the
7890
+ // system dialog; let the pairing screen offer Try again.
7891
+ Bridge.log(
7892
+ "LIVE: CTKD: secure pairing bond not completed — reporting pairing failure"
7893
+ )
7894
+ bondingRetryCount = 0
7895
+ cancelSecureBondWait()
7896
+ Bridge.sendPairFailureEvent("errors:pairingCouldNotStart")
7897
+ } else if (previousBondState == BluetoothDevice.BOND_BONDING) {
7322
7898
  // User cancelled or bonding failed - retry up to
7323
7899
  // MAX_BONDING_RETRIES times
7324
7900
  bondingRetryCount++
@@ -7556,6 +8132,16 @@ class MentraLive : SGCManager() {
7556
8132
  if (ctkdInitiatedThisGattSession) {
7557
8133
  return
7558
8134
  }
8135
+ if (MentraLiveOwnerLossPolicy.shouldDeferCtkdBond(
8136
+ isExplicitPairingAttempt(),
8137
+ isSecurePairingTarget(),
8138
+ device.bondState,
8139
+ pairingInfoSeen,
8140
+ )
8141
+ ) {
8142
+ Bridge.log("LIVE: CTKD: deferring bond until pairing_info allows it")
8143
+ return
8144
+ }
7559
8145
  ctkdInitiatedThisGattSession = true
7560
8146
  Bridge.log(
7561
8147
  "LIVE: CTKD: BLE ready - initiating CTKD bonding for BT Classic (bondState=" +
@@ -7637,7 +8223,7 @@ class MentraLive : SGCManager() {
7637
8223
  }
7638
8224
 
7639
8225
  private fun canConnectClassicAudio(device: BluetoothDevice): Boolean =
7640
- !isKilled && !pairingYieldActive && isConnected && notificationsEnabled &&
8226
+ !isKilled && !automaticConnectBlocked() && isConnected && notificationsEnabled &&
7641
8227
  ctkdInitiatedThisGattSession && connectedDevice?.address == device.address &&
7642
8228
  device.bondState == BluetoothDevice.BOND_BONDED
7643
8229
 
@@ -7752,6 +8338,194 @@ class MentraLive : SGCManager() {
7752
8338
  )
7753
8339
  }
7754
8340
 
8341
+ private fun armSecureBondWait() {
8342
+ if (!MentraLiveOwnerLossPolicy.shouldRunSecureBondWait(
8343
+ isExplicitPairingAttempt(),
8344
+ isSecurePairingTarget(),
8345
+ )
8346
+ ) {
8347
+ return
8348
+ }
8349
+ if (secureBondWaitRunnable != null) return
8350
+ val runnable = Runnable {
8351
+ secureBondWaitRunnable = null
8352
+ if (isKilled || !isExplicitPairingAttempt()) return@Runnable
8353
+ val alreadyBooted = DeviceStore.store.get("glasses", "fullyBooted") as? Boolean ?: false
8354
+ if (alreadyBooted) return@Runnable
8355
+ // A bond alone no longer ends the wait: the glasses must also have reported
8356
+ // owner_committed. If both arrived, readiness is being finished by the bond or
8357
+ // pairing_info handlers.
8358
+ val device = connectedDevice
8359
+ if (device != null &&
8360
+ !MentraLiveOwnerLossPolicy.shouldDeferReadyForBond(
8361
+ isSecurePairingTarget(),
8362
+ device.bondState,
8363
+ securePairingConfirmed,
8364
+ )
8365
+ ) {
8366
+ return@Runnable
8367
+ }
8368
+ awaitingSecurePairingConfirmation = false
8369
+ Bridge.log(
8370
+ "LIVE: secure pairing bond wait expired " +
8371
+ "(bond=${device?.bondState} ownerCommitted=$securePairingConfirmed)"
8372
+ )
8373
+ Bridge.sendPairFailureEvent("errors:pairingCouldNotStart")
8374
+ }
8375
+ secureBondWaitRunnable = runnable
8376
+ handler.postDelayed(runnable, MentraLiveOwnerLossPolicy.SECURE_BOND_WAIT_MS)
8377
+ }
8378
+
8379
+ private fun cancelSecureBondWait() {
8380
+ secureBondWaitRunnable?.let { handler.removeCallbacks(it) }
8381
+ secureBondWaitRunnable = null
8382
+ }
8383
+
8384
+ /** Forget the owner commit when the GATT session ends or a new one starts, like iOS. */
8385
+ private fun resetSecurePairingConfirmation() {
8386
+ securePairingConfirmed = false
8387
+ sessionPairingInfoSecure = null
8388
+ awaitingSecurePairingConfirmation = false
8389
+ awaitingPairingInfoForReadiness = false
8390
+ unknownCapabilityWaitExpired = false
8391
+ phoneHelloSentThisSession = false
8392
+ pairSelectSentThisSession = false
8393
+ // Also tear down any in-flight owner-commit wait so a leftover 40s timer can't fire
8394
+ // pairingCouldNotStart on a later session after GATT drops mid-wait. The other
8395
+ // session timers die with the session too.
8396
+ cancelSecureBondWait()
8397
+ cancelUnknownCapabilityPairingInfoWait()
8398
+ cancelSecureFirmwareRefresh()
8399
+ }
8400
+
8401
+ /**
8402
+ * Bounds the wait for `pairing_info` on an explicit pair to glasses of unknown capability.
8403
+ * Without one by the deadline the glasses count as legacy firmware and are reported ready.
8404
+ */
8405
+ private fun armUnknownCapabilityPairingInfoWait() {
8406
+ if (unknownCapabilityWaitRunnable != null) return
8407
+ val runnable = Runnable {
8408
+ unknownCapabilityWaitRunnable = null
8409
+ if (isKilled || !awaitingPairingInfoForReadiness) return@Runnable
8410
+ unknownCapabilityWaitExpired = true
8411
+ Bridge.log(
8412
+ "LIVE: no pairing_info " +
8413
+ "${MentraLivePairingReadinessPolicy.UNKNOWN_CAPABILITY_PAIRING_INFO_WAIT_MS}ms " +
8414
+ "after glasses_ready — treating the pairing target as legacy firmware"
8415
+ )
8416
+ resolveUnknownCapabilityReadiness("unknown_capability_timeout")
8417
+ }
8418
+ unknownCapabilityWaitRunnable = runnable
8419
+ handler.postDelayed(
8420
+ runnable,
8421
+ MentraLivePairingReadinessPolicy.UNKNOWN_CAPABILITY_PAIRING_INFO_WAIT_MS,
8422
+ )
8423
+ }
8424
+
8425
+ private fun cancelUnknownCapabilityPairingInfoWait() {
8426
+ unknownCapabilityWaitRunnable?.let { handler.removeCallbacks(it) }
8427
+ unknownCapabilityWaitRunnable = null
8428
+ }
8429
+
8430
+ /**
8431
+ * Ends readiness parked for `pairing_info`. A secure report switches to the owner-commit rule
8432
+ * (with the [armSecureBondWait] deadline); a legacy report, or none by the deadline, reports
8433
+ * ready now.
8434
+ */
8435
+ private fun resolveUnknownCapabilityReadiness(via: String) {
8436
+ awaitingPairingInfoForReadiness = false
8437
+ cancelUnknownCapabilityPairingInfoWait()
8438
+ if (isKilled || !glassesReadyReceived) return
8439
+ when (pairingReadiness(connectedDevice)) {
8440
+ MentraLivePairingReadinessPolicy.Readiness.AWAIT_OWNER_COMMIT -> {
8441
+ Bridge.log(
8442
+ "LIVE: pairing target reported secure firmware — waiting for BLE bond / owner commit " +
8443
+ "(bond=${connectedDevice?.bondState} ownerCommitted=$securePairingConfirmed)"
8444
+ )
8445
+ markPairingTiming("waiting_owner_commit", "queueSize=${sendQueue.size}")
8446
+ awaitingSecurePairingConfirmation = true
8447
+ armSecureBondWait()
8448
+ }
8449
+ MentraLivePairingReadinessPolicy.Readiness.AWAIT_PAIRING_INFO -> {
8450
+ // Not reachable: pairing_info arrived or the wait expired. Keep a deadline anyway.
8451
+ awaitingPairingInfoForReadiness = true
8452
+ armUnknownCapabilityPairingInfoWait()
8453
+ }
8454
+ MentraLivePairingReadinessPolicy.Readiness.READY -> completeSecurePairingReadiness(via)
8455
+ }
8456
+ }
8457
+
8458
+ /**
8459
+ * A ready session refreshes `mentra_live_secure_firmware`: `pairing_info` writes it, and a
8460
+ * session without one within [MentraLivePairingReadinessPolicy.SECURE_FIRMWARE_REFRESH_MS]
8461
+ * clears it, so glasses rolled back to old firmware stop counting as secure.
8462
+ */
8463
+ private fun armSecureFirmwareRefresh() {
8464
+ if (pairingInfoSeen || secureFirmwareRefreshRunnable != null) return
8465
+ val runnable = Runnable {
8466
+ secureFirmwareRefreshRunnable = null
8467
+ if (isKilled || !isConnected || !glassesReadyReceived) return@Runnable
8468
+ val secure =
8469
+ MentraLivePairingReadinessPolicy.secureFirmwareAfterReadySession(pairingInfoSeen)
8470
+ ?: return@Runnable
8471
+ if (isSavedGlassesSecureFirmware() != secure) {
8472
+ Bridge.log(
8473
+ "LIVE: no pairing_info " +
8474
+ "${MentraLivePairingReadinessPolicy.SECURE_FIRMWARE_REFRESH_MS}ms after " +
8475
+ "glasses_ready — glasses are not secure-pairing firmware"
8476
+ )
8477
+ }
8478
+ rememberSecureFirmware(secure)
8479
+ }
8480
+ secureFirmwareRefreshRunnable = runnable
8481
+ handler.postDelayed(runnable, MentraLivePairingReadinessPolicy.SECURE_FIRMWARE_REFRESH_MS)
8482
+ }
8483
+
8484
+ private fun cancelSecureFirmwareRefresh() {
8485
+ secureFirmwareRefreshRunnable?.let { handler.removeCallbacks(it) }
8486
+ secureFirmwareRefreshRunnable = null
8487
+ }
8488
+
8489
+ /**
8490
+ * True while an explicit secure pair must keep waiting: either the BLE bond or the glasses'
8491
+ * `owner_committed` is still missing. Non-explicit reconnects and legacy targets never gate.
8492
+ */
8493
+ private fun shouldGateReadyOnOwnerCommit(device: BluetoothDevice?): Boolean =
8494
+ isExplicitPairingAttempt() &&
8495
+ MentraLiveOwnerLossPolicy.shouldDeferReadyForBond(
8496
+ isSecurePairingTarget(),
8497
+ device?.bondState,
8498
+ securePairingConfirmed,
8499
+ )
8500
+
8501
+ /**
8502
+ * Finishes readiness that glasses_ready parked for the owner commit. Runs from
8503
+ * `pairing_info` once `owner_committed` arrives; if the BLE bond is still missing, the
8504
+ * BOND_BONDED handler finishes it instead. Also finishes a parked unknown-capability target
8505
+ * once [resolveUnknownCapabilityReadiness] found it ready.
8506
+ */
8507
+ private fun completeSecurePairingReadiness(via: String) {
8508
+ if (isKilled || !glassesReadyReceived) return
8509
+ val alreadyBooted = DeviceStore.store.get("glasses", "fullyBooted") as? Boolean ?: false
8510
+ if (alreadyBooted) {
8511
+ awaitingSecurePairingConfirmation = false
8512
+ cancelSecureBondWait()
8513
+ return
8514
+ }
8515
+ if (shouldGateReadyOnOwnerCommit(connectedDevice)) {
8516
+ Bridge.log("LIVE: owner committed but BLE bond not reported yet — waiting for bond")
8517
+ return
8518
+ }
8519
+ awaitingSecurePairingConfirmation = false
8520
+ cancelSecureBondWait()
8521
+ endPairingTiming("fully_connected", "via=$via queueSize=${sendQueue.size}")
8522
+ DeviceStore.apply("glasses", "fullyBooted", true)
8523
+ updateConnectionState(ConnTypes.CONNECTED)
8524
+ if (!audioConnected) {
8525
+ markPairingTiming("waiting_ctkd_bond", "queueSize=${sendQueue.size}")
8526
+ }
8527
+ }
8528
+
7755
8529
  /** Helper to mark audio as connected and notify */
7756
8530
  private fun markAudioConnected(device: BluetoothDevice) {
7757
8531
  if (isKilled) {
@@ -7766,6 +8540,24 @@ class MentraLive : SGCManager() {
7766
8540
  Bridge.sendAudioConnected(safeDeviceName(device))
7767
8541
  }
7768
8542
  if (glassesReadyReceived) {
8543
+ if (awaitingPairingInfoForReadiness) {
8544
+ Bridge.log("LIVE: A2DP up while readiness waits for pairing_info — not marking paired yet")
8545
+ return
8546
+ }
8547
+ if (!MentraLiveOwnerLossPolicy.shouldMarkReadyFromAudio(
8548
+ isExplicitPairingAttempt(),
8549
+ isSecurePairingTarget(),
8550
+ device.bondState,
8551
+ securePairingConfirmed,
8552
+ )
8553
+ ) {
8554
+ Bridge.log("LIVE: A2DP up before BLE bond / owner commit — not marking paired")
8555
+ awaitingSecurePairingConfirmation = true
8556
+ armSecureBondWait()
8557
+ return
8558
+ }
8559
+ awaitingSecurePairingConfirmation = false
8560
+ cancelSecureBondWait()
7769
8561
  Bridge.log(
7770
8562
  "LIVE: A2DP: Both audio and glasses_ready confirmed - marking as fully connected"
7771
8563
  )
@@ -7967,10 +8759,8 @@ class MentraLive : SGCManager() {
7967
8759
  isKilled = true
7968
8760
  classicAudioServiceDiscovery.cancel()
7969
8761
  explicitConnectByName = false
7970
- pairingYieldActive = false
7971
- pairingYieldAwaitingReclaim = false
7972
- pairingYieldEndRunnable?.let { handler.removeCallbacks(it) }
7973
- pairingYieldEndRunnable = null
8762
+ // The pairing state itself lives on in MentraLivePairingStateStore.
8763
+ cancelPairingPauseTimer()
7974
8764
  unpairFlushRunnable?.let { handler.removeCallbacks(it) }
7975
8765
  unpairFlushRunnable = null
7976
8766
  unpairFlushPending = false
@@ -8066,6 +8856,7 @@ class MentraLive : SGCManager() {
8066
8856
  isReconnecting = false
8067
8857
  glassesReady = false
8068
8858
  glassesReadyReceived = false
8859
+ resetSecurePairingConfirmation()
8069
8860
  audioConnected = false
8070
8861
  ctkdInitiatedThisGattSession = false
8071
8862
  classicAudioServiceDiscovery.cancel()
@@ -9088,13 +9879,34 @@ class MentraLive : SGCManager() {
9088
9879
  wireHandshakeSentGeneration = -1
9089
9880
  }
9090
9881
 
9882
+ /**
9883
+ * A glasses_ready that echoes a readyId answers a phone_ready exchange. The answer to the
9884
+ * exchange the phone is waiting on, and any answer from a glasses process other than the one
9885
+ * this link last handled (an asg restart resets for every exchange it first sees), followed a
9886
+ * transport reset. Any other answer repeats an exchange that process already reset for, or one
9887
+ * superseded by the pending exchange, whose answer is still to come.
9888
+ */
9889
+ private fun isRepeatedGlassesReady(readyId: String, sid: String?): Boolean =
9890
+ readyId != pendingReadyId && sid == readyGlassesSessionId
9891
+
9892
+ private fun resetReadinessExchange() {
9893
+ pendingReadyId = null
9894
+ readyGlassesSessionId = null
9895
+ }
9896
+
9091
9897
  /** Sends phone_ready to (re)start the glasses-driven readiness flow. */
9092
9898
  private fun sendPhoneReady(reason: String) {
9093
- Bridge.log("LIVE: 📱 Sending phone_ready to glasses ($reason) - waiting for glasses_ready response")
9899
+ val readyId = pendingReadyId ?: UUID.randomUUID().toString()
9900
+ pendingReadyId = readyId
9901
+ Bridge.log(
9902
+ "LIVE: 📱 Sending phone_ready to glasses ($reason, exchange $readyId) - " +
9903
+ "waiting for glasses_ready response"
9904
+ )
9094
9905
  markPairingTiming("phone_ready_sent", "reason=$reason queueSize=${sendQueue.size}")
9095
9906
  val readyMsg = JSONObject()
9096
9907
  readyMsg.put("type", "phone_ready")
9097
9908
  readyMsg.put("timestamp", System.currentTimeMillis())
9909
+ readyMsg.put("readyId", readyId)
9098
9910
  sendJson(readyMsg, true)
9099
9911
  }
9100
9912
 
@@ -10035,6 +10847,20 @@ class MentraLive : SGCManager() {
10035
10847
  }
10036
10848
  }
10037
10849
 
10850
+ fun sendWifiAdbStateToPeer(enabled: Boolean, expectedBluetoothMac: String) {
10851
+ val generation = bleSessionGeneration.get()
10852
+ val identity = wifiAdbPeerIdentity
10853
+ if (!wifiAdbPeerMatches(expectedBluetoothMac, identity, generation,
10854
+ isConnected && bluetoothGatt != null && txCharacteristic != null)) {
10855
+ throw BluetoothSdkException("device_identity_changed", "The selected glasses identity or connection changed.")
10856
+ }
10857
+ val command = JSONObject().put("type", "set_wifi_adb_state").put("enabled", enabled)
10858
+ // Preserve the checked generation through framing and the existing BLE queue fence.
10859
+ if (!sendJson(command, true, true, generation)) {
10860
+ throw BluetoothSdkException("command_send_failed", "Could not queue Wi-Fi debugging for the selected glasses.")
10861
+ }
10862
+ }
10863
+
10038
10864
  override fun sendWifiAdbState(enabled: Boolean) {
10039
10865
  Bridge.log("LIVE: 🔧 Sending Wi-Fi ADB state to glasses - enabled: " + enabled)
10040
10866
  try {
@@ -10463,6 +11289,15 @@ class MentraLive : SGCManager() {
10463
11289
  // Transfer is complete - process successfully
10464
11290
  Bridge.log("LIVE: 📦 File transfer complete: " + packetInfo.fileName)
10465
11291
 
11292
+ if (IncidentLogBleRelayNaming.isRelayFileName(packetInfo.fileName)) {
11293
+ // No relay registered (e.g. the app restarted mid-relay): nothing reached
11294
+ // Cloud, so success would make the glasses mark the incident uploaded.
11295
+ Log.w(TAG, "Incident log relay without a registered report: " + packetInfo.fileName)
11296
+ sendTransferCompleteConfirmation(packetInfo.fileName, false)
11297
+ activeFileTransfers.remove(packetInfo.fileName)
11298
+ return
11299
+ }
11300
+
10466
11301
  // Assemble and save the file
10467
11302
  val fileData = session.assembleFile()
10468
11303
  if (fileData != null) {
@@ -10679,6 +11514,13 @@ class MentraLive : SGCManager() {
10679
11514
  success,
10680
11515
  message ->
10681
11516
  Handler(Looper.getMainLooper()).post {
11517
+ // A different report now owns this name (it was admitted after our owner finished),
11518
+ // so a completion here would mark ITS file done. Drop the stale callback.
11519
+ val owner = bleIncidentLogRelays[relay.fileBaseKey]
11520
+ if (owner != null && owner.incidentId != relay.incidentId) {
11521
+ Log.w(TAG, "Dropping stale incident relay callback for " + relay.fileBaseKey)
11522
+ return@post
11523
+ }
10682
11524
  if (success) {
10683
11525
  Bridge.log(
10684
11526
  "LIVE: ✅ Incident log BLE relay uploaded (" +
@@ -10686,7 +11528,6 @@ class MentraLive : SGCManager() {
10686
11528
  "): " +
10687
11529
  relay.incidentId
10688
11530
  )
10689
- bleIncidentLogRelays.remove(relay.fileBaseKey)
10690
11531
  } else {
10691
11532
  Log.e(
10692
11533
  TAG,
@@ -10699,6 +11540,11 @@ class MentraLive : SGCManager() {
10699
11540
  relay.session = null
10700
11541
  }
10701
11542
  sendTransferCompleteConfirmation(fileName, success)
11543
+ // Release only after the glasses' confirmation is queued, so a report that reuses
11544
+ // this name is ordered behind the owner's completion.
11545
+ if (success) {
11546
+ bleIncidentLogRelays.remove(relay.fileBaseKey, relay)
11547
+ }
10702
11548
  }
10703
11549
  }
10704
11550
  }
@@ -10855,20 +11701,19 @@ class MentraLive : SGCManager() {
10855
11701
  }
10856
11702
 
10857
11703
  /**
10858
- * Get the core authentication token. Reads from DeviceStore first (synced from JS via
10859
- * BluetoothSdkModule.update), then falls back to SharedPreferences for backward compatibility.
11704
+ * Get the current Core access token, synced from JS into the in-memory DeviceStore
11705
+ * (BluetoothSdkModule.update). Empty when there is none: credentials are never read from
11706
+ * plain storage.
10860
11707
  */
10861
11708
  private fun getCoreToken(): String {
10862
11709
  val fromStore = DeviceStore.get("bluetooth", "core_token")
10863
- if (fromStore is String) {
10864
- val token = fromStore
10865
- if (token != null && !token.isEmpty()) {
10866
- return token
10867
- }
10868
- }
10869
- val prefs = context!!.getSharedPreferences(AUTH_PREFS_NAME, Context.MODE_PRIVATE)
10870
- val fromPrefs = prefs.getString(KEY_CORE_TOKEN, "")
10871
- return if (fromPrefs != null) fromPrefs else ""
11710
+ return if (fromStore is String) fromStore else ""
11711
+ }
11712
+
11713
+ /** Delete the Core token older builds left in plain SharedPreferences. */
11714
+ private fun forgetLegacyCoreToken() {
11715
+ val prefs = context?.getSharedPreferences(LEGACY_AUTH_PREFS_NAME, Context.MODE_PRIVATE) ?: return
11716
+ if (prefs.contains(LEGACY_KEY_CORE_TOKEN)) prefs.edit().remove(LEGACY_KEY_CORE_TOKEN).apply()
10872
11717
  }
10873
11718
 
10874
11719
  /** Send BLE transfer completion notification */