@mentra/miniapp 3.3.0-beta.1018 → 3.3.0-beta.1021

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/session.ts CHANGED
@@ -171,6 +171,17 @@ export class NotConnectedError extends Error {
171
171
  }
172
172
  }
173
173
 
174
+ /**
175
+ * @internal — `connect()` rejects with this when the host did not answer CONNECT
176
+ * within `connectTimeoutMs`. The session stays usable: `connect()` sends CONNECT again.
177
+ */
178
+ export class ConnectAckTimeoutError extends Error {
179
+ constructor() {
180
+ super("MiniappSession: CONNECT_ACK timeout")
181
+ this.name = "ConnectAckTimeoutError"
182
+ }
183
+ }
184
+
174
185
  export interface MiniappRequestError {
175
186
  code: string
176
187
  message: string
@@ -189,6 +200,8 @@ interface PendingRequest {
189
200
  }
190
201
 
191
202
  const DEFAULT_CONNECT_TIMEOUT_MS = 10_000
203
+ /** Pause before a `registerMiniapp` session sends CONNECT again after a CONNECT_ACK timeout. */
204
+ const CONNECT_RETRY_MS = 1_000
192
205
 
193
206
  // Hard ceiling on how long a single bridge request waits for the host's
194
207
  // REQUEST_RESULT. Without it, a host that never responds (a hung cloud call, a
@@ -315,11 +328,26 @@ export class MiniappSession<TChannels extends object = any> {
315
328
 
316
329
  /**
317
330
  * Outbound queue for anything sent before CONNECT_ACK. Flushed in FIFO order
318
- * once the phone responds with CONNECT_ACK.
331
+ * once the phone responds with CONNECT_ACK. A queued request carries its id so
332
+ * one that has already been rejected is dropped instead of sent.
319
333
  */
320
- private readonly outboundQueue: string[] = []
334
+ private readonly outboundQueue: Array<{raw: string; requestId?: string}> = []
321
335
  private readonly pendingRequests = new Map<string, PendingRequest>()
336
+ /** In flight or succeeded. A failed attempt clears it so `connect()` can send CONNECT again. */
322
337
  private connectPromise: Promise<void> | null = null
338
+ /**
339
+ * Set by the first CONNECT_ACK and never cleared: the handshake completes once
340
+ * per session. The host answers every CONNECT, so after a retry the ACK for
341
+ * another CONNECT of this session can still arrive, in either order. Unlike
342
+ * `ready`, this survives a transport drop, which a session does not recover from.
343
+ */
344
+ private handshakeComplete = false
345
+ /** Rejects the handshake in flight. Set only while waiting for CONNECT_ACK. */
346
+ private failHandshake: ((error: Error) => void) | null = null
347
+ /** Set by `registerMiniapp`: a CONNECT_ACK timeout sends CONNECT again instead of failing `connect()`. */
348
+ private retryHandshake = false
349
+ /** Ends the pause before CONNECT is sent again, with the failure that ended it if any. Set only during that pause. */
350
+ private endRetryPause: ((failure?: Error) => void) | null = null
323
351
  private disposed = false
324
352
  /**
325
353
  * Set by `registerMiniapp` to the host's id for this spawn: CONNECT tells the
@@ -458,52 +486,158 @@ export class MiniappSession<TChannels extends object = any> {
458
486
  // -------------------------------------------------------------------------
459
487
 
460
488
  /**
461
- * Connect to LocalMiniappRuntime. Idempotent — calling multiple times
462
- * returns the same Promise.
489
+ * Connect to LocalMiniappRuntime. Idempotent while a handshake is in flight
490
+ * or has succeeded: repeat calls return the same Promise. A failed attempt
491
+ * (CONNECT_ACK timeout, transport failure) does not stick, so a later call
492
+ * sends CONNECT again. A session started by `registerMiniapp` keeps sending
493
+ * CONNECT after a timeout, so this Promise (and `waitForReady()`) settles
494
+ * only when the host answers, the transport fails, or the session ends.
463
495
  */
464
496
  connect(): Promise<void> {
465
497
  if (this.disposed) {
466
498
  return Promise.reject(new NotConnectedError("MiniappSession was disposed"))
467
499
  }
468
500
  if (this.connectPromise) return this.connectPromise
501
+ // A CONNECT_ACK that arrived after an earlier attempt timed out still completed the handshake.
502
+ if (this.handshakeComplete) {
503
+ this.connectPromise = Promise.resolve()
504
+ return this.connectPromise
505
+ }
506
+
507
+ const attempt = this.retryHandshake ? this.connectUntilAcknowledged() : this.sendConnect()
508
+ this.connectPromise = attempt
509
+ attempt.catch(() => {
510
+ // Registered before the caller's handlers, so a retry from a rejection handler sends CONNECT again.
511
+ if (this.connectPromise === attempt) this.connectPromise = null
512
+ })
513
+ return attempt
514
+ }
515
+
516
+ /**
517
+ * @internal — called by `registerMiniapp` before its handler runs. The host
518
+ * owns this context's lifetime, so a host that has not answered CONNECT is
519
+ * stalled rather than gone: send CONNECT again instead of failing.
520
+ */
521
+ retryHandshakeOnTimeout(): void {
522
+ this.retryHandshake = true
523
+ }
524
+
525
+ private async connectUntilAcknowledged(): Promise<void> {
526
+ for (;;) {
527
+ try {
528
+ await this.sendConnect()
529
+ return
530
+ } catch (err) {
531
+ if (this.disposed || !(err instanceof ConnectAckTimeoutError)) throw err
532
+ }
533
+ // eslint-disable-next-line no-console
534
+ console.warn("[mentra-miniapp] CONNECT_ACK timed out; sending CONNECT again")
535
+ const failure = await this.pauseBeforeRetry()
536
+ if (failure) throw failure
537
+ // The CONNECT_ACK for an earlier CONNECT can still land during the pause.
538
+ if (this.handshakeComplete) return
539
+ if (this.disposed) throw new NotConnectedError("MiniappSession: connect aborted")
540
+ }
541
+ }
469
542
 
543
+ /**
544
+ * Resolves after CONNECT_RETRY_MS, or as soon as CONNECT_ACK lands or the
545
+ * session ends. Resolves with the error when the transport failed meanwhile.
546
+ */
547
+ private pauseBeforeRetry(): Promise<Error | undefined> {
548
+ return new Promise<Error | undefined>((resolve) => {
549
+ const end = (failure?: Error) => {
550
+ clearTimeout(timer)
551
+ this.emitter.off("ready", onReady)
552
+ if (this.endRetryPause === end) this.endRetryPause = null
553
+ resolve(failure)
554
+ }
555
+ const onReady = () => end()
556
+ const timer = setTimeout(end, CONNECT_RETRY_MS)
557
+ this.emitter.on("ready", onReady)
558
+ this.endRetryPause = end
559
+ })
560
+ }
561
+
562
+ /** Send one CONNECT and wait for its CONNECT_ACK. */
563
+ private sendConnect(): Promise<void> {
564
+ // Only a host that received CONNECT can be waited out. Before that, the transport is what failed.
565
+ let connectSent = false
566
+ // This attempt's own outcome. A slow open() can finish after a newer attempt
567
+ // took over, so nothing below acts through the session-wide failHandshake.
568
+ let attemptSettled = false
569
+ let failAttempt: (error: Error) => void = () => {}
470
570
  // Register the readiness listener BEFORE any awaits so that a synchronous
471
571
  // CONNECT_ACK delivery in tests (or the phone) can't race the subscription.
472
572
  const readyPromise = new Promise<void>((resolve, reject) => {
573
+ const settle = (error?: Error) => {
574
+ if (attemptSettled) return
575
+ attemptSettled = true
576
+ clearTimeout(timer)
577
+ this.emitter.off("ready", onReady)
578
+ this.emitter.off("error", onError)
579
+ if (this.failHandshake === onError) this.failHandshake = null
580
+ if (error) reject(error)
581
+ else resolve()
582
+ }
583
+ const onReady = () => settle()
584
+ const onError = (error: Error) => settle(error)
473
585
  const timer = setTimeout(() => {
474
- const err = new Error("MiniappSession: CONNECT_ACK timeout")
586
+ const err = connectSent
587
+ ? new ConnectAckTimeoutError()
588
+ : new Error("MiniappSession: transport did not open before the CONNECT_ACK timeout")
589
+ // Settled before the public emit, so a throwing "error" listener cannot leave it pending.
590
+ settle(err)
591
+ // Requests queued for a retried handshake wait for it, bounded by their own timeouts.
592
+ if (connectSent && this.retryHandshake) return
475
593
  this.failAllPending({code: MiniappErrorCode.NOT_CONNECTED, message: err.message})
476
594
  this.emitter.emit("error", err)
477
- reject(err)
478
595
  }, this.connectTimeoutMs)
479
-
480
- this.emitter.once("ready", () => {
481
- clearTimeout(timer)
482
- resolve()
483
- })
484
- this.emitter.once("error", (err) => {
485
- clearTimeout(timer)
486
- reject(err)
487
- })
596
+ this.emitter.on("ready", onReady)
597
+ this.emitter.on("error", onError)
598
+ this.failHandshake = onError
599
+ failAttempt = onError
488
600
  })
489
-
490
- this.connectPromise = (async () => {
491
- this.transport.onMessage((raw) => this.handleIncoming(raw))
492
- this.transport.onDisconnect((reason) => this.handleTransportDisconnect(reason))
493
- await this.transport.open()
494
-
495
- const requestId = makeRequestId()
496
- const connectPayload = {
497
- type: MiniappRequestType.CONNECT,
498
- packageName: this.packageName,
499
- ...(this.initSessionId !== null ? {initReady: true, sessionId: this.initSessionId} : {}),
601
+ // Settles once CONNECT is sent, or rejects if opening or sending fails.
602
+ const sent = (async () => {
603
+ try {
604
+ this.transport.onMessage((raw) => this.handleIncoming(raw))
605
+ this.transport.onDisconnect((reason) => this.handleTransportDisconnect(reason))
606
+ // An open transport stays as it is: a retried handshake only sends CONNECT again.
607
+ const opening = this.transport.isOpen() ? Promise.resolve() : this.transport.open()
608
+ // An open that finishes after disconnect() must not leave the transport open.
609
+ opening.then(
610
+ () => {
611
+ if (this.disposed) this.transport.close()
612
+ },
613
+ () => {},
614
+ )
615
+ await opening
616
+ // Settled while opening: failed (the timeout, disconnect(), a transport drop),
617
+ // or completed by an earlier CONNECT's ACK. Either way, send nothing.
618
+ if (attemptSettled) return
619
+ if (this.disposed) throw new NotConnectedError("MiniappSession: connect aborted")
620
+
621
+ const requestId = makeRequestId()
622
+ const connectPayload = {
623
+ type: MiniappRequestType.CONNECT,
624
+ packageName: this.packageName,
625
+ ...(this.initSessionId !== null ? {initReady: true, sessionId: this.initSessionId} : {}),
626
+ }
627
+ connectSent = true
628
+ this.transport.send(serializeEnvelope({payload: connectPayload, requestId}))
629
+ } catch (err) {
630
+ // Already reported through readyPromise; a newer attempt may own the session now.
631
+ if (attemptSettled) return
632
+ const error = err instanceof Error ? err : new Error(String(err))
633
+ if (!this.disposed) this.failAllPending({code: MiniappErrorCode.NOT_CONNECTED, message: error.message})
634
+ failAttempt(error)
635
+ throw error
500
636
  }
501
- this.transport.send(serializeEnvelope({payload: connectPayload, requestId}))
502
-
503
- await readyPromise
504
637
  })()
505
-
506
- return this.connectPromise
638
+ // The handshake can fail while the transport is still opening (disconnect(),
639
+ // the timeout): the attempt settles then, without waiting for open().
640
+ return Promise.all([sent, readyPromise]).then(() => undefined)
507
641
  }
508
642
 
509
643
  /**
@@ -534,6 +668,10 @@ export class MiniappSession<TChannels extends object = any> {
534
668
  disconnect(): void {
535
669
  if (this.disposed) return
536
670
  this.disposed = true
671
+ // End a handshake still waiting for CONNECT_ACK. Its timer would otherwise
672
+ // report a timeout for a session that no longer exists.
673
+ this.failHandshake?.(new NotConnectedError("MiniappSession: connect aborted"))
674
+ this.endRetryPause?.()
537
675
  // Give listeners one synchronous chance to flush final messages
538
676
  // (e.g. display.render([])) before we tear down the transport.
539
677
  try {
@@ -602,7 +740,7 @@ export class MiniappSession<TChannels extends object = any> {
602
740
  reject,
603
741
  timer,
604
742
  })
605
- this.enqueueOrSend(serializeEnvelope(envelope))
743
+ this.enqueueOrSend(serializeEnvelope(envelope), requestId)
606
744
  })
607
745
  }
608
746
 
@@ -647,7 +785,7 @@ export class MiniappSession<TChannels extends object = any> {
647
785
  // Internal — transport glue
648
786
  // -------------------------------------------------------------------------
649
787
 
650
- private enqueueOrSend(raw: string): void {
788
+ private enqueueOrSend(raw: string, requestId?: string): void {
651
789
  if (this.ready) {
652
790
  try {
653
791
  this.transport.send(raw)
@@ -657,12 +795,15 @@ export class MiniappSession<TChannels extends object = any> {
657
795
  }
658
796
  return
659
797
  }
660
- this.outboundQueue.push(raw)
798
+ this.outboundQueue.push(requestId === undefined ? {raw} : {raw, requestId})
661
799
  }
662
800
 
663
801
  private flushQueue(): void {
664
802
  const queue = this.outboundQueue.splice(0)
665
- for (const raw of queue) {
803
+ for (const {raw, requestId} of queue) {
804
+ // Rejected while waiting for the handshake (a CONNECT_ACK timeout or its own
805
+ // timeout). Its caller has seen the failure, so the host must not run it.
806
+ if (requestId !== undefined && !this.pendingRequests.has(requestId)) continue
666
807
  try {
667
808
  this.transport.send(raw)
668
809
  } catch (err) {
@@ -680,6 +821,10 @@ export class MiniappSession<TChannels extends object = any> {
680
821
 
681
822
  switch (type) {
682
823
  case MiniappResponseType.CONNECT_ACK: {
824
+ // The answer to another CONNECT of this session (a retry, or one whose
825
+ // attempt timed out). Applying it would run the handshake again: emit
826
+ // "ready" twice and replace state that later updates may have changed.
827
+ if (this.handshakeComplete) return
683
828
  const ack = payload as unknown as ConnectAckPayload
684
829
  this.userId = ack.userId ?? ""
685
830
  if (ack.packageName) this.packageName = ack.packageName
@@ -698,6 +843,7 @@ export class MiniappSession<TChannels extends object = any> {
698
843
  // that don't send `permissions` leave the all-false default in place
699
844
  // — `hasPermission` getters will simply return false.
700
845
  if (ack.permissions) this.applyPermissions(ack.permissions)
846
+ this.handshakeComplete = true
701
847
  this.ready = true
702
848
  this.flushQueue()
703
849
  this.emitter.emit("ready")
@@ -912,6 +1058,11 @@ export class MiniappSession<TChannels extends object = any> {
912
1058
 
913
1059
  private handleTransportDisconnect(reason: string): void {
914
1060
  this.ready = false
1061
+ // A transport that drops during the handshake has failed it. Sending CONNECT
1062
+ // again over a dead bridge would keep that failure from the host.
1063
+ const failure = new Error(`MiniappSession: transport disconnected: ${reason}`)
1064
+ this.failHandshake?.(failure)
1065
+ this.endRetryPause?.(failure)
915
1066
  this.failAllPending({code: MiniappErrorCode.NOT_CONNECTED, message: `Transport disconnected: ${reason}`})
916
1067
  this.emitter.emit("disconnect", reason)
917
1068
  }
@@ -84,6 +84,11 @@ class LocalSocketWithMockFallback implements Transport {
84
84
  constructor(private readonly options: LocalSocketTransportOptions) {}
85
85
 
86
86
  async open(): Promise<void> {
87
+ // A retried handshake opens again: keep the transport already selected.
88
+ if (this.active?.isOpen()) return
89
+ // One that dropped is replaced, so it cannot keep delivering to the handlers.
90
+ this.active?.close()
91
+ this.active = null
87
92
  const local = new LocalSocketTransport(this.options)
88
93
  let timedOut = false
89
94
  const timeout = new Promise<void>((_, reject) => {
@@ -43,6 +43,8 @@ export class DispatchTransport implements Transport {
43
43
  private messageHandler: TransportMessageHandler | null = null
44
44
  private disconnectHandler: TransportDisconnectHandler | null = null
45
45
  private open_ = false
46
+ /** The delivery hook this transport installed; another transport may own the global later. */
47
+ private deliverHook: ((raw: string) => void) | null = null
46
48
 
47
49
  /** True iff `__dispatch` is bound on the current globalThis. */
48
50
  static isAvailable(): boolean {
@@ -57,9 +59,10 @@ export class DispatchTransport implements Transport {
57
59
  // route bridge frames here. Installed lazily so multiple transports
58
60
  // can share the same global if a test spins up two.
59
61
  const g = globalThis as unknown as BridgeDeliverGlobal
60
- g.__mentraDeliverBridgeRaw = (raw: string) => {
62
+ this.deliverHook = (raw: string) => {
61
63
  if (this.messageHandler) this.messageHandler(raw)
62
64
  }
65
+ g.__mentraDeliverBridgeRaw = this.deliverHook
63
66
  this.open_ = true
64
67
  }
65
68
 
@@ -95,9 +98,11 @@ export class DispatchTransport implements Transport {
95
98
  close(): void {
96
99
  this.open_ = false
97
100
  const g = globalThis as unknown as BridgeDeliverGlobal
98
- if (g.__mentraDeliverBridgeRaw) {
101
+ // A replacement session's transport may have installed its own hook since.
102
+ if (this.deliverHook && g.__mentraDeliverBridgeRaw === this.deliverHook) {
99
103
  delete g.__mentraDeliverBridgeRaw
100
104
  }
105
+ this.deliverHook = null
101
106
  }
102
107
 
103
108
  isOpen(): boolean {
@@ -20,6 +20,11 @@ const DEFAULT_URL = "ws://127.0.0.1:8765"
20
20
  export class LocalSocketTransport implements Transport {
21
21
  private url: string
22
22
  private ws: WebSocket | null = null
23
+ /**
24
+ * The socket an open() in progress is connecting. A later open() or close()
25
+ * abandons it, so a socket that connects late cannot replace the active one.
26
+ */
27
+ private connecting: WebSocket | null = null
23
28
  private messageHandler: TransportMessageHandler | null = null
24
29
  private disconnectHandler: TransportDisconnectHandler | null = null
25
30
 
@@ -32,9 +37,11 @@ export class LocalSocketTransport implements Transport {
32
37
  if (typeof WebSocket === "undefined") {
33
38
  throw new Error("LocalSocketTransport: browser WebSocket global not available")
34
39
  }
40
+ this.abandonConnecting()
35
41
 
36
42
  await new Promise<void>((resolve, reject) => {
37
43
  const ws = new WebSocket(this.url)
44
+ this.connecting = ws
38
45
  let settled = false
39
46
  const settle = (fn: () => void) => {
40
47
  if (settled) return
@@ -43,6 +50,11 @@ export class LocalSocketTransport implements Transport {
43
50
  }
44
51
 
45
52
  ws.onopen = () => {
53
+ if (this.connecting !== ws) {
54
+ settle(() => reject(new Error("LocalSocketTransport: open was superseded")))
55
+ return
56
+ }
57
+ this.connecting = null
46
58
  this.ws = ws
47
59
  settle(() => resolve())
48
60
  }
@@ -52,11 +64,16 @@ export class LocalSocketTransport implements Transport {
52
64
  )
53
65
  }
54
66
  ws.onmessage = (ev: MessageEvent) => {
67
+ if (this.ws !== ws) return
55
68
  const data = ev.data
56
69
  if (typeof data === "string") this.messageHandler?.(data)
57
70
  }
58
71
  ws.onclose = (ev) => {
59
- if (this.ws === ws) this.ws = null
72
+ if (this.connecting === ws) this.connecting = null
73
+ settle(() => reject(new Error(`LocalSocketTransport: closed before opening: ${ev.code} ${ev.reason}`)))
74
+ // Only the active socket's close is a disconnect; an abandoned one was never in use.
75
+ if (this.ws !== ws) return
76
+ this.ws = null
60
77
  this.disconnectHandler?.(`closed: ${ev.code} ${ev.reason}`)
61
78
  }
62
79
  })
@@ -78,6 +95,7 @@ export class LocalSocketTransport implements Transport {
78
95
  }
79
96
 
80
97
  close(): void {
98
+ this.abandonConnecting()
81
99
  if (!this.ws) return
82
100
  try {
83
101
  this.ws.close()
@@ -90,4 +108,15 @@ export class LocalSocketTransport implements Transport {
90
108
  isOpen(): boolean {
91
109
  return !!this.ws && this.ws.readyState === WebSocket.OPEN
92
110
  }
111
+
112
+ private abandonConnecting(): void {
113
+ const ws = this.connecting
114
+ this.connecting = null
115
+ if (!ws) return
116
+ try {
117
+ ws.close()
118
+ } catch {
119
+ // ignore
120
+ }
121
+ }
93
122
  }
@@ -12,7 +12,10 @@ export type TransportMessageHandler = (raw: string) => void
12
12
  export type TransportDisconnectHandler = (reason: string) => void
13
13
 
14
14
  export interface Transport {
15
- /** Establish whatever connection the transport needs. May be a no-op. */
15
+ /**
16
+ * Establish whatever connection the transport needs. May be a no-op. Resolves
17
+ * at once when already open: a retried handshake calls it again.
18
+ */
16
19
  open(): Promise<void>
17
20
  /** Send a serialized envelope. */
18
21
  send(raw: string): void