File size: 36,214 Bytes
914f53d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
import {checkCurrentGlassesForUpdate, selectMtkUpdate} from "../../modules/engine/src/services/OtaUpdateCheckService"
import {useGlassesStore} from "../../modules/engine/src/stores/glasses"
import {SETTINGS} from "@mentra/engine"
import {useSettingsStore} from "@mentra/engine-host-internal"
import {startOtaDeviceSession, stopOtaDeviceSession} from "../../modules/engine/src/services/OtaDeviceSession"
import {bluetoothSdkMock, emitBluetoothSdkEvent, resetBluetoothSdkMock} from "@/test-utils/mockBluetoothSdk"

describe("MTK full fallback", () => {
  const full = {
    end_firmware: "MentraLive_20260908.10",
    url: "https://cdn/full.zip",
    sha256: "a".repeat(64),
    size: 640341205,
  }
  const patch = {start_firmware: "20260709", end_firmware: "20260908.10", url: "https://cdn/delta.zip"}
  const manifest = {mtk_patches: [patch], mtk_full_ota: full}

  it("prefers the exact-base delta even when a full image exists", () => {
    expect(selectMtkUpdate(manifest, "MentraLive_20260709")).toBe(patch)
  })
  it.each(["20260908.9", "MentraLive_20260907.20", "20260101"])("offers full to older %s", (current) => {
    expect(selectMtkUpdate(manifest, current)).toBe(full)
  })
  it.each([undefined, "", "unknown", "20260908.10", "MentraLive_20260908.11", "20260909"])(
    "does not offer full to %s",
    (current) => {
      expect(selectMtkUpdate(manifest, current)).toBeNull()
    },
  )
  it("handles full-only, legacy-only, and date-only revision zero", () => {
    expect(selectMtkUpdate({mtk_full_ota: full}, "20260709")).toBe(full)
    expect(selectMtkUpdate({mtk_patches: [patch]}, "20260101")).toBeNull()
    expect(selectMtkUpdate({mtk_full_ota: {...full, end_firmware: "20260908.0"}}, "20260908")).toBeNull()
  })
  it.each([{sha256: ""}, {size: 0}, {size: 2 ** 31}, {url: "file:///tmp/full.zip"}, {end_firmware: "unknown"}])(
    "refuses malformed full metadata %j",
    (invalid) => {
      expect(selectMtkUpdate({mtk_full_ota: {...full, ...invalid}}, "20260101")).toBeNull()
    },
  )
})

describe("OtaUpdateCheckService", () => {
  const originalFetch = global.fetch
  const originalEmbeddedManifestUrl = process.env.EXPO_PUBLIC_ASG_OTA_VERSION_URL

  beforeEach(() => {
    process.env.EXPO_PUBLIC_ASG_OTA_VERSION_URL = "https://ota.example/app-pinned-version.json"
    resetBluetoothSdkMock()
    useGlassesStore.getState().reset()
    useSettingsStore.getState().resetAllSettingsLocally()
    useGlassesStore.getState().setGlassesInfo({
      connection: {state: "connected", fullyBooted: true},
      buildNumber: "10",
      otaVersionUrl: "https://ota.example/version.json",
      mtkFirmwareVersion: "20260101",
      besFirmwareVersion: "17.26.1.14",
    })
  })

  afterEach(() => {
    global.fetch = originalFetch
  })

  afterAll(() => {
    if (originalEmbeddedManifestUrl === undefined) {
      delete process.env.EXPO_PUBLIC_ASG_OTA_VERSION_URL
    } else {
      process.env.EXPO_PUBLIC_ASG_OTA_VERSION_URL = originalEmbeddedManifestUrl
    }
  })

  it("does not publish a delayed manifest result after the paired glasses change", async () => {
    stopOtaDeviceSession()
    ;(bluetoothSdkMock.getDefaultDevice as jest.Mock).mockResolvedValue({id: "A", model: "Mentra Live", name: "A"})
    await startOtaDeviceSession()
    let resolve!: (response: unknown) => void
    global.fetch = jest.fn(
      () =>
        new Promise((r) => {
          resolve = r
        }),
    ) as unknown as typeof fetch
    const pending = checkCurrentGlassesForUpdate({refreshVersionInfo: false, fixClockBeforeCheck: false})
    emitBluetoothSdkEvent("default_device_changed", {device: {id: "B", model: "Mentra Live", name: "B"}})
    const newOffer = {
      available: true,
      versionCode: 999,
      versionName: "new pair",
      updates: ["apk"] as "apk"[],
      totalSize: 0,
    }
    useGlassesStore.getState().setOtaUpdateAvailable(newOffer)
    resolve({
      ok: true,
      status: 200,
      json: async () => ({versionCode: 39, versionName: "old offer", downloadUrl: "https://cdn/asg.apk"}),
    })
    expect((await pending).skippedReason).toBe("disconnected")
    expect(useGlassesStore.getState().otaUpdateAvailable).toEqual(newOffer)
    stopOtaDeviceSession()
  })

  it("does not apply a late version response to the replacement pair", async () => {
    stopOtaDeviceSession()
    ;(bluetoothSdkMock.getDefaultDevice as jest.Mock).mockResolvedValue({id: "A", model: "Mentra Live", name: "A"})
    await startOtaDeviceSession()
    let resolve!: (response: Awaited<ReturnType<typeof bluetoothSdkMock.requestVersionInfo>>) => void
    bluetoothSdkMock.requestVersionInfo.mockReturnValueOnce(
      new Promise((r) => {
        resolve = r
      }),
    )
    const pending = checkCurrentGlassesForUpdate({fixClockBeforeCheck: false})
    emitBluetoothSdkEvent("default_device_changed", {device: {id: "B", model: "Mentra Live", name: "B"}})
    useGlassesStore.getState().setGlassesInfo({buildNumber: "46818067", appVersion: "new pair"})
    resolve({
      buildNumber: "303000008",
      appVersion: "3.3.0",
      androidVersion: "12",
      firmwareVersion: "",
      besFirmwareVersion: "",
      mtkFirmwareVersion: "",
      otaVersionUrl: "",
    })
    expect((await pending).skippedReason).toBe("disconnected")
    expect(useGlassesStore.getState().appVersion).toBe("new pair")
    stopOtaDeviceSession()
  })

  it.each(["resolve", "reject"])("serializes replacement checks until the old request can %s", async (settlement) => {
    stopOtaDeviceSession()
    const pair = (id: string) => ({id, model: "Mentra Live", name: id})
    ;(bluetoothSdkMock.getDefaultDevice as jest.Mock).mockResolvedValue(pair("A"))
    await startOtaDeviceSession()
    const version = {
      androidVersion: "12",
      firmwareVersion: "",
      besFirmwareVersion: "26.9.29.0",
      mtkFirmwareVersion: "20260923.0",
      buildNumber: "303000008",
      appVersion: "3.3.0",
      otaVersionUrl: "",
    }
    let resolveOld!: (value: typeof version) => void
    let rejectOld!: (error: Error) => void
    let busy = false
    let calls = 0
    bluetoothSdkMock.requestVersionInfo.mockImplementation(() => {
      if (busy) return Promise.reject(new Error("request_in_flight"))
      busy = true
      calls += 1
      if (calls === 1)
        return new Promise<typeof version>((resolve, reject) => {
          resolveOld = resolve
          rejectOld = reject
        }).finally(() => {
          busy = false
        })
      busy = false
      return Promise.resolve({...version, buildNumber: "302010070", appVersion: "3.2.1"})
    })
    global.fetch = jest.fn(async () => ({
      ok: true,
      status: 200,
      json: async () => ({versionCode: 302010070, versionName: "3.2.1", downloadUrl: "https://cdn/asg.apk"}),
    })) as unknown as typeof fetch
    const options = {fixClockBeforeCheck: false, waitForBesVersionMs: 0, waitForMtkVersionMs: 0}
    const oldCheck = checkCurrentGlassesForUpdate(options)
    emitBluetoothSdkEvent("default_device_changed", {device: pair("B")})
    const firstB = checkCurrentGlassesForUpdate(options)
    const secondB = checkCurrentGlassesForUpdate(options)
    expect(bluetoothSdkMock.requestVersionInfo).toHaveBeenCalledTimes(1)
    if (settlement === "resolve") resolveOld(version)
    else rejectOld(new Error("Old request timed out"))
    const [, one, two] = await Promise.all([oldCheck, firstB, secondB])
    expect(one.hasCheckCompleted).toBe(true)
    expect(two.hasCheckCompleted).toBe(true)
    expect(one.buildNumber).toBe("302010070")
    expect(bluetoothSdkMock.requestVersionInfo).toHaveBeenCalledTimes(2)
    expect(useGlassesStore.getState().appVersion).toBe("3.2.1")
    stopOtaDeviceSession()
  })

  it("abandons B while waiting for A when the phone switches again to C", async () => {
    stopOtaDeviceSession()
    const pair = (id: string) => ({id, model: "Mentra Live", name: id})
    ;(bluetoothSdkMock.getDefaultDevice as jest.Mock).mockResolvedValue(pair("A"))
    await startOtaDeviceSession()
    const version = {
      androidVersion: "12",
      firmwareVersion: "",
      besFirmwareVersion: "26.9.29.0",
      mtkFirmwareVersion: "20260923.0",
      buildNumber: "303000008",
      appVersion: "3.3.0",
      otaVersionUrl: "",
    }
    let resolveOld!: (value: typeof version) => void
    bluetoothSdkMock.requestVersionInfo
      .mockReturnValueOnce(
        new Promise((resolve) => {
          resolveOld = resolve
        }),
      )
      .mockResolvedValueOnce({...version, buildNumber: "302010070", appVersion: "C"})
    global.fetch = jest.fn(async () => ({
      ok: true,
      status: 200,
      json: async () => ({versionCode: 302010070, versionName: "3.2.1", downloadUrl: "https://cdn/asg.apk"}),
    })) as unknown as typeof fetch
    const options = {fixClockBeforeCheck: false, waitForBesVersionMs: 0, waitForMtkVersionMs: 0}
    const a = checkCurrentGlassesForUpdate(options)
    emitBluetoothSdkEvent("default_device_changed", {device: pair("B")})
    const b = checkCurrentGlassesForUpdate(options)
    emitBluetoothSdkEvent("default_device_changed", {device: pair("C")})
    const c = checkCurrentGlassesForUpdate(options)
    resolveOld(version)
    const [, abandoned, current] = await Promise.all([a, b, c])
    expect(abandoned.skippedReason).toBe("disconnected")
    expect(current.hasCheckCompleted).toBe(true)
    expect(bluetoothSdkMock.requestVersionInfo).toHaveBeenCalledTimes(2)
    expect(useGlassesStore.getState().appVersion).toBe("C")
    stopOtaDeviceSession()
  })

  it("skips the check entirely when the mobile app has no embedded OTA manifest pin", async () => {
    delete process.env.EXPO_PUBLIC_ASG_OTA_VERSION_URL
    useGlassesStore.getState().setGlassesInfo({appVersion: "staging.20260731.022348.189fe56"})
    global.fetch = jest.fn() as unknown as typeof fetch

    const result = await checkCurrentGlassesForUpdate({
      refreshVersionInfo: false,
      fixClockBeforeCheck: false,
      waitForBesVersionMs: 0,
      waitForMtkVersionMs: 0,
    })

    expect(result.skippedReason).toBe("dev_build")
    expect(result.updateAvailable).toBe(false)
    // An unpinned phone build must not fetch or apply an automatic OTA manifest.
    expect(global.fetch).not.toHaveBeenCalled()
  })

  it("skips the check when the glasses run a sideloaded client package", async () => {
    useGlassesStore.getState().setGlassesInfo({
      buildNumber: "120",
      packageName: "com.mentra.asg_client.thirdparty",
    })
    global.fetch = jest.fn() as unknown as typeof fetch

    const result = await checkCurrentGlassesForUpdate({
      refreshVersionInfo: false,
      fixClockBeforeCheck: false,
      waitForBesVersionMs: 0,
      waitForMtkVersionMs: 0,
    })

    expect(result.skippedReason).toBe("unofficial_client")
    expect(result.packageName).toBe("com.mentra.asg_client.thirdparty")
    expect(result.updateAvailable).toBe(false)
    // Installing the manifest APK would replace a package this client is not, so the
    // manifest must not even be fetched: the prompt could never be satisfied.
    expect(global.fetch).not.toHaveBeenCalled()
  })

  it("checks normally when the glasses report the stock client package", async () => {
    useGlassesStore.getState().setGlassesInfo({buildNumber: "40", packageName: "com.mentra.asg_client"})
    global.fetch = jest.fn(() =>
      Promise.resolve({
        ok: true,
        json: () => Promise.resolve({apps: {"com.mentra.asg_client": {versionCode: 10}}}),
      } as unknown as Response),
    ) as unknown as typeof fetch

    const result = await checkCurrentGlassesForUpdate({
      refreshVersionInfo: false,
      fixClockBeforeCheck: false,
      waitForBesVersionMs: 0,
      waitForMtkVersionMs: 0,
    })

    expect(result.skippedReason).toBeUndefined()
    expect(result.hasCheckCompleted).toBe(true)
  })

  it("checks normally when the glasses predate the package_name field", async () => {
    // Fielded glasses report no package_name at all; they must keep getting OTA.
    useGlassesStore.getState().setGlassesInfo({buildNumber: "40"})
    global.fetch = jest.fn(() =>
      Promise.resolve({
        ok: true,
        json: () => Promise.resolve({apps: {"com.mentra.asg_client": {versionCode: 10}}}),
      } as unknown as Response),
    ) as unknown as typeof fetch

    const result = await checkCurrentGlassesForUpdate({
      refreshVersionInfo: false,
      fixClockBeforeCheck: false,
      waitForBesVersionMs: 0,
      waitForMtkVersionMs: 0,
    })

    expect(result.skippedReason).toBeUndefined()
    expect(result.hasCheckCompleted).toBe(true)
  })

  it("keeps identity paired with the build number across a disconnect", async () => {
    // Regression: clearing packageName on disconnect while buildNumber survived left a stale
    // sideloaded build paired with a blank package. A blank package reads as stock, so the
    // reconnect would compare the leftover sideloaded build to the stock pin and prompt forever
    // — the original loop. Identity may only be cleared together with the build number, which
    // the native session boundary does atomically.
    useGlassesStore.getState().setGlassesInfo({
      buildNumber: "120",
      packageName: "com.mentra.asg_client.thirdparty",
    })
    useGlassesStore.getState().setGlassesInfo({connection: {state: "disconnected"}})
    expect(useGlassesStore.getState().packageName).toBe("com.mentra.asg_client.thirdparty")
    expect(useGlassesStore.getState().buildNumber).toBe("120")

    // Reconnect before version_info_1 lands: stale build + stale identity is fail-closed.
    useGlassesStore.getState().setGlassesInfo({connection: {state: "connected", fullyBooted: true}})
    global.fetch = jest.fn() as unknown as typeof fetch
    const stale = await checkCurrentGlassesForUpdate({
      refreshVersionInfo: false,
      fixClockBeforeCheck: false,
      waitForBesVersionMs: 0,
      waitForMtkVersionMs: 0,
    })
    expect(stale.skippedReason).toBe("unofficial_client")
    expect(global.fetch).not.toHaveBeenCalled()

    // The native boundary clears both together, so the next session starts clean.
    useGlassesStore.getState().setGlassesInfo({buildNumber: "", packageName: ""})
    useGlassesStore.getState().setGlassesInfo({
      connection: {state: "connected", fullyBooted: true},
      buildNumber: "40",
    })
    global.fetch = jest.fn(() =>
      Promise.resolve({
        ok: true,
        json: () => Promise.resolve({apps: {"com.mentra.asg_client": {versionCode: 10}}}),
      } as unknown as Response),
    ) as unknown as typeof fetch

    const result = await checkCurrentGlassesForUpdate({
      refreshVersionInfo: false,
      fixClockBeforeCheck: false,
      waitForBesVersionMs: 0,
      waitForMtkVersionMs: 0,
    })

    expect(result.skippedReason).toBeUndefined()
    expect(result.hasCheckCompleted).toBe(true)
  })

  it("keeps a known package when a version_info response omits the field", async () => {
    // requestVersionInfo() resolves from ANY version_info chunk, and only chunk 1 carries
    // package_name. The bridges therefore omit the key unless it is known; if they emitted ""
    // instead, the raw-spread apply below would blank a known identity, and a blank package
    // reads as stock — failing OPEN on the exact client the guard just identified.
    useGlassesStore.getState().setGlassesInfo({
      buildNumber: "120",
      packageName: "com.mentra.asg_client.thirdparty",
    })

    const chunkWithoutIdentity = await bluetoothSdkMock.requestVersionInfo()
    // The omission is the contract under test, not an accident of the fixture.
    expect(Object.prototype.hasOwnProperty.call(chunkWithoutIdentity, "packageName")).toBe(false)
    useGlassesStore.getState().setGlassesInfo(chunkWithoutIdentity)

    expect(useGlassesStore.getState().packageName).toBe("com.mentra.asg_client.thirdparty")

    // That same apply does blank buildNumber, which is pre-existing behaviour for every field
    // the responding chunk omits and is out of scope here; restore it so the guard is reached.
    useGlassesStore.getState().setGlassesInfo({buildNumber: "120"})

    global.fetch = jest.fn() as unknown as typeof fetch
    const result = await checkCurrentGlassesForUpdate({
      refreshVersionInfo: false,
      fixClockBeforeCheck: false,
      waitForBesVersionMs: 0,
      waitForMtkVersionMs: 0,
    })

    expect(result.skippedReason).toBe("unofficial_client")
    expect(global.fetch).not.toHaveBeenCalled()
  })

  it("allows a pinned mobile build regardless of the ASG app version", async () => {
    useGlassesStore.getState().setGlassesInfo({appVersion: "49076573-dev", buildNumber: "40"})
    global.fetch = jest.fn(() =>
      Promise.resolve({
        ok: true,
        json: () => Promise.resolve({apps: {"com.mentra.asg_client": {versionCode: 10}}}),
      } as unknown as Response),
    ) as unknown as typeof fetch

    const result = await checkCurrentGlassesForUpdate({
      refreshVersionInfo: false,
      fixClockBeforeCheck: false,
      waitForBesVersionMs: 0,
      waitForMtkVersionMs: 0,
    })

    expect(result.skippedReason).toBeUndefined()
    expect(result.hasCheckCompleted).toBe(true)
    expect(global.fetch).toHaveBeenCalledWith("https://ota.example/app-pinned-version.json")
  })

  it("allows an explicit super-mode manifest override from an unpinned mobile build", async () => {
    delete process.env.EXPO_PUBLIC_ASG_OTA_VERSION_URL
    useGlassesStore.getState().setGlassesInfo({buildNumber: "40"})
    useSettingsStore.setState((state) => ({
      settings: {
        ...state.settings,
        [SETTINGS.super_mode.key]: true,
        [SETTINGS.ota_version_url.key]: "https://ota.example/manual-version.json",
      },
    }))
    global.fetch = jest.fn(() =>
      Promise.resolve({
        ok: true,
        json: () => Promise.resolve({apps: {"com.mentra.asg_client": {versionCode: 40}}}),
      } as unknown as Response),
    ) as unknown as typeof fetch

    const result = await checkCurrentGlassesForUpdate({
      refreshVersionInfo: false,
      fixClockBeforeCheck: false,
      waitForBesVersionMs: 0,
      waitForMtkVersionMs: 0,
    })

    expect(result.skippedReason).toBeUndefined()
    expect(result.hasCheckCompleted).toBe(true)
    expect(global.fetch).toHaveBeenCalledWith("https://ota.example/manual-version.json")
  })

  it("reports a failed check (never up-to-date) for a zeroed pin on modern glasses", async () => {
    useGlassesStore.getState().setGlassesInfo({buildNumber: "49076573"})
    global.fetch = jest.fn(() =>
      Promise.resolve({
        ok: true,
        json: () => Promise.resolve({apps: {"com.mentra.asg_client": {versionCode: 0}}}),
      } as unknown as Response),
    ) as unknown as typeof fetch

    const result = await checkCurrentGlassesForUpdate({
      refreshVersionInfo: false,
      fixClockBeforeCheck: false,
      waitForBesVersionMs: 0,
      waitForMtkVersionMs: 0,
    })

    expect(result.hasCheckCompleted).toBe(false)
    expect(result.updateAvailable).toBe(false)
    expect(result.checkFailureReason).toBe("pin_unavailable")
  })

  it("classifies a 404 pin as pin_unavailable and a network error as network", async () => {
    const check = () =>
      checkCurrentGlassesForUpdate({
        refreshVersionInfo: false,
        fixClockBeforeCheck: false,
        waitForBesVersionMs: 0,
        waitForMtkVersionMs: 0,
      })

    global.fetch = jest.fn(() =>
      Promise.resolve({ok: false, status: 404} as unknown as Response),
    ) as unknown as typeof fetch
    let result = await check()
    expect(result.hasCheckCompleted).toBe(false)
    expect(result.checkFailureReason).toBe("pin_unavailable")

    global.fetch = jest.fn(() => Promise.reject(new Error("offline"))) as unknown as typeof fetch
    result = await check()
    expect(result.hasCheckCompleted).toBe(false)
    expect(result.checkFailureReason).toBe("network")

    global.fetch = jest.fn(() =>
      Promise.resolve({ok: false, status: 503} as unknown as Response),
    ) as unknown as typeof fetch
    result = await check()
    expect(result.checkFailureReason).toBe("network")
  })

  it("keeps a handled network check failure out of the error console", async () => {
    const consoleError = jest.spyOn(console, "error").mockImplementation(() => {})
    const consoleWarn = jest.spyOn(console, "warn").mockImplementation(() => {})
    global.fetch = jest.fn(() => Promise.reject(new Error("network switching"))) as unknown as typeof fetch

    const result = await checkCurrentGlassesForUpdate({
      refreshVersionInfo: false,
      fixClockBeforeCheck: false,
      waitForBesVersionMs: 0,
      waitForMtkVersionMs: 0,
    })

    expect(result.hasCheckCompleted).toBe(false)
    expect(result.checkFailureReason).toBe("network")
    expect(consoleWarn).toHaveBeenCalledWith("OTA: Error fetching version info:", expect.any(Error))
    expect(consoleError).not.toHaveBeenCalled()
    consoleError.mockRestore()
    consoleWarn.mockRestore()
  })

  it("skips (missing_build) for an unparseable or zero glasses build number", async () => {
    useGlassesStore.getState().setGlassesInfo({buildNumber: "0"})
    global.fetch = jest.fn() as unknown as typeof fetch

    const result = await checkCurrentGlassesForUpdate({
      refreshVersionInfo: false,
      fixClockBeforeCheck: false,
      waitForBesVersionMs: 0,
      waitForMtkVersionMs: 0,
    })

    expect(result.skippedReason).toBe("missing_build")
    expect(global.fetch).not.toHaveBeenCalled()
  })

  it("projects the explicit version response after an APK check clears Engine's cached build", async () => {
    useGlassesStore.getState().setGlassesInfo({buildNumber: ""})
    bluetoothSdkMock.requestVersionInfo.mockResolvedValueOnce({
      androidVersion: "13",
      firmwareVersion: "firmware",
      besFirmwareVersion: "17.26.1.14",
      mtkFirmwareVersion: "20260101",
      buildNumber: "10",
      otaVersionUrl: "https://ota.example/version.json",
      appVersion: "10.0",
    })
    global.fetch = jest.fn(() =>
      Promise.resolve({
        ok: true,
        json: () => Promise.resolve({apps: {"com.mentra.asg_client": {versionCode: 10}}}),
      } as unknown as Response),
    ) as unknown as typeof fetch

    const result = await checkCurrentGlassesForUpdate({
      fixClockBeforeCheck: false,
      waitForBuildNumberMs: 100,
      waitForBesVersionMs: 0,
      waitForMtkVersionMs: 0,
    })

    expect(result.skippedReason).toBeUndefined()
    expect(result.hasCheckCompleted).toBe(true)
    expect(useGlassesStore.getState().buildNumber).toBe("10")
  })

  describe("post-reboot verification", () => {
    const freshVersions = {
      androidVersion: "11",
      firmwareVersion: "",
      besFirmwareVersion: "17.26.7.9",
      mtkFirmwareVersion: "MentraLive_20260709",
      buildNumber: "39",
      otaVersionUrl: "https://ota.example/legacy.json",
      appVersion: "39.0",
    }
    const releaseManifest = {
      releaseVersion: "3.1.1",
      apps: {"com.mentra.asg_client": {versionCode: 301010001, versionName: "3.1.1"}},
      bes_firmware: {version: "26.9.4.1", url: "https://ota.example/bes.bin"},
    }
    const options = {
      fixClockBeforeCheck: false,
      waitForBesVersionMs: 0,
      waitForMtkVersionMs: 0,
      waitForLegacyMigrationMs: 120_000,
    }

    beforeEach(() => jest.useFakeTimers())
    afterEach(() => jest.useRealTimers())

    it("awaits one shared fresh response before comparing cached versions", async () => {
      useGlassesStore.getState().setGlassesInfo({buildNumber: "36", appVersion: "3.2.1"})
      let resolveVersions!: (value: typeof freshVersions) => void
      bluetoothSdkMock.requestVersionInfo.mockImplementationOnce(
        () =>
          new Promise((resolve) => {
            resolveVersions = resolve
          }),
      )
      global.fetch = jest.fn(
        async () => ({ok: true, json: async () => releaseManifest}) as Response,
      ) as unknown as typeof fetch

      const first = checkCurrentGlassesForUpdate(options)
      const second = checkCurrentGlassesForUpdate(options)
      await jest.advanceTimersByTimeAsync(0)
      expect(global.fetch).not.toHaveBeenCalled()
      expect(bluetoothSdkMock.requestVersionInfo).toHaveBeenCalledTimes(1)

      resolveVersions(freshVersions)
      const results = await Promise.all([first, second])
      for (const result of results) {
        expect(result).toMatchObject({buildNumber: "39", updates: ["apk", "bes"], hasCheckCompleted: true})
      }
      expect(useGlassesStore.getState().appVersion).toBe("39.0")
      expect(global.fetch).toHaveBeenCalledWith("https://ota.example/app-pinned-version.json")
    })

    it("does not declare cached versions up to date when the fresh request fails", async () => {
      bluetoothSdkMock.requestVersionInfo.mockRejectedValueOnce(new Error("request_timeout"))
      global.fetch = jest.fn() as unknown as typeof fetch
      const result = await checkCurrentGlassesForUpdate(options)
      expect(result).toMatchObject({hasCheckCompleted: false, checkFailureReason: "version_info"})
      expect(global.fetch).not.toHaveBeenCalled()
    })

    it.each([false, true])("waits for the release pin with a pending MTK reboot: %s", async (pendingMtkReboot) => {
      const legacyVersions = {
        ...freshVersions,
        buildNumber: "37",
        appVersion: "37.0",
        mtkFirmwareVersion: pendingMtkReboot ? "MentraLive_20260418" : freshVersions.mtkFirmwareVersion,
      }
      useGlassesStore.getState().setGlassesInfo(legacyVersions)
      useGlassesStore.getState().setMtkUpdatedThisSession(pendingMtkReboot)
      bluetoothSdkMock.requestVersionInfo.mockResolvedValueOnce(legacyVersions).mockResolvedValueOnce(freshVersions)
      global.fetch = jest.fn(
        async (url) =>
          ({
            ok: true,
            json: async () =>
              url === "https://ota.example/legacy.json"
                ? {
                    apps: {"com.mentra.asg_client": {versionCode: 37, versionName: "37.0"}},
                    mtk_patches: [
                      {
                        start_firmware: "MentraLive_20260418",
                        end_firmware: freshVersions.mtkFirmwareVersion,
                        url: "https://ota.example/mtk.zip",
                      },
                    ],
                  }
                : releaseManifest,
          }) as Response,
      ) as unknown as typeof fetch
      let settled = false
      const pending = checkCurrentGlassesForUpdate(options).then((result) => {
        settled = true
        return result
      })

      await jest.advanceTimersByTimeAsync(7_000)
      expect(settled).toBe(false)
      expect(global.fetch).toHaveBeenCalledTimes(1)
      useGlassesStore.getState().setMtkUpdatedThisSession(false)
      useGlassesStore.getState().setGlassesInfo({buildNumber: "39", appVersion: "39.0"})
      const result = await pending
      expect(result).toMatchObject({
        hasCheckCompleted: true,
        updateAvailable: true,
        buildNumber: "39",
        manifestUrl: "https://ota.example/app-pinned-version.json",
        updates: ["apk", "bes"],
      })
      expect(bluetoothSdkMock.requestVersionInfo).toHaveBeenCalledTimes(2)
    })

    it("fails verification if legacy rescue never hands off, instead of reporting completion", async () => {
      bluetoothSdkMock.requestVersionInfo.mockResolvedValueOnce({
        ...freshVersions,
        buildNumber: "37",
        appVersion: "37.0",
      })
      global.fetch = jest.fn(
        async () =>
          ({
            ok: true,
            json: async () => ({apps: {"com.mentra.asg_client": {versionCode: 37, versionName: "37.0"}}}),
          }) as Response,
      ) as unknown as typeof fetch
      const pending = checkCurrentGlassesForUpdate(options)
      await jest.advanceTimersByTimeAsync(120_000)
      expect(await pending).toMatchObject({hasCheckCompleted: false, checkFailureReason: "version_info"})
      expect(global.fetch).toHaveBeenCalledTimes(1)
    })

    it("does not accept a legacy response as final verification after a modern build was observed", async () => {
      const legacyVersions = {...freshVersions, buildNumber: "37", appVersion: "37.0"}
      bluetoothSdkMock.requestVersionInfo.mockResolvedValueOnce(legacyVersions).mockResolvedValueOnce(legacyVersions)
      global.fetch = jest.fn(
        async () =>
          ({
            ok: true,
            json: async () => ({apps: {"com.mentra.asg_client": {versionCode: 37, versionName: "37.0"}}}),
          }) as Response,
      ) as unknown as typeof fetch
      const pending = checkCurrentGlassesForUpdate(options)
      await jest.advanceTimersByTimeAsync(0)
      useGlassesStore.getState().setGlassesInfo({buildNumber: "39", appVersion: "39.0"})
      expect(await pending).toMatchObject({hasCheckCompleted: false, checkFailureReason: "version_info"})
    })
  })

  it.each([
    [51518113, false],
    [51518114, true],
    [51518115, true],
    [100000095, false],
  ])("uses the shipped downgrade floor for target %i", async (versionCode, available) => {
    useGlassesStore.getState().setGlassesInfo({buildNumber: "100000095"})
    global.fetch = jest.fn(
      async () =>
        ({
          ok: true,
          json: async () => ({apps: {"com.mentra.asg_client": {versionCode}}}),
        }) as Response,
    ) as unknown as typeof fetch

    const result = await checkCurrentGlassesForUpdate({
      refreshVersionInfo: false,
      fixClockBeforeCheck: false,
      waitForBesVersionMs: 0,
      waitForMtkVersionMs: 0,
    })
    expect(result.updateAvailable).toBe(available)
    expect(result.isApkDowngrade).toBe(available)
    expect(useGlassesStore.getState().otaUpdateAvailable?.isDowngrade ?? false).toBe(available)
  })

  it("downgrades default to skippable; explicit isRequired forces them", async () => {
    // Use a small test-only floor for this synthetic manifest.
    const check = () =>
      checkCurrentGlassesForUpdate({
        refreshVersionInfo: false,
        fixClockBeforeCheck: false,
        waitForBesVersionMs: 0,
        waitForMtkVersionMs: 0,
        floorVersionCode: 9,
      })
    const manifestWith = (extra: object) => ({
      apps: {
        "com.mentra.asg_client": {
          versionCode: 9,
          versionName: "9",
          downloadUrl: "u",
          apkSize: 1,
          sha256: "s",
          releaseNotes: "",
          ...extra,
        },
      },
    })

    // Glasses newer than the pin -> downgrade; absent isRequired -> skippable.
    global.fetch = jest.fn(() =>
      Promise.resolve({ok: true, json: () => Promise.resolve(manifestWith({}))} as unknown as Response),
    ) as unknown as typeof fetch
    let result = await check()
    expect(result.isApkDowngrade).toBe(true)
    expect(result.isRequired).toBe(false)

    // Explicit isRequired: true is the escape hatch and forces the downgrade.
    global.fetch = jest.fn(() =>
      Promise.resolve({ok: true, json: () => Promise.resolve(manifestWith({isRequired: true}))} as unknown as Response),
    ) as unknown as typeof fetch
    result = await check()
    expect(result.isRequired).toBe(true)

    // Upgrades keep the historical forced default when isRequired is absent.
    global.fetch = jest.fn(() =>
      Promise.resolve({
        ok: true,
        json: () =>
          Promise.resolve({
            apps: {
              "com.mentra.asg_client": {
                versionCode: 999999,
                versionName: "n",
                downloadUrl: "u",
                apkSize: 1,
                sha256: "s",
                releaseNotes: "",
              },
            },
          }),
      } as unknown as Response),
    ) as unknown as typeof fetch
    result = await check()
    expect(result.isApkDowngrade).toBe(false)
    expect(result.isRequired).toBe(true)

    // An explicit floor 0 disables downgrades entirely: the same lower pin is not offered.
    global.fetch = jest.fn(() =>
      Promise.resolve({ok: true, json: () => Promise.resolve(manifestWith({}))} as unknown as Response),
    ) as unknown as typeof fetch
    result = await checkCurrentGlassesForUpdate({
      refreshVersionInfo: false,
      fixClockBeforeCheck: false,
      waitForBesVersionMs: 0,
      waitForMtkVersionMs: 0,
      floorVersionCode: 0,
    })
    expect(result.isApkDowngrade).toBe(false)
    expect(result.updateAvailable).toBe(false)
  })

  it("checks the current glasses and writes the available OTA snapshot", async () => {
    global.fetch = jest.fn(() =>
      Promise.resolve({
        ok: true,
        json: () =>
          Promise.resolve({
            releaseVersion: "3.1.0-beta.3",
            apps: {
              "com.mentra.asg_client": {
                versionCode: 11,
                versionName: "11",
                downloadUrl: "https://ota.example/app.apk",
                apkSize: 1,
                sha256: "abc",
                releaseNotes: "test",
                isRequired: false,
              },
            },
            mtk_patches: [
              {
                start_firmware: "MentraLive_20260101",
                end_firmware: "MentraLive_20260201",
                url: "https://ota.example/mtk.zip",
              },
            ],
            bes_firmware: {
              version: "17.26.1.15",
              url: "https://ota.example/bes.bin",
            },
          }),
      } as unknown as Response),
    ) as unknown as typeof fetch

    const result = await checkCurrentGlassesForUpdate({
      refreshVersionInfo: false,
      fixClockBeforeCheck: false,
      waitForBesVersionMs: 0,
      waitForMtkVersionMs: 0,
    })

    expect(global.fetch).toHaveBeenCalledWith("https://ota.example/version.json")
    expect(result).toEqual(
      expect.objectContaining({
        hasCheckCompleted: true,
        updateAvailable: true,
        isRequired: false,
        releaseVersion: "3.1.0-beta.3",
        updates: ["apk", "mtk", "bes"],
      }),
    )
    expect(useGlassesStore.getState().otaUpdateAvailable).toEqual(
      expect.objectContaining({
        available: true,
        versionCode: 11,
        versionName: "11",
        updates: ["apk", "mtk", "bes"],
        besVersion: "17.26.1.15",
      }),
    )
  })

  it("filters MTK from the written update info after MTK already updated this session", async () => {
    useGlassesStore.getState().setMtkUpdatedThisSession(true)
    global.fetch = jest.fn(() =>
      Promise.resolve({
        ok: true,
        json: () =>
          Promise.resolve({
            mtk_patches: [
              {
                start_firmware: "MentraLive_20260101",
                end_firmware: "MentraLive_20260201",
                url: "https://ota.example/mtk.zip",
              },
            ],
          }),
      } as unknown as Response),
    ) as unknown as typeof fetch

    const result = await checkCurrentGlassesForUpdate({
      refreshVersionInfo: false,
      fixClockBeforeCheck: false,
      waitForBesVersionMs: 0,
      waitForMtkVersionMs: 0,
    })

    expect(result.updateAvailable).toBe(false)
    expect(result.updates).toEqual([])
    expect(useGlassesStore.getState().otaUpdateAvailable).toBeNull()
  })
})