@mentra/engine 3.1.0-dev.10 → 3.1.0-dev.102

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.
Files changed (185) hide show
  1. package/README.md +24 -6
  2. package/build/bluetooth-sdk/ota-transport.d.ts +2 -0
  3. package/build/bluetooth-sdk/ota-transport.d.ts.map +1 -0
  4. package/build/bluetooth-sdk/ota-transport.js +2 -0
  5. package/build/bluetooth-sdk/ota-transport.js.map +1 -0
  6. package/build/engine.d.ts +5 -2
  7. package/build/engine.d.ts.map +1 -1
  8. package/build/facades/ota.d.ts +12 -7
  9. package/build/facades/ota.d.ts.map +1 -1
  10. package/build/facades/ota.js +10 -6
  11. package/build/facades/ota.js.map +1 -1
  12. package/build/facades/pairing.d.ts +4 -0
  13. package/build/facades/pairing.d.ts.map +1 -1
  14. package/build/facades/pairing.js +81 -7
  15. package/build/facades/pairing.js.map +1 -1
  16. package/build/generated/releaseMetadata.js +5 -5
  17. package/build/generated/releaseMetadata.js.map +1 -1
  18. package/build/index.d.ts +3 -3
  19. package/build/index.d.ts.map +1 -1
  20. package/build/index.js +2 -2
  21. package/build/index.js.map +1 -1
  22. package/build/react/MentraLiveOtaFlow.d.ts +8 -2
  23. package/build/react/MentraLiveOtaFlow.d.ts.map +1 -1
  24. package/build/react/MentraLiveOtaFlow.js +256 -354
  25. package/build/react/MentraLiveOtaFlow.js.map +1 -1
  26. package/build/react/index.d.ts +1 -0
  27. package/build/react/index.d.ts.map +1 -1
  28. package/build/react/index.js +1 -0
  29. package/build/react/index.js.map +1 -1
  30. package/build/react/useMentraLiveOta.d.ts +84 -0
  31. package/build/react/useMentraLiveOta.d.ts.map +1 -0
  32. package/build/react/useMentraLiveOta.js +627 -0
  33. package/build/react/useMentraLiveOta.js.map +1 -0
  34. package/build/services/BlobStore.d.ts +2 -0
  35. package/build/services/BlobStore.d.ts.map +1 -1
  36. package/build/services/BlobStore.js +63 -10
  37. package/build/services/BlobStore.js.map +1 -1
  38. package/build/services/DisplayProcessor.d.ts +3 -3
  39. package/build/services/DisplayProcessor.js +3 -3
  40. package/build/services/DisplayProcessor.js.map +1 -1
  41. package/build/services/GlassesStatusProjection.d.ts +15 -2
  42. package/build/services/GlassesStatusProjection.d.ts.map +1 -1
  43. package/build/services/GlassesStatusProjection.js +3 -3
  44. package/build/services/GlassesStatusProjection.js.map +1 -1
  45. package/build/services/HotspotOtaTransport.d.ts.map +1 -1
  46. package/build/services/HotspotOtaTransport.js +8 -7
  47. package/build/services/HotspotOtaTransport.js.map +1 -1
  48. package/build/services/LocalDisplayManager.d.ts +2 -3
  49. package/build/services/LocalDisplayManager.d.ts.map +1 -1
  50. package/build/services/LocalDisplayManager.js +2 -3
  51. package/build/services/LocalDisplayManager.js.map +1 -1
  52. package/build/services/OtaAutoChain.d.ts +9 -2
  53. package/build/services/OtaAutoChain.d.ts.map +1 -1
  54. package/build/services/OtaAutoChain.js +10 -2
  55. package/build/services/OtaAutoChain.js.map +1 -1
  56. package/build/services/OtaInstallCoordinator.d.ts +26 -3
  57. package/build/services/OtaInstallCoordinator.d.ts.map +1 -1
  58. package/build/services/OtaInstallCoordinator.js +35 -13
  59. package/build/services/OtaInstallCoordinator.js.map +1 -1
  60. package/build/services/OtaService.d.ts.map +1 -1
  61. package/build/services/OtaService.js +1 -1
  62. package/build/services/OtaService.js.map +1 -1
  63. package/build/services/OtaUpdateCheckService.d.ts +4 -1
  64. package/build/services/OtaUpdateCheckService.d.ts.map +1 -1
  65. package/build/services/OtaUpdateCheckService.js +21 -5
  66. package/build/services/OtaUpdateCheckService.js.map +1 -1
  67. package/build/services/PhonePhotoCoordinator.js +1 -1
  68. package/build/services/PhonePhotoCoordinator.js.map +1 -1
  69. package/build/services/PhoneStreamCoordinator.d.ts.map +1 -1
  70. package/build/services/PhoneStreamCoordinator.js +9 -6
  71. package/build/services/PhoneStreamCoordinator.js.map +1 -1
  72. package/build/services/StreamLifecycleController.d.ts +3 -3
  73. package/build/services/StreamLifecycleController.js +3 -3
  74. package/build/services/StreamLifecycleController.js.map +1 -1
  75. package/build/services/asg/localNetworkTransport.d.ts.map +1 -1
  76. package/build/services/asg/localNetworkTransport.js +13 -12
  77. package/build/services/asg/localNetworkTransport.js.map +1 -1
  78. package/build/services/glassesClockSync.js +1 -1
  79. package/build/services/glassesClockSync.js.map +1 -1
  80. package/build/services/otaInstallPolicy.d.ts +4 -0
  81. package/build/services/otaInstallPolicy.d.ts.map +1 -1
  82. package/build/services/otaInstallPolicy.js +4 -0
  83. package/build/services/otaInstallPolicy.js.map +1 -1
  84. package/build/services/otaReleaseVersion.d.ts +10 -0
  85. package/build/services/otaReleaseVersion.d.ts.map +1 -0
  86. package/build/services/otaReleaseVersion.js +14 -0
  87. package/build/services/otaReleaseVersion.js.map +1 -0
  88. package/build/stores/appVisibility.d.ts +3 -0
  89. package/build/stores/appVisibility.d.ts.map +1 -0
  90. package/build/stores/appVisibility.js +3 -0
  91. package/build/stores/appVisibility.js.map +1 -0
  92. package/build/stores/apps.d.ts.map +1 -1
  93. package/build/stores/apps.js +7 -1
  94. package/build/stores/apps.js.map +1 -1
  95. package/build/stores/core.d.ts +3 -3
  96. package/build/stores/core.d.ts.map +1 -1
  97. package/build/stores/core.js.map +1 -1
  98. package/build/stores/glasses.d.ts +10 -4
  99. package/build/stores/glasses.d.ts.map +1 -1
  100. package/build/stores/glasses.js.map +1 -1
  101. package/build/types/applet.d.ts +1 -1
  102. package/build/types/applet.js +1 -1
  103. package/build/types/applet.js.map +1 -1
  104. package/build/types/capabilities/even-realities-g1.d.ts.map +1 -1
  105. package/build/types/capabilities/even-realities-g1.js +2 -0
  106. package/build/types/capabilities/even-realities-g1.js.map +1 -1
  107. package/build/types/capabilities/even-realities-g2.d.ts.map +1 -1
  108. package/build/types/capabilities/even-realities-g2.js +2 -0
  109. package/build/types/capabilities/even-realities-g2.js.map +1 -1
  110. package/build/types/capabilities/mentra-display.d.ts.map +1 -1
  111. package/build/types/capabilities/mentra-display.js +2 -0
  112. package/build/types/capabilities/mentra-display.js.map +1 -1
  113. package/build/types/capabilities/mentra-live.d.ts.map +1 -1
  114. package/build/types/capabilities/mentra-live.js +2 -0
  115. package/build/types/capabilities/mentra-live.js.map +1 -1
  116. package/build/types/capabilities/nimo.d.ts +9 -0
  117. package/build/types/capabilities/nimo.d.ts.map +1 -0
  118. package/build/types/capabilities/nimo.js +57 -0
  119. package/build/types/capabilities/nimo.js.map +1 -0
  120. package/build/types/capabilities/none.d.ts.map +1 -1
  121. package/build/types/capabilities/none.js +2 -0
  122. package/build/types/capabilities/none.js.map +1 -1
  123. package/build/types/capabilities/simulated-glasses.d.ts.map +1 -1
  124. package/build/types/capabilities/simulated-glasses.js +2 -0
  125. package/build/types/capabilities/simulated-glasses.js.map +1 -1
  126. package/build/types/capabilities/vuzix-z100.d.ts.map +1 -1
  127. package/build/types/capabilities/vuzix-z100.js +2 -0
  128. package/build/types/capabilities/vuzix-z100.js.map +1 -1
  129. package/build/types/enums.d.ts +2 -1
  130. package/build/types/enums.d.ts.map +1 -1
  131. package/build/types/enums.js +1 -0
  132. package/build/types/enums.js.map +1 -1
  133. package/build/types/hardware.d.ts +3 -2
  134. package/build/types/hardware.d.ts.map +1 -1
  135. package/build/types/hardware.js +3 -1
  136. package/build/types/hardware.js.map +1 -1
  137. package/build/types/index.d.ts +1 -1
  138. package/build/types/index.d.ts.map +1 -1
  139. package/build/types/index.js +1 -1
  140. package/build/types/index.js.map +1 -1
  141. package/build/utils/display/composer/ColumnComposer.d.ts +1 -1
  142. package/build/utils/display/composer/ColumnComposer.js +1 -1
  143. package/build/utils/display/composer/ColumnComposer.js.map +1 -1
  144. package/package.json +13 -6
  145. package/src/bluetooth-sdk/ota-transport.ts +1 -0
  146. package/src/facades/ota.ts +20 -7
  147. package/src/facades/pairing.ts +88 -12
  148. package/src/generated/releaseMetadata.ts +5 -5
  149. package/src/index.ts +3 -0
  150. package/src/react/MentraLiveOtaFlow.tsx +378 -480
  151. package/src/react/index.ts +14 -0
  152. package/src/react/useMentraLiveOta.ts +793 -0
  153. package/src/services/BlobStore.ts +57 -10
  154. package/src/services/DisplayProcessor.ts +3 -3
  155. package/src/services/GlassesStatusProjection.ts +7 -6
  156. package/src/services/HotspotOtaTransport.ts +8 -7
  157. package/src/services/LocalDisplayManager.ts +2 -3
  158. package/src/services/OtaAutoChain.ts +26 -2
  159. package/src/services/OtaInstallCoordinator.ts +37 -13
  160. package/src/services/OtaService.ts +1 -2
  161. package/src/services/OtaUpdateCheckService.ts +26 -8
  162. package/src/services/PhonePhotoCoordinator.ts +1 -1
  163. package/src/services/PhoneStreamCoordinator.ts +10 -6
  164. package/src/services/StreamLifecycleController.ts +3 -3
  165. package/src/services/asg/localNetworkTransport.ts +20 -19
  166. package/src/services/glassesClockSync.ts +1 -1
  167. package/src/services/otaInstallPolicy.ts +4 -0
  168. package/src/services/otaReleaseVersion.ts +22 -0
  169. package/src/stores/appVisibility.ts +3 -0
  170. package/src/stores/apps.ts +7 -1
  171. package/src/stores/core.ts +4 -4
  172. package/src/stores/glasses.ts +13 -6
  173. package/src/types/applet.ts +1 -1
  174. package/src/types/capabilities/even-realities-g1.ts +3 -0
  175. package/src/types/capabilities/even-realities-g2.ts +3 -0
  176. package/src/types/capabilities/mentra-display.ts +3 -0
  177. package/src/types/capabilities/mentra-live.ts +3 -0
  178. package/src/types/capabilities/nimo.ts +59 -0
  179. package/src/types/capabilities/none.ts +3 -0
  180. package/src/types/capabilities/simulated-glasses.ts +3 -0
  181. package/src/types/capabilities/vuzix-z100.ts +3 -0
  182. package/src/types/enums.ts +1 -0
  183. package/src/types/hardware.ts +4 -2
  184. package/src/types/index.ts +1 -0
  185. package/src/utils/display/composer/ColumnComposer.ts +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"PhoneStreamCoordinator.js","sourceRoot":"","sources":["../../src/services/PhoneStreamCoordinator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,OAAO,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ACL,GAAG,SAAS;QACZ,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,SAAS,EAAE,KAAK,CAAC,SAAS;KAC3B,CAAA;AACH,CAAC;AAED,sEAAsE;AACtE,MAAM,CAAC,MAAM,sBAAsB,GAAG,IAAI,sBAAsB,EAAE,CAAA","sourcesContent":["/**\n * PhoneStreamCoordinator — owns all local-miniapp streaming on the phone.\n *\n * Architecture:\n * miniapp → SDK → LocalMiniappRuntime → coordinator\n * coordinator → BluetoothSdk (BLE → glasses publisher)\n * coordinator ↔ cloudStreamApi (managed only, cloud-v2 runtime provisioning)\n * coordinator ↔ StreamLifecycleController (keep-alive heartbeat)\n * coordinator → status listeners → routed back to miniapp(s)\n *\n * Single-stream constraint:\n * At most ONE stream is active across all miniapps. The exception is that\n * multiple miniapps can subscribe to a single managed stream that's already\n * running — Cloudflare muxes one ingest into many viewers, so subscribers\n * share the same playback URLs. Refcounted; teardown happens when the last\n * subscriber releases.\n *\n * Status routing:\n * Glasses publisher status arrives over BLE as `stream_status` events with\n * a `streamId`. The coordinator's `owns(streamId)` lookup lets MantleManager\n * route phone-owned status events here (not to cloud). For managed streams,\n * we additionally poll Cloudflare's live-input status every 5s to surface\n * what the OTHER end of the pipe sees.\n *\n * Important: this is the ONLY place that mints `streamId`s for phone-owned\n * streams. We use a `phone-` prefix so they're trivially distinguishable from\n * cloud-minted IDs in logs and from cloud-SDK app streams that flow through\n * the legacy path.\n */\n\nimport BluetoothSdk from \"@mentra/bluetooth-sdk/internal\"\nimport type {\n KeepAliveAckEvent,\n StreamResolvedConfig,\n StreamStartRequest,\n StreamStatusEvent,\n} from \"@mentra/bluetooth-sdk/internal\"\nimport {isGlassesConnected} from \"./GlassesReadiness\"\nimport {useGlassesStore} from \"../stores/glasses\"\n\nimport {StreamLifecycleController, type LifecycleLogger} from \"./StreamLifecycleController\"\nimport {slimStreamStatusEvent, streamStatusSignature} from \"./slimStreamStatus\"\nimport {\n getManagedStreamStatus,\n provisionManagedStream,\n teardownManagedStream,\n type CloudflareStatus,\n type ProvisionResult,\n type RestreamDestinationInput,\n} from \"./cloudStreamApi\"\n\n/**\n * Default cadence + thresholds. Exposed via {@link CoordinatorTimings} so tests\n * can shorten them; production code should never override these.\n */\nconst DEFAULT_TIMINGS = {\n keepAliveIntervalMs: 15_000,\n ackTimeoutMs: 10_000,\n maxMissedAcks: 3,\n cloudflareStatusPollMs: 5_000,\n // During WHIP startup, probe quickly so readiness is not quantized to the\n // steady-state 5s monitoring cadence. The delay backs off on each miss.\n cloudflareStartupPollInitialMs: 500,\n // Cloudflare typically needs ~5-10s after first frame before HLS is live.\n hlsReadinessInitialDelayMs: 5_000,\n hlsReadinessPollMs: 2_000,\n hlsReadinessMaxAttempts: 30,\n} as const\n\ntype TimingConfig = {[K in keyof typeof DEFAULT_TIMINGS]: number}\nexport type CoordinatorTimings = Partial<TimingConfig>\n\n// Console-backed minimal logger; replaces pino on the phone.\nconst consoleLogger: LifecycleLogger = {\n child: (bindings) => ({\n ...consoleLogger,\n debug: (...args) => console.debug(\"[STREAM]\", bindings, ...args),\n warn: (...args) => console.warn(\"[STREAM]\", bindings, ...args),\n error: (...args) => console.error(\"[STREAM]\", bindings, ...args),\n }),\n debug: (...args) => console.debug(\"[STREAM]\", ...args),\n warn: (...args) => console.warn(\"[STREAM]\", ...args),\n error: (...args) => console.error(\"[STREAM]\", ...args),\n}\n\nexport interface StartUnmanagedOptions {\n streamUrl: string\n video?: StreamStartRequest[\"video\"]\n audio?: StreamStartRequest[\"audio\"]\n sound?: boolean\n /** Optional Bearer token for WHIP Authorization (custom authenticated endpoints). */\n authToken?: string\n}\n\nexport interface StartManagedOptions {\n restreamDestinations?: RestreamDestinationInput[]\n video?: StreamStartRequest[\"video\"]\n audio?: StreamStartRequest[\"audio\"]\n sound?: boolean\n /**\n * Ingest protocol preference — a real latency/durability trade on Cloudflare:\n * - \"srt\" (default): SRT ingest -> LL-HLS playback (~10-20s glass-to-screen),\n * with shareable HLS/DASH URLs and automatic recording.\n * - \"whip\": WebRTC ingest -> WHEP playback (<1s glass-to-screen), but NO\n * HLS/DASH playback and NO recording (Cloudflare limitation; the returned\n * hlsUrl will serve 204 forever).\n * - \"rtmp\": RTMPS ingest over TCP 443 -> HLS playback. Survives networks\n * that drop WHIP/SRT UDP.\n */\n ingest?: \"srt\" | \"whip\" | \"rtmp\"\n}\n\nexport interface StreamPublisherStartResult {\n streamId: string\n status: string\n resolvedConfig?: StreamResolvedConfig\n}\n\nexport interface ManagedStartResult extends StreamPublisherStartResult {\n liveInputId: string\n /** Playback mode this stream supports: \"hls\" (SRT/RTMP ingest — use hlsUrl/\n * dashUrl, recording on) or \"webrtc\" (WHIP ingest — use webrtcUrl/WHEP,\n * sub-second, no HLS, no recording). */\n mode: \"hls\" | \"webrtc\"\n hlsUrl: string\n dashUrl: string\n webrtcUrl?: string\n}\n\nexport type StreamStatusUpdate = {\n streamId: string\n source: \"glasses\" | \"cloudflare\" | \"coordinator\"\n status: string\n data?: Record<string, unknown>\n}\n\nexport type StatusSubscriber = (packageName: string, update: StreamStatusUpdate) => void\n\ninterface UnmanagedEntry {\n kind: \"unmanaged\"\n streamId: string\n packageName: string\n streamUrl: string\n}\n\ninterface ManagedEntry {\n kind: \"managed\"\n streamId: string\n liveInputId: string\n ingestUrl: string\n /** Playback mode the chosen ingest supports: SRT/RTMP feed HLS; WHIP feeds\n * only WHEP. Readiness is gated differently per mode. */\n mode: \"hls\" | \"webrtc\"\n hlsUrl: string\n dashUrl: string\n webrtcUrl?: string\n publisherStart?: StreamPublisherStartResult\n subscribers: Set<string>\n hlsReady: boolean\n hlsReadyResolvers: Array<(result: ManagedStartResult) => void>\n hlsReadyRejecters: Array<(err: Error) => void>\n cloudflareTimer?: ReturnType<typeof setTimeout>\n hlsTimer?: ReturnType<typeof setInterval>\n hlsAttempts: number\n /** Cloudflare status probes made during this stream session. */\n cloudflareAttempts: number\n /** Wall-clock origin for end-to-end managed startup diagnostics. */\n startupStartedAtMs: number\n}\n\ntype Entry = UnmanagedEntry | ManagedEntry\n\nexport class StreamConflictError extends Error {\n constructor(\n public readonly code: string,\n message: string,\n /** Pipeline stage that failed (provision | command | publish | playback). */\n public readonly stage?: string,\n /** Transport in play at the failure (cloud-rest | ble | wifi). */\n public readonly transport?: string,\n ) {\n super(message)\n this.name = \"StreamConflictError\"\n }\n}\n\n/**\n * Fail fast if glasses aren't connected — BEFORE provisioning. Without this a\n * managed start would create a provider live input, fail the BLE command, and\n * tear the input down again: a slow, billable no-op with a confusing error.\n */\nfunction assertGlassesConnected(): void {\n if (!isGlassesConnected(useGlassesStore.getState().connection)) {\n throw new StreamConflictError(\n \"GLASSES_NOT_CONNECTED\",\n \"Glasses are not connected\",\n \"command\",\n \"ble\",\n )\n }\n}\n\nexport class PhoneStreamCoordinator {\n private current: Entry | null = null\n private lifecycle: StreamLifecycleController | null = null\n private statusSubscriber: StatusSubscriber | null = null\n private idCounter = 0\n private readonly timings: TimingConfig\n /**\n * Serializes state transitions (start, stop, teardown). Without it, a\n * second `start*` racing with the first can pass the `this.current === null`\n * pre-check while the first is still awaiting its provision/BLE work, and\n * end up provisioning two separate streams. A teardown racing with a start\n * can clear `current` mid-stop and let the start fire BLE writes that\n * collide with the in-flight stopStream.\n */\n private inFlight: Promise<void> = Promise.resolve()\n /** Drop identical stream_status fanouts within one session. */\n private lastFanoutSignature: string | null = null\n /** Send full resolvedConfig only once per stream session. */\n private resolvedConfigForwarded = false\n\n constructor(timings: CoordinatorTimings = {}) {\n this.timings = {...DEFAULT_TIMINGS, ...timings}\n }\n\n /**\n * Run `work` under the transition lock. Each call awaits the previous\n * transition before re-evaluating preconditions, so e.g. two concurrent\n * `startManaged` calls are observed sequentially.\n */\n private async runExclusive<T>(work: () => Promise<T>): Promise<T> {\n const prev = this.inFlight\n let release!: () => void\n this.inFlight = new Promise<void>((r) => (release = r))\n try {\n await prev\n return await work()\n } finally {\n release()\n }\n }\n\n /**\n * Register the function that routes status updates to miniapps.\n * LocalMiniappRuntime wires this so updates become EVENT envelopes on the\n * `stream_status` stream for every subscribing miniapp.\n */\n setStatusSubscriber(cb: StatusSubscriber): void {\n this.statusSubscriber = cb\n }\n\n /**\n * True when a phone-owned stream currently uses this streamId. For managed\n * streams, all subscribers share the same streamId so a single equality\n * check covers the multi-subscriber case.\n */\n owns(streamId: string): boolean {\n return this.current !== null && this.current.streamId === streamId\n }\n\n /** Report-safe stream ownership snapshot for incident diagnostics. */\n getDiagnosticSnapshot(): Record<string, unknown> {\n if (!this.current) return {active: false}\n return this.current.kind === \"managed\"\n ? {\n active: true,\n kind: this.current.kind,\n streamId: this.current.streamId,\n subscribers: [...this.current.subscribers].sort(),\n mode: this.current.mode,\n playbackReady: this.current.hlsReady,\n }\n : {\n active: true,\n kind: this.current.kind,\n streamId: this.current.streamId,\n ownerPackageName: this.current.packageName,\n }\n }\n\n async startUnmanaged(\n packageName: string,\n opts: StartUnmanagedOptions,\n ): Promise<StreamPublisherStartResult> {\n // Pre-check the obvious-bad input before queueing — the lock is for\n // serializing state transitions, not for validating arguments.\n if (!opts.streamUrl || typeof opts.streamUrl !== \"string\") {\n throw new StreamConflictError(\"STREAM_URL_REQUIRED\", \"streamUrl is required\")\n }\n assertGlassesConnected()\n return this.runExclusive(async () => {\n if (this.current) {\n throw new StreamConflictError(\n \"STREAM_ALREADY_ACTIVE\",\n `A ${this.current.kind} stream is already active. Stop it before starting a new one.`,\n )\n }\n\n const streamId = this.mintId(\"u\")\n const entry: UnmanagedEntry = {\n kind: \"unmanaged\",\n streamId,\n packageName,\n streamUrl: opts.streamUrl,\n }\n // Claim the slot BEFORE the BLE call so a concurrent caller waiting on\n // the lock sees the in-progress entry and rejects with the conflict.\n this.current = entry\n\n try {\n const event = await BluetoothSdk.startExternallyManagedStream({\n type: \"start_stream\",\n streamUrl: opts.streamUrl,\n streamId,\n sound: opts.sound ?? true,\n // The native bridge rejects explicit `undefined` values (\"Value is\n // undefined, expected an Object\") — only include what was provided.\n ...(opts.video !== undefined ? {video: opts.video} : {}),\n ...(opts.audio !== undefined ? {audio: opts.audio} : {}),\n ...(opts.authToken ? {authToken: opts.authToken} : {}),\n })\n const result = publisherStartResult(streamId, event)\n this.startLifecycle(streamId)\n return result\n } catch (err) {\n this.current = null\n throw err\n }\n })\n }\n\n async startManaged(\n packageName: string,\n opts: StartManagedOptions,\n ): Promise<ManagedStartResult> {\n const startupStartedAtMs = Date.now()\n // streamId doesn't exist yet — it's minted a few lines below, once we\n // know this is a fresh provision rather than a join onto an existing one.\n console.info(\"[STREAM_STARTUP]\", {\n stage: \"requested\",\n packageName,\n ingest: opts.ingest,\n elapsedMs: 0,\n })\n // Two-phase: the entry-claim runs under the transition lock; the wait for\n // HLS readiness happens AFTER the lock releases so a long warm-up doesn't\n // block subsequent start/stop transitions on this coordinator.\n assertGlassesConnected()\n type JoinDecision =\n | {kind: \"join\"; entry: ManagedEntry; immediate: ManagedStartResult | null}\n | {kind: \"fresh\"; entry: ManagedEntry}\n\n const decision = await this.runExclusive(async (): Promise<JoinDecision> => {\n if (this.current && this.current.kind === \"unmanaged\") {\n throw new StreamConflictError(\n \"STREAM_ALREADY_ACTIVE\",\n \"An unmanaged stream is already active. Stop it before starting a managed stream.\",\n )\n }\n\n // Join an existing managed stream if one is already running.\n if (this.current && this.current.kind === \"managed\") {\n const existing = this.current\n // Restream destinations are immutable after provision — a second\n // caller trying to dictate destinations on an already-live stream\n // is a likely bug or a feature we don't yet support.\n if (opts.restreamDestinations && opts.restreamDestinations.length > 0) {\n throw new StreamConflictError(\n \"STREAM_DESTINATIONS_LOCKED\",\n \"Restream destinations cannot be modified on an already-running managed stream.\",\n )\n }\n existing.subscribers.add(packageName)\n const immediate: ManagedStartResult | null = existing.hlsReady\n ? managedStartResult(existing)\n : null\n return {kind: \"join\", entry: existing, immediate}\n }\n\n // Fresh provision — claim slot BEFORE awaiting Cloudflare so a\n // concurrent caller queued behind us sees a managed stream in flight\n // and joins instead of double-provisioning.\n const provision = await provisionManagedStream(opts.restreamDestinations)\n const streamId = this.mintId(\"m\")\n const ingestUrl = pickIngestUrl(provision, opts.ingest)\n const mode: ManagedEntry[\"mode\"] =\n ingestUrl === provision.webrtcPublishUrl ? \"webrtc\" : \"hls\"\n\n const entry: ManagedEntry = {\n kind: \"managed\",\n streamId,\n liveInputId: provision.liveInputId,\n ingestUrl,\n mode,\n hlsUrl: provision.hlsUrl,\n dashUrl: provision.dashUrl,\n webrtcUrl: provision.webrtcUrl,\n subscribers: new Set([packageName]),\n hlsReady: false,\n hlsReadyResolvers: [],\n hlsReadyRejecters: [],\n hlsAttempts: 0,\n cloudflareAttempts: 0,\n startupStartedAtMs,\n }\n this.current = entry\n\n console.info(\"[STREAM_STARTUP]\", {\n streamId,\n stage: \"provisioned\",\n mode,\n elapsedMs: Date.now() - startupStartedAtMs,\n })\n\n try {\n const event = await BluetoothSdk.startExternallyManagedStream({\n type: \"start_stream\",\n streamUrl: ingestUrl,\n streamId,\n sound: opts.sound ?? true,\n // See startUnmanaged: the native bridge rejects explicit `undefined`.\n ...(opts.video !== undefined ? {video: opts.video} : {}),\n ...(opts.audio !== undefined ? {audio: opts.audio} : {}),\n })\n entry.publisherStart = publisherStartResult(streamId, event)\n console.info(\"[STREAM_STARTUP]\", {\n streamId,\n stage: \"publisher_ready\",\n mode,\n elapsedMs: Date.now() - startupStartedAtMs,\n })\n } catch (err) {\n this.current = null\n await teardownManagedStream(provision.liveInputId).catch(() => undefined)\n throw err\n }\n\n this.startLifecycle(streamId)\n this.startCloudflareStatusPoll(entry)\n // hls mode: readiness = a real HLS manifest exists. webrtc mode: HLS\n // never materializes (Cloudflare WHIP limitation) — readiness resolves\n // off the status poll's first \"connected\" instead.\n if (entry.mode === \"hls\") {\n this.startHlsReadinessPoll(entry)\n }\n return {kind: \"fresh\", entry}\n })\n\n if (decision.kind === \"join\" && decision.immediate) {\n return decision.immediate\n }\n\n // The first Cloudflare probe runs immediately and can complete before the\n // transition lock releases. Avoid stranding this caller after readiness\n // resolvers have already been drained.\n if (decision.entry.hlsReady) {\n return managedStartResult(decision.entry)\n }\n\n // Wait for playback readiness OUTSIDE the lock — readiness can take ~10s\n // and we don't want to block other transitions for that long.\n return new Promise<ManagedStartResult>((resolve, reject) => {\n decision.entry.hlsReadyResolvers.push(resolve)\n decision.entry.hlsReadyRejecters.push(reject)\n })\n }\n\n async stop(packageName: string, streamId?: string): Promise<void> {\n await this.runExclusive(async () => {\n if (!this.current) return\n\n // If a streamId was passed but doesn't match, ignore — silent no-op\n // matches the cloud's tolerant behavior.\n if (streamId && this.current.streamId !== streamId) return\n\n if (this.current.kind === \"managed\") {\n const entry = this.current\n entry.subscribers.delete(packageName)\n if (entry.subscribers.size > 0) {\n // Other miniapps still subscribed; keep the stream alive.\n return\n }\n } else if (this.current.packageName !== packageName) {\n // Unmanaged stream: only the owner can stop it.\n return\n }\n\n await this.teardownLocked(\"explicit_stop\")\n })\n }\n\n /**\n * Called by MantleManager when a `stream_status` event arrives from glasses\n * and the registry says it's phone-owned.\n */\n handleGlassesStatus(event: StreamStatusEvent): void {\n if (!this.current) return\n if (event.streamId && event.streamId !== this.current.streamId) return\n\n this.lifecycle?.recordActivity()\n const includeResolvedConfig = !this.resolvedConfigForwarded && !!event.resolvedConfig\n if (includeResolvedConfig) this.resolvedConfigForwarded = true\n const slimData = slimStreamStatusEvent(event, {includeResolvedConfig})\n const signature = streamStatusSignature(slimData)\n if (signature === this.lastFanoutSignature) return\n this.lastFanoutSignature = signature\n\n this.fanout({\n streamId: this.current.streamId,\n source: \"glasses\",\n status: event.status,\n data: slimData,\n })\n\n // Glasses-reported TERMINAL states unwind the coordinator. Terminal means\n // the publisher gave up or stopped — NOT a transient `kind:\"error\"`: the\n // glasses publisher auto-recovers (error → reconnecting → reconnected),\n // and tearing down on the first hiccup deletes the live input out from\n // under a publisher that comes right back (it then retries into a dead\n // input forever). A publisher that errors and never recovers is reaped by\n // the keep-alive ack timeout. Queue the teardown through the transition\n // lock so it serializes with any start/stop currently in flight.\n const isStopped =\n (event.kind === \"lifecycle\" && event.status === \"stopped\") ||\n (event.kind === \"snapshot\" && event.status === \"stopped\")\n const isGiveUp = event.kind === \"reconnect\" && event.status === \"reconnect_failed\"\n if (isGiveUp || isStopped) {\n const reason = isGiveUp ? \"glasses_gave_up\" : \"glasses_stopped\"\n const targetStreamId = this.current.streamId\n void this.runExclusive(async () => {\n // The stream we wanted to tear down may already be gone (e.g. another\n // teardown won the lock and unwound it). Guard before acting.\n if (this.current?.streamId !== targetStreamId) return\n await this.teardownLocked(reason, {sendBleStop: false})\n })\n }\n }\n\n /** Called by MantleManager when a phone-owned keep_alive_ack arrives. */\n handleKeepAliveAck(event: KeepAliveAckEvent): void {\n if (!event.ackId) return\n this.lifecycle?.handleAck(event.ackId)\n }\n\n // ===========================================================================\n // Internal\n // ===========================================================================\n\n private mintId(prefix: \"u\" | \"m\"): string {\n this.idCounter += 1\n return `phone-${prefix}-${Date.now().toString(36)}-${this.idCounter}`\n }\n\n private startLifecycle(streamId: string): void {\n this.lifecycle?.dispose()\n const ctrl = new StreamLifecycleController(\n {\n logger: consoleLogger,\n streamId,\n keepAliveIntervalMs: this.timings.keepAliveIntervalMs,\n ackTimeoutMs: this.timings.ackTimeoutMs,\n maxMissedAcks: this.timings.maxMissedAcks,\n },\n {\n sendKeepAlive: async (ackId) => {\n await BluetoothSdk.sendExternallyManagedStreamKeepAlive({\n type: \"keep_stream_alive\",\n streamId,\n ackId,\n })\n },\n onTimeout: async () => {\n this.fanout({\n streamId,\n source: \"coordinator\",\n status: \"error\",\n data: {reason: \"keep_alive_timeout\"},\n })\n await this.runExclusive(async () => {\n // The stream this timeout was bound to may already be gone.\n if (this.current?.streamId !== streamId) return\n await this.teardownLocked(\"keep_alive_timeout\")\n })\n },\n },\n )\n ctrl.setActive(true)\n this.lifecycle = ctrl\n }\n\n private startCloudflareStatusPoll(entry: ManagedEntry): void {\n // Keep the existing ~60s readiness budget while decoupling it from probe\n // count. Startup probes begin immediately and back off to the normal 5s\n // monitoring cadence, so a just-connected publisher is noticed quickly\n // without increasing steady-state traffic.\n const connectTimeoutMs = Math.max(1, this.timings.hlsReadinessMaxAttempts * this.timings.hlsReadinessPollMs)\n const pollingStartedAtMs = Date.now()\n\n const scheduleNext = () => {\n if (this.current !== entry) return\n const waitingForWebRtc = entry.mode === \"webrtc\" && !entry.hlsReady\n const elapsedMs = Date.now() - pollingStartedAtMs\n const remainingMs = Math.max(0, connectTimeoutMs - elapsedMs)\n const startupDelayMs = Math.min(\n this.timings.cloudflareStatusPollMs,\n this.timings.cloudflareStartupPollInitialMs * 2 ** Math.min(Math.max(0, entry.cloudflareAttempts - 1), 10),\n )\n const delayMs = waitingForWebRtc ? Math.min(startupDelayMs, remainingMs) : this.timings.cloudflareStatusPollMs\n entry.cloudflareTimer = setTimeout(() => void poll(), delayMs)\n }\n\n const poll = async () => {\n if (this.current !== entry) return\n const requestStartedAtMs = Date.now()\n let keepPolling = true\n entry.cloudflareAttempts += 1\n try {\n const status: CloudflareStatus = await getManagedStreamStatus(entry.liveInputId)\n console.debug(\"[STREAM_STARTUP]\", {\n streamId: entry.streamId,\n stage: \"cloudflare_probe\",\n connected: status.isConnected,\n attempt: entry.cloudflareAttempts,\n requestMs: Date.now() - requestStartedAtMs,\n elapsedMs: Date.now() - entry.startupStartedAtMs,\n })\n this.fanout({\n streamId: entry.streamId,\n source: \"cloudflare\",\n status: status.isConnected ? \"connected\" : \"disconnected\",\n data: status as unknown as Record<string, unknown>,\n })\n // webrtc mode readiness: first \"connected\" means WHEP playback is\n // available (WebRTC playback follows the ingest directly; there is no\n // manifest to probe).\n if (entry.mode === \"webrtc\" && !entry.hlsReady) {\n if (status.isConnected) {\n entry.hlsReady = true\n console.info(\"[STREAM_STARTUP]\", {\n streamId: entry.streamId,\n stage: \"playback_ready\",\n mode: entry.mode,\n probes: entry.cloudflareAttempts,\n elapsedMs: Date.now() - entry.startupStartedAtMs,\n })\n const result = managedStartResult(entry)\n for (const r of entry.hlsReadyResolvers) r(result)\n entry.hlsReadyResolvers = []\n entry.hlsReadyRejecters = []\n this.fanout({\n streamId: entry.streamId,\n source: \"coordinator\",\n status: \"webrtc_ready\",\n data: result as unknown as Record<string, unknown>,\n })\n } else {\n if (Date.now() - pollingStartedAtMs >= connectTimeoutMs) {\n const err = new Error(`WebRTC ingest never reached Cloudflare after ${connectTimeoutMs}ms`)\n for (const reject of entry.hlsReadyRejecters) reject(err)\n entry.hlsReadyResolvers = []\n entry.hlsReadyRejecters = []\n this.fanout({\n streamId: entry.streamId,\n source: \"coordinator\",\n status: \"error\",\n data: {reason: \"webrtc_not_connected\"},\n })\n const targetStreamId = entry.streamId\n void this.runExclusive(async () => {\n if (this.current?.streamId !== targetStreamId) return\n await this.teardownLocked(\"webrtc_not_connected\")\n })\n keepPolling = false\n }\n }\n }\n } catch (err) {\n console.warn(\"[STREAM] cloudflare status poll failed:\", err)\n if (entry.mode === \"webrtc\" && !entry.hlsReady && Date.now() - pollingStartedAtMs >= connectTimeoutMs) {\n const timeoutErr = new Error(`WebRTC ingest status could not be confirmed after ${connectTimeoutMs}ms`)\n for (const reject of entry.hlsReadyRejecters) reject(timeoutErr)\n entry.hlsReadyResolvers = []\n entry.hlsReadyRejecters = []\n const targetStreamId = entry.streamId\n void this.runExclusive(async () => {\n if (this.current?.streamId !== targetStreamId) return\n await this.teardownLocked(\"webrtc_status_unavailable\")\n })\n keepPolling = false\n }\n } finally {\n if (keepPolling) scheduleNext()\n }\n }\n\n // The glasses publisher has already reported streaming, so the first\n // status request is useful now. Most starts avoid the old blind 5s wait.\n void poll()\n }\n\n private startHlsReadinessPoll(entry: ManagedEntry): void {\n // Skip the first few seconds — Cloudflare doesn't have first-frame yet,\n // and the HEAD requests would all 404 and burn battery.\n const tick = async () => {\n if (this.current !== entry) return\n entry.hlsAttempts += 1\n try {\n // Require a real manifest (200 with a body), not just res.ok — the\n // playback edge returns 204 No Content while the input has no\n // HLS-capable frames (e.g. WebRTC ingest), and 204 is \"ok\".\n const res = await fetch(entry.hlsUrl, {method: \"HEAD\"})\n if (res.status === 200) {\n entry.hlsReady = true\n console.info(\"[STREAM_STARTUP]\", {\n streamId: entry.streamId,\n stage: \"playback_ready\",\n mode: entry.mode,\n probes: entry.hlsAttempts,\n elapsedMs: Date.now() - entry.startupStartedAtMs,\n })\n if (entry.hlsTimer) {\n clearInterval(entry.hlsTimer)\n entry.hlsTimer = undefined\n }\n const result = managedStartResult(entry)\n for (const r of entry.hlsReadyResolvers) r(result)\n entry.hlsReadyResolvers = []\n entry.hlsReadyRejecters = []\n this.fanout({\n streamId: entry.streamId,\n source: \"coordinator\",\n status: \"hls_ready\",\n data: result as unknown as Record<string, unknown>,\n })\n return\n }\n } catch {\n // 404 / network blip is expected while Cloudflare warms up.\n }\n if (entry.hlsAttempts >= this.timings.hlsReadinessMaxAttempts) {\n if (entry.hlsTimer) {\n clearInterval(entry.hlsTimer)\n entry.hlsTimer = undefined\n }\n const err = new Error(\n `HLS playback URL did not become ready after ${this.timings.hlsReadinessMaxAttempts} attempts`,\n )\n for (const reject of entry.hlsReadyRejecters) reject(err)\n entry.hlsReadyResolvers = []\n entry.hlsReadyRejecters = []\n this.fanout({\n streamId: entry.streamId,\n source: \"coordinator\",\n status: \"error\",\n data: {reason: \"hls_not_ready\"},\n })\n const targetStreamId = entry.streamId\n void this.runExclusive(async () => {\n if (this.current?.streamId !== targetStreamId) return\n await this.teardownLocked(\"hls_not_ready\")\n })\n }\n }\n setTimeout(() => {\n // Guard: stream may have been torn down during the initial delay.\n if (this.current !== entry) return\n entry.hlsTimer = setInterval(tick, this.timings.hlsReadinessPollMs)\n }, this.timings.hlsReadinessInitialDelayMs)\n }\n\n private fanout(update: StreamStatusUpdate): void {\n if (!this.current || !this.statusSubscriber) return\n const targets =\n this.current.kind === \"managed\"\n ? Array.from(this.current.subscribers)\n : [this.current.packageName]\n for (const pkg of targets) {\n try {\n this.statusSubscriber(pkg, update)\n } catch (err) {\n console.warn(\"[STREAM] statusSubscriber threw:\", err)\n }\n }\n }\n\n /**\n * Run teardown of the currently-active stream. Caller must hold the\n * transition lock (see {@link runExclusive}). Keeps `this.current`\n * populated until BluetoothSdk.stopStream resolves so a concurrent caller\n * waiting on the lock can't claim the slot mid-stop and have its\n * startStream BLE write collide with our in-flight stopStream.\n */\n private async teardownLocked(reason: string, options: {sendBleStop?: boolean} = {}): Promise<void> {\n const entry = this.current\n if (!entry) return\n const sendBleStop = options.sendBleStop !== false\n\n this.lastFanoutSignature = null\n this.resolvedConfigForwarded = false\n\n // Dispose the lifecycle controller immediately so it doesn't fire one\n // more keep-alive against a stream we're tearing down. The transition\n // lock guarantees no new lifecycle is started concurrently.\n this.lifecycle?.dispose()\n this.lifecycle = null\n\n if (entry.kind === \"managed\") {\n if (entry.cloudflareTimer) clearTimeout(entry.cloudflareTimer)\n if (entry.hlsTimer) clearInterval(entry.hlsTimer)\n // Reject any still-pending HLS readiness waiters.\n const pendingErr = new Error(`Stream torn down: ${reason}`)\n for (const reject of entry.hlsReadyRejecters) reject(pendingErr)\n entry.hlsReadyResolvers = []\n entry.hlsReadyRejecters = []\n // Cloudflare DELETE is fire-and-forget — failing it doesn't undo the\n // BLE stop we're about to do, and Cloudflare's idle-input scavenger\n // will eventually clean up leaked inputs.\n teardownManagedStream(entry.liveInputId).catch((err) => {\n console.warn(\"[STREAM] teardownManagedStream failed:\", err)\n })\n }\n\n try {\n if (sendBleStop) {\n await BluetoothSdk.stopStream()\n }\n } catch (err) {\n console.warn(\"[STREAM] BluetoothSdk.stopStream failed:\", err)\n } finally {\n // Release the slot AFTER the BLE stop finished, so the next start can\n // safely write its own start_stream without colliding with ours.\n // Only clear if we're still the active entry (defensive — runExclusive\n // serializes us, so this should always be true).\n if (this.current === entry) this.current = null\n }\n }\n}\n\nfunction pickIngestUrl(p: ProvisionResult, preference?: \"srt\" | \"whip\" | \"rtmp\"): string {\n // Glasses' StreamCommandHandler detects protocol from URL prefix.\n //\n // Default priority: SRT > RTMP > WHIP. SRT first: Cloudflare's WebRTC (WHIP)\n // ingest does NOT feed HLS/DASH playback or recording — a WHIP-ingested\n // managed stream reports \"connected\" while its hlsUrl serves 204 forever,\n // which breaks the managed contract (subscribers share HLS playback). SRT\n // also survives office firewalls that kill RTMPS:443 mid-handshake.\n //\n // \"whip\" preference flips the trade: sub-second WHEP playback for\n // live-monitor use cases, accepting no HLS and no recording.\n // \"rtmp\" prefers TCP 443 ingest so networks that drop WHIP/SRT UDP still\n // get HLS playback. Callers must request it explicitly; WHIP starts do not\n // fall back to RTMP.\n //\n // Throw if none resolved so the caller's Promise rejects with a clear\n // message rather than the glasses' \"unknown protocol\" error.\n const url =\n preference === \"whip\"\n ? p.webrtcPublishUrl || p.srtUrl || p.rtmpUrl\n : preference === \"rtmp\"\n ? p.rtmpUrl || p.srtUrl || p.webrtcPublishUrl\n : p.srtUrl || p.rtmpUrl || p.webrtcPublishUrl\n if (!url) {\n throw new Error(\"Cloudflare provision returned no usable ingest URL\")\n }\n return url\n}\n\nfunction publisherStartResult(streamId: string, event?: StreamStatusEvent): StreamPublisherStartResult {\n return {\n streamId: event?.streamId || streamId,\n status: event?.status ?? \"streaming\",\n ...(event?.resolvedConfig ? {resolvedConfig: event.resolvedConfig} : {}),\n }\n}\n\nfunction managedStartResult(entry: ManagedEntry): ManagedStartResult {\n const publisher = entry.publisherStart ?? publisherStartResult(entry.streamId)\n return {\n ...publisher,\n streamId: entry.streamId,\n liveInputId: entry.liveInputId,\n mode: entry.mode,\n hlsUrl: entry.hlsUrl,\n dashUrl: entry.dashUrl,\n webrtcUrl: entry.webrtcUrl,\n }\n}\n\n// Singleton — coordinator's single-stream constraint is process-wide.\nexport const phoneStreamCoordinator = new PhoneStreamCoordinator()\n"]}
1
+ {"version":3,"file":"PhoneStreamCoordinator.js","sourceR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Ac,EAAC,CAAC,CAAC,CAAC,EAAE,CAAC;KACzE,CAAA;AACH,CAAC;AAED,SAAS,kBAAkB,CAAC,KAAmB;IAC7C,MAAM,SAAS,GAAG,KAAK,CAAC,cAAc,IAAI,oBAAoB,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;IAC9E,OAAO;QACL,GAAG,SAAS;QACZ,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,SAAS,EAAE,KAAK,CAAC,SAAS;KAC3B,CAAA;AACH,CAAC;AAED,sEAAsE;AACtE,MAAM,CAAC,MAAM,sBAAsB,GAAG,IAAI,sBAAsB,EAAE,CAAA","sourcesContent":["/**\n * PhoneStreamCoordinator — owns all local-miniapp streaming on the phone.\n *\n * Architecture:\n * miniapp → SDK → LocalMiniappRuntime → coordinator\n * coordinator → BluetoothSdk (BLE → glasses publisher)\n * coordinator ↔ cloudStreamApi (managed only, cloud-v2 runtime provisioning)\n * coordinator ↔ StreamLifecycleController (keep-alive heartbeat)\n * coordinator → status listeners → routed back to miniapp(s)\n *\n * Single-stream constraint:\n * At most ONE stream is active across all miniapps. The exception is that\n * multiple miniapps can subscribe to a single managed stream that's already\n * running — Cloudflare muxes one ingest into many viewers, so subscribers\n * share the same playback URLs. Refcounted; teardown happens when the last\n * subscriber releases.\n *\n * Status routing:\n * Glasses publisher status arrives over BLE as `stream_status` events with\n * a `streamId`. The coordinator's `owns(streamId)` lookup lets MantleManager\n * route phone-owned status events here (not to cloud). For managed streams,\n * we additionally poll Cloudflare's live-input status every 5s to surface\n * what the OTHER end of the pipe sees.\n *\n * Important: this is the ONLY place that mints `streamId`s for phone-owned\n * streams. We use a `phone-` prefix so they're trivially distinguishable from\n * cloud-minted IDs in logs and from cloud-SDK app streams that flow through\n * the legacy path.\n */\n\nimport BluetoothSdk from \"@mentra/bluetooth-sdk/internal\"\nimport type {\n KeepAliveAckEvent,\n StreamResolvedConfig,\n StreamStartRequest,\n StreamStatusEvent,\n} from \"@mentra/bluetooth-sdk/internal\"\nimport {isGlassesConnected} from \"./GlassesReadiness\"\nimport {useGlassesStore} from \"../stores/glasses\"\n\nimport {StreamLifecycleController, type LifecycleLogger} from \"./StreamLifecycleController\"\nimport {slimStreamStatusEvent, streamStatusSignature} from \"./slimStreamStatus\"\nimport {\n getManagedStreamStatus,\n provisionManagedStream,\n teardownManagedStream,\n type CloudflareStatus,\n type ProvisionResult,\n type RestreamDestinationInput,\n} from \"./cloudStreamApi\"\n\n/**\n * Default cadence + thresholds. Exposed via {@link CoordinatorTimings} so tests\n * can shorten them; production code should never override these.\n */\nconst DEFAULT_TIMINGS = {\n keepAliveIntervalMs: 15_000,\n ackTimeoutMs: 10_000,\n maxMissedAcks: 3,\n cloudflareStatusPollMs: 5_000,\n // During WHIP startup, probe quickly so readiness is not quantized to the\n // steady-state 5s monitoring cadence. The delay backs off on each miss.\n cloudflareStartupPollInitialMs: 500,\n // Cloudflare typically needs ~5-10s after first frame before HLS is live.\n hlsReadinessInitialDelayMs: 5_000,\n hlsReadinessPollMs: 2_000,\n hlsReadinessMaxAttempts: 30,\n} as const\n\ntype TimingConfig = {[K in keyof typeof DEFAULT_TIMINGS]: number}\nexport type CoordinatorTimings = Partial<TimingConfig>\n\n// Console-backed minimal logger; replaces pino on the phone.\nconst consoleLogger: LifecycleLogger = {\n child: (bindings) => ({\n ...consoleLogger,\n debug: (...args) => console.debug(\"[STREAM]\", bindings, ...args),\n warn: (...args) => console.warn(\"[STREAM]\", bindings, ...args),\n error: (...args) => console.error(\"[STREAM]\", bindings, ...args),\n }),\n debug: (...args) => console.debug(\"[STREAM]\", ...args),\n warn: (...args) => console.warn(\"[STREAM]\", ...args),\n error: (...args) => console.error(\"[STREAM]\", ...args),\n}\n\nexport interface StartUnmanagedOptions {\n streamUrl: string\n video?: StreamStartRequest[\"video\"]\n audio?: StreamStartRequest[\"audio\"]\n sound?: boolean\n /** Optional Bearer token for WHIP Authorization (custom authenticated endpoints). */\n authToken?: string\n}\n\nexport interface StartManagedOptions {\n restreamDestinations?: RestreamDestinationInput[]\n video?: StreamStartRequest[\"video\"]\n audio?: StreamStartRequest[\"audio\"]\n sound?: boolean\n /**\n * Ingest protocol preference — a real latency/durability trade on Cloudflare:\n * - \"srt\" (default): SRT ingest -> LL-HLS playback (~10-20s glass-to-screen),\n * with shareable HLS/DASH URLs and automatic recording.\n * - \"whip\": WebRTC ingest -> WHEP playback (<1s glass-to-screen), but NO\n * HLS/DASH playback and NO recording (Cloudflare limitation; the returned\n * hlsUrl will serve 204 forever).\n * - \"rtmp\": RTMPS ingest over TCP 443 -> HLS playback. Survives networks\n * that drop WHIP/SRT UDP.\n */\n ingest?: \"srt\" | \"whip\" | \"rtmp\"\n}\n\nexport interface StreamPublisherStartResult {\n streamId: string\n status: string\n resolvedConfig?: StreamResolvedConfig\n}\n\nexport interface ManagedStartResult extends StreamPublisherStartResult {\n liveInputId: string\n /** Playback mode this stream supports: \"hls\" (SRT/RTMP ingest — use hlsUrl/\n * dashUrl, recording on) or \"webrtc\" (WHIP ingest — use webrtcUrl/WHEP,\n * sub-second, no HLS, no recording). */\n mode: \"hls\" | \"webrtc\"\n hlsUrl: string\n dashUrl: string\n webrtcUrl?: string\n}\n\nexport type StreamStatusUpdate = {\n streamId: string\n source: \"glasses\" | \"cloudflare\" | \"coordinator\"\n status: string\n data?: Record<string, unknown>\n}\n\nexport type StatusSubscriber = (packageName: string, update: StreamStatusUpdate) => void\n\ninterface UnmanagedEntry {\n kind: \"unmanaged\"\n streamId: string\n packageName: string\n streamUrl: string\n}\n\ninterface ManagedEntry {\n kind: \"managed\"\n streamId: string\n liveInputId: string\n ingestUrl: string\n /** Playback mode the chosen ingest supports: SRT/RTMP feed HLS; WHIP feeds\n * only WHEP. Readiness is gated differently per mode. */\n mode: \"hls\" | \"webrtc\"\n hlsUrl: string\n dashUrl: string\n webrtcUrl?: string\n publisherStart?: StreamPublisherStartResult\n subscribers: Set<string>\n hlsReady: boolean\n hlsReadyResolvers: Array<(result: ManagedStartResult) => void>\n hlsReadyRejecters: Array<(err: Error) => void>\n cloudflareTimer?: ReturnType<typeof setTimeout>\n hlsTimer?: ReturnType<typeof setInterval>\n hlsAttempts: number\n /** Cloudflare status probes made during this stream session. */\n cloudflareAttempts: number\n /** Wall-clock origin for end-to-end managed startup diagnostics. */\n startupStartedAtMs: number\n}\n\ntype Entry = UnmanagedEntry | ManagedEntry\n\nexport class StreamConflictError extends Error {\n constructor(\n public readonly code: string,\n message: string,\n /** Pipeline stage that failed (provision | command | publish | playback). */\n public readonly stage?: string,\n /** Transport in play at the failure (cloud-rest | ble | wifi). */\n public readonly transport?: string,\n ) {\n super(message)\n this.name = \"StreamConflictError\"\n }\n}\n\n/**\n * Fail fast if glasses aren't connected — BEFORE provisioning. Without this a\n * managed start would create a provider live input, fail the BLE command, and\n * tear the input down again: a slow, billable no-op with a confusing error.\n */\nfunction assertGlassesConnected(): void {\n if (!isGlassesConnected(useGlassesStore.getState().connection)) {\n throw new StreamConflictError(\n \"GLASSES_NOT_CONNECTED\",\n \"Glasses are not connected\",\n \"command\",\n \"ble\",\n )\n }\n}\n\nexport class PhoneStreamCoordinator {\n private current: Entry | null = null\n private lifecycle: StreamLifecycleController | null = null\n private statusSubscriber: StatusSubscriber | null = null\n private idCounter = 0\n private readonly timings: TimingConfig\n /**\n * Serializes state transitions (start, stop, teardown). Without it, a\n * second `start*` racing with the first can pass the `this.current === null`\n * pre-check while the first is still awaiting its provision/BLE work, and\n * end up provisioning two separate streams. A teardown racing with a start\n * can clear `current` mid-stop and let the start fire BLE writes that\n * collide with the in-flight stopStream.\n */\n private inFlight: Promise<void> = Promise.resolve()\n /** Drop identical stream_status fanouts within one session. */\n private lastFanoutSignature: string | null = null\n /** Send full resolvedConfig only once per stream session. */\n private resolvedConfigForwarded = false\n\n constructor(timings: CoordinatorTimings = {}) {\n this.timings = {...DEFAULT_TIMINGS, ...timings}\n }\n\n /**\n * Run `work` under the transition lock. Each call awaits the previous\n * transition before re-evaluating preconditions, so e.g. two concurrent\n * `startManaged` calls are observed sequentially.\n */\n private async runExclusive<T>(work: () => Promise<T>): Promise<T> {\n const prev = this.inFlight\n let release!: () => void\n this.inFlight = new Promise<void>((r) => (release = r))\n try {\n await prev\n return await work()\n } finally {\n release()\n }\n }\n\n /**\n * Register the function that routes status updates to miniapps.\n * LocalMiniappRuntime wires this so updates become EVENT envelopes on the\n * `stream_status` stream for every subscribing miniapp.\n */\n setStatusSubscriber(cb: StatusSubscriber): void {\n this.statusSubscriber = cb\n }\n\n /**\n * True when a phone-owned stream currently uses this streamId. For managed\n * streams, all subscribers share the same streamId so a single equality\n * check covers the multi-subscriber case.\n */\n owns(streamId: string): boolean {\n return this.current !== null && this.current.streamId === streamId\n }\n\n /** Report-safe stream ownership snapshot for incident diagnostics. */\n getDiagnosticSnapshot(): Record<string, unknown> {\n if (!this.current) return {active: false}\n return this.current.kind === \"managed\"\n ? {\n active: true,\n kind: this.current.kind,\n streamId: this.current.streamId,\n subscribers: [...this.current.subscribers].sort(),\n mode: this.current.mode,\n playbackReady: this.current.hlsReady,\n }\n : {\n active: true,\n kind: this.current.kind,\n streamId: this.current.streamId,\n ownerPackageName: this.current.packageName,\n }\n }\n\n async startUnmanaged(\n packageName: string,\n opts: StartUnmanagedOptions,\n ): Promise<StreamPublisherStartResult> {\n // Pre-check the obvious-bad input before queueing — the lock is for\n // serializing state transitions, not for validating arguments.\n if (!opts.streamUrl || typeof opts.streamUrl !== \"string\") {\n throw new StreamConflictError(\"STREAM_URL_REQUIRED\", \"streamUrl is required\")\n }\n assertGlassesConnected()\n return this.runExclusive(async () => {\n if (this.current) {\n throw new StreamConflictError(\n \"STREAM_ALREADY_ACTIVE\",\n `A ${this.current.kind} stream is already active. Stop it before starting a new one.`,\n )\n }\n\n const streamId = this.mintId(\"u\")\n const entry: UnmanagedEntry = {\n kind: \"unmanaged\",\n streamId,\n packageName,\n streamUrl: opts.streamUrl,\n }\n // Claim the slot BEFORE the BLE call so a concurrent caller waiting on\n // the lock sees the in-progress entry and rejects with the conflict.\n this.current = entry\n\n try {\n const event = await BluetoothSdk.startExternallyManagedStream({\n type: \"start_stream\",\n streamUrl: opts.streamUrl,\n streamId,\n sound: opts.sound ?? true,\n // The native bridge rejects explicit `undefined` values (\"Value is\n // undefined, expected an Object\") — only include what was provided.\n ...(opts.video !== undefined ? {video: opts.video} : {}),\n ...(opts.audio !== undefined ? {audio: opts.audio} : {}),\n ...(opts.authToken ? {authToken: opts.authToken} : {}),\n })\n const result = publisherStartResult(streamId, event)\n this.startLifecycle(streamId)\n return result\n } catch (err) {\n this.current = null\n throw err\n }\n })\n }\n\n async startManaged(\n packageName: string,\n opts: StartManagedOptions,\n ): Promise<ManagedStartResult> {\n const startupStartedAtMs = Date.now()\n // streamId doesn't exist yet — it's minted a few lines below, once we\n // know this is a fresh provision rather than a join onto an existing one.\n console.info(\"[STREAM_STARTUP]\", {\n stage: \"requested\",\n packageName,\n ingest: opts.ingest,\n elapsedMs: 0,\n })\n // Two-phase: the entry-claim runs under the transition lock; the wait for\n // HLS readiness happens AFTER the lock releases so a long warm-up doesn't\n // block subsequent start/stop transitions on this coordinator.\n assertGlassesConnected()\n type JoinDecision =\n | {kind: \"join\"; entry: ManagedEntry; immediate: ManagedStartResult | null}\n | {kind: \"fresh\"; entry: ManagedEntry}\n\n const decision = await this.runExclusive(async (): Promise<JoinDecision> => {\n if (this.current && this.current.kind === \"unmanaged\") {\n throw new StreamConflictError(\n \"STREAM_ALREADY_ACTIVE\",\n \"An unmanaged stream is already active. Stop it before starting a managed stream.\",\n )\n }\n\n // Join an existing managed stream if one is already running.\n if (this.current && this.current.kind === \"managed\") {\n const existing = this.current\n // Restream destinations are immutable after provision — a second\n // caller trying to dictate destinations on an already-live stream\n // is a likely bug or a feature we don't yet support.\n if (opts.restreamDestinations && opts.restreamDestinations.length > 0) {\n throw new StreamConflictError(\n \"STREAM_DESTINATIONS_LOCKED\",\n \"Restream destinations cannot be modified on an already-running managed stream.\",\n )\n }\n existing.subscribers.add(packageName)\n const immediate: ManagedStartResult | null = existing.hlsReady\n ? managedStartResult(existing)\n : null\n return {kind: \"join\", entry: existing, immediate}\n }\n\n // Fresh provision — claim slot BEFORE awaiting Cloudflare so a\n // concurrent caller queued behind us sees a managed stream in flight\n // and joins instead of double-provisioning.\n const provision = await provisionManagedStream(opts.restreamDestinations)\n const streamId = this.mintId(\"m\")\n const ingestUrl = pickIngestUrl(provision, opts.ingest)\n const mode: ManagedEntry[\"mode\"] =\n ingestUrl === provision.webrtcPublishUrl ? \"webrtc\" : \"hls\"\n\n const entry: ManagedEntry = {\n kind: \"managed\",\n streamId,\n liveInputId: provision.liveInputId,\n ingestUrl,\n mode,\n hlsUrl: provision.hlsUrl,\n dashUrl: provision.dashUrl,\n webrtcUrl: provision.webrtcUrl,\n subscribers: new Set([packageName]),\n hlsReady: false,\n hlsReadyResolvers: [],\n hlsReadyRejecters: [],\n hlsAttempts: 0,\n cloudflareAttempts: 0,\n startupStartedAtMs,\n }\n this.current = entry\n\n console.info(\"[STREAM_STARTUP]\", {\n streamId,\n stage: \"provisioned\",\n mode,\n elapsedMs: Date.now() - startupStartedAtMs,\n })\n\n try {\n const event = await BluetoothSdk.startExternallyManagedStream({\n type: \"start_stream\",\n streamUrl: ingestUrl,\n streamId,\n sound: opts.sound ?? true,\n // See startUnmanaged: the native bridge rejects explicit `undefined`.\n ...(opts.video !== undefined ? {video: opts.video} : {}),\n ...(opts.audio !== undefined ? {audio: opts.audio} : {}),\n })\n entry.publisherStart = publisherStartResult(streamId, event)\n console.info(\"[STREAM_STARTUP]\", {\n streamId,\n stage: \"publisher_ready\",\n mode,\n elapsedMs: Date.now() - startupStartedAtMs,\n })\n } catch (err) {\n this.current = null\n await teardownManagedStream(provision.liveInputId).catch(() => undefined)\n throw err\n }\n\n this.startLifecycle(streamId)\n this.startCloudflareStatusPoll(entry)\n // hls mode: readiness = a real HLS manifest exists. webrtc mode: HLS\n // never materializes (Cloudflare WHIP limitation) — readiness resolves\n // off the status poll's first \"connected\" instead.\n if (entry.mode === \"hls\") {\n this.startHlsReadinessPoll(entry)\n }\n return {kind: \"fresh\", entry}\n })\n\n if (decision.kind === \"join\" && decision.immediate) {\n return decision.immediate\n }\n\n // The first Cloudflare probe runs immediately and can complete before the\n // transition lock releases. Avoid stranding this caller after readiness\n // resolvers have already been drained.\n if (decision.entry.hlsReady) {\n return managedStartResult(decision.entry)\n }\n\n // Wait for playback readiness OUTSIDE the lock — readiness can take ~10s\n // and we don't want to block other transitions for that long.\n return new Promise<ManagedStartResult>((resolve, reject) => {\n decision.entry.hlsReadyResolvers.push(resolve)\n decision.entry.hlsReadyRejecters.push(reject)\n })\n }\n\n async stop(packageName: string, streamId?: string): Promise<void> {\n await this.runExclusive(async () => {\n if (!this.current) return\n\n // If a streamId was passed but doesn't match, ignore — silent no-op\n // matches the cloud's tolerant behavior.\n if (streamId && this.current.streamId !== streamId) return\n\n if (this.current.kind === \"managed\") {\n const entry = this.current\n entry.subscribers.delete(packageName)\n if (entry.subscribers.size > 0) {\n // Other miniapps still subscribed; keep the stream alive.\n return\n }\n } else if (this.current.packageName !== packageName) {\n // Unmanaged stream: only the owner can stop it.\n return\n }\n\n await this.teardownLocked(\"explicit_stop\")\n })\n }\n\n /**\n * Called by MantleManager when a `stream_status` event arrives from glasses\n * and the registry says it's phone-owned.\n */\n handleGlassesStatus(event: StreamStatusEvent): void {\n if (!this.current) return\n if (event.streamId && event.streamId !== this.current.streamId) return\n\n this.lifecycle?.recordActivity()\n const includeResolvedConfig = !this.resolvedConfigForwarded && !!event.resolvedConfig\n if (includeResolvedConfig) this.resolvedConfigForwarded = true\n const slimData = slimStreamStatusEvent(event, {includeResolvedConfig})\n const signature = streamStatusSignature(slimData)\n if (signature === this.lastFanoutSignature) return\n this.lastFanoutSignature = signature\n\n this.fanout({\n streamId: this.current.streamId,\n source: \"glasses\",\n status: event.status,\n data: slimData,\n })\n\n // Glasses-reported TERMINAL states unwind the coordinator. Terminal means\n // the publisher gave up or stopped — NOT a transient `kind:\"error\"`: the\n // glasses publisher auto-recovers (error → reconnecting → reconnected),\n // and tearing down on the first hiccup deletes the live input out from\n // under a publisher that comes right back (it then retries into a dead\n // input forever). A publisher that errors and never recovers is reaped by\n // the keep-alive ack timeout. Queue the teardown through the transition\n // lock so it serializes with any start/stop currently in flight.\n const isStopped =\n (event.kind === \"lifecycle\" && event.status === \"stopped\") ||\n (event.kind === \"snapshot\" && event.status === \"stopped\")\n const isGiveUp = event.kind === \"reconnect\" && event.status === \"reconnect_failed\"\n if (isGiveUp || isStopped) {\n const reason = isGiveUp ? \"glasses_gave_up\" : \"glasses_stopped\"\n const targetStreamId = this.current.streamId\n void this.runExclusive(async () => {\n // The stream we wanted to tear down may already be gone (e.g. another\n // teardown won the lock and unwound it). Guard before acting.\n if (this.current?.streamId !== targetStreamId) return\n await this.teardownLocked(reason, {sendBleStop: false})\n })\n }\n }\n\n /** Called by MantleManager when a phone-owned keep_alive_ack arrives. */\n handleKeepAliveAck(event: KeepAliveAckEvent): void {\n if (!event.ackId) return\n this.lifecycle?.handleAck(event.ackId)\n }\n\n // ===========================================================================\n // Internal\n // ===========================================================================\n\n private mintId(prefix: \"u\" | \"m\"): string {\n this.idCounter += 1\n return `phone-${prefix}-${Date.now().toString(36)}-${this.idCounter}`\n }\n\n private startLifecycle(streamId: string): void {\n this.lifecycle?.dispose()\n const ctrl = new StreamLifecycleController(\n {\n logger: consoleLogger,\n streamId,\n keepAliveIntervalMs: this.timings.keepAliveIntervalMs,\n ackTimeoutMs: this.timings.ackTimeoutMs,\n maxMissedAcks: this.timings.maxMissedAcks,\n },\n {\n sendKeepAlive: async (ackId) => {\n await BluetoothSdk.sendExternallyManagedStreamKeepAlive({\n type: \"keep_stream_alive\",\n streamId,\n ackId,\n })\n },\n onTimeout: async () => {\n this.fanout({\n streamId,\n source: \"coordinator\",\n status: \"error\",\n data: {reason: \"keep_alive_timeout\"},\n })\n await this.runExclusive(async () => {\n // The stream this timeout was bound to may already be gone.\n if (this.current?.streamId !== streamId) return\n await this.teardownLocked(\"keep_alive_timeout\")\n })\n },\n },\n )\n ctrl.setActive(true)\n this.lifecycle = ctrl\n }\n\n private startCloudflareStatusPoll(entry: ManagedEntry): void {\n // Keep the existing ~60s readiness budget while decoupling it from probe\n // count. Startup probes begin immediately and back off to the normal 5s\n // monitoring cadence, so a just-connected publisher is noticed quickly\n // without increasing steady-state traffic.\n const connectTimeoutMs = Math.max(1, this.timings.hlsReadinessMaxAttempts * this.timings.hlsReadinessPollMs)\n const pollingStartedAtMs = Date.now()\n\n const scheduleNext = () => {\n if (this.current !== entry) return\n const waitingForWebRtc = entry.mode === \"webrtc\" && !entry.hlsReady\n const elapsedMs = Date.now() - pollingStartedAtMs\n const remainingMs = Math.max(0, connectTimeoutMs - elapsedMs)\n const startupDelayMs = Math.min(\n this.timings.cloudflareStatusPollMs,\n this.timings.cloudflareStartupPollInitialMs * 2 ** Math.min(Math.max(0, entry.cloudflareAttempts - 1), 10),\n )\n const delayMs = waitingForWebRtc ? Math.min(startupDelayMs, remainingMs) : this.timings.cloudflareStatusPollMs\n entry.cloudflareTimer = setTimeout(() => void poll(), delayMs)\n }\n\n const poll = async () => {\n if (this.current !== entry) return\n const requestStartedAtMs = Date.now()\n let keepPolling = true\n entry.cloudflareAttempts += 1\n try {\n const status: CloudflareStatus = await getManagedStreamStatus(entry.liveInputId)\n console.debug(\"[STREAM_STARTUP]\", {\n streamId: entry.streamId,\n stage: \"cloudflare_probe\",\n connected: status.isConnected,\n attempt: entry.cloudflareAttempts,\n requestMs: Date.now() - requestStartedAtMs,\n elapsedMs: Date.now() - entry.startupStartedAtMs,\n })\n this.fanout({\n streamId: entry.streamId,\n source: \"cloudflare\",\n status: status.isConnected ? \"connected\" : \"disconnected\",\n data: status as unknown as Record<string, unknown>,\n })\n // webrtc mode readiness: first \"connected\" means WHEP playback is\n // available (WebRTC playback follows the ingest directly; there is no\n // manifest to probe).\n if (entry.mode === \"webrtc\" && !entry.hlsReady) {\n if (status.isConnected) {\n entry.hlsReady = true\n console.info(\"[STREAM_STARTUP]\", {\n streamId: entry.streamId,\n stage: \"playback_ready\",\n mode: entry.mode,\n probes: entry.cloudflareAttempts,\n elapsedMs: Date.now() - entry.startupStartedAtMs,\n })\n const result = managedStartResult(entry)\n for (const r of entry.hlsReadyResolvers) r(result)\n entry.hlsReadyResolvers = []\n entry.hlsReadyRejecters = []\n this.fanout({\n streamId: entry.streamId,\n source: \"coordinator\",\n status: \"webrtc_ready\",\n data: result as unknown as Record<string, unknown>,\n })\n } else {\n if (Date.now() - pollingStartedAtMs >= connectTimeoutMs) {\n const err = new Error(`WebRTC ingest never reached Cloudflare after ${connectTimeoutMs}ms`)\n for (const reject of entry.hlsReadyRejecters) reject(err)\n entry.hlsReadyResolvers = []\n entry.hlsReadyRejecters = []\n this.fanout({\n streamId: entry.streamId,\n source: \"coordinator\",\n status: \"error\",\n data: {reason: \"webrtc_not_connected\"},\n })\n const targetStreamId = entry.streamId\n void this.runExclusive(async () => {\n if (this.current?.streamId !== targetStreamId) return\n await this.teardownLocked(\"webrtc_not_connected\")\n })\n keepPolling = false\n }\n }\n }\n } catch (err) {\n console.warn(\"[STREAM] cloudflare status poll failed:\", err)\n if (entry.mode === \"webrtc\" && !entry.hlsReady && Date.now() - pollingStartedAtMs >= connectTimeoutMs) {\n const timeoutErr = new Error(`WebRTC ingest status could not be confirmed after ${connectTimeoutMs}ms`)\n for (const reject of entry.hlsReadyRejecters) reject(timeoutErr)\n entry.hlsReadyResolvers = []\n entry.hlsReadyRejecters = []\n const targetStreamId = entry.streamId\n void this.runExclusive(async () => {\n if (this.current?.streamId !== targetStreamId) return\n await this.teardownLocked(\"webrtc_status_unavailable\")\n })\n keepPolling = false\n }\n } finally {\n if (keepPolling) scheduleNext()\n }\n }\n\n // The glasses publisher has already reported streaming, so the first\n // status request is useful now. Most starts avoid the old blind 5s wait.\n void poll()\n }\n\n private startHlsReadinessPoll(entry: ManagedEntry): void {\n // Skip the first few seconds — Cloudflare doesn't have first-frame yet,\n // and the HEAD requests would all 404 and burn battery.\n const tick = async () => {\n if (this.current !== entry) return\n entry.hlsAttempts += 1\n try {\n // Require a real manifest (200 with a body), not just res.ok — the\n // playback edge returns 204 No Content while the input has no\n // HLS-capable frames (e.g. WebRTC ingest), and 204 is \"ok\".\n const res = await fetch(entry.hlsUrl, {method: \"HEAD\"})\n if (res.status === 200) {\n entry.hlsReady = true\n console.info(\"[STREAM_STARTUP]\", {\n streamId: entry.streamId,\n stage: \"playback_ready\",\n mode: entry.mode,\n probes: entry.hlsAttempts,\n elapsedMs: Date.now() - entry.startupStartedAtMs,\n })\n if (entry.hlsTimer) {\n clearInterval(entry.hlsTimer)\n entry.hlsTimer = undefined\n }\n const result = managedStartResult(entry)\n for (const r of entry.hlsReadyResolvers) r(result)\n entry.hlsReadyResolvers = []\n entry.hlsReadyRejecters = []\n this.fanout({\n streamId: entry.streamId,\n source: \"coordinator\",\n status: \"hls_ready\",\n data: result as unknown as Record<string, unknown>,\n })\n return\n }\n } catch {\n // 404 / network blip is expected while Cloudflare warms up.\n }\n if (entry.hlsAttempts >= this.timings.hlsReadinessMaxAttempts) {\n if (entry.hlsTimer) {\n clearInterval(entry.hlsTimer)\n entry.hlsTimer = undefined\n }\n const err = new Error(\n `HLS playback URL did not become ready after ${this.timings.hlsReadinessMaxAttempts} attempts`,\n )\n for (const reject of entry.hlsReadyRejecters) reject(err)\n entry.hlsReadyResolvers = []\n entry.hlsReadyRejecters = []\n this.fanout({\n streamId: entry.streamId,\n source: \"coordinator\",\n status: \"error\",\n data: {reason: \"hls_not_ready\"},\n })\n const targetStreamId = entry.streamId\n void this.runExclusive(async () => {\n if (this.current?.streamId !== targetStreamId) return\n await this.teardownLocked(\"hls_not_ready\")\n })\n }\n }\n setTimeout(() => {\n // Guard: stream may have been torn down during the initial delay.\n if (this.current !== entry) return\n entry.hlsTimer = setInterval(tick, this.timings.hlsReadinessPollMs)\n }, this.timings.hlsReadinessInitialDelayMs)\n }\n\n private fanout(update: StreamStatusUpdate): void {\n if (!this.current || !this.statusSubscriber) return\n const targets =\n this.current.kind === \"managed\"\n ? Array.from(this.current.subscribers)\n : [this.current.packageName]\n for (const pkg of targets) {\n try {\n this.statusSubscriber(pkg, update)\n } catch (err) {\n console.warn(\"[STREAM] statusSubscriber threw:\", err)\n }\n }\n }\n\n /**\n * Run teardown of the currently-active stream. Caller must hold the\n * transition lock (see {@link runExclusive}). Keeps `this.current`\n * populated until BluetoothSdk.stopStream resolves so a concurrent caller\n * waiting on the lock can't claim the slot mid-stop and have its\n * startStream BLE write collide with our in-flight stopStream.\n */\n private async teardownLocked(reason: string, options: {sendBleStop?: boolean} = {}): Promise<void> {\n const entry = this.current\n if (!entry) return\n const sendBleStop = options.sendBleStop !== false\n\n this.lastFanoutSignature = null\n this.resolvedConfigForwarded = false\n\n // Dispose the lifecycle controller immediately so it doesn't fire one\n // more keep-alive against a stream we're tearing down. The transition\n // lock guarantees no new lifecycle is started concurrently.\n this.lifecycle?.dispose()\n this.lifecycle = null\n\n if (entry.kind === \"managed\") {\n if (entry.cloudflareTimer) clearTimeout(entry.cloudflareTimer)\n if (entry.hlsTimer) clearInterval(entry.hlsTimer)\n // Reject any still-pending HLS readiness waiters.\n const pendingErr = new Error(`Stream torn down: ${reason}`)\n for (const reject of entry.hlsReadyRejecters) reject(pendingErr)\n entry.hlsReadyResolvers = []\n entry.hlsReadyRejecters = []\n }\n\n try {\n if (sendBleStop) {\n await BluetoothSdk.stopStream()\n }\n } catch (err) {\n console.warn(\"[STREAM] BluetoothSdk.stopStream failed:\", err)\n } finally {\n // Release the slot AFTER the BLE stop finished, so the next start can\n // safely write its own start_stream without colliding with ours.\n // Only clear if we're still the active entry (defensive — runExclusive\n // serializes us, so this should always be true).\n if (this.current === entry) this.current = null\n\n if (entry.kind === \"managed\") {\n // Start remote cleanup only after the publisher has stopped, but do not\n // hold the local transition lock on an unbounded network request. The\n // runtime's durable cleanup queue owns retries if this request fails or\n // the app exits before Cloudflare finishes finalizing the recording.\n void teardownManagedStream(entry.liveInputId).catch((err) => {\n console.warn(\"[STREAM] teardownManagedStream failed:\", err)\n })\n }\n }\n }\n}\n\nfunction pickIngestUrl(p: ProvisionResult, preference?: \"srt\" | \"whip\" | \"rtmp\"): string {\n // Glasses' StreamCommandHandler detects protocol from URL prefix.\n //\n // Default priority: SRT > RTMP > WHIP. SRT first: Cloudflare's WebRTC (WHIP)\n // ingest does NOT feed HLS/DASH playback or recording — a WHIP-ingested\n // managed stream reports \"connected\" while its hlsUrl serves 204 forever,\n // which breaks the managed contract (subscribers share HLS playback). SRT\n // also survives office firewalls that kill RTMPS:443 mid-handshake.\n //\n // \"whip\" preference flips the trade: sub-second WHEP playback for\n // live-monitor use cases, accepting no HLS and no recording.\n // \"rtmp\" prefers TCP 443 ingest so networks that drop WHIP/SRT UDP still\n // get HLS playback. Callers must request it explicitly; WHIP starts do not\n // fall back to RTMP.\n //\n // Throw if none resolved so the caller's Promise rejects with a clear\n // message rather than the glasses' \"unknown protocol\" error.\n const url =\n preference === \"whip\"\n ? p.webrtcPublishUrl || p.srtUrl || p.rtmpUrl\n : preference === \"rtmp\"\n ? p.rtmpUrl || p.srtUrl || p.webrtcPublishUrl\n : p.srtUrl || p.rtmpUrl || p.webrtcPublishUrl\n if (!url) {\n throw new Error(\"Cloudflare provision returned no usable ingest URL\")\n }\n return url\n}\n\nfunction publisherStartResult(streamId: string, event?: StreamStatusEvent): StreamPublisherStartResult {\n return {\n streamId: event?.streamId || streamId,\n status: event?.status ?? \"streaming\",\n ...(event?.resolvedConfig ? {resolvedConfig: event.resolvedConfig} : {}),\n }\n}\n\nfunction managedStartResult(entry: ManagedEntry): ManagedStartResult {\n const publisher = entry.publisherStart ?? publisherStartResult(entry.streamId)\n return {\n ...publisher,\n streamId: entry.streamId,\n liveInputId: entry.liveInputId,\n mode: entry.mode,\n hlsUrl: entry.hlsUrl,\n dashUrl: entry.dashUrl,\n webrtcUrl: entry.webrtcUrl,\n }\n}\n\n// Singleton — coordinator's single-stream constraint is process-wide.\nexport const phoneStreamCoordinator = new PhoneStreamCoordinator()\n"]}
@@ -3,9 +3,9 @@
3
3
  * `setActive(true)` starts the timer; each tick sends a keep-alive with a
4
4
  * fresh ackId; `maxMissedAcks` consecutive timeouts fire `onTimeout`.
5
5
  *
6
- * Mirror of `cloud/packages/cloud/src/services/streaming/StreamLifecycleController.ts`
7
- * — kept byte-equivalent except for the `LifecycleLogger` interface (pino
8
- * isn't a phone dep). Behavior changes must land in both files.
6
+ * Phone-owned successor to the retired cloud stream lifecycle controller.
7
+ * It uses the local `LifecycleLogger` interface because pino is not a phone
8
+ * dependency.
9
9
  */
10
10
  export interface LifecycleLogger {
11
11
  child(bindings: Record<string, unknown>): LifecycleLogger;
@@ -3,9 +3,9 @@
3
3
  * `setActive(true)` starts the timer; each tick sends a keep-alive with a
4
4
  * fresh ackId; `maxMissedAcks` consecutive timeouts fire `onTimeout`.
5
5
  *
6
- * Mirror of `cloud/packages/cloud/src/services/streaming/StreamLifecycleController.ts`
7
- * — kept byte-equivalent except for the `LifecycleLogger` interface (pino
8
- * isn't a phone dep). Behavior changes must land in both files.
6
+ * Phone-owned successor to the retired cloud stream lifecycle controller.
7
+ * It uses the local `LifecycleLogger` interface because pino is not a phone
8
+ * dependency.
9
9
  */
10
10
  /**
11
11
  * Drives RTMP stream liveliness checks. Activate to start the heartbeat;
@@ -1 +1 @@
1
- {"version":3,"file":"StreamLifecycleController.js","sourceRoot":"","sources":["../../src/services/StreamLifecycleController.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAgCH;;;;;GAKG;AACH,MAAM,OAAO,yBAAyB;IAkBjB;IAjBX,cAAc,CAAiC;IAC/C,WAAW,GAAgC,IAAI,GAAG,EAAE,CAAA;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;gBACvB,UAAU,EAAE,IAAI,CAAC,UAAU;gBAC3B,aAAa,EAAE,IAAI,CAAC,aAAa;aAClC,EACD,iDAAiD,CAClD,CAAA;YAED,KAAK,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE,CAAA;QACjC,CAAC;IACH,CAAC;IAEO,gBAAgB;QACtB,KAAK,MAAM,EAAC,OAAO,EAAC,IAAI,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE,CAAC;YAClD,YAAY,CAAC,OAAO,CAAC,CAAA;QACvB,CAAC;QACD,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAA;IAC1B,CAAC;IAEO,WAAW;QACjB,OAAO,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;IAChD,CAAC;CACF","sourcesContent":["/**\n * Drives RTMP stream liveliness checks via a keep-alive heartbeat:\n * `setActive(true)` starts the timer; each tick sends a keep-alive with a\n * fresh ackId; `maxMissedAcks` consecutive timeouts fire `onTimeout`.\n *\n * Mirror of `cloud/packages/cloud/src/services/streaming/StreamLifecycleController.ts`\n * — kept byte-equivalent except for the `LifecycleLogger` interface (pino\n * isn't a phone dep). Behavior changes must land in both files.\n */\n\nexport interface LifecycleLogger {\n child(bindings: Record<string, unknown>): LifecycleLogger\n debug(...args: unknown[]): void\n warn(...args: unknown[]): void\n error(...args: unknown[]): void\n}\n\ninterface StreamLifecycleCallbacks {\n sendKeepAlive: (ackId: string) => Promise<void> | void\n onTimeout: () => Promise<void> | void\n onKeepAliveSent?: (ackId: string) => void\n onKeepAliveAcked?: (ackId: string, ageMs: number) => void\n onKeepAliveMissed?: (ackId: string, ageMs: number, missedCount: number) => void\n}\n\nexport interface StreamLifecycleOptions {\n logger: LifecycleLogger\n streamId: string\n keepAliveIntervalMs: number\n ackTimeoutMs: number\n maxMissedAcks: number\n shouldSendKeepAlive?: () => boolean\n now?: () => number\n}\n\ninterface PendingAckInfo {\n sentAt: number\n timeout: ReturnType<typeof setTimeout>\n}\n\n/**\n * Drives RTMP stream liveliness checks. Activate to start the heartbeat;\n * each tick sends a keep-alive with a fresh ackId and arms a timeout. When\n * `maxMissedAcks` consecutive timeouts fire, `onTimeout` is invoked and the\n * caller is expected to tear the stream down.\n */\nexport class StreamLifecycleController {\n private keepAliveTimer?: ReturnType<typeof setInterval>\n private pendingAcks: Map<string, PendingAckInfo> = new Map()\n private missedAcks = 0\n private lastActivityMs: number\n private active = false\n private disposed = false\n\n private readonly logger: LifecycleLogger\n private readonly streamId: string\n private readonly keepAliveIntervalMs: number\n private readonly ackTimeoutMs: number\n private readonly maxMissedAcks: number\n private readonly shouldSendKeepAlive?: () => boolean\n private readonly now: () => number\n\n constructor(\n options: StreamLifecycleOptions,\n private readonly callbacks: StreamLifecycleCallbacks,\n ) {\n this.logger = options.logger.child({component: \"StreamLifecycle\"})\n this.streamId = options.streamId\n this.keepAliveIntervalMs = options.keepAliveIntervalMs\n this.ackTimeoutMs = options.ackTimeoutMs\n this.maxMissedAcks = options.maxMissedAcks\n this.shouldSendKeepAlive = options.shouldSendKeepAlive\n this.now = options.now ?? (() => Date.now())\n this.lastActivityMs = this.now()\n }\n\n setActive(active: boolean): void {\n if (this.disposed || this.active === active) return\n\n this.logger.debug({streamId: this.streamId, active}, \"Updating lifecycle active state\")\n\n this.active = active\n if (active) {\n this.startTimer()\n } else {\n this.stopTimer()\n this.clearPendingAcks()\n this.missedAcks = 0\n }\n }\n\n recordActivity(): void {\n this.lastActivityMs = this.now()\n this.missedAcks = 0\n }\n\n handleAck(ackId: string): void {\n if (this.disposed) return\n\n const ackInfo = this.pendingAcks.get(ackId)\n if (!ackInfo) {\n this.logger.warn({streamId: this.streamId, ackId}, \"Received unknown keep-alive ACK\")\n return\n }\n\n clearTimeout(ackInfo.timeout)\n this.pendingAcks.delete(ackId)\n this.recordActivity()\n\n this.callbacks.onKeepAliveAcked?.(ackId, this.now() - ackInfo.sentAt)\n }\n\n dispose(): void {\n if (this.disposed) return\n\n this.disposed = true\n this.stopTimer()\n this.clearPendingAcks()\n this.logger.debug({streamId: this.streamId}, \"Lifecycle disposed\")\n }\n\n getLastActivityMs(): number {\n return this.lastActivityMs\n }\n\n private startTimer(): void {\n if (this.keepAliveTimer) return\n this.keepAliveTimer = setInterval(() => {\n void this.tick()\n }, this.keepAliveIntervalMs)\n this.logger.debug({streamId: this.streamId}, \"Keep-alive timer started\")\n }\n\n private stopTimer(): void {\n if (this.keepAliveTimer) {\n clearInterval(this.keepAliveTimer)\n this.keepAliveTimer = undefined\n this.logger.debug({streamId: this.streamId}, \"Keep-alive timer stopped\")\n }\n }\n\n private async tick(): Promise<void> {\n if (this.disposed || !this.active) return\n\n if (this.shouldSendKeepAlive && !this.shouldSendKeepAlive()) {\n this.logger.warn(\n {streamId: this.streamId},\n \"Skipping keep-alive send because transport is unavailable\",\n )\n return\n }\n\n const ackId = this.createAckId()\n const sentAt = this.now()\n\n const timeout = setTimeout(() => {\n this.onAckTimeout(ackId, sentAt)\n }, this.ackTimeoutMs)\n\n this.pendingAcks.set(ackId, {sentAt, timeout})\n this.callbacks.onKeepAliveSent?.(ackId)\n\n try {\n await this.callbacks.sendKeepAlive(ackId)\n } catch (error) {\n this.logger.error({streamId: this.streamId, ackId, error}, \"Error sending keep-alive\")\n }\n }\n\n private onAckTimeout(ackId: string, sentAt: number): void {\n if (this.disposed) return\n\n // Race guard: handleAck may have processed the ACK between the timeout\n // being scheduled and this callback running. In that case the ackId is\n // no longer pending — counting it as missed would falsely escalate.\n if (!this.pendingAcks.has(ackId)) return\n\n this.pendingAcks.delete(ackId)\n this.missedAcks += 1\n const ageMs = this.now() - sentAt\n\n this.logger.warn(\n {streamId: this.streamId, ackId, missedAcks: this.missedAcks, ageMs},\n \"Keep-alive ACK timeout\",\n )\n\n this.callbacks.onKeepAliveMissed?.(ackId, ageMs, this.missedAcks)\n\n if (this.missedAcks >= this.maxMissedAcks) {\n this.logger.error(\n {\n streamId: this.streamId,\n missedAcks: this.missedAcks,\n maxMissedAcks: this.maxMissedAcks,\n },\n \"Maximum missed ACKs reached; triggering timeout\",\n )\n\n void this.callbacks.onTimeout()\n }\n }\n\n private clearPendingAcks(): void {\n for (const {timeout} of this.pendingAcks.values()) {\n clearTimeout(timeout)\n }\n this.pendingAcks.clear()\n }\n\n private createAckId(): string {\n return `a${this.now().toString(36).slice(-5)}`\n }\n}\n"]}
1
+ {"version":3,"file":"StreamLifecycleController.js","sourceRoot":"","sources":["../../src/services/StreamLifecycleController.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAgCH;;;;;GAKG;AACH,MAAM,OAAO,yBAAyB;IAkBjB;IAjBX,cAAc,CAAiC;IAC/C,WAAW,GAAgC,IAAI,GAAG,EAAE,CAAA;IACpD,UAAU,GAAG,CAAC,CAAA;IACd,cAAc,CAAQ;IACtB,MAAM,GAAG,KAAK,CAAA;IACd,QAAQ,GAAG,KAAK,CAAA;IAEP,MAAM,CAAiB;IACvB,QAAQ,CAAQ;IAChB,mBAAmB,CAAQ;IAC3B,YAAY,CAAQ;IACpB,aAAa,CAAQ;IACrB,mBAAmB,CAAgB;IACnC,GAAG,CAAc;IAElC,YACE,OAA+B,EACd,SAAmC;QAAnC,cAAS,GAAT,SAAS,CAA0B;QAEpD,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,EAAC,SAAS,EAAE,iBAAiB,EAAC,CAAC,CAAA;QAClE,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAA;QAChC,IAAI,CAAC,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,CAAA;QACtD,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAA;QACxC,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,aAAa,CAAA;QAC1C,IAAI,CAAC,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,CAAA;QACtD,IAAI,CAAC,G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AI,CAAC,CAAA;QACpB,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,MAAM,CAAA;QAEjC,IAAI,CAAC,MAAM,CAAC,IAAI,CACd,EAAC,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,KAAK,EAAC,EACpE,wBAAwB,CACzB,CAAA;QAED,IAAI,CAAC,SAAS,CAAC,iBAAiB,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,CAAA;QAEjE,IAAI,IAAI,CAAC,UAAU,IAAI,IAAI,CAAC,aAAa,EAAE,CAAC;YAC1C,IAAI,CAAC,MAAM,CAAC,KAAK,CACf;gBACE,QAAQ,EAAE,IAAI,CAAC,QAAQ;gBACvB,UAAU,EAAE,IAAI,CAAC,UAAU;gBAC3B,aAAa,EAAE,IAAI,CAAC,aAAa;aAClC,EACD,iDAAiD,CAClD,CAAA;YAED,KAAK,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE,CAAA;QACjC,CAAC;IACH,CAAC;IAEO,gBAAgB;QACtB,KAAK,MAAM,EAAC,OAAO,EAAC,IAAI,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE,CAAC;YAClD,YAAY,CAAC,OAAO,CAAC,CAAA;QACvB,CAAC;QACD,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAA;IAC1B,CAAC;IAEO,WAAW;QACjB,OAAO,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;IAChD,CAAC;CACF","sourcesContent":["/**\n * Drives RTMP stream liveliness checks via a keep-alive heartbeat:\n * `setActive(true)` starts the timer; each tick sends a keep-alive with a\n * fresh ackId; `maxMissedAcks` consecutive timeouts fire `onTimeout`.\n *\n * Phone-owned successor to the retired cloud stream lifecycle controller.\n * It uses the local `LifecycleLogger` interface because pino is not a phone\n * dependency.\n */\n\nexport interface LifecycleLogger {\n child(bindings: Record<string, unknown>): LifecycleLogger\n debug(...args: unknown[]): void\n warn(...args: unknown[]): void\n error(...args: unknown[]): void\n}\n\ninterface StreamLifecycleCallbacks {\n sendKeepAlive: (ackId: string) => Promise<void> | void\n onTimeout: () => Promise<void> | void\n onKeepAliveSent?: (ackId: string) => void\n onKeepAliveAcked?: (ackId: string, ageMs: number) => void\n onKeepAliveMissed?: (ackId: string, ageMs: number, missedCount: number) => void\n}\n\nexport interface StreamLifecycleOptions {\n logger: LifecycleLogger\n streamId: string\n keepAliveIntervalMs: number\n ackTimeoutMs: number\n maxMissedAcks: number\n shouldSendKeepAlive?: () => boolean\n now?: () => number\n}\n\ninterface PendingAckInfo {\n sentAt: number\n timeout: ReturnType<typeof setTimeout>\n}\n\n/**\n * Drives RTMP stream liveliness checks. Activate to start the heartbeat;\n * each tick sends a keep-alive with a fresh ackId and arms a timeout. When\n * `maxMissedAcks` consecutive timeouts fire, `onTimeout` is invoked and the\n * caller is expected to tear the stream down.\n */\nexport class StreamLifecycleController {\n private keepAliveTimer?: ReturnType<typeof setInterval>\n private pendingAcks: Map<string, PendingAckInfo> = new Map()\n private missedAcks = 0\n private lastActivityMs: number\n private active = false\n private disposed = false\n\n private readonly logger: LifecycleLogger\n private readonly streamId: string\n private readonly keepAliveIntervalMs: number\n private readonly ackTimeoutMs: number\n private readonly maxMissedAcks: number\n private readonly shouldSendKeepAlive?: () => boolean\n private readonly now: () => number\n\n constructor(\n options: StreamLifecycleOptions,\n private readonly callbacks: StreamLifecycleCallbacks,\n ) {\n this.logger = options.logger.child({component: \"StreamLifecycle\"})\n this.streamId = options.streamId\n this.keepAliveIntervalMs = options.keepAliveIntervalMs\n this.ackTimeoutMs = options.ackTimeoutMs\n this.maxMissedAcks = options.maxMissedAcks\n this.shouldSendKeepAlive = options.shouldSendKeepAlive\n this.now = options.now ?? (() => Date.now())\n this.lastActivityMs = this.now()\n }\n\n setActive(active: boolean): void {\n if (this.disposed || this.active === active) return\n\n this.logger.debug({streamId: this.streamId, active}, \"Updating lifecycle active state\")\n\n this.active = active\n if (active) {\n this.startTimer()\n } else {\n this.stopTimer()\n this.clearPendingAcks()\n this.missedAcks = 0\n }\n }\n\n recordActivity(): void {\n this.lastActivityMs = this.now()\n this.missedAcks = 0\n }\n\n handleAck(ackId: string): void {\n if (this.disposed) return\n\n const ackInfo = this.pendingAcks.get(ackId)\n if (!ackInfo) {\n this.logger.warn({streamId: this.streamId, ackId}, \"Received unknown keep-alive ACK\")\n return\n }\n\n clearTimeout(ackInfo.timeout)\n this.pendingAcks.delete(ackId)\n this.recordActivity()\n\n this.callbacks.onKeepAliveAcked?.(ackId, this.now() - ackInfo.sentAt)\n }\n\n dispose(): void {\n if (this.disposed) return\n\n this.disposed = true\n this.stopTimer()\n this.clearPendingAcks()\n this.logger.debug({streamId: this.streamId}, \"Lifecycle disposed\")\n }\n\n getLastActivityMs(): number {\n return this.lastActivityMs\n }\n\n private startTimer(): void {\n if (this.keepAliveTimer) return\n this.keepAliveTimer = setInterval(() => {\n void this.tick()\n }, this.keepAliveIntervalMs)\n this.logger.debug({streamId: this.streamId}, \"Keep-alive timer started\")\n }\n\n private stopTimer(): void {\n if (this.keepAliveTimer) {\n clearInterval(this.keepAliveTimer)\n this.keepAliveTimer = undefined\n this.logger.debug({streamId: this.streamId}, \"Keep-alive timer stopped\")\n }\n }\n\n private async tick(): Promise<void> {\n if (this.disposed || !this.active) return\n\n if (this.shouldSendKeepAlive && !this.shouldSendKeepAlive()) {\n this.logger.warn(\n {streamId: this.streamId},\n \"Skipping keep-alive send because transport is unavailable\",\n )\n return\n }\n\n const ackId = this.createAckId()\n const sentAt = this.now()\n\n const timeout = setTimeout(() => {\n this.onAckTimeout(ackId, sentAt)\n }, this.ackTimeoutMs)\n\n this.pendingAcks.set(ackId, {sentAt, timeout})\n this.callbacks.onKeepAliveSent?.(ackId)\n\n try {\n await this.callbacks.sendKeepAlive(ackId)\n } catch (error) {\n this.logger.error({streamId: this.streamId, ackId, error}, \"Error sending keep-alive\")\n }\n }\n\n private onAckTimeout(ackId: string, sentAt: number): void {\n if (this.disposed) return\n\n // Race guard: handleAck may have processed the ACK between the timeout\n // being scheduled and this callback running. In that case the ackId is\n // no longer pending — counting it as missed would falsely escalate.\n if (!this.pendingAcks.has(ackId)) return\n\n this.pendingAcks.delete(ackId)\n this.missedAcks += 1\n const ageMs = this.now() - sentAt\n\n this.logger.warn(\n {streamId: this.streamId, ackId, missedAcks: this.missedAcks, ageMs},\n \"Keep-alive ACK timeout\",\n )\n\n this.callbacks.onKeepAliveMissed?.(ackId, ageMs, this.missedAcks)\n\n if (this.missedAcks >= this.maxMissedAcks) {\n this.logger.error(\n {\n streamId: this.streamId,\n missedAcks: this.missedAcks,\n maxMissedAcks: this.maxMissedAcks,\n },\n \"Maximum missed ACKs reached; triggering timeout\",\n )\n\n void this.callbacks.onTimeout()\n }\n }\n\n private clearPendingAcks(): void {\n for (const {timeout} of this.pendingAcks.values()) {\n clearTimeout(timeout)\n }\n this.pendingAcks.clear()\n }\n\n private createAckId(): string {\n return `a${this.now().toString(36).slice(-5)}`\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"localNetworkTransport.d.ts","sourceRoot":"","sources":["../../../src/services/asg/localNetworkTransport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,6BAA6B,CAAA;AAMnD,KAAK,eAAe,GAAG,UAAU,CAAC,OAAO,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAA;AAC9D,KAAK,cAAc,GAAG,UAAU,CAAC,OAAO,IAAI,CAAC,YAAY,CAAC,CAAA;AAO1D,wBAAgB,2BAA2B,CAAC,EAAE,EAAE,MAAM,EAAE,eAAe,EAAE,OAAO,GAAG,OAAO,CAEzF;AAuBD,eAAO,MAAM,qBAAqB;oCACF,OAAO;oCACP,OAAO;kBAEjB,MAAM,YAAY,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;kBAYtD,OAAO,CAAC,IAAI,CAAC;eAQhB,MAAM,GAAG,GAAG,GAAG,OAAO,SAAS,WAAW,uBAAuB,OAAO,CAAC,QAAQ,CAAC;0BA8B7E,eAAe,GAAG,cAAc;wBA6DlC,MAAM,GAAG,IAAI;CASlC,CAAA"}
1
+ {"version":3,"file":"localNetworkTransport.d.ts","sourceRoot":"","sources":["../../../src/services/asg/localNetworkTransport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,6BAA6B,CAAA;AAMnD,KAAK,eAAe,GAAG,UAAU,CAAC,OAAO,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAA;AAC9D,KAAK,cAAc,GAAG,UAAU,CAAC,OAAO,IAAI,CAAC,YAAY,CAAC,CAAA;AAO1D,wBAAgB,2BAA2B,CAAC,EAAE,EAAE,MAAM,EAAE,eAAe,EAAE,OAAO,GAAG,OAAO,CAEzF;AAuBD,eAAO,MAAM,qBAAqB;oCACF,OAAO;oCACP,OAAO;kBAEjB,MAAM,YAAY,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;kBAYtD,OAAO,CAAC,IAAI,CAAC;eAQhB,MAAM,GAAG,GAAG,GAAG,OAAO,SAAS,WAAW,uBAAuB,OAAO,CAAC,QAAQ,CAAC;0BA8B7E,eAAe,GAAG,cAAc;wBA8DlC,MAAM,GAAG,IAAI;CASlC,CAAA"}
@@ -1,5 +1,5 @@
1
1
  import * as RNFS from "@dr.pogodin/react-native-fs";
2
- import { MentraLocalNetwork } from "@mentra/bluetooth-sdk/internal";
2
+ import { otaLocalNetwork } from "@mentra/bluetooth-sdk/ota-transport";
3
3
  import { Buffer } from "buffer";
4
4
  import { Platform } from "react-native";
5
5
  import WifiManager from "react-native-wifi-reborn";
@@ -11,7 +11,7 @@ export function shouldUseScopedLocalNetwork(os, moduleAvailable) {
11
11
  return os === "android" && moduleAvailable;
12
12
  }
13
13
  function supportsScopedConnection() {
14
- return shouldUseScopedLocalNetwork(Platform.OS, MentraLocalNetwork != null);
14
+ return shouldUseScopedLocalNetwork(Platform.OS, otaLocalNetwork.isAvailable());
15
15
  }
16
16
  function normalizeHeaders(headers) {
17
17
  if (!headers)
@@ -40,22 +40,22 @@ export const localNetworkTransport = {
40
40
  await WifiManager.connectToProtectedSSID(ssid, password, false, false);
41
41
  return undefined;
42
42
  }
43
- const result = await MentraLocalNetwork.connect(ssid, password);
43
+ const result = await otaLocalNetwork.connect(ssid, password);
44
44
  scopedConnectionActive = true;
45
45
  return result.localAddress;
46
46
  },
47
47
  async disconnect() {
48
48
  if (supportsScopedConnection()) {
49
- await MentraLocalNetwork.disconnect().catch(() => { });
49
+ await otaLocalNetwork.disconnect().catch(() => { });
50
50
  }
51
51
  scopedConnectionActive = false;
52
52
  nativeJobs.clear();
53
53
  },
54
54
  async fetch(url, init, timeoutMs = 30_000) {
55
- if (!scopedConnectionActive || !MentraLocalNetwork || typeof url !== "string") {
55
+ if (!scopedConnectionActive || !otaLocalNetwork.isAvailable() || typeof url !== "string") {
56
56
  return globalThis.fetch(url, init);
57
57
  }
58
- const nativeModule = MentraLocalNetwork;
58
+ const nativeModule = otaLocalNetwork;
59
59
  const id = requestId("request");
60
60
  const signal = init?.signal;
61
61
  const cancel = () => void nativeModule.cancel(id);
@@ -75,13 +75,13 @@ export const localNetworkTransport = {
75
75
  }
76
76
  },
77
77
  downloadFile(options) {
78
- if (!scopedConnectionActive || !MentraLocalNetwork)
78
+ if (!scopedConnectionActive || !otaLocalNetwork.isAvailable())
79
79
  return RNFS.downloadFile(options);
80
80
  const jobId = nextJobId++;
81
81
  const id = requestId("download");
82
82
  let began = false;
83
83
  nativeJobs.set(jobId, id);
84
- const subscription = MentraLocalNetwork.addListener("downloadProgress", (event) => {
84
+ const subscription = otaLocalNetwork.onDownloadProgress((event) => {
85
85
  if (event.requestId !== id)
86
86
  return;
87
87
  if (!began) {
@@ -99,7 +99,8 @@ export const localNetworkTransport = {
99
99
  bytesWritten: event.bytesWritten,
100
100
  });
101
101
  });
102
- const promise = MentraLocalNetwork.download(id, options.fromUrl, options.toFile, options.headers || {}, options.connectionTimeout || 30_000, options.readTimeout || 30_000)
102
+ const promise = otaLocalNetwork
103
+ .download(id, options.fromUrl, options.toFile, options.headers || {}, options.connectionTimeout || 30_000, options.readTimeout || 30_000)
103
104
  .then((result) => {
104
105
  if (!began) {
105
106
  options.begin?.({
@@ -129,15 +130,15 @@ export const localNetworkTransport = {
129
130
  },
130
131
  stopDownload(jobId) {
131
132
  const nativeId = nativeJobs.get(jobId);
132
- if (nativeId && MentraLocalNetwork) {
133
+ if (nativeId && otaLocalNetwork.isAvailable()) {
133
134
  cancelledNativeJobs.add(jobId);
134
- void MentraLocalNetwork.cancel(nativeId);
135
+ void otaLocalNetwork.cancel(nativeId);
135
136
  return;
136
137
  }
137
138
  RNFS.stopDownload(jobId);
138
139
  },
139
140
  };
140
- MentraLocalNetwork?.addListener("networkLost", () => {
141
+ otaLocalNetwork.onNetworkLost(() => {
141
142
  scopedConnectionActive = false;
142
143
  nativeJobs.clear();
143
144
  });
@@ -1 +1 @@
1
- {"version":3,"file":"localNetworkTransport.js","sourceRoot":"","sources":["../../../src/services/asg/localNetworkTransport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,6BAA6B,CAAA;AACnD,OAAO,EAAC,kBAAkB,EAAoC,MAAM,gCAAgC,CAAA;AACpG,OAAO,EAAC,MAAM,EAAC,MAAM,QAAQ,CAAA;AAC7B,OAAO,EAAC,QAAQ,EAAC,MAAM,cAAc,CAAA;AACrC,OAAO,WAAW,MAAM,0BAA0B,CAAA;AAKlD,IAAI,sBAAsB,GAAG,KAAK,CAAA;AAClC,IAAI,SAAS,GAAG,SAAS,CAAA;AACzB,MAAM,UAAU,GAAG,IAAI,GAAG,EAAkB,CAAA;AAC5C,MAAM,mBAAmB,GAAG,IAAI,GAAG,EAAU,CAAA;AAE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AA;QACvB,CAAC,CAAC,CAAA;QAEJ,OAAO,EAAC,KAAK,EAAE,OAAO,EAAmB,CAAA;IAC3C,CAAC;IAED,YAAY,CAAC,KAAa;QACxB,MAAM,QAAQ,GAAG,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;QACtC,IAAI,QAAQ,IAAI,kBAAkB,EAAE,CAAC;YACnC,mBAAmB,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;YAC9B,KAAK,kBAAkB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAA;YACxC,OAAM;QACR,CAAC;QACD,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAA;IAC1B,CAAC;CACF,CAAA;AAED,kBAAkB,EAAE,WAAW,CAAC,aAAa,EAAE,GAAG,EAAE;IAClD,sBAAsB,GAAG,KAAK,CAAA;IAC9B,UAAU,CAAC,KAAK,EAAE,CAAA;AACpB,CAAC,CAAC,CAAA","sourcesContent":["import * as RNFS from \"@dr.pogodin/react-native-fs\"\nimport {MentraLocalNetwork, type LocalNetworkDownloadProgress} from \"@mentra/bluetooth-sdk/internal\"\nimport {Buffer} from \"buffer\"\nimport {Platform} from \"react-native\"\nimport WifiManager from \"react-native-wifi-reborn\"\n\ntype DownloadOptions = Parameters<typeof RNFS.downloadFile>[0]\ntype DownloadHandle = ReturnType<typeof RNFS.downloadFile>\n\nlet scopedConnectionActive = false\nlet nextJobId = 1_000_000\nconst nativeJobs = new Map<number, string>()\nconst cancelledNativeJobs = new Set<number>()\n\nexport function shouldUseScopedLocalNetwork(os: string, moduleAvailable: boolean): boolean {\n return os === \"android\" && moduleAvailable\n}\n\nfunction supportsScopedConnection(): boolean {\n return shouldUseScopedLocalNetwork(Platform.OS, MentraLocalNetwork != null)\n}\n\nfunction normalizeHeaders(headers?: HeadersInit): Record<string, string> {\n if (!headers) return {}\n if (headers instanceof Headers) {\n const result: Record<string, string> = {}\n headers.forEach((value, key) => {\n result[key] = value\n })\n return result\n }\n if (Array.isArray(headers)) return Object.fromEntries(headers)\n return {...headers}\n}\n\nfunction requestId(prefix: string): string {\n return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2)}`\n}\n\nexport const localNetworkTransport = {\n supportsScopedConnection: (): boolean => supportsScopedConnection(),\n isScopedConnectionActive: (): boolean => scopedConnectionActive,\n\n async connect(ssid: string, password: string): Promise<string | undefined> {\n scopedConnectionActive = false\n nativeJobs.clear()\n if (!supportsScopedConnection()) {\n await WifiManager.connectToProtectedSSID(ssid, password, false, false)\n return undefined\n }\n const result = await MentraLocalNetwork!.connect(ssid, password)\n scopedConnectionActive = true\n return result.localAddress\n },\n\n async disconnect(): Promise<void> {\n if (supportsScopedConnection()) {\n await MentraLocalNetwork!.disconnect().catch(() => {})\n }\n scopedConnectionActive = false\n nativeJobs.clear()\n },\n\n async fetch(url: string | URL | Request, init?: RequestInit, timeoutMs = 30_000): Promise<Response> {\n if (!scopedConnectionActive || !MentraLocalNetwork || typeof url !== \"string\") {\n return globalThis.fetch(url, init)\n }\n\n const nativeModule = MentraLocalNetwork\n const id = requestId(\"request\")\n const signal = init?.signal\n const cancel = () => void nativeModule.cancel(id)\n if (signal?.aborted) throw new Error(\"Request aborted\")\n signal?.addEventListener(\"abort\", cancel, {once: true})\n try {\n const result = await nativeModule.request(\n id,\n url,\n init?.method || \"GET\",\n normalizeHeaders(init?.headers),\n typeof init?.body === \"string\" ? init.body : null,\n timeoutMs,\n )\n const bytes = Buffer.from(result.bodyBase64, \"base64\")\n return new Response(bytes as unknown as BodyInit, {\n status: result.status,\n headers: result.headers,\n })\n } finally {\n signal?.removeEventListener(\"abort\", cancel)\n }\n },\n\n downloadFile(options: DownloadOptions): DownloadHandle {\n if (!scopedConnectionActive || !MentraLocalNetwork) return RNFS.downloadFile(options)\n\n const jobId = nextJobId++\n const id = requestId(\"download\")\n let began = false\n nativeJobs.set(jobId, id)\n const subscription = MentraLocalNetwork.addListener(\"downloadProgress\", (event: LocalNetworkDownloadProgress) => {\n if (event.requestId !== id) return\n if (!began) {\n began = true\n options.begin?.({\n jobId,\n statusCode: event.statusCode || 200,\n contentLength: event.contentLength,\n headers: event.headers || {},\n })\n }\n options.progress?.({\n jobId,\n contentLength: event.contentLength,\n bytesWritten: event.bytesWritten,\n })\n })\n\n const promise = MentraLocalNetwork.download(\n id,\n options.fromUrl,\n options.toFile,\n options.headers || {},\n options.connectionTimeout || 30_000,\n options.readTimeout || 30_000,\n )\n .then((result) => {\n if (!began) {\n options.begin?.({\n jobId,\n statusCode: result.statusCode,\n contentLength: result.bytesWritten,\n headers: result.headers,\n })\n }\n return {\n jobId,\n statusCode: result.statusCode,\n bytesWritten: result.bytesWritten,\n }\n })\n .catch((error) => {\n if (cancelledNativeJobs.has(jobId)) throw new Error(\"Sync cancelled\")\n throw error\n })\n .finally(() => {\n nativeJobs.delete(jobId)\n cancelledNativeJobs.delete(jobId)\n subscription.remove()\n })\n\n return {jobId, promise} as DownloadHandle\n },\n\n stopDownload(jobId: number): void {\n const nativeId = nativeJobs.get(jobId)\n if (nativeId && MentraLocalNetwork) {\n cancelledNativeJobs.add(jobId)\n void MentraLocalNetwork.cancel(nativeId)\n return\n }\n RNFS.stopDownload(jobId)\n },\n}\n\nMentraLocalNetwork?.addListener(\"networkLost\", () => {\n scopedConnectionActive = false\n nativeJobs.clear()\n})\n"]}
1
+ {"version":3,"file":"localNetworkTransport.js","sourceRoot":"","sources":["../../../src/services/asg/localNetworkTransport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,6BAA6B,CAAA;AACnD,OAAO,EAAC,eAAe,EAAuC,MAAM,qCAAqC,CAAA;AACzG,OAAO,EAAC,MAAM,EAAC,MAAM,QAAQ,CAAA;AAC7B,OAAO,EAAC,QAAQ,EAAC,MAAM,cAAc,CAAA;AACrC,OAAO,WAAW,MAAM,0BAA0B,CAAA;AAKlD,IAAI,sBAAsB,GAAG,KAAK,CAAA;AAClC,IAAI,SAAS,GAAG,SAAS,CAAA;AACzB,MAAM,UAAU,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,CAAC,CAAA;YACxB,mBAAmB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YACjC,YAAY,CAAC,MAAM,EAAE,CAAA;QACvB,CAAC,CAAC,CAAA;QAEJ,OAAO,EAAC,KAAK,EAAE,OAAO,EAAmB,CAAA;IAC3C,CAAC;IAED,YAAY,CAAC,KAAa;QACxB,MAAM,QAAQ,GAAG,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;QACtC,IAAI,QAAQ,IAAI,eAAe,CAAC,WAAW,EAAE,EAAE,CAAC;YAC9C,mBAAmB,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;YAC9B,KAAK,eAAe,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAA;YACrC,OAAM;QACR,CAAC;QACD,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAA;IAC1B,CAAC;CACF,CAAA;AAED,eAAe,CAAC,aAAa,CAAC,GAAG,EAAE;IACjC,sBAAsB,GAAG,KAAK,CAAA;IAC9B,UAAU,CAAC,KAAK,EAAE,CAAA;AACpB,CAAC,CAAC,CAAA","sourcesContent":["import * as RNFS from \"@dr.pogodin/react-native-fs\"\nimport {otaLocalNetwork, type OtaLocalNetworkDownloadProgress} from \"@mentra/bluetooth-sdk/ota-transport\"\nimport {Buffer} from \"buffer\"\nimport {Platform} from \"react-native\"\nimport WifiManager from \"react-native-wifi-reborn\"\n\ntype DownloadOptions = Parameters<typeof RNFS.downloadFile>[0]\ntype DownloadHandle = ReturnType<typeof RNFS.downloadFile>\n\nlet scopedConnectionActive = false\nlet nextJobId = 1_000_000\nconst nativeJobs = new Map<number, string>()\nconst cancelledNativeJobs = new Set<number>()\n\nexport function shouldUseScopedLocalNetwork(os: string, moduleAvailable: boolean): boolean {\n return os === \"android\" && moduleAvailable\n}\n\nfunction supportsScopedConnection(): boolean {\n return shouldUseScopedLocalNetwork(Platform.OS, otaLocalNetwork.isAvailable())\n}\n\nfunction normalizeHeaders(headers?: HeadersInit): Record<string, string> {\n if (!headers) return {}\n if (headers instanceof Headers) {\n const result: Record<string, string> = {}\n headers.forEach((value, key) => {\n result[key] = value\n })\n return result\n }\n if (Array.isArray(headers)) return Object.fromEntries(headers)\n return {...headers}\n}\n\nfunction requestId(prefix: string): string {\n return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2)}`\n}\n\nexport const localNetworkTransport = {\n supportsScopedConnection: (): boolean => supportsScopedConnection(),\n isScopedConnectionActive: (): boolean => scopedConnectionActive,\n\n async connect(ssid: string, password: string): Promise<string | undefined> {\n scopedConnectionActive = false\n nativeJobs.clear()\n if (!supportsScopedConnection()) {\n await WifiManager.connectToProtectedSSID(ssid, password, false, false)\n return undefined\n }\n const result = await otaLocalNetwork.connect(ssid, password)\n scopedConnectionActive = true\n return result.localAddress\n },\n\n async disconnect(): Promise<void> {\n if (supportsScopedConnection()) {\n await otaLocalNetwork.disconnect().catch(() => {})\n }\n scopedConnectionActive = false\n nativeJobs.clear()\n },\n\n async fetch(url: string | URL | Request, init?: RequestInit, timeoutMs = 30_000): Promise<Response> {\n if (!scopedConnectionActive || !otaLocalNetwork.isAvailable() || typeof url !== \"string\") {\n return globalThis.fetch(url, init)\n }\n\n const nativeModule = otaLocalNetwork\n const id = requestId(\"request\")\n const signal = init?.signal\n const cancel = () => void nativeModule.cancel(id)\n if (signal?.aborted) throw new Error(\"Request aborted\")\n signal?.addEventListener(\"abort\", cancel, {once: true})\n try {\n const result = await nativeModule.request(\n id,\n url,\n init?.method || \"GET\",\n normalizeHeaders(init?.headers),\n typeof init?.body === \"string\" ? init.body : null,\n timeoutMs,\n )\n const bytes = Buffer.from(result.bodyBase64, \"base64\")\n return new Response(bytes as unknown as BodyInit, {\n status: result.status,\n headers: result.headers,\n })\n } finally {\n signal?.removeEventListener(\"abort\", cancel)\n }\n },\n\n downloadFile(options: DownloadOptions): DownloadHandle {\n if (!scopedConnectionActive || !otaLocalNetwork.isAvailable()) return RNFS.downloadFile(options)\n\n const jobId = nextJobId++\n const id = requestId(\"download\")\n let began = false\n nativeJobs.set(jobId, id)\n const subscription = otaLocalNetwork.onDownloadProgress((event: OtaLocalNetworkDownloadProgress) => {\n if (event.requestId !== id) return\n if (!began) {\n began = true\n options.begin?.({\n jobId,\n statusCode: event.statusCode || 200,\n contentLength: event.contentLength,\n headers: event.headers || {},\n })\n }\n options.progress?.({\n jobId,\n contentLength: event.contentLength,\n bytesWritten: event.bytesWritten,\n })\n })\n\n const promise = otaLocalNetwork\n .download(\n id,\n options.fromUrl,\n options.toFile,\n options.headers || {},\n options.connectionTimeout || 30_000,\n options.readTimeout || 30_000,\n )\n .then((result) => {\n if (!began) {\n options.begin?.({\n jobId,\n statusCode: result.statusCode,\n contentLength: result.bytesWritten,\n headers: result.headers,\n })\n }\n return {\n jobId,\n statusCode: result.statusCode,\n bytesWritten: result.bytesWritten,\n }\n })\n .catch((error) => {\n if (cancelledNativeJobs.has(jobId)) throw new Error(\"Sync cancelled\")\n throw error\n })\n .finally(() => {\n nativeJobs.delete(jobId)\n cancelledNativeJobs.delete(jobId)\n subscription.remove()\n })\n\n return {jobId, promise} as DownloadHandle\n },\n\n stopDownload(jobId: number): void {\n const nativeId = nativeJobs.get(jobId)\n if (nativeId && otaLocalNetwork.isAvailable()) {\n cancelledNativeJobs.add(jobId)\n void otaLocalNetwork.cancel(nativeId)\n return\n }\n RNFS.stopDownload(jobId)\n },\n}\n\notaLocalNetwork.onNetworkLost(() => {\n scopedConnectionActive = false\n nativeJobs.clear()\n})\n"]}
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Push phone time to glasses only when clock skew is detected (gallery sync, OTA, etc.).
3
3
  */
4
- import BluetoothSdk from "@mentra/bluetooth-sdk/internal";
4
+ import BluetoothSdk from "@mentra/bluetooth-sdk";
5
5
  import { BgTimer } from "../utils/timers";
6
6
  import { useGlassesStore } from "../stores/glasses";
7
7
  import { resolveOtaManifestUrl } from "./otaManifestUrl";
@@ -1 +1 @@
1
- {"version":3,"file":"glassesClockSync.js","source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;YAED,iBAAiB,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;YAC9B,MAAM,EAAC,WAAW,EAAE,aAAa,EAAC,GAAG,eAAe,CAAC,QAAQ,EAAE,CAAA;YAC/D,MAAM,WAAW,GAAG,qBAAqB,CAAC,aAAa,EAAE,WAAW,CAAC,CAAA;YACrE,IAAI,CAAC,WAAW,EAAE,CAAC;gBACjB,OAAO,CAAC,IAAI,CAAC,+EAA+E,CAAC,CAAA;gBAC7F,OAAO,KAAK,CAAA;YACd,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,oEAAoE,CAAC,CAAA;YACjF,MAAM,YAAY,CAAC,cAAc,CAAC,WAAW,CAAC,CAAA;YAC9C,OAAO,IAAI,CAAA;QACb,CAAC;gBAAS,CAAC;YACT,mBAAmB,GAAG,IAAI,CAAA;QAC5B,CAAC;IACH,CAAC,CAAC,EAAE,CAAA;IAEJ,OAAO,mBAAmB,CAAA;AAC5B,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,YAAgC;IACxF,IAAI,OAAO,YAAY,KAAK,QAAQ,IAAI,YAAY,IAAI,CAAC,EAAE,CAAC;QAC1D,OAAO,KAAK,CAAA;IACd,CAAC;IAED,MAAM,KAAK,GAAG,MAAM,uBAAuB,CAAC,YAAY,EAAE,CAAC,CAAC,CAAA;IAC5D,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,KAAK,CAAA;IACd,CAAC;IAED,OAAO,IAAI,CAAA;AACb,CAAC","sourcesContent":["/**\n * Push phone time to glasses only when clock skew is detected (gallery sync, OTA, etc.).\n */\n\nimport BluetoothSdk from \"@mentra/bluetooth-sdk/internal\"\nimport {BgTimer} from \"../utils/timers\"\nimport {useGlassesStore} from \"../stores/glasses\"\n\nimport {resolveOtaManifestUrl} from \"./otaManifestUrl\"\nimport {detectClockSkew} from \"./gallerySyncClock\"\n\nexport const CLOCK_SETTLE_MS = 500\n\nconst OTA_CLOCK_FIX_COOLDOWN_MS = 30_000\nlet lastOtaClockFixAt = 0\n// Coalesce concurrent OTA clock-fix attempts. Glasses can emit two clock_skew events\n// back-to-back during BLE handshake; without this guard both would await the BLE fix\n// + retry pair before either updated `lastOtaClockFixAt`.\nlet inflightOtaClockFix: Promise<boolean> | null = null\n\n/** @internal test-only */\nexport function resetOtaClockFixCooldownForTests(): void {\n lastOtaClockFixAt = 0\n inflightOtaClockFix = null\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => BgTimer.setTimeout(resolve, ms))\n}\n\n/**\n * Set glasses system clock from phone when skew is detected.\n */\nexport async function fixGlassesClockIfSkewed(glassesServerTime: number, lastSyncTime = 0): Promise<boolean> {\n const {skewed, reason} = detectClockSkew(Date.now(), glassesServerTime, lastSyncTime)\n if (!skewed) {\n return false\n }\n console.log(`[GlassesClockSync] ⏰ Clock skew detected (${reason}) — setting glasses time from phone`)\n await BluetoothSdk.setSystemTime(Date.now())\n await delay(CLOCK_SETTLE_MS)\n return true\n}\n\n/**\n * After glasses report OTA failure due to clock skew, fix time and restart\n * through the normal phone-driven ota_start path.\n */\nexport async function handleOtaClockSkewFromGlasses(\n errorCode: string | undefined,\n glassesTimeMs?: number,\n): Promise<boolean> {\n if (Date.now() - lastOtaClockFixAt < OTA_CLOCK_FIX_COOLDOWN_MS) {\n return false\n }\n\n const hasGlassesTime = typeof glassesTimeMs === \"number\" && Number.isFinite(glassesTimeMs) && glassesTimeMs > 0\n\n if (errorCode === \"ssl_error\") {\n if (!hasGlassesTime) {\n return false\n }\n const {skewed} = detectClockSkew(Date.now(), glassesTimeMs, 0)\n if (!skewed) {\n return false\n }\n console.log(\"[GlassesClockSync] ⏰ OTA ssl_error with wall-clock drift — treating as clock skew\")\n } else if (errorCode !== \"clock_skew\") {\n return false\n }\n\n // Coalesce concurrent attempts: if a fix is already in flight, await its result instead\n // of racing it through the cooldown guard.\n if (inflightOtaClockFix) {\n return inflightOtaClockFix\n }\n\n const glassesTime = hasGlassesTime ? glassesTimeMs : Date.now() - 86_400_000\n\n inflightOtaClockFix = (async () => {\n try {\n const fixed = await fixGlassesClockIfSkewed(glassesTime, 0)\n if (!fixed) {\n return false\n }\n\n lastOtaClockFixAt = Date.now()\n const {buildNumber, otaVersionUrl} = useGlassesStore.getState()\n const manifestUrl = resolveOtaManifestUrl(otaVersionUrl, buildNumber)\n if (!manifestUrl) {\n console.warn(\"[GlassesClockSync] OTA restart skipped because this build has no manifest pin\")\n return false\n }\n console.log(\"[GlassesClockSync] ⏰ Restarting OTA with ota_start after clock fix\")\n await BluetoothSdk.startOtaUpdate(manifestUrl)\n return true\n } finally {\n inflightOtaClockFix = null\n }\n })()\n\n return inflightOtaClockFix\n}\n\n/**\n * Proactive fix when version_info includes glasses system_time_ms before OTA manifest checks.\n */\nexport async function maybeFixGlassesClockFromVersionInfo(systemTimeMs: number | undefined): Promise<boolean> {\n if (typeof systemTimeMs !== \"number\" || systemTimeMs <= 0) {\n return false\n }\n\n const fixed = await fixGlassesClockIfSkewed(systemTimeMs, 0)\n if (!fixed) {\n return false\n }\n\n return true\n}\n"]}
1
+ {"version":3,"file":"glassesClockSync.js","sourceRoot":"","sources":["../../src/services/glassesClockSync.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,YAAY,MAAM,uBAAuB,CAAA;AAChD,OAAO,EAAC,OAAO,EAAC,MAAM,iBAAiB,CAAA;AACvC,OAAO,EAAC,eAAe,EAAC,MAAM,mBAAmB,CAAA;AAEjD,OAAO,EAAC,qBAAqB,EAAC,MAAM,kBAAkB,CAAA;AACtD,OAAO,EAAC,eAAe,EAAC,MAAM,oBAAoB,CAAA;AAElD,MAAM,CAAC,MAAM,eAAe,GAAG,GAAG,CAAA;AAElC,MAAM,yBAAyB,GAAG,MAAM,CAAA;AACxC,IAAI,iBAAiB,GAAG,CAAC,CAAA;AACzB,qFAAqF;AACrF,qFAAqF;AACrF,0DAA0D;AAC1D,IAAI,mBAAmB,GAA4B,IAAI,CAAA;AAEvD,0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;IACH,CAAC,CAAC,EAAE,CAAA;IAEJ,OAAO,mBAAmB,CAAA;AAC5B,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,YAAgC;IACxF,IAAI,OAAO,YAAY,KAAK,QAAQ,IAAI,YAAY,IAAI,CAAC,EAAE,CAAC;QAC1D,OAAO,KAAK,CAAA;IACd,CAAC;IAED,MAAM,KAAK,GAAG,MAAM,uBAAuB,CAAC,YAAY,EAAE,CAAC,CAAC,CAAA;IAC5D,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,KAAK,CAAA;IACd,CAAC;IAED,OAAO,IAAI,CAAA;AACb,CAAC","sourcesContent":["/**\n * Push phone time to glasses only when clock skew is detected (gallery sync, OTA, etc.).\n */\n\nimport BluetoothSdk from \"@mentra/bluetooth-sdk\"\nimport {BgTimer} from \"../utils/timers\"\nimport {useGlassesStore} from \"../stores/glasses\"\n\nimport {resolveOtaManifestUrl} from \"./otaManifestUrl\"\nimport {detectClockSkew} from \"./gallerySyncClock\"\n\nexport const CLOCK_SETTLE_MS = 500\n\nconst OTA_CLOCK_FIX_COOLDOWN_MS = 30_000\nlet lastOtaClockFixAt = 0\n// Coalesce concurrent OTA clock-fix attempts. Glasses can emit two clock_skew events\n// back-to-back during BLE handshake; without this guard both would await the BLE fix\n// + retry pair before either updated `lastOtaClockFixAt`.\nlet inflightOtaClockFix: Promise<boolean> | null = null\n\n/** @internal test-only */\nexport function resetOtaClockFixCooldownForTests(): void {\n lastOtaClockFixAt = 0\n inflightOtaClockFix = null\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => BgTimer.setTimeout(resolve, ms))\n}\n\n/**\n * Set glasses system clock from phone when skew is detected.\n */\nexport async function fixGlassesClockIfSkewed(glassesServerTime: number, lastSyncTime = 0): Promise<boolean> {\n const {skewed, reason} = detectClockSkew(Date.now(), glassesServerTime, lastSyncTime)\n if (!skewed) {\n return false\n }\n console.log(`[GlassesClockSync] ⏰ Clock skew detected (${reason}) — setting glasses time from phone`)\n await BluetoothSdk.setSystemTime(Date.now())\n await delay(CLOCK_SETTLE_MS)\n return true\n}\n\n/**\n * After glasses report OTA failure due to clock skew, fix time and restart\n * through the normal phone-driven ota_start path.\n */\nexport async function handleOtaClockSkewFromGlasses(\n errorCode: string | undefined,\n glassesTimeMs?: number,\n): Promise<boolean> {\n if (Date.now() - lastOtaClockFixAt < OTA_CLOCK_FIX_COOLDOWN_MS) {\n return false\n }\n\n const hasGlassesTime = typeof glassesTimeMs === \"number\" && Number.isFinite(glassesTimeMs) && glassesTimeMs > 0\n\n if (errorCode === \"ssl_error\") {\n if (!hasGlassesTime) {\n return false\n }\n const {skewed} = detectClockSkew(Date.now(), glassesTimeMs, 0)\n if (!skewed) {\n return false\n }\n console.log(\"[GlassesClockSync] ⏰ OTA ssl_error with wall-clock drift — treating as clock skew\")\n } else if (errorCode !== \"clock_skew\") {\n return false\n }\n\n // Coalesce concurrent attempts: if a fix is already in flight, await its result instead\n // of racing it through the cooldown guard.\n if (inflightOtaClockFix) {\n return inflightOtaClockFix\n }\n\n const glassesTime = hasGlassesTime ? glassesTimeMs : Date.now() - 86_400_000\n\n inflightOtaClockFix = (async () => {\n try {\n const fixed = await fixGlassesClockIfSkewed(glassesTime, 0)\n if (!fixed) {\n return false\n }\n\n lastOtaClockFixAt = Date.now()\n const {buildNumber, otaVersionUrl} = useGlassesStore.getState()\n const manifestUrl = resolveOtaManifestUrl(otaVersionUrl, buildNumber)\n if (!manifestUrl) {\n console.warn(\"[GlassesClockSync] OTA restart skipped because this build has no manifest pin\")\n return false\n }\n console.log(\"[GlassesClockSync] ⏰ Restarting OTA with ota_start after clock fix\")\n await BluetoothSdk.startOtaUpdate(manifestUrl)\n return true\n } finally {\n inflightOtaClockFix = null\n }\n })()\n\n return inflightOtaClockFix\n}\n\n/**\n * Proactive fix when version_info includes glasses system_time_ms before OTA manifest checks.\n */\nexport async function maybeFixGlassesClockFromVersionInfo(systemTimeMs: number | undefined): Promise<boolean> {\n if (typeof systemTimeMs !== \"number\" || systemTimeMs <= 0) {\n return false\n }\n\n const fixed = await fixGlassesClockIfSkewed(systemTimeMs, 0)\n if (!fixed) {\n return false\n }\n\n return true\n}\n"]}
@@ -30,6 +30,8 @@ export declare const PING_INTERVAL_MS = 10000;
30
30
  export declare const QUERY_REPLY_TIMEOUT_MS = 6000;
31
31
  /** 15s lockout on the Continue button after a BES restart, to prevent an accidental tap. */
32
32
  export declare const BES_CONTINUE_LOCKOUT_MS = 15000;
33
+ /** Fail closed if a BES reboot never reconnects; normal restarts complete in a fraction of this window. */
34
+ export declare const BES_RESTART_TIMEOUT_MS = 120000;
33
35
  /** The uniform pad progress-legacy.tsx added to every duration for old builds. */
34
36
  export declare const LEGACY_EXTRA_TIMEOUT_MS = 20000;
35
37
  export declare const LEGACY_RETRY_INTERVAL_MS: number;
@@ -39,6 +41,7 @@ export declare const LEGACY_MTK_INSTALL_TIMEOUT_MS: number;
39
41
  export declare const LEGACY_GLOBAL_OTA_TIMEOUT_MS: number;
40
42
  export declare const LEGACY_PING_INTERVAL_MS: number;
41
43
  export declare const LEGACY_BES_CONTINUE_LOCKOUT_MS: number;
44
+ export declare const LEGACY_BES_RESTART_TIMEOUT_MS: number;
42
45
  /**
43
46
  * After a legacy apk `install FINISHED` observed in-flight, the legacy screen held the
44
47
  * completed state for 12s (+20s pad) so the ASG process restart settles (and fresh
@@ -82,6 +85,7 @@ export declare function selectOtaProtocolProfile(otaStatus: OtaStatus | null, ot
82
85
  export declare const OtaProgressMessages: {
83
86
  readonly stalledOrStuck: "Update may have failed. Ensure glasses have internet access and try again.";
84
87
  readonly globalTimeout: "Update took too long. Please try again.";
88
+ readonly restartTimeout: "Glasses did not finish restarting. Restart them before trying the update again.";
85
89
  readonly sendOtaStartFailed: "Failed to communicate with glasses.";
86
90
  readonly hotspotArtifactDownloadFailed: "Could not download the update to your phone. Check phone internet and try again.";
87
91
  readonly hotspotArtifactVerifyFailed: "The update package could not be verified. Please try again later.";
@@ -1 +1 @@
1
- {"version":3,"file":"otaInstallPolicy.d.ts","sourceRoot":"","sources":["../../src/services/otaInstallPolicy.ts"],"names":[],"mappings":"AAAA,qFAAqF;AACrF,OAAO,KAAK,EAAC,WAAW,EAAE,SAAS,EAAC,MAAM,uBAAuB,CAAA;AAEjE;;;;;GAKG;AACH,eAAO,MAAM,wBAAwB,KAAK,CAAA;AAE1C,eAAO,MAAM,WAAW,IAAI,CAAA;AAC5B,sFAAsF;AACtF,eAAO,MAAM,iBAAiB,OAAO,CAAA;AACrC,oEAAoE;AACpE,eAAO,MAAM,mBAAmB,SAAU,CAAA;AAC1C,kDAAkD;AAClD,eAAO,MAAM,yBAAyB,QAAS,CAAA;AAC/C,2DAA2D;AAC3D,eAAO,MAAM,sBAAsB,SAAU,CAAA;AAC7C,mCAAmC;AACnC,eAAO,MAAM,qBAAqB,QAAiB,CAAA;AACnD,+BAA+B;AAC/B,eAAO,MAAM,gBAAgB,QAAS,CAAA;AACtC;;;;;;GAMG;AACH,eAAO,MAAM,sBAAsB,OAAO,CAAA;AAC1C,4FAA4F;AAC5F,eAAO,MAAM,uBAAuB,QAAS,CAAA;AAW7C,kFAAkF;AAClF,eAAO,MAAM,uBAAuB,QAAS,CAAA;AAC7C,eAAO,MAAM,wBAAwB,QAA8C,CAAA;AACnF,eAAO,MAAM,0BAA0B,QAAgD,CAAA;AACvF,eAAO,MAAM,gCAAgC,QAAsD,CAAA;AACnG,eAAO,MAAM,6BAA6B,QAAmD,CAAA;AAC7F,eAAO,MAAM,4BAA4B,QAAkD,CAAA;AAC3F,eAAO,MAAM,uBAAuB,QAA6C,CAAA;AACjF,eAAO,MAAM,8BAA8B,QAAoD,CAAA;AAC/F;;;;GAIG;AACH,eAAO,MAAM,+BAA+B,QAAmC,CAAA;AAC/E;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,QAAmC,CAAA;AAC1E,eAAO,MAAM,sBAAsB,QAAmC,CAAA;AACtE,eAAO,MAA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