@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.mjs CHANGED
@@ -91,7 +91,7 @@ import { z } from "zod";
91
91
  // package.json
92
92
  var package_default = {
93
93
  name: "@reactor-team/js-sdk",
94
- version: "2.11.1",
94
+ version: "2.12.0",
95
95
  description: "Reactor JavaScript frontend SDK \u2014 connect React and TypeScript apps to real-time AI video models on Reactor.",
96
96
  license: "Apache-2.0",
97
97
  repository: {
@@ -147,6 +147,7 @@ var package_default = {
147
147
  },
148
148
  packageManager: "pnpm@10.12.1",
149
149
  dependencies: {
150
+ awaitqueue: "^3.3.0",
150
151
  mp4box: "^2.3.0",
151
152
  "sdp-transform": "^3.0.0",
152
153
  zod: "^4.4.3"
@@ -165,6 +166,7 @@ var package_default = {
165
166
  "@roamhq/wrtc": "^0.8.0",
166
167
  "@types/node": "^25",
167
168
  "@types/react": "^19.2.15",
169
+ "@types/sdp-transform": "^2.15.0",
168
170
  "hls.js": "^1.6.0",
169
171
  prettier: "^3.6.2",
170
172
  tsup: "^8.5.0",
@@ -260,8 +262,12 @@ var WebRTCSdpOfferRequestSchema = z.object({
260
262
  client_info: ClientInfoSchema.optional(),
261
263
  track_mapping: z.array(TrackMappingEntrySchema)
262
264
  });
265
+ var WebRTCSdpOfferResponseSchema = z.object({
266
+ connection_id: z.number().optional()
267
+ });
263
268
  var WebRTCSdpAnswerResponseSchema = z.object({
264
- sdp_answer: z.string()
269
+ sdp_answer: z.string(),
270
+ connection_id: z.number().optional()
265
271
  });
266
272
  var IceCandidateSchema = z.object({
267
273
  candidate: z.string(),
@@ -403,6 +409,18 @@ var CoordinatorClient = class {
403
409
  return parsed;
404
410
  });
405
411
  }
412
+ /**
413
+ * Attaches to a session created elsewhere (e.g. by a backend) instead of
414
+ * creating one via {@link createSession}. After this, {@link pollSessionReady}
415
+ * and {@link getSession} operate on the adopted id. The session must be owned
416
+ * by the account behind this client's JWT.
417
+ */
418
+ adoptSession(sessionId) {
419
+ return __async(this, null, function* () {
420
+ this.currentSessionId = sessionId;
421
+ console.debug("[CoordinatorClient] Adopted existing session:", sessionId);
422
+ });
423
+ }
406
424
  /**
407
425
  * Polls GET /sessions/{id} until the Runtime has accepted the session
408
426
  * and populated capabilities and selected_transport.
@@ -694,6 +712,48 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
694
712
  return CreateSessionResponseSchema.parse(data);
695
713
  });
696
714
  }
715
+ /**
716
+ * Adopts the local session for `connect({ sessionId })`: records the id and
717
+ * reads the session descriptor, caching it so {@link pollSessionReady}
718
+ * returns immediately. No `start_session` is issued.
719
+ *
720
+ * The local runtime hosts a single session (always id `"local"`), so the
721
+ * lookup ignores the specific id. This is a pure read of session info — it
722
+ * does not start or otherwise advance the session.
723
+ */
724
+ adoptSession(sessionId) {
725
+ return __async(this, null, function* () {
726
+ this.currentSessionId = sessionId;
727
+ this.cachedSessionResponse = yield this.getSession();
728
+ console.debug(
729
+ "[LocalCoordinatorClient] Adopted existing session:",
730
+ sessionId
731
+ );
732
+ });
733
+ }
734
+ /**
735
+ * Reads the local session descriptor (model, capabilities, transport,
736
+ * state) via the runtime's read-only `GET /session`.
737
+ *
738
+ * The local runtime exposes a single session, so — unlike the Coordinator's
739
+ * id-addressed `GET /sessions/{id}` — there is no id in the path. Read-only:
740
+ * it does not start or advance the session.
741
+ */
742
+ getSession() {
743
+ return __async(this, null, function* () {
744
+ const response = yield fetch(`${this.baseUrl}/session`, {
745
+ method: "GET",
746
+ headers: yield this.getHeaders(),
747
+ signal: this.signal
748
+ });
749
+ if (!response.ok) {
750
+ const errorText = yield response.text();
751
+ throw new Error(`Failed to get session: ${response.status} ${errorText}`);
752
+ }
753
+ const data = yield response.json();
754
+ return SessionResponseSchema.parse(data);
755
+ });
756
+ }
697
757
  /**
698
758
  * Returns the cached full session response immediately.
699
759
  * The local runtime already provided everything in start_session.
@@ -735,6 +795,9 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
735
795
  }
736
796
  };
737
797
 
798
+ // src/core/WebRTCTransportClient.ts
799
+ import { AwaitQueue } from "awaitqueue";
800
+
738
801
  // src/utils/sdp.ts
739
802
  import { parse, parsePayloads } from "sdp-transform";
740
803
  function sdpLineSeparator(sdp) {
@@ -785,13 +848,6 @@ function collectSanitizedCodecPayloadSet(media) {
785
848
  }
786
849
  return tracked.size > 0 ? tracked : null;
787
850
  }
788
- function mediaSectionNeedsSanitizedPtRelocate(media) {
789
- const pts = collectSanitizedCodecPayloadSet(media);
790
- if (!pts) {
791
- return false;
792
- }
793
- return [...pts].some((p) => p < DYNAMIC_PT_MIN || p > DYNAMIC_PT_MAX);
794
- }
795
851
  function codecRelocationPriority(enc) {
796
852
  const u = (enc != null ? enc : "").toUpperCase();
797
853
  if (/^(H265|HEVC|HEV1|HVC1)/.test(u)) return 0;
@@ -825,7 +881,7 @@ function computeCodecRemapForMedia(media, forbidden) {
825
881
  return remap;
826
882
  }
827
883
  const relocate = [...tracked].filter(
828
- (p) => p < DYNAMIC_PT_MIN || p > DYNAMIC_PT_MAX
884
+ (p) => p < DYNAMIC_PT_MIN || p > DYNAMIC_PT_MAX || forbidden.has(p)
829
885
  );
830
886
  if (relocate.length === 0) {
831
887
  return remap;
@@ -1062,7 +1118,7 @@ function stripTelephoneEventsPreserveOrder(sdp) {
1062
1118
  function transformOfferSdpCodecDynamicPts(sdp) {
1063
1119
  var _a;
1064
1120
  const session = parse(sdp);
1065
- if (!session.media.some(mediaSectionNeedsSanitizedPtRelocate)) {
1121
+ if (!session.media.some((m) => collectSanitizedCodecPayloadSet(m) !== null)) {
1066
1122
  return sdp;
1067
1123
  }
1068
1124
  const remaps = [];
@@ -1184,6 +1240,26 @@ function parseMessage(data) {
1184
1240
  }
1185
1241
  return data;
1186
1242
  }
1243
+ function complementDirection(direction) {
1244
+ if (direction === "sendonly") return "recvonly";
1245
+ if (direction === "recvonly") return "sendonly";
1246
+ return direction;
1247
+ }
1248
+ function replaceSdpDirectionForMid(sdp, mid, direction) {
1249
+ const [session, ...mediaSections] = sdp.split(/(?=\r\nm=)/);
1250
+ const updated = mediaSections.map((section) => {
1251
+ if (!section.includes(`\r
1252
+ a=mid:${mid}\r
1253
+ `)) return section;
1254
+ return section.replace(
1255
+ /\r\na=(sendonly|recvonly|sendrecv|inactive)\r\n/,
1256
+ `\r
1257
+ a=${direction}\r
1258
+ `
1259
+ );
1260
+ });
1261
+ return session + updated.join("");
1262
+ }
1187
1263
  function closePeerConnection(pc) {
1188
1264
  pc.close();
1189
1265
  }
@@ -1269,6 +1345,8 @@ var INITIAL_BACKOFF_MS = 200;
1269
1345
  var MAX_BACKOFF_MS = 15e3;
1270
1346
  var BACKOFF_MULTIPLIER = 2;
1271
1347
  var DEFAULT_MAX_POLL_ATTEMPTS = 6;
1348
+ var MIN_CONNECTION_ID = 1e3;
1349
+ var MAX_CONNECTION_ID = 9999;
1272
1350
  var ICE_CANDIDATE_BATCH_WINDOW_MS = 25;
1273
1351
  var WebRTCTransportClient = class {
1274
1352
  constructor(config) {
@@ -1276,8 +1354,14 @@ var WebRTCTransportClient = class {
1276
1354
  this.status = "disconnected";
1277
1355
  this.transceiverMap = /* @__PURE__ */ new Map();
1278
1356
  this.publishedTracks = /* @__PURE__ */ new Map();
1357
+ // Serializes all SDP renegotiations (pause/resume direction changes) and gates
1358
+ // them behind the connection-ready task. Reset on each prepare() call.
1359
+ this.peerConnectionQueue = new AwaitQueue();
1360
+ this.pendingControlRequests = /* @__PURE__ */ new Map();
1361
+ this.controlRequestCounter = 0;
1279
1362
  this.peerConnected = false;
1280
1363
  this.dataChannelOpen = false;
1364
+ this.controlChannelOpen = false;
1281
1365
  // Trickle ICE batching
1282
1366
  this.pendingIceCandidates = [];
1283
1367
  var _a, _b;
@@ -1382,11 +1466,34 @@ var WebRTCTransportClient = class {
1382
1466
  return iceServers;
1383
1467
  });
1384
1468
  }
1385
- sendSdpOffer(sdpOffer, trackMapping, method = "POST") {
1469
+ registerConnection() {
1470
+ return __async(this, null, function* () {
1471
+ console.debug("[WebRTCTransport] Registering connection...");
1472
+ const response = yield fetch(`${this.transportBaseUrl}/connections`, {
1473
+ method: "POST",
1474
+ headers: yield this.getHeaders(),
1475
+ signal: this.signal
1476
+ });
1477
+ yield this.checkVersionMismatch(response);
1478
+ if (response.status !== 201) {
1479
+ const errorText = yield response.text();
1480
+ throw new Error(
1481
+ `Failed to register connection: ${response.status} ${errorText}`
1482
+ );
1483
+ }
1484
+ const data = yield response.json();
1485
+ const connectionId = data.connection_id;
1486
+ console.debug(
1487
+ `[WebRTCTransport] Connection registered: id=${connectionId}`
1488
+ );
1489
+ return connectionId;
1490
+ });
1491
+ }
1492
+ sendSdpOffer(connectionId, sdpOffer, trackMapping, reconnect = false) {
1386
1493
  return __async(this, null, function* () {
1494
+ const method = reconnect ? "PUT" : "POST";
1387
1495
  console.debug(
1388
- `[WebRTCTransport] Sending SDP offer (${method}) for session:`,
1389
- this.sessionId
1496
+ `[WebRTCTransport] Sending SDP offer (${method}) connection=${connectionId}`
1390
1497
  );
1391
1498
  const requestBody = {
1392
1499
  sdp_offer: sdpOffer,
@@ -1396,17 +1503,30 @@ var WebRTCTransportClient = class {
1396
1503
  },
1397
1504
  track_mapping: trackMapping
1398
1505
  };
1399
- const response = yield fetch(`${this.transportBaseUrl}/sdp_params`, {
1400
- method,
1401
- headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
1402
- "Content-Type": "application/json"
1403
- }),
1404
- body: JSON.stringify(requestBody),
1405
- signal: this.signal
1406
- });
1506
+ const response = yield fetch(
1507
+ `${this.transportBaseUrl}/connections/${connectionId}/sdp_params`,
1508
+ {
1509
+ method,
1510
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
1511
+ "Content-Type": "application/json"
1512
+ }),
1513
+ body: JSON.stringify(requestBody),
1514
+ signal: this.signal
1515
+ }
1516
+ );
1407
1517
  yield this.checkVersionMismatch(response);
1408
1518
  if (response.status !== 202) {
1409
1519
  const errorText = yield response.text();
1520
+ if (response.status === 404) {
1521
+ throw new Error(
1522
+ `[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}`
1523
+ );
1524
+ }
1525
+ if (response.status === 400) {
1526
+ throw new Error(
1527
+ `[WebRTCTransport] Connection ${connectionId} rejected (400): ${errorText}`
1528
+ );
1529
+ }
1410
1530
  throw new Error(
1411
1531
  `Failed to send SDP offer: ${response.status} ${errorText}`
1412
1532
  );
@@ -1416,6 +1536,12 @@ var WebRTCTransportClient = class {
1416
1536
  }
1417
1537
  sendIceCandidates(candidates, is_final) {
1418
1538
  return __async(this, null, function* () {
1539
+ if (this.connectionId === void 0) {
1540
+ console.debug(
1541
+ "[WebRTCTransport] ICE candidates dropped: no active connection"
1542
+ );
1543
+ return;
1544
+ }
1419
1545
  console.debug(
1420
1546
  `[WebRTCTransport] Sending ICE candidates (count=${candidates.length}, is_final=${is_final})`
1421
1547
  );
@@ -1427,14 +1553,17 @@ var WebRTCTransportClient = class {
1427
1553
  sdk_type: REACTOR_SDK_TYPE
1428
1554
  }
1429
1555
  };
1430
- const response = yield fetch(`${this.transportBaseUrl}/ice_candidates`, {
1431
- method: "POST",
1432
- headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
1433
- "Content-Type": "application/json"
1434
- }),
1435
- body: JSON.stringify(requestBody),
1436
- signal: this.signal
1437
- });
1556
+ const response = yield fetch(
1557
+ `${this.transportBaseUrl}/connections/${this.connectionId}/ice_candidates`,
1558
+ {
1559
+ method: "POST",
1560
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
1561
+ "Content-Type": "application/json"
1562
+ }),
1563
+ body: JSON.stringify(requestBody),
1564
+ signal: this.signal
1565
+ }
1566
+ );
1438
1567
  yield this.checkVersionMismatch(response);
1439
1568
  if (response.status !== 202) {
1440
1569
  const errorText = yield response.text();
@@ -1443,7 +1572,6 @@ var WebRTCTransportClient = class {
1443
1572
  );
1444
1573
  }
1445
1574
  console.debug("[WebRTCTransport] ICE candidates accepted (202)");
1446
- return;
1447
1575
  });
1448
1576
  }
1449
1577
  /**
@@ -1478,9 +1606,10 @@ var WebRTCTransportClient = class {
1478
1606
  }
1479
1607
  this.pendingIceCandidates = [];
1480
1608
  }
1481
- pollSdpAnswer() {
1609
+ pollSdpAnswer(connectionId) {
1482
1610
  return __async(this, null, function* () {
1483
1611
  console.debug("[WebRTCTransport] Polling for SDP answer...");
1612
+ const pollUrl = `${this.transportBaseUrl}/connections/${connectionId}/sdp_params`;
1484
1613
  const pollStart = performance.now();
1485
1614
  let backoffMs = INITIAL_BACKOFF_MS;
1486
1615
  let attempt = 0;
@@ -1497,7 +1626,7 @@ var WebRTCTransportClient = class {
1497
1626
  console.debug(
1498
1627
  `[WebRTCTransport] SDP poll attempt ${attempt}/${this.maxPollAttempts}`
1499
1628
  );
1500
- const response = yield fetch(`${this.transportBaseUrl}/sdp_params`, {
1629
+ const response = yield fetch(pollUrl, {
1501
1630
  method: "GET",
1502
1631
  headers: yield this.getHeaders(),
1503
1632
  signal: this.signal
@@ -1552,16 +1681,34 @@ var WebRTCTransportClient = class {
1552
1681
  this.dataChannel.close();
1553
1682
  this.dataChannel = void 0;
1554
1683
  }
1684
+ if (this.controlChannel) {
1685
+ this.controlChannel.close();
1686
+ this.controlChannel = void 0;
1687
+ }
1555
1688
  if (this.peerConnection) {
1556
1689
  closePeerConnection(this.peerConnection);
1557
1690
  this.peerConnection = void 0;
1558
1691
  }
1559
1692
  this.peerConnected = false;
1560
1693
  this.dataChannelOpen = false;
1694
+ this.controlChannelOpen = false;
1695
+ this.peerConnectionQueue.stop();
1696
+ this.peerConnectionQueue = new AwaitQueue();
1697
+ this.peerConnectionQueue.push(
1698
+ () => new Promise((resolve) => {
1699
+ this.readyGateResolve = resolve;
1700
+ })
1701
+ ).catch(() => {
1702
+ });
1561
1703
  const iceServers = this.cachedIceServers ? yield this.cachedIceServers : yield this.fetchIceServers();
1562
1704
  this.cachedIceServers = void 0;
1563
1705
  this.peerConnection = createPeerConnection({ iceServers });
1564
1706
  this.setupPeerConnectionHandlers();
1707
+ this.controlChannel = createDataChannel(
1708
+ this.peerConnection,
1709
+ "control"
1710
+ );
1711
+ this.setupControlChannelHandlers();
1565
1712
  this.dataChannel = createDataChannel(this.peerConnection);
1566
1713
  this.setupDataChannelHandlers();
1567
1714
  this.transceiverMap.clear();
@@ -1584,20 +1731,34 @@ var WebRTCTransportClient = class {
1584
1731
  console.debug("[WebRTCTransport] SDP offer prepared");
1585
1732
  });
1586
1733
  }
1587
- connect(reconnect = false) {
1734
+ connect(reconnect = false, connectionId) {
1588
1735
  return __async(this, null, function* () {
1589
1736
  if (!this.pendingSdpOffer || !this.pendingTrackMapping) {
1590
1737
  throw new Error(
1591
1738
  "[WebRTCTransport] No prepared connection. Call prepare() first."
1592
1739
  );
1593
1740
  }
1594
- const method = reconnect ? "PUT" : "POST";
1595
1741
  const sdpOffer = this.pendingSdpOffer;
1596
1742
  const trackMapping = this.pendingTrackMapping;
1597
1743
  this.pendingSdpOffer = void 0;
1598
1744
  this.pendingTrackMapping = void 0;
1599
- yield this.sendSdpOffer(sdpOffer, trackMapping, method);
1600
- const answerResponse = yield this.pollSdpAnswer();
1745
+ if (connectionId !== void 0) {
1746
+ if (!Number.isInteger(connectionId) || connectionId <= MIN_CONNECTION_ID || connectionId > MAX_CONNECTION_ID) {
1747
+ throw new Error(
1748
+ `[WebRTCTransport] Invalid connectionId ${connectionId}: must be an integer in (${MIN_CONNECTION_ID}, ${MAX_CONNECTION_ID}]`
1749
+ );
1750
+ }
1751
+ this.connectionId = connectionId;
1752
+ } else if (!reconnect || this.connectionId === void 0) {
1753
+ this.connectionId = yield this.registerConnection();
1754
+ }
1755
+ yield this.sendSdpOffer(
1756
+ this.connectionId,
1757
+ sdpOffer,
1758
+ trackMapping,
1759
+ reconnect
1760
+ );
1761
+ const answerResponse = yield this.pollSdpAnswer(this.connectionId);
1601
1762
  this.iceStartTime = performance.now();
1602
1763
  yield setRemoteDescription(
1603
1764
  this.peerConnection,
@@ -1618,13 +1779,28 @@ var WebRTCTransportClient = class {
1618
1779
  this.dataChannel.close();
1619
1780
  this.dataChannel = void 0;
1620
1781
  }
1782
+ if (this.controlChannel) {
1783
+ this.controlChannel.close();
1784
+ this.controlChannel = void 0;
1785
+ }
1621
1786
  if (this.peerConnection) {
1622
1787
  closePeerConnection(this.peerConnection);
1623
1788
  this.peerConnection = void 0;
1624
1789
  }
1790
+ for (const [, pending] of this.pendingControlRequests) {
1791
+ clearTimeout(pending.timeout);
1792
+ pending.reject(
1793
+ new Error("[WebRTCTransport] Disconnected while waiting for response")
1794
+ );
1795
+ }
1796
+ this.pendingControlRequests.clear();
1797
+ this.readyGateResolve = void 0;
1798
+ this.peerConnectionQueue.stop();
1799
+ this.connectionId = void 0;
1625
1800
  this.transceiverMap.clear();
1626
1801
  this.peerConnected = false;
1627
1802
  this.dataChannelOpen = false;
1803
+ this.controlChannelOpen = false;
1628
1804
  this.resetTransportTimings();
1629
1805
  this.setStatus("disconnected");
1630
1806
  console.debug("[WebRTCTransport] Disconnected");
@@ -1687,6 +1863,119 @@ var WebRTCTransportClient = class {
1687
1863
  console.warn("[WebRTCTransport] Failed to send message:", error);
1688
1864
  }
1689
1865
  }
1866
+ sendControlMessage(command, data, reqId) {
1867
+ if (!this.controlChannel) {
1868
+ console.warn("[WebRTCTransport] Control channel not available");
1869
+ return;
1870
+ }
1871
+ try {
1872
+ if (this.controlChannel.readyState !== "open") {
1873
+ throw new Error(
1874
+ `Control channel not open: ${this.controlChannel.readyState}`
1875
+ );
1876
+ }
1877
+ this.controlChannel.send(
1878
+ JSON.stringify({ type: "notification", event: command, data })
1879
+ );
1880
+ } catch (error) {
1881
+ console.warn("[WebRTCTransport] Failed to send control message:", error);
1882
+ }
1883
+ }
1884
+ sendControlRequest(method, data, timeoutMs = 1e4) {
1885
+ return new Promise((resolve, reject) => {
1886
+ const requestId = `ctrl_${++this.controlRequestCounter}`;
1887
+ const timeout = setTimeout(() => {
1888
+ this.pendingControlRequests.delete(requestId);
1889
+ reject(new Error(`[WebRTCTransport] Request "${method}" timed out`));
1890
+ }, timeoutMs);
1891
+ this.pendingControlRequests.set(requestId, { resolve, reject, timeout });
1892
+ try {
1893
+ if (!this.controlChannel || this.controlChannel.readyState !== "open") {
1894
+ throw new Error("Control channel not available");
1895
+ }
1896
+ this.controlChannel.send(
1897
+ JSON.stringify({
1898
+ type: "request",
1899
+ method,
1900
+ request_id: requestId,
1901
+ data
1902
+ })
1903
+ );
1904
+ } catch (error) {
1905
+ clearTimeout(timeout);
1906
+ this.pendingControlRequests.delete(requestId);
1907
+ reject(error);
1908
+ }
1909
+ });
1910
+ }
1911
+ pauseTrack(name) {
1912
+ this.peerConnectionQueue.push(() => __async(this, null, function* () {
1913
+ var _a;
1914
+ const entry = this.transceiverMap.get(name);
1915
+ if ((_a = entry == null ? void 0 : entry.transceiver) == null ? void 0 : _a.mid) {
1916
+ entry.transceiver.direction = "inactive";
1917
+ yield this.applyDirectionLocally(entry.transceiver.mid, "inactive");
1918
+ }
1919
+ this.sendControlMessage("pause_track", { name });
1920
+ })).catch((e) => {
1921
+ console.warn("[WebRTCTransport] Failed to pause track:", e);
1922
+ });
1923
+ }
1924
+ resumeTrack(name) {
1925
+ this.peerConnectionQueue.push(() => __async(this, null, function* () {
1926
+ var _a;
1927
+ const entry = this.transceiverMap.get(name);
1928
+ if ((_a = entry == null ? void 0 : entry.transceiver) == null ? void 0 : _a.mid) {
1929
+ entry.transceiver.direction = entry.direction;
1930
+ yield this.applyDirectionLocally(
1931
+ entry.transceiver.mid,
1932
+ entry.direction
1933
+ );
1934
+ }
1935
+ this.sendControlMessage("resume_track", { name });
1936
+ })).catch((e) => {
1937
+ console.warn("[WebRTCTransport] Failed to resume track:", e);
1938
+ });
1939
+ }
1940
+ applyDirectionLocally(mid, localDirection) {
1941
+ return __async(this, null, function* () {
1942
+ var _a, _b;
1943
+ const pc = this.peerConnection;
1944
+ if (!pc) return;
1945
+ const tx = pc.getTransceivers().find((t) => t.mid === mid);
1946
+ if (tx && tx.currentDirection === localDirection) return;
1947
+ if (pc.signalingState !== "stable") return;
1948
+ const localSdp = (_a = pc.localDescription) == null ? void 0 : _a.sdp;
1949
+ const remoteSdp = (_b = pc.remoteDescription) == null ? void 0 : _b.sdp;
1950
+ if (!localSdp || !remoteSdp) return;
1951
+ const modifiedLocal = replaceSdpDirectionForMid(
1952
+ localSdp,
1953
+ mid,
1954
+ localDirection
1955
+ );
1956
+ const modifiedRemote = replaceSdpDirectionForMid(
1957
+ remoteSdp,
1958
+ mid,
1959
+ complementDirection(localDirection)
1960
+ );
1961
+ try {
1962
+ yield pc.setLocalDescription(
1963
+ new RTCSessionDescription({ type: "offer", sdp: modifiedLocal })
1964
+ );
1965
+ yield pc.setRemoteDescription(
1966
+ new RTCSessionDescription({ type: "answer", sdp: modifiedRemote })
1967
+ );
1968
+ } catch (e) {
1969
+ if (pc.signalingState === "have-local-offer") {
1970
+ try {
1971
+ yield pc.setLocalDescription({ type: "rollback" });
1972
+ } catch (e2) {
1973
+ }
1974
+ }
1975
+ throw e;
1976
+ }
1977
+ });
1978
+ }
1690
1979
  // ─────────────────────────────────────────────────────────────────────────
1691
1980
  // Track Publishing
1692
1981
  // ─────────────────────────────────────────────────────────────────────────
@@ -1713,6 +2002,7 @@ var WebRTCTransportClient = class {
1713
2002
  `[WebRTCTransport] Cannot publish track "${name}" - transceiver is recvonly`
1714
2003
  );
1715
2004
  }
2005
+ yield this.sendControlRequest("publish_track", { name });
1716
2006
  yield entry.transceiver.sender.replaceTrack(track);
1717
2007
  this.publishedTracks.set(name, track);
1718
2008
  console.debug(`[WebRTCTransport] Track "${name}" published successfully`);
@@ -1724,6 +2014,7 @@ var WebRTCTransportClient = class {
1724
2014
  if (!(entry == null ? void 0 : entry.transceiver) || !this.publishedTracks.has(name)) return;
1725
2015
  try {
1726
2016
  yield entry.transceiver.sender.replaceTrack(null);
2017
+ this.sendControlMessage("unpublish_track", { name });
1727
2018
  console.debug(
1728
2019
  `[WebRTCTransport] Track "${name}" unpublished successfully`
1729
2020
  );
@@ -1809,9 +2100,11 @@ var WebRTCTransportClient = class {
1809
2100
  // Internal Helpers
1810
2101
  // ─────────────────────────────────────────────────────────────────────────
1811
2102
  checkFullyConnected() {
1812
- if (this.peerConnected && this.dataChannelOpen) {
2103
+ if (this.peerConnected && this.dataChannelOpen && this.controlChannelOpen) {
1813
2104
  this.setStatus("connected");
1814
2105
  this.startStatsPolling();
2106
+ this.readyGateResolve();
2107
+ this.readyGateResolve = void 0;
1815
2108
  }
1816
2109
  }
1817
2110
  setStatus(newStatus) {
@@ -1931,6 +2224,46 @@ var WebRTCTransportClient = class {
1931
2224
  }
1932
2225
  };
1933
2226
  }
2227
+ setupControlChannelHandlers() {
2228
+ if (!this.controlChannel) return;
2229
+ this.controlChannel.onopen = () => {
2230
+ console.debug("[WebRTCTransport] Control channel open");
2231
+ this.controlChannelOpen = true;
2232
+ this.checkFullyConnected();
2233
+ };
2234
+ this.controlChannel.onclose = () => {
2235
+ console.debug("[WebRTCTransport] Control channel closed");
2236
+ this.controlChannelOpen = false;
2237
+ };
2238
+ this.controlChannel.onerror = (error) => {
2239
+ console.error("[WebRTCTransport] Control channel error:", error);
2240
+ };
2241
+ this.controlChannel.onmessage = (event) => {
2242
+ var _a, _b;
2243
+ const raw = parseMessage(event.data);
2244
+ if ((raw == null ? void 0 : raw.type) === "response") {
2245
+ const requestId = raw == null ? void 0 : raw.request_id;
2246
+ if (requestId) {
2247
+ const pending = this.pendingControlRequests.get(requestId);
2248
+ if (pending) {
2249
+ clearTimeout(pending.timeout);
2250
+ this.pendingControlRequests.delete(requestId);
2251
+ if (raw == null ? void 0 : raw.error) {
2252
+ pending.reject(
2253
+ new Error(
2254
+ `[WebRTCTransport] ${(_a = raw.method) != null ? _a : "request"} failed: ${(_b = raw.error.message) != null ? _b : "unknown error"}`
2255
+ )
2256
+ );
2257
+ } else {
2258
+ pending.resolve();
2259
+ }
2260
+ }
2261
+ }
2262
+ return;
2263
+ }
2264
+ console.debug("[WebRTCTransport] Received control message:", raw);
2265
+ };
2266
+ }
1934
2267
  };
1935
2268
 
1936
2269
  // src/core/Reactor.ts
@@ -2614,7 +2947,17 @@ var OptionsSchema = z3.object({
2614
2947
  var Reactor = class {
2615
2948
  constructor(options) {
2616
2949
  this.status = "disconnected";
2950
+ /**
2951
+ * True only when the active session was created by THIS connect flow
2952
+ * (via `createSession()`). False when the session was adopted via
2953
+ * `connect({ sessionId })`. We must never DELETE a session we did not
2954
+ * create — another client (or the backend that created it) owns its
2955
+ * lifecycle, so on disconnect/teardown/error an adopting client tears
2956
+ * down its own transport but leaves the session alive.
2957
+ */
2958
+ this.createdSession = false;
2617
2959
  this.tracks = [];
2960
+ this.autoResumeTracks = false;
2618
2961
  this.eventListeners = /* @__PURE__ */ new Map();
2619
2962
  const validatedOptions = OptionsSchema.parse(options);
2620
2963
  this.coordinatorUrl = validatedOptions.apiUrl;
@@ -2851,6 +3194,7 @@ var Reactor = class {
2851
3194
  "gpu",
2852
3195
  true
2853
3196
  );
3197
+ throw error;
2854
3198
  }
2855
3199
  });
2856
3200
  }
@@ -2870,6 +3214,14 @@ var Reactor = class {
2870
3214
  }
2871
3215
  });
2872
3216
  }
3217
+ pauseTrack(name) {
3218
+ var _a;
3219
+ (_a = this.transportClient) == null ? void 0 : _a.pauseTrack(name);
3220
+ }
3221
+ resumeTrack(name) {
3222
+ var _a;
3223
+ (_a = this.transportClient) == null ? void 0 : _a.resumeTrack(name);
3224
+ }
2873
3225
  /**
2874
3226
  * Reconnects to an existing session with a fresh transport.
2875
3227
  */
@@ -2919,9 +3271,16 @@ var Reactor = class {
2919
3271
  * be a static string or a {@link JwtSource} resolver; pass a
2920
3272
  * resolver when the token is short-lived so each Coordinator HTTP
2921
3273
  * hop sees a fresh value.
3274
+ *
3275
+ * Pass `options.sessionId` to attach to a session that already exists
3276
+ * (e.g. one created by a backend) instead of creating a new one — session
3277
+ * creation is skipped and the transport is brought up against that id. The
3278
+ * `jwtToken` must be valid for the account that owns the session. Works in
3279
+ * local mode too (it looks the session up by id rather than starting one).
2922
3280
  */
2923
3281
  connect(jwtToken, options) {
2924
3282
  return __async(this, null, function* () {
3283
+ var _a;
2925
3284
  console.debug("[Reactor] Connecting, status:", this.status);
2926
3285
  if (jwtToken == void 0 && !this.local) {
2927
3286
  throw new Error("No authentication provided and not in local mode");
@@ -2940,20 +3299,31 @@ var Reactor = class {
2940
3299
  jwtToken,
2941
3300
  model: this.model
2942
3301
  });
2943
- const tSession = performance.now();
2944
- const initialResponse = yield this.coordinatorClient.createSession();
2945
- const sessionCreationMs = performance.now() - tSession;
2946
- this.setSessionId(initialResponse.session_id);
2947
- console.debug(
2948
- "[Reactor] Session created:",
2949
- initialResponse.session_id,
2950
- "state:",
2951
- initialResponse.state
2952
- );
3302
+ let sessionCreationMs = 0;
3303
+ let sessionId;
3304
+ if (options == null ? void 0 : options.sessionId) {
3305
+ yield this.coordinatorClient.adoptSession(options.sessionId);
3306
+ sessionId = options.sessionId;
3307
+ this.createdSession = false;
3308
+ console.debug("[Reactor] Attaching to existing session:", sessionId);
3309
+ } else {
3310
+ const tSession = performance.now();
3311
+ const initialResponse = yield this.coordinatorClient.createSession();
3312
+ sessionCreationMs = performance.now() - tSession;
3313
+ sessionId = initialResponse.session_id;
3314
+ this.createdSession = true;
3315
+ console.debug(
3316
+ "[Reactor] Session created:",
3317
+ sessionId,
3318
+ "state:",
3319
+ initialResponse.state
3320
+ );
3321
+ }
3322
+ this.setSessionId(sessionId);
2953
3323
  this.setStatus("waiting");
2954
3324
  this.transportClient = new WebRTCTransportClient({
2955
3325
  baseUrl: this.coordinatorUrl,
2956
- sessionId: initialResponse.session_id,
3326
+ sessionId,
2957
3327
  jwtToken: this.local ? "local" : jwtToken,
2958
3328
  webrtcVersion: REACTOR_WEBRTC_VERSION,
2959
3329
  maxPollAttempts: options == null ? void 0 : options.maxAttempts
@@ -2961,19 +3331,22 @@ var Reactor = class {
2961
3331
  this.setupTransportHandlers();
2962
3332
  let sessionPollingMs;
2963
3333
  let transportConnectingMs;
3334
+ this.autoResumeTracks = (_a = options == null ? void 0 : options.autoResumeTracks) != null ? _a : true;
2964
3335
  if (this.presetTracks) {
3336
+ this.tracks = this.presetTracks;
2965
3337
  const tParallel = performance.now();
2966
3338
  const [sessionResponse] = yield Promise.all([
2967
3339
  this.coordinatorClient.pollSessionReady(),
2968
- this.transportClient.prepare(this.presetTracks)
3340
+ this.transportClient.prepare(this.tracks)
2969
3341
  ]);
2970
3342
  sessionPollingMs = performance.now() - tParallel;
2971
3343
  this.sessionResponse = sessionResponse;
2972
- this.capabilities = sessionResponse.capabilities;
2973
- this.tracks = this.presetTracks;
3344
+ this.capabilities = __spreadProps(__spreadValues({}, sessionResponse.capabilities), {
3345
+ tracks: this.tracks
3346
+ });
2974
3347
  this.emit("capabilitiesReceived", this.capabilities);
2975
3348
  const tConnect = performance.now();
2976
- yield this.transportClient.connect();
3349
+ yield this.transportClient.connect(false, options == null ? void 0 : options.connectionId);
2977
3350
  transportConnectingMs = performance.now() - tConnect;
2978
3351
  } else {
2979
3352
  this.transportClient.warmup();
@@ -2981,8 +3354,10 @@ var Reactor = class {
2981
3354
  const sessionResponse = yield this.coordinatorClient.pollSessionReady();
2982
3355
  sessionPollingMs = performance.now() - tPoll;
2983
3356
  this.sessionResponse = sessionResponse;
2984
- this.capabilities = sessionResponse.capabilities;
2985
3357
  this.tracks = sessionResponse.capabilities.tracks;
3358
+ this.capabilities = __spreadProps(__spreadValues({}, sessionResponse.capabilities), {
3359
+ tracks: this.tracks
3360
+ });
2986
3361
  this.emit("capabilitiesReceived", this.capabilities);
2987
3362
  const protocol = sessionResponse.selected_transport.protocol;
2988
3363
  if (protocol !== "webrtc") {
@@ -2990,7 +3365,7 @@ var Reactor = class {
2990
3365
  }
2991
3366
  const tTransport = performance.now();
2992
3367
  yield this.transportClient.prepare(this.tracks);
2993
- yield this.transportClient.connect();
3368
+ yield this.transportClient.connect(false, options == null ? void 0 : options.connectionId);
2994
3369
  transportConnectingMs = performance.now() - tTransport;
2995
3370
  }
2996
3371
  console.debug("[Reactor] Session ready, tracks:", this.tracks.length);
@@ -3040,6 +3415,13 @@ var Reactor = class {
3040
3415
  switch (status) {
3041
3416
  case "connected":
3042
3417
  this.finalizeConnectionTimings();
3418
+ if (this.autoResumeTracks) {
3419
+ for (const track of this.tracks) {
3420
+ if (track.direction === "recvonly") {
3421
+ this.resumeTrack(track.name);
3422
+ }
3423
+ }
3424
+ }
3043
3425
  this.setStatus("ready");
3044
3426
  break;
3045
3427
  case "disconnected":
@@ -3061,6 +3443,13 @@ var Reactor = class {
3061
3443
  (name, track, stream) => {
3062
3444
  if (this.transportClient !== client) return;
3063
3445
  this.emit("trackReceived", name, track, stream);
3446
+ if (this.autoResumeTracks) {
3447
+ for (const track2 of this.tracks) {
3448
+ if (track2.direction === "recvonly") {
3449
+ this.resumeTrack(track2.name);
3450
+ }
3451
+ }
3452
+ }
3064
3453
  }
3065
3454
  );
3066
3455
  client.on("statsUpdate", (stats) => {
@@ -3083,10 +3472,16 @@ var Reactor = class {
3083
3472
  (_a = this.coordinatorClient) == null ? void 0 : _a.abort();
3084
3473
  (_b = this.transportClient) == null ? void 0 : _b.abort();
3085
3474
  if (this.coordinatorClient && !recoverable) {
3086
- try {
3087
- yield this.coordinatorClient.terminateSession();
3088
- } catch (error) {
3089
- console.error("[Reactor] Error terminating session:", error);
3475
+ if (this.createdSession) {
3476
+ try {
3477
+ yield this.coordinatorClient.terminateSession();
3478
+ } catch (error) {
3479
+ console.error("[Reactor] Error terminating session:", error);
3480
+ }
3481
+ } else {
3482
+ console.debug(
3483
+ "[Reactor] Adopted session (not the creator) \u2014 skipping DELETE, leaving it alive"
3484
+ );
3090
3485
  }
3091
3486
  this.coordinatorClient = void 0;
3092
3487
  }
@@ -3108,6 +3503,7 @@ var Reactor = class {
3108
3503
  this.capabilities = void 0;
3109
3504
  this.tracks = [];
3110
3505
  this.sessionResponse = void 0;
3506
+ this.createdSession = false;
3111
3507
  }
3112
3508
  });
3113
3509
  }
@@ -3217,7 +3613,8 @@ var defaultInitState = {
3217
3613
  lastError: void 0,
3218
3614
  sessionExpiration: void 0,
3219
3615
  jwtToken: void 0,
3220
- sessionId: void 0
3616
+ sessionId: void 0,
3617
+ connectOptions: void 0
3221
3618
  };
3222
3619
  var initReactorStore = (props) => {
3223
3620
  return __spreadValues(__spreadValues({}, defaultInitState), props);
@@ -3273,6 +3670,7 @@ var createReactorStore = (initProps, publicState = defaultInitState) => {
3273
3670
  });
3274
3671
  return __spreadProps(__spreadValues({}, publicState), {
3275
3672
  jwtToken: initProps.jwtToken,
3673
+ connectOptions: initProps.connectOptions,
3276
3674
  internal: { reactor },
3277
3675
  // actions
3278
3676
  onMessage: (handler) => {
@@ -3301,9 +3699,10 @@ var createReactorStore = (initProps, publicState = defaultInitState) => {
3301
3699
  if (jwtToken === void 0) {
3302
3700
  jwtToken = get().jwtToken;
3303
3701
  }
3702
+ const resolvedOptions = __spreadValues(__spreadValues({}, get().connectOptions), options);
3304
3703
  console.debug("[ReactorStore] Connect called.");
3305
3704
  try {
3306
- yield get().internal.reactor.connect(jwtToken, options);
3705
+ yield get().internal.reactor.connect(jwtToken, resolvedOptions);
3307
3706
  console.debug("[ReactorStore] Connect completed successfully");
3308
3707
  } catch (error) {
3309
3708
  console.error("[ReactorStore] Connect failed:", error);
@@ -3411,30 +3810,31 @@ function ReactorProvider(_a) {
3411
3810
  const storeRef = useRef(void 0);
3412
3811
  const firstRender = useRef(true);
3413
3812
  const [_storeVersion, setStoreVersion] = useState(0);
3813
+ const _a2 = connectOptions != null ? connectOptions : {}, { autoConnect = false } = _a2, pollingOptions = __objRest(_a2, ["autoConnect"]);
3414
3814
  if (storeRef.current === void 0) {
3415
3815
  console.debug("[ReactorProvider] Creating new reactor store");
3416
3816
  storeRef.current = createReactorStore(
3417
3817
  initReactorStore(__spreadProps(__spreadValues({}, props), {
3418
- jwtToken: jwtSource
3818
+ jwtToken: jwtSource,
3819
+ connectOptions: pollingOptions
3419
3820
  }))
3420
3821
  );
3421
3822
  console.debug("[ReactorProvider] Reactor store created successfully");
3422
3823
  }
3423
- const _a2 = connectOptions != null ? connectOptions : {}, { autoConnect = false } = _a2, pollingOptions = __objRest(_a2, ["autoConnect"]);
3424
3824
  const { apiUrl, modelName, local } = props;
3425
3825
  const maxAttempts = pollingOptions.maxAttempts;
3826
+ const { autoResumeTracks } = pollingOptions;
3827
+ useEffect(() => {
3828
+ var _a3;
3829
+ (_a3 = storeRef.current) == null ? void 0 : _a3.setState({ connectOptions: pollingOptions });
3830
+ }, [autoResumeTracks, maxAttempts]);
3426
3831
  useEffect(() => {
3427
3832
  const handleBeforeUnload = () => {
3428
3833
  var _a3;
3429
- console.debug(
3430
- "[ReactorProvider] Page unloading, performing non-recoverable disconnect"
3431
- );
3432
3834
  (_a3 = storeRef.current) == null ? void 0 : _a3.getState().internal.reactor.disconnect(false);
3433
3835
  };
3434
3836
  window.addEventListener("beforeunload", handleBeforeUnload);
3435
- return () => {
3436
- window.removeEventListener("beforeunload", handleBeforeUnload);
3437
- };
3837
+ return () => window.removeEventListener("beforeunload", handleBeforeUnload);
3438
3838
  }, []);
3439
3839
  useEffect(() => {
3440
3840
  if (firstRender.current) {
@@ -3477,7 +3877,8 @@ function ReactorProvider(_a) {
3477
3877
  apiUrl,
3478
3878
  modelName,
3479
3879
  local,
3480
- jwtToken: jwtSource
3880
+ jwtToken: jwtSource,
3881
+ connectOptions: pollingOptions
3481
3882
  })
3482
3883
  );
3483
3884
  const current = storeRef.current;
@@ -3603,26 +4004,39 @@ function ReactorView({
3603
4004
  hasVideoTrack: !!videoMediaTrack,
3604
4005
  hasAudioTrack: !!audioMediaTrack
3605
4006
  });
3606
- if (videoRef.current && mediaStream) {
3607
- console.debug("[ReactorView] Attaching media stream to element");
4007
+ const el = videoRef.current;
4008
+ if (!el || !mediaStream) {
4009
+ console.debug("[ReactorView] No tracks or element to attach");
4010
+ return;
4011
+ }
4012
+ const attach = (reset) => {
3608
4013
  try {
3609
- videoRef.current.srcObject = mediaStream;
3610
- videoRef.current.play().catch((e) => {
4014
+ if (reset) el.srcObject = null;
4015
+ el.srcObject = mediaStream;
4016
+ el.play().catch((e) => {
3611
4017
  console.warn("[ReactorView] Auto-play failed:", e);
3612
4018
  });
3613
- console.debug("[ReactorView] Media stream attached successfully");
3614
4019
  } catch (error) {
3615
4020
  console.error("[ReactorView] Failed to attach media stream:", error);
3616
4021
  }
3617
- return () => {
3618
- console.debug("[ReactorView] Detaching media stream from element");
3619
- if (videoRef.current) {
3620
- videoRef.current.srcObject = null;
3621
- }
3622
- };
3623
- } else {
3624
- console.debug("[ReactorView] No tracks or element to attach");
3625
- }
4022
+ };
4023
+ console.debug("[ReactorView] Attaching media stream to element");
4024
+ attach(false);
4025
+ const onUnmute = () => {
4026
+ console.debug(
4027
+ "[ReactorView] Track unmuted \u2014 re-attaching to render incoming media"
4028
+ );
4029
+ attach(true);
4030
+ };
4031
+ const tracks = mediaStream.getTracks();
4032
+ for (const t of tracks) t.addEventListener("unmute", onUnmute);
4033
+ return () => {
4034
+ console.debug("[ReactorView] Detaching media stream from element");
4035
+ for (const t of tracks) t.removeEventListener("unmute", onUnmute);
4036
+ if (videoRef.current) {
4037
+ videoRef.current.srcObject = null;
4038
+ }
4039
+ };
3626
4040
  }, [mediaStream]);
3627
4041
  return /* @__PURE__ */ jsx2(
3628
4042
  "div",