@mentra/engine 3.2.0-dev.261 → 3.2.0-dev.262
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/generated/releaseMetadata.js +5 -5
- package/build/generated/releaseMetadata.js.map +1 -1
- package/build/services/AcsMeetingService.d.ts +25 -1
- package/build/services/AcsMeetingService.d.ts.map +1 -1
- package/build/services/AcsMeetingService.js +41 -3
- package/build/services/AcsMeetingService.js.map +1 -1
- package/build/services/LocalMiniappRuntime.d.ts +32 -3
- package/build/services/LocalMiniappRuntime.d.ts.map +1 -1
- package/build/services/LocalMiniappRuntime.js +284 -30
- package/build/services/LocalMiniappRuntime.js.map +1 -1
- package/build/services/MiniappLiveness.d.ts +11 -0
- package/build/services/MiniappLiveness.d.ts.map +1 -1
- package/build/services/MiniappLiveness.js +11 -0
- package/build/services/MiniappLiveness.js.map +1 -1
- package/build/services/PhoneStreamCoordinator.d.ts +13 -1
- package/build/services/PhoneStreamCoordinator.d.ts.map +1 -1
- package/build/services/PhoneStreamCoordinator.js +27 -4
- package/build/services/PhoneStreamCoordinator.js.map +1 -1
- package/build/services/SoftapCallTransport.d.ts +87 -7
- package/build/services/SoftapCallTransport.d.ts.map +1 -1
- package/build/services/SoftapCallTransport.js +229 -28
- package/build/services/SoftapCallTransport.js.map +1 -1
- package/build/utils/miniappGlobals.d.ts.map +1 -1
- package/build/utils/miniappGlobals.js +13 -11
- package/build/utils/miniappGlobals.js.map +1 -1
- package/package.json +8 -8
- package/src/generated/releaseMetadata.ts +5 -5
- package/src/services/AcsMeetingService.ts +51 -3
- package/src/services/LocalMiniappRuntime.ts +296 -30
- package/src/services/MiniappLiveness.ts +18 -0
- package/src/services/PhoneStreamCoordinator.ts +27 -5
- package/src/services/SoftapCallTransport.ts +274 -32
- package/src/utils/miniappGlobals.ts +13 -11
|
@@ -2,6 +2,17 @@ export interface MiniappPingLivenessDecision {
|
|
|
2
2
|
shouldUnregister: boolean;
|
|
3
3
|
unansweredPingRounds: number;
|
|
4
4
|
}
|
|
5
|
+
/**
|
|
6
|
+
* SoftAP join can spend a minute in native `prepareAgent` before the glasses
|
|
7
|
+
* hotspot even turns on. The JS bundle stays alive but may miss pongs while
|
|
8
|
+
* ACS is on the native thread. Unregistering for missed pings in that window
|
|
9
|
+
* cancels the join and leaves the UI stuck on the hotspot row.
|
|
10
|
+
*/
|
|
11
|
+
export declare function shouldHoldMiniappPingLiveness(args: {
|
|
12
|
+
packageName: string;
|
|
13
|
+
softapPackageName?: string | null;
|
|
14
|
+
softapCancelled?: boolean;
|
|
15
|
+
}): boolean;
|
|
5
16
|
/**
|
|
6
17
|
* Advance liveness by one scheduled ping round.
|
|
7
18
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MiniappLiveness.d.ts","sourceRoot":"","sources":["../../src/services/MiniappLiveness.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,2BAA2B;IAC1C,gBAAgB,EAAE,OAAO,CAAA;IACzB,oBAAoB,EAAE,MAAM,CAAA;CAC7B;AAED;;;;;GAKG;AACH,wBAAgB,0BAA0B,CACxC,oBAAoB,EAAE,MAAM,EAC5B,gBAAgB,EAAE,MAAM,GACvB,2BAA2B,CAS7B"}
|
|
1
|
+
{"version":3,"file":"MiniappLiveness.d.ts","sourceRoot":"","sources":["../../src/services/MiniappLiveness.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,2BAA2B;IAC1C,gBAAgB,EAAE,OAAO,CAAA;IACzB,oBAAoB,EAAE,MAAM,CAAA;CAC7B;AAED;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAAC,IAAI,EAAE;IAClD,WAAW,EAAE,MAAM,CAAA;IACnB,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACjC,eAAe,CAAC,EAAE,OAAO,CAAA;CAC1B,GAAG,OAAO,CAMV;AAED;;;;;GAKG;AACH,wBAAgB,0BAA0B,CACxC,oBAAoB,EAAE,MAAM,EAC5B,gBAAgB,EAAE,MAAM,GACvB,2BAA2B,CAS7B"}
|
|
@@ -1,3 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SoftAP join can spend a minute in native `prepareAgent` before the glasses
|
|
3
|
+
* hotspot even turns on. The JS bundle stays alive but may miss pongs while
|
|
4
|
+
* ACS is on the native thread. Unregistering for missed pings in that window
|
|
5
|
+
* cancels the join and leaves the UI stuck on the hotspot row.
|
|
6
|
+
*/
|
|
7
|
+
export function shouldHoldMiniappPingLiveness(args) {
|
|
8
|
+
return Boolean(args.softapPackageName &&
|
|
9
|
+
args.softapPackageName === args.packageName &&
|
|
10
|
+
!args.softapCancelled);
|
|
11
|
+
}
|
|
1
12
|
/**
|
|
2
13
|
* Advance liveness by one scheduled ping round.
|
|
3
14
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MiniappLiveness.js","sourceRoot":"","sources":["../../src/services/MiniappLiveness.ts"],"names":[],"mappings":"AAKA;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CACxC,oBAA4B,EAC5B,gBAAwB;IAExB,IAAI,oBAAoB,IAAI,gBAAgB,EAAE,CAAC;QAC7C,OAAO,EAAC,gBAAgB,EAAE,IAAI,EAAE,oBAAoB,EAAC,CAAA;IACvD,CAAC;IAED,OAAO;QACL,gBAAgB,EAAE,KAAK;QACvB,oBAAoB,EAAE,oBAAoB,GAAG,CAAC;KAC/C,CAAA;AACH,CAAC","sourcesContent":["export interface MiniappPingLivenessDecision {\n shouldUnregister: boolean\n unansweredPingRounds: number\n}\n\n/**\n * Advance liveness by one scheduled ping round.\n *\n * Counting actual rounds avoids treating time while React Native's scheduler\n * was paused in the background as pings the miniapp failed to answer.\n */\nexport function advanceMiniappPingLiveness(\n unansweredPingRounds: number,\n timeoutThreshold: number,\n): MiniappPingLivenessDecision {\n if (unansweredPingRounds >= timeoutThreshold) {\n return {shouldUnregister: true, unansweredPingRounds}\n }\n\n return {\n shouldUnregister: false,\n unansweredPingRounds: unansweredPingRounds + 1,\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"MiniappLiveness.js","sourceRoot":"","sources":["../../src/services/MiniappLiveness.ts"],"names":[],"mappings":"AAKA;;;;;GAKG;AACH,MAAM,UAAU,6BAA6B,CAAC,IAI7C;IACC,OAAO,OAAO,CACZ,IAAI,CAAC,iBAAiB;QACpB,IAAI,CAAC,iBAAiB,KAAK,IAAI,CAAC,WAAW;QAC3C,CAAC,IAAI,CAAC,eAAe,CACxB,CAAA;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CACxC,oBAA4B,EAC5B,gBAAwB;IAExB,IAAI,oBAAoB,IAAI,gBAAgB,EAAE,CAAC;QAC7C,OAAO,EAAC,gBAAgB,EAAE,IAAI,EAAE,oBAAoB,EAAC,CAAA;IACvD,CAAC;IAED,OAAO;QACL,gBAAgB,EAAE,KAAK;QACvB,oBAAoB,EAAE,oBAAoB,GAAG,CAAC;KAC/C,CAAA;AACH,CAAC","sourcesContent":["export interface MiniappPingLivenessDecision {\n shouldUnregister: boolean\n unansweredPingRounds: number\n}\n\n/**\n * SoftAP join can spend a minute in native `prepareAgent` before the glasses\n * hotspot even turns on. The JS bundle stays alive but may miss pongs while\n * ACS is on the native thread. Unregistering for missed pings in that window\n * cancels the join and leaves the UI stuck on the hotspot row.\n */\nexport function shouldHoldMiniappPingLiveness(args: {\n packageName: string\n softapPackageName?: string | null\n softapCancelled?: boolean\n}): boolean {\n return Boolean(\n args.softapPackageName &&\n args.softapPackageName === args.packageName &&\n !args.softapCancelled,\n )\n}\n\n/**\n * Advance liveness by one scheduled ping round.\n *\n * Counting actual rounds avoids treating time while React Native's scheduler\n * was paused in the background as pings the miniapp failed to answer.\n */\nexport function advanceMiniappPingLiveness(\n unansweredPingRounds: number,\n timeoutThreshold: number,\n): MiniappPingLivenessDecision {\n if (unansweredPingRounds >= timeoutThreshold) {\n return {shouldUnregister: true, unansweredPingRounds}\n }\n\n return {\n shouldUnregister: false,\n unansweredPingRounds: unansweredPingRounds + 1,\n }\n}\n"]}
|
|
@@ -150,9 +150,12 @@ export declare class PhoneStreamCoordinator {
|
|
|
150
150
|
* A stream was torn down while the BLE link was down, so the glasses never
|
|
151
151
|
* got `stopStream`. Sent on the next reconnect (if no new stream has claimed
|
|
152
152
|
* the slot) so a publisher that outlived its input does not keep pushing
|
|
153
|
-
* until its own watchdog fires.
|
|
153
|
+
* until its own watchdog fires. `generation` belongs to the publisher that
|
|
154
|
+
* queued it; a later SoftAP media hop must not inherit this stop.
|
|
154
155
|
*/
|
|
155
156
|
private pendingBleStop;
|
|
157
|
+
/** Bumped each time an unmanaged/managed publisher claims the slot. */
|
|
158
|
+
private publisherGeneration;
|
|
156
159
|
/**
|
|
157
160
|
* Serializes state transitions (start, stop, teardown). Without it, a
|
|
158
161
|
* second `start*` racing with the first can pass the `this.current === null`
|
|
@@ -202,6 +205,15 @@ export declare class PhoneStreamCoordinator {
|
|
|
202
205
|
startUnmanaged(packageName: string, opts: StartUnmanagedOptions): Promise<StreamPublisherStartResult>;
|
|
203
206
|
startManaged(packageName: string, opts: StartManagedOptions): Promise<ManagedStartResult>;
|
|
204
207
|
stop(packageName: string, streamId?: string): Promise<void>;
|
|
208
|
+
/**
|
|
209
|
+
* Drop a deferred BLE `stopStream` that belonged to a publisher that is gone.
|
|
210
|
+
*
|
|
211
|
+
* SoftAP recovery destroys generation N and rebuilds N+1. If failSuspended already
|
|
212
|
+
* tore the publisher down after `glassesGraceMs`, `stop()` is a no-op but a pending
|
|
213
|
+
* stop would still flush into the new hop on reconnect. Call this from SoftAP
|
|
214
|
+
* `stopPublishing` so the deferred command dies with its generation.
|
|
215
|
+
*/
|
|
216
|
+
discardPendingBleStop(): void;
|
|
205
217
|
/**
|
|
206
218
|
* Called by MantleManager when a `stream_status` event arrives from glasses
|
|
207
219
|
* and the registry says it's phone-owned.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PhoneStreamCoordinator.d.ts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OAAO,CAAC,MAAM;IAYd;;;;;;OAMG;YACW,cAAc;CAgE7B;AAiDD,eAAO,MAAM,sBAAsB,wBAA+B,CAAA"}
|
|
@@ -98,9 +98,12 @@ export class PhoneStreamCoordinator {
|
|
|
98
98
|
* A stream was torn down while the BLE link was down, so the glasses never
|
|
99
99
|
* got `stopStream`. Sent on the next reconnect (if no new stream has claimed
|
|
100
100
|
* the slot) so a publisher that outlived its input does not keep pushing
|
|
101
|
-
* until its own watchdog fires.
|
|
101
|
+
* until its own watchdog fires. `generation` belongs to the publisher that
|
|
102
|
+
* queued it; a later SoftAP media hop must not inherit this stop.
|
|
102
103
|
*/
|
|
103
104
|
pendingBleStop = null;
|
|
105
|
+
/** Bumped each time an unmanaged/managed publisher claims the slot. */
|
|
106
|
+
publisherGeneration = 0;
|
|
104
107
|
/**
|
|
105
108
|
* Serializes state transitions (start, stop, teardown). Without it, a
|
|
106
109
|
* second `start*` racing with the first can pass the `this.current === null`
|
|
@@ -212,6 +215,7 @@ export class PhoneStreamCoordinator {
|
|
|
212
215
|
throw new StreamConflictError("STREAM_ALREADY_ACTIVE", `A ${this.current.kind} stream is already active. Stop it before starting a new one.`);
|
|
213
216
|
}
|
|
214
217
|
const streamId = this.mintId("u");
|
|
218
|
+
++this.publisherGeneration;
|
|
215
219
|
const entry = {
|
|
216
220
|
kind: "unmanaged",
|
|
217
221
|
streamId,
|
|
@@ -291,6 +295,7 @@ export class PhoneStreamCoordinator {
|
|
|
291
295
|
// and joins instead of double-provisioning.
|
|
292
296
|
const provision = await provisionManagedStream(opts.restreamDestinations);
|
|
293
297
|
const streamId = this.mintId("m");
|
|
298
|
+
++this.publisherGeneration;
|
|
294
299
|
let ingestUrl;
|
|
295
300
|
try {
|
|
296
301
|
ingestUrl = pickIngestUrl(provision, opts.ingest);
|
|
@@ -337,7 +342,7 @@ export class PhoneStreamCoordinator {
|
|
|
337
342
|
await this.teardownLocked("relay_failed");
|
|
338
343
|
}).catch((cleanupError) => console.warn("[STREAM] relay cleanup failed", cleanupError));
|
|
339
344
|
}, () => this.linkSource.isConnected(), () => {
|
|
340
|
-
this.pendingBleStop = { streamId, hotspot: true };
|
|
345
|
+
this.pendingBleStop = { streamId, hotspot: true, generation: this.publisherGeneration };
|
|
341
346
|
this.attachLink();
|
|
342
347
|
});
|
|
343
348
|
}
|
|
@@ -432,6 +437,22 @@ export class PhoneStreamCoordinator {
|
|
|
432
437
|
await this.teardownLocked("explicit_stop");
|
|
433
438
|
});
|
|
434
439
|
}
|
|
440
|
+
/**
|
|
441
|
+
* Drop a deferred BLE `stopStream` that belonged to a publisher that is gone.
|
|
442
|
+
*
|
|
443
|
+
* SoftAP recovery destroys generation N and rebuilds N+1. If failSuspended already
|
|
444
|
+
* tore the publisher down after `glassesGraceMs`, `stop()` is a no-op but a pending
|
|
445
|
+
* stop would still flush into the new hop on reconnect. Call this from SoftAP
|
|
446
|
+
* `stopPublishing` so the deferred command dies with its generation.
|
|
447
|
+
*/
|
|
448
|
+
discardPendingBleStop() {
|
|
449
|
+
const pending = this.pendingBleStop;
|
|
450
|
+
if (!pending)
|
|
451
|
+
return;
|
|
452
|
+
pending.discarded = true;
|
|
453
|
+
this.pendingBleStop = null;
|
|
454
|
+
this.detachLinkIfIdle();
|
|
455
|
+
}
|
|
435
456
|
/**
|
|
436
457
|
* Called by MantleManager when a `stream_status` event arrives from glasses
|
|
437
458
|
* and the registry says it's phone-owned.
|
|
@@ -572,10 +593,12 @@ export class PhoneStreamCoordinator {
|
|
|
572
593
|
}
|
|
573
594
|
async flushPendingBleStop() {
|
|
574
595
|
const pending = this.pendingBleStop;
|
|
575
|
-
if (!pending || this.current || !this.linkSource.isConnected())
|
|
596
|
+
if (!pending || pending.discarded || this.current || !this.linkSource.isConnected())
|
|
576
597
|
return;
|
|
577
598
|
console.info("[STREAM] BLE link back; sending deferred stopStream", pending);
|
|
578
599
|
await BluetoothSdk.stopStream();
|
|
600
|
+
if (pending.discarded || this.pendingBleStop !== pending || this.current)
|
|
601
|
+
return;
|
|
579
602
|
if (pending.hotspot) {
|
|
580
603
|
const result = await BluetoothSdk.setHotspotState(false);
|
|
581
604
|
if (result.state !== "disabled")
|
|
@@ -828,7 +851,7 @@ export class PhoneStreamCoordinator {
|
|
|
828
851
|
// lock for the native timeout). Defer it to the next reconnect instead.
|
|
829
852
|
const linkUp = this.linkSource.isConnected();
|
|
830
853
|
if (sendBleStop && !linkUp) {
|
|
831
|
-
this.pendingBleStop = { streamId: entry.streamId, hotspot: entry.kind === "managed" && !!entry.relay };
|
|
854
|
+
this.pendingBleStop = { streamId: entry.streamId, hotspot: entry.kind === "managed" && !!entry.relay, generation: this.publisherGeneration };
|
|
832
855
|
console.warn("[STREAM] BLE link down during teardown; stopStream deferred", {
|
|
833
856
|
streamId: entry.streamId,
|
|
834
857
|
reason,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PhoneStreamCoordinator.js","sourceRoot":"","sources":["../../src/services/PhoneStreamCoordinator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,YAAY,MAAM,gCAAgC,CAAA;AAEzD,OAAO,EAAC,wBAAwB,EAAoB,MAAM,sBAAsB,CAAA;AAChF,OAAO,EAAC,kBAAkB,EAAC,MAAM,oBAAoB,CAAA;AACrD,OAAO,EAAC,yBAAyB,EAAC,MAAM,6BAA6B,CAAA;AACrE,OAAO,EAAC,eAAe,EAAC,MAAM,mBAAmB,CAAA;AAEjD,OAAO,EAAC,OAAO,EAAC,MAAM,iBAAiB,CAAA;AACvC,OAAO,EAAC,qBAAqB,EAAE,qBAAqB,EAAC,MAAM,oBAAoB,CAAA;AAC/E,OAAO,EACL,sBAAsB,EACtB,sBAAsB,EACtB,qBAAqB,GAItB,MAAM,kBAAkB,CAAA;AAEzB;;;GAGG;AACH,MAAM,eAAe,GAAG;IACtB,sBAAsB,EAAE,KAAK;IAC7B,0EAA0E;IAC1E,wEAAwE;IACxE,8BA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C,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 → 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 managed-stream resource IDs in logs.\n *\n * BLE link loss is a SUSPENDED state, not a failure:\n * ASG owns the ten-second phone/controller liveness deadline. The coordinator\n * observes link suspension, retains cloud resources briefly for reconciliation,\n * and never uses missing JavaScript heartbeats as evidence of publisher failure.\n * An explicit stop that could not reach BLE is sent on the next reconnect.\n */\n\nimport BluetoothSdk from \"@mentra/bluetooth-sdk/internal\"\nimport type {StreamResolvedConfig, StreamStartRequest, StreamStatusEvent} from \"@mentra/bluetooth-sdk/internal\"\nimport {createManagedWebRtcRelay, type ManagedRelay} from \"./ManagedWebRtcRelay\"\nimport {isGlassesConnected} from \"./GlassesReadiness\"\nimport {phoneCameraFovCoordinator} from \"./PhoneCameraFovCoordinator\"\nimport {useGlassesStore} from \"../stores/glasses\"\n\nimport {BgTimer} from \"../utils/timers\"\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 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 // Allow ASG's ten-second stop plus a short delivery/reconciliation margin.\n glassesGraceMs: 15_000,\n // Consecutive Cloudflare \"publisher disconnected\" probes while suspended\n // before we conclude the glasses are off (not just out of BLE range).\n suspendedPublisherGoneProbes: 2,\n} as const\n\ntype TimingConfig = {[K in keyof typeof DEFAULT_TIMINGS]: number}\nexport type CoordinatorTimings = Partial<TimingConfig>\n\n/**\n * Where the coordinator learns whether the phone↔glasses BLE link is up.\n * Injected so tests can drive link transitions without the zustand store.\n */\nexport interface GlassesLinkSource {\n isConnected(): boolean\n /** Fires on every connected↔disconnected transition. */\n subscribe(listener: (connected: boolean) => void): () => void\n}\n\nconst storeLinkSource: GlassesLinkSource = {\n isConnected: () => isGlassesConnected(useGlassesStore.getState().connection),\n subscribe: (listener) => useGlassesStore.subscribe((s) => isGlassesConnected(s.connection), listener),\n}\n\n/** Reasons carried on coordinator-sourced `stream_status` fanouts for link events. */\nexport const LINK_STATUS = {\n suspended: \"suspended\",\n resumed: \"resumed\",\n reason: \"glasses_disconnected\",\n} as const\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 captureAudio?: boolean\n /**\n * ICE configuration for the glasses' publisher. SoftAP passes `{stun: \"\"}`, which puts the\n * glasses in host-only mode: there is no route from the hotspot to a STUN server, so a\n * configured one would only add doomed gathering to every call.\n */\n ice?: StreamStartRequest[\"ice\"]\n /** Correlation id echoed by the glasses into their own logs. See softapTrace. */\n traceId?: 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 /** When false, glasses skip encoding their mic for this WHIP session. */\n captureAudio?: boolean\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 stopping?: boolean\n relay?: ManagedRelay\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 BgTimer.setTimeout>\n hlsTimer?: ReturnType<typeof BgTimer.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\ninterface SuspendedState {\n since: number\n graceTimer: ReturnType<typeof BgTimer.setTimeout>\n /** Consecutive Cloudflare probes that saw no publisher during this suspension. */\n publisherGoneProbes: number\n}\n\nexport class PhoneStreamCoordinator {\n private current: Entry | null = null\n private statusSubscriber: StatusSubscriber | null = null\n private idCounter = 0\n private readonly timings: TimingConfig\n private readonly relayFactory: typeof createManagedWebRtcRelay\n private readonly linkSource: GlassesLinkSource\n private readonly pendingCameraChanges: () => Promise<void>\n private unsubscribeLink: (() => void) | null = null\n private suspended: SuspendedState | null = null\n /**\n * A stream was torn down while the BLE link was down, so the glasses never\n * got `stopStream`. Sent on the next reconnect (if no new stream has claimed\n * the slot) so a publisher that outlived its input does not keep pushing\n * until its own watchdog fires.\n */\n private pendingBleStop: {streamId: string; hotspot?: boolean} | null = null\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(\n timings: CoordinatorTimings = {},\n deps: {\n linkSource?: GlassesLinkSource\n pendingCameraChanges?: () => Promise<void>\n relayFactory?: typeof createManagedWebRtcRelay\n } = {},\n ) {\n this.relayFactory = deps.relayFactory ?? createManagedWebRtcRelay\n this.timings = {...DEFAULT_TIMINGS, ...timings}\n this.linkSource = deps.linkSource ?? storeLinkSource\n this.pendingCameraChanges = deps.pendingCameraChanges ?? (() => phoneCameraFovCoordinator.whenSettled())\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 */\n private assertGlassesConnected(): void {\n if (!this.linkSource.isConnected()) {\n throw new StreamConflictError(\"GLASSES_NOT_CONNECTED\", \"Glasses are not connected\", \"command\", \"ble\")\n }\n }\n\n /** True while the active stream is parked on a dropped BLE link. */\n isSuspended(): boolean {\n return this.suspended !== null\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 (\n this.current !== null &&\n (this.current.streamId === streamId || (this.current.kind === \"managed\" && !!this.current.relay?.owns(streamId)))\n )\n }\n\n /** Report-safe stream ownership snapshot for incident diagnostics. */\n getDiagnosticSnapshot(): Record<string, unknown> {\n if (!this.current) return {active: false, pendingBleStop: this.pendingBleStop?.streamId ?? null}\n const link = {\n suspended: this.suspended !== null,\n ...(this.suspended ? {suspendedForMs: Date.now() - this.suspended.since} : {}),\n }\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 ...link,\n }\n : {\n active: true,\n kind: this.current.kind,\n streamId: this.current.streamId,\n ownerPackageName: this.current.packageName,\n ...link,\n }\n }\n\n async startUnmanaged(packageName: string, opts: StartUnmanagedOptions): 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 this.assertGlassesConnected()\n // Capture before entering the stream queue: a later FOV release may itself\n // await stop(), and must not become a circular dependency of this start.\n const cameraReady = this.pendingCameraChanges()\n return this.runExclusive(async () => {\n await cameraReady\n this.assertGlassesConnected()\n await this.flushPendingBleStop()\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.startStream({\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 ...(typeof opts.captureAudio === \"boolean\" ? {captureAudio: opts.captureAudio} : {}),\n ...(opts.ice !== undefined ? {ice: opts.ice} : {}),\n ...(opts.traceId ? {traceId: opts.traceId} : {}),\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(packageName: string, opts: StartManagedOptions): Promise<ManagedStartResult> {\n const cameraReady = this.pendingCameraChanges()\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 this.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 await cameraReady\n this.assertGlassesConnected()\n await this.flushPendingBleStop()\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 if (existing.stopping)\n throw new StreamConflictError(\n \"STREAM_CLEANUP_PENDING\",\n \"Previous stream cleanup has not completed; retry stop first\",\n )\n if (opts.ingest !== undefined && (opts.ingest === \"whip\") !== (existing.mode === \"webrtc\")) {\n throw new StreamConflictError(\n \"STREAM_MODE_CONFLICT\",\n \"Stop the existing stream before switching playback modes\",\n )\n }\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 ? managedStartResult(existing) : 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 let ingestUrl: string\n try {\n ingestUrl = pickIngestUrl(provision, opts.ingest)\n } catch (error) {\n await teardownManagedStream(provision.liveInputId).catch(() => undefined)\n throw error\n }\n const mode: ManagedEntry[\"mode\"] = 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 if (mode === \"webrtc\") {\n entry.relay = this.relayFactory(\n {streamId, ingestUrl, ...opts},\n (status, reason) => {\n if (this.current === entry && !entry.stopping)\n this.fanout({streamId, source: \"coordinator\", status, data: {reason, transport: \"softap_relay\"}})\n },\n (error) => {\n void this.runExclusive(async () => {\n if (this.current !== entry) return\n this.fanout({streamId, source: \"coordinator\", status: \"error\", data: {reason: error.message}})\n await this.teardownLocked(\"relay_failed\")\n }).catch((cleanupError) => console.warn(\"[STREAM] relay cleanup failed\", cleanupError))\n },\n () => this.linkSource.isConnected(),\n () => {\n this.pendingBleStop = {streamId, hotspot: true}\n this.attachLink()\n },\n )\n }\n const event = entry.relay\n ? await entry.relay.start()\n : await BluetoothSdk.startStream({\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 ...(typeof opts.captureAudio === \"boolean\" ? {captureAudio: opts.captureAudio} : {}),\n })\n entry.publisherStart = {...publisherStartResult(streamId, event), streamId}\n console.info(\"[STREAM_STARTUP]\", {\n streamId,\n stage: \"publisher_ready\",\n mode,\n elapsedMs: Date.now() - startupStartedAtMs,\n })\n } catch (err) {\n entry.stopping = true\n try {\n await entry.relay?.stop()\n this.current = null\n await this.flushPendingBleStop()\n } finally {\n await teardownManagedStream(provision.liveInputId).catch(() => undefined)\n }\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 (this.current !== decision.entry || decision.entry.stopping) {\n throw new Error(\"Stream stopped before playback readiness\")\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 // Cancel in-flight native preparation immediately; cleanup remains serialized below.\n const pending = this.current\n if (\n pending?.kind === \"managed\" &&\n (!streamId || pending.streamId === streamId) &&\n pending.subscribers.size === 1 &&\n pending.subscribers.has(packageName)\n )\n pending.relay?.cancel()\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 (this.current.kind === \"managed\" && this.current.relay) {\n this.current.relay.handleGlassesStatus(event)\n return\n }\n if (event.streamId && event.streamId !== this.current.streamId) return\n\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). ASG explicitly marks terminal failures; serialize teardown\n // 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 (event.terminal === true || isGiveUp || isStopped) {\n const reason = isGiveUp ? \"glasses_gave_up\" : event.status === \"error\" ? \"glasses_error\" : \"glasses_stopped\"\n const targetStreamId = this.current.streamId\n this.requestTeardown(targetStreamId, reason, {sendBleStop: false})\n }\n }\n\n // ===========================================================================\n // BLE link suspension\n // ===========================================================================\n\n private attachLink(): void {\n if (this.unsubscribeLink) return\n this.unsubscribeLink = this.linkSource.subscribe((connected) => this.handleLinkChange(connected))\n }\n\n private detachLinkIfIdle(): void {\n if (this.current || this.pendingBleStop || !this.unsubscribeLink) return\n this.unsubscribeLink()\n this.unsubscribeLink = null\n }\n\n private handleLinkChange(connected: boolean): void {\n if (connected) {\n if (this.current && this.suspended) {\n this.resumeLocked()\n } else if (!this.current && this.pendingBleStop) {\n void this.runExclusive(() => this.flushPendingBleStop()).catch((error) =>\n console.warn(\"[STREAM] deferred cleanup failed\", error),\n )\n }\n return\n }\n if (this.current && !this.suspended) this.suspend()\n }\n\n private suspend(): void {\n const entry = this.current\n if (!entry) return\n const since = Date.now()\n const graceTimer = BgTimer.setTimeout(() => this.onGraceExpired(entry.streamId), this.timings.glassesGraceMs)\n this.suspended = {since, graceTimer, publisherGoneProbes: 0}\n console.warn(\"[STREAM] BLE link lost; stream suspended\", {\n streamId: entry.streamId,\n graceMs: this.timings.glassesGraceMs,\n })\n this.fanout({\n streamId: entry.streamId,\n source: \"coordinator\",\n status: LINK_STATUS.suspended,\n data: {reason: LINK_STATUS.reason, graceMs: this.timings.glassesGraceMs, since},\n })\n }\n\n private resumeLocked(): void {\n const entry = this.current\n const suspended = this.suspended\n if (!entry || !suspended) return\n BgTimer.clearTimeout(suspended.graceTimer)\n this.suspended = null\n const suspendedMs = Date.now() - suspended.since\n console.info(\"[STREAM] BLE link back; stream resumed\", {streamId: entry.streamId, suspendedMs})\n // A resumed session is a fresh status baseline for subscribers.\n this.lastFanoutSignature = null\n this.fanout({\n streamId: entry.streamId,\n source: \"coordinator\",\n status: LINK_STATUS.resumed,\n data: {reason: LINK_STATUS.reason, suspendedMs},\n })\n }\n\n private onGraceExpired(streamId: string): void {\n if (this.current?.streamId !== streamId || !this.suspended) return\n this.failSuspended(streamId, \"glasses_disconnected\", {publisherGone: false})\n }\n\n /**\n * End a suspended stream. `publisherGone` distinguishes \"glasses are off and\n * Cloudflare confirms nothing is publishing\" from \"grace ran out with the\n * publisher possibly still alive\" — miniapps word the two differently.\n */\n private failSuspended(streamId: string, reason: string, detail: {publisherGone: boolean}): void {\n this.fanout({\n streamId,\n source: \"coordinator\",\n status: \"error\",\n data: {reason: LINK_STATUS.reason, teardownReason: reason, ...detail},\n })\n this.requestTeardown(streamId, reason)\n }\n\n /** Event/timer failures have no awaiting caller; retain and report cleanup errors locally. */\n private requestTeardown(streamId: string, reason: string, options: {sendBleStop?: boolean} = {}): void {\n void this.runExclusive(async () => {\n if (this.current?.streamId !== streamId) return\n await this.teardownLocked(reason, options)\n }).catch((error) => {\n console.warn(\"[STREAM] cleanup failed\", error)\n if (this.current?.streamId === streamId) {\n this.fanout({streamId, source: \"coordinator\", status: \"error\", data: {reason: \"cleanup_failed\"}})\n }\n })\n }\n\n private async flushPendingBleStop(): Promise<void> {\n const pending = this.pendingBleStop\n if (!pending || this.current || !this.linkSource.isConnected()) return\n console.info(\"[STREAM] BLE link back; sending deferred stopStream\", pending)\n await BluetoothSdk.stopStream()\n if (pending.hotspot) {\n const result = await BluetoothSdk.setHotspotState(false)\n if (result.state !== \"disabled\") throw new Error(\"Deferred hotspot shutdown was not confirmed\")\n }\n if (this.pendingBleStop === pending) this.pendingBleStop = null\n this.detachLinkIfIdle()\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 /** Observe link/status; native SDK and ASG own controller liveness. */\n private startLifecycle(_streamId: string): void {\n this.pendingBleStop = null\n this.attachLink()\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 || entry.stopping) 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 = BgTimer.setTimeout(() => void poll(), delayMs)\n }\n\n const poll = async () => {\n if (this.current !== entry || entry.stopping) 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 if (this.current !== entry || entry.stopping) return\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 // While the BLE link is down, Cloudflare is the only witness to the\n // publisher. Two consecutive \"nobody is publishing\" probes mean the\n // glasses are off, not merely out of Bluetooth range — stop waiting.\n if (this.suspended) {\n if (status.isConnected) {\n this.suspended.publisherGoneProbes = 0\n } else {\n this.suspended.publisherGoneProbes += 1\n if (this.suspended.publisherGoneProbes >= this.timings.suspendedPublisherGoneProbes) {\n this.failSuspended(entry.streamId, \"glasses_disconnected_publisher_gone\", {publisherGone: true})\n keepPolling = false\n }\n }\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 this.requestTeardown(targetStreamId, \"webrtc_not_connected\")\n keepPolling = false\n }\n }\n }\n } catch (err) {\n if (this.current !== entry || entry.stopping) return\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 this.requestTeardown(targetStreamId, \"webrtc_status_unavailable\")\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 || entry.stopping) 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 (this.current !== entry || entry.stopping) return\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 BgTimer.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 BgTimer.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 this.requestTeardown(targetStreamId, \"hls_not_ready\")\n }\n }\n BgTimer.setTimeout(() => {\n // Guard: stream may have been torn down during the initial delay.\n if (this.current !== entry || entry.stopping) return\n entry.hlsTimer = BgTimer.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 = this.current.kind === \"managed\" ? Array.from(this.current.subscribers) : [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 if (this.suspended) {\n BgTimer.clearTimeout(this.suspended.graceTimer)\n this.suspended = null\n }\n\n // With the link down a BLE write can only fail (and hold the transition\n // lock for the native timeout). Defer it to the next reconnect instead.\n const linkUp = this.linkSource.isConnected()\n if (sendBleStop && !linkUp) {\n this.pendingBleStop = {streamId: entry.streamId, hotspot: entry.kind === \"managed\" && !!entry.relay}\n console.warn(\"[STREAM] BLE link down during teardown; stopStream deferred\", {\n streamId: entry.streamId,\n reason,\n })\n }\n\n if (entry.kind === \"managed\") {\n entry.stopping = true\n if (entry.cloudflareTimer) BgTimer.clearTimeout(entry.cloudflareTimer)\n if (entry.hlsTimer) BgTimer.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 // Relay stop owns the BLE publisher, native peers and hotspot. Keep the entry on failure\n // so another start cannot acquire resources whose teardown has not been confirmed.\n if (entry.kind === \"managed\" && entry.relay) await entry.relay.stop()\n try {\n if (sendBleStop && linkUp && !(entry.kind === \"managed\" && entry.relay)) {\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 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 // BLE can recover while native cleanup is draining; no second link event is required.\n await this.flushPendingBleStop()\n this.detachLinkIfIdle()\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 is explicit. 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\" ? p.webrtcPublishUrl : preference === \"rtmp\" ? p.rtmpUrl || p.srtUrl : p.srtUrl || p.rtmpUrl\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,"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AG,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 → 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 managed-stream resource IDs in logs.\n *\n * BLE link loss is a SUSPENDED state, not a failure:\n * ASG owns the ten-second phone/controller liveness deadline. The coordinator\n * observes link suspension, retains cloud resources briefly for reconciliation,\n * and never uses missing JavaScript heartbeats as evidence of publisher failure.\n * An explicit stop that could not reach BLE is sent on the next reconnect.\n */\n\nimport BluetoothSdk from \"@mentra/bluetooth-sdk/internal\"\nimport type {StreamResolvedConfig, StreamStartRequest, StreamStatusEvent} from \"@mentra/bluetooth-sdk/internal\"\nimport {createManagedWebRtcRelay, type ManagedRelay} from \"./ManagedWebRtcRelay\"\nimport {isGlassesConnected} from \"./GlassesReadiness\"\nimport {phoneCameraFovCoordinator} from \"./PhoneCameraFovCoordinator\"\nimport {useGlassesStore} from \"../stores/glasses\"\n\nimport {BgTimer} from \"../utils/timers\"\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 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 // Allow ASG's ten-second stop plus a short delivery/reconciliation margin.\n glassesGraceMs: 15_000,\n // Consecutive Cloudflare \"publisher disconnected\" probes while suspended\n // before we conclude the glasses are off (not just out of BLE range).\n suspendedPublisherGoneProbes: 2,\n} as const\n\ntype TimingConfig = {[K in keyof typeof DEFAULT_TIMINGS]: number}\nexport type CoordinatorTimings = Partial<TimingConfig>\n\n/**\n * Where the coordinator learns whether the phone↔glasses BLE link is up.\n * Injected so tests can drive link transitions without the zustand store.\n */\nexport interface GlassesLinkSource {\n isConnected(): boolean\n /** Fires on every connected↔disconnected transition. */\n subscribe(listener: (connected: boolean) => void): () => void\n}\n\nconst storeLinkSource: GlassesLinkSource = {\n isConnected: () => isGlassesConnected(useGlassesStore.getState().connection),\n subscribe: (listener) => useGlassesStore.subscribe((s) => isGlassesConnected(s.connection), listener),\n}\n\n/** Reasons carried on coordinator-sourced `stream_status` fanouts for link events. */\nexport const LINK_STATUS = {\n suspended: \"suspended\",\n resumed: \"resumed\",\n reason: \"glasses_disconnected\",\n} as const\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 captureAudio?: boolean\n /**\n * ICE configuration for the glasses' publisher. SoftAP passes `{stun: \"\"}`, which puts the\n * glasses in host-only mode: there is no route from the hotspot to a STUN server, so a\n * configured one would only add doomed gathering to every call.\n */\n ice?: StreamStartRequest[\"ice\"]\n /** Correlation id echoed by the glasses into their own logs. See softapTrace. */\n traceId?: 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 /** When false, glasses skip encoding their mic for this WHIP session. */\n captureAudio?: boolean\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 stopping?: boolean\n relay?: ManagedRelay\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 BgTimer.setTimeout>\n hlsTimer?: ReturnType<typeof BgTimer.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\ninterface SuspendedState {\n since: number\n graceTimer: ReturnType<typeof BgTimer.setTimeout>\n /** Consecutive Cloudflare probes that saw no publisher during this suspension. */\n publisherGoneProbes: number\n}\n\nexport class PhoneStreamCoordinator {\n private current: Entry | null = null\n private statusSubscriber: StatusSubscriber | null = null\n private idCounter = 0\n private readonly timings: TimingConfig\n private readonly relayFactory: typeof createManagedWebRtcRelay\n private readonly linkSource: GlassesLinkSource\n private readonly pendingCameraChanges: () => Promise<void>\n private unsubscribeLink: (() => void) | null = null\n private suspended: SuspendedState | null = null\n /**\n * A stream was torn down while the BLE link was down, so the glasses never\n * got `stopStream`. Sent on the next reconnect (if no new stream has claimed\n * the slot) so a publisher that outlived its input does not keep pushing\n * until its own watchdog fires. `generation` belongs to the publisher that\n * queued it; a later SoftAP media hop must not inherit this stop.\n */\n private pendingBleStop: {streamId: string; hotspot?: boolean; generation: number; discarded?: boolean} | null = null\n /** Bumped each time an unmanaged/managed publisher claims the slot. */\n private publisherGeneration = 0\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(\n timings: CoordinatorTimings = {},\n deps: {\n linkSource?: GlassesLinkSource\n pendingCameraChanges?: () => Promise<void>\n relayFactory?: typeof createManagedWebRtcRelay\n } = {},\n ) {\n this.relayFactory = deps.relayFactory ?? createManagedWebRtcRelay\n this.timings = {...DEFAULT_TIMINGS, ...timings}\n this.linkSource = deps.linkSource ?? storeLinkSource\n this.pendingCameraChanges = deps.pendingCameraChanges ?? (() => phoneCameraFovCoordinator.whenSettled())\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 */\n private assertGlassesConnected(): void {\n if (!this.linkSource.isConnected()) {\n throw new StreamConflictError(\"GLASSES_NOT_CONNECTED\", \"Glasses are not connected\", \"command\", \"ble\")\n }\n }\n\n /** True while the active stream is parked on a dropped BLE link. */\n isSuspended(): boolean {\n return this.suspended !== null\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 (\n this.current !== null &&\n (this.current.streamId === streamId || (this.current.kind === \"managed\" && !!this.current.relay?.owns(streamId)))\n )\n }\n\n /** Report-safe stream ownership snapshot for incident diagnostics. */\n getDiagnosticSnapshot(): Record<string, unknown> {\n if (!this.current) return {active: false, pendingBleStop: this.pendingBleStop?.streamId ?? null}\n const link = {\n suspended: this.suspended !== null,\n ...(this.suspended ? {suspendedForMs: Date.now() - this.suspended.since} : {}),\n }\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 ...link,\n }\n : {\n active: true,\n kind: this.current.kind,\n streamId: this.current.streamId,\n ownerPackageName: this.current.packageName,\n ...link,\n }\n }\n\n async startUnmanaged(packageName: string, opts: StartUnmanagedOptions): 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 this.assertGlassesConnected()\n // Capture before entering the stream queue: a later FOV release may itself\n // await stop(), and must not become a circular dependency of this start.\n const cameraReady = this.pendingCameraChanges()\n return this.runExclusive(async () => {\n await cameraReady\n this.assertGlassesConnected()\n await this.flushPendingBleStop()\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 ++this.publisherGeneration\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.startStream({\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 ...(typeof opts.captureAudio === \"boolean\" ? {captureAudio: opts.captureAudio} : {}),\n ...(opts.ice !== undefined ? {ice: opts.ice} : {}),\n ...(opts.traceId ? {traceId: opts.traceId} : {}),\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(packageName: string, opts: StartManagedOptions): Promise<ManagedStartResult> {\n const cameraReady = this.pendingCameraChanges()\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 this.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 await cameraReady\n this.assertGlassesConnected()\n await this.flushPendingBleStop()\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 if (existing.stopping)\n throw new StreamConflictError(\n \"STREAM_CLEANUP_PENDING\",\n \"Previous stream cleanup has not completed; retry stop first\",\n )\n if (opts.ingest !== undefined && (opts.ingest === \"whip\") !== (existing.mode === \"webrtc\")) {\n throw new StreamConflictError(\n \"STREAM_MODE_CONFLICT\",\n \"Stop the existing stream before switching playback modes\",\n )\n }\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 ? managedStartResult(existing) : 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 ++this.publisherGeneration\n let ingestUrl: string\n try {\n ingestUrl = pickIngestUrl(provision, opts.ingest)\n } catch (error) {\n await teardownManagedStream(provision.liveInputId).catch(() => undefined)\n throw error\n }\n const mode: ManagedEntry[\"mode\"] = 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 if (mode === \"webrtc\") {\n entry.relay = this.relayFactory(\n {streamId, ingestUrl, ...opts},\n (status, reason) => {\n if (this.current === entry && !entry.stopping)\n this.fanout({streamId, source: \"coordinator\", status, data: {reason, transport: \"softap_relay\"}})\n },\n (error) => {\n void this.runExclusive(async () => {\n if (this.current !== entry) return\n this.fanout({streamId, source: \"coordinator\", status: \"error\", data: {reason: error.message}})\n await this.teardownLocked(\"relay_failed\")\n }).catch((cleanupError) => console.warn(\"[STREAM] relay cleanup failed\", cleanupError))\n },\n () => this.linkSource.isConnected(),\n () => {\n this.pendingBleStop = {streamId, hotspot: true, generation: this.publisherGeneration}\n this.attachLink()\n },\n )\n }\n const event = entry.relay\n ? await entry.relay.start()\n : await BluetoothSdk.startStream({\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 ...(typeof opts.captureAudio === \"boolean\" ? {captureAudio: opts.captureAudio} : {}),\n })\n entry.publisherStart = {...publisherStartResult(streamId, event), streamId}\n console.info(\"[STREAM_STARTUP]\", {\n streamId,\n stage: \"publisher_ready\",\n mode,\n elapsedMs: Date.now() - startupStartedAtMs,\n })\n } catch (err) {\n entry.stopping = true\n try {\n await entry.relay?.stop()\n this.current = null\n await this.flushPendingBleStop()\n } finally {\n await teardownManagedStream(provision.liveInputId).catch(() => undefined)\n }\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 (this.current !== decision.entry || decision.entry.stopping) {\n throw new Error(\"Stream stopped before playback readiness\")\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 // Cancel in-flight native preparation immediately; cleanup remains serialized below.\n const pending = this.current\n if (\n pending?.kind === \"managed\" &&\n (!streamId || pending.streamId === streamId) &&\n pending.subscribers.size === 1 &&\n pending.subscribers.has(packageName)\n )\n pending.relay?.cancel()\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 * Drop a deferred BLE `stopStream` that belonged to a publisher that is gone.\n *\n * SoftAP recovery destroys generation N and rebuilds N+1. If failSuspended already\n * tore the publisher down after `glassesGraceMs`, `stop()` is a no-op but a pending\n * stop would still flush into the new hop on reconnect. Call this from SoftAP\n * `stopPublishing` so the deferred command dies with its generation.\n */\n discardPendingBleStop(): void {\n const pending = this.pendingBleStop\n if (!pending) return\n pending.discarded = true\n this.pendingBleStop = null\n this.detachLinkIfIdle()\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 (this.current.kind === \"managed\" && this.current.relay) {\n this.current.relay.handleGlassesStatus(event)\n return\n }\n if (event.streamId && event.streamId !== this.current.streamId) return\n\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). ASG explicitly marks terminal failures; serialize teardown\n // 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 (event.terminal === true || isGiveUp || isStopped) {\n const reason = isGiveUp ? \"glasses_gave_up\" : event.status === \"error\" ? \"glasses_error\" : \"glasses_stopped\"\n const targetStreamId = this.current.streamId\n this.requestTeardown(targetStreamId, reason, {sendBleStop: false})\n }\n }\n\n // ===========================================================================\n // BLE link suspension\n // ===========================================================================\n\n private attachLink(): void {\n if (this.unsubscribeLink) return\n this.unsubscribeLink = this.linkSource.subscribe((connected) => this.handleLinkChange(connected))\n }\n\n private detachLinkIfIdle(): void {\n if (this.current || this.pendingBleStop || !this.unsubscribeLink) return\n this.unsubscribeLink()\n this.unsubscribeLink = null\n }\n\n private handleLinkChange(connected: boolean): void {\n if (connected) {\n if (this.current && this.suspended) {\n this.resumeLocked()\n } else if (!this.current && this.pendingBleStop) {\n void this.runExclusive(() => this.flushPendingBleStop()).catch((error) =>\n console.warn(\"[STREAM] deferred cleanup failed\", error),\n )\n }\n return\n }\n if (this.current && !this.suspended) this.suspend()\n }\n\n private suspend(): void {\n const entry = this.current\n if (!entry) return\n const since = Date.now()\n const graceTimer = BgTimer.setTimeout(() => this.onGraceExpired(entry.streamId), this.timings.glassesGraceMs)\n this.suspended = {since, graceTimer, publisherGoneProbes: 0}\n console.warn(\"[STREAM] BLE link lost; stream suspended\", {\n streamId: entry.streamId,\n graceMs: this.timings.glassesGraceMs,\n })\n this.fanout({\n streamId: entry.streamId,\n source: \"coordinator\",\n status: LINK_STATUS.suspended,\n data: {reason: LINK_STATUS.reason, graceMs: this.timings.glassesGraceMs, since},\n })\n }\n\n private resumeLocked(): void {\n const entry = this.current\n const suspended = this.suspended\n if (!entry || !suspended) return\n BgTimer.clearTimeout(suspended.graceTimer)\n this.suspended = null\n const suspendedMs = Date.now() - suspended.since\n console.info(\"[STREAM] BLE link back; stream resumed\", {streamId: entry.streamId, suspendedMs})\n // A resumed session is a fresh status baseline for subscribers.\n this.lastFanoutSignature = null\n this.fanout({\n streamId: entry.streamId,\n source: \"coordinator\",\n status: LINK_STATUS.resumed,\n data: {reason: LINK_STATUS.reason, suspendedMs},\n })\n }\n\n private onGraceExpired(streamId: string): void {\n if (this.current?.streamId !== streamId || !this.suspended) return\n this.failSuspended(streamId, \"glasses_disconnected\", {publisherGone: false})\n }\n\n /**\n * End a suspended stream. `publisherGone` distinguishes \"glasses are off and\n * Cloudflare confirms nothing is publishing\" from \"grace ran out with the\n * publisher possibly still alive\" — miniapps word the two differently.\n */\n private failSuspended(streamId: string, reason: string, detail: {publisherGone: boolean}): void {\n this.fanout({\n streamId,\n source: \"coordinator\",\n status: \"error\",\n data: {reason: LINK_STATUS.reason, teardownReason: reason, ...detail},\n })\n this.requestTeardown(streamId, reason)\n }\n\n /** Event/timer failures have no awaiting caller; retain and report cleanup errors locally. */\n private requestTeardown(streamId: string, reason: string, options: {sendBleStop?: boolean} = {}): void {\n void this.runExclusive(async () => {\n if (this.current?.streamId !== streamId) return\n await this.teardownLocked(reason, options)\n }).catch((error) => {\n console.warn(\"[STREAM] cleanup failed\", error)\n if (this.current?.streamId === streamId) {\n this.fanout({streamId, source: \"coordinator\", status: \"error\", data: {reason: \"cleanup_failed\"}})\n }\n })\n }\n\n private async flushPendingBleStop(): Promise<void> {\n const pending = this.pendingBleStop\n if (!pending || pending.discarded || this.current || !this.linkSource.isConnected()) return\n console.info(\"[STREAM] BLE link back; sending deferred stopStream\", pending)\n await BluetoothSdk.stopStream()\n if (pending.discarded || this.pendingBleStop !== pending || this.current) return\n if (pending.hotspot) {\n const result = await BluetoothSdk.setHotspotState(false)\n if (result.state !== \"disabled\") throw new Error(\"Deferred hotspot shutdown was not confirmed\")\n }\n if (this.pendingBleStop === pending) this.pendingBleStop = null\n this.detachLinkIfIdle()\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 /** Observe link/status; native SDK and ASG own controller liveness. */\n private startLifecycle(_streamId: string): void {\n this.pendingBleStop = null\n this.attachLink()\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 || entry.stopping) 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 = BgTimer.setTimeout(() => void poll(), delayMs)\n }\n\n const poll = async () => {\n if (this.current !== entry || entry.stopping) 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 if (this.current !== entry || entry.stopping) return\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 // While the BLE link is down, Cloudflare is the only witness to the\n // publisher. Two consecutive \"nobody is publishing\" probes mean the\n // glasses are off, not merely out of Bluetooth range — stop waiting.\n if (this.suspended) {\n if (status.isConnected) {\n this.suspended.publisherGoneProbes = 0\n } else {\n this.suspended.publisherGoneProbes += 1\n if (this.suspended.publisherGoneProbes >= this.timings.suspendedPublisherGoneProbes) {\n this.failSuspended(entry.streamId, \"glasses_disconnected_publisher_gone\", {publisherGone: true})\n keepPolling = false\n }\n }\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 this.requestTeardown(targetStreamId, \"webrtc_not_connected\")\n keepPolling = false\n }\n }\n }\n } catch (err) {\n if (this.current !== entry || entry.stopping) return\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 this.requestTeardown(targetStreamId, \"webrtc_status_unavailable\")\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 || entry.stopping) 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 (this.current !== entry || entry.stopping) return\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 BgTimer.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 BgTimer.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 this.requestTeardown(targetStreamId, \"hls_not_ready\")\n }\n }\n BgTimer.setTimeout(() => {\n // Guard: stream may have been torn down during the initial delay.\n if (this.current !== entry || entry.stopping) return\n entry.hlsTimer = BgTimer.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 = this.current.kind === \"managed\" ? Array.from(this.current.subscribers) : [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 if (this.suspended) {\n BgTimer.clearTimeout(this.suspended.graceTimer)\n this.suspended = null\n }\n\n // With the link down a BLE write can only fail (and hold the transition\n // lock for the native timeout). Defer it to the next reconnect instead.\n const linkUp = this.linkSource.isConnected()\n if (sendBleStop && !linkUp) {\n this.pendingBleStop = {streamId: entry.streamId, hotspot: entry.kind === \"managed\" && !!entry.relay, generation: this.publisherGeneration}\n console.warn(\"[STREAM] BLE link down during teardown; stopStream deferred\", {\n streamId: entry.streamId,\n reason,\n })\n }\n\n if (entry.kind === \"managed\") {\n entry.stopping = true\n if (entry.cloudflareTimer) BgTimer.clearTimeout(entry.cloudflareTimer)\n if (entry.hlsTimer) BgTimer.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 // Relay stop owns the BLE publisher, native peers and hotspot. Keep the entry on failure\n // so another start cannot acquire resources whose teardown has not been confirmed.\n if (entry.kind === \"managed\" && entry.relay) await entry.relay.stop()\n try {\n if (sendBleStop && linkUp && !(entry.kind === \"managed\" && entry.relay)) {\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 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 // BLE can recover while native cleanup is draining; no second link event is required.\n await this.flushPendingBleStop()\n this.detachLinkIfIdle()\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 is explicit. 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\" ? p.webrtcPublishUrl : preference === \"rtmp\" ? p.rtmpUrl || p.srtUrl : p.srtUrl || p.rtmpUrl\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"]}
|