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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/MIGRATION.md +61 -0
  2. package/README.md +80 -11
  3. package/android/build.gradle +60 -51
  4. package/android/gradle.properties +3 -0
  5. package/android/settings.gradle +47 -3
  6. package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -2
  8. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +85 -6
  9. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +35 -1
  10. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +154 -110
  11. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceStore.kt +21 -0
  12. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +1 -0
  13. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  14. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +27 -2
  15. package/android/src/main/java/com/mentra/bluetoothsdk/connection/ConnectionModels.kt +5 -0
  16. package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
  17. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicy.kt +64 -0
  18. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +925 -155
  19. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +227 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisement.kt +19 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicy.kt +94 -0
  22. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachine.kt +411 -0
  23. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateStore.kt +124 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +54 -59
  25. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +5 -32
  26. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasEncoder.kt +8 -1
  27. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +3 -10
  28. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
  29. package/android/src/main/java/com/mentra/bluetoothsdk/status/DeviceStatus.kt +50 -0
  30. package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
  31. package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
  32. package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
  33. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
  34. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
  35. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
  36. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
  37. package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
  38. package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
  39. package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
  40. package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
  41. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
  42. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
  43. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
  44. package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
  45. package/android/src/test/java/com/mentra/bluetoothsdk/DeviceManagerOwnerLossTest.kt +146 -0
  46. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusAudioSetupTest.kt +51 -0
  47. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusClassicAudioTest.kt +2 -0
  48. package/android/src/test/java/com/mentra/bluetoothsdk/WifiAdbPeerIntentTest.kt +19 -0
  49. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicyTest.kt +65 -0
  50. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveAudioSetupReadinessTest.kt +231 -0
  51. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +5 -1
  52. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
  53. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +368 -0
  54. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisementParserTest.kt +20 -0
  55. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicyTest.kt +136 -0
  56. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachineTest.kt +346 -0
  57. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
  58. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
  59. package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
  60. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
  61. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
  62. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
  63. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
  64. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
  65. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
  66. package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
  67. package/build/BluetoothSdk.types.d.ts +201 -1
  68. package/build/BluetoothSdk.types.d.ts.map +1 -1
  69. package/build/BluetoothSdk.types.js.map +1 -1
  70. package/build/_private/BluetoothSdkModule.d.ts +43 -5
  71. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  72. package/build/_private/BluetoothSdkModule.js +2 -0
  73. package/build/_private/BluetoothSdkModule.js.map +1 -1
  74. package/build/generated/changelogCatalog.d.ts +3 -0
  75. package/build/generated/changelogCatalog.d.ts.map +1 -1
  76. package/build/generated/changelogCatalog.js +4 -0
  77. package/build/generated/changelogCatalog.js.map +1 -1
  78. package/build/generated/releaseMetadata.js +6 -6
  79. package/build/generated/releaseMetadata.js.map +1 -1
  80. package/build/index.d.ts +1 -1
  81. package/build/index.d.ts.map +1 -1
  82. package/build/index.js +9 -0
  83. package/build/index.js.map +1 -1
  84. package/ios/BluetoothSdkModule.swift +76 -12
  85. package/ios/MentraBluetoothSDK.podspec +4 -0
  86. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  87. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  88. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  89. package/ios/Source/BluetoothSdkDefaults.swift +2 -2
  90. package/ios/Source/Bridge.swift +11 -3
  91. package/ios/Source/DeviceManager.swift +131 -18
  92. package/ios/Source/DeviceStore.swift +27 -0
  93. package/ios/Source/GeneratedChangelogCatalog.swift +1 -0
  94. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  95. package/ios/Source/MentraBluetoothSDK.swift +40 -5
  96. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  97. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  98. package/ios/Source/audio/SpeechActivity.swift +277 -0
  99. package/ios/Source/errors/BluetoothSdkError.swift +5 -1
  100. package/ios/Source/events/BluetoothEvents.swift +41 -0
  101. package/ios/Source/internal/BleTraceLogger.swift +9 -6
  102. package/ios/Source/internal/BluetoothAvailability.swift +15 -5
  103. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +186 -0
  104. package/ios/Source/sgcs/MentraLive.swift +1270 -189
  105. package/ios/Source/sgcs/MentraLivePairingAdvertisement.swift +260 -1
  106. package/ios/Source/sgcs/MentraLivePairingStateMachine.swift +385 -0
  107. package/ios/Source/sgcs/MentraLivePairingStateStore.swift +121 -0
  108. package/ios/Source/sgcs/Nimo.swift +10 -3
  109. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +39 -9
  110. package/ios/Source/sgcs/SGCManager.swift +13 -0
  111. package/ios/Source/sgcs/Simulated.swift +2 -0
  112. package/ios/Source/status/DeviceStatus.swift +35 -0
  113. package/ios/Source/stt/STTTools.swift +13 -31
  114. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  115. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  116. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  117. package/ios/Source/types/DeviceModels.swift +8 -1
  118. package/ios/Source/utils/AudioSessionMonitor.swift +158 -5
  119. package/ios/Source/utils/BoundedWait.swift +44 -0
  120. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  121. package/ios/Source/utils/SttModelTraits.swift +62 -0
  122. package/ios/Tests/BesCrashReportTests.swift +142 -0
  123. package/ios/Tests/BluetoothAudioRouteTests.swift +82 -0
  124. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  125. package/ios/Tests/DeviceManagerReconnectTests.swift +4 -2
  126. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +197 -0
  127. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  128. package/ios/Tests/MentraLiveAudioSetupTests.swift +209 -0
  129. package/ios/Tests/MentraLiveConnectionOptionsTests.swift +55 -0
  130. package/ios/Tests/MentraLivePairingAdvertisementTests.swift +327 -0
  131. package/ios/Tests/MentraLivePairingStateMachineTests.swift +402 -0
  132. package/ios/Tests/MentraLiveSessionReadinessTests.swift +368 -26
  133. package/ios/Tests/NimoCanvasTransportTests.swift +58 -0
  134. package/ios/Tests/PcmStreamTests.swift +299 -0
  135. package/ios/Tests/SpeechActivityTests.swift +238 -0
  136. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  137. package/ios/Tests/WifiAdbDispatchTests.swift +118 -0
  138. package/package.json +3 -2
  139. package/plugin/build/withAndroid.js +9 -11
  140. package/plugin/build/withKotlinVersion.d.ts +2 -0
  141. package/plugin/build/withKotlinVersion.js +46 -0
  142. package/src/BluetoothSdk.types.ts +201 -1
  143. package/src/_private/BluetoothSdkModule.ts +47 -5
  144. package/src/generated/changelogCatalog.ts +4 -0
  145. package/src/generated/releaseMetadata.ts +6 -6
  146. package/src/index.ts +22 -0
  147. package/android/silero/LICENSE.md +0 -17
  148. package/android/silero/build.gradle +0 -50
  149. package/android/silero/proguard-rules.pro +0 -24
  150. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  151. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  152. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  153. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  154. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  155. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  156. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  157. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  158. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  159. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  160. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
  161. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
  162. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  163. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
  164. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
  165. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
  166. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -288
  167. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  168. /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
@@ -132,6 +132,10 @@ class MentraLive : SGCManager() {
132
132
  private val besOtaHeartbeatGuard = BesOtaHeartbeatGuard()
133
133
 
134
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
+
135
139
  private const val TAG = "Live"
136
140
 
137
141
  // Feature Flags
@@ -151,6 +155,9 @@ class MentraLive : SGCManager() {
151
155
  private const val A2DP_CONNECT_MAX_ATTEMPTS = 5
152
156
  private const val A2DP_CONNECT_RETRY_MS = 800L
153
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
154
161
  private const val GATT_DISCONNECT_TIMEOUT_MS = 2_000L
155
162
  private const val MTU_CALLBACK_TIMEOUT_MS = 3_000L
156
163
  private val gattTeardownBarrier = MentraLiveGattTeardownBarrier()
@@ -199,6 +206,8 @@ class MentraLive : SGCManager() {
199
206
  10_000L // 10s before first scan after shutdown
200
207
 
201
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
202
211
 
203
212
  private fun manufacturerData(result: ScanResult): ByteArray? {
204
213
  return result.scanRecord?.getManufacturerSpecificData(MENTRA_MANUFACTURER_ID)
@@ -217,9 +226,16 @@ class MentraLive : SGCManager() {
217
226
  val advertisement =
218
227
  MentraLivePairingAdvertisementParser.parse(manufacturerData(result))
219
228
  ?: return Triple(false, null, false)
229
+ result.device?.address?.let { secureTrailerScanMemory.noteSecureTrailer(it) }
220
230
  return Triple(advertisement.pairingMode, advertisement.pairingCode, true)
221
231
  }
222
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
+
223
239
  fun isMentraLiveBluetoothName(name: String?): Boolean {
224
240
  if (name.isNullOrEmpty()) {
225
241
  return false
@@ -444,6 +460,22 @@ class MentraLive : SGCManager() {
444
460
  }
445
461
  }
446
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
+
447
479
  private const val SHUTDOWN_RECENT_MS = 45_000L // Consider "recent shutdown" for 45s
448
480
 
449
481
  // Keep-alive parameters
@@ -466,9 +498,9 @@ class MentraLive : SGCManager() {
466
498
  private const val PREFS_NAME = "MentraLivePrefs"
467
499
  private const val PREF_DEVICE_NAME = "LastConnectedDeviceName"
468
500
 
469
- // Auth settings
470
- private const val AUTH_PREFS_NAME = "augmentos_auth_prefs"
471
- 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"
472
504
 
473
505
  private const val MAX_BONDING_RETRIES = 3
474
506
  private const val BONDING_RETRY_DELAY_MS =
@@ -625,11 +657,41 @@ class MentraLive : SGCManager() {
625
657
  private var isConnecting = false
626
658
  private var isKilled = false
627
659
 
628
- /** Glasses opened a pairing window — stop reconnect without forgetting identity/bonds. */
629
- private var pairingYieldActive = false
630
- private var pairingYieldEndRunnable: Runnable? = null
631
- /** After yield ends, auth/not-owner failures may clear saved glasses. */
632
- 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
633
695
  /** Hold GATT teardown until the unpair write can leave the phone. */
634
696
  private var unpairFlushPending = false
635
697
  private var unpairFlushRunnable: Runnable? = null
@@ -726,6 +788,7 @@ class MentraLive : SGCManager() {
726
788
 
727
789
  // Local state tracking (not in parent SGCManager)
728
790
  private var isCharging = false // Charging status (batteryLevel is in parent)
791
+ @Volatile private var wifiAdbPeerIdentity: Pair<Long, String>? = null
729
792
  private var isConnected = false
730
793
 
731
794
  // File transfer management
@@ -786,6 +849,7 @@ class MentraLive : SGCManager() {
786
849
  val apiBaseUrl: String,
787
850
  val kind: BleIncidentLogKind
788
851
  ) {
852
+ val reservedAtMs: Long = SystemClock.elapsedRealtime()
789
853
  var session: FileTransferSession? = null
790
854
  }
791
855
 
@@ -1041,6 +1105,7 @@ class MentraLive : SGCManager() {
1041
1105
  this.type = DeviceTypes.LIVE
1042
1106
  this.hasMic = true
1043
1107
  this.context = Bridge.getContext()
1108
+ forgetLegacyCoreToken()
1044
1109
 
1045
1110
  // Initialize bluetooth adapter
1046
1111
  val bluetoothManager =
@@ -1144,6 +1209,8 @@ class MentraLive : SGCManager() {
1144
1209
  } else {
1145
1210
  Bridge.log("LIVE: 🎵 Phone audio monitor disabled (BLOCK_AUDIO_DUPLEX=false)")
1146
1211
  }
1212
+
1213
+ restorePairingState()
1147
1214
  }
1148
1215
 
1149
1216
  override fun cleanup() {
@@ -1194,6 +1261,7 @@ class MentraLive : SGCManager() {
1194
1261
 
1195
1262
  private fun updateConnectionState(state: String) {
1196
1263
  if (state == ConnTypes.DISCONNECTED) {
1264
+ wifiAdbPeerIdentity = null
1197
1265
  DeviceStore.apply("glasses", "hotspotOtaVersion", 0)
1198
1266
  }
1199
1267
  val isEqual = state == connectionState
@@ -1226,8 +1294,18 @@ class MentraLive : SGCManager() {
1226
1294
  DeviceStore.apply("glasses", "connectionState", state)
1227
1295
 
1228
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
+ }
1229
1302
  DeviceStore.apply("glasses", "connected", true)
1230
- 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
+ ) {
1231
1309
  DeviceStore.apply("glasses", "fullyBooted", true)
1232
1310
  }
1233
1311
  // Drop cached version fields from the previous BLE session so the next version_info
@@ -1304,10 +1382,8 @@ class MentraLive : SGCManager() {
1304
1382
  /** Starts BLE scanning for Mentra Live glasses */
1305
1383
  private fun startScan() {
1306
1384
  if (postGattLifecycle { startScan() }) return
1307
- if (pairingYieldActive) {
1308
- Bridge.log("LIVE: startScan blocked — pairing yield active")
1309
- return
1310
- }
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.
1311
1387
  if (bluetoothAdapter == null || isScanning) {
1312
1388
  return
1313
1389
  }
@@ -1367,6 +1443,8 @@ class MentraLive : SGCManager() {
1367
1443
  }
1368
1444
 
1369
1445
  val generation = ++scanGeneration
1446
+ // A unit rolled back to old firmware must not keep counting as secure.
1447
+ secureTrailerScanMemory.onScanStart()
1370
1448
  isScanning = true
1371
1449
  scanCallback = createScanCallback(generation)
1372
1450
  bluetoothScanner!!.startScan(filters, settings, scanCallback)
@@ -1407,6 +1485,8 @@ class MentraLive : SGCManager() {
1407
1485
  "LIVE: 🔌 ⏰ Reconnect scan timed out - scheduling next reconnect attempt"
1408
1486
  )
1409
1487
  handleReconnection()
1488
+ } else {
1489
+ startPairingWatchScan()
1410
1490
  }
1411
1491
  }
1412
1492
  }
@@ -1458,7 +1538,7 @@ class MentraLive : SGCManager() {
1458
1538
  * an established owner's connected glasses have no pending name/address and stay hidden.
1459
1539
  */
1460
1540
  private fun emitConnectedPendingDeviceForPairingScan() {
1461
- if (!manualDiscoveryActive || isReconnecting || pairingYieldActive) return
1541
+ if (!manualDiscoveryActive || isReconnecting) return
1462
1542
  val device = connectedDevice ?: bluetoothGatt?.device ?: return
1463
1543
  val name = safeBondedDeviceName(device)
1464
1544
  if (!isMentraLiveBluetoothName(name)) return
@@ -1553,17 +1633,21 @@ class MentraLive : SGCManager() {
1553
1633
  // Connect-by-name only when reconnecting OR connectById() asked for
1554
1634
  // this name. A discovery-only pairing scan must not auto-connect just
1555
1635
  // because savedDeviceName still matches (spoof risk).
1636
+ val isSavedGlasses =
1637
+ savedDeviceName.isNotEmpty() && savedDeviceName == deviceName
1556
1638
  val isNamedConnectTarget =
1557
- savedDeviceName.isNotEmpty() &&
1558
- savedDeviceName == deviceName &&
1559
- (isReconnecting || explicitConnectByName)
1560
- if (!isReconnecting &&
1561
- advertisesPairingFlag(result) &&
1562
- !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
+ )
1563
1646
  ) {
1564
- // Tell RN a nearby unit is advertising but not pairable. The scan
1565
- // screen keeps it visible with pairing-mode guidance but blocks the
1566
- // 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.
1567
1651
  Bridge.log(
1568
1652
  "LIVE: Nearby $deviceName is secure firmware not in pairing mode — exposing as non-pairable"
1569
1653
  )
@@ -1600,8 +1684,28 @@ class MentraLive : SGCManager() {
1600
1684
  securePairingCapable = secureCapable,
1601
1685
  )
1602
1686
 
1687
+ if (savedDeviceName.isNotEmpty() && savedDeviceName == deviceName) {
1688
+ observeSavedGlassesAdvertisement(result)
1689
+ }
1690
+
1691
+ if (isNamedConnectTarget && automaticConnectBlocked()) {
1692
+ return
1693
+ }
1694
+
1603
1695
  // connectById / reconnect: user (or reconnect) asked for this name —
1604
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
+
1605
1709
  if (isNamedConnectTarget) {
1606
1710
  Log.i(
1607
1711
  TAG,
@@ -1621,7 +1725,7 @@ class MentraLive : SGCManager() {
1621
1725
  else " (connectById)")
1622
1726
  )
1623
1727
  synchronized(connectionLock) {
1624
- if (pairingYieldActive || isConnected || isConnecting) {
1728
+ if (automaticConnectBlocked() || isConnected || isConnecting) {
1625
1729
  return
1626
1730
  }
1627
1731
  isConnecting = true
@@ -1722,6 +1826,7 @@ class MentraLive : SGCManager() {
1722
1826
  streamControlVersion = 0
1723
1827
  readinessCompletedThisBleSession = false
1724
1828
  glassesReadyReceived = false
1829
+ resetSecurePairingConfirmation()
1725
1830
  ctkdInitiatedThisGattSession = false
1726
1831
  classicAudioServiceDiscovery.cancel()
1727
1832
  audioConnected = false
@@ -1842,8 +1947,10 @@ class MentraLive : SGCManager() {
1842
1947
  if (device == null) {
1843
1948
  return
1844
1949
  }
1845
- if (isKilled || pairingYieldActive) {
1846
- Bridge.log("LIVE: connectToDevice blocked — pairing yield active")
1950
+ if (isKilled || automaticConnectBlocked()) {
1951
+ Bridge.log(
1952
+ "LIVE: connectToDevice blocked — pairing state ${MentraLivePairingStateStore.describe()}"
1953
+ )
1847
1954
  isConnecting = false
1848
1955
  isReconnecting = false
1849
1956
  return
@@ -1852,7 +1959,7 @@ class MentraLive : SGCManager() {
1852
1959
  // Never replace a still-open GATT. Its disconnect/close must finish first.
1853
1960
  bluetoothGatt?.let { beginGattTeardown(it) }
1854
1961
  gattTeardownBarrier.runWhenIdle {
1855
- if (requestEpoch == connectionRequestEpoch && !isKilled && !pairingYieldActive) {
1962
+ if (requestEpoch == connectionRequestEpoch && !isKilled && !automaticConnectBlocked()) {
1856
1963
  connectToDeviceWhenIdle(device)
1857
1964
  }
1858
1965
  }
@@ -1967,87 +2074,253 @@ class MentraLive : SGCManager() {
1967
2074
  // }
1968
2075
  // }
1969
2076
 
1970
- private fun enterPairingYield(windowMs: Long) {
1971
- 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() {
1972
2137
  connectionRequestEpoch++
1973
- pairingYieldActive = true
1974
- pairingYieldAwaitingReclaim = false
2138
+ // Invalidate delayed reconnect callbacks already on the handler.
2139
+ reconnectGeneration++
1975
2140
  isReconnecting = false
1976
2141
  isConnecting = false
1977
- pairingYieldEndRunnable?.let { handler.removeCallbacks(it) }
2142
+ cancelSecureBondWait()
1978
2143
  if (connectionTimeoutRunnable != null) {
1979
2144
  connectionTimeoutHandler.removeCallbacks(connectionTimeoutRunnable!!)
1980
2145
  connectionTimeoutRunnable = null
1981
2146
  }
1982
- // Stop scans/reconnect work; keep default_wearable / Classic bond.
1983
- if (isScanning) {
2147
+ if (isScanning && !manualDiscoveryActive) {
1984
2148
  stopScan()
1985
2149
  emitStopScanEvent()
1986
2150
  }
1987
- // Drop A2DP/HFP (keep the Classic bond) so glasses can advertise for reclaim.
1988
- // Do this before nulling connectedDevice — disconnectClassicProfiles needs it.
1989
- val yieldingDevice = connectedDevice
1990
- disconnectClassicProfiles(yieldingDevice)
1991
- // closeGattQuietly nulls bluetoothGatt before the disconnect callback, so
1992
- // onConnectionStateChange treats it as stale and never publishes DISCONNECTED.
1993
- // Mirror a real disconnect for UI + session state, then tear GATT down.
1994
- isConnected = false
1995
- connectedDevice = null
1996
- glassesReady = false
1997
- glassesSessionId = null
1998
- streamControlVersion = 0
1999
- readinessCompletedThisBleSession = false
2000
- glassesReadyReceived = false
2001
- ctkdInitiatedThisGattSession = false
2002
- 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)
2003
2156
  audioConnected = false
2004
- notificationsEnabled = false
2005
- processSendQueueRunnable?.let { handler.removeCallbacks(it) }
2006
- stopReadinessCheckLoop()
2007
- stopHeartbeat()
2008
- stopSignalStrengthPolling()
2009
- stopMicBeat()
2010
- closeL2capFileChannel()
2011
- fileProcessingHandler.removeCallbacksAndMessages(null)
2012
- clearFilePacketBuffer()
2013
- updateConnectionState(ConnTypes.DISCONNECTED)
2014
- closeGattQuietly(true)
2015
- // Stand down for the whole window. Probing GATT during yield races the new
2016
- // phone for BLE_CONNECTION_MAX=1 and is exactly what entering_pairing_mode forbids.
2017
- val end =
2018
- Runnable {
2019
- Bridge.log("LIVE: Pairing yield ended — resume reconnect if still owned")
2020
- pairingYieldActive = false
2021
- pairingYieldAwaitingReclaim = true
2022
- pairingYieldEndRunnable = null
2023
- if (!isKilled && !isConnected && !isConnecting) {
2024
- 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())
2025
2173
  }
2026
- }
2027
- pairingYieldEndRunnable = end
2028
- handler.postDelayed(end, windowMs)
2174
+ )
2175
+ }
2176
+ pairingPauseEndRunnable = end
2177
+ handler.postDelayed(end, remaining + 50L)
2029
2178
  }
2030
2179
 
2031
- fun isPairingYieldActive(): Boolean = pairingYieldActive
2180
+ private fun cancelPairingPauseTimer() {
2181
+ pairingPauseEndRunnable?.let { handler.removeCallbacks(it) }
2182
+ pairingPauseEndRunnable = null
2183
+ }
2032
2184
 
2033
- private fun clearSavedGlassesAfterOwnerLoss(reason: String) {
2034
- Bridge.log("LIVE: Owner loss ($reason) — clearing saved glasses (not generic GATT)")
2035
- pairingYieldAwaitingReclaim = false
2036
- pairingYieldActive = false
2037
- pairingYieldEndRunnable?.let { handler.removeCallbacks(it) }
2038
- 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
2039
2191
  try {
2040
- forget()
2041
- } catch (e: Exception) {
2042
- 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}")
2043
2195
  }
2044
- DeviceStore.apply("bluetooth", "default_wearable", "")
2045
- DeviceStore.apply("bluetooth", "device_name", "")
2046
- DeviceStore.apply("bluetooth", "device_address", "")
2047
- Bridge.saveSetting("default_wearable", "")
2048
- Bridge.saveSetting("device_name", "")
2049
- Bridge.saveSetting("device_address", "")
2050
- Bridge.sendTypedMessage("owner_replaced", mapOf("reason" to reason))
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
2322
+ }
2323
+ applyPairingTransition(transition)
2051
2324
  }
2052
2325
 
2053
2326
  /** Handle reconnection with exponential backoff */
@@ -2068,9 +2341,12 @@ class MentraLive : SGCManager() {
2068
2341
  return
2069
2342
  }
2070
2343
 
2071
- if (pairingYieldActive) {
2072
- 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
+ )
2073
2348
  isReconnecting = false
2349
+ if (MentraLivePairingStateStore.isPaused) startPairingWatchScan()
2074
2350
  return
2075
2351
  }
2076
2352
 
@@ -2157,20 +2433,23 @@ class MentraLive : SGCManager() {
2157
2433
  )
2158
2434
  return
2159
2435
  }
2160
- if (pairingYieldActive) {
2436
+ if (!MentraLivePairingStateStore.allowsAutomaticReconnect) {
2161
2437
  isReconnecting = false
2162
2438
  Bridge.log(
2163
- "LIVE: 🔌 RECONNECT ABORTED - pairing yield active (glasses in pairing mode)"
2439
+ "LIVE: 🔌 RECONNECT ABORTED - pairing state ${MentraLivePairingStateStore.describe()}"
2164
2440
  )
2165
2441
  return
2166
2442
  }
2167
2443
  if (!isConnected && !isConnecting && !isKilled) {
2168
2444
  // Prefer saved MAC for direct GATT connect (faster and more reliable
2169
2445
  // than scanning).
2170
- // 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.
2171
2449
  val lastDeviceAddress =
2172
2450
  selectedConnectionAddress()
2173
2451
  if (lastDeviceAddress != null &&
2452
+ !MentraLivePairingStateStore.awaitingTakeoverCheck &&
2174
2453
  !lastDeviceAddress.isEmpty() &&
2175
2454
  bluetoothAdapter != null
2176
2455
  ) {
@@ -2331,6 +2610,9 @@ class MentraLive : SGCManager() {
2331
2610
  "LIVE: 🔌 🔗 BLE GATT link connected - validating services/characteristics..."
2332
2611
  )
2333
2612
  markPairingTiming("gatt_connected")
2613
+ lastAutoReconnectLinkAt =
2614
+ if (isExplicitPairingAttempt()) null
2615
+ else SystemClock.elapsedRealtime()
2334
2616
  isConnecting = false
2335
2617
  isConnected = true
2336
2618
  connectedDevice = gatt.device
@@ -2368,6 +2650,8 @@ class MentraLive : SGCManager() {
2368
2650
  bondingRetryCount = 0
2369
2651
  ctkdInitiatedThisGattSession = false
2370
2652
  classicAudioServiceDiscovery.cancel()
2653
+ // A new GATT link has not heard the glasses' owner commit yet.
2654
+ resetSecurePairingConfirmation()
2371
2655
  Bridge.log(
2372
2656
  "LIVE: CTKD: BLE GATT up - deferring Classic/A2DP until notifications ready"
2373
2657
  )
@@ -2415,6 +2699,7 @@ class MentraLive : SGCManager() {
2415
2699
 
2416
2700
  // Reset audio pairing flags
2417
2701
  glassesReadyReceived = false
2702
+ resetSecurePairingConfirmation()
2418
2703
  ctkdInitiatedThisGattSession = false
2419
2704
  classicAudioServiceDiscovery.cancel()
2420
2705
  audioConnected = false
@@ -2477,6 +2762,7 @@ class MentraLive : SGCManager() {
2477
2762
  streamControlVersion = 0
2478
2763
  readinessCompletedThisBleSession = false
2479
2764
  glassesReadyReceived = false
2765
+ resetSecurePairingConfirmation()
2480
2766
  audioConnected = false
2481
2767
  ctkdInitiatedThisGattSession = false
2482
2768
  classicAudioServiceDiscovery.cancel()
@@ -2503,17 +2789,22 @@ class MentraLive : SGCManager() {
2503
2789
  // Clean up resources
2504
2790
  closeGattQuietly(false)
2505
2791
 
2506
- // Auth/not-owner after pairing yield — not a generic RF blip.
2507
- // GATT 8 / 0x08 is connection timeout; a reclaim RF timeout must
2508
- // not wipe the saved owner.
2509
- if (pairingYieldAwaitingReclaim &&
2510
- (status == 5 ||
2511
- status == 15 ||
2512
- status == 0x05 ||
2513
- 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
+ )
2514
2802
  ) {
2515
- clearSavedGlassesAfterOwnerLoss("gatt_auth_status_$status")
2516
- return
2803
+ if (recordAuthRejection("gatt_auth_status_$status")) return
2804
+ } else {
2805
+ MentraLivePairingStateStore.update("connect_failed_$status") {
2806
+ it.onConnectAttemptFailed()
2807
+ }
2517
2808
  }
2518
2809
 
2519
2810
  // Attempt reconnection if not killed
@@ -2978,6 +3269,7 @@ class MentraLive : SGCManager() {
2978
3269
  Bridge.log("LIVE: Starting send queue and readiness check loop")
2979
3270
  startSignalStrengthPolling()
2980
3271
  handler.post(processSendQueueRunnable!!)
3272
+ sendPairingSessionMessages("gatt_ready")
2981
3273
  startReadinessCheckLoop()
2982
3274
  // Classic/A2DP after BLE is armed — avoids GATT 19 when dual-mode stacks
2983
3275
  // collide during service discovery / descriptor writes.
@@ -4173,23 +4465,93 @@ class MentraLive : SGCManager() {
4173
4465
  // Process heartbeat pong response
4174
4466
  Bridge.log("LIVE: Received pong response - connection healthy")
4175
4467
  "entering_pairing_mode" -> {
4176
- val windowMs = json.optLong("window_ms", 120_000L).coerceIn(5_000L, 180_000L)
4177
- Bridge.log("LIVE: Glasses entering pairing mode — yield ${windowMs}ms (no forget)")
4178
- 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
+ )
4179
4488
  val body = HashMap<String, Any>()
4180
4489
  body["window_ms"] = windowMs
4490
+ if (windowId != null) body["window_id"] = windowId
4181
4491
  body["reason"] = json.optString("reason", "user_gesture")
4492
+ body["owner_retained"] = ownerRetained
4182
4493
  Bridge.sendTypedMessage("entering_pairing_mode", body)
4183
- }
4184
- "pairing_info" ->
4185
- Bridge.sendPairingInfo(
4186
- json.optBoolean("had_previous_bond", false),
4187
- jsonNullableString(json, "pairing_code"),
4188
- json.optBoolean("classic_bond_ready", false),
4189
- // Legacy firmware that omits this field is not secure-capable.
4190
- json.optBoolean("secure_pairing_capable", false),
4191
- 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"
4192
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
+ }
4193
4555
  "imu_response",
4194
4556
  "imu_stream_response",
4195
4557
  "imu_gesture_response",
@@ -4440,6 +4802,16 @@ class MentraLive : SGCManager() {
4440
4802
  if (json.has("bytes_downloaded")) json.optLong("bytes_downloaded", 0) else null
4441
4803
  )
4442
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
+ }
4443
4815
  "ota_progress" -> {
4444
4816
  // Legacy glasses firmware: map to unified ota_status so JS has a single path
4445
4817
  // (Mantle / progress UI).
@@ -4627,8 +4999,8 @@ class MentraLive : SGCManager() {
4627
4999
  }
4628
5000
  "glasses_ready" -> {
4629
5001
  // Glasses SOC has booted and is ready for communication
4630
- if (pairingYieldActive && !isConnected) {
4631
- Bridge.log("LIVE: Ignoring stale glasses_ready during pairing yield")
5002
+ if (!isConnected) {
5003
+ Bridge.log("LIVE: Ignoring stale glasses_ready without a link")
4632
5004
  return
4633
5005
  }
4634
5006
  val sid = json.optString("sid", "").takeIf { it.isNotEmpty() }
@@ -4645,10 +5017,6 @@ class MentraLive : SGCManager() {
4645
5017
  }
4646
5018
  readyGlassesSessionId = sid
4647
5019
  Bridge.log("LIVE: 🎉 Received glasses_ready message - SOC is booted and ready!")
4648
- pairingYieldAwaitingReclaim = false
4649
- pairingYieldActive = false
4650
- pairingYieldEndRunnable?.let { handler.removeCallbacks(it) }
4651
- pairingYieldEndRunnable = null
4652
5020
  markPairingTiming(
4653
5021
  "glasses_ready",
4654
5022
  "audioConnected=$audioConnected queueSize=${sendQueue.size}"
@@ -4680,6 +5048,7 @@ class MentraLive : SGCManager() {
4680
5048
  // Set the ready flag to stop any future readiness checks
4681
5049
  glassesReady = true
4682
5050
  glassesReadyReceived = true
5051
+ armSecureFirmwareRefresh()
4683
5052
  // Match iOS MentraLive.handleGlassesReady: BLE/SOC ready is enough for
4684
5053
  // fullyBooted + CONNECTED. CTKD Classic bonding continues in the background
4685
5054
  // for SCO/A2DP and must not gate the pairing success UI (~9s on some phones).
@@ -4802,8 +5171,42 @@ class MentraLive : SGCManager() {
4802
5171
  Bridge.log("LIVE: ⚠️ glasses_ready: mic restore threw: " + t)
4803
5172
  }
4804
5173
 
4805
- // Pairing UI / DeviceManager.handleDeviceReady gate on fullyBooted.
4806
- // 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()
4807
5210
  endPairingTiming(
4808
5211
  "fully_connected",
4809
5212
  "via=glasses_ready audioConnected=$audioConnected queueSize=${sendQueue.size}"
@@ -4861,6 +5264,7 @@ class MentraLive : SGCManager() {
4861
5264
  )
4862
5265
  DeviceStore.apply("glasses", "firmwareVersion", firmwareVersionLegacy)
4863
5266
  btMacAddressLegacy.trim().takeIf { it.isNotEmpty() }?.let {
5267
+ wifiAdbPeerIdentity = bleSessionGeneration.get() to it
4864
5268
  DeviceStore.apply("glasses", "bluetoothMacAddress", it)
4865
5269
  }
4866
5270
  serialNumberLegacy.trim().takeIf { it.isNotEmpty() }?.let {
@@ -5133,6 +5537,7 @@ class MentraLive : SGCManager() {
5133
5537
  )
5134
5538
  }
5135
5539
  (fields["bt_mac_address"] as? String)?.trim()?.takeIf { it.isNotEmpty() }?.let {
5540
+ wifiAdbPeerIdentity = bleSessionGeneration.get() to it
5136
5541
  DeviceStore.apply("glasses", "bluetoothMacAddress", it)
5137
5542
  }
5138
5543
  (fields["wifi_mac_address"] as? String)?.trim()?.takeIf { it.isNotEmpty() }?.let {
@@ -5679,6 +6084,7 @@ class MentraLive : SGCManager() {
5679
6084
  updateConnectionState(ConnTypes.DISCONNECTED)
5680
6085
  glassesReady = false
5681
6086
  glassesReadyReceived = false
6087
+ resetSecurePairingConfirmation()
5682
6088
  glassesSessionId = null
5683
6089
  streamControlVersion = 0
5684
6090
  readinessCompletedThisBleSession = false
@@ -6127,6 +6533,30 @@ class MentraLive : SGCManager() {
6127
6533
  }
6128
6534
  }
6129
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
+
6130
6560
  override fun sendIncidentId(incidentId: String, apiBaseUrl: String?) {
6131
6561
  if (!isConnected || bluetoothGatt == null || txCharacteristic == null) {
6132
6562
  throw BluetoothSdkException(
@@ -6146,10 +6576,9 @@ class MentraLive : SGCManager() {
6146
6576
  }
6147
6577
  val bKey = IncidentLogBleRelayNaming.bleFileBaseName(incidentId, 'B')
6148
6578
  val lKey = IncidentLogBleRelayNaming.bleFileBaseName(incidentId, 'L')
6149
- bleIncidentLogRelays[bKey] =
6150
- BleIncidentLogRelay(bKey, incidentId, base, BleIncidentLogKind.FIRMWARE)
6151
- bleIncidentLogRelays[lKey] =
6152
- 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)
6153
6582
 
6154
6583
  val auth = JSONObject()
6155
6584
  auth.put("type", "auth_token")
@@ -6164,8 +6593,8 @@ class MentraLive : SGCManager() {
6164
6593
  sessionGeneration != bleSessionGeneration.get() ||
6165
6594
  !isConnected || bluetoothGatt == null || txCharacteristic == null ||
6166
6595
  !sendJson(json, true, true, sessionGeneration) || sessionGeneration != bleSessionGeneration.get()) {
6167
- bleIncidentLogRelays.remove(bKey)
6168
- bleIncidentLogRelays.remove(lKey)
6596
+ bleIncidentLogRelays.remove(bKey, bRelay)
6597
+ bleIncidentLogRelays.remove(lKey, lRelay)
6169
6598
  throw BluetoothSdkException("incident_dispatch_failed", "Could not queue the glasses incident-log request.")
6170
6599
  }
6171
6600
  Bridge.log(
@@ -6182,6 +6611,27 @@ class MentraLive : SGCManager() {
6182
6611
  }
6183
6612
  }
6184
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
+
6185
6635
  /** Query gallery status from the glasses */
6186
6636
  override fun queryGalleryStatus() {
6187
6637
  try {
@@ -6604,8 +7054,19 @@ class MentraLive : SGCManager() {
6604
7054
 
6605
7055
  override fun connectById(id: String) {
6606
7056
  if (postGattLifecycle { connectById(id) }) return
6607
- if (pairingYieldActive) {
6608
- 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
+ }
6609
7070
  return
6610
7071
  }
6611
7072
  reconnectGeneration++
@@ -6729,8 +7190,10 @@ class MentraLive : SGCManager() {
6729
7190
 
6730
7191
  fun connectToSmartGlasses() {
6731
7192
  if (postGattLifecycle { connectToSmartGlasses() }) return
6732
- if (pairingYieldActive) {
6733
- Bridge.log("LIVE: connectToSmartGlasses blocked — pairing yield active")
7193
+ if (automaticConnectBlocked()) {
7194
+ Bridge.log(
7195
+ "LIVE: connectToSmartGlasses blocked — pairing state ${MentraLivePairingStateStore.describe()}"
7196
+ )
6734
7197
  return
6735
7198
  }
6736
7199
  Bridge.log("LIVE: Connecting to Mentra Live glasses")
@@ -7311,6 +7774,12 @@ class MentraLive : SGCManager() {
7311
7774
  }
7312
7775
  bondingRetryCount =
7313
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
+ }
7314
7783
  // Bond != audio profile. Explicitly open A2DP
7315
7784
  // after createBond() completes (already-bonded
7316
7785
  // path does this at GATT connect).
@@ -7327,10 +7796,34 @@ class MentraLive : SGCManager() {
7327
7796
  "fullyBooted"
7328
7797
  ) as? Boolean
7329
7798
  ?: false
7330
- 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) {
7331
7823
  Bridge.log(
7332
7824
  "LIVE: Audio: CTKD bonded; catching up fullyBooted (glasses_ready already received)"
7333
7825
  )
7826
+ awaitingSecurePairingConfirmation = false
7334
7827
  endPairingTiming(
7335
7828
  "fully_connected",
7336
7829
  "via=ctkd_bond+glasses_ready queueSize=${sendQueue.size}"
@@ -7357,6 +7850,22 @@ class MentraLive : SGCManager() {
7357
7850
  Bridge.log(
7358
7851
  "LIVE: CTKD: ❌ Bonding failed or removed for device"
7359
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
+ }
7360
7869
  markPairingTiming(
7361
7870
  "ctkd_bond_none",
7362
7871
  "prev=$previousBondState queueSize=${sendQueue.size}"
@@ -7372,7 +7881,20 @@ class MentraLive : SGCManager() {
7372
7881
  classicAudioConnectionTracker.clear(device.address)
7373
7882
  }
7374
7883
  audioConnected = false
7375
- 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) {
7376
7898
  // User cancelled or bonding failed - retry up to
7377
7899
  // MAX_BONDING_RETRIES times
7378
7900
  bondingRetryCount++
@@ -7610,6 +8132,16 @@ class MentraLive : SGCManager() {
7610
8132
  if (ctkdInitiatedThisGattSession) {
7611
8133
  return
7612
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
+ }
7613
8145
  ctkdInitiatedThisGattSession = true
7614
8146
  Bridge.log(
7615
8147
  "LIVE: CTKD: BLE ready - initiating CTKD bonding for BT Classic (bondState=" +
@@ -7691,7 +8223,7 @@ class MentraLive : SGCManager() {
7691
8223
  }
7692
8224
 
7693
8225
  private fun canConnectClassicAudio(device: BluetoothDevice): Boolean =
7694
- !isKilled && !pairingYieldActive && isConnected && notificationsEnabled &&
8226
+ !isKilled && !automaticConnectBlocked() && isConnected && notificationsEnabled &&
7695
8227
  ctkdInitiatedThisGattSession && connectedDevice?.address == device.address &&
7696
8228
  device.bondState == BluetoothDevice.BOND_BONDED
7697
8229
 
@@ -7806,6 +8338,194 @@ class MentraLive : SGCManager() {
7806
8338
  )
7807
8339
  }
7808
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
+
7809
8529
  /** Helper to mark audio as connected and notify */
7810
8530
  private fun markAudioConnected(device: BluetoothDevice) {
7811
8531
  if (isKilled) {
@@ -7820,6 +8540,24 @@ class MentraLive : SGCManager() {
7820
8540
  Bridge.sendAudioConnected(safeDeviceName(device))
7821
8541
  }
7822
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()
7823
8561
  Bridge.log(
7824
8562
  "LIVE: A2DP: Both audio and glasses_ready confirmed - marking as fully connected"
7825
8563
  )
@@ -8021,10 +8759,8 @@ class MentraLive : SGCManager() {
8021
8759
  isKilled = true
8022
8760
  classicAudioServiceDiscovery.cancel()
8023
8761
  explicitConnectByName = false
8024
- pairingYieldActive = false
8025
- pairingYieldAwaitingReclaim = false
8026
- pairingYieldEndRunnable?.let { handler.removeCallbacks(it) }
8027
- pairingYieldEndRunnable = null
8762
+ // The pairing state itself lives on in MentraLivePairingStateStore.
8763
+ cancelPairingPauseTimer()
8028
8764
  unpairFlushRunnable?.let { handler.removeCallbacks(it) }
8029
8765
  unpairFlushRunnable = null
8030
8766
  unpairFlushPending = false
@@ -8120,6 +8856,7 @@ class MentraLive : SGCManager() {
8120
8856
  isReconnecting = false
8121
8857
  glassesReady = false
8122
8858
  glassesReadyReceived = false
8859
+ resetSecurePairingConfirmation()
8123
8860
  audioConnected = false
8124
8861
  ctkdInitiatedThisGattSession = false
8125
8862
  classicAudioServiceDiscovery.cancel()
@@ -10110,6 +10847,20 @@ class MentraLive : SGCManager() {
10110
10847
  }
10111
10848
  }
10112
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
+
10113
10864
  override fun sendWifiAdbState(enabled: Boolean) {
10114
10865
  Bridge.log("LIVE: 🔧 Sending Wi-Fi ADB state to glasses - enabled: " + enabled)
10115
10866
  try {
@@ -10538,6 +11289,15 @@ class MentraLive : SGCManager() {
10538
11289
  // Transfer is complete - process successfully
10539
11290
  Bridge.log("LIVE: 📦 File transfer complete: " + packetInfo.fileName)
10540
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
+
10541
11301
  // Assemble and save the file
10542
11302
  val fileData = session.assembleFile()
10543
11303
  if (fileData != null) {
@@ -10754,6 +11514,13 @@ class MentraLive : SGCManager() {
10754
11514
  success,
10755
11515
  message ->
10756
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
+ }
10757
11524
  if (success) {
10758
11525
  Bridge.log(
10759
11526
  "LIVE: ✅ Incident log BLE relay uploaded (" +
@@ -10761,7 +11528,6 @@ class MentraLive : SGCManager() {
10761
11528
  "): " +
10762
11529
  relay.incidentId
10763
11530
  )
10764
- bleIncidentLogRelays.remove(relay.fileBaseKey)
10765
11531
  } else {
10766
11532
  Log.e(
10767
11533
  TAG,
@@ -10774,6 +11540,11 @@ class MentraLive : SGCManager() {
10774
11540
  relay.session = null
10775
11541
  }
10776
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
+ }
10777
11548
  }
10778
11549
  }
10779
11550
  }
@@ -10930,20 +11701,19 @@ class MentraLive : SGCManager() {
10930
11701
  }
10931
11702
 
10932
11703
  /**
10933
- * Get the core authentication token. Reads from DeviceStore first (synced from JS via
10934
- * 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.
10935
11707
  */
10936
11708
  private fun getCoreToken(): String {
10937
11709
  val fromStore = DeviceStore.get("bluetooth", "core_token")
10938
- if (fromStore is String) {
10939
- val token = fromStore
10940
- if (token != null && !token.isEmpty()) {
10941
- return token
10942
- }
10943
- }
10944
- val prefs = context!!.getSharedPreferences(AUTH_PREFS_NAME, Context.MODE_PRIVATE)
10945
- val fromPrefs = prefs.getString(KEY_CORE_TOKEN, "")
10946
- 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()
10947
11717
  }
10948
11718
 
10949
11719
  /** Send BLE transfer completion notification */