@reactor-team/js-sdk 2.11.1 → 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.1",
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(),
@@ -465,6 +471,18 @@ var CoordinatorClient = class {
465
471
  return parsed;
466
472
  });
467
473
  }
474
+ /**
475
+ * Attaches to a session created elsewhere (e.g. by a backend) instead of
476
+ * creating one via {@link createSession}. After this, {@link pollSessionReady}
477
+ * and {@link getSession} operate on the adopted id. The session must be owned
478
+ * by the account behind this client's JWT.
479
+ */
480
+ adoptSession(sessionId) {
481
+ return __async(this, null, function* () {
482
+ this.currentSessionId = sessionId;
483
+ console.debug("[CoordinatorClient] Adopted existing session:", sessionId);
484
+ });
485
+ }
468
486
  /**
469
487
  * Polls GET /sessions/{id} until the Runtime has accepted the session
470
488
  * and populated capabilities and selected_transport.
@@ -756,6 +774,48 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
756
774
  return CreateSessionResponseSchema.parse(data);
757
775
  });
758
776
  }
777
+ /**
778
+ * Adopts the local session for `connect({ sessionId })`: records the id and
779
+ * reads the session descriptor, caching it so {@link pollSessionReady}
780
+ * returns immediately. No `start_session` is issued.
781
+ *
782
+ * The local runtime hosts a single session (always id `"local"`), so the
783
+ * lookup ignores the specific id. This is a pure read of session info — it
784
+ * does not start or otherwise advance the session.
785
+ */
786
+ adoptSession(sessionId) {
787
+ return __async(this, null, function* () {
788
+ this.currentSessionId = sessionId;
789
+ this.cachedSessionResponse = yield this.getSession();
790
+ console.debug(
791
+ "[LocalCoordinatorClient] Adopted existing session:",
792
+ sessionId
793
+ );
794
+ });
795
+ }
796
+ /**
797
+ * Reads the local session descriptor (model, capabilities, transport,
798
+ * state) via the runtime's read-only `GET /session`.
799
+ *
800
+ * The local runtime exposes a single session, so — unlike the Coordinator's
801
+ * id-addressed `GET /sessions/{id}` — there is no id in the path. Read-only:
802
+ * it does not start or advance the session.
803
+ */
804
+ getSession() {
805
+ return __async(this, null, function* () {
806
+ const response = yield fetch(`${this.baseUrl}/session`, {
807
+ method: "GET",
808
+ headers: yield this.getHeaders(),
809
+ signal: this.signal
810
+ });
811
+ if (!response.ok) {
812
+ const errorText = yield response.text();
813
+ throw new Error(`Failed to get session: ${response.status} ${errorText}`);
814
+ }
815
+ const data = yield response.json();
816
+ return SessionResponseSchema.parse(data);
817
+ });
818
+ }
759
819
  /**
760
820
  * Returns the cached full session response immediately.
761
821
  * The local runtime already provided everything in start_session.
@@ -797,6 +857,9 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
797
857
  }
798
858
  };
799
859
 
860
+ // src/core/WebRTCTransportClient.ts
861
+ var import_awaitqueue = require("awaitqueue");
862
+
800
863
  // src/utils/sdp.ts
801
864
  var import_sdp_transform = require("sdp-transform");
802
865
  function sdpLineSeparator(sdp) {
@@ -847,13 +910,6 @@ function collectSanitizedCodecPayloadSet(media) {
847
910
  }
848
911
  return tracked.size > 0 ? tracked : null;
849
912
  }
850
- function mediaSectionNeedsSanitizedPtRelocate(media) {
851
- const pts = collectSanitizedCodecPayloadSet(media);
852
- if (!pts) {
853
- return false;
854
- }
855
- return [...pts].some((p) => p < DYNAMIC_PT_MIN || p > DYNAMIC_PT_MAX);
856
- }
857
913
  function codecRelocationPriority(enc) {
858
914
  const u = (enc != null ? enc : "").toUpperCase();
859
915
  if (/^(H265|HEVC|HEV1|HVC1)/.test(u)) return 0;
@@ -887,7 +943,7 @@ function computeCodecRemapForMedia(media, forbidden) {
887
943
  return remap;
888
944
  }
889
945
  const relocate = [...tracked].filter(
890
- (p) => p < DYNAMIC_PT_MIN || p > DYNAMIC_PT_MAX
946
+ (p) => p < DYNAMIC_PT_MIN || p > DYNAMIC_PT_MAX || forbidden.has(p)
891
947
  );
892
948
  if (relocate.length === 0) {
893
949
  return remap;
@@ -1124,7 +1180,7 @@ function stripTelephoneEventsPreserveOrder(sdp) {
1124
1180
  function transformOfferSdpCodecDynamicPts(sdp) {
1125
1181
  var _a;
1126
1182
  const session = (0, import_sdp_transform.parse)(sdp);
1127
- if (!session.media.some(mediaSectionNeedsSanitizedPtRelocate)) {
1183
+ if (!session.media.some((m) => collectSanitizedCodecPayloadSet(m) !== null)) {
1128
1184
  return sdp;
1129
1185
  }
1130
1186
  const remaps = [];
@@ -1246,6 +1302,26 @@ function parseMessage(data) {
1246
1302
  }
1247
1303
  return data;
1248
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
+ }
1249
1325
  function closePeerConnection(pc) {
1250
1326
  pc.close();
1251
1327
  }
@@ -1331,6 +1407,8 @@ var INITIAL_BACKOFF_MS = 200;
1331
1407
  var MAX_BACKOFF_MS = 15e3;
1332
1408
  var BACKOFF_MULTIPLIER = 2;
1333
1409
  var DEFAULT_MAX_POLL_ATTEMPTS = 6;
1410
+ var MIN_CONNECTION_ID = 1e3;
1411
+ var MAX_CONNECTION_ID = 9999;
1334
1412
  var ICE_CANDIDATE_BATCH_WINDOW_MS = 25;
1335
1413
  var WebRTCTransportClient = class {
1336
1414
  constructor(config) {
@@ -1338,8 +1416,14 @@ var WebRTCTransportClient = class {
1338
1416
  this.status = "disconnected";
1339
1417
  this.transceiverMap = /* @__PURE__ */ new Map();
1340
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;
1341
1424
  this.peerConnected = false;
1342
1425
  this.dataChannelOpen = false;
1426
+ this.controlChannelOpen = false;
1343
1427
  // Trickle ICE batching
1344
1428
  this.pendingIceCandidates = [];
1345
1429
  var _a, _b;
@@ -1444,11 +1528,34 @@ var WebRTCTransportClient = class {
1444
1528
  return iceServers;
1445
1529
  });
1446
1530
  }
1447
- 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) {
1448
1555
  return __async(this, null, function* () {
1556
+ const method = reconnect ? "PUT" : "POST";
1449
1557
  console.debug(
1450
- `[WebRTCTransport] Sending SDP offer (${method}) for session:`,
1451
- this.sessionId
1558
+ `[WebRTCTransport] Sending SDP offer (${method}) connection=${connectionId}`
1452
1559
  );
1453
1560
  const requestBody = {
1454
1561
  sdp_offer: sdpOffer,
@@ -1458,17 +1565,30 @@ var WebRTCTransportClient = class {
1458
1565
  },
1459
1566
  track_mapping: trackMapping
1460
1567
  };
1461
- const response = yield fetch(`${this.transportBaseUrl}/sdp_params`, {
1462
- method,
1463
- headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
1464
- "Content-Type": "application/json"
1465
- }),
1466
- body: JSON.stringify(requestBody),
1467
- signal: this.signal
1468
- });
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
+ );
1469
1579
  yield this.checkVersionMismatch(response);
1470
1580
  if (response.status !== 202) {
1471
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
+ }
1472
1592
  throw new Error(
1473
1593
  `Failed to send SDP offer: ${response.status} ${errorText}`
1474
1594
  );
@@ -1478,6 +1598,12 @@ var WebRTCTransportClient = class {
1478
1598
  }
1479
1599
  sendIceCandidates(candidates, is_final) {
1480
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
+ }
1481
1607
  console.debug(
1482
1608
  `[WebRTCTransport] Sending ICE candidates (count=${candidates.length}, is_final=${is_final})`
1483
1609
  );
@@ -1489,14 +1615,17 @@ var WebRTCTransportClient = class {
1489
1615
  sdk_type: REACTOR_SDK_TYPE
1490
1616
  }
1491
1617
  };
1492
- const response = yield fetch(`${this.transportBaseUrl}/ice_candidates`, {
1493
- method: "POST",
1494
- headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
1495
- "Content-Type": "application/json"
1496
- }),
1497
- body: JSON.stringify(requestBody),
1498
- signal: this.signal
1499
- });
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
+ );
1500
1629
  yield this.checkVersionMismatch(response);
1501
1630
  if (response.status !== 202) {
1502
1631
  const errorText = yield response.text();
@@ -1505,7 +1634,6 @@ var WebRTCTransportClient = class {
1505
1634
  );
1506
1635
  }
1507
1636
  console.debug("[WebRTCTransport] ICE candidates accepted (202)");
1508
- return;
1509
1637
  });
1510
1638
  }
1511
1639
  /**
@@ -1540,9 +1668,10 @@ var WebRTCTransportClient = class {
1540
1668
  }
1541
1669
  this.pendingIceCandidates = [];
1542
1670
  }
1543
- pollSdpAnswer() {
1671
+ pollSdpAnswer(connectionId) {
1544
1672
  return __async(this, null, function* () {
1545
1673
  console.debug("[WebRTCTransport] Polling for SDP answer...");
1674
+ const pollUrl = `${this.transportBaseUrl}/connections/${connectionId}/sdp_params`;
1546
1675
  const pollStart = performance.now();
1547
1676
  let backoffMs = INITIAL_BACKOFF_MS;
1548
1677
  let attempt = 0;
@@ -1559,7 +1688,7 @@ var WebRTCTransportClient = class {
1559
1688
  console.debug(
1560
1689
  `[WebRTCTransport] SDP poll attempt ${attempt}/${this.maxPollAttempts}`
1561
1690
  );
1562
- const response = yield fetch(`${this.transportBaseUrl}/sdp_params`, {
1691
+ const response = yield fetch(pollUrl, {
1563
1692
  method: "GET",
1564
1693
  headers: yield this.getHeaders(),
1565
1694
  signal: this.signal
@@ -1614,16 +1743,34 @@ var WebRTCTransportClient = class {
1614
1743
  this.dataChannel.close();
1615
1744
  this.dataChannel = void 0;
1616
1745
  }
1746
+ if (this.controlChannel) {
1747
+ this.controlChannel.close();
1748
+ this.controlChannel = void 0;
1749
+ }
1617
1750
  if (this.peerConnection) {
1618
1751
  closePeerConnection(this.peerConnection);
1619
1752
  this.peerConnection = void 0;
1620
1753
  }
1621
1754
  this.peerConnected = false;
1622
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
+ });
1623
1765
  const iceServers = this.cachedIceServers ? yield this.cachedIceServers : yield this.fetchIceServers();
1624
1766
  this.cachedIceServers = void 0;
1625
1767
  this.peerConnection = createPeerConnection({ iceServers });
1626
1768
  this.setupPeerConnectionHandlers();
1769
+ this.controlChannel = createDataChannel(
1770
+ this.peerConnection,
1771
+ "control"
1772
+ );
1773
+ this.setupControlChannelHandlers();
1627
1774
  this.dataChannel = createDataChannel(this.peerConnection);
1628
1775
  this.setupDataChannelHandlers();
1629
1776
  this.transceiverMap.clear();
@@ -1646,20 +1793,34 @@ var WebRTCTransportClient = class {
1646
1793
  console.debug("[WebRTCTransport] SDP offer prepared");
1647
1794
  });
1648
1795
  }
1649
- connect(reconnect = false) {
1796
+ connect(reconnect = false, connectionId) {
1650
1797
  return __async(this, null, function* () {
1651
1798
  if (!this.pendingSdpOffer || !this.pendingTrackMapping) {
1652
1799
  throw new Error(
1653
1800
  "[WebRTCTransport] No prepared connection. Call prepare() first."
1654
1801
  );
1655
1802
  }
1656
- const method = reconnect ? "PUT" : "POST";
1657
1803
  const sdpOffer = this.pendingSdpOffer;
1658
1804
  const trackMapping = this.pendingTrackMapping;
1659
1805
  this.pendingSdpOffer = void 0;
1660
1806
  this.pendingTrackMapping = void 0;
1661
- yield this.sendSdpOffer(sdpOffer, trackMapping, method);
1662
- 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);
1663
1824
  this.iceStartTime = performance.now();
1664
1825
  yield setRemoteDescription(
1665
1826
  this.peerConnection,
@@ -1680,13 +1841,28 @@ var WebRTCTransportClient = class {
1680
1841
  this.dataChannel.close();
1681
1842
  this.dataChannel = void 0;
1682
1843
  }
1844
+ if (this.controlChannel) {
1845
+ this.controlChannel.close();
1846
+ this.controlChannel = void 0;
1847
+ }
1683
1848
  if (this.peerConnection) {
1684
1849
  closePeerConnection(this.peerConnection);
1685
1850
  this.peerConnection = void 0;
1686
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;
1687
1862
  this.transceiverMap.clear();
1688
1863
  this.peerConnected = false;
1689
1864
  this.dataChannelOpen = false;
1865
+ this.controlChannelOpen = false;
1690
1866
  this.resetTransportTimings();
1691
1867
  this.setStatus("disconnected");
1692
1868
  console.debug("[WebRTCTransport] Disconnected");
@@ -1749,6 +1925,119 @@ var WebRTCTransportClient = class {
1749
1925
  console.warn("[WebRTCTransport] Failed to send message:", error);
1750
1926
  }
1751
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
+ }
1752
2041
  // ─────────────────────────────────────────────────────────────────────────
1753
2042
  // Track Publishing
1754
2043
  // ─────────────────────────────────────────────────────────────────────────
@@ -1775,6 +2064,7 @@ var WebRTCTransportClient = class {
1775
2064
  `[WebRTCTransport] Cannot publish track "${name}" - transceiver is recvonly`
1776
2065
  );
1777
2066
  }
2067
+ yield this.sendControlRequest("publish_track", { name });
1778
2068
  yield entry.transceiver.sender.replaceTrack(track);
1779
2069
  this.publishedTracks.set(name, track);
1780
2070
  console.debug(`[WebRTCTransport] Track "${name}" published successfully`);
@@ -1786,6 +2076,7 @@ var WebRTCTransportClient = class {
1786
2076
  if (!(entry == null ? void 0 : entry.transceiver) || !this.publishedTracks.has(name)) return;
1787
2077
  try {
1788
2078
  yield entry.transceiver.sender.replaceTrack(null);
2079
+ this.sendControlMessage("unpublish_track", { name });
1789
2080
  console.debug(
1790
2081
  `[WebRTCTransport] Track "${name}" unpublished successfully`
1791
2082
  );
@@ -1871,9 +2162,11 @@ var WebRTCTransportClient = class {
1871
2162
  // Internal Helpers
1872
2163
  // ─────────────────────────────────────────────────────────────────────────
1873
2164
  checkFullyConnected() {
1874
- if (this.peerConnected && this.dataChannelOpen) {
2165
+ if (this.peerConnected && this.dataChannelOpen && this.controlChannelOpen) {
1875
2166
  this.setStatus("connected");
1876
2167
  this.startStatsPolling();
2168
+ this.readyGateResolve();
2169
+ this.readyGateResolve = void 0;
1877
2170
  }
1878
2171
  }
1879
2172
  setStatus(newStatus) {
@@ -1993,6 +2286,46 @@ var WebRTCTransportClient = class {
1993
2286
  }
1994
2287
  };
1995
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
+ }
1996
2329
  };
1997
2330
 
1998
2331
  // src/core/Reactor.ts
@@ -2676,7 +3009,17 @@ var OptionsSchema = import_zod3.z.object({
2676
3009
  var Reactor = class {
2677
3010
  constructor(options) {
2678
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;
2679
3021
  this.tracks = [];
3022
+ this.autoResumeTracks = false;
2680
3023
  this.eventListeners = /* @__PURE__ */ new Map();
2681
3024
  const validatedOptions = OptionsSchema.parse(options);
2682
3025
  this.coordinatorUrl = validatedOptions.apiUrl;
@@ -2913,6 +3256,7 @@ var Reactor = class {
2913
3256
  "gpu",
2914
3257
  true
2915
3258
  );
3259
+ throw error;
2916
3260
  }
2917
3261
  });
2918
3262
  }
@@ -2932,6 +3276,14 @@ var Reactor = class {
2932
3276
  }
2933
3277
  });
2934
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
+ }
2935
3287
  /**
2936
3288
  * Reconnects to an existing session with a fresh transport.
2937
3289
  */
@@ -2981,9 +3333,16 @@ var Reactor = class {
2981
3333
  * be a static string or a {@link JwtSource} resolver; pass a
2982
3334
  * resolver when the token is short-lived so each Coordinator HTTP
2983
3335
  * hop sees a fresh value.
3336
+ *
3337
+ * Pass `options.sessionId` to attach to a session that already exists
3338
+ * (e.g. one created by a backend) instead of creating a new one — session
3339
+ * creation is skipped and the transport is brought up against that id. The
3340
+ * `jwtToken` must be valid for the account that owns the session. Works in
3341
+ * local mode too (it looks the session up by id rather than starting one).
2984
3342
  */
2985
3343
  connect(jwtToken, options) {
2986
3344
  return __async(this, null, function* () {
3345
+ var _a;
2987
3346
  console.debug("[Reactor] Connecting, status:", this.status);
2988
3347
  if (jwtToken == void 0 && !this.local) {
2989
3348
  throw new Error("No authentication provided and not in local mode");
@@ -3002,20 +3361,31 @@ var Reactor = class {
3002
3361
  jwtToken,
3003
3362
  model: this.model
3004
3363
  });
3005
- const tSession = performance.now();
3006
- const initialResponse = yield this.coordinatorClient.createSession();
3007
- const sessionCreationMs = performance.now() - tSession;
3008
- this.setSessionId(initialResponse.session_id);
3009
- console.debug(
3010
- "[Reactor] Session created:",
3011
- initialResponse.session_id,
3012
- "state:",
3013
- initialResponse.state
3014
- );
3364
+ let sessionCreationMs = 0;
3365
+ let sessionId;
3366
+ if (options == null ? void 0 : options.sessionId) {
3367
+ yield this.coordinatorClient.adoptSession(options.sessionId);
3368
+ sessionId = options.sessionId;
3369
+ this.createdSession = false;
3370
+ console.debug("[Reactor] Attaching to existing session:", sessionId);
3371
+ } else {
3372
+ const tSession = performance.now();
3373
+ const initialResponse = yield this.coordinatorClient.createSession();
3374
+ sessionCreationMs = performance.now() - tSession;
3375
+ sessionId = initialResponse.session_id;
3376
+ this.createdSession = true;
3377
+ console.debug(
3378
+ "[Reactor] Session created:",
3379
+ sessionId,
3380
+ "state:",
3381
+ initialResponse.state
3382
+ );
3383
+ }
3384
+ this.setSessionId(sessionId);
3015
3385
  this.setStatus("waiting");
3016
3386
  this.transportClient = new WebRTCTransportClient({
3017
3387
  baseUrl: this.coordinatorUrl,
3018
- sessionId: initialResponse.session_id,
3388
+ sessionId,
3019
3389
  jwtToken: this.local ? "local" : jwtToken,
3020
3390
  webrtcVersion: REACTOR_WEBRTC_VERSION,
3021
3391
  maxPollAttempts: options == null ? void 0 : options.maxAttempts
@@ -3023,19 +3393,22 @@ var Reactor = class {
3023
3393
  this.setupTransportHandlers();
3024
3394
  let sessionPollingMs;
3025
3395
  let transportConnectingMs;
3396
+ this.autoResumeTracks = (_a = options == null ? void 0 : options.autoResumeTracks) != null ? _a : true;
3026
3397
  if (this.presetTracks) {
3398
+ this.tracks = this.presetTracks;
3027
3399
  const tParallel = performance.now();
3028
3400
  const [sessionResponse] = yield Promise.all([
3029
3401
  this.coordinatorClient.pollSessionReady(),
3030
- this.transportClient.prepare(this.presetTracks)
3402
+ this.transportClient.prepare(this.tracks)
3031
3403
  ]);
3032
3404
  sessionPollingMs = performance.now() - tParallel;
3033
3405
  this.sessionResponse = sessionResponse;
3034
- this.capabilities = sessionResponse.capabilities;
3035
- this.tracks = this.presetTracks;
3406
+ this.capabilities = __spreadProps(__spreadValues({}, sessionResponse.capabilities), {
3407
+ tracks: this.tracks
3408
+ });
3036
3409
  this.emit("capabilitiesReceived", this.capabilities);
3037
3410
  const tConnect = performance.now();
3038
- yield this.transportClient.connect();
3411
+ yield this.transportClient.connect(false, options == null ? void 0 : options.connectionId);
3039
3412
  transportConnectingMs = performance.now() - tConnect;
3040
3413
  } else {
3041
3414
  this.transportClient.warmup();
@@ -3043,8 +3416,10 @@ var Reactor = class {
3043
3416
  const sessionResponse = yield this.coordinatorClient.pollSessionReady();
3044
3417
  sessionPollingMs = performance.now() - tPoll;
3045
3418
  this.sessionResponse = sessionResponse;
3046
- this.capabilities = sessionResponse.capabilities;
3047
3419
  this.tracks = sessionResponse.capabilities.tracks;
3420
+ this.capabilities = __spreadProps(__spreadValues({}, sessionResponse.capabilities), {
3421
+ tracks: this.tracks
3422
+ });
3048
3423
  this.emit("capabilitiesReceived", this.capabilities);
3049
3424
  const protocol = sessionResponse.selected_transport.protocol;
3050
3425
  if (protocol !== "webrtc") {
@@ -3052,7 +3427,7 @@ var Reactor = class {
3052
3427
  }
3053
3428
  const tTransport = performance.now();
3054
3429
  yield this.transportClient.prepare(this.tracks);
3055
- yield this.transportClient.connect();
3430
+ yield this.transportClient.connect(false, options == null ? void 0 : options.connectionId);
3056
3431
  transportConnectingMs = performance.now() - tTransport;
3057
3432
  }
3058
3433
  console.debug("[Reactor] Session ready, tracks:", this.tracks.length);
@@ -3102,6 +3477,13 @@ var Reactor = class {
3102
3477
  switch (status) {
3103
3478
  case "connected":
3104
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
+ }
3105
3487
  this.setStatus("ready");
3106
3488
  break;
3107
3489
  case "disconnected":
@@ -3123,6 +3505,13 @@ var Reactor = class {
3123
3505
  (name, track, stream) => {
3124
3506
  if (this.transportClient !== client) return;
3125
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
+ }
3126
3515
  }
3127
3516
  );
3128
3517
  client.on("statsUpdate", (stats) => {
@@ -3145,10 +3534,16 @@ var Reactor = class {
3145
3534
  (_a = this.coordinatorClient) == null ? void 0 : _a.abort();
3146
3535
  (_b = this.transportClient) == null ? void 0 : _b.abort();
3147
3536
  if (this.coordinatorClient && !recoverable) {
3148
- try {
3149
- yield this.coordinatorClient.terminateSession();
3150
- } catch (error) {
3151
- 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
+ );
3152
3547
  }
3153
3548
  this.coordinatorClient = void 0;
3154
3549
  }
@@ -3170,6 +3565,7 @@ var Reactor = class {
3170
3565
  this.capabilities = void 0;
3171
3566
  this.tracks = [];
3172
3567
  this.sessionResponse = void 0;
3568
+ this.createdSession = false;
3173
3569
  }
3174
3570
  });
3175
3571
  }
@@ -3273,7 +3669,8 @@ var defaultInitState = {
3273
3669
  lastError: void 0,
3274
3670
  sessionExpiration: void 0,
3275
3671
  jwtToken: void 0,
3276
- sessionId: void 0
3672
+ sessionId: void 0,
3673
+ connectOptions: void 0
3277
3674
  };
3278
3675
  var initReactorStore = (props) => {
3279
3676
  return __spreadValues(__spreadValues({}, defaultInitState), props);
@@ -3329,6 +3726,7 @@ var createReactorStore = (initProps, publicState = defaultInitState) => {
3329
3726
  });
3330
3727
  return __spreadProps(__spreadValues({}, publicState), {
3331
3728
  jwtToken: initProps.jwtToken,
3729
+ connectOptions: initProps.connectOptions,
3332
3730
  internal: { reactor },
3333
3731
  // actions
3334
3732
  onMessage: (handler) => {
@@ -3357,9 +3755,10 @@ var createReactorStore = (initProps, publicState = defaultInitState) => {
3357
3755
  if (jwtToken === void 0) {
3358
3756
  jwtToken = get().jwtToken;
3359
3757
  }
3758
+ const resolvedOptions = __spreadValues(__spreadValues({}, get().connectOptions), options);
3360
3759
  console.debug("[ReactorStore] Connect called.");
3361
3760
  try {
3362
- yield get().internal.reactor.connect(jwtToken, options);
3761
+ yield get().internal.reactor.connect(jwtToken, resolvedOptions);
3363
3762
  console.debug("[ReactorStore] Connect completed successfully");
3364
3763
  } catch (error) {
3365
3764
  console.error("[ReactorStore] Connect failed:", error);
@@ -3467,30 +3866,31 @@ function ReactorProvider(_a) {
3467
3866
  const storeRef = (0, import_react3.useRef)(void 0);
3468
3867
  const firstRender = (0, import_react3.useRef)(true);
3469
3868
  const [_storeVersion, setStoreVersion] = (0, import_react3.useState)(0);
3869
+ const _a2 = connectOptions != null ? connectOptions : {}, { autoConnect = false } = _a2, pollingOptions = __objRest(_a2, ["autoConnect"]);
3470
3870
  if (storeRef.current === void 0) {
3471
3871
  console.debug("[ReactorProvider] Creating new reactor store");
3472
3872
  storeRef.current = createReactorStore(
3473
3873
  initReactorStore(__spreadProps(__spreadValues({}, props), {
3474
- jwtToken: jwtSource
3874
+ jwtToken: jwtSource,
3875
+ connectOptions: pollingOptions
3475
3876
  }))
3476
3877
  );
3477
3878
  console.debug("[ReactorProvider] Reactor store created successfully");
3478
3879
  }
3479
- const _a2 = connectOptions != null ? connectOptions : {}, { autoConnect = false } = _a2, pollingOptions = __objRest(_a2, ["autoConnect"]);
3480
3880
  const { apiUrl, modelName, local } = props;
3481
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]);
3482
3887
  (0, import_react3.useEffect)(() => {
3483
3888
  const handleBeforeUnload = () => {
3484
3889
  var _a3;
3485
- console.debug(
3486
- "[ReactorProvider] Page unloading, performing non-recoverable disconnect"
3487
- );
3488
3890
  (_a3 = storeRef.current) == null ? void 0 : _a3.getState().internal.reactor.disconnect(false);
3489
3891
  };
3490
3892
  window.addEventListener("beforeunload", handleBeforeUnload);
3491
- return () => {
3492
- window.removeEventListener("beforeunload", handleBeforeUnload);
3493
- };
3893
+ return () => window.removeEventListener("beforeunload", handleBeforeUnload);
3494
3894
  }, []);
3495
3895
  (0, import_react3.useEffect)(() => {
3496
3896
  if (firstRender.current) {
@@ -3533,7 +3933,8 @@ function ReactorProvider(_a) {
3533
3933
  apiUrl,
3534
3934
  modelName,
3535
3935
  local,
3536
- jwtToken: jwtSource
3936
+ jwtToken: jwtSource,
3937
+ connectOptions: pollingOptions
3537
3938
  })
3538
3939
  );
3539
3940
  const current = storeRef.current;
@@ -3659,26 +4060,39 @@ function ReactorView({
3659
4060
  hasVideoTrack: !!videoMediaTrack,
3660
4061
  hasAudioTrack: !!audioMediaTrack
3661
4062
  });
3662
- if (videoRef.current && mediaStream) {
3663
- 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) => {
3664
4069
  try {
3665
- videoRef.current.srcObject = mediaStream;
3666
- videoRef.current.play().catch((e) => {
4070
+ if (reset) el.srcObject = null;
4071
+ el.srcObject = mediaStream;
4072
+ el.play().catch((e) => {
3667
4073
  console.warn("[ReactorView] Auto-play failed:", e);
3668
4074
  });
3669
- console.debug("[ReactorView] Media stream attached successfully");
3670
4075
  } catch (error) {
3671
4076
  console.error("[ReactorView] Failed to attach media stream:", error);
3672
4077
  }
3673
- return () => {
3674
- console.debug("[ReactorView] Detaching media stream from element");
3675
- if (videoRef.current) {
3676
- videoRef.current.srcObject = null;
3677
- }
3678
- };
3679
- } else {
3680
- console.debug("[ReactorView] No tracks or element to attach");
3681
- }
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
+ };
3682
4096
  }, [mediaStream]);
3683
4097
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
3684
4098
  "div",