@mentra/bluetooth-sdk 3.4.0-dev.1059 → 3.4.0-dev.1061

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 (41) hide show
  1. package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
  2. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +9 -0
  3. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +7 -0
  4. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +5 -5
  5. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +22 -0
  6. package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
  7. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +85 -7
  8. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
  9. package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
  10. package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
  11. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +175 -0
  12. package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
  13. package/build/BluetoothSdk.types.d.ts +47 -0
  14. package/build/BluetoothSdk.types.d.ts.map +1 -1
  15. package/build/BluetoothSdk.types.js.map +1 -1
  16. package/build/_private/BluetoothSdkModule.d.ts +6 -0
  17. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  18. package/build/_private/BluetoothSdkModule.js +1 -0
  19. package/build/_private/BluetoothSdkModule.js.map +1 -1
  20. package/build/generated/releaseMetadata.js +5 -5
  21. package/build/generated/releaseMetadata.js.map +1 -1
  22. package/build/index.d.ts +1 -1
  23. package/build/index.d.ts.map +1 -1
  24. package/build/index.js +1 -0
  25. package/build/index.js.map +1 -1
  26. package/ios/BluetoothSdkModule.swift +8 -0
  27. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  28. package/ios/Source/BluetoothSdkDefaults.swift +1 -1
  29. package/ios/Source/DeviceManager.swift +7 -0
  30. package/ios/Source/GeneratedReleaseMetadata.swift +5 -5
  31. package/ios/Source/MentraBluetoothSDK.swift +25 -0
  32. package/ios/Source/events/BluetoothEvents.swift +41 -0
  33. package/ios/Source/sgcs/MentraLive.swift +88 -12
  34. package/ios/Source/sgcs/SGCManager.swift +6 -0
  35. package/ios/Tests/BesCrashReportTests.swift +142 -0
  36. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  37. package/package.json +2 -2
  38. package/src/BluetoothSdk.types.ts +51 -0
  39. package/src/_private/BluetoothSdkModule.ts +10 -0
  40. package/src/generated/releaseMetadata.ts +5 -5
  41. package/src/index.ts +5 -0
@@ -143,6 +143,44 @@ public struct OtaStatusEvent: CustomStringConvertible {
143
143
  }
144
144
  }
145
145
 
146
+ /// Mentra Live stored a BES crash incident; `values` is the glasses message unchanged.
147
+ public struct BesCrashDetectedEvent: CustomStringConvertible {
148
+ public let values: [String: Any]
149
+
150
+ public init(values: [String: Any]) {
151
+ var values = values
152
+ // JavaScript sees null, not undefined, before the incident has a report.
153
+ if stringValue(values, "reportId")?.isEmpty ?? true {
154
+ values["reportId"] = NSNull()
155
+ }
156
+ self.values = values
157
+ }
158
+
159
+ public var incidentKey: String {
160
+ stringValue(values, "incidentKey") ?? ""
161
+ }
162
+
163
+ public var reason: String {
164
+ stringValue(values, "reason") ?? ""
165
+ }
166
+
167
+ public var state: String {
168
+ stringValue(values, "state") ?? ""
169
+ }
170
+
171
+ public var reportId: String? {
172
+ stringValue(values, "reportId")
173
+ }
174
+
175
+ public var summary: [String: Any] {
176
+ values["summary"] as? [String: Any] ?? [:]
177
+ }
178
+
179
+ public var description: String {
180
+ "BesCrashDetectedEvent(incidentKey: \(incidentKey), state: \(state))"
181
+ }
182
+ }
183
+
146
184
  public struct OtaQueryResult: CustomStringConvertible {
147
185
  public let values: [String: Any]
148
186
 
@@ -273,6 +311,7 @@ public enum BluetoothEvent: CustomStringConvertible {
273
311
  case keepAliveAck(KeepAliveAckEvent)
274
312
  case otaStartAck(OtaStartAckEvent)
275
313
  case otaStatus(OtaStatusEvent)
314
+ case besCrashDetected(BesCrashDetectedEvent)
276
315
  case settingsAck(SettingsAckEvent)
277
316
  case versionInfo(VersionInfoResult)
278
317
  case localTranscription(LocalTranscriptionEvent)
@@ -316,6 +355,8 @@ public enum BluetoothEvent: CustomStringConvertible {
316
355
  event.description
317
356
  case let .otaStatus(event):
318
357
  event.description
358
+ case let .besCrashDetected(event):
359
+ event.description
319
360
  case let .settingsAck(event):
320
361
  event.description
321
362
  case let .versionInfo(event):
@@ -696,25 +696,28 @@ private struct BlePhotoTransfer {
696
696
  }
697
697
  }
698
698
 
699
- private enum BleIncidentLogRelayKind {
699
+ enum BleIncidentLogRelayKind {
700
700
  case firmware
701
701
  case logcat
702
702
  }
703
703
 
704
- private final class BleIncidentLogRelayEntry {
704
+ final class BleIncidentLogRelayEntry {
705
705
  let fileBaseKey: String
706
706
  let incidentId: String
707
707
  let apiBaseUrl: String
708
708
  let kind: BleIncidentLogRelayKind
709
+ let reservedAt: TimeInterval
709
710
  var session: MentraLiveFileTransferSession?
710
711
 
711
712
  init(
712
- fileBaseKey: String, incidentId: String, apiBaseUrl: String, kind: BleIncidentLogRelayKind
713
+ fileBaseKey: String, incidentId: String, apiBaseUrl: String, kind: BleIncidentLogRelayKind,
714
+ reservedAt: TimeInterval
713
715
  ) {
714
716
  self.fileBaseKey = fileBaseKey
715
717
  self.incidentId = incidentId
716
718
  self.apiBaseUrl = apiBaseUrl
717
719
  self.kind = kind
720
+ self.reservedAt = reservedAt
718
721
  }
719
722
  }
720
723
 
@@ -1643,7 +1646,11 @@ class MentraLive: NSObject, SGCManager {
1643
1646
  private var fileWriteCharacteristic: CBCharacteristic?
1644
1647
  private var activeFileTransfers = [String: MentraLiveFileTransferSession]()
1645
1648
  private var blePhotoTransfers = [String: BlePhotoTransfer]()
1646
- private var bleIncidentLogRelays = [String: BleIncidentLogRelayEntry]()
1649
+ private(set) var bleIncidentLogRelays = [String: BleIncidentLogRelayEntry]()
1650
+ // Longer than the glasses' bounded relay of one report (BES logs, two file transfers, the
1651
+ // phone POST), so an unreleased name cannot be reused while its report is in flight.
1652
+ static let incidentRelayOwnershipSeconds: TimeInterval = 600
1653
+ var incidentRelayClock: () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }
1647
1654
  private var l2capFileChannel: MentraLiveL2capChannel?
1648
1655
  private var l2capFileChannelId: UUID?
1649
1656
  private var l2capFileChannelOpening = false
@@ -3764,6 +3771,11 @@ class MentraLive: NSObject, SGCManager {
3764
3771
  Bridge.log("LIVE: 📱 Received ota_start_ack from glasses")
3765
3772
  Bridge.sendOtaStartAck()
3766
3773
 
3774
+ case "bes_crash_detected", "bes_crash_reported_ack":
3775
+ let ok = json["ok"].map { "\($0)" } ?? "-"
3776
+ Bridge.log("LIVE: \(type) incidentKey=\(json["incidentKey"] as? String ?? "") state=\(json["state"] as? String ?? "-") ok=\(ok)")
3777
+ Bridge.sendTypedMessage(type, body: json)
3778
+
3767
3779
  case "ota_status":
3768
3780
  // Short keys (sid/ts/cs/st/sq/sp/op/err) are used by new firmware to keep BLE payload small.
3769
3781
  // Verbose keys (session_id/total_steps/…) are the fallback for older firmware.
@@ -4505,12 +4517,14 @@ class MentraLive: NSObject, SGCManager {
4505
4517
  }
4506
4518
  let bKey = MentraLive.incidentBleFileBase(incidentId: incidentId, prefix: "B")
4507
4519
  let lKey = MentraLive.incidentBleFileBase(incidentId: incidentId, prefix: "L")
4508
- bleIncidentLogRelays[bKey] = BleIncidentLogRelayEntry(
4509
- fileBaseKey: bKey, incidentId: incidentId, apiBaseUrl: base, kind: .firmware
4520
+ let now = incidentRelayClock()
4521
+ let bRelay = BleIncidentLogRelayEntry(
4522
+ fileBaseKey: bKey, incidentId: incidentId, apiBaseUrl: base, kind: .firmware, reservedAt: now
4510
4523
  )
4511
- bleIncidentLogRelays[lKey] = BleIncidentLogRelayEntry(
4512
- fileBaseKey: lKey, incidentId: incidentId, apiBaseUrl: base, kind: .logcat
4524
+ let lRelay = BleIncidentLogRelayEntry(
4525
+ fileBaseKey: lKey, incidentId: incidentId, apiBaseUrl: base, kind: .logcat, reservedAt: now
4513
4526
  )
4527
+ try reserveIncidentRelays([bRelay, lRelay], now: now)
4514
4528
 
4515
4529
  let auth: [String: Any] = [
4516
4530
  "type": "auth_token", "coreToken": coreToken,
@@ -4521,13 +4535,56 @@ class MentraLive: NSObject, SGCManager {
4521
4535
  sendJson(["type": "upload_incident_logs", "incidentId": incidentId, "apiBaseUrl": base],
4522
4536
  wakeUp: true, requireAck: true, bridgeLogging: true)
4523
4537
  else {
4524
- bleIncidentLogRelays.removeValue(forKey: bKey)
4525
- bleIncidentLogRelays.removeValue(forKey: lKey)
4538
+ releaseIncidentRelay(bRelay)
4539
+ releaseIncidentRelay(lRelay)
4526
4540
  throw BluetoothSdkError(code: "incident_dispatch_failed", message: "Could not queue the glasses incident-log request.")
4527
4541
  }
4528
4542
  Bridge.log("LIVE: Queued incidentId to glasses for log upload: \(incidentId) (BLE relay \(bKey), \(lKey))")
4529
4543
  }
4530
4544
 
4545
+ /// The 16-character relay file names keep only 15 characters of the report id, so two reports
4546
+ /// can share them. A received file goes to the report registered under its name; refuse a
4547
+ /// second report until the owner's Cloud POST is confirmed or its ownership expires.
4548
+ private func reserveIncidentRelays(_ relays: [BleIncidentLogRelayEntry], now: TimeInterval) throws {
4549
+ for relay in relays {
4550
+ if let owner = bleIncidentLogRelays[relay.fileBaseKey],
4551
+ owner.incidentId != relay.incidentId,
4552
+ now - owner.reservedAt < MentraLive.incidentRelayOwnershipSeconds
4553
+ {
4554
+ throw BluetoothSdkError(
4555
+ code: "incident_relay_busy",
4556
+ message: "BLE relay \(relay.fileBaseKey) is still owned by report \(owner.incidentId)."
4557
+ )
4558
+ }
4559
+ }
4560
+ for relay in relays {
4561
+ bleIncidentLogRelays[relay.fileBaseKey] = relay
4562
+ }
4563
+ }
4564
+
4565
+ private func releaseIncidentRelay(_ relay: BleIncidentLogRelayEntry) {
4566
+ if bleIncidentLogRelays[relay.fileBaseKey] === relay {
4567
+ bleIncidentLogRelays.removeValue(forKey: relay.fileBaseKey)
4568
+ }
4569
+ }
4570
+
4571
+ func sendBesCrashReported(incidentKey: String, reportId: String) throws {
4572
+ guard incidentLogTransportReady else {
4573
+ throw BluetoothSdkError(code: "glasses_not_connected", message: "Cannot report the BES crash because the glasses BLE link is not ready.")
4574
+ }
4575
+ guard sendJson(["type": "bes_crash_reported", "incidentKey": incidentKey, "reportId": reportId],
4576
+ wakeUp: true, requireAck: true, bridgeLogging: true)
4577
+ else {
4578
+ throw BluetoothSdkError(code: "bes_crash_dispatch_failed", message: "Could not queue bes_crash_reported to the glasses.")
4579
+ }
4580
+ Bridge.log("LIVE: Queued bes_crash_reported incidentKey=\(incidentKey) reportId=\(reportId)")
4581
+ }
4582
+
4583
+ static func isIncidentRelayFileName(_ fileName: String) -> Bool {
4584
+ guard fileName.count == 16, let first = fileName.first, first == "B" || first == "L" else { return false }
4585
+ return fileName.dropFirst().allSatisfy { ("a" ... "z").contains($0) || ("0" ... "9").contains($0) || $0 == "_" }
4586
+ }
4587
+
4531
4588
  private static func incidentBleFileBase(incidentId: String, prefix: Character) -> String {
4532
4589
  var compact = incidentId.replacingOccurrences(of: "-", with: "").lowercased()
4533
4590
  if compact.count < 15 {
@@ -5355,6 +5412,15 @@ class MentraLive: NSObject, SGCManager {
5355
5412
  if sess.isComplete {
5356
5413
  Bridge.log("LIVE: 📦 File transfer complete: \(packetInfo.fileName)")
5357
5414
 
5415
+ if Self.isIncidentRelayFileName(packetInfo.fileName) {
5416
+ // No relay registered (e.g. the app restarted mid-relay): nothing reached
5417
+ // Cloud, so success would make the glasses mark the incident uploaded.
5418
+ Bridge.log("LIVE: Incident log relay without a registered report: \(packetInfo.fileName)")
5419
+ sendTransferCompleteConfirmation(fileName: packetInfo.fileName, success: false)
5420
+ activeFileTransfers.removeValue(forKey: packetInfo.fileName)
5421
+ return
5422
+ }
5423
+
5358
5424
  if let fileData = sess.assembleFile() {
5359
5425
  saveReceivedFile(
5360
5426
  fileName: packetInfo.fileName, fileData: fileData,
@@ -5456,7 +5522,7 @@ class MentraLive: NSObject, SGCManager {
5456
5522
  ]
5457
5523
  }
5458
5524
 
5459
- private func uploadBleIncidentLogRelay(
5525
+ func uploadBleIncidentLogRelay(
5460
5526
  relay: BleIncidentLogRelayEntry, fileName: String, data: Data
5461
5527
  ) {
5462
5528
  let token = DeviceStore.shared.get("bluetooth", "core_token") as? String ?? ""
@@ -5507,14 +5573,24 @@ class MentraLive: NSObject, SGCManager {
5507
5573
  statusCode = nil
5508
5574
  }
5509
5575
  DispatchQueue.main.async {
5576
+ // A different report now owns this name (it was admitted after our owner finished),
5577
+ // so a completion here would mark ITS file done. Drop the stale callback.
5578
+ if let owner = self.bleIncidentLogRelays[relay.fileBaseKey], owner.incidentId != relay.incidentId {
5579
+ Bridge.log("LIVE: Dropping stale incident relay callback for \(relay.fileBaseKey)")
5580
+ return
5581
+ }
5510
5582
  if ok {
5511
5583
  Bridge.log("LIVE: ✅ Incident log BLE relay uploaded (\(relay.kind))")
5512
- self.bleIncidentLogRelays.removeValue(forKey: relay.fileBaseKey)
5513
5584
  } else if let existing = self.bleIncidentLogRelays[relay.fileBaseKey] {
5514
5585
  // Keep relay entry for glasses retry after transfer_complete:false.
5515
5586
  existing.session = nil
5516
5587
  }
5517
5588
  self.sendTransferCompleteConfirmation(fileName: fileName, success: ok)
5589
+ // Release only after the glasses' confirmation is queued, so a report that reuses
5590
+ // this name is ordered behind the owner's completion.
5591
+ if ok {
5592
+ self.releaseIncidentRelay(relay)
5593
+ }
5518
5594
  }
5519
5595
  }.resume()
5520
5596
  }
@@ -221,6 +221,8 @@ protocol SGCManager {
221
221
  // MARK: - Incident Reporting
222
222
 
223
223
  func sendIncidentId(_ incidentId: String, apiBaseUrl: String?) throws
224
+ /// Tell the glasses Cloud recorded `reportId` for a BES crash incident (Mentra Live only).
225
+ func sendBesCrashReported(incidentKey: String, reportId: String) throws
224
226
 
225
227
  // MARK: - Gallery
226
228
 
@@ -287,6 +289,10 @@ extension SGCManager {
287
289
 
288
290
  func replayStreamControlReady() {}
289
291
 
292
+ func sendBesCrashReported(incidentKey _: String, reportId _: String) throws {
293
+ throw BluetoothSdkError(code: "unsupported_device", message: "BES crash reporting is not supported on \(type).")
294
+ }
295
+
290
296
  @discardableResult func requestSavedWifiNetworks(requestId _: String, sid _: String) -> Bool {
291
297
  false
292
298
  }
@@ -0,0 +1,142 @@
1
+ @testable import MentraBluetoothSDK
2
+ import XCTest
3
+
4
+ /// Keep native serialization and fragment packing; replace only the radio writes.
5
+ @MainActor
6
+ private final class BesCrashTransport: MentraLive {
7
+ var ready = true
8
+ var writes: [(Data, BleWriteTrace?)] = []
9
+
10
+ override var incidentLogTransportReady: Bool {
11
+ ready
12
+ }
13
+
14
+ override func queueSend(_ data: Data, id _: String, trace: BleWriteTrace?) {
15
+ writes.append((data, trace))
16
+ }
17
+ }
18
+
19
+ @MainActor
20
+ final class BesCrashReportTests: XCTestCase {
21
+ private let keyA = "ML395018B-dump-0000002a-1f2e3d4c"
22
+ private let keyB = "ML395018B-reset-9f3a0c1b2d4e5f60"
23
+
24
+ private func ack(_ key: String, _ reportId: String?, ok: Bool, error: String? = nil) -> [String: Any] {
25
+ var values: [String: Any] = ["type": "bes_crash_reported_ack", "incidentKey": key, "ok": ok]
26
+ if let reportId { values["reportId"] = reportId }
27
+ if let error { values["error"] = error }
28
+ return values
29
+ }
30
+
31
+ private func expectCode(_ code: String, _ body: () async throws -> Void) async -> BluetoothSdkError? {
32
+ do {
33
+ try await body()
34
+ XCTFail("expected \(code)")
35
+ return nil
36
+ } catch {
37
+ let sdkError = error as? BluetoothSdkError
38
+ XCTAssertEqual(sdkError?.code, code)
39
+ return sdkError
40
+ }
41
+ }
42
+
43
+ func testAckDeliveredDuringSendResolves() async throws {
44
+ let waiters = BesCrashReportWaiters()
45
+ try await waiters.report(incidentKey: keyA, reportId: "rep_1", timeoutMs: 1000) {
46
+ XCTAssertEqual(waiters.onAck(ack(keyA, "rep_1", ok: true)), 1)
47
+ }
48
+ }
49
+
50
+ func testConcurrentIncidentsSettleOnlyTheirOwnCall() async throws {
51
+ let waiters = BesCrashReportWaiters()
52
+ let b = Task { @MainActor in
53
+ try await waiters.report(incidentKey: keyB, reportId: "rep_b", timeoutMs: 300) {}
54
+ }
55
+ try await waiters.report(incidentKey: keyA, reportId: "rep_a", timeoutMs: 1000) {
56
+ XCTAssertEqual(waiters.onAck(ack(keyA, "rep_a", ok: true)), 1)
57
+ }
58
+ _ = await expectCode("request_timeout") { try await b.value }
59
+ }
60
+
61
+ func testStaleReportIdIsIgnored() async {
62
+ let waiters = BesCrashReportWaiters()
63
+ _ = await expectCode("request_timeout") {
64
+ try await waiters.report(incidentKey: keyA, reportId: "rep_new", timeoutMs: 200) {
65
+ XCTAssertEqual(waiters.onAck(ack(keyA, "rep_old", ok: true)), 0)
66
+ }
67
+ }
68
+ }
69
+
70
+ func testOkFalseRejectsWithGlassesError() async {
71
+ let waiters = BesCrashReportWaiters()
72
+ let error = await expectCode("bes_crash_report_rejected") {
73
+ try await waiters.report(incidentKey: keyA, reportId: "rep_1", timeoutMs: 1000) {
74
+ XCTAssertEqual(waiters.onAck(ack(keyA, "rep_1", ok: false, error: "unknown_incident")), 1)
75
+ }
76
+ }
77
+ XCTAssertTrue(error?.message.contains("unknown_incident") == true)
78
+ }
79
+
80
+ func testOkTrueWithoutReportIdDoesNotResolve() async {
81
+ let waiters = BesCrashReportWaiters()
82
+ _ = await expectCode("request_timeout") {
83
+ try await waiters.report(incidentKey: keyA, reportId: "rep_1", timeoutMs: 200) {
84
+ XCTAssertEqual(waiters.onAck(ack(keyA, nil, ok: true)), 0)
85
+ }
86
+ }
87
+ }
88
+
89
+ func testDisconnectRejectsPendingCalls() async {
90
+ let waiters = BesCrashReportWaiters()
91
+ _ = await expectCode("glasses_not_connected") {
92
+ try await waiters.report(incidentKey: keyA, reportId: "rep_1", timeoutMs: 5000) {
93
+ waiters.rejectAll(BluetoothSdkError(code: "glasses_not_connected", message: "disconnected"))
94
+ }
95
+ }
96
+ }
97
+
98
+ func testSendFailureLeavesNoWaiter() async {
99
+ let waiters = BesCrashReportWaiters()
100
+ _ = await expectCode("glasses_not_connected") {
101
+ try await waiters.report(incidentKey: keyA, reportId: "rep_1", timeoutMs: 1000) {
102
+ throw BluetoothSdkError(code: "glasses_not_connected", message: "no link")
103
+ }
104
+ }
105
+ XCTAssertEqual(waiters.onAck(ack(keyA, "rep_1", ok: true)), 0)
106
+ }
107
+
108
+ func testCommandIsQueuedWithWakeUp() throws {
109
+ let live = BesCrashTransport()
110
+ try live.sendBesCrashReported(incidentKey: keyA, reportId: "rep_01M4HBVT88DFSN8TYNZ1WTV4PB")
111
+ XCTAssertEqual(live.writes.compactMap { $0.1?.commandType }, ["bes_crash_reported"])
112
+ XCTAssertTrue(live.writes.allSatisfy { $0.1?.wakeup == true })
113
+ let wire = live.writes.map { String(decoding: $0.0, as: UTF8.self) }.joined()
114
+ XCTAssertTrue(wire.contains(keyA))
115
+ XCTAssertTrue(wire.contains("rep_01M4HBVT88DFSN8TYNZ1WTV4PB"))
116
+ }
117
+
118
+ func testCommandRejectsWithoutLink() {
119
+ let live = BesCrashTransport()
120
+ live.ready = false
121
+ XCTAssertThrowsError(try live.sendBesCrashReported(incidentKey: keyA, reportId: "rep_1")) { error in
122
+ XCTAssertEqual((error as? BluetoothSdkError)?.code, "glasses_not_connected")
123
+ }
124
+ XCTAssertTrue(live.writes.isEmpty)
125
+ }
126
+
127
+ func testDetectedEventReportsNullBeforeAReport() {
128
+ let event = BesCrashDetectedEvent(values: ["incidentKey": keyA, "reportId": NSNull(), "summary": ["traceGaps": 0]])
129
+ XCTAssertNil(event.reportId)
130
+ XCTAssertTrue(event.values["reportId"] is NSNull)
131
+ XCTAssertEqual(event.summary["traceGaps"] as? Int, 0)
132
+ XCTAssertEqual(BesCrashDetectedEvent(values: ["reportId": "rep_1"]).reportId, "rep_1")
133
+ }
134
+
135
+ func testRelayFileNamesAreRecognized() {
136
+ XCTAssertTrue(MentraLive.isIncidentRelayFileName("Brep_01m4hbvt88d"))
137
+ XCTAssertTrue(MentraLive.isIncidentRelayFileName("Lrep_01m4hbvt88d"))
138
+ for name in ["I000123456", "I000123456.jpg", "ble_1234567890", "Brep_01m4hbvt88d.json", "Xrep_01m4hbvt88d", ""] {
139
+ XCTAssertFalse(MentraLive.isIncidentRelayFileName(name), name)
140
+ }
141
+ }
142
+ }
@@ -16,6 +16,41 @@ private final class IncidentLogTransport: MentraLive {
16
16
  }
17
17
  }
18
18
 
19
+ /// Stands in for Cloud so the tests observe the report each relayed file is posted to.
20
+ private final class CloudStub: URLProtocol {
21
+ nonisolated(unsafe) static var status = 200
22
+ nonisolated(unsafe) static var requests: [String] = []
23
+
24
+ override class func canInit(with request: URLRequest) -> Bool {
25
+ request.url?.host == "cloud-stub.invalid"
26
+ }
27
+
28
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest {
29
+ request
30
+ }
31
+
32
+ override func startLoading() {
33
+ var body = request.httpBody ?? Data()
34
+ if body.isEmpty, let stream = request.httpBodyStream {
35
+ stream.open()
36
+ var buffer = [UInt8](repeating: 0, count: 4096)
37
+ while stream.hasBytesAvailable {
38
+ let count = stream.read(&buffer, maxLength: buffer.count)
39
+ if count <= 0 { break }
40
+ body.append(buffer, count: count)
41
+ }
42
+ stream.close()
43
+ }
44
+ let path = request.url?.path ?? ""
45
+ DispatchQueue.main.sync { CloudStub.requests.append("\(path) \(String(decoding: body, as: UTF8.self))") }
46
+ let response = HTTPURLResponse(url: request.url!, statusCode: CloudStub.status, httpVersion: nil, headerFields: nil)!
47
+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
48
+ client?.urlProtocolDidFinishLoading(self)
49
+ }
50
+
51
+ override func stopLoading() {}
52
+ }
53
+
19
54
  @MainActor
20
55
  final class IncidentLogDispatchTests: XCTestCase {
21
56
  private let incident = "rep_01M4HBVT88DFSN8TYNZ1WTV4PB"
@@ -98,6 +133,129 @@ final class IncidentLogDispatchTests: XCTestCase {
98
133
  XCTAssertNil(queue.dequeue())
99
134
  }
100
135
 
136
+ func testCollidingReportWaitsForOwnerCloudConfirmationAndNeverReceivesItsEvidence() async throws {
137
+ try await withCloud(status: 200) {
138
+ let live = IncidentLogTransport()
139
+ let name = "Brep_01m4hbvt88d"
140
+ try live.sendIncidentId(incident, apiBaseUrl: cloudBase)
141
+ XCTAssertThrowsError(try live.sendIncidentId(collidingIncident, apiBaseUrl: cloudBase)) { error in
142
+ XCTAssertEqual((error as? BluetoothSdkError)?.code, "incident_relay_busy")
143
+ }
144
+ XCTAssertFalse(wire(live).contains(collidingIncident))
145
+ XCTAssertEqual(live.bleIncidentLogRelays[name]?.incidentId, incident)
146
+ XCTAssertEqual(live.bleIncidentLogRelays["Lrep_01m4hbvt88d"]?.incidentId, incident)
147
+
148
+ let logcat = "Lrep_01m4hbvt88d"
149
+ try await receive(live, name, "owner")
150
+ XCTAssertEqual(CloudStub.requests, ["/api/client/reports/\(incident)/artifacts owner"])
151
+ let confirmation = try XCTUnwrap(sentMessages(live).last { $0.contains("transfer_complete") })
152
+ XCTAssertTrue(confirmation.contains(name) && confirmation.contains("\"success\":true"))
153
+ XCTAssertThrowsError(try live.sendIncidentId(collidingIncident, apiBaseUrl: cloudBase)) { error in
154
+ XCTAssertEqual((error as? BluetoothSdkError)?.code, "incident_relay_busy")
155
+ }
156
+ try await receive(live, logcat, "owner-logcat")
157
+
158
+ try live.sendIncidentId(collidingIncident, apiBaseUrl: cloudBase)
159
+ try await receive(live, name, "second")
160
+ XCTAssertEqual(CloudStub.requests.last, "/api/client/reports/\(collidingIncident)/artifacts second")
161
+ }
162
+ }
163
+
164
+ func testStaleCallbackOfFinishedOwnerCannotConfirmCollidingReportsFile() async throws {
165
+ try await withCloud(status: 200) {
166
+ let live = IncidentLogTransport()
167
+ let name = "Brep_01m4hbvt88d"
168
+ let logcat = "Lrep_01m4hbvt88d"
169
+ try live.sendIncidentId(incident, apiBaseUrl: cloudBase)
170
+ let staleRelay = try XCTUnwrap(live.bleIncidentLogRelays[name])
171
+ try await receive(live, name, "owner")
172
+ try await receive(live, logcat, "owner-logcat")
173
+ try live.sendIncidentId(collidingIncident, apiBaseUrl: cloudBase)
174
+ let confirmationsBefore = sentMessages(live).filter { $0.contains("transfer_complete") }.count
175
+ let requestsBefore = CloudStub.requests.count
176
+
177
+ // A late callback of the first report's request arrives while the colliding report owns the name.
178
+ live.uploadBleIncidentLogRelay(relay: staleRelay, fileName: name, data: Data("late".utf8))
179
+ try await waitFor { CloudStub.requests.count == requestsBefore + 1 }
180
+ try await Task.sleep(nanoseconds: 300_000_000)
181
+
182
+ XCTAssertEqual(sentMessages(live).filter { $0.contains("transfer_complete") }.count, confirmationsBefore)
183
+ XCTAssertEqual(live.bleIncidentLogRelays[name]?.incidentId, collidingIncident)
184
+ }
185
+ }
186
+
187
+ func testFailedCloudPostKeepsOwnerUntilOwnershipExpires() async throws {
188
+ try await withCloud(status: 500) {
189
+ let live = IncidentLogTransport()
190
+ var now: TimeInterval = 1000
191
+ live.incidentRelayClock = { now }
192
+ let name = "Brep_01m4hbvt88d"
193
+ try live.sendIncidentId(incident, apiBaseUrl: cloudBase)
194
+ live.uploadBleIncidentLogRelay(
195
+ relay: try XCTUnwrap(live.bleIncidentLogRelays[name]), fileName: name, data: Data("owner".utf8)
196
+ )
197
+ try await waitFor { wire(live).contains("transfer_complete") }
198
+ XCTAssertEqual(live.bleIncidentLogRelays[name]?.incidentId, incident)
199
+ XCTAssertThrowsError(try live.sendIncidentId(collidingIncident, apiBaseUrl: cloudBase)) { error in
200
+ XCTAssertEqual((error as? BluetoothSdkError)?.code, "incident_relay_busy")
201
+ }
202
+
203
+ now += MentraLive.incidentRelayOwnershipSeconds
204
+ try live.sendIncidentId(collidingIncident, apiBaseUrl: cloudBase)
205
+ XCTAssertEqual(live.bleIncidentLogRelays[name]?.incidentId, collidingIncident)
206
+ }
207
+ }
208
+
209
+ func testDispatchFailureOfRefusedReportCannotReleaseOwner() throws {
210
+ try withToken("synthetic") {
211
+ let live = IncidentLogTransport()
212
+ try live.sendIncidentId(incident, apiBaseUrl: apiBase)
213
+ live.ready = false
214
+ XCTAssertThrowsError(try live.sendIncidentId(collidingIncident, apiBaseUrl: apiBase))
215
+ XCTAssertEqual(live.bleIncidentLogRelays["Brep_01m4hbvt88d"]?.incidentId, incident)
216
+ }
217
+ }
218
+
219
+ private let collidingIncident = "rep_01M4HBVT88DZZZZZZZZZZZZZZZ"
220
+ private let cloudBase = "https://cloud-stub.invalid"
221
+
222
+ /// Each message is wrapped as {"C":"<escaped json>"}; unescape so assertions read the message.
223
+ private func sentMessages(_ live: IncidentLogTransport) -> [String] {
224
+ live.writes.map { String(decoding: $0.0, as: UTF8.self).replacingOccurrences(of: "\\\"", with: "\"") }
225
+ }
226
+
227
+ private func wire(_ live: IncidentLogTransport) -> String {
228
+ sentMessages(live).joined()
229
+ }
230
+
231
+ private func withCloud(status: Int, body: () async throws -> Void) async throws {
232
+ CloudStub.status = status
233
+ CloudStub.requests = []
234
+ URLProtocol.registerClass(CloudStub.self)
235
+ defer { URLProtocol.unregisterClass(CloudStub.self) }
236
+ let store = DeviceStore.shared.store
237
+ let saved = store.getCategory("bluetooth")["core_token"]
238
+ store.set("bluetooth", "core_token", "synthetic")
239
+ defer {
240
+ if let saved { store.set("bluetooth", "core_token", saved) }
241
+ else { store.remove("bluetooth", "core_token") }
242
+ }
243
+ try await body()
244
+ }
245
+
246
+ private func receive(_ live: IncidentLogTransport, _ name: String, _ payload: String) async throws {
247
+ let relay = try XCTUnwrap(live.bleIncidentLogRelays[name])
248
+ live.uploadBleIncidentLogRelay(relay: relay, fileName: name, data: Data(payload.utf8))
249
+ try await waitFor { live.bleIncidentLogRelays[name] !== relay }
250
+ }
251
+
252
+ private func waitFor(_ condition: () -> Bool) async throws {
253
+ for _ in 0 ..< 500 where !condition() {
254
+ try await Task.sleep(nanoseconds: 10_000_000)
255
+ }
256
+ XCTAssertTrue(condition())
257
+ }
258
+
101
259
  private func withToken<T>(_ value: String, body: () throws -> T) rethrows -> T {
102
260
  let store = DeviceStore.shared.store
103
261
  let saved = store.getCategory("bluetooth")["core_token"]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mentra/bluetooth-sdk",
3
- "version": "3.4.0-dev.1059",
3
+ "version": "3.4.0-dev.1061",
4
4
  "description": "SDK for communicating with smart glasses",
5
5
  "main": "build/index.js",
6
6
  "react-native": "src/index.ts",
@@ -115,7 +115,7 @@
115
115
  "registry": "https://registry.npmjs.org/"
116
116
  },
117
117
  "dependencies": {
118
- "@mentra/cloud-protocol": "3.4.0-dev.1059"
118
+ "@mentra/cloud-protocol": "3.4.0-dev.1061"
119
119
  },
120
120
  "devDependencies": {
121
121
  "@types/node": "^25.9.3",
@@ -1192,6 +1192,54 @@ export type OtaStatusEvent = {
1192
1192
 
1193
1193
  export type OtaQueryResult = OtaStatusEvent
1194
1194
 
1195
+ /** Lifecycle of a BES crash incident bundle on Mentra Live glasses. */
1196
+ export type BesCrashIncidentState = "COLLECTING" | "STORED" | "REPORTED" | "UPLOADED" | "EVICTED"
1197
+
1198
+ /** One incident bundle the glasses dropped to stay within their storage budget. */
1199
+ export type BesCrashEviction = {
1200
+ incidentKey: string
1201
+ reason: string
1202
+ bytes: number
1203
+ ms: number
1204
+ }
1205
+
1206
+ /**
1207
+ * Glasses-side summary of a BES crash incident. Fields the glasses could not
1208
+ * determine (for example `dumpId` of a reset without a dump) may be absent or null.
1209
+ */
1210
+ export type BesCrashSummary = {
1211
+ attribution: "match" | "older" | "unknown"
1212
+ dumpId?: string | null
1213
+ bootId?: string | null
1214
+ resetHw?: number | null
1215
+ resetSw?: number | null
1216
+ crashUnixMs?: number | null
1217
+ coveredFromMs?: number | null
1218
+ coveredToMs?: number | null
1219
+ traceGaps: number
1220
+ truncated: boolean
1221
+ torn: boolean
1222
+ tailCaptured: boolean
1223
+ dumpGap: boolean
1224
+ evictedCount: number
1225
+ recentEvictions: BesCrashEviction[]
1226
+ }
1227
+
1228
+ /**
1229
+ * Mentra Live stored a BES crash or unexpected-reset incident. Sent when the
1230
+ * incident becomes `STORED`, and again on every reconnect while it is `STORED`
1231
+ * or `REPORTED`, so handlers must be idempotent per `incidentKey`.
1232
+ */
1233
+ export type BesCrashDetectedEvent = {
1234
+ type: "bes_crash_detected"
1235
+ incidentKey: string
1236
+ reason: "bes_crash" | "bes_unexpected_reset"
1237
+ state: BesCrashIncidentState
1238
+ /** Cloud report already recorded for this incident, or null before one is reported. */
1239
+ reportId: string | null
1240
+ summary: BesCrashSummary
1241
+ }
1242
+
1195
1243
  /** Nex BLE protobuf trace (NexEventUtils); payload matches native Map keys. */
1196
1244
  export type BleCommandTraceEvent = {
1197
1245
  command: string
@@ -1276,6 +1324,7 @@ export type BluetoothSdkModuleEvents = {
1276
1324
  ota_start_ack: (event: OtaStartAckEvent) => void
1277
1325
  ota_status: (event: OtaStatusEvent) => void
1278
1326
  ar99_ota_status: (event: Ar99OtaStatusEvent) => void
1327
+ bes_crash_detected: (event: BesCrashDetectedEvent) => void
1279
1328
  version_info: (event: VersionInfoEvent) => void
1280
1329
  send_command_to_ble: (event: BleCommandTraceEvent) => void
1281
1330
  receive_command_from_ble: (event: BleCommandTraceEvent) => void
@@ -1442,6 +1491,8 @@ export type BluetoothSdkEventMap = {
1442
1491
  ota_start_ack: OtaStartAckEvent
1443
1492
  ota_status: OtaStatusEvent
1444
1493
  ar99_ota_status: Ar99OtaStatusEvent
1494
+ /** Mentra Live stored a BES crash incident for the phone to report. */
1495
+ bes_crash_detected: BesCrashDetectedEvent
1445
1496
  version_info: VersionInfoEvent
1446
1497
  extraction_progress: ExtractionProgressEvent
1447
1498
  }