@reactor-team/js-sdk 2.11.2 → 2.12.0

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/dist/index.js CHANGED
@@ -153,7 +153,7 @@ var import_zod = require("zod");
153
153
  // package.json
154
154
  var package_default = {
155
155
  name: "@reactor-team/js-sdk",
156
- version: "2.11.2",
156
+ version: "2.12.0",
157
157
  description: "Reactor JavaScript frontend SDK \u2014 connect React and TypeScript apps to real-time AI video models on Reactor.",
158
158
  license: "Apache-2.0",
159
159
  repository: {
@@ -209,6 +209,7 @@ var package_default = {
209
209
  },
210
210
  packageManager: "pnpm@10.12.1",
211
211
  dependencies: {
212
+ awaitqueue: "^3.3.0",
212
213
  mp4box: "^2.3.0",
213
214
  "sdp-transform": "^3.0.0",
214
215
  zod: "^4.4.3"
@@ -227,6 +228,7 @@ var package_default = {
227
228
  "@roamhq/wrtc": "^0.8.0",
228
229
  "@types/node": "^25",
229
230
  "@types/react": "^19.2.15",
231
+ "@types/sdp-transform": "^2.15.0",
230
232
  "hls.js": "^1.6.0",
231
233
  prettier: "^3.6.2",
232
234
  tsup: "^8.5.0",
@@ -322,8 +324,12 @@ var WebRTCSdpOfferRequestSchema = import_zod.z.object({
322
324
  client_info: ClientInfoSchema.optional(),
323
325
  track_mapping: import_zod.z.array(TrackMappingEntrySchema)
324
326
  });
327
+ var WebRTCSdpOfferResponseSchema = import_zod.z.object({
328
+ connection_id: import_zod.z.number().optional()
329
+ });
325
330
  var WebRTCSdpAnswerResponseSchema = import_zod.z.object({
326
- sdp_answer: import_zod.z.string()
331
+ sdp_answer: import_zod.z.string(),
332
+ connection_id: import_zod.z.number().optional()
327
333
  });
328
334
  var IceCandidateSchema = import_zod.z.object({
329
335
  candidate: import_zod.z.string(),
@@ -851,6 +857,9 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
851
857
  }
852
858
  };
853
859
 
860
+ // src/core/WebRTCTransportClient.ts
861
+ var import_awaitqueue = require("awaitqueue");
862
+
854
863
  // src/utils/sdp.ts
855
864
  var import_sdp_transform = require("sdp-transform");
856
865
  function sdpLineSeparator(sdp) {
@@ -901,13 +910,6 @@ function collectSanitizedCodecPayloadSet(media) {
901
910
  }
902
911
  return tracked.size > 0 ? tracked : null;
903
912
  }
904
- function mediaSectionNeedsSanitizedPtRelocate(media) {
905
- const pts = collectSanitizedCodecPayloadSet(media);
906
- if (!pts) {
907
- return false;
908
- }
909
- return [...pts].some((p) => p < DYNAMIC_PT_MIN || p > DYNAMIC_PT_MAX);
910
- }
911
913
  function codecRelocationPriority(enc) {
912
914
  const u = (enc != null ? enc : "").toUpperCase();
913
915
  if (/^(H265|HEVC|HEV1|HVC1)/.test(u)) return 0;
@@ -941,7 +943,7 @@ function computeCodecRemapForMedia(media, forbidden) {
941
943
  return remap;
942
944
  }
943
945
  const relocate = [...tracked].filter(
944
- (p) => p < DYNAMIC_PT_MIN || p > DYNAMIC_PT_MAX
946
+ (p) => p < DYNAMIC_PT_MIN || p > DYNAMIC_PT_MAX || forbidden.has(p)
945
947
  );
946
948
  if (relocate.length === 0) {
947
949
  return remap;
@@ -1178,7 +1180,7 @@ function stripTelephoneEventsPreserveOrder(sdp) {
1178
1180
  function transformOfferSdpCodecDynamicPts(sdp) {
1179
1181
  var _a;
1180
1182
  const session = (0, import_sdp_transform.parse)(sdp);
1181
- if (!session.media.some(mediaSectionNeedsSanitizedPtRelocate)) {
1183
+ if (!session.media.some((m) => collectSanitizedCodecPayloadSet(m) !== null)) {
1182
1184
  return sdp;
1183
1185
  }
1184
1186
  const remaps = [];
@@ -1300,6 +1302,26 @@ function parseMessage(data) {
1300
1302
  }
1301
1303
  return data;
1302
1304
  }
1305
+ function complementDirection(direction) {
1306
+ if (direction === "sendonly") return "recvonly";
1307
+ if (direction === "recvonly") return "sendonly";
1308
+ return direction;
1309
+ }
1310
+ function replaceSdpDirectionForMid(sdp, mid, direction) {
1311
+ const [session, ...mediaSections] = sdp.split(/(?=\r\nm=)/);
1312
+ const updated = mediaSections.map((section) => {
1313
+ if (!section.includes(`\r
1314
+ a=mid:${mid}\r
1315
+ `)) return section;
1316
+ return section.replace(
1317
+ /\r\na=(sendonly|recvonly|sendrecv|inactive)\r\n/,
1318
+ `\r
1319
+ a=${direction}\r
1320
+ `
1321
+ );
1322
+ });
1323
+ return session + updated.join("");
1324
+ }
1303
1325
  function closePeerConnection(pc) {
1304
1326
  pc.close();
1305
1327
  }
@@ -1385,6 +1407,8 @@ var INITIAL_BACKOFF_MS = 200;
1385
1407
  var MAX_BACKOFF_MS = 15e3;
1386
1408
  var BACKOFF_MULTIPLIER = 2;
1387
1409
  var DEFAULT_MAX_POLL_ATTEMPTS = 6;
1410
+ var MIN_CONNECTION_ID = 1e3;
1411
+ var MAX_CONNECTION_ID = 9999;
1388
1412
  var ICE_CANDIDATE_BATCH_WINDOW_MS = 25;
1389
1413
  var WebRTCTransportClient = class {
1390
1414
  constructor(config) {
@@ -1392,8 +1416,14 @@ var WebRTCTransportClient = class {
1392
1416
  this.status = "disconnected";
1393
1417
  this.transceiverMap = /* @__PURE__ */ new Map();
1394
1418
  this.publishedTracks = /* @__PURE__ */ new Map();
1419
+ // Serializes all SDP renegotiations (pause/resume direction changes) and gates
1420
+ // them behind the connection-ready task. Reset on each prepare() call.
1421
+ this.peerConnectionQueue = new import_awaitqueue.AwaitQueue();
1422
+ this.pendingControlRequests = /* @__PURE__ */ new Map();
1423
+ this.controlRequestCounter = 0;
1395
1424
  this.peerConnected = false;
1396
1425
  this.dataChannelOpen = false;
1426
+ this.controlChannelOpen = false;
1397
1427
  // Trickle ICE batching
1398
1428
  this.pendingIceCandidates = [];
1399
1429
  var _a, _b;
@@ -1498,11 +1528,34 @@ var WebRTCTransportClient = class {
1498
1528
  return iceServers;
1499
1529
  });
1500
1530
  }
1501
- sendSdpOffer(sdpOffer, trackMapping, method = "POST") {
1531
+ registerConnection() {
1532
+ return __async(this, null, function* () {
1533
+ console.debug("[WebRTCTransport] Registering connection...");
1534
+ const response = yield fetch(`${this.transportBaseUrl}/connections`, {
1535
+ method: "POST",
1536
+ headers: yield this.getHeaders(),
1537
+ signal: this.signal
1538
+ });
1539
+ yield this.checkVersionMismatch(response);
1540
+ if (response.status !== 201) {
1541
+ const errorText = yield response.text();
1542
+ throw new Error(
1543
+ `Failed to register connection: ${response.status} ${errorText}`
1544
+ );
1545
+ }
1546
+ const data = yield response.json();
1547
+ const connectionId = data.connection_id;
1548
+ console.debug(
1549
+ `[WebRTCTransport] Connection registered: id=${connectionId}`
1550
+ );
1551
+ return connectionId;
1552
+ });
1553
+ }
1554
+ sendSdpOffer(connectionId, sdpOffer, trackMapping, reconnect = false) {
1502
1555
  return __async(this, null, function* () {
1556
+ const method = reconnect ? "PUT" : "POST";
1503
1557
  console.debug(
1504
- `[WebRTCTransport] Sending SDP offer (${method}) for session:`,
1505
- this.sessionId
1558
+ `[WebRTCTransport] Sending SDP offer (${method}) connection=${connectionId}`
1506
1559
  );
1507
1560
  const requestBody = {
1508
1561
  sdp_offer: sdpOffer,
@@ -1512,17 +1565,30 @@ var WebRTCTransportClient = class {
1512
1565
  },
1513
1566
  track_mapping: trackMapping
1514
1567
  };
1515
- const response = yield fetch(`${this.transportBaseUrl}/sdp_params`, {
1516
- method,
1517
- headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
1518
- "Content-Type": "application/json"
1519
- }),
1520
- body: JSON.stringify(requestBody),
1521
- signal: this.signal
1522
- });
1568
+ const response = yield fetch(
1569
+ `${this.transportBaseUrl}/connections/${connectionId}/sdp_params`,
1570
+ {
1571
+ method,
1572
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
1573
+ "Content-Type": "application/json"
1574
+ }),
1575
+ body: JSON.stringify(requestBody),
1576
+ signal: this.signal
1577
+ }
1578
+ );
1523
1579
  yield this.checkVersionMismatch(response);
1524
1580
  if (response.status !== 202) {
1525
1581
  const errorText = yield response.text();
1582
+ if (response.status === 404) {
1583
+ throw new Error(
1584
+ `[WebRTCTransport] Connection ${connectionId} not found or already closed (404). A supplied connectionId must reference a connection registered under this session (POST .../connections) that is still open. ${errorText}`
1585
+ );
1586
+ }
1587
+ if (response.status === 400) {
1588
+ throw new Error(
1589
+ `[WebRTCTransport] Connection ${connectionId} rejected (400): ${errorText}`
1590
+ );
1591
+ }
1526
1592
  throw new Error(
1527
1593
  `Failed to send SDP offer: ${response.status} ${errorText}`
1528
1594
  );
@@ -1532,6 +1598,12 @@ var WebRTCTransportClient = class {
1532
1598
  }
1533
1599
  sendIceCandidates(candidates, is_final) {
1534
1600
  return __async(this, null, function* () {
1601
+ if (this.connectionId === void 0) {
1602
+ console.debug(
1603
+ "[WebRTCTransport] ICE candidates dropped: no active connection"
1604
+ );
1605
+ return;
1606
+ }
1535
1607
  console.debug(
1536
1608
  `[WebRTCTransport] Sending ICE candidates (count=${candidates.length}, is_final=${is_final})`
1537
1609
  );
@@ -1543,14 +1615,17 @@ var WebRTCTransportClient = class {
1543
1615
  sdk_type: REACTOR_SDK_TYPE
1544
1616
  }
1545
1617
  };
1546
- const response = yield fetch(`${this.transportBaseUrl}/ice_candidates`, {
1547
- method: "POST",
1548
- headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
1549
- "Content-Type": "application/json"
1550
- }),
1551
- body: JSON.stringify(requestBody),
1552
- signal: this.signal
1553
- });
1618
+ const response = yield fetch(
1619
+ `${this.transportBaseUrl}/connections/${this.connectionId}/ice_candidates`,
1620
+ {
1621
+ method: "POST",
1622
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
1623
+ "Content-Type": "application/json"
1624
+ }),
1625
+ body: JSON.stringify(requestBody),
1626
+ signal: this.signal
1627
+ }
1628
+ );
1554
1629
  yield this.checkVersionMismatch(response);
1555
1630
  if (response.status !== 202) {
1556
1631
  const errorText = yield response.text();
@@ -1559,7 +1634,6 @@ var WebRTCTransportClient = class {
1559
1634
  );
1560
1635
  }
1561
1636
  console.debug("[WebRTCTransport] ICE candidates accepted (202)");
1562
- return;
1563
1637
  });
1564
1638
  }
1565
1639
  /**
@@ -1594,9 +1668,10 @@ var WebRTCTransportClient = class {
1594
1668
  }
1595
1669
  this.pendingIceCandidates = [];
1596
1670
  }
1597
- pollSdpAnswer() {
1671
+ pollSdpAnswer(connectionId) {
1598
1672
  return __async(this, null, function* () {
1599
1673
  console.debug("[WebRTCTransport] Polling for SDP answer...");
1674
+ const pollUrl = `${this.transportBaseUrl}/connections/${connectionId}/sdp_params`;
1600
1675
  const pollStart = performance.now();
1601
1676
  let backoffMs = INITIAL_BACKOFF_MS;
1602
1677
  let attempt = 0;
@@ -1613,7 +1688,7 @@ var WebRTCTransportClient = class {
1613
1688
  console.debug(
1614
1689
  `[WebRTCTransport] SDP poll attempt ${attempt}/${this.maxPollAttempts}`
1615
1690
  );
1616
- const response = yield fetch(`${this.transportBaseUrl}/sdp_params`, {
1691
+ const response = yield fetch(pollUrl, {
1617
1692
  method: "GET",
1618
1693
  headers: yield this.getHeaders(),
1619
1694
  signal: this.signal
@@ -1668,16 +1743,34 @@ var WebRTCTransportClient = class {
1668
1743
  this.dataChannel.close();
1669
1744
  this.dataChannel = void 0;
1670
1745
  }
1746
+ if (this.controlChannel) {
1747
+ this.controlChannel.close();
1748
+ this.controlChannel = void 0;
1749
+ }
1671
1750
  if (this.peerConnection) {
1672
1751
  closePeerConnection(this.peerConnection);
1673
1752
  this.peerConnection = void 0;
1674
1753
  }
1675
1754
  this.peerConnected = false;
1676
1755
  this.dataChannelOpen = false;
1756
+ this.controlChannelOpen = false;
1757
+ this.peerConnectionQueue.stop();
1758
+ this.peerConnectionQueue = new import_awaitqueue.AwaitQueue();
1759
+ this.peerConnectionQueue.push(
1760
+ () => new Promise((resolve) => {
1761
+ this.readyGateResolve = resolve;
1762
+ })
1763
+ ).catch(() => {
1764
+ });
1677
1765
  const iceServers = this.cachedIceServers ? yield this.cachedIceServers : yield this.fetchIceServers();
1678
1766
  this.cachedIceServers = void 0;
1679
1767
  this.peerConnection = createPeerConnection({ iceServers });
1680
1768
  this.setupPeerConnectionHandlers();
1769
+ this.controlChannel = createDataChannel(
1770
+ this.peerConnection,
1771
+ "control"
1772
+ );
1773
+ this.setupControlChannelHandlers();
1681
1774
  this.dataChannel = createDataChannel(this.peerConnection);
1682
1775
  this.setupDataChannelHandlers();
1683
1776
  this.transceiverMap.clear();
@@ -1700,20 +1793,34 @@ var WebRTCTransportClient = class {
1700
1793
  console.debug("[WebRTCTransport] SDP offer prepared");
1701
1794
  });
1702
1795
  }
1703
- connect(reconnect = false) {
1796
+ connect(reconnect = false, connectionId) {
1704
1797
  return __async(this, null, function* () {
1705
1798
  if (!this.pendingSdpOffer || !this.pendingTrackMapping) {
1706
1799
  throw new Error(
1707
1800
  "[WebRTCTransport] No prepared connection. Call prepare() first."
1708
1801
  );
1709
1802
  }
1710
- const method = reconnect ? "PUT" : "POST";
1711
1803
  const sdpOffer = this.pendingSdpOffer;
1712
1804
  const trackMapping = this.pendingTrackMapping;
1713
1805
  this.pendingSdpOffer = void 0;
1714
1806
  this.pendingTrackMapping = void 0;
1715
- yield this.sendSdpOffer(sdpOffer, trackMapping, method);
1716
- const answerResponse = yield this.pollSdpAnswer();
1807
+ if (connectionId !== void 0) {
1808
+ if (!Number.isInteger(connectionId) || connectionId <= MIN_CONNECTION_ID || connectionId > MAX_CONNECTION_ID) {
1809
+ throw new Error(
1810
+ `[WebRTCTransport] Invalid connectionId ${connectionId}: must be an integer in (${MIN_CONNECTION_ID}, ${MAX_CONNECTION_ID}]`
1811
+ );
1812
+ }
1813
+ this.connectionId = connectionId;
1814
+ } else if (!reconnect || this.connectionId === void 0) {
1815
+ this.connectionId = yield this.registerConnection();
1816
+ }
1817
+ yield this.sendSdpOffer(
1818
+ this.connectionId,
1819
+ sdpOffer,
1820
+ trackMapping,
1821
+ reconnect
1822
+ );
1823
+ const answerResponse = yield this.pollSdpAnswer(this.connectionId);
1717
1824
  this.iceStartTime = performance.now();
1718
1825
  yield setRemoteDescription(
1719
1826
  this.peerConnection,
@@ -1734,13 +1841,28 @@ var WebRTCTransportClient = class {
1734
1841
  this.dataChannel.close();
1735
1842
  this.dataChannel = void 0;
1736
1843
  }
1844
+ if (this.controlChannel) {
1845
+ this.controlChannel.close();
1846
+ this.controlChannel = void 0;
1847
+ }
1737
1848
  if (this.peerConnection) {
1738
1849
  closePeerConnection(this.peerConnection);
1739
1850
  this.peerConnection = void 0;
1740
1851
  }
1852
+ for (const [, pending] of this.pendingControlRequests) {
1853
+ clearTimeout(pending.timeout);
1854
+ pending.reject(
1855
+ new Error("[WebRTCTransport] Disconnected while waiting for response")
1856
+ );
1857
+ }
1858
+ this.pendingControlRequests.clear();
1859
+ this.readyGateResolve = void 0;
1860
+ this.peerConnectionQueue.stop();
1861
+ this.connectionId = void 0;
1741
1862
  this.transceiverMap.clear();
1742
1863
  this.peerConnected = false;
1743
1864
  this.dataChannelOpen = false;
1865
+ this.controlChannelOpen = false;
1744
1866
  this.resetTransportTimings();
1745
1867
  this.setStatus("disconnected");
1746
1868
  console.debug("[WebRTCTransport] Disconnected");
@@ -1803,6 +1925,119 @@ var WebRTCTransportClient = class {
1803
1925
  console.warn("[WebRTCTransport] Failed to send message:", error);
1804
1926
  }
1805
1927
  }
1928
+ sendControlMessage(command, data, reqId) {
1929
+ if (!this.controlChannel) {
1930
+ console.warn("[WebRTCTransport] Control channel not available");
1931
+ return;
1932
+ }
1933
+ try {
1934
+ if (this.controlChannel.readyState !== "open") {
1935
+ throw new Error(
1936
+ `Control channel not open: ${this.controlChannel.readyState}`
1937
+ );
1938
+ }
1939
+ this.controlChannel.send(
1940
+ JSON.stringify({ type: "notification", event: command, data })
1941
+ );
1942
+ } catch (error) {
1943
+ console.warn("[WebRTCTransport] Failed to send control message:", error);
1944
+ }
1945
+ }
1946
+ sendControlRequest(method, data, timeoutMs = 1e4) {
1947
+ return new Promise((resolve, reject) => {
1948
+ const requestId = `ctrl_${++this.controlRequestCounter}`;
1949
+ const timeout = setTimeout(() => {
1950
+ this.pendingControlRequests.delete(requestId);
1951
+ reject(new Error(`[WebRTCTransport] Request "${method}" timed out`));
1952
+ }, timeoutMs);
1953
+ this.pendingControlRequests.set(requestId, { resolve, reject, timeout });
1954
+ try {
1955
+ if (!this.controlChannel || this.controlChannel.readyState !== "open") {
1956
+ throw new Error("Control channel not available");
1957
+ }
1958
+ this.controlChannel.send(
1959
+ JSON.stringify({
1960
+ type: "request",
1961
+ method,
1962
+ request_id: requestId,
1963
+ data
1964
+ })
1965
+ );
1966
+ } catch (error) {
1967
+ clearTimeout(timeout);
1968
+ this.pendingControlRequests.delete(requestId);
1969
+ reject(error);
1970
+ }
1971
+ });
1972
+ }
1973
+ pauseTrack(name) {
1974
+ this.peerConnectionQueue.push(() => __async(this, null, function* () {
1975
+ var _a;
1976
+ const entry = this.transceiverMap.get(name);
1977
+ if ((_a = entry == null ? void 0 : entry.transceiver) == null ? void 0 : _a.mid) {
1978
+ entry.transceiver.direction = "inactive";
1979
+ yield this.applyDirectionLocally(entry.transceiver.mid, "inactive");
1980
+ }
1981
+ this.sendControlMessage("pause_track", { name });
1982
+ })).catch((e) => {
1983
+ console.warn("[WebRTCTransport] Failed to pause track:", e);
1984
+ });
1985
+ }
1986
+ resumeTrack(name) {
1987
+ this.peerConnectionQueue.push(() => __async(this, null, function* () {
1988
+ var _a;
1989
+ const entry = this.transceiverMap.get(name);
1990
+ if ((_a = entry == null ? void 0 : entry.transceiver) == null ? void 0 : _a.mid) {
1991
+ entry.transceiver.direction = entry.direction;
1992
+ yield this.applyDirectionLocally(
1993
+ entry.transceiver.mid,
1994
+ entry.direction
1995
+ );
1996
+ }
1997
+ this.sendControlMessage("resume_track", { name });
1998
+ })).catch((e) => {
1999
+ console.warn("[WebRTCTransport] Failed to resume track:", e);
2000
+ });
2001
+ }
2002
+ applyDirectionLocally(mid, localDirection) {
2003
+ return __async(this, null, function* () {
2004
+ var _a, _b;
2005
+ const pc = this.peerConnection;
2006
+ if (!pc) return;
2007
+ const tx = pc.getTransceivers().find((t) => t.mid === mid);
2008
+ if (tx && tx.currentDirection === localDirection) return;
2009
+ if (pc.signalingState !== "stable") return;
2010
+ const localSdp = (_a = pc.localDescription) == null ? void 0 : _a.sdp;
2011
+ const remoteSdp = (_b = pc.remoteDescription) == null ? void 0 : _b.sdp;
2012
+ if (!localSdp || !remoteSdp) return;
2013
+ const modifiedLocal = replaceSdpDirectionForMid(
2014
+ localSdp,
2015
+ mid,
2016
+ localDirection
2017
+ );
2018
+ const modifiedRemote = replaceSdpDirectionForMid(
2019
+ remoteSdp,
2020
+ mid,
2021
+ complementDirection(localDirection)
2022
+ );
2023
+ try {
2024
+ yield pc.setLocalDescription(
2025
+ new RTCSessionDescription({ type: "offer", sdp: modifiedLocal })
2026
+ );
2027
+ yield pc.setRemoteDescription(
2028
+ new RTCSessionDescription({ type: "answer", sdp: modifiedRemote })
2029
+ );
2030
+ } catch (e) {
2031
+ if (pc.signalingState === "have-local-offer") {
2032
+ try {
2033
+ yield pc.setLocalDescription({ type: "rollback" });
2034
+ } catch (e2) {
2035
+ }
2036
+ }
2037
+ throw e;
2038
+ }
2039
+ });
2040
+ }
1806
2041
  // ─────────────────────────────────────────────────────────────────────────
1807
2042
  // Track Publishing
1808
2043
  // ─────────────────────────────────────────────────────────────────────────
@@ -1829,6 +2064,7 @@ var WebRTCTransportClient = class {
1829
2064
  `[WebRTCTransport] Cannot publish track "${name}" - transceiver is recvonly`
1830
2065
  );
1831
2066
  }
2067
+ yield this.sendControlRequest("publish_track", { name });
1832
2068
  yield entry.transceiver.sender.replaceTrack(track);
1833
2069
  this.publishedTracks.set(name, track);
1834
2070
  console.debug(`[WebRTCTransport] Track "${name}" published successfully`);
@@ -1840,6 +2076,7 @@ var WebRTCTransportClient = class {
1840
2076
  if (!(entry == null ? void 0 : entry.transceiver) || !this.publishedTracks.has(name)) return;
1841
2077
  try {
1842
2078
  yield entry.transceiver.sender.replaceTrack(null);
2079
+ this.sendControlMessage("unpublish_track", { name });
1843
2080
  console.debug(
1844
2081
  `[WebRTCTransport] Track "${name}" unpublished successfully`
1845
2082
  );
@@ -1925,9 +2162,11 @@ var WebRTCTransportClient = class {
1925
2162
  // Internal Helpers
1926
2163
  // ─────────────────────────────────────────────────────────────────────────
1927
2164
  checkFullyConnected() {
1928
- if (this.peerConnected && this.dataChannelOpen) {
2165
+ if (this.peerConnected && this.dataChannelOpen && this.controlChannelOpen) {
1929
2166
  this.setStatus("connected");
1930
2167
  this.startStatsPolling();
2168
+ this.readyGateResolve();
2169
+ this.readyGateResolve = void 0;
1931
2170
  }
1932
2171
  }
1933
2172
  setStatus(newStatus) {
@@ -2047,6 +2286,46 @@ var WebRTCTransportClient = class {
2047
2286
  }
2048
2287
  };
2049
2288
  }
2289
+ setupControlChannelHandlers() {
2290
+ if (!this.controlChannel) return;
2291
+ this.controlChannel.onopen = () => {
2292
+ console.debug("[WebRTCTransport] Control channel open");
2293
+ this.controlChannelOpen = true;
2294
+ this.checkFullyConnected();
2295
+ };
2296
+ this.controlChannel.onclose = () => {
2297
+ console.debug("[WebRTCTransport] Control channel closed");
2298
+ this.controlChannelOpen = false;
2299
+ };
2300
+ this.controlChannel.onerror = (error) => {
2301
+ console.error("[WebRTCTransport] Control channel error:", error);
2302
+ };
2303
+ this.controlChannel.onmessage = (event) => {
2304
+ var _a, _b;
2305
+ const raw = parseMessage(event.data);
2306
+ if ((raw == null ? void 0 : raw.type) === "response") {
2307
+ const requestId = raw == null ? void 0 : raw.request_id;
2308
+ if (requestId) {
2309
+ const pending = this.pendingControlRequests.get(requestId);
2310
+ if (pending) {
2311
+ clearTimeout(pending.timeout);
2312
+ this.pendingControlRequests.delete(requestId);
2313
+ if (raw == null ? void 0 : raw.error) {
2314
+ pending.reject(
2315
+ new Error(
2316
+ `[WebRTCTransport] ${(_a = raw.method) != null ? _a : "request"} failed: ${(_b = raw.error.message) != null ? _b : "unknown error"}`
2317
+ )
2318
+ );
2319
+ } else {
2320
+ pending.resolve();
2321
+ }
2322
+ }
2323
+ }
2324
+ return;
2325
+ }
2326
+ console.debug("[WebRTCTransport] Received control message:", raw);
2327
+ };
2328
+ }
2050
2329
  };
2051
2330
 
2052
2331
  // src/core/Reactor.ts
@@ -2730,7 +3009,17 @@ var OptionsSchema = import_zod3.z.object({
2730
3009
  var Reactor = class {
2731
3010
  constructor(options) {
2732
3011
  this.status = "disconnected";
3012
+ /**
3013
+ * True only when the active session was created by THIS connect flow
3014
+ * (via `createSession()`). False when the session was adopted via
3015
+ * `connect({ sessionId })`. We must never DELETE a session we did not
3016
+ * create — another client (or the backend that created it) owns its
3017
+ * lifecycle, so on disconnect/teardown/error an adopting client tears
3018
+ * down its own transport but leaves the session alive.
3019
+ */
3020
+ this.createdSession = false;
2733
3021
  this.tracks = [];
3022
+ this.autoResumeTracks = false;
2734
3023
  this.eventListeners = /* @__PURE__ */ new Map();
2735
3024
  const validatedOptions = OptionsSchema.parse(options);
2736
3025
  this.coordinatorUrl = validatedOptions.apiUrl;
@@ -2967,6 +3256,7 @@ var Reactor = class {
2967
3256
  "gpu",
2968
3257
  true
2969
3258
  );
3259
+ throw error;
2970
3260
  }
2971
3261
  });
2972
3262
  }
@@ -2986,6 +3276,14 @@ var Reactor = class {
2986
3276
  }
2987
3277
  });
2988
3278
  }
3279
+ pauseTrack(name) {
3280
+ var _a;
3281
+ (_a = this.transportClient) == null ? void 0 : _a.pauseTrack(name);
3282
+ }
3283
+ resumeTrack(name) {
3284
+ var _a;
3285
+ (_a = this.transportClient) == null ? void 0 : _a.resumeTrack(name);
3286
+ }
2989
3287
  /**
2990
3288
  * Reconnects to an existing session with a fresh transport.
2991
3289
  */
@@ -3044,6 +3342,7 @@ var Reactor = class {
3044
3342
  */
3045
3343
  connect(jwtToken, options) {
3046
3344
  return __async(this, null, function* () {
3345
+ var _a;
3047
3346
  console.debug("[Reactor] Connecting, status:", this.status);
3048
3347
  if (jwtToken == void 0 && !this.local) {
3049
3348
  throw new Error("No authentication provided and not in local mode");
@@ -3067,12 +3366,14 @@ var Reactor = class {
3067
3366
  if (options == null ? void 0 : options.sessionId) {
3068
3367
  yield this.coordinatorClient.adoptSession(options.sessionId);
3069
3368
  sessionId = options.sessionId;
3369
+ this.createdSession = false;
3070
3370
  console.debug("[Reactor] Attaching to existing session:", sessionId);
3071
3371
  } else {
3072
3372
  const tSession = performance.now();
3073
3373
  const initialResponse = yield this.coordinatorClient.createSession();
3074
3374
  sessionCreationMs = performance.now() - tSession;
3075
3375
  sessionId = initialResponse.session_id;
3376
+ this.createdSession = true;
3076
3377
  console.debug(
3077
3378
  "[Reactor] Session created:",
3078
3379
  sessionId,
@@ -3092,19 +3393,22 @@ var Reactor = class {
3092
3393
  this.setupTransportHandlers();
3093
3394
  let sessionPollingMs;
3094
3395
  let transportConnectingMs;
3396
+ this.autoResumeTracks = (_a = options == null ? void 0 : options.autoResumeTracks) != null ? _a : true;
3095
3397
  if (this.presetTracks) {
3398
+ this.tracks = this.presetTracks;
3096
3399
  const tParallel = performance.now();
3097
3400
  const [sessionResponse] = yield Promise.all([
3098
3401
  this.coordinatorClient.pollSessionReady(),
3099
- this.transportClient.prepare(this.presetTracks)
3402
+ this.transportClient.prepare(this.tracks)
3100
3403
  ]);
3101
3404
  sessionPollingMs = performance.now() - tParallel;
3102
3405
  this.sessionResponse = sessionResponse;
3103
- this.capabilities = sessionResponse.capabilities;
3104
- this.tracks = this.presetTracks;
3406
+ this.capabilities = __spreadProps(__spreadValues({}, sessionResponse.capabilities), {
3407
+ tracks: this.tracks
3408
+ });
3105
3409
  this.emit("capabilitiesReceived", this.capabilities);
3106
3410
  const tConnect = performance.now();
3107
- yield this.transportClient.connect();
3411
+ yield this.transportClient.connect(false, options == null ? void 0 : options.connectionId);
3108
3412
  transportConnectingMs = performance.now() - tConnect;
3109
3413
  } else {
3110
3414
  this.transportClient.warmup();
@@ -3112,8 +3416,10 @@ var Reactor = class {
3112
3416
  const sessionResponse = yield this.coordinatorClient.pollSessionReady();
3113
3417
  sessionPollingMs = performance.now() - tPoll;
3114
3418
  this.sessionResponse = sessionResponse;
3115
- this.capabilities = sessionResponse.capabilities;
3116
3419
  this.tracks = sessionResponse.capabilities.tracks;
3420
+ this.capabilities = __spreadProps(__spreadValues({}, sessionResponse.capabilities), {
3421
+ tracks: this.tracks
3422
+ });
3117
3423
  this.emit("capabilitiesReceived", this.capabilities);
3118
3424
  const protocol = sessionResponse.selected_transport.protocol;
3119
3425
  if (protocol !== "webrtc") {
@@ -3121,7 +3427,7 @@ var Reactor = class {
3121
3427
  }
3122
3428
  const tTransport = performance.now();
3123
3429
  yield this.transportClient.prepare(this.tracks);
3124
- yield this.transportClient.connect();
3430
+ yield this.transportClient.connect(false, options == null ? void 0 : options.connectionId);
3125
3431
  transportConnectingMs = performance.now() - tTransport;
3126
3432
  }
3127
3433
  console.debug("[Reactor] Session ready, tracks:", this.tracks.length);
@@ -3171,6 +3477,13 @@ var Reactor = class {
3171
3477
  switch (status) {
3172
3478
  case "connected":
3173
3479
  this.finalizeConnectionTimings();
3480
+ if (this.autoResumeTracks) {
3481
+ for (const track of this.tracks) {
3482
+ if (track.direction === "recvonly") {
3483
+ this.resumeTrack(track.name);
3484
+ }
3485
+ }
3486
+ }
3174
3487
  this.setStatus("ready");
3175
3488
  break;
3176
3489
  case "disconnected":
@@ -3192,6 +3505,13 @@ var Reactor = class {
3192
3505
  (name, track, stream) => {
3193
3506
  if (this.transportClient !== client) return;
3194
3507
  this.emit("trackReceived", name, track, stream);
3508
+ if (this.autoResumeTracks) {
3509
+ for (const track2 of this.tracks) {
3510
+ if (track2.direction === "recvonly") {
3511
+ this.resumeTrack(track2.name);
3512
+ }
3513
+ }
3514
+ }
3195
3515
  }
3196
3516
  );
3197
3517
  client.on("statsUpdate", (stats) => {
@@ -3214,10 +3534,16 @@ var Reactor = class {
3214
3534
  (_a = this.coordinatorClient) == null ? void 0 : _a.abort();
3215
3535
  (_b = this.transportClient) == null ? void 0 : _b.abort();
3216
3536
  if (this.coordinatorClient && !recoverable) {
3217
- try {
3218
- yield this.coordinatorClient.terminateSession();
3219
- } catch (error) {
3220
- console.error("[Reactor] Error terminating session:", error);
3537
+ if (this.createdSession) {
3538
+ try {
3539
+ yield this.coordinatorClient.terminateSession();
3540
+ } catch (error) {
3541
+ console.error("[Reactor] Error terminating session:", error);
3542
+ }
3543
+ } else {
3544
+ console.debug(
3545
+ "[Reactor] Adopted session (not the creator) \u2014 skipping DELETE, leaving it alive"
3546
+ );
3221
3547
  }
3222
3548
  this.coordinatorClient = void 0;
3223
3549
  }
@@ -3239,6 +3565,7 @@ var Reactor = class {
3239
3565
  this.capabilities = void 0;
3240
3566
  this.tracks = [];
3241
3567
  this.sessionResponse = void 0;
3568
+ this.createdSession = false;
3242
3569
  }
3243
3570
  });
3244
3571
  }
@@ -3342,7 +3669,8 @@ var defaultInitState = {
3342
3669
  lastError: void 0,
3343
3670
  sessionExpiration: void 0,
3344
3671
  jwtToken: void 0,
3345
- sessionId: void 0
3672
+ sessionId: void 0,
3673
+ connectOptions: void 0
3346
3674
  };
3347
3675
  var initReactorStore = (props) => {
3348
3676
  return __spreadValues(__spreadValues({}, defaultInitState), props);
@@ -3398,6 +3726,7 @@ var createReactorStore = (initProps, publicState = defaultInitState) => {
3398
3726
  });
3399
3727
  return __spreadProps(__spreadValues({}, publicState), {
3400
3728
  jwtToken: initProps.jwtToken,
3729
+ connectOptions: initProps.connectOptions,
3401
3730
  internal: { reactor },
3402
3731
  // actions
3403
3732
  onMessage: (handler) => {
@@ -3426,9 +3755,10 @@ var createReactorStore = (initProps, publicState = defaultInitState) => {
3426
3755
  if (jwtToken === void 0) {
3427
3756
  jwtToken = get().jwtToken;
3428
3757
  }
3758
+ const resolvedOptions = __spreadValues(__spreadValues({}, get().connectOptions), options);
3429
3759
  console.debug("[ReactorStore] Connect called.");
3430
3760
  try {
3431
- yield get().internal.reactor.connect(jwtToken, options);
3761
+ yield get().internal.reactor.connect(jwtToken, resolvedOptions);
3432
3762
  console.debug("[ReactorStore] Connect completed successfully");
3433
3763
  } catch (error) {
3434
3764
  console.error("[ReactorStore] Connect failed:", error);
@@ -3536,30 +3866,31 @@ function ReactorProvider(_a) {
3536
3866
  const storeRef = (0, import_react3.useRef)(void 0);
3537
3867
  const firstRender = (0, import_react3.useRef)(true);
3538
3868
  const [_storeVersion, setStoreVersion] = (0, import_react3.useState)(0);
3869
+ const _a2 = connectOptions != null ? connectOptions : {}, { autoConnect = false } = _a2, pollingOptions = __objRest(_a2, ["autoConnect"]);
3539
3870
  if (storeRef.current === void 0) {
3540
3871
  console.debug("[ReactorProvider] Creating new reactor store");
3541
3872
  storeRef.current = createReactorStore(
3542
3873
  initReactorStore(__spreadProps(__spreadValues({}, props), {
3543
- jwtToken: jwtSource
3874
+ jwtToken: jwtSource,
3875
+ connectOptions: pollingOptions
3544
3876
  }))
3545
3877
  );
3546
3878
  console.debug("[ReactorProvider] Reactor store created successfully");
3547
3879
  }
3548
- const _a2 = connectOptions != null ? connectOptions : {}, { autoConnect = false } = _a2, pollingOptions = __objRest(_a2, ["autoConnect"]);
3549
3880
  const { apiUrl, modelName, local } = props;
3550
3881
  const maxAttempts = pollingOptions.maxAttempts;
3882
+ const { autoResumeTracks } = pollingOptions;
3883
+ (0, import_react3.useEffect)(() => {
3884
+ var _a3;
3885
+ (_a3 = storeRef.current) == null ? void 0 : _a3.setState({ connectOptions: pollingOptions });
3886
+ }, [autoResumeTracks, maxAttempts]);
3551
3887
  (0, import_react3.useEffect)(() => {
3552
3888
  const handleBeforeUnload = () => {
3553
3889
  var _a3;
3554
- console.debug(
3555
- "[ReactorProvider] Page unloading, performing non-recoverable disconnect"
3556
- );
3557
3890
  (_a3 = storeRef.current) == null ? void 0 : _a3.getState().internal.reactor.disconnect(false);
3558
3891
  };
3559
3892
  window.addEventListener("beforeunload", handleBeforeUnload);
3560
- return () => {
3561
- window.removeEventListener("beforeunload", handleBeforeUnload);
3562
- };
3893
+ return () => window.removeEventListener("beforeunload", handleBeforeUnload);
3563
3894
  }, []);
3564
3895
  (0, import_react3.useEffect)(() => {
3565
3896
  if (firstRender.current) {
@@ -3602,7 +3933,8 @@ function ReactorProvider(_a) {
3602
3933
  apiUrl,
3603
3934
  modelName,
3604
3935
  local,
3605
- jwtToken: jwtSource
3936
+ jwtToken: jwtSource,
3937
+ connectOptions: pollingOptions
3606
3938
  })
3607
3939
  );
3608
3940
  const current = storeRef.current;
@@ -3728,26 +4060,39 @@ function ReactorView({
3728
4060
  hasVideoTrack: !!videoMediaTrack,
3729
4061
  hasAudioTrack: !!audioMediaTrack
3730
4062
  });
3731
- if (videoRef.current && mediaStream) {
3732
- console.debug("[ReactorView] Attaching media stream to element");
4063
+ const el = videoRef.current;
4064
+ if (!el || !mediaStream) {
4065
+ console.debug("[ReactorView] No tracks or element to attach");
4066
+ return;
4067
+ }
4068
+ const attach = (reset) => {
3733
4069
  try {
3734
- videoRef.current.srcObject = mediaStream;
3735
- videoRef.current.play().catch((e) => {
4070
+ if (reset) el.srcObject = null;
4071
+ el.srcObject = mediaStream;
4072
+ el.play().catch((e) => {
3736
4073
  console.warn("[ReactorView] Auto-play failed:", e);
3737
4074
  });
3738
- console.debug("[ReactorView] Media stream attached successfully");
3739
4075
  } catch (error) {
3740
4076
  console.error("[ReactorView] Failed to attach media stream:", error);
3741
4077
  }
3742
- return () => {
3743
- console.debug("[ReactorView] Detaching media stream from element");
3744
- if (videoRef.current) {
3745
- videoRef.current.srcObject = null;
3746
- }
3747
- };
3748
- } else {
3749
- console.debug("[ReactorView] No tracks or element to attach");
3750
- }
4078
+ };
4079
+ console.debug("[ReactorView] Attaching media stream to element");
4080
+ attach(false);
4081
+ const onUnmute = () => {
4082
+ console.debug(
4083
+ "[ReactorView] Track unmuted \u2014 re-attaching to render incoming media"
4084
+ );
4085
+ attach(true);
4086
+ };
4087
+ const tracks = mediaStream.getTracks();
4088
+ for (const t of tracks) t.addEventListener("unmute", onUnmute);
4089
+ return () => {
4090
+ console.debug("[ReactorView] Detaching media stream from element");
4091
+ for (const t of tracks) t.removeEventListener("unmute", onUnmute);
4092
+ if (videoRef.current) {
4093
+ videoRef.current.srcObject = null;
4094
+ }
4095
+ };
3751
4096
  }, [mediaStream]);
3752
4097
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
3753
4098
  "div",