File size: 34,869 Bytes
8a29801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**

 * LocalDisplayManager

 *

 * Phone-side arbiter for display requests originating from LOCAL miniapps

 * (the @mentra/miniapp SDK). Preserves the retired cloud display manager's

 * user-facing behavior for the features that matter on the phone:

 *

 *   - boot message ("Starting <AppName>…") with a bounded window

 *   - durationMs auto-clear

 *   - core-app vs background-app arbitration with a background lock

 *

 * Display pacing is NOT done here. A JS-side ~300ms throttle used to live in

 * this class, but JS timers (and therefore the throttle's trailing flush) do

 * not fire on schedule while the iOS app is suspended in the background β€” so

 * under streaming captions, updates accumulated and then flushed in a burst on

 * the next wake. Pacing + last-wins coalescing now live in the native per-device

 * queue (e.g. G2's event-driven EvenHub queue), which drains off the same BLE

 * events that wake the process. This class forwards every request straight

 * through; the native layer collapses redundant frames per display target.

 *

 * The remaining BgTimer use (boot window, durationMs expiry) is timing that

 * does not need sub-second background fidelity.

 */

import BluetoothSdk from "@mentra/bluetooth-sdk/internal"
import displayProcessor from "./DisplayProcessor"
import {useDisplayStore} from "../stores/display"
import sceneRenderer from "./SceneRenderer"
import {isGlassesConnected} from "./GlassesReadiness"
import {useGlassesStore} from "../stores/glasses"
import type {SceneTextLayout} from "../utils/display/scene/types"
import type {SceneElementInput} from "../utils/display/scene"
import {BgTimer} from "../utils/timers"

// =============================================================================
// Types
// =============================================================================

export interface DisplayPayload {
  view?: "main" | "dashboard" | string
  /** Legacy layout (sugar / old bundles / cloud shapes). Either this or `scene`. */
  layout?: {layoutType: string; [key: string]: unknown}
  /** Scene elements from display.render(). Either this or `layout`. */
  scene?: SceneElementInput[]
  durationMs?: number
  includeTextLayout?: boolean
  ifDisplayToken?: string
}

/** Outcome delivered to an awaiting render() call (REQUEST_RESULT payload). */
export interface DisplayRequestResult {
  status: "displayed" | "blocked"
  displayToken?: string
  degraded?: boolean
  dropped?: string[]
  reason?: string
  textLayout?: Record<string, SceneTextLayout>
}

export type DisplayRequestResolver = (result: DisplayRequestResult) => void

interface ActiveDisplay {
  packageName: string
  processedEvent: Record<string, unknown>
  /** Set when this display is a scene β€” restore goes through SceneRenderer replay. */
  scene?: SceneElementInput[]
  /** Latest blocked core request; not yet processed or retained by SceneRenderer. */
  pendingPayload?: DisplayPayload
  expiresAt: number | null
}

interface BootingApp {
  packageName: string
  displayName: string
  startedAt: number
  timerId: number
  /** Whatever was on the glasses when this boot started, so a boot that times

   * out without the app rendering can restore it instead of blanking a frame

   * another (e.g. foreground) app owns. Null if the glasses were empty. */
  preBoot: ActiveDisplay | null
}

interface BackgroundLock {
  packageName: string
  acquiredAt: number
  expiresAt: number
  lastActiveTime: number
}

// =============================================================================
// Constants
// =============================================================================

const LOG_TAG = "LOCAL_DISPLAY"
const BOOT_DURATION_MS = 1500
// Background renders renew this lease. An expired lock is dropped when the
// next display request is arbitrated, allowing another app to take the screen.
const BACKGROUND_LOCK_TIMEOUT_MS = 10_000
// Sentinel package name used as the "source" of the system boot message.
const SYSTEM_BOOT_PKG = "system.boot"

/** "Render nothing" β€” an empty scene or an explicit clear_view layout. */
function isClearPayload(payload: DisplayPayload): boolean {
  if (payload.scene) return payload.scene.length === 0
  return payload.layout?.layoutType === "clear_view"
}

// =============================================================================
// LocalDisplayManager
// =============================================================================

class LocalDisplayManager {
  private static instance: LocalDisplayManager | null = null

  private coreApp: string | null = null
  private coreAppDisplay: ActiveDisplay | null = null
  private currentDisplay: ActiveDisplay | null = null
  private displayRevision = 0
  private backgroundLock: BackgroundLock | null = null

  private bootingApp: BootingApp | null = null
  private bootQueue: Map<string, {payload: DisplayPayload; resolve?: DisplayRequestResolver}> = new Map()

  private expiryTimerId: number | null = null

  /** Reconnect-replay subscription state (attachToRuntime). */
  private runtimeAttached = false
  private glassesWasConnected = false
  private unsubscribeGlassesStatus: (() => void) | null = null

  /** Injectable for tests. */
  private now: () => number = () => Date.now()

  private constructor() {}

  public static getInstance(): LocalDisplayManager {
    if (!LocalDisplayManager.instance) {
      LocalDisplayManager.instance = new LocalDisplayManager()
    }
    return LocalDisplayManager.instance
  }

  // ===========================================================================
  // Lifecycle API (called from MiniappHost)
  // ===========================================================================

  /**

   * A new local miniapp just mounted. Start the boot window.

   * Calling this for a different pkg while another is booting cancels the

   * previous boot.

   */
  public onMount(packageName: string, displayName: string): void {
    console.log(`${LOG_TAG}: onMount(${packageName}, "${displayName}")`)

    // Snapshot whatever's on the glasses BEFORE the boot text overwrites it.
    // registerApp fires onMount for every spawn β€” including a background app or
    // a crash-respawn while another app is foreground β€” so a boot that times out
    // without rendering must put the prior frame back rather than blank it.
    // Never snapshot the boot text itself: back-to-back mounts (the autostart
    // restore loop, crash-respawn chains) land while the previous app's
    // "Starting X…" is still on the glasses, and endBoot would "restore" that
    // stale, expiry-less frame permanently. Across chained boots, inherit the
    // original pre-boot frame instead.
    const inherited = this.bootingApp ? this.bootingApp.preBoot : this.currentDisplay
    const preBoot = inherited?.packageName === SYSTEM_BOOT_PKG ? null : inherited

    // Cancel any in-flight boot for a prior app.
    this.cancelBoot()

    // Send the boot message directly (bypass arbitration β€” this is a system
    // display). Goes through sendNow so scene devices render it as a scene:
    // otherwise every app start would be a legacy→scene transition on the
    // glasses (which costs a blanking clear).
    this.sendNow(SYSTEM_BOOT_PKG, {
      view: "main",
      layout: {layoutType: "text_wall", text: `Starting ${displayName}…`},
    })

    const timerId = BgTimer.setTimeout(() => {
      this.endBoot()
    }, BOOT_DURATION_MS)

    this.bootingApp = {
      packageName,
      displayName,
      startedAt: this.now(),
      timerId,
      preBoot,
    }
    this.bootQueue.clear()
  }

  /**

   * Mark which miniapp is the "core" (foreground) app. Pass null when no local

   * miniapp is foreground.

   */
  public onCoreAppChange(packageName: string | null): void {
    if (this.coreApp === packageName) return
    console.log(`${LOG_TAG}: onCoreAppChange(${packageName ?? "null"})`)

    this.coreApp = packageName

    // No core app means no saved frame to restore on the next unmount.
    // Without this, the previous core's last frame can flicker back onto
    // the glasses when the user-initiated clear is followed by an
    // onUnmount that still finds a populated coreAppDisplay.
    if (packageName === null) {
      this.coreAppDisplay = null
    }
  }

  /** Report-safe ownership snapshot for incident diagnostics. */
  public getDiagnosticSnapshot(): Record<string, unknown> {
    return {
      coreAppPackageName: this.coreApp,
      currentDisplayPackageName: this.currentDisplay?.packageName ?? null,
      backgroundLockPackageName: this.backgroundLock?.packageName ?? null,
      bootingPackageName: this.bootingApp?.packageName ?? null,
    }
  }

  /**

   * A local miniapp is going away. Clean up all state associated with it.

   */
  public onUnmount(packageName: string): void {
    console.log(`${LOG_TAG}: onUnmount(${packageName})`)

    // If this was the booting app, cancel boot β€” and don't strand its
    // "Starting X…" text (a system frame with no expiry): put back what the
    // boot covered, or clear.
    if (this.bootingApp?.packageName === packageName) {
      const preBoot = this.bootingApp.preBoot
      this.cancelBoot()
      if (this.currentDisplay?.packageName === SYSTEM_BOOT_PKG) {
        // The preBoot owner may have forfeited its frame during the boot
        // window (a clear parked in the boot queue) β€” don't resurrect it.
        const ownerQueued = preBoot ? this.bootQueue.get(preBoot.packageName) : undefined
        const preBootForfeited = ownerQueued !== undefined && isClearPayload(ownerQueued.payload)
        if (preBoot && !preBootForfeited && (preBoot.expiresAt === null || preBoot.expiresAt > this.now())) {
          this.restoreDisplay(preBoot)
        } else {
          this.sendClear()
        }
      }
    }
    this.bootQueue.get(packageName)?.resolve?.({status: "blocked", reason: "app stopped"})
    this.bootQueue.delete(packageName)

    // Forget the app's retained scenes β€” nothing left to replay for it.
    sceneRenderer.clearApp(packageName)

    // Release bg lock if this app held it.
    if (this.backgroundLock?.packageName === packageName) {
      this.backgroundLock = null
    }

    // Drop the saved core frame if the core's context is going away β€” the
    // frame belongs to a dead context and must not be restored later. The
    // coreApp POINTER itself is NOT cleared here: it is derived state owned
    // by the apps-store reconciler. A liveness/crash respawn tears the
    // context down (this path) without any store change β€” the app is still
    // "running" β€” and clearing the pointer here would leave the respawned
    // foreground app arbitrating as background until an unrelated store
    // write happened to re-run the reconciler. Real stops release the slot
    // via the store (running β†’ false β†’ reconciler β†’ onCoreAppChange(null)).
    if (this.coreApp === packageName) {
      this.coreAppDisplay = null
    }

    // If this app owned the current on-glasses display, clear it (and maybe
    // restore the core app's display if it still has time left).
    if (this.currentDisplay?.packageName === packageName) {
      this.clearExpiryTimer()
      this.currentDisplay = null
      this.tryRestoreCoreDisplay()
      if (!this.currentDisplay) {
        // Nothing to restore β†’ clear the glasses.
        this.sendClear()
      }
    }
  }

  // ===========================================================================
  // Display request API (called from LocalMiniappRuntime.handleDisplay)
  // ===========================================================================

  /**

   * A miniapp requested a display. Routes through boot queue, arbitration,

   * and throttle. This is the only public entry point for miniapp display

   * traffic on the local path.

   *

   * `resolve`, when provided (render() requests), is guaranteed to be called

   * exactly once with the request's outcome β€” including for requests parked in

   * the boot queue (resolved when drained or superseded).

   */
  public request(packageName: string, payload: DisplayPayload, resolve?: DisplayRequestResolver): void {
    const deliver = resolve
    resolve = (result) =>
      deliver?.({
        ...result,
        ...(result.status === "displayed" &&
        payload.view !== "dashboard" &&
        !isClearPayload(payload) &&
        this.currentDisplay?.packageName === packageName
          ? {displayToken: String(this.displayRevision)}
          : {}),
      })
    // Conditional writes never enter the boot queue or affect another view.
    if (
      payload.ifDisplayToken !== undefined &&
      (payload.view === "dashboard" || this.bootingApp || !this.matchesFrame(packageName, payload.ifDisplayToken))
    ) {
      resolve({status: "blocked", reason: "display frame changed"})
      return
    }
    // Dashboard view: pass straight through (no throttle/arbitration). Local
    // dashboard rendering is currently a stub on the phone anyway.
    if (payload.view === "dashboard") {
      this.sendNow(packageName, payload, resolve)
      return
    }

    // During boot, any app's requests go into the queue. If the booting app
    // itself makes its first display call, end boot early and drain.
    if (this.bootingApp) {
      const superseded = this.bootQueue.get(packageName)
      superseded?.resolve?.({status: "blocked", reason: "superseded by a newer frame"})
      this.bootQueue.set(packageName, {payload, resolve})
      if (this.bootingApp.packageName === packageName) {
        this.endBoot()
      }
      return
    }

    this.arbitrateAndSend(packageName, payload, resolve)
  }

  /**

   * End a package's temporary display early. If it currently owns the main

   * view, release its background lock and restore the foreground miniapp's

   * saved frame. A dismissal for a package that is no longer visible is a

   * no-op.

   */
  public dismiss(packageName: string): void {
    this.handleExpiry(packageName)
  }

  // ===========================================================================
  // Internals β€” arbitration
  // ===========================================================================

  private matchesFrame(packageName: string, token: string): boolean {
    return this.currentDisplay?.packageName === packageName && token === String(this.displayRevision)
  }

  private arbitrateAndSend(packageName: string, payload: DisplayPayload, resolve?: DisplayRequestResolver): void {
    // Recheck at arbitration, before modifying locks or saved core frames.
    if (payload.ifDisplayToken !== undefined && !this.matchesFrame(packageName, payload.ifDisplayToken)) {
      resolve?.({status: "blocked", reason: "display frame changed"})
      return
    }
    const now = this.now()

    // Expire a stale bg lock before arbitrating.
    if (this.backgroundLock && now > this.backgroundLock.expiresAt) {
      this.backgroundLock = null
    }

    // A clear ("render nothing") means "I'm done with the display" β€” it is a
    // forfeit, not a frame. A background app releases its lock and the core
    // app's still-valid display comes back; treating it as a render instead
    // would RENEW the lock with an empty frame and blank the glasses while
    // still blocking everyone else.
    if (isClearPayload(payload)) {
      this.handleAppClear(packageName, resolve)
      return
    }

    const isCore = packageName === this.coreApp

    if (isCore) {
      // Save so we can restore later.
      this.coreAppDisplay = {
        packageName,
        processedEvent: {}, // filled by sendNow
        scene: payload.scene,
        pendingPayload: payload,
        expiresAt: payload.durationMs ? now + payload.durationMs : null,
      }

      // If a bg app holds the lock AND is currently on the glasses, core is
      // blocked. The saved coreAppDisplay surfaces when the bg app expires
      // or unmounts.
      const bgHoldsAndDisplays =
        this.backgroundLock &&
        this.currentDisplay &&
        this.currentDisplay.packageName === this.backgroundLock.packageName
      if (bgHoldsAndDisplays) {
        resolve?.({status: "blocked", reason: "a background app holds the display"})
        return
      }

      // Core can display. If a bg lock exists but holder isn't actively on
      // the glasses, release it.
      if (this.backgroundLock && !bgHoldsAndDisplays) {
        this.backgroundLock = null
      }

      this.sendNow(packageName, payload, resolve)
      return
    }

    // Non-core: this is a background app.
    if (this.backgroundLock && this.backgroundLock.packageName !== packageName) {
      // Another bg app already holds the lock β€” drop.
      resolve?.({status: "blocked", reason: "another background app holds the display"})
      return
    }

    // Acquire or bump the lock.
    if (!this.backgroundLock) {
      this.backgroundLock = {
        packageName,
        acquiredAt: now,
        expiresAt: now + BACKGROUND_LOCK_TIMEOUT_MS,
        lastActiveTime: now,
      }
    } else {
      this.backgroundLock.lastActiveTime = now
      this.backgroundLock.expiresAt = now + BACKGROUND_LOCK_TIMEOUT_MS
    }

    this.sendNow(packageName, payload, resolve)
  }

  /**

   * An app cleared its display ("render nothing"). Same semantics as its

   * frame expiring: give up ownership, restore the core app's still-valid

   * display if there is one, otherwise clear the glasses.

   */
  private handleAppClear(packageName: string, resolve?: DisplayRequestResolver): void {
    // Forget the app's retained scene state β€” its next render starts fresh.
    sceneRenderer.clearApp(packageName)

    if (this.backgroundLock?.packageName === packageName) {
      this.backgroundLock = null
    }
    if (this.coreApp === packageName) {
      this.coreAppDisplay = null
    }

    if (this.currentDisplay?.packageName === packageName) {
      this.clearExpiryTimer()
      this.currentDisplay = null
      this.tryRestoreCoreDisplay()
      if (!this.currentDisplay) {
        this.sendClear()
      }
    }
    resolve?.({status: "displayed"})
  }

  // ===========================================================================
  // Internals β€” send
  // ===========================================================================

  private sendNow(
    packageName: string,
    payload: DisplayPayload,
    resolve?: DisplayRequestResolver,
    replay = false,
  ): void {
    const expiresAt = payload.durationMs ? this.now() + payload.durationMs : null
    const view = (payload.view === "dashboard" ? "dashboard" : "main") as "main" | "dashboard"

    // Scene requests β€” and legacy layouts a positioning device can render as a
    // scene (sugar, old bundles) β€” go through the scene pipeline. Everything
    // else stays on the legacy path.
    let sceneElements = payload.scene ?? null
    if (!sceneElements && payload.layout) {
      const caps = sceneRenderer.currentCapabilities()
      if (caps?.canPosition) {
        sceneElements = sceneRenderer.convertLegacyLayout(payload.layout, caps)
      }
    }

    if (sceneElements) {
      this.sendScene(packageName, view, sceneElements, expiresAt, resolve, replay, payload.includeTextLayout)
    } else if (payload.layout) {
      // This layout bypasses the scene pipeline (clear_view, dashboard_card,
      // unknown types, or a non-positioning device). If this (app, view) had a
      // retained scene, the glasses no longer match it β€” reset the diff
      // baseline so the next render() repaints from empty instead of skipping
      // "unchanged" elements.
      sceneRenderer.resetBaseline(packageName, view)
      const rawEvent: Record<string, unknown> = {
        view: payload.view ?? "main",
        layout: payload.layout,
      }
      if (payload.durationMs !== undefined) {
        rawEvent.durationMs = payload.durationMs
      }
      this.sendToNative(packageName, rawEvent, expiresAt)
      resolve?.({status: "displayed"})
    } else {
      // A scene payload on a device with no display block at all.
      resolve?.({status: "blocked", reason: "no display connected"})
      return
    }

    // If core app fired, refresh the saved snapshot with the actual processed
    // event so restore uses the wrapped text (legacy) / the retained scene.
    if (view === "main" && packageName === this.coreApp && this.currentDisplay?.packageName === packageName) {
      this.coreAppDisplay = {
        packageName,
        processedEvent: this.currentDisplay.processedEvent,
        scene: this.currentDisplay.scene,
        expiresAt: this.currentDisplay.expiresAt,
      }
    }
  }

  /**

   * Send a scene through SceneRenderer. On positioning devices this emits a

   * SceneFrame; on degrade devices SceneRenderer hands back a legacy layout

   * that rides the existing (unchanged) DisplayProcessor path.

   */
  private sendScene(
    packageName: string,
    view: "main" | "dashboard",
    elements: SceneElementInput[],
    expiresAt: number | null,
    resolve?: DisplayRequestResolver,
    replay = false,
    includeTextLayout = false,
  ): void {
    const result = sceneRenderer.emitScene(packageName, view, elements, replay, includeTextLayout)

    if (result.kind === "no-display") {
      resolve?.({status: "blocked", reason: "no display connected"})
      return
    }

    if (result.kind === "legacy") {
      if (result.layout) {
        this.sendToNative(
          packageName,
          {view, layout: result.layout, ...(result.prewrapped ? {_processed: true} : {})},
          expiresAt,
        )
        if (view === "main" && this.currentDisplay) this.currentDisplay.scene = elements
      } else {
        // Scene degraded to nothing (e.g. all-image scene on a text-only
        // device). Clear only the requested view.
        this.sendClear(view)
      }
      resolve?.({
        status: "displayed",
        degraded: result.degraded,
        dropped: result.dropped,
        ...(includeTextLayout ? {textLayout: result.textLayout} : {}),
      })
      return
    }

    if (view === "dashboard") {
      resolve?.({
        status: "displayed",
        degraded: result.degraded,
        dropped: result.dropped,
        ...(includeTextLayout ? {textLayout: result.textLayout} : {}),
      })
      return
    }
    this.displayRevision++
    this.currentDisplay = {packageName, processedEvent: {}, scene: elements, expiresAt}
    this.clearExpiryTimer()
    if (expiresAt !== null) {
      const delay = Math.max(0, expiresAt - this.now())
      this.expiryTimerId = BgTimer.setTimeout(() => {
        this.expiryTimerId = null
        this.handleExpiry(packageName)
      }, delay)
    }
    resolve?.({
      status: "displayed",
      degraded: result.degraded,
      dropped: result.dropped,
      ...(includeTextLayout ? {textLayout: result.textLayout} : {}),
    })
  }

  private sendToNative(packageName: string, rawEvent: Record<string, unknown>, expiresAt: number | null): void {
    let processedEvent: Record<string, unknown>
    try {
      processedEvent = displayProcessor.processDisplayEvent(rawEvent as any)
    } catch (err) {
      console.error(`${LOG_TAG}: DisplayProcessor error, using raw event:`, err)
      processedEvent = rawEvent
    }

    try {
      // The display output path is a direct btsdk call now (was a host sendDisplayEvent
      // hook) so a bare OEM renders to the glasses without wiring it.
      void Promise.resolve(BluetoothSdk.displayEvent(processedEvent)).catch((err) => {
        console.error(`${LOG_TAG}: native display failed:`, err)
      })
      // The mirror store also lives in engine, so display requests update the
      // phone-side preview without any host hook.
      useDisplayStore.getState().setDisplayEvent(JSON.stringify(processedEvent))
    } catch (err) {
      console.error(`${LOG_TAG}: native display failed:`, err)
    }

    // Dashboard traffic does not replace or expire the main-view owner.
    if (rawEvent.view === "dashboard") return
    this.displayRevision++
    this.currentDisplay = {packageName, processedEvent, expiresAt}

    this.clearExpiryTimer()
    if (expiresAt !== null) {
      const delay = Math.max(0, expiresAt - this.now())
      this.expiryTimerId = BgTimer.setTimeout(() => {
        this.expiryTimerId = null
        this.handleExpiry(packageName)
      }, delay)
    }
  }

  private handleExpiry(packageName: string): void {
    // Someone else is on the glasses now β€” ignore.
    if (!this.currentDisplay || this.currentDisplay.packageName !== packageName) {
      return
    }

    // Release the lock if it belonged to this (bg) app.
    if (this.backgroundLock?.packageName === packageName) {
      this.backgroundLock = null
    }

    this.currentDisplay = null
    this.tryRestoreCoreDisplay()
    if (!this.currentDisplay) {
      this.sendClear()
    }
  }

  private tryRestoreCoreDisplay(): void {
    if (!this.coreAppDisplay) return
    // If the core snapshot has a duration and it's already elapsed, skip.
    if (this.coreAppDisplay.expiresAt !== null && this.now() >= this.coreAppDisplay.expiresAt) {
      this.coreAppDisplay = null
      return
    }
    // Re-send the core's saved display.
    this.restoreDisplay(this.coreAppDisplay)
  }

  private sendClear(view: "main" | "dashboard" = "main"): void {
    const clearEvent: Record<string, unknown> = {
      view,
      layout: {layoutType: "clear_view"},
    }
    this.sendToNative("system.clear", clearEvent, null)
    if (view === "main") this.currentDisplay = null
    // Only this view is blank; unrelated retained content stays current.
    sceneRenderer.markViewStale(view)
  }

  // ===========================================================================
  // Internals β€” boot
  // ===========================================================================

  private cancelBoot(): void {
    if (!this.bootingApp) return
    BgTimer.clearTimeout(this.bootingApp.timerId)
    this.bootingApp = null
  }

  private endBoot(): void {
    if (!this.bootingApp) return
    const preBoot = this.bootingApp.preBoot
    BgTimer.clearTimeout(this.bootingApp.timerId)
    this.bootingApp = null

    // Drain the queue: core first, then everyone else. Per-app last wins
    // because the map holds one payload per packageName.
    const queued = Array.from(this.bootQueue.entries())
    this.bootQueue.clear()

    const corePayload = this.coreApp ? queued.find(([pkg]) => pkg === this.coreApp) : undefined
    if (corePayload) {
      this.arbitrateAndSend(corePayload[0], corePayload[1].payload, corePayload[1].resolve)
    }
    for (const [pkg, entry] of queued) {
      if (pkg === this.coreApp) continue
      this.arbitrateAndSend(pkg, entry.payload, entry.resolve)
    }

    // If the boot text is still on the glasses β€” nothing was queued, or every
    // drained request lost arbitration β€” it must not strand: it's a system
    // frame with no expiry. Restore whatever was on the glasses before the
    // boot, else clear. Two reasons NOT to restore: the frame's duration
    // elapsed during the boot window, or its owner FORFEITED it during the
    // window (its final queued intent β€” the queue keeps last-wins per app β€”
    // was a clear, which the drain above processed as a forfeit; restoring
    // would resurrect content the clear removed).
    if (this.currentDisplay?.packageName === SYSTEM_BOOT_PKG) {
      const ownerEntry = preBoot ? queued.find(([pkg]) => pkg === preBoot.packageName) : undefined
      const preBootForfeited = ownerEntry !== undefined && isClearPayload(ownerEntry[1].payload)
      if (preBoot && !preBootForfeited && (preBoot.expiresAt === null || preBoot.expiresAt > this.now())) {
        this.restoreDisplay(preBoot)
      } else {
        this.sendClear()
      }
    }
  }

  /**

   * Re-push a previously-captured on-glasses frame (e.g. the display a boot

   * window overwrote). Mirrors tryRestoreCoreDisplay: the saved event is already

   * processed, and any remaining duration is recomputed from its expiry.

   */
  private restoreDisplay(saved: ActiveDisplay): void {
    const remaining = saved.expiresAt !== null ? Math.max(0, saved.expiresAt - this.now()) : undefined

    // Blocked requests never reached SceneRenderer. Process the latest payload
    // now, preserving its original deadline, and replace the covered scene in
    // one create-based replay rather than replaying an older retained frame.
    if (saved.pendingPayload) {
      // durationMs: 0 means persistent; an expired deadline must not become one.
      if (remaining === 0) {
        this.coreAppDisplay = null
        return
      }
      this.sendNow(saved.packageName, {...saved.pendingPayload, durationMs: remaining}, undefined, true)
      return
    }

    // Scene restores must REPLAY (create-based, epoch-bumped): re-emitting the
    // scene through the normal diff would come back all-"unchanged" and the
    // device would skip every element (spec Β§4 β€” replay is always create-based).
    if (saved.scene) {
      const expiresAt = remaining !== undefined ? this.now() + remaining : null
      if (sceneRenderer.replayApp(saved.packageName, "main")) {
        this.displayRevision++
        this.currentDisplay = {packageName: saved.packageName, processedEvent: {}, scene: saved.scene, expiresAt}
        this.clearExpiryTimer()
        if (expiresAt !== null) {
          const delay = Math.max(0, expiresAt - this.now())
          this.expiryTimerId = BgTimer.setTimeout(() => {
            this.expiryTimerId = null
            this.handleExpiry(saved.packageName)
          }, delay)
        }
      } else {
        // Retained state gone (app stopped since) β€” re-render the saved
        // elements as a fresh scene instead.
        this.sendNow(saved.packageName, {view: "main", scene: saved.scene, durationMs: remaining})
      }
      return
    }

    this.sendNow(saved.packageName, {
      view: "main",
      layout: saved.processedEvent.layout as DisplayPayload["layout"],
      durationMs: remaining,
    })
  }

  // ===========================================================================
  // Reconnect replay (design doc Β§3.4.7 β€” recovery = replay, host-driven)
  // ===========================================================================

  /**

   * Subscribe to glasses connection state so the current owner's frame is

   * replayed after a reconnect. Safe to call repeatedly; attaches once. Wired

   * from MantleManager next to displayProcessor.attachToRuntime().

   */
  public attachToRuntime(): void {
    if (this.runtimeAttached) return
    // dev wired this through the (since-removed) glassesStatus runtime hooks;
    // engine reads its own glasses store directly.
    this.glassesWasConnected = isGlassesConnected(useGlassesStore.getState().connection)
    this.unsubscribeGlassesStatus = useGlassesStore.subscribe(() => {
      const connected = isGlassesConnected(useGlassesStore.getState().connection)
      if (connected === this.glassesWasConnected) return
      this.glassesWasConnected = connected
      this.displayRevision++ // In-flight page updates cannot cross a disconnect.
      if (connected) {
        this.replayCurrent()
      }
    })
    this.runtimeAttached = true
  }

  /**

   * Re-push the current on-glasses frame after a device recovery. Scenes replay

   * from SceneRenderer's retained state (create-based, epoch-bumped); legacy

   * frames re-send their processed event. Expired frames don't come back.

   */
  public replayCurrent(): void {
    const current = this.currentDisplay
    if (!current) return
    if (current.expiresAt !== null && this.now() >= current.expiresAt) return

    console.log(`${LOG_TAG}: replayCurrent(${current.packageName})`)
    if (current.scene) {
      this.displayRevision++
      if (!sceneRenderer.replayApp(current.packageName, "main")) {
        this.sendNow(
          current.packageName,
          {
            view: "main",
            scene: current.scene,
            durationMs: current.expiresAt === null ? 0 : Math.max(0, current.expiresAt - this.now()),
          },
          undefined,
          true,
        )
      }
    } else if (current.processedEvent.layout) {
      this.sendToNative(current.packageName, current.processedEvent, current.expiresAt)
    }
  }

  // ===========================================================================
  // Internals β€” timer helpers
  // ===========================================================================

  private clearExpiryTimer(): void {
    if (this.expiryTimerId !== null) {
      BgTimer.clearTimeout(this.expiryTimerId)
      this.expiryTimerId = null
    }
  }

  // ===========================================================================
  // Test hooks
  // ===========================================================================

  /** Injected clock β€” tests only. */
  public _setNowForTest(fn: () => number): void {
    this.now = fn
  }

  /** Wipe state β€” tests only. */
  public _resetForTest(): void {
    this.cancelBoot()
    this.clearExpiryTimer()
    this.coreApp = null
    this.coreAppDisplay = null
    this.currentDisplay = null
    this.backgroundLock = null
    this.bootQueue.clear()
    this.now = () => Date.now()
    this.unsubscribeGlassesStatus?.()
    this.unsubscribeGlassesStatus = null
    this.runtimeAttached = false
    this.glassesWasConnected = false
    sceneRenderer._resetForTest()
  }

  /** Read-only state snapshot β€” tests only. */
  public _peekForTest(): {
    coreApp: string | null
    currentDisplayPkg: string | null
    bgLockPkg: string | null
    isBooting: boolean
  } {
    return {
      coreApp: this.coreApp,
      currentDisplayPkg: this.currentDisplay?.packageName ?? null,
      bgLockPkg: this.backgroundLock?.packageName ?? null,
      isBooting: this.bootingApp !== null,
    }
  }
}

const localDisplayManager = LocalDisplayManager.getInstance()
export default localDisplayManager
export {LocalDisplayManager}