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

import {describe, expect, test} from "bun:test"
import {readFileSync} from "node:fs"

// A miniapp's token carries what Core knew about the user when it was minted (the features they hold), so the
// runtime asks for a fresh one whenever the miniapp opens: on CONNECT, on its foreground edge, and when the
// scheduled refresh falls due. If CONNECT's fresh mint fails, its retries go through the default path, which
// serves a still-valid cached token. These run the shipped methods against a fake clock, fake timers and a fake
// Cloud Client, in the style of the runtime's other isolated suites, instead of booting the Expo app singleton.
const source = readFileSync(new URL("../LocalMiniappRuntime.ts", import.meta.url), "utf8")
const methods = [
  "updateVisibility",
  "handleConnect",
  "requestMiniappAuth",
  "refreshMiniappAuth",
  "handleAuthRefresh",
  "authRefreshOptions",
  "currentAuthApp",
  "scheduleMiniappAuthRefresh",
  "armMiniappAuthRefresh",
  "clearMiniappAuthRefresh",
  "deliverInitialMiniappAuth",
  "scheduleInitialMiniappAuthRetry",
  "clearMiniappAuthDeliveryRetry",
  "redriveMiniappAuthDelivery",
]
  .map((name) => {
    const start = source.search(new RegExp(`^  (?:public|private) (?:async )?${name}\\(`, "m"))
    if (start < 0) throw new Error(`Missing runtime method ${name}`)
    const rest = source.slice(start)
    const end = rest.search(/^ {2}}$/m)
    if (end < 0) throw new Error(`Missing end of runtime method ${name}`)
    return rest.slice(0, end + 3)
  })
  .join("\n")

/** The runtime's own timing constants, read from the source so a change there cannot leave this suite stale. */
const constants = [
  "MINIAPP_AUTH_REFRESH_HEADROOM_MS",
  "MINIAPP_AUTH_REFRESH_MIN_DELAY_MS",
  "MINIAPP_AUTH_RETRY_BASE_MS",
  "MINIAPP_AUTH_RETRY_MAX_MS",
]
  .map((name) => {
    const line = source.match(new RegExp(`^const ${name} = .*$`, "m"))
    if (!line) throw new Error(`Missing runtime constant ${name}`)
    return line[0]
  })
  .join("\n")
const compiled = new Bun.Transpiler({loader: "ts"}).transformSync(`${constants}\nclass Host { ${methods} }`)
const constantValue = (name: string): number => Number(new Function(`${constants}; return ${name}`)())

const HEADROOM_MS = constantValue("MINIAPP_AUTH_REFRESH_HEADROOM_MS")
const MIN_DELAY_MS = constantValue("MINIAPP_AUTH_REFRESH_MIN_DELAY_MS")
const RETRY_BASE_MS = constantValue("MINIAPP_AUTH_RETRY_BASE_MS")
const RETRY_MAX_MS = constantValue("MINIAPP_AUTH_RETRY_MAX_MS")

const CALL = "com.mentra.call"
const HOUR_MS = 60 * 60 * 1000
/** The cloud client keeps a cached miniapp token until this close to its expiry. */
const CACHE_MARGIN_MS = 60_000

interface Token {
  token: string
  expiresAt: number
}
interface Request {
  packageName: string
  opts: {minTtlMs?: number; fresh?: boolean; localBuild?: boolean} | undefined
}
type Plan = (request: Request) => Promise<Token>

async function flush(): Promise<void> {
  for (let i = 0; i < 20; i++) await Promise.resolve()
}

function fixture() {
  let now = 1_800_000_000_000
  let timerSeq = 0
  const timers = new Map<number, {at: number; delay: number; callback: () => void}>()
  const bgTimer = {
    setTimeout(callback: () => void, delay: number) {
      const id = ++timerSeq
      timers.set(id, {at: now + delay, delay, callback})
      return id
    },
    clearTimeout(id: number) {
      timers.delete(id)
    },
  }

  // The cloud client's cache rule, which is why a scheduled refresh before expiry used to hand back the same token.
  let minted = 0
  let cached: Token | null = null
  const requests: Request[] = []
  const plans: Plan[] = []
  let coreDown = false
  const mint = (): Token => {
    cached = {token: `token-${++minted}`, expiresAt: now + HOUR_MS}
    return cached
  }
  const cloudClientService = {
    hasCore: () => true,
    getMiniappAuthToken(packageName: string, opts?: Request["opts"]): Promise<Token> {
      const request = {packageName, opts}
      requests.push(request)
      const plan = plans.shift()
      if (plan) return plan(request)
      if (coreDown) return Promise.reject(new Error("Core is down"))
      if (!opts?.fresh && cached && cached.expiresAt - CACHE_MARGIN_MS > now) return Promise.resolve(cached)
      return Promise.resolve(mint())
    },
  }

  const warnings: string[] = []
  /** Packages whose context started as a local or development build (the router records it at the spawn). */
  const localBuilds = new Set<string>()
  const Host = new Function(
    "BgTimer",
    "cloudClientService",
    "isLocalBuildContext",
    "useSettingsStore",
    "ISLAND_SETTINGS_KEYS",
    "DeviceTypes",
    "getModelCapabilities",
    "computeDeclaredPermissionRecord",
    "getMiniappConfiguration",
    "MiniappResponseType",
    "MiniappErrorCode",
    "LOG_TAG",
    "Date",
    "console",
    `${compiled}; return Host`,
  )(
    bgTimer,
    cloudClientService,
    (packageName: string) => localBuilds.has(packageName),
    {getState: () => ({getSetting: () => undefined})},
    {defaultWearable: "default_wearable"},
    {NONE: "none"},
    () => ({}),
    () => ({}),
    () => ({}),
    {CONNECT_ACK: "connect_ack", AUTH_UPDATE: "auth_update"},
    {NOT_CONNECTED: "not_connected", INTERNAL: "internal"},
    "LOCAL_MINIAPP",
    {now: () => now},
    {log() {}, warn: (message: string) => warnings.push(message)},
  )

  let visible: string | null = null
  const host = new Host()
  const sent: Array<{type: string; auth?: Token}> = []
  const visibility: Array<[string, string]> = []
  host.connectedApps = new Map()
  host.handshookApps = new Set()
  host.visiblePackage = null
  host.authSessionSeq = 0
  host.currentVisiblePackage = () => visible
  host.sendToMiniapp = (_packageName: string, message: {type: string; auth?: Token}) => sent.push(message)
  host.sendVisibilityChange = (packageName: string, state: string) => visibility.push([packageName, state])
  const results: Array<{requestId?: string; ok: boolean; auth?: Token; error?: {code: string; message: string}}> = []
  host.sendResult = (

    _packageName: string,

    requestId: string | undefined,

    ok: boolean,

    data?: {auth?: Token},

    error?: {code: string; message: string},

  ) => results.push({requestId, ok, auth: data?.auth, error})
  host.sendCloudStatusToMiniapp = () => {}
  host.flushConnectWaiters = () => {}

  /** registerApp: a respawned miniapp replaces the old entry and drops its timers. */
  const register = (packageName = CALL) => {
    const existing = host.connectedApps.get(packageName)
    if (existing?.authRefreshTimerId != null) bgTimer.clearTimeout(existing.authRefreshTimerId)
    if (existing?.authRetryTimerId != null) bgTimer.clearTimeout(existing.authRetryTimerId)
    host.connectedApps.set(packageName, {
      lastPongAt: 0,
      unansweredPingRounds: 0,
      installedManifest: undefined,
      authRefreshTimerId: null,
      authRetryTimerId: null,
      authDelivered: false,
      authSession: 0,
      authRequestPending: false,
    })
  }

  /** Move the clock forward, running every timer that falls due on the way, in order. */
  async function advance(ms: number): Promise<void> {
    const target = now + ms
    for (;;) {
      const due = [...timers.entries()].filter(([, timer]) => timer.at <= target).sort((a, b) => a[1].at - b[1].at)[0]
      if (!due) break
      timers.delete(due[0])
      now = Math.max(now, due[1].at)
      due[1].callback()
      await flush()
    }
    now = target
    await flush()
  }

  return {
    host,
    requests,
    warnings,
    localBuilds,
    visibility,
    /** Tokens the miniapp was handed, in order (CONNECT's delivery and every AUTH_UPDATE after it). */
    /** The results the miniapp was sent for its own AUTH_REFRESH requests. */
    results,
    delivered: () => sent.filter((message) => message.type === "auth_update").map((message) => message.auth?.token),
    now: () => now,
    /** Timers still armed, with the delay each was armed for. */
    armed: () => [...timers.values()].map((timer) => timer.delay),
    plan: (...next: Plan[]) => plans.push(...next),
    /** Every request without a plan of its own fails while Core is down. */
    setCoreDown: (down: boolean) => {
      coreDown = down
    },
    advance,
    /** The miniapp's WebView connects. */
    async connect() {
      register()
      host.handleConnect(CALL, {}, "req-1")
      await flush()
    },
    /** The miniapp asks for a refreshed token itself. */
    async askForRefresh(minTtlMs?: number) {
      host.handleAuthRefresh(CALL, minTtlMs ? {minTtlMs} : {}, "req-refresh")
      await flush()
    },
    /** The same WebView sends CONNECT again without being respawned. */
    async connectAgain() {
      host.handleConnect(CALL, {}, "req-2")
      await flush()
    },
    /** The cloud client (re)connects: apps still missing their first token retry at once. */
    async redrive() {
      host.redriveMiniappAuthDelivery()
      await flush()
    },
    /** The miniapp becomes the visible one (or, with null, none is). */
    async show(packageName: string | null) {
      visible = packageName
      host.updateVisibility()
      await flush()
    },
    register,
  }
}

const fails =
  (message: string): Plan =>
  () =>
    Promise.reject(new Error(message))

/** A token request the test answers itself, when and as it likes. */
function pending() {
  let resolve!: (token: Token) => void
  let reject!: (error: Error) => void
  const promise = new Promise<Token>((res, rej) => {
    resolve = res
    reject = rej
  })
  const plan: Plan = () => promise
  return {plan, resolve, reject}
}

describe("a miniapp that connects", () => {
  test("is handed a token minted now, not a cached one", async () => {
    const f = fixture()
    await f.connect()

    expect(f.requests).toEqual([{packageName: CALL, opts: {fresh: true}}])
    expect(f.delivered()).toEqual(["token-1"])
  })

  test("two opens within an hour get two tokens", async () => {
    const f = fixture()
    await f.connect()
    await f.advance(10 * 60_000)
    await f.connect()

    expect(f.requests.map((request) => request.opts)).toEqual([{fresh: true}, {fresh: true}])
    expect(f.delivered()).toEqual(["token-1", "token-2"])
  })

  test("arms the scheduled refresh for the token's own expiry", async () => {
    const f = fixture()
    await f.connect()

    expect(f.armed()).toEqual([HOUR_MS - HEADROOM_MS])
  })

  test("asks for a token marked as a local build's when it runs a local or development build", async () => {
    const f = fixture()
    f.localBuilds.add(CALL)
    await f.connect()
    await f.askForRefresh(60_000)

    expect(f.requests).toEqual([
      {packageName: CALL, opts: {fresh: true, localBuild: true}},
      {packageName: CALL, opts: {minTtlMs: 60_000, localBuild: true}},
    ])
  })

  test("asks for its package's ordinary token otherwise", async () => {
    const f = fixture()
    f.localBuilds.add("com.example.other")
    await f.connect()

    expect(f.requests).toEqual([{packageName: CALL, opts: {fresh: true}}])
  })
})

describe("the scheduled refresh before expiry", () => {
  test("delivers a new token and re-arms for the new expiry, not every few seconds", async () => {
    const f = fixture()
    await f.connect()

    await f.advance(HOUR_MS - HEADROOM_MS)

    expect(f.requests.map((request) => request.opts?.fresh)).toEqual([true, true])
    expect(f.delivered()).toEqual(["token-1", "token-2"])
    expect(f.armed()).toEqual([HOUR_MS - HEADROOM_MS])
    expect(f.armed()[0]).toBeGreaterThan(MIN_DELAY_MS)

    // Nothing more goes out until the new token's own refresh falls due.
    await f.advance(HOUR_MS - HEADROOM_MS - 1_000)
    expect(f.requests).toHaveLength(2)
    await f.advance(1_000)
    expect(f.requests).toHaveLength(3)
    expect(f.delivered()).toEqual(["token-1", "token-2", "token-3"])
  })

  test("does not hand the same token back and re-send it", async () => {
    const f = fixture()
    await f.connect()

    await f.advance(HOUR_MS - HEADROOM_MS + 5 * MIN_DELAY_MS)

    expect(new Set(f.delivered()).size).toBe(f.delivered().length)
    expect(f.requests).toHaveLength(2)
  })

  test("a failed refresh is logged and keeps the token the miniapp has", async () => {
    const f = fixture()
    await f.connect()
    f.plan(fails("offline"))

    await f.advance(HOUR_MS - HEADROOM_MS)

    expect(f.warnings.some((warning) => warning.includes("auth refresh failed"))).toBe(true)
    expect(f.delivered()).toEqual(["token-1"])
  })

  test("a failed refresh is tried again with the existing backoff until a new token lands", async () => {
    const f = fixture()
    await f.connect()
    f.plan(fails("offline"), fails("offline"), fails("offline"))

    await f.advance(HOUR_MS - HEADROOM_MS)
    expect(f.armed()).toEqual([RETRY_BASE_MS])
    await f.advance(RETRY_BASE_MS)
    expect(f.armed()).toEqual([RETRY_BASE_MS * 2])
    await f.advance(RETRY_BASE_MS * 2)
    expect(f.armed()).toEqual([RETRY_BASE_MS * 4])
    await f.advance(RETRY_BASE_MS * 4)

    // Every attempt asks for a new token: the cached one is the token being replaced.
    expect(f.requests.map((request) => request.opts?.fresh)).toEqual([true, true, true, true, true])
    expect(f.delivered()).toEqual(["token-1", "token-2"])
    expect(f.armed()).toEqual([HOUR_MS - HEADROOM_MS])
  })

  test("backs off no further than the cap", async () => {
    const f = fixture()
    await f.connect()
    f.plan(...Array.from({length: 7}, () => fails("offline")))

    await f.advance(HOUR_MS - HEADROOM_MS)
    const delays: number[] = []
    for (let i = 0; i < 6; i++) {
      delays.push(...f.armed())
      await f.advance(f.armed()[0])
    }

    expect(delays).toEqual([1_000, 2_000, 4_000, 8_000, RETRY_MAX_MS, RETRY_MAX_MS])
  })

  test("a retry waiting to run gives way to a token that arrives first", async () => {
    const f = fixture()
    await f.connect()
    f.plan(fails("offline"))
    await f.advance(HOUR_MS - HEADROOM_MS)
    expect(f.armed()).toEqual([RETRY_BASE_MS])

    await f.show(CALL)

    expect(f.delivered()).toEqual(["token-1", "token-2"])
    expect(f.armed()).toEqual([HOUR_MS - HEADROOM_MS])
  })

  test("a refresh that fails after the miniapp was replaced starts no retry for the new one", async () => {
    const f = fixture()
    await f.connect()
    const stale = pending()
    f.plan(stale.plan)
    await f.advance(HOUR_MS - HEADROOM_MS)

    await f.connect()
    stale.reject(new Error("offline"))
    await flush()

    expect(f.delivered()).toEqual(["token-1", "token-2"])
    expect(f.armed()).toEqual([HOUR_MS - HEADROOM_MS])
  })
})

describe("a miniapp that comes to the foreground", () => {
  test("is handed a token minted now, after the visibility change", async () => {
    const f = fixture()
    await f.connect()

    await f.show(CALL)

    expect(f.visibility).toEqual([[CALL, "foreground"]])
    expect(f.requests.map((request) => request.opts)).toEqual([{fresh: true}, {fresh: true}])
    expect(f.delivered()).toEqual(["token-1", "token-2"])
  })

  test("re-arms the scheduled refresh for the new token only", async () => {
    const f = fixture()
    await f.connect()
    await f.advance(20 * 60_000)

    await f.show(CALL)

    expect(f.armed()).toEqual([HOUR_MS - HEADROOM_MS])
  })

  test("is handed a new token each time it returns", async () => {
    const f = fixture()
    await f.connect()

    await f.show(CALL)
    await f.show(null)
    await f.show(CALL)

    expect(f.delivered()).toEqual(["token-1", "token-2", "token-3"])
  })

  test("is not handed another token while the first is still on its way", async () => {
    const f = fixture()
    let release!: (token: Token) => void
    f.plan(() => new Promise<Token>((resolve) => (release = resolve)))
    await f.connect()

    await f.show(CALL)
    expect(f.requests).toHaveLength(1)

    release({token: "token-1", expiresAt: f.now() + HOUR_MS})
    await flush()
    expect(f.requests).toHaveLength(1)
    expect(f.delivered()).toEqual(["token-1"])
  })

  test("leaves the miniapp it moves away from alone", async () => {
    const f = fixture()
    await f.connect()
    await f.show(CALL)
    f.requests.length = 0

    await f.show(null)

    expect(f.visibility.at(-1)).toEqual([CALL, "background"])
    expect(f.requests).toHaveLength(0)
  })

  test("does nothing when the visible miniapp has not changed", async () => {
    const f = fixture()
    await f.connect()
    await f.show(CALL)
    f.requests.length = 0

    await f.show(CALL)

    expect(f.requests).toHaveLength(0)
  })

  test("is left to its own CONNECT when it has not connected yet", async () => {
    const f = fixture()
    f.register()

    await f.show(CALL)

    expect(f.requests).toHaveLength(0)
  })

  test("keeps the token it has when the mint fails", async () => {
    const f = fixture()
    await f.connect()
    f.plan(fails("offline"))

    await f.show(CALL)

    expect(f.warnings.some((warning) => warning.includes("auth refresh failed"))).toBe(true)
    expect(f.delivered()).toEqual(["token-1"])
    expect(f.armed()).toEqual([HOUR_MS - HEADROOM_MS])
  })
})

describe("a mint that fails when the miniapp connects", () => {
  test("is retried with the existing backoff, through the default path after the first fresh request", async () => {
    const f = fixture()
    f.plan(fails("not ready"), fails("not ready"), fails("not ready"))
    await f.connect()

    expect(f.armed()).toEqual([RETRY_BASE_MS])
    await f.advance(RETRY_BASE_MS)
    expect(f.armed()).toEqual([RETRY_BASE_MS * 2])
    await f.advance(RETRY_BASE_MS * 2)
    expect(f.armed()).toEqual([RETRY_BASE_MS * 4])
    await f.advance(RETRY_BASE_MS * 4)

    expect(f.requests.map((request) => request.opts)).toEqual([{fresh: true}, undefined, undefined, undefined])
    expect(f.delivered()).toEqual(["token-1"])
    // The retries are over; only the token's refresh is armed.
    expect(f.armed()).toEqual([HOUR_MS - HEADROOM_MS])
  })

  test("backs off no further than the cap", async () => {
    const f = fixture()
    f.plan(...Array.from({length: 7}, () => fails("not ready")))
    await f.connect()

    const delays: number[] = []
    for (let i = 0; i < 7; i++) {
      delays.push(...f.armed())
      await f.advance(f.armed()[0])
    }

    expect(delays).toEqual([1_000, 2_000, 4_000, 8_000, RETRY_MAX_MS, RETRY_MAX_MS, RETRY_MAX_MS])
  })

  test("with a still-valid cached token, delivers it on the first retry", async () => {
    const f = fixture()
    await f.connect()
    await f.advance(10 * 60_000)
    f.plan(fails("Core is down"))

    await f.connect()
    // The fresh mint failed and nothing has been delivered for this open yet.
    expect(f.delivered()).toEqual(["token-1"])
    expect(f.armed()).toEqual([RETRY_BASE_MS])

    await f.advance(RETRY_BASE_MS)

    expect(f.requests.map((request) => request.opts)).toEqual([{fresh: true}, {fresh: true}, undefined])
    expect(f.delivered()).toEqual(["token-1", "token-1"])
    // No more retries; the refresh is armed for the cached token's own expiry.
    expect(f.armed()).toEqual([HOUR_MS - HEADROOM_MS - 10 * 60_000 - RETRY_BASE_MS])
  })

  test("with a cached token, the refresh that follows is still fresh", async () => {
    const f = fixture()
    await f.connect()
    f.plan(fails("Core is down"))
    await f.connect()
    await f.advance(RETRY_BASE_MS)

    await f.advance(f.armed()[0])

    expect(f.requests.at(-1)?.opts).toEqual({fresh: true})
    expect(f.delivered().at(-1)).toBe("token-2")
  })

  test("with a cached token that is about to expire, the retry mints", async () => {
    const f = fixture()
    await f.connect()
    // Every refresh failed, so the cached token ran down into the cloud client's expiry margin, where the default
    // path no longer serves it.
    f.setCoreDown(true)
    await f.advance(HOUR_MS - CACHE_MARGIN_MS / 2)
    expect(f.delivered()).toEqual(["token-1"])

    f.plan(fails("Core is down"))
    f.setCoreDown(false)
    await f.connect()
    await f.advance(RETRY_BASE_MS)

    expect(f.requests.at(-1)?.opts).toBeUndefined()
    expect(f.delivered().at(-1)).toBe("token-2")
  })

  test("the reconnect redrive also takes the default path, delivering a valid cached token", async () => {
    const f = fixture()
    await f.connect()
    f.plan(fails("Core is down"))
    await f.connect()
    expect(f.armed()).toEqual([RETRY_BASE_MS])

    await f.redrive()

    expect(f.requests.map((request) => request.opts)).toEqual([{fresh: true}, {fresh: true}, undefined])
    expect(f.delivered()).toEqual(["token-1", "token-1"])
    // The redrive took over from the pending retry.
    expect(f.armed()).toEqual([HOUR_MS - HEADROOM_MS])
  })

  test("the reconnect redrive with no cached token mints", async () => {
    const f = fixture()
    f.plan(fails("Core is down"))
    await f.connect()

    await f.redrive()

    expect(f.requests.map((request) => request.opts)).toEqual([{fresh: true}, undefined])
    expect(f.delivered()).toEqual(["token-1"])
  })
})

describe("a miniapp that connects again while an earlier token request is out", () => {
  // The purchase happens between the two opens: request A was made before it and request B after it.
  const before = (f: ReturnType<typeof fixture>): Token => ({token: "before-purchase", expiresAt: f.now() + HOUR_MS})
  const after = (f: ReturnType<typeof fixture>): Token => ({
    token: "after-purchase",
    expiresAt: f.now() + HOUR_MS + 10 * 60_000,
  })

  test("a replaced miniapp gets the token minted for its own open, not the older answer", async () => {
    const f = fixture()
    const a = pending()
    const b = pending()
    f.plan(a.plan, b.plan)
    await f.connect()
    await f.connect()

    a.resolve(before(f))
    await flush()
    b.resolve(after(f))
    await flush()

    expect(f.delivered()).toEqual(["after-purchase"])
    expect(f.armed()).toEqual([HOUR_MS + 10 * 60_000 - HEADROOM_MS])
  })

  test("the same WebView sending CONNECT again gets the token minted for its second open", async () => {
    const f = fixture()
    const a = pending()
    const b = pending()
    f.plan(a.plan, b.plan)
    await f.connect()
    await f.connectAgain()

    a.resolve(before(f))
    await flush()
    b.resolve(after(f))
    await flush()

    expect(f.delivered()).toEqual(["after-purchase"])
    expect(f.armed()).toEqual([HOUR_MS + 10 * 60_000 - HEADROOM_MS])
  })

  test("the older answer arriving last changes nothing", async () => {
    const f = fixture()
    const a = pending()
    const b = pending()
    f.plan(a.plan, b.plan)
    await f.connect()
    await f.connect()

    b.resolve(after(f))
    await flush()
    a.resolve(before(f))
    await flush()

    expect(f.delivered()).toEqual(["after-purchase"])
    expect(f.armed()).toEqual([HOUR_MS + 10 * 60_000 - HEADROOM_MS])
  })

  test("an older request that fails starts no retry for the later open", async () => {
    const f = fixture()
    const a = pending()
    const b = pending()
    f.plan(a.plan, b.plan)
    await f.connect()
    await f.connectAgain()

    a.reject(new Error("offline"))
    await flush()
    expect(f.armed()).toEqual([])

    b.resolve(after(f))
    await flush()
    expect(f.requests).toHaveLength(2)
    expect(f.delivered()).toEqual(["after-purchase"])
  })

  test("a reconnect redrive leaves the open alone while its fresh request is still out", async () => {
    const f = fixture()
    await f.connect()
    const fresh = pending()
    f.plan(fresh.plan)
    await f.connect()

    await f.redrive()
    expect(f.requests.map((request) => request.opts)).toEqual([{fresh: true}, {fresh: true}])

    fresh.resolve(after(f))
    await flush()
    expect(f.delivered()).toEqual(["token-1", "after-purchase"])
  })

  test("a reconnect redrive still takes over once that request has failed", async () => {
    const f = fixture()
    await f.connect()
    const fresh = pending()
    f.plan(fresh.plan)
    await f.connect()
    fresh.reject(new Error("not ready"))
    await flush()
    expect(f.armed()).toEqual([RETRY_BASE_MS])

    await f.redrive()

    expect(f.requests.map((request) => request.opts)).toEqual([{fresh: true}, {fresh: true}, undefined])
    expect(f.delivered()).toEqual(["token-1", "token-1"])
  })

  test("a refresh the miniapp asked for is answered with an error, not the older token, once it has reconnected", async () => {
    const f = fixture()
    await f.connect()
    const stale = pending()
    f.plan(stale.plan)
    await f.askForRefresh()

    await f.connectAgain()
    expect(f.delivered()).toEqual(["token-1", "token-2"])
    stale.resolve(before(f))
    await flush()

    expect(f.results).toHaveLength(1)
    expect(f.results[0]).toMatchObject({requestId: "req-refresh", ok: false})
    expect(f.results[0].auth).toBeUndefined()
    expect(f.delivered()).toEqual(["token-1", "token-2"])
    expect(f.armed()).toEqual([HOUR_MS - HEADROOM_MS])
  })

  test("a refresh the miniapp asked for is answered with the token and the update when nothing intervened", async () => {
    const f = fixture()
    await f.connect()

    await f.askForRefresh()

    expect(f.results).toEqual([{requestId: "req-refresh", ok: true, auth: expect.objectContaining({token: "token-1"})}])
    expect(f.delivered()).toEqual(["token-1", "token-1"])
  })

  test("a foreground refresh that is still out when the miniapp is replaced is not handed to the new one", async () => {
    const f = fixture()
    await f.connect()
    const stale = pending()
    f.plan(stale.plan)
    await f.show(CALL)

    await f.connect()
    expect(f.delivered()).toEqual(["token-1", "token-2"])
    stale.resolve(before(f))
    await flush()

    expect(f.delivered()).toEqual(["token-1", "token-2"])
    expect(f.armed()).toEqual([HOUR_MS - HEADROOM_MS])
  })
})