File size: 26,724 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
/// <reference types="bun-types" />

import {afterEach, beforeEach, describe, expect, jest, mock, test} from "bun:test"

/**

 * Unit tests for LocalDisplayManager.

 *

 * Covers boot window, pass-through (pacing now lives in the native per-device

 * queue, not here), durationMs expiry, and core-vs-background arbitration.

 * Uses jest fake timers + an injected clock.

 */

const displayEventMock = mock(() => {})

// DisplayProcessor: pass through unchanged so we can assert on the raw event.
mock.module("../DisplayProcessor", () => ({
  __esModule: true,
  default: {
    setDeviceModel: () => {},
    processDisplayEvent: (e: Record<string, unknown>) => ({...e, _processed: true}),
  },
}))

import {bluetoothSdk} from "./bluetoothSdkTestMock"

bluetoothSdk.displayEvent = displayEventMock

// The store ports (SceneRenderer reads settings/glasses; attachToRuntime
// subscribes to the glasses store) pull native modules bun can't parse —
// stub the stores like the PhonePhotoCoordinator suite does.
mock.module("../../stores/settings", () => ({
  SETTINGS: {default_wearable: {key: "default_wearable"}},
  useSettingsStore: {
    // No device model: keeps these suites on the legacy (non-scene) path, the
    // same effective condition they ran under on dev (unset runtime hooks).
    getState: () => ({getSetting: () => undefined}),
  },
}))
mock.module("../../stores/glasses", () => ({
  useGlassesStore: {
    getState: () => ({connection: {state: "connected", fullyBooted: true}, deviceModel: undefined}),
    subscribe: () => () => {},
  },
}))
mock.module("../GlassesReadiness", () => ({
  isGlassesConnected: (connection: {state?: string} | undefined) => connection?.state === "connected",
}))

mock.module("../../utils/timers", () => ({
  BgTimer: {
    setTimeout: (callback: () => void, delay: number) => setTimeout(callback, delay) as unknown as number,
    clearTimeout: (timeoutId: number) => clearTimeout(timeoutId),
    setInterval: (callback: () => void, delay: number) => setInterval(callback, delay) as unknown as number,
    clearInterval: (intervalId: number) => clearInterval(intervalId),
  },
}))

// Import AFTER mocks

const {LocalDisplayManager} = require("../LocalDisplayManager")

type Mgr = InstanceType<typeof LocalDisplayManager>

describe("LocalDisplayManager", () => {
  let mgr: Mgr
  let now = 1_000_000

  const advance = (ms: number) => {
    now += ms
    jest.advanceTimersByTime(ms)
  }

  const displayCalls = () =>
    displayEventMock.mock.calls.map(([event]: any[]) => ({
      pkg: (event.layout?.layoutType as string) ?? "?",
      view: event.view,
      layout: event.layout,
      durationMs: event.durationMs,
    }))

  const lastLayoutType = (): string | undefined => {
    const calls = displayEventMock.mock.calls
    if (calls.length === 0) return undefined
    return calls[calls.length - 1][0].layout?.layoutType
  }

  const lastText = (): string | undefined => {
    const calls = displayEventMock.mock.calls
    if (calls.length === 0) return undefined
    return calls[calls.length - 1][0].layout?.text
  }

  beforeEach(() => {
    bluetoothSdk.displayEvent = displayEventMock
    jest.useFakeTimers()
    displayEventMock.mockClear()
    now = 1_000_000
    // Fresh singleton per test.
    mgr = LocalDisplayManager.getInstance()
    mgr._resetForTest()
    mgr._setNowForTest(() => now)
  })

  afterEach(() => {
    jest.useRealTimers()
  })

  describe("conditional main-view updates", () => {
    const frame = (text: string, ifDisplayToken?: string) => ({
      layout: {layoutType: "text_wall", text},
      ifDisplayToken,
    })
    const render = (pkg: string, payload: import("../LocalDisplayManager").DisplayPayload) => {
      let result: import("../LocalDisplayManager").DisplayRequestResult | undefined
      mgr.request(pkg, payload, (value: import("../LocalDisplayManager").DisplayRequestResult) => {
        result = value
      })
      return result!
    }
    test("accepted frames rotate the token, including same-app frames", () => {
      mgr.onCoreAppChange("ai")
      const first = render("ai", frame("one"))
      expect(first.displayToken).toBeString()
      const second = render("ai", frame("two", first.displayToken))
      expect(second.status).toBe("displayed")
      expect(second.displayToken).not.toBe(first.displayToken)
      expect(render("ai", frame("stale", first.displayToken)).status).toBe("blocked")
      expect(lastText()).toBe("two")
    })
    test("stale pages do not acquire a lock or replace the retained core snapshot", () => {
      mgr.onCoreAppChange("ai")
      const first = render("ai", frame("original"))
      render("other", {...frame("other app"), durationMs: 1000})
      expect(render("ai", frame("unread page", first.displayToken)).status).toBe("blocked")
      advance(1000)
      expect(lastText()).toBe("original")
      // Restoring a frame invalidates its old token too.
      expect(render("ai", frame("late", first.displayToken)).status).toBe("blocked")
    })
    test("an expired background lease cannot let an old timer take the display back", () => {
      const first = render("ai", frame("answer"))
      advance(10_001)
      render("other", frame("other app"))
      advance(10_001)
      expect(render("ai", frame("next page", first.displayToken)).status).toBe("blocked")
      expect(lastText()).toBe("other app")
      expect(render("other", frame("still other app")).status).toBe("displayed")
    })
    test("tokens are scoped to package, and stale clears cannot clear another frame", () => {
      const first = render("ai", frame("answer"))
      expect(render("other", frame("hijack", first.displayToken)).status).toBe("blocked")
      render("ai", frame("new answer"))
      expect(render("ai", {scene: [], ifDisplayToken: first.displayToken}).status).toBe("blocked")
      expect(lastText()).toBe("new answer")
    })
    test("boot rejects a conditional page immediately without queueing or saving it", () => {
      const first = render("ai", frame("answer"))
      mgr.onMount("new-app", "New app")
      expect(render("ai", frame("stale page", first.displayToken)).status).toBe("blocked")
      advance(1500)
      expect(lastText()).toBe("answer")
    })
    test("dashboard traffic does not invalidate the main token or return one", () => {
      const first = render("ai", frame("answer"))
      const dashboard = render("dashboard-app", {...frame("dashboard"), view: "dashboard"})
      expect(dashboard.displayToken).toBeUndefined()
      expect(render("ai", frame("next", first.displayToken)).status).toBe("displayed")
    })
    test("a core dashboard update cannot save a background notice as its main frame", () => {
      mgr.onCoreAppChange("core")
      render("core", frame("original core frame"))
      render("notice", {...frame("temporary notice"), durationMs: 1000})
      render("core", {...frame("core dashboard"), view: "dashboard"})
      advance(1000)
      expect(lastText()).toBe("original core frame")
    })
    test("a core dashboard update during boot cannot become the saved main frame", () => {
      mgr.onCoreAppChange("core")
      render("core", frame("original core frame"))
      mgr.onMount("new-app", "New app")
      render("core", {...frame("core dashboard"), view: "dashboard"})
      render("new-app", {...frame("temporary new app"), durationMs: 1000})
      advance(1000)
      expect(lastText()).toBe("original core frame")
    })
    test("conditional clears forfeit the frame and do not return a reusable token", () => {
      const first = render("ai", frame("answer"))
      const result = render("ai", {scene: [], ifDisplayToken: first.displayToken})
      expect(result).toEqual({status: "displayed"})
      expect(render("ai", frame("late", first.displayToken)).status).toBe("blocked")
    })
  })

  // ==========================================================================
  // Boot window
  // ==========================================================================

  describe("boot window", () => {
    test("onMount sends 'Starting <name>…' immediately", () => {
      mgr.onMount("com.app.foo", "Foo")
      expect(displayEventMock).toHaveBeenCalledTimes(1)
      expect(lastLayoutType()).toBe("text_wall")
      expect(lastText()).toBe("Starting Foo…")
    })

    test("display requests during boot are queued until timeout", () => {
      mgr.onCoreAppChange("com.app.foo")
      mgr.onMount("com.app.foo", "Foo")
      displayEventMock.mockClear() // drop the boot message

      // A request from a different (non-booting) app during boot — queued.
      mgr.request("com.app.bar", {
        layout: {layoutType: "text_wall", text: "bar"},
      })
      expect(displayEventMock).not.toHaveBeenCalled()

      // Still nothing after 1000ms.
      advance(1000)
      expect(displayEventMock).not.toHaveBeenCalled()

      // Boot timer elapses at 1500ms → drain.
      advance(500)
      // "bar" was queued but core app is com.app.foo (didn't queue). Since bar
      // is NOT core, it would take a bg lock and send.
      expect(displayEventMock).toHaveBeenCalledTimes(1)
      expect(lastText()).toBe("bar")
    })

    test("booting app's own first display ends boot early and renders immediately", () => {
      mgr.onCoreAppChange("com.app.foo")
      mgr.onMount("com.app.foo", "Foo")
      displayEventMock.mockClear()

      mgr.request("com.app.foo", {
        layout: {layoutType: "text_wall", text: "ready"},
      })
      // No advance — should render right away.
      expect(displayEventMock).toHaveBeenCalledTimes(1)
      expect(lastText()).toBe("ready")
      expect(mgr._peekForTest().isBooting).toBe(false)
    })

    test("boot timeout with no queued displays clears the boot text for the core app", () => {
      mgr.onCoreAppChange("com.app.foo")
      mgr.onMount("com.app.foo", "Foo")
      displayEventMock.mockClear()
      advance(1500)
      // Clear sent.
      expect(lastLayoutType()).toBe("clear_view")
    })

    // Production wires onMount (from LocalMiniappRuntime.registerApp) but NOT
    // onCoreAppChange, so coreApp is null. The boot text must still clear on
    // timeout, or a miniapp that never renders would strand "Starting …".
    test("boot timeout clears the boot text even when no core app is wired", () => {
      mgr.onMount("com.app.foo", "Foo")
      expect(lastText()).toBe("Starting Foo…")
      displayEventMock.mockClear()
      advance(1500)
      expect(lastLayoutType()).toBe("clear_view")
    })

    // The common case: a single foreground display app, onMount only. The boot
    // message shows, then the app's first render replaces it — no core wiring
    // needed.
    test("booting app's first display replaces the boot text with no core app wired", () => {
      mgr.onMount("com.app.foo", "Foo")
      expect(lastText()).toBe("Starting Foo…")
      mgr.request("com.app.foo", {layout: {layoutType: "text_wall", text: "ready"}})
      expect(lastText()).toBe("ready")
      expect(mgr._peekForTest().isBooting).toBe(false)
    })

    // registerApp fires onMount for EVERY spawn (background app, crash-respawn),
    // so a second app's boot must not blank whatever the first app is showing.
    // On timeout with nothing rendered, the prior frame is restored, not cleared.
    test("a second app's boot that times out restores the prior frame, not a blank", () => {
      // App A renders content (its own boot ends early on first display).
      mgr.onMount("com.app.a", "A")
      mgr.request("com.app.a", {layout: {layoutType: "text_wall", text: "A-content"}})
      expect(lastText()).toBe("A-content")

      // App B spawns and never renders.
      mgr.onMount("com.app.b", "B")
      expect(lastText()).toBe("Starting B…")
      displayEventMock.mockClear()

      advance(1500)
      // B never rendered → A's frame restored, glasses not blanked.
      expect(lastLayoutType()).not.toBe("clear_view")
      expect(lastText()).toBe("A-content")
    })

    test("mounting a second app cancels the first boot", () => {
      mgr.onCoreAppChange("com.app.foo")
      mgr.onMount("com.app.foo", "Foo")
      mgr.onMount("com.app.bar", "Bar")
      // Second mount kicks off its own boot message.
      expect(lastText()).toBe("Starting Bar…")
      expect(mgr._peekForTest().isBooting).toBe(true)
    })
  })

  // ==========================================================================
  // Pass-through (no JS-side throttle)
  // ==========================================================================
  //
  // Display pacing + last-wins coalescing now live in the native per-device
  // queue (e.g. G2's event-driven EvenHub queue), not here — a JS throttle could
  // not flush on schedule while the iOS app was suspended, so updates bursted on
  // the next wake. This class forwards every request straight through.

  describe("pass-through", () => {
    beforeEach(() => {
      mgr.onCoreAppChange("com.app.foo")
      mgr.onMount("com.app.foo", "Foo")
      // Consume the boot message so counts are clean.
      mgr.request("com.app.foo", {
        layout: {layoutType: "text_wall", text: "boot-flush"},
      })
      displayEventMock.mockClear()
    })

    test("5 rapid-fire requests → 5 sends, no time advance, in order", () => {
      for (let i = 0; i < 5; i++) {
        mgr.request("com.app.foo", {
          layout: {layoutType: "text_wall", text: `msg${i}`},
        })
      }

      // Every request forwarded immediately — no throttle, no coalescing here.
      expect(displayEventMock.mock.calls.length).toBe(5)
      expect(lastText()).toBe("msg4")

      // Nothing deferred to a trailing timer.
      advance(THROTTLE_MS)
      expect(displayEventMock.mock.calls.length).toBe(5)
    })

    test("each request renders immediately without waiting for a window", () => {
      mgr.request("com.app.foo", {
        layout: {layoutType: "text_wall", text: "a"},
      })
      expect(lastText()).toBe("a")
      mgr.request("com.app.foo", {
        layout: {layoutType: "text_wall", text: "b"},
      })
      expect(lastText()).toBe("b")
      mgr.request("com.app.foo", {
        layout: {layoutType: "text_wall", text: "c"},
      })
      expect(lastText()).toBe("c")
      expect(displayEventMock.mock.calls.length).toBe(3)
    })
  })

  // ==========================================================================
  // Duration expiry
  // ==========================================================================

  describe("durationMs expiry", () => {
    beforeEach(() => {
      mgr.onCoreAppChange("com.app.foo")
      mgr.onMount("com.app.foo", "Foo")
    })

    test("display clears when durationMs elapses", () => {
      mgr.request("com.app.foo", {
        layout: {layoutType: "text_wall", text: "hi"},
        durationMs: 500,
      })
      displayEventMock.mockClear()
      advance(500)
      expect(lastLayoutType()).toBe("clear_view")
    })

    test("new request before expiry cancels the clear", () => {
      mgr.request("com.app.foo", {
        layout: {layoutType: "text_wall", text: "hi"},
        durationMs: 500,
      })
      advance(200)
      advance(THROTTLE_MS) // make sure throttle is clear
      mgr.request("com.app.foo", {
        layout: {layoutType: "text_wall", text: "hi2"},
      })
      displayEventMock.mockClear()
      advance(1000)
      // No clear_view should have been triggered.
      const hasClear = displayEventMock.mock.calls.some(([e]: any[]) => e.layout?.layoutType === "clear_view")
      expect(hasClear).toBe(false)
    })
  })

  // ==========================================================================
  // Core vs background arbitration
  // ==========================================================================

  describe("core vs background arbitration", () => {
    beforeEach(() => {
      mgr.onCoreAppChange("com.app.core")
      mgr.onMount("com.app.core", "Core")
      // Drain boot
      advance(1500)
      displayEventMock.mockClear()
    })

    test("background app acquires lock when core isn't displaying", () => {
      advance(THROTTLE_MS)
      mgr.request("com.app.bg1", {
        layout: {layoutType: "text_wall", text: "bg1"},
      })
      expect(lastText()).toBe("bg1")
      expect(mgr._peekForTest().bgLockPkg).toBe("com.app.bg1")
    })

    test("second background app is blocked while first holds lock and displays", () => {
      advance(THROTTLE_MS)
      mgr.request("com.app.bg1", {
        layout: {layoutType: "text_wall", text: "bg1"},
      })
      displayEventMock.mockClear()
      advance(THROTTLE_MS)
      mgr.request("com.app.bg2", {
        layout: {layoutType: "text_wall", text: "bg2"},
      })
      expect(displayEventMock).not.toHaveBeenCalled()
    })

    test("core app is blocked while bg lock-holder is actively on the glasses", () => {
      advance(THROTTLE_MS)
      mgr.request("com.app.bg1", {
        layout: {layoutType: "text_wall", text: "bg1"},
      })
      displayEventMock.mockClear()
      advance(THROTTLE_MS)

      // Core tries to render — blocked.
      mgr.request("com.app.core", {
        layout: {layoutType: "text_wall", text: "core-wants"},
      })
      expect(displayEventMock).not.toHaveBeenCalled()
    })

    test("when bg holder's display expires, core's saved display is restored", () => {
      // Core sets a long-lived display, then bg preempts with short duration.
      advance(THROTTLE_MS)
      mgr.request("com.app.core", {
        layout: {layoutType: "text_wall", text: "core-saved"},
        durationMs: 10_000,
      })
      displayEventMock.mockClear()

      advance(THROTTLE_MS)
      mgr.request("com.app.bg1", {
        layout: {layoutType: "text_wall", text: "bg1"},
        durationMs: 200,
      })
      // Core was blocked; bg is on glasses.
      expect(lastText()).toBe("bg1")
      displayEventMock.mockClear()

      // Bg expires → core restored.
      advance(200)
      expect(lastText()).toBe("core-saved")
    })

    test("unmounting the lock holder releases the lock and restores core", () => {
      advance(THROTTLE_MS)
      mgr.request("com.app.core", {
        layout: {layoutType: "text_wall", text: "core-saved"},
        durationMs: 10_000,
      })
      advance(THROTTLE_MS)
      mgr.request("com.app.bg1", {
        layout: {layoutType: "text_wall", text: "bg1"},
      })
      displayEventMock.mockClear()

      mgr.onUnmount("com.app.bg1")
      // Lock released, core restored.
      expect(mgr._peekForTest().bgLockPkg).toBeNull()
      expect(lastText()).toBe("core-saved")
    })

    test("dismissing a temporary background display restores core", () => {
      mgr.request("com.app.core", {
        layout: {layoutType: "text_wall", text: "core-saved"},
      })
      mgr.request("cloud.augmentos.notify", {
        layout: {layoutType: "reference_card", title: "Messages", text: "Hello"},
        durationMs: 5_000,
      })
      expect(lastLayoutType()).toBe("reference_card")
      displayEventMock.mockClear()

      mgr.dismiss("cloud.augmentos.notify")

      expect(mgr._peekForTest().bgLockPkg).toBeNull()
      expect(lastText()).toBe("core-saved")
    })
  })

  // ==========================================================================
  // Foreground flip
  // ==========================================================================

  describe("onCoreAppChange", () => {
    test("flipping core to null drops the saved core display", () => {
      mgr.onCoreAppChange("com.app.a")
      mgr.onMount("com.app.a", "A")
      advance(1500)
      displayEventMock.mockClear()

      mgr.request("com.app.a", {
        layout: {layoutType: "text_wall", text: "a1"},
        durationMs: 10_000,
      })
      expect(lastText()).toBe("a1")

      // Core goes away → saved frame is dropped so it can't flicker back later.
      mgr.onCoreAppChange(null)
      expect(mgr._peekForTest().coreApp).toBeNull()

      // A bg app can now take the screen; the old core frame is not restored
      // when that bg app later unmounts.
      mgr.request("com.app.bg", {layout: {layoutType: "text_wall", text: "bg"}})
      expect(lastText()).toBe("bg")
      displayEventMock.mockClear()
      mgr.onUnmount("com.app.bg")
      const restoredOldCore = displayEventMock.mock.calls.some(([e]: any[]) => e.layout?.text === "a1")
      expect(restoredOldCore).toBe(false)
    })
  })

  // ==========================================================================
  // Boot-strand and clear-forfeit regressions (bug hunt 2026-07-22)
  // ==========================================================================

  describe("boot-strand and clear-forfeit regressions", () => {
    test("chained boots never restore a stale 'Starting…' frame", () => {
      mgr.onCoreAppChange("com.app.core")
      mgr.request("com.app.core", {layout: {layoutType: "text_wall", text: "core content"}})

      // Back-to-back mounts (autostart restore): the second boot starts while
      // the first's "Starting A…" is still on the glasses.
      mgr.onMount("com.app.a", "A")
      mgr.onMount("com.app.b", "B")

      // Neither app renders; the boot window times out.
      advance(1500)

      // Must restore the ORIGINAL pre-boot frame — not "Starting A…".
      expect(lastText()).toBe("core content")
    })

    test("boot text clears when the glasses were empty and the app never renders", () => {
      mgr.onMount("com.app.a", "A")
      mgr.onMount("com.app.b", "B")
      advance(1500)
      expect(lastLayoutType()).toBe("clear_view")
    })

    test("unmounting the booting app does not strand its boot text", () => {
      mgr.onCoreAppChange("com.app.core")
      mgr.request("com.app.core", {layout: {layoutType: "text_wall", text: "core content"}})

      mgr.onMount("com.app.a", "A")
      expect(lastText()).toBe("Starting A…")

      mgr.onUnmount("com.app.a")
      expect(lastText()).toBe("core content")
    })

    test("a background app's clear forfeits the lock and restores the core display", () => {
      mgr.onCoreAppChange("com.app.core")
      mgr.request("com.app.core", {layout: {layoutType: "text_wall", text: "core content"}})

      mgr.request("com.app.bg", {layout: {layoutType: "text_wall", text: "bg overlay"}})
      expect(lastText()).toBe("bg overlay")

      // Clear = "I'm done": core comes back and the lock is free immediately.
      mgr.request("com.app.bg", {layout: {layoutType: "clear_view"}})
      expect(lastText()).toBe("core content")

      mgr.request("com.app.bg2", {layout: {layoutType: "text_wall", text: "bg2 overlay"}})
      expect(lastText()).toBe("bg2 overlay")
    })

    test("an empty scene render (render([])) is a forfeit too", () => {
      mgr.onCoreAppChange("com.app.core")
      mgr.request("com.app.core", {layout: {layoutType: "text_wall", text: "core content"}})

      mgr.request("com.app.bg", {layout: {layoutType: "text_wall", text: "bg overlay"}})
      expect(lastText()).toBe("bg overlay")

      mgr.request("com.app.bg", {view: "main", scene: []})
      expect(lastText()).toBe("core content")
    })

    test("a context teardown (respawn) does not release the core claim", () => {
      // The coreApp pointer is derived from the apps store; a liveness/crash
      // respawn tears the context down with NO store change (the app is
      // still "running"), so the claim must survive the unmount. Only the
      // saved frame is dropped (it belongs to the dead context).
      mgr.onCoreAppChange("com.app.core")
      mgr.request("com.app.core", {layout: {layoutType: "text_wall", text: "core content"}, durationMs: 10_000})

      mgr.onUnmount("com.app.core")
      expect(mgr._peekForTest().coreApp).toBe("com.app.core")

      // The respawned context's first render must arbitrate as CORE: a bg
      // overlay that then expires restores it.
      mgr.onMount("com.app.core", "Core")
      advance(1500)
      mgr.request("com.app.core", {layout: {layoutType: "text_wall", text: "respawned"}, durationMs: 10_000})
      mgr.request("com.app.bg", {layout: {layoutType: "text_wall", text: "bg overlay"}, durationMs: 1000})
      advance(1000)
      expect(lastText()).toBe("respawned")
    })

    test("a clear queued during boot forfeits the pre-boot frame (no resurrection)", () => {
      mgr.onCoreAppChange("com.app.core")
      mgr.request("com.app.core", {layout: {layoutType: "text_wall", text: "core content"}})

      // An app boots; while its "Starting…" is up, the core CLEARS. The clear
      // parks in the boot queue; endBoot must not restore the forfeited frame.
      mgr.onMount("com.app.b", "B")
      mgr.request("com.app.core", {layout: {layoutType: "clear_view"}})
      advance(1500)

      expect(lastLayoutType()).toBe("clear_view")
    })

    test("a clear queued during boot also blocks the unmount-mid-boot restore", () => {
      mgr.onCoreAppChange("com.app.core")
      mgr.request("com.app.core", {layout: {layoutType: "text_wall", text: "core content"}})

      mgr.onMount("com.app.b", "B")
      mgr.request("com.app.core", {layout: {layoutType: "clear_view"}})
      mgr.onUnmount("com.app.b")

      expect(lastLayoutType()).toBe("clear_view")
    })

    test("the core app's own clear forgets its snapshot so it cannot resurrect", () => {
      mgr.onCoreAppChange("com.app.core")
      mgr.request("com.app.core", {layout: {layoutType: "text_wall", text: "core content"}})

      mgr.request("com.app.core", {layout: {layoutType: "clear_view"}})
      expect(lastLayoutType()).toBe("clear_view")

      // A bg overlay that later expires must NOT bring the cleared frame back.
      mgr.request("com.app.bg", {layout: {layoutType: "text_wall", text: "bg overlay"}, durationMs: 1000})
      expect(lastText()).toBe("bg overlay")
      advance(1000)
      expect(lastLayoutType()).toBe("clear_view")
    })
  })
})

// Generic "let some time pass" amount for arbitration/expiry tests. The JS
// throttle this once mirrored is gone; pacing now lives in the native queue.
const THROTTLE_MS = 300