@coasys/ad4m 0.13.1-staging.8 → 0.13.1-staging.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/lib/index.cjs +652 -147
  2. package/lib/index.js +648 -148
  3. package/lib/src/agent/AgentClient.d.ts +6 -0
  4. package/lib/src/agent/AgentClient.js +17 -0
  5. package/lib/src/agent/AgentKind.d.ts +17 -0
  6. package/lib/src/agent/AgentKind.js +21 -0
  7. package/lib/src/apiClient.d.ts +4 -1
  8. package/lib/src/apiClient.js +13 -4
  9. package/lib/src/generated/api/CallSessionInfo.d.ts +1 -1
  10. package/lib/src/generated/api/Events.d.ts +2 -0
  11. package/lib/src/generated/api/PerspectiveModelSubscribeParams.d.ts +11 -0
  12. package/lib/src/generated/api/PerspectiveModelSubscribeParams.js +2 -0
  13. package/lib/src/generated/api/PerspectiveSubscribeQueryParams.d.ts +9 -0
  14. package/lib/src/generated/api/PerspectiveSubscribeQueryParams.js +2 -0
  15. package/lib/src/generated/api/RpcMethods.d.ts +10 -4
  16. package/lib/src/generated/api/RpcMethods.js +5 -0
  17. package/lib/src/generated/api/SfuAddIceCandidateParams.d.ts +4 -0
  18. package/lib/src/generated/api/SfuAnswerServerOfferParams.d.ts +4 -0
  19. package/lib/src/generated/api/SfuCallJoinParams.d.ts +13 -0
  20. package/lib/src/generated/api/SfuCallLeaveParams.d.ts +12 -0
  21. package/lib/src/generated/api/SfuCallLeaveParams.js +2 -0
  22. package/lib/src/generated/api/SfuCallRenegotiationOffer.d.ts +5 -0
  23. package/lib/src/generated/api/SfuDataMessage.d.ts +6 -0
  24. package/lib/src/generated/api/SfuQualityPreferenceParams.d.ts +4 -0
  25. package/lib/src/generated/api/SfuRestartIceParams.d.ts +12 -0
  26. package/lib/src/generated/api/SfuRestartIceParams.js +2 -0
  27. package/lib/src/generated/api/SfuRoomParticipantInfo.d.ts +4 -0
  28. package/lib/src/generated/api/SfuRoomRoster.d.ts +6 -2
  29. package/lib/src/generated/api/SfuRoomRoster.js +0 -1
  30. package/lib/src/generated/api/SfuRosterParticipant.d.ts +7 -0
  31. package/lib/src/generated/api/SfuRosterParticipant.js +2 -0
  32. package/lib/src/generated/api/SfuSendDataParams.d.ts +4 -0
  33. package/lib/src/generated/api/SfuSessionReplaced.d.ts +15 -0
  34. package/lib/src/generated/api/SfuSessionReplaced.js +2 -0
  35. package/lib/src/generated/api/SubscribeQueryRequest.d.ts +4 -0
  36. package/lib/src/generated/api/TrackMapEntry.d.ts +6 -1
  37. package/lib/src/generated/api/index.d.ts +1 -1
  38. package/lib/src/generated/api/index.js +1 -1
  39. package/lib/src/index.d.ts +1 -0
  40. package/lib/src/index.js +1 -0
  41. package/lib/src/neighbourhood/MeshManager.d.ts +19 -2
  42. package/lib/src/neighbourhood/MeshManager.js +55 -8
  43. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +34 -13
  44. package/lib/src/neighbourhood/NeighbourhoodClient.js +44 -14
  45. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +15 -7
  46. package/lib/src/neighbourhood/NeighbourhoodProxy.js +26 -13
  47. package/lib/src/neighbourhood/Session.d.ts +24 -5
  48. package/lib/src/neighbourhood/Session.js +179 -35
  49. package/lib/src/neighbourhood/SfuManager.d.ts +98 -28
  50. package/lib/src/neighbourhood/SfuManager.js +258 -71
  51. package/lib/src/neighbourhood/SfuTypes.d.ts +4 -0
  52. package/lib/src/perspectives/PerspectiveClient.js +33 -4
  53. package/package.json +2 -2
  54. package/src/Ad4mClient.test.ts +5 -5
  55. package/src/agent/AgentClient.ts +20 -0
  56. package/src/agent/AgentKind.ts +28 -0
  57. package/src/agent/mutatePublicPerspective.test.ts +72 -0
  58. package/src/apiClient.test.ts +46 -0
  59. package/src/apiClient.ts +16 -5
  60. package/src/generated/api/CallSessionInfo.ts +1 -1
  61. package/src/generated/api/Events.ts +2 -0
  62. package/src/generated/api/PerspectiveModelSubscribeParams.ts +7 -0
  63. package/src/generated/api/PerspectiveSubscribeQueryParams.ts +7 -0
  64. package/src/generated/api/RpcMethods.ts +14 -4
  65. package/src/generated/api/SfuAddIceCandidateParams.ts +4 -0
  66. package/src/generated/api/SfuAnswerServerOfferParams.ts +4 -0
  67. package/src/generated/api/SfuCallJoinParams.ts +13 -0
  68. package/src/generated/api/SfuCallLeaveParams.ts +11 -0
  69. package/src/generated/api/SfuCallRenegotiationOffer.ts +6 -1
  70. package/src/generated/api/SfuDataMessage.ts +7 -1
  71. package/src/generated/api/SfuQualityPreferenceParams.ts +4 -0
  72. package/src/generated/api/SfuRestartIceParams.ts +11 -0
  73. package/src/generated/api/SfuRoomParticipantInfo.ts +5 -1
  74. package/src/generated/api/SfuRoomRoster.ts +6 -2
  75. package/src/generated/api/SfuRosterParticipant.ts +6 -0
  76. package/src/generated/api/SfuSendDataParams.ts +5 -1
  77. package/src/generated/api/SfuSessionReplaced.ts +13 -0
  78. package/src/generated/api/SubscribeQueryRequest.ts +5 -1
  79. package/src/generated/api/TrackMapEntry.ts +6 -1
  80. package/src/generated/api/index.ts +1 -1
  81. package/src/index.ts +1 -0
  82. package/src/neighbourhood/MeshManager.test.ts +101 -25
  83. package/src/neighbourhood/MeshManager.ts +56 -7
  84. package/src/neighbourhood/NeighbourhoodClient.test.ts +45 -15
  85. package/src/neighbourhood/NeighbourhoodClient.ts +49 -9
  86. package/src/neighbourhood/NeighbourhoodProxy.ts +29 -6
  87. package/src/neighbourhood/Session.test.ts +388 -36
  88. package/src/neighbourhood/Session.ts +185 -38
  89. package/src/neighbourhood/SfuManager.test.ts +626 -20
  90. package/src/neighbourhood/SfuManager.ts +275 -67
  91. package/src/neighbourhood/SfuTypes.ts +4 -0
  92. package/src/perspectives/PerspectiveClient.ts +36 -4
  93. package/src/perspectives/abandoned-subscribe.test.ts +219 -0
package/lib/index.cjs CHANGED
@@ -120,6 +120,11 @@ const LONG_METHODS = new Set([
120
120
  "perspective.runInterpretationWithHarness",
121
121
  "runtime.restartHolochain",
122
122
  ]);
123
+ /** Calls that open something on the executor that outlives them (a live query): the client cancels one that timed out, as one it aborted. */
124
+ const OPENS_METHODS = new Set([
125
+ "perspective.modelSubscribe",
126
+ "perspective.subscribeQuery",
127
+ ]);
123
128
 
124
129
  /** Error thrown by ApiClient when an RPC call fails. */
125
130
  class RpcError extends Error {
@@ -605,7 +610,18 @@ class ApiClient {
605
610
  signal?.removeEventListener('abort', onAbort);
606
611
  fn();
607
612
  };
613
+ // Tell the executor the call is no longer wanted, so it stops the work. A late
614
+ // reply finds no pending call and is dropped.
615
+ const cancel = () => {
616
+ if (pending.sent && this._ws?.readyState === 1 /* OPEN */) {
617
+ this._send(this._ws, JSON.stringify({ id: nextId(), type: 'request.cancel', params: { targetId: id } }));
618
+ }
619
+ };
608
620
  const timer = setTimeout(() => {
621
+ // Only a call that opens something is cancelled on timeout: a write that
622
+ // timed out still runs to its end on the executor, as it always has.
623
+ if (OPENS_METHODS.has(type))
624
+ cancel();
609
625
  settle(() => reject(new RpcError(408, `RPC call '${type}' timed out after ${timeoutMs}ms`)));
610
626
  // A connect that never completes (a black-holed port) would hold every later
611
627
  // call. Drop it once no call waits on it, so the next call dials again.
@@ -616,9 +632,7 @@ class ApiClient {
616
632
  }
617
633
  }, timeoutMs);
618
634
  const onAbort = () => {
619
- if (pending.sent && this._ws?.readyState === 1 /* OPEN */) {
620
- this._send(this._ws, JSON.stringify({ id: nextId(), type: 'request.cancel', params: { targetId: id } }));
621
- }
635
+ cancel();
622
636
  settle(() => reject(new DOMException('Aborted', 'AbortError')));
623
637
  };
624
638
  const pending = {
@@ -1265,6 +1279,28 @@ class AgentStatus {
1265
1279
  }
1266
1280
  }
1267
1281
 
1282
+ /**
1283
+ * What kind of agent this is, as the agent says itself: one link in its public perspective,
1284
+ * `<its did> ad4m://agent_kind <kind>`.
1285
+ *
1286
+ * Only the agent can write its public perspective, so the kind is its own claim, the same in
1287
+ * every space and every app. Nothing checks it: a bot that leaves it out reads as an agent of no
1288
+ * declared kind. It exists so an app can tell a program speaking from a person without each
1289
+ * community marking its bots by hand.
1290
+ */
1291
+ const AGENT_KIND = "ad4m://agent_kind";
1292
+ /** The kind of an agent that is a program acting by itself: a bot, an AI agent, an integration. */
1293
+ const AGENT_KIND_BOT = "ad4m://bot";
1294
+ /** The kind `agent` declares in its public perspective, or `undefined` when it declares none. */
1295
+ function agentKind(agent) {
1296
+ const link = agent?.perspective?.links?.find((l) => l.data.source === agent.did && l.data.predicate === AGENT_KIND);
1297
+ return link?.data.target || undefined;
1298
+ }
1299
+ /** Whether `agent` says it is a bot. */
1300
+ function isBot(agent) {
1301
+ return agentKind(agent) === AGENT_KIND_BOT;
1302
+ }
1303
+
1268
1304
  /**
1269
1305
  * PersistentCache — two-tier persistent key-value cache abstraction.
1270
1306
  *
@@ -1548,6 +1584,22 @@ class AgentClient {
1548
1584
  const kept = (perspective?.links ?? []).filter(link => !removals.some(r => linkEqual(link, r)));
1549
1585
  return this.updatePublicPerspective({ links: [...kept, ...added] });
1550
1586
  }
1587
+ /**
1588
+ * Say what kind of agent this is in its public perspective (`AGENT_KIND`; a bot is
1589
+ * `AGENT_KIND_BOT`), replacing any kind it said before, or say none with `null`. Changes
1590
+ * nothing when the perspective already says exactly that, so it can be called on every start.
1591
+ */
1592
+ async setKind(kind) {
1593
+ const me = await this.me();
1594
+ const said = (me.perspective?.links ?? []).filter((l) => l.data.source === me.did && l.data.predicate === AGENT_KIND);
1595
+ if ((kind === null && said.length === 0) || (said.length === 1 && said[0].data.target === kind)) {
1596
+ return me;
1597
+ }
1598
+ return this.mutatePublicPerspective({
1599
+ additions: kind === null ? [] : [{ source: me.did, predicate: AGENT_KIND, target: kind }],
1600
+ removals: said,
1601
+ });
1602
+ }
1551
1603
  async updateDirectMessageLanguage(directMessageLanguage) {
1552
1604
  const agent = toAgent(await __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").call('agent.updateProfile', { dmLanguage: directMessageLanguage }));
1553
1605
  // Immediately update byDID cache so subsequent byDID() calls
@@ -1890,35 +1942,49 @@ class NeighbourhoodClient {
1890
1942
  async sfuListRooms() {
1891
1943
  return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.listRooms", {});
1892
1944
  }
1893
- async sfuCallJoin(neighbourhoodUrl, roomName, sdpOffer) {
1945
+ /**
1946
+ * Join a call from `deviceId`. The executor replaces this agent's session
1947
+ * from the same device (another tab) and keeps those from other devices.
1948
+ * The result's `participantId` names the session in every later call.
1949
+ * `sessionKey` is the caller's random key for the session: a rebuild
1950
+ * sends it again; a key a later join from this device replaced is
1951
+ * refused with `RpcError` status 409, and that session must stop.
1952
+ */
1953
+ async sfuCallJoin(neighbourhoodUrl, roomName, sdpOffer, deviceId, sessionKey) {
1894
1954
  return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callJoin", {
1895
1955
  neighbourhoodUrl,
1896
1956
  roomName,
1897
1957
  sdpOffer,
1958
+ deviceId,
1959
+ sessionKey,
1898
1960
  });
1899
1961
  }
1900
- async sfuCallLeave(neighbourhoodUrl, roomName) {
1901
- return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callLeave", { neighbourhoodUrl, roomName });
1962
+ /** Leave the session `participantId`; `false` when it is not this agent's or is gone already. */
1963
+ async sfuCallLeave(neighbourhoodUrl, roomName, participantId) {
1964
+ return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callLeave", { neighbourhoodUrl, roomName, participantId });
1902
1965
  }
1903
- async sfuCallSetQualityPreference(neighbourhoodUrl, roomName, preference) {
1966
+ async sfuCallSetQualityPreference(neighbourhoodUrl, roomName, participantId, preference) {
1904
1967
  return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callSetQualityPreference", {
1905
1968
  neighbourhoodUrl,
1906
1969
  roomName,
1970
+ participantId,
1907
1971
  preference,
1908
1972
  });
1909
1973
  }
1910
- async sfuCallAnswerServerOffer(neighbourhoodUrl, roomName, sdpAnswer) {
1974
+ async sfuCallAnswerServerOffer(neighbourhoodUrl, roomName, participantId, sdpAnswer) {
1911
1975
  return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callAnswerServerOffer", {
1912
1976
  neighbourhoodUrl,
1913
1977
  roomName,
1978
+ participantId,
1914
1979
  sdpAnswer,
1915
1980
  });
1916
1981
  }
1917
- /** Ask the SFU to restart ICE on this agent's call connection. The offer
1918
- * arrives as an `sfu-call-renegotiation-offer` event; answer it with
1919
- * {@link sfuCallAnswerServerOffer}. */
1920
- async sfuCallRestartIce(neighbourhoodUrl, roomName) {
1921
- return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callRestartIce", { neighbourhoodUrl, roomName });
1982
+ /** Ask the SFU to restart ICE on the session `participantId` (this
1983
+ * agent's, as its join returned it; any other is refused). The offer
1984
+ * arrives as an `sfu-call-renegotiation-offer` event for that session;
1985
+ * answer it with {@link sfuCallAnswerServerOffer}. */
1986
+ async sfuCallRestartIce(neighbourhoodUrl, roomName, participantId) {
1987
+ return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callRestartIce", { neighbourhoodUrl, roomName, participantId });
1922
1988
  }
1923
1989
  /** Fires after a network change, once the client's socket is back on
1924
1990
  * the new network. See {@link ApiClient.onNetworkChange}. */
@@ -1951,10 +2017,11 @@ class NeighbourhoodClient {
1951
2017
  * complete (which can take up to 8 seconds on restrictive
1952
2018
  * networks).
1953
2019
  */
1954
- async sfuAddIceCandidate(neighbourhoodUrl, roomName, candidate) {
2020
+ async sfuAddIceCandidate(neighbourhoodUrl, roomName, participantId, candidate) {
1955
2021
  return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.addIceCandidate", {
1956
2022
  neighbourhoodUrl,
1957
2023
  roomName,
2024
+ participantId,
1958
2025
  candidate,
1959
2026
  });
1960
2027
  }
@@ -1964,10 +2031,11 @@ class NeighbourhoodClient {
1964
2031
  * The server relays it to their matching data channel and
1965
2032
  * publishes it as an `sfu-data` event.
1966
2033
  */
1967
- async sfuSendData(neighbourhoodUrl, roomName, channelLabel, data, binary = false) {
2034
+ async sfuSendData(neighbourhoodUrl, roomName, participantId, channelLabel, data, binary = false) {
1968
2035
  return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.sendData", {
1969
2036
  neighbourhoodUrl,
1970
2037
  roomName,
2038
+ participantId,
1971
2039
  channelLabel,
1972
2040
  data,
1973
2041
  binary,
@@ -1976,17 +2044,28 @@ class NeighbourhoodClient {
1976
2044
  /**
1977
2045
  * Subscribe to SFU data channel messages. Returns an unsubscribe
1978
2046
  * function. Messages arrive for every participant in the room;
1979
- * filter by `senderDid` if needed.
2047
+ * filter by `senderDid` or `senderParticipantId` if needed. One sent by
2048
+ * a session of this agent arrives here when the agent is in the call on
2049
+ * another device too: it carries the sending session's participant id.
1980
2050
  */
1981
2051
  subscribeSfuDataChannel(callback) {
1982
2052
  // A fresh handler per call: `on` merges a repeated handler, and
1983
2053
  // each subscription must own its unsubscribe.
1984
2054
  return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").on("sfu-data", (message) => callback(message));
1985
2055
  }
1986
- /** Subscribe to the rosters of the call rooms this agent is in: who is in each, whenever that changes. */
2056
+ /** Subscribe to the rosters of the call rooms this agent is in: who is in each, by session, whenever that changes. */
1987
2057
  subscribeSfuRoomRoster(callback) {
1988
2058
  return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").on("sfu-room-roster", (roster) => callback(roster));
1989
2059
  }
2060
+ /**
2061
+ * Subscribe to the executor's notice that a session of this agent was
2062
+ * replaced: a later join from the same device took its call over. The
2063
+ * notice names the replaced session's participant id; the session that
2064
+ * holds it stops and does not rejoin.
2065
+ */
2066
+ subscribeSfuSessionReplaced(callback) {
2067
+ return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").on("sfu-session-replaced", (event) => callback(event));
2068
+ }
1990
2069
  /**
1991
2070
  * Subscribe to server-pushed SFU SDP renegotiation offers. The
1992
2071
  * server publishes an `sfu-call-renegotiation-offer` event every
@@ -1996,6 +2075,8 @@ class NeighbourhoodClient {
1996
2075
  *
1997
2076
  * The executor already sends each socket only its own DID's offers;
1998
2077
  * this subscription additionally filters on `targetDid` for safety.
2078
+ * An agent in the call on two devices gets the offers of both: each
2079
+ * names the session it is for (`participantId`).
1999
2080
  * Returns an unsubscribe function.
2000
2081
  */
2001
2082
  subscribeSfuCallRenegotiationOffer(targetDid, callback) {
@@ -2004,6 +2085,7 @@ class NeighbourhoodClient {
2004
2085
  return;
2005
2086
  callback({
2006
2087
  targetDid: event.targetDid,
2088
+ participantId: event.participantId,
2007
2089
  neighbourhoodUrl: event.neighbourhoodUrl,
2008
2090
  roomName: event.roomName,
2009
2091
  sdpOffer: event.sdpOffer,
@@ -2096,6 +2178,15 @@ _NeighbourhoodClient_apiClient = new WeakMap(), _NeighbourhoodClient_signalHandl
2096
2178
  * through cascade pipes between executors, so the client never follows
2097
2179
  * a redirect or a rebalance to another node — it has no way to reach one.
2098
2180
  *
2181
+ * One session per device: a join names this device (`deviceId`), and the
2182
+ * executor gives it a participant id that every later call about the
2183
+ * session names. The same agent on another device is another participant;
2184
+ * a later join from this device — another tab — replaces this session, and
2185
+ * the manager stops (`replaced`) rather than taking the call back. Each
2186
+ * user join sends a random session key that the rebuilds of that call send
2187
+ * again; the executor refuses (409) a key another tab's join replaced, so a
2188
+ * tab that missed its `sfu-session-replaced` notice stops all the same.
2189
+ *
2099
2190
  * Applications (Flux, WE, or any other) wrap this class with their
2100
2191
  * own reactive store and UI layer. The manager itself only touches
2101
2192
  * Web APIs (RTCPeerConnection, MediaStream) and the AD4M
@@ -2105,9 +2196,58 @@ _NeighbourhoodClient_apiClient = new WeakMap(), _NeighbourhoodClient_signalHandl
2105
2196
  const DEFAULT_ICE_SERVERS$1 = [
2106
2197
  { urls: "stun:stun.l.google.com:19302" },
2107
2198
  ];
2199
+ /**
2200
+ * Where a browser profile keeps its device id. The prefix versions the
2201
+ * stored value, as `connect`'s `{version}/ad4m-token` does; it is not the
2202
+ * SDK release, so an upgrade does not make every browser a new device.
2203
+ */
2204
+ const DEVICE_ID_KEY = "v1/ad4m-sfu-device-id";
2205
+ /** Outside a browser: one device id for the life of the process. */
2206
+ let processDeviceId = null;
2207
+ function randomId() {
2208
+ const crypto = globalThis.crypto;
2209
+ if (crypto?.randomUUID)
2210
+ return crypto.randomUUID();
2211
+ return Array.from({ length: 4 }, () => Math.random().toString(36).slice(2, 10)).join("");
2212
+ }
2213
+ /**
2214
+ * This device's id for SFU calls, unless the app gives one. In a browser it
2215
+ * is kept in `localStorage`, which every tab of one profile shares, so the
2216
+ * tabs of one browser are one device; outside a browser (Node), the process
2217
+ * is the device.
2218
+ */
2219
+ function defaultDeviceId() {
2220
+ let storage;
2221
+ try {
2222
+ storage = globalThis.localStorage;
2223
+ }
2224
+ catch {
2225
+ storage = undefined; // storage denied (sandboxed frame, privacy settings)
2226
+ }
2227
+ if (storage) {
2228
+ try {
2229
+ let id = storage.getItem(DEVICE_ID_KEY);
2230
+ if (!id) {
2231
+ id = randomId();
2232
+ storage.setItem(DEVICE_ID_KEY, id);
2233
+ }
2234
+ return id;
2235
+ }
2236
+ catch {
2237
+ /* unusable storage: fall back to the process */
2238
+ }
2239
+ }
2240
+ return (processDeviceId ?? (processDeviceId = randomId()));
2241
+ }
2108
2242
  // ── SFU Manager ───────────────────────────────────────────────────
2109
2243
  class SfuManager {
2110
- constructor(neighbourhood, roomId, agentDid, neighbourhoodUrl, iceConfig, sfuConfig) {
2244
+ constructor(neighbourhood, roomId, agentDid, neighbourhoodUrl, iceConfig, sfuConfig,
2245
+ /** This device; unset, `defaultDeviceId()`. Apps outside a browser profile (Electron, tests) pass their own. */
2246
+ deviceId) {
2247
+ /** This call session's key: a rebuild joins with it again, a user's join
2248
+ * makes a new one. The executor refuses a key a later join from this
2249
+ * device replaced, so a tab that missed its notice cannot take the call back. */
2250
+ this.sessionKey = randomId();
2111
2251
  this.callbacks = new Map();
2112
2252
  /** Reconnects since ICE last reached connected — not since a join: a
2113
2253
  * join can succeed while the media path never comes up. */
@@ -2116,9 +2256,9 @@ class SfuManager {
2116
2256
  this.reconnecting = false;
2117
2257
  /** Bumped by `leave()`, so a reconnect in flight stops before rejoining. */
2118
2258
  this.generation = 0;
2119
- /** Which participant each received media section carries, from the server's mappings. */
2259
+ /** Which participant (session and agent) each received media section carries, from the server's mappings. */
2120
2260
  this.midToParticipant = new Map();
2121
- /** DIDs the roster removed and has not listed since. */
2261
+ /** Participant ids the roster removed and has not listed since. */
2122
2262
  this.departed = new Set();
2123
2263
  /** The sender of each kind of local media: declared at join, so a later camera or screen needs no renegotiation. */
2124
2264
  this.senders = new Map();
@@ -2134,17 +2274,24 @@ class SfuManager {
2134
2274
  this.answeredOffer = null;
2135
2275
  this.renegotiationUnsubscribe = null;
2136
2276
  this.rosterUnsubscribe = null;
2277
+ /** For the manager's call, not one join: a reconnect between its leave and its join still hears a notice. */
2278
+ this.replacedUnsubscribe = null;
2279
+ /** Participant ids of this call a notice can still name: the current one, and any whose leave found it gone. */
2280
+ this.heldIds = new Set();
2281
+ /** Settles when the latest join has its participant id, or failed. */
2282
+ this.joinSettled = Promise.resolve();
2137
2283
  this.dataChannelUnsubscribe = null;
2138
2284
  /** An ICE restart is in flight until this fires: ICE going disconnected
2139
2285
  * again joins it, a network change replaces it. */
2140
2286
  this.restartTimer = null;
2141
2287
  this.networkUnsubscribe = null;
2142
- /** Running while the room's roster leaves this agent out: see `noticeRoster`. */
2288
+ /** Running while the room's roster leaves this session out: see `noticeRoster`. */
2143
2289
  this.unlistedTimer = null;
2144
2290
  this.neighbourhood = neighbourhood;
2145
2291
  this.neighbourhoodUrl = neighbourhoodUrl || "";
2146
2292
  this.roomId = roomId;
2147
2293
  this.agentDid = agentDid;
2294
+ this.deviceId = deviceId || defaultDeviceId();
2148
2295
  this.state = {
2149
2296
  topology: "sfu",
2150
2297
  roomId,
@@ -2173,8 +2320,13 @@ class SfuManager {
2173
2320
  }
2174
2321
  /**
2175
2322
  * Rebuild the call after its connection failed: leave, then join again
2176
- * on this executor. Leaving first matters: the executor still holds this
2177
- * DID's old session until it notices the connection died.
2323
+ * on this executor. Leaving first frees the old session's slot at once;
2324
+ * the join would replace it anyway, as it comes from this device.
2325
+ * Another tab's join can still replace the old session before the leave
2326
+ * lands: that notice stops the rebuild wherever it is, and a session its
2327
+ * join already got is left. A tab that missed the notice learns it from
2328
+ * the rejoin: the executor refuses the replaced session key (409), and
2329
+ * the manager stops as the notice would have stopped it, without retrying.
2178
2330
  *
2179
2331
  * Two budgets. A rebuild whose join works but whose connection fails
2180
2332
  * again counts once against `MAX_RECONNECTS`, reset when ICE connects.
@@ -2194,6 +2346,7 @@ class SfuManager {
2194
2346
  console.info(`SFU: connection failed, reconnecting (${this.reconnectAttempts}/${SfuManager.MAX_RECONNECTS})`);
2195
2347
  this.reconnecting = true;
2196
2348
  this.endRestart();
2349
+ const previous = this.state.participantId;
2197
2350
  try {
2198
2351
  const deadline = Date.now() + SfuManager.REJOIN_WINDOW_MS;
2199
2352
  for (let delay = 1000;; delay = Math.min(delay * 2, 10000)) {
@@ -2202,14 +2355,9 @@ class SfuManager {
2202
2355
  this.state.peerConnection.close();
2203
2356
  this.state.peerConnection = null;
2204
2357
  }
2205
- try {
2206
- await this.neighbourhood.sfuCallLeave(this.neighbourhoodUrl, this.roomId);
2207
- }
2208
- catch {
2209
- /* best-effort: the executor frees a dead session on its own */
2210
- }
2358
+ await this.leaveSession();
2211
2359
  if (generation !== this.generation)
2212
- return; // left meanwhile
2360
+ return; // left or replaced meanwhile
2213
2361
  this.resetParticipants();
2214
2362
  try {
2215
2363
  await this.join(stream);
@@ -2220,6 +2368,15 @@ class SfuManager {
2220
2368
  catch (e) {
2221
2369
  if (generation !== this.generation)
2222
2370
  return;
2371
+ if (e instanceof RpcError && e.status === 409) {
2372
+ this.stopReplaced({
2373
+ targetDid: this.agentDid,
2374
+ neighbourhoodUrl: this.neighbourhoodUrl,
2375
+ roomName: this.roomId,
2376
+ participantId: previous ?? "",
2377
+ });
2378
+ return;
2379
+ }
2223
2380
  if (Date.now() + delay > deadline) {
2224
2381
  console.error("SFU reconnect failed:", e);
2225
2382
  this.emit("error", e);
@@ -2243,22 +2400,30 @@ class SfuManager {
2243
2400
  * DTLS, tracks and the room slot stay. If the connection is not back
2244
2401
  * within `RESTART_TIMEOUT_MS`, the call is rebuilt. One restart at a
2245
2402
  * time: a call while one is in flight does nothing.
2403
+ *
2404
+ * The restart names this manager's session, the participant id its
2405
+ * current join returned: the executor restarts that session only, never
2406
+ * another device's of the same agent. A manager with no session — its
2407
+ * join not back yet, between a rebuild's leave and join, left, or
2408
+ * replaced by another tab — sends nothing.
2246
2409
  */
2247
2410
  restartIce(pc) {
2248
- if (this.restartTimer || this.reconnecting || this.state.peerConnection !== pc)
2411
+ const participantId = this.state.participantId;
2412
+ if (this.restartTimer || this.reconnecting || this.state.peerConnection !== pc || !participantId)
2249
2413
  return;
2414
+ const generation = this.generation;
2250
2415
  console.info("SFU: restarting ICE");
2251
2416
  this.restartTimer = setTimeout(() => {
2252
2417
  this.restartTimer = null;
2253
- if (this.state.peerConnection !== pc)
2418
+ if (generation !== this.generation || this.state.peerConnection !== pc)
2254
2419
  return;
2255
2420
  if (pc.iceConnectionState === "connected" || pc.iceConnectionState === "completed")
2256
2421
  return;
2257
2422
  void this.reconnect();
2258
2423
  }, SfuManager.RESTART_TIMEOUT_MS);
2259
- // A refusal (an executor without the method, or one that lost this
2260
- // session) leaves the decision to the timeout: a blip may still heal.
2261
- this.neighbourhood.sfuCallRestartIce(this.neighbourhoodUrl, this.roomId).catch((err) => {
2424
+ // A refusal (an executor that lost this session) leaves the decision
2425
+ // to the timeout: a blip may still heal.
2426
+ this.neighbourhood.sfuCallRestartIce(this.neighbourhoodUrl, this.roomId, participantId).catch((err) => {
2262
2427
  console.warn("SFU: ICE restart refused:", err);
2263
2428
  });
2264
2429
  }
@@ -2303,6 +2468,9 @@ class SfuManager {
2303
2468
  }
2304
2469
  /** Join the SFU call with simulcast support. */
2305
2470
  async join(localStream) {
2471
+ const generation = this.generation;
2472
+ if (!this.reconnecting)
2473
+ this.sessionKey = randomId();
2306
2474
  this.state.localStream = localStream;
2307
2475
  const pc = new RTCPeerConnection({ iceServers: this.iceServers });
2308
2476
  this.state.peerConnection = pc;
@@ -2376,11 +2544,11 @@ class SfuManager {
2376
2544
  if (this.state.peerConnection !== pc)
2377
2545
  return;
2378
2546
  const mid = event.transceiver?.mid;
2379
- const did = mid ? this.midToParticipant.get(mid) : undefined;
2547
+ const owner = mid ? this.midToParticipant.get(mid) : undefined;
2380
2548
  // Someone the roster said left stays gone: a late offer can still name them.
2381
- if (!did || did === this.agentDid || this.departed.has(did))
2549
+ if (!owner || owner.participantId === this.state.participantId || this.departed.has(owner.participantId))
2382
2550
  return;
2383
- const participant = this.ensureParticipant(did);
2551
+ const participant = this.ensureParticipant(owner.participantId, owner.did);
2384
2552
  participant.stream.addTrack(event.track);
2385
2553
  this.refreshKinds(participant);
2386
2554
  this.emit("stream-added", participant.stream, event.track);
@@ -2401,7 +2569,9 @@ class SfuManager {
2401
2569
  if (!event.candidate)
2402
2570
  return;
2403
2571
  if (joinComplete) {
2404
- this.neighbourhood.sfuAddIceCandidate(this.neighbourhoodUrl, this.roomId, event.candidate.candidate).catch((err) => {
2572
+ if (this.state.peerConnection !== pc || !this.state.participantId)
2573
+ return;
2574
+ this.neighbourhood.sfuAddIceCandidate(this.neighbourhoodUrl, this.roomId, this.state.participantId, event.candidate.candidate).catch((err) => {
2405
2575
  console.error("SFU: failed to trickle ICE candidate:", err);
2406
2576
  });
2407
2577
  }
@@ -2417,36 +2587,57 @@ class SfuManager {
2417
2587
  // they wait for it, then apply in order.
2418
2588
  let markJoined;
2419
2589
  const joined = new Promise((resolve) => { markJoined = resolve; });
2590
+ this.joinSettled = joined;
2420
2591
  this.subscribeServerEvents(pc, joined);
2421
2592
  let session;
2422
2593
  try {
2423
- session = await this.neighbourhood.sfuCallJoin(this.neighbourhoodUrl, this.roomId, sdpOffer);
2594
+ session = await this.neighbourhood.sfuCallJoin(this.neighbourhoodUrl, this.roomId, sdpOffer, this.deviceId, this.sessionKey);
2424
2595
  }
2425
2596
  catch (err) {
2426
2597
  // Settled either way: offers queued behind this join reach
2427
2598
  // `applyServerOffer`, which drops them for the abandoned connection.
2599
+ // The executor holds no session for it, so there is nothing to leave.
2428
2600
  markJoined();
2429
2601
  this.abandon(pc);
2430
2602
  throw err;
2431
2603
  }
2604
+ if (generation !== this.generation) {
2605
+ // Left or replaced while the join was out: the session it got is no one's.
2606
+ markJoined();
2607
+ this.abandon(pc);
2608
+ await this.neighbourhood
2609
+ .sfuCallLeave(this.neighbourhoodUrl, this.roomId, session.participantId)
2610
+ .catch((e) => console.warn("SFU: leaving the call failed:", e));
2611
+ return;
2612
+ }
2432
2613
  this.state.participantId = session.participantId;
2614
+ this.heldIds.add(session.participantId);
2433
2615
  try {
2434
2616
  const answer = JSON.parse(session.sdpAnswer);
2435
2617
  await pc.setRemoteDescription(new RTCSessionDescription(answer));
2436
2618
  }
2437
2619
  catch (err) {
2438
2620
  markJoined();
2621
+ // Replaced or left while the answer applied: that already closed the
2622
+ // connection and settled the session, so the join just ends.
2623
+ if (generation !== this.generation)
2624
+ return;
2625
+ // The executor holds a session this connection cannot use: leave it.
2439
2626
  this.abandon(pc);
2627
+ await this.leaveSession();
2440
2628
  throw err;
2441
2629
  }
2442
2630
  markJoined();
2443
2631
  // Who was in the room when this join landed (`participantId:did`).
2444
2632
  // The roster event keeps it current from here.
2445
- this.applyRoster(session.streamMapping.map((entry) => entry.slice(entry.indexOf(":") + 1)), false);
2633
+ this.applyRoster(session.streamMapping.map((entry) => {
2634
+ const at = entry.indexOf(":");
2635
+ return { participantId: entry.slice(0, at), agentDid: entry.slice(at + 1) };
2636
+ }), false);
2446
2637
  // Flush buffered trickle ICE candidates
2447
2638
  joinComplete = true;
2448
2639
  for (const candidate of pendingCandidates) {
2449
- this.neighbourhood.sfuAddIceCandidate(this.neighbourhoodUrl, this.roomId, candidate).catch((err) => {
2640
+ this.neighbourhood.sfuAddIceCandidate(this.neighbourhoodUrl, this.roomId, session.participantId, candidate).catch((err) => {
2450
2641
  console.error("SFU: failed to trickle buffered ICE candidate:", err);
2451
2642
  });
2452
2643
  }
@@ -2466,16 +2657,22 @@ class SfuManager {
2466
2657
  }
2467
2658
  }
2468
2659
  /**
2469
- * The room's roster no longer lists this agent while `pc` is the call's:
2470
- * the server has dropped this session, and ICE may not say so. In E6
2471
- * (CI job 53158) one of six sessions never started a rebuild after a
2472
- * 20 s outage the server had dropped it for. Rebuild once the roster has
2473
- * left this agent out for `UNLISTED_GRACE_MS`; a roster that lists it
2474
- * again in that time cancels, since one published just before this
2475
- * join landed can arrive after it.
2476
- */
2477
- noticeRoster(pc, dids) {
2478
- if (dids.includes(this.agentDid)) {
2660
+ * The room's roster no longer lists this session (its participant id)
2661
+ * while `pc` is the call's: the server has dropped this session, and ICE
2662
+ * may not say so. In E6 (CI job 53158) one of six sessions never started
2663
+ * a rebuild after a 20 s outage the server had dropped it for. The check
2664
+ * is per session, not per agent: another device of this agent keeps the
2665
+ * DID listed. Rebuild once the roster has left this session out for
2666
+ * `UNLISTED_GRACE_MS`; a roster that lists it again in that time
2667
+ * cancels, since one published just before this join landed can arrive
2668
+ * after it. A manager with no session (between leave and join, or
2669
+ * stopped because a later tab replaced it) starts no rebuild: `stop`
2670
+ * clears the timer and drops `pc`, so a replaced session never rejoins
2671
+ * and never takes the call back from the newer tab.
2672
+ */
2673
+ noticeRoster(pc, sessions) {
2674
+ const participantId = this.state.participantId;
2675
+ if (!participantId || sessions.some((s) => s.participantId === participantId)) {
2479
2676
  this.clearUnlistedTimer();
2480
2677
  return;
2481
2678
  }
@@ -2483,15 +2680,44 @@ class SfuManager {
2483
2680
  return;
2484
2681
  this.unlistedTimer = setTimeout(() => {
2485
2682
  this.unlistedTimer = null;
2486
- if (this.state.peerConnection !== pc)
2683
+ if (this.state.peerConnection !== pc || this.state.participantId !== participantId)
2487
2684
  return;
2488
2685
  console.info("SFU: the room no longer lists this session, rebuilding the call");
2489
2686
  void this.reconnect();
2490
2687
  }, SfuManager.UNLISTED_GRACE_MS);
2491
2688
  }
2492
- /** Undo a join that failed part way: its subscription and its connection. */
2689
+ /**
2690
+ * Leave this manager's session on the executor, if it has one, and forget
2691
+ * it. Only the participant id a join returned is ever left: a manager
2692
+ * that never joined, or whose join was refused, sends nothing, so it can
2693
+ * never end a session another tab of this agent is in.
2694
+ */
2695
+ async leaveSession() {
2696
+ const participantId = this.state.participantId;
2697
+ if (!participantId)
2698
+ return;
2699
+ this.state.participantId = null;
2700
+ // A session the leave found gone may have been replaced, its notice
2701
+ // still on the way. One the leave ended, or that it never reached, a
2702
+ // notice names only if this manager's own rejoin replaced it.
2703
+ let found = true;
2704
+ try {
2705
+ found = await this.neighbourhood.sfuCallLeave(this.neighbourhoodUrl, this.roomId, participantId);
2706
+ }
2707
+ catch (e) {
2708
+ /* best-effort: the executor frees a dead session on its own */
2709
+ console.warn("SFU: leaving the call failed:", e);
2710
+ }
2711
+ if (found)
2712
+ this.heldIds.delete(participantId);
2713
+ }
2714
+ /** Undo a join that failed part way: its subscriptions and its connection. */
2493
2715
  abandon(pc) {
2494
2716
  this.releaseServerEvents();
2717
+ if (this.heldIds.size === 0) {
2718
+ this.replacedUnsubscribe?.();
2719
+ this.replacedUnsubscribe = null;
2720
+ }
2495
2721
  pc.close();
2496
2722
  if (this.state.peerConnection === pc)
2497
2723
  this.state.peerConnection = null;
@@ -2511,12 +2737,18 @@ class SfuManager {
2511
2737
  // never drops to zero listeners in between.
2512
2738
  const previous = [this.renegotiationUnsubscribe, this.rosterUnsubscribe];
2513
2739
  const ours = (e) => e.neighbourhoodUrl === this.neighbourhoodUrl && e.roomName === this.roomId;
2740
+ // The executor sends this agent's offers and notices to each of its
2741
+ // sessions; only those naming this session's participant id are ours,
2742
+ // and that id is known once the join returns.
2514
2743
  this.renegotiationUnsubscribe = this.neighbourhood.subscribeSfuCallRenegotiationOffer(this.agentDid, (event) => {
2515
2744
  if (!ours(event))
2516
2745
  return;
2517
2746
  this.offerQueue = this.offerQueue
2518
2747
  .then(() => joined)
2519
- .then(() => this.applyServerOffer(pc, event));
2748
+ .then(() => {
2749
+ if (event.participantId === this.state.participantId)
2750
+ return this.applyServerOffer(pc, event);
2751
+ });
2520
2752
  });
2521
2753
  this.rosterUnsubscribe = this.neighbourhood.subscribeSfuRoomRoster((roster) => {
2522
2754
  if (!ours(roster) || this.state.peerConnection !== pc)
@@ -2528,6 +2760,17 @@ class SfuManager {
2528
2760
  this.noticeRoster(pc, roster.participants);
2529
2761
  });
2530
2762
  });
2763
+ // A notice can name the id the join in flight is about to return.
2764
+ this.replacedUnsubscribe ?? (this.replacedUnsubscribe = this.neighbourhood.subscribeSfuSessionReplaced((event) => {
2765
+ if (!ours(event))
2766
+ return;
2767
+ const stopIfHeld = () => {
2768
+ if (this.heldIds.has(event.participantId))
2769
+ this.stopReplaced(event);
2770
+ };
2771
+ stopIfHeld();
2772
+ void this.joinSettled.then(stopIfHeld);
2773
+ }));
2531
2774
  for (const unsubscribe of previous)
2532
2775
  unsubscribe?.();
2533
2776
  }
@@ -2537,12 +2780,12 @@ class SfuManager {
2537
2780
  return;
2538
2781
  // The mapping first: the tracks this offer adds arrive while it is applied.
2539
2782
  for (const entry of event.trackMapping ?? []) {
2540
- this.midToParticipant.set(entry.mid, entry.agentDid);
2783
+ this.midToParticipant.set(entry.mid, { participantId: entry.participantId, did: entry.agentDid });
2541
2784
  }
2542
2785
  try {
2543
2786
  await pc.setRemoteDescription(new RTCSessionDescription(JSON.parse(event.sdpOffer)));
2544
2787
  await pc.setLocalDescription(await pc.createAnswer());
2545
- await this.neighbourhood.sfuCallAnswerServerOffer(this.neighbourhoodUrl, event.roomName, JSON.stringify(pc.localDescription));
2788
+ await this.neighbourhood.sfuCallAnswerServerOffer(this.neighbourhoodUrl, event.roomName, event.participantId, JSON.stringify(pc.localDescription));
2546
2789
  this.answeredOffer = event.sdpOffer;
2547
2790
  }
2548
2791
  catch (err) {
@@ -2557,53 +2800,71 @@ class SfuManager {
2557
2800
  }
2558
2801
  }
2559
2802
  /**
2560
- * Make the participants match `dids`, the room's roster: everyone new
2803
+ * Make the participants match `sessions`, the room's roster: everyone new
2561
2804
  * joins, and — when `complete`, as the roster event is — everyone
2562
2805
  * missing leaves. The join's own roster can lag the room, so it only adds.
2806
+ * This session is never a participant; this agent's other devices are.
2563
2807
  */
2564
- applyRoster(dids, complete) {
2565
- const present = new Set(dids.filter((did) => did !== this.agentDid));
2566
- for (const did of present) {
2567
- this.departed.delete(did);
2568
- this.ensureParticipant(did);
2808
+ applyRoster(sessions, complete) {
2809
+ const present = sessions.filter((s) => s.participantId !== this.state.participantId);
2810
+ for (const { participantId, agentDid } of present) {
2811
+ this.departed.delete(participantId);
2812
+ this.ensureParticipant(participantId, agentDid);
2569
2813
  }
2570
2814
  if (!complete)
2571
2815
  return;
2572
- for (const [did, participant] of [...this.state.participants]) {
2573
- if (present.has(did))
2816
+ const listed = new Set(present.map((s) => s.participantId));
2817
+ for (const [participantId, participant] of [...this.state.participants]) {
2818
+ if (listed.has(participantId))
2574
2819
  continue;
2575
- this.state.participants.delete(did);
2576
- this.departed.add(did);
2820
+ this.state.participants.delete(participantId);
2821
+ this.departed.add(participantId);
2577
2822
  for (const [mid, owner] of this.midToParticipant) {
2578
- if (owner === did)
2823
+ if (owner.participantId === participantId)
2579
2824
  this.midToParticipant.delete(mid);
2580
2825
  }
2581
2826
  this.emit("participant-left", participant);
2582
2827
  }
2583
2828
  }
2584
- /** The participant for `did`, joining them to the call if they are new. */
2585
- ensureParticipant(did) {
2586
- let participant = this.state.participants.get(did);
2829
+ /** The participant for session `participantId` of `did`, joining them to the call if they are new. */
2830
+ ensureParticipant(participantId, did) {
2831
+ let participant = this.state.participants.get(participantId);
2587
2832
  if (!participant) {
2588
2833
  participant = {
2834
+ participantId,
2589
2835
  did,
2590
2836
  stream: new MediaStream(),
2591
2837
  hasAudio: false,
2592
2838
  hasVideo: false,
2593
2839
  isActiveSpeaker: false,
2594
2840
  };
2595
- this.state.participants.set(did, participant);
2841
+ this.state.participants.set(participantId, participant);
2596
2842
  this.emit("participant-joined", participant);
2597
2843
  }
2598
2844
  return participant;
2599
2845
  }
2600
- refreshKinds(participant) {
2601
- participant.hasAudio = participant.stream.getAudioTracks().length > 0;
2602
- participant.hasVideo = participant.stream.getVideoTracks().length > 0;
2846
+ /**
2847
+ * A later join from this device replaced a session of this call: the
2848
+ * executor has already dropped it. Stop as `leave` does, but never
2849
+ * rejoin — the other tab has the call now — and say so with `replaced`.
2850
+ * A session this manager got since (a reconnect's) is left.
2851
+ */
2852
+ stopReplaced(event) {
2853
+ console.info("SFU: another tab on this device joined the call; this one stops");
2854
+ if (this.state.participantId === event.participantId)
2855
+ this.state.participantId = null;
2856
+ this.stop();
2857
+ void this.leaveSession();
2858
+ this.resetParticipants();
2859
+ this.emit("replaced", event);
2603
2860
  }
2604
- async leave() {
2861
+ /** End this manager's call locally: no reconnect in flight continues, nothing is sent. */
2862
+ stop() {
2605
2863
  this.generation++;
2606
2864
  this.releaseServerEvents();
2865
+ this.replacedUnsubscribe?.();
2866
+ this.replacedUnsubscribe = null;
2867
+ this.heldIds.clear();
2607
2868
  this.endRestart();
2608
2869
  this.networkUnsubscribe?.();
2609
2870
  this.networkUnsubscribe = null;
@@ -2623,12 +2884,16 @@ class SfuManager {
2623
2884
  this.state.peerConnection.close();
2624
2885
  this.state.peerConnection = null;
2625
2886
  }
2626
- try {
2627
- await this.neighbourhood.sfuCallLeave(this.neighbourhoodUrl, this.roomId);
2628
- }
2629
- catch (e) {
2630
- console.error("Error leaving SFU call:", e);
2631
- }
2887
+ this.state.localStream = null;
2888
+ }
2889
+ refreshKinds(participant) {
2890
+ participant.hasAudio = participant.stream.getAudioTracks().length > 0;
2891
+ participant.hasVideo = participant.stream.getVideoTracks().length > 0;
2892
+ }
2893
+ /** End the call: locally, and on the executor if this manager joined. */
2894
+ async leave() {
2895
+ this.stop();
2896
+ await this.leaveSession();
2632
2897
  this.resetParticipants();
2633
2898
  }
2634
2899
  /** Forget the call's participants, telling listeners each one left. */
@@ -2637,7 +2902,6 @@ class SfuManager {
2637
2902
  this.emit("participant-left", participant);
2638
2903
  }
2639
2904
  this.state.participants.clear();
2640
- this.state.participantId = null;
2641
2905
  this.midToParticipant.clear();
2642
2906
  this.departed.clear();
2643
2907
  }
@@ -2648,7 +2912,7 @@ class SfuManager {
2648
2912
  return;
2649
2913
  }
2650
2914
  try {
2651
- await this.neighbourhood.sfuCallSetQualityPreference(this.neighbourhoodUrl, this.roomId, preference);
2915
+ await this.neighbourhood.sfuCallSetQualityPreference(this.neighbourhoodUrl, this.roomId, this.state.participantId, preference);
2652
2916
  }
2653
2917
  catch (e) {
2654
2918
  console.error("Failed to set quality preference:", e);
@@ -2687,7 +2951,7 @@ class SfuManager {
2687
2951
  return;
2688
2952
  }
2689
2953
  try {
2690
- await this.neighbourhood.sfuSendData(this.neighbourhoodUrl, this.roomId, channelLabel, data, binary);
2954
+ await this.neighbourhood.sfuSendData(this.neighbourhoodUrl, this.roomId, this.state.participantId, channelLabel, data, binary);
2691
2955
  }
2692
2956
  catch (e) {
2693
2957
  console.error("SFU: sendData failed:", e);
@@ -2695,7 +2959,8 @@ class SfuManager {
2695
2959
  }
2696
2960
  }
2697
2961
  /**
2698
- * Subscribe to data channel messages from other participants.
2962
+ * Subscribe to data channel messages from other participants — this
2963
+ * agent's other devices included, this session's own messages not.
2699
2964
  * Returns an unsubscribe function. Only one subscription per
2700
2965
  * manager instance — a second call replaces the first.
2701
2966
  */
@@ -2709,8 +2974,11 @@ class SfuManager {
2709
2974
  /* swallow */
2710
2975
  }
2711
2976
  }
2712
- this.dataChannelUnsubscribe =
2713
- this.neighbourhood.subscribeSfuDataChannel(callback);
2977
+ this.dataChannelUnsubscribe = this.neighbourhood.subscribeSfuDataChannel((message) => {
2978
+ if (message.senderParticipantId && message.senderParticipantId === this.state.participantId)
2979
+ return;
2980
+ callback(message);
2981
+ });
2714
2982
  return () => {
2715
2983
  if (this.dataChannelUnsubscribe) {
2716
2984
  try {
@@ -2739,7 +3007,7 @@ SfuManager.MAX_RECONNECTS = 3;
2739
3007
  SfuManager.REJOIN_WINDOW_MS = 120000;
2740
3008
  /** How long an ICE restart has to bring the connection back before a rebuild. */
2741
3009
  SfuManager.RESTART_TIMEOUT_MS = 5000;
2742
- /** How long the roster may leave this agent out before the call is rebuilt. */
3010
+ /** How long the roster may leave this session out before the call is rebuilt. */
2743
3011
  SfuManager.UNLISTED_GRACE_MS = 3000;
2744
3012
 
2745
3013
  /**
@@ -2876,9 +3144,37 @@ function parseCallMessage(payload) {
2876
3144
  // ── Signalling channel ──────────────────────────────────────────────
2877
3145
  const RTC_PREDICATE = "ad4m://session/rtc";
2878
3146
  const TARGET_ALL = "*";
3147
+ /**
3148
+ * A mesh peer: one agent on one device. An agent calling from two devices is
3149
+ * two peers, each with its own connection to everyone else, so neither device's
3150
+ * media or teardown can stand in for the other's.
3151
+ */
3152
+ function meshPeerId(did, device) {
3153
+ if (!isMeshDevice(device))
3154
+ throw new Error(`mesh: device id must be non-empty and without '#': ${JSON.stringify(device)}`);
3155
+ return `${did}#${device}`;
3156
+ }
3157
+ /** A device id a mesh peer id can carry: `#` would move the split in {@link agentOfMeshPeer}. */
3158
+ function isMeshDevice(device) {
3159
+ return typeof device === "string" && device.length > 0 && !device.includes("#");
3160
+ }
3161
+ /** The agent a mesh peer id belongs to. */
3162
+ function agentOfMeshPeer(peerId) {
3163
+ const at = peerId.lastIndexOf("#");
3164
+ return at === -1 ? peerId : peerId.slice(0, at);
3165
+ }
2879
3166
  /**
2880
3167
  * Bridge NeighbourhoodProxy telepresence to the SignallingChannel
2881
- * the mesh consumes.
3168
+ * the mesh consumes, as the peer `selfDid` on `selfDevice`.
3169
+ *
3170
+ * ## Peers are devices
3171
+ *
3172
+ * The sender a message reports is a {@link meshPeerId}: the link's author,
3173
+ * which the executor verified, and the device the author's payload names. A
3174
+ * device is only the author's own claim, so it can tell this agent's devices
3175
+ * apart but never speak for another agent. Only this device's own echo is
3176
+ * dropped: a broadcast from another device of this agent — the executor hands
3177
+ * one to every client of the agent — is a peer like any other.
2882
3178
  *
2883
3179
  * ## Why unicast runs emulated over broadcast
2884
3180
  *
@@ -2888,9 +3184,11 @@ const TARGET_ALL = "*";
2888
3184
  * receivers drop anything not addressed to them. That provides
2889
3185
  * **addressing, not privacy** — every peer still receives the payload.
2890
3186
  */
2891
- function createTelepresenceChannel(proxy, selfDid) {
3187
+ function createTelepresenceChannel(proxy, selfDid, selfDevice) {
3188
+ const self = meshPeerId(selfDid, selfDevice);
2892
3189
  const resultListeners = new Set();
2893
3190
  let subscribed = Promise.resolve();
3191
+ let warnedNoDevice = false;
2894
3192
  const report = (result) => {
2895
3193
  for (const cb of resultListeners) {
2896
3194
  try {
@@ -2910,7 +3208,7 @@ function createTelepresenceChannel(proxy, selfDid) {
2910
3208
  try {
2911
3209
  sent = proxy.sendBroadcastU({
2912
3210
  links: [{
2913
- source: JSON.stringify(payload),
3211
+ source: JSON.stringify({ device: selfDevice, message: payload }),
2914
3212
  predicate: RTC_PREDICATE,
2915
3213
  target: to?.agentId ?? TARGET_ALL,
2916
3214
  }],
@@ -2947,10 +3245,7 @@ function createTelepresenceChannel(proxy, selfDid) {
2947
3245
  if (typeof predicate !== "string" || predicate !== RTC_PREDICATE)
2948
3246
  return;
2949
3247
  // Emulated unicast: drop messages addressed to someone else
2950
- if (target && target !== TARGET_ALL && target !== selfDid)
2951
- return;
2952
- // Drop our own echo
2953
- if (link.author === selfDid)
3248
+ if (target && target !== TARGET_ALL && target !== self)
2954
3249
  return;
2955
3250
  let parsed;
2956
3251
  try {
@@ -2959,7 +3254,22 @@ function createTelepresenceChannel(proxy, selfDid) {
2959
3254
  catch {
2960
3255
  return;
2961
3256
  }
2962
- cb(link.author, parsed);
3257
+ if (typeof parsed !== "object" || parsed === null)
3258
+ return;
3259
+ const { device, message } = parsed;
3260
+ if (!isMeshDevice(device)) {
3261
+ // An SDK from before peers were devices sends none: say so once, or a mixed call just looks empty.
3262
+ if (device === undefined && !warnedNoDevice) {
3263
+ warnedNoDevice = true;
3264
+ console.warn(`mesh: ${link.author} sends no device id (an older SDK); its mesh messages are ignored`);
3265
+ }
3266
+ return;
3267
+ }
3268
+ const from = meshPeerId(link.author, device);
3269
+ // Drop this device's own echo, and only that.
3270
+ if (from === self)
3271
+ return;
3272
+ cb(from, message);
2963
3273
  };
2964
3274
  subscribed = proxy.addSignalHandler(handler).catch((err) => {
2965
3275
  console.warn("mesh: signal handler registration failed — inbound traffic will get missed:", err);
@@ -3158,6 +3468,9 @@ class MeshManager {
3158
3468
  });
3159
3469
  // A session announces itself once `join` returns; peers offer at once.
3160
3470
  await this.channel.listening?.();
3471
+ // Left or destroyed while the channel came up: start nothing.
3472
+ if (this.closed)
3473
+ return;
3161
3474
  /*
3162
3475
  * Spend the transport's first-send cost on something that does not
3163
3476
  * matter. The first broadcast on a freshly joined neighbourhood has
@@ -3317,6 +3630,8 @@ class MeshManager {
3317
3630
  handleData(from, message) {
3318
3631
  const msg = {
3319
3632
  senderDid: from,
3633
+ // The mesh keys its peers by DID: one session per agent.
3634
+ senderParticipantId: from,
3320
3635
  neighbourhoodUrl: "",
3321
3636
  roomName: this.callId,
3322
3637
  channelLabel: message.label,
@@ -3930,15 +4245,47 @@ class MeshManager {
3930
4245
 
3931
4246
  /**
3932
4247
  * Call-presence predicate. When the session joins, it publishes an
3933
- * online-status link with this predicate and the room id as target.
3934
- * Other agents polling `onlineAgents()` use this to discover the
3935
- * roster without a join message.
4248
+ * online-status link with this predicate, its mesh peer id as source and
4249
+ * the room id as target. Other agents polling `onlineAgents()` use this
4250
+ * to discover the roster without a join message; one agent's devices each
4251
+ * add a link of their own to the agent's one status.
3936
4252
  */
3937
4253
  const CALL_PRESENCE_PREDICATE = "ad4m://session/in-call";
3938
4254
  /** How often (ms) the mesh session polls `onlineAgents` for roster changes. */
3939
4255
  const ROSTER_POLL_INTERVAL_MS = 3000;
4256
+ /**
4257
+ * The mesh peer a call-presence link of `did` announces, or `null`. A link
4258
+ * counts only for a peer of the agent whose status carries it, so no agent
4259
+ * can place another in a call.
4260
+ */
4261
+ function presencePeer(did, link, roomId) {
4262
+ if (link?.predicate !== CALL_PRESENCE_PREDICATE || link.target !== roomId)
4263
+ return null;
4264
+ const source = link.source;
4265
+ if (typeof source !== "string" || source === did || agentOfMeshPeer(source) !== did)
4266
+ return null;
4267
+ return source;
4268
+ }
4269
+ /**
4270
+ * Where a mesh session hears that this device joined the same call again,
4271
+ * from another tab. `BroadcastChannel` reaches every tab of one browser
4272
+ * profile — the same reach as the `localStorage` the device id lives in.
4273
+ */
4274
+ function sameDeviceChannel(agentDid, device, roomId) {
4275
+ const Channel = globalThis.BroadcastChannel;
4276
+ if (typeof Channel !== "function")
4277
+ return null;
4278
+ try {
4279
+ return new Channel(`ad4m-call:${agentDid}:${device}:${roomId}`);
4280
+ }
4281
+ catch {
4282
+ return null;
4283
+ }
4284
+ }
3940
4285
  function createSession(config) {
3941
- const { api, roomId, agentDid, neighbourhoodUrl, topology, sfuConfig, iceServers, channel, setOnlineStatus, ownOnlineStatus, onlineAgents, localSfuStatus, sfuServesAllMembers, } = config;
4286
+ const { api, roomId, agentDid, neighbourhoodUrl, topology, sfuConfig, iceServers, deviceId, channel, setOnlineStatus, ownOnlineStatus, onlineAgents, localSfuStatus, sfuServesAllMembers, } = config;
4287
+ const device = deviceId || defaultDeviceId();
4288
+ const selfPeer = meshPeerId(agentDid, device);
3942
4289
  let state = "idle";
3943
4290
  let sfuManager = null;
3944
4291
  let meshManager = null;
@@ -3951,6 +4298,8 @@ function createSession(config) {
3951
4298
  const trackListeners = [];
3952
4299
  const dataListeners = [];
3953
4300
  let dataUnsubscribe = null;
4301
+ /** The mesh call's line to this device's other tabs; see {@link sameDeviceChannel}. */
4302
+ let sameDevice = null;
3954
4303
  function emit(event, ...args) {
3955
4304
  const cbs = callbacks.get(event);
3956
4305
  if (cbs)
@@ -3961,6 +4310,13 @@ function createSession(config) {
3961
4310
  state = next;
3962
4311
  emit("state-changed", next);
3963
4312
  }
4313
+ /** `destroy()` ran: a join still resolving must not go on to reach the executor. */
4314
+ /** Set when `destroy()` starts, before its awaits: a join that resumes
4315
+ * while the session closes must not go on. */
4316
+ let destroying = false;
4317
+ function destroyed() {
4318
+ return destroying || state === "closed";
4319
+ }
3964
4320
  /**
3965
4321
  * Resolve the effective topology.
3966
4322
  *
@@ -3994,7 +4350,7 @@ function createSession(config) {
3994
4350
  * leaving restores if the status cannot be read then. */
3995
4351
  let statusBeforeCall = [];
3996
4352
  let announced = false;
3997
- /** This agent's status links, without this call's presence link. */
4353
+ /** This agent's status links, without this device's presence link for this call. */
3998
4354
  async function ownLinksWithoutCall() {
3999
4355
  const status = ownOnlineStatus ? await ownOnlineStatus() : null;
4000
4356
  const links = [];
@@ -4002,7 +4358,7 @@ function createSession(config) {
4002
4358
  const l = link.data;
4003
4359
  if (!l?.source || l.target === undefined)
4004
4360
  continue;
4005
- if (l.predicate === CALL_PRESENCE_PREDICATE && l.target === roomId)
4361
+ if (presencePeer(agentDid, l, roomId) === selfPeer)
4006
4362
  continue;
4007
4363
  links.push({ source: l.source, target: l.target, ...(l.predicate ? { predicate: l.predicate } : {}) });
4008
4364
  }
@@ -4020,7 +4376,7 @@ function createSession(config) {
4020
4376
  console.warn("session: reading own status failed:", err);
4021
4377
  return [];
4022
4378
  });
4023
- const presence = { source: agentDid, predicate: CALL_PRESENCE_PREDICATE, target: roomId };
4379
+ const presence = { source: selfPeer, predicate: CALL_PRESENCE_PREDICATE, target: roomId };
4024
4380
  await setOnlineStatus({ links: [...statusBeforeCall, presence] });
4025
4381
  announced = true;
4026
4382
  }
@@ -4047,10 +4403,11 @@ function createSession(config) {
4047
4403
  /**
4048
4404
  * Poll online agents and reconcile the mesh roster.
4049
4405
  *
4050
- * Agents in the same call carry a link with predicate
4051
- * `CALL_PRESENCE_PREDICATE` and target matching the room id.
4052
- * The poll reads the full online-agents list, filters to those
4053
- * links, and passes the resulting DID set to `mesh.setRoster()`.
4406
+ * Each device in the call carries a link with predicate
4407
+ * `CALL_PRESENCE_PREDICATE`, its peer id as source and the room id as
4408
+ * target, in its agent's status. The poll reads other agents' statuses
4409
+ * from the online-agents list and this agent's own — its other devices —
4410
+ * from `ownOnlineStatus`, and passes the peers to `mesh.setRoster()`.
4054
4411
  * That function opens connections to new arrivals and tears down
4055
4412
  * connections to departed peers.
4056
4413
  */
@@ -4061,25 +4418,28 @@ function createSession(config) {
4061
4418
  polling = true;
4062
4419
  try {
4063
4420
  const agents = await onlineAgents();
4421
+ const own = ownOnlineStatus ? await ownOnlineStatus() : null;
4064
4422
  // The session left while the poll was in flight.
4065
4423
  if (meshManager !== mesh)
4066
4424
  return;
4067
- const inCall = [];
4068
- for (const agent of agents) {
4069
- if (agent.did === agentDid)
4070
- continue;
4071
- // Each agent's status is a signed perspective: its links
4072
- // sit under `data`. Check for the call-presence link
4073
- // matching this room.
4074
- for (const link of agent.status?.data?.links ?? []) {
4075
- const l = link.data;
4076
- if (l?.predicate === CALL_PRESENCE_PREDICATE && l.target === roomId) {
4077
- inCall.push(agent.did);
4078
- break;
4079
- }
4425
+ const inCall = new Set();
4426
+ const collect = (did, links) => {
4427
+ for (const link of links ?? []) {
4428
+ const peer = presencePeer(did, link.data, roomId);
4429
+ if (peer && peer !== selfPeer)
4430
+ inCall.add(peer);
4080
4431
  }
4432
+ };
4433
+ // Each agent's status is a signed perspective: its links sit
4434
+ // under `data`. Whether an executor lists the caller among the
4435
+ // online agents varies, so this agent's own status is read here
4436
+ // from where it was set, never from the list.
4437
+ for (const agent of agents) {
4438
+ if (agent.did !== agentDid)
4439
+ collect(agent.did, agent.status?.data?.links);
4081
4440
  }
4082
- mesh.setRoster(inCall);
4441
+ collect(agentDid, own?.data?.links);
4442
+ mesh.setRoster([...inCall]);
4083
4443
  }
4084
4444
  catch (err) {
4085
4445
  console.warn("session: roster poll failed:", err);
@@ -4101,9 +4461,13 @@ function createSession(config) {
4101
4461
  }
4102
4462
  // ── Mesh wiring helpers ─────────────────────────────────────────
4103
4463
  function wireMeshEvents(mesh) {
4104
- for (const event of ["participant-joined", "participant-left", "participant-updated", "peer-state", "peer-recovery", "error"]) {
4464
+ for (const event of ["peer-state", "peer-recovery", "error"]) {
4105
4465
  mesh.on(event, (...args) => emit(event, ...args));
4106
4466
  }
4467
+ // As the SFU path reports them: the session (here, the device) and the agent it belongs to.
4468
+ for (const event of ["participant-joined", "participant-left", "participant-updated"]) {
4469
+ mesh.on(event, (p) => emit(event, { ...p, participantId: p.did, did: agentOfMeshPeer(p.did) }));
4470
+ }
4107
4471
  mesh.on("stream-added", (stream, track) => {
4108
4472
  emit("stream-added", stream, track);
4109
4473
  for (const cb of trackListeners)
@@ -4113,19 +4477,83 @@ function createSession(config) {
4113
4477
  emit("stream-removed", stream, track);
4114
4478
  });
4115
4479
  }
4480
+ /**
4481
+ * The mesh another tab of this device took over. A destroy also lets the mesh go, so only
4482
+ * this tells a join that its call moved on, and that the presence link is no longer its own.
4483
+ */
4484
+ let replacedMesh = null;
4485
+ /**
4486
+ * Listen for this device joining the same mesh call from another tab,
4487
+ * and tell any tab already in it. Both tabs are one peer, so only one
4488
+ * can hold the call: the earlier lets go, without withdrawing the
4489
+ * presence link the two share, and says `replaced`.
4490
+ */
4491
+ function claimDevice(mesh) {
4492
+ sameDevice = sameDeviceChannel(agentDid, device, roomId);
4493
+ if (!sameDevice)
4494
+ return;
4495
+ const channel = sameDevice;
4496
+ channel.onmessage = (event) => {
4497
+ if (meshManager !== mesh || event.data?.joined !== true)
4498
+ return;
4499
+ replacedMesh = mesh;
4500
+ releaseDevice();
4501
+ stopRosterPolling();
4502
+ if (dataUnsubscribe) {
4503
+ dataUnsubscribe();
4504
+ dataUnsubscribe = null;
4505
+ }
4506
+ meshManager = null;
4507
+ announced = false;
4508
+ void mesh.leave();
4509
+ // Idle before listeners hear it: one may join again at once.
4510
+ setState("idle");
4511
+ emit("replaced", { targetDid: agentDid, neighbourhoodUrl, roomName: roomId, participantId: selfPeer });
4512
+ };
4513
+ channel.postMessage({ joined: true });
4514
+ }
4515
+ function releaseDevice() {
4516
+ if (!sameDevice)
4517
+ return;
4518
+ sameDevice.onmessage = null;
4519
+ sameDevice.close();
4520
+ sameDevice = null;
4521
+ }
4116
4522
  // ── SFU wiring helpers ──────────────────────────────────────────
4117
4523
  function wireSfuEvents(sfu) {
4524
+ // A manager the session let go of (replaced, or left) may still settle a call it
4525
+ // made before: none of its events reach the session's listeners.
4526
+ const current = () => sfuManager === sfu;
4118
4527
  for (const event of ["topology-changed", "participant-joined", "participant-left", "active-speaker", "error"]) {
4119
- sfu.on(event, (...args) => emit(event, ...args));
4528
+ sfu.on(event, (...args) => { if (current())
4529
+ emit(event, ...args); });
4120
4530
  }
4121
4531
  sfu.on("stream-added", (stream, track) => {
4532
+ if (!current())
4533
+ return;
4122
4534
  emit("stream-added", stream, track);
4123
4535
  for (const cb of trackListeners)
4124
4536
  cb(stream, track);
4125
4537
  });
4126
4538
  sfu.on("stream-removed", (stream, track) => {
4539
+ if (!current())
4540
+ return;
4127
4541
  emit("stream-removed", stream, track);
4128
4542
  });
4543
+ // Another tab on this device took the call over. The manager has stopped
4544
+ // and will not rejoin; the session is idle and may join again.
4545
+ sfu.on("replaced", (event) => {
4546
+ if (sfuManager !== sfu)
4547
+ return;
4548
+ if (dataUnsubscribe) {
4549
+ dataUnsubscribe();
4550
+ dataUnsubscribe = null;
4551
+ }
4552
+ sfuManager = null;
4553
+ // Idle before listeners hear it: one may join again at once.
4554
+ setState("idle");
4555
+ emit("replaced", event);
4556
+ });
4129
4557
  }
4130
4558
  // ── Session object ──────────────────────────────────────────────
4131
4559
  const session = {
@@ -4136,6 +4564,8 @@ function createSession(config) {
4136
4564
  throw new Error("Session already active");
4137
4565
  setState("joining");
4138
4566
  const topo = await resolveTopology();
4567
+ if (destroyed())
4568
+ throw new Error("Session destroyed");
4139
4569
  if (topo === "mesh") {
4140
4570
  if (!channel) {
4141
4571
  throw new Error("Mesh topology requires a signalling channel — " +
@@ -4166,7 +4596,7 @@ function createSession(config) {
4166
4596
  const mesh = new MeshManager({
4167
4597
  channel,
4168
4598
  callId: roomId,
4169
- selfId: agentDid,
4599
+ selfId: selfPeer,
4170
4600
  ...(meshIce.length > 0 ? { iceServers: meshIce } : {}),
4171
4601
  onNetworkChange: (cb) => api.onNetworkChange(cb),
4172
4602
  checkConnection: () => api.checkConnection(),
@@ -4177,11 +4607,29 @@ function createSession(config) {
4177
4607
  for (const cb of dataListeners)
4178
4608
  cb(msg);
4179
4609
  });
4610
+ claimDevice(mesh);
4180
4611
  await mesh.join(localStream);
4612
+ // Replaced while joining: the session is idle again.
4613
+ if (replacedMesh === mesh)
4614
+ return;
4615
+ // Destroyed while the mesh joined: destroy() already let the
4616
+ // mesh go and found nothing to leave.
4617
+ if (destroyed())
4618
+ throw new Error("Session destroyed");
4181
4619
  // Announce this agent's presence in the call, then
4182
4620
  // start polling so the mesh reconciles connections
4183
4621
  // against whoever else the roster contains.
4184
4622
  await announceCallPresence();
4623
+ // Replaced while announcing, destroyed or not: the link stays,
4624
+ // for the tab that took over.
4625
+ if (replacedMesh === mesh) {
4626
+ announced = false;
4627
+ return;
4628
+ }
4629
+ if (destroyed()) {
4630
+ await withdrawCallPresence();
4631
+ throw new Error("Session destroyed");
4632
+ }
4185
4633
  startRosterPolling();
4186
4634
  emit("topology-changed", "mesh");
4187
4635
  setState("active");
@@ -4191,13 +4639,19 @@ function createSession(config) {
4191
4639
  const iceConfig = iceServers && iceServers.length > 0
4192
4640
  ? { servers: iceServers.map(s => ({ urls: s.urls, ...(s.username ? { username: s.username } : {}), ...(s.credential ? { credential: s.credential } : {}) })) }
4193
4641
  : undefined;
4194
- sfuManager = new SfuManager(api, roomId, agentDid, neighbourhoodUrl, iceConfig, sfuConfig);
4195
- wireSfuEvents(sfuManager);
4196
- dataUnsubscribe = sfuManager.subscribeDataChannel((msg) => {
4642
+ const manager = new SfuManager(api, roomId, agentDid, neighbourhoodUrl, iceConfig, sfuConfig, device);
4643
+ sfuManager = manager;
4644
+ wireSfuEvents(manager);
4645
+ dataUnsubscribe = manager.subscribeDataChannel((msg) => {
4197
4646
  for (const cb of dataListeners)
4198
4647
  cb(msg);
4199
4648
  });
4200
- await sfuManager.join(localStream);
4649
+ await manager.join(localStream);
4650
+ if (destroyed())
4651
+ throw new Error("Session destroyed");
4652
+ // Replaced while joining: the session is idle again.
4653
+ if (sfuManager !== manager)
4654
+ return;
4201
4655
  emit("topology-changed", "sfu");
4202
4656
  setState("active");
4203
4657
  },
@@ -4206,6 +4660,7 @@ function createSession(config) {
4206
4660
  return;
4207
4661
  setState("leaving");
4208
4662
  stopRosterPolling();
4663
+ releaseDevice();
4209
4664
  await withdrawCallPresence();
4210
4665
  if (dataUnsubscribe) {
4211
4666
  dataUnsubscribe();
@@ -4224,7 +4679,8 @@ function createSession(config) {
4224
4679
  get participants() {
4225
4680
  if (meshManager) {
4226
4681
  return meshManager.getParticipants().map(p => ({
4227
- agentDid: p.did,
4682
+ participantId: p.did,
4683
+ agentDid: agentOfMeshPeer(p.did),
4228
4684
  stream: p.stream,
4229
4685
  hasAudio: p.hasAudio,
4230
4686
  hasVideo: p.hasVideo,
@@ -4233,6 +4689,7 @@ function createSession(config) {
4233
4689
  }
4234
4690
  if (sfuManager) {
4235
4691
  return sfuManager.getParticipants().map(p => ({
4692
+ participantId: p.participantId,
4236
4693
  agentDid: p.did,
4237
4694
  stream: p.stream,
4238
4695
  hasAudio: p.hasAudio,
@@ -4317,12 +4774,14 @@ function createSession(config) {
4317
4774
  }
4318
4775
  },
4319
4776
  async destroy() {
4777
+ destroying = true;
4320
4778
  // Capture refs before leave() nulls them
4321
4779
  const mesh = meshManager;
4322
4780
  const sfu = sfuManager;
4323
4781
  if (state === "active" || state === "joining")
4324
4782
  await session.leave();
4325
4783
  stopRosterPolling();
4784
+ releaseDevice();
4326
4785
  if (mesh) {
4327
4786
  await mesh.destroy();
4328
4787
  }
@@ -4454,6 +4913,7 @@ class NeighbourhoodProxy {
4454
4913
  }
4455
4914
  }
4456
4915
  const proxy = this;
4916
+ const deviceId = options?.deviceId || defaultDeviceId();
4457
4917
  const session = createSession({
4458
4918
  api: __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f"),
4459
4919
  roomId: roomName,
@@ -4462,12 +4922,13 @@ class NeighbourhoodProxy {
4462
4922
  topology: options?.topology ?? "auto",
4463
4923
  sfuConfig: options?.sfuConfig,
4464
4924
  iceServers: options?.iceServers,
4925
+ deviceId,
4465
4926
  localSfuStatus: __classPrivateFieldGet$a(this, _NeighbourhoodProxy_sfuStatusCache, "f") ?? undefined,
4466
4927
  sfuServesAllMembers: () => __classPrivateFieldGet$a(proxy, _NeighbourhoodProxy_client, "f").sfuServesAllMembers(__classPrivateFieldGet$a(proxy, _NeighbourhoodProxy_pID, "f")),
4467
4928
  // Mesh needs a signalling channel and presence callbacks.
4468
4929
  // SFU ignores these — they remain unused when the resolved
4469
4930
  // topology selects the SFU path.
4470
- channel: createTelepresenceChannel(proxy, __classPrivateFieldGet$a(proxy, _NeighbourhoodProxy_agentDid, "f")),
4931
+ channel: createTelepresenceChannel(proxy, __classPrivateFieldGet$a(proxy, _NeighbourhoodProxy_agentDid, "f"), deviceId),
4471
4932
  ownOnlineStatus: () => proxy.ownOnlineStatus(),
4472
4933
  setOnlineStatus: (status) => proxy.setOnlineStatusU(status),
4473
4934
  onlineAgents: () => proxy.onlineAgents(),
@@ -4509,17 +4970,27 @@ class NeighbourhoodProxy {
4509
4970
  async sfuListRooms() {
4510
4971
  return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuListRooms();
4511
4972
  }
4512
- async callJoin(neighbourhoodUrl, roomName, sdpOffer) {
4513
- return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallJoin(neighbourhoodUrl, roomName, sdpOffer);
4973
+ /** Join from `deviceId`: a join from the same device replaces this agent's session there. */
4974
+ async callJoin(neighbourhoodUrl, roomName, sdpOffer, deviceId, sessionKey) {
4975
+ return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallJoin(neighbourhoodUrl, roomName, sdpOffer, deviceId, sessionKey);
4514
4976
  }
4515
- async callLeave(neighbourhoodUrl, roomName) {
4516
- return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallLeave(neighbourhoodUrl, roomName);
4977
+ /** Leave the session `participantId` (the join's). */
4978
+ async callLeave(neighbourhoodUrl, roomName, participantId) {
4979
+ return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallLeave(neighbourhoodUrl, roomName, participantId);
4517
4980
  }
4518
- async callSetQualityPreference(neighbourhoodUrl, roomName, preference) {
4519
- return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallSetQualityPreference(neighbourhoodUrl, roomName, preference);
4981
+ async callSetQualityPreference(neighbourhoodUrl, roomName, participantId, preference) {
4982
+ return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallSetQualityPreference(neighbourhoodUrl, roomName, participantId, preference);
4520
4983
  }
4521
- async callAnswerServerOffer(neighbourhoodUrl, roomName, sdpAnswer) {
4522
- return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallAnswerServerOffer(neighbourhoodUrl, roomName, sdpAnswer);
4984
+ async callAnswerServerOffer(neighbourhoodUrl, roomName, participantId, sdpAnswer) {
4985
+ return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallAnswerServerOffer(neighbourhoodUrl, roomName, participantId, sdpAnswer);
4986
+ }
4987
+ /**
4988
+ * Subscribe to the executor's notices that a session of this agent was
4989
+ * replaced by a later join from the same device. Returns an unsubscribe
4990
+ * function.
4991
+ */
4992
+ subscribeSessionReplaced(callback) {
4993
+ return __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").subscribeSfuSessionReplaced(callback);
4523
4994
  }
4524
4995
  /**
4525
4996
  * Subscribe to server-pushed renegotiation offers for `targetDid`.
@@ -4538,12 +5009,12 @@ class NeighbourhoodProxy {
4538
5009
  return __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").subscribeSfuMigrateEvent(targetDid, callback);
4539
5010
  }
4540
5011
  // ── SFU trickle ICE ─────────────────────────────────────────────────
4541
- async addIceCandidate(neighbourhoodUrl, roomName, candidate) {
4542
- return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuAddIceCandidate(neighbourhoodUrl, roomName, candidate);
5012
+ async addIceCandidate(neighbourhoodUrl, roomName, participantId, candidate) {
5013
+ return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuAddIceCandidate(neighbourhoodUrl, roomName, participantId, candidate);
4543
5014
  }
4544
5015
  // ── SFU data channel relay ────────────────────────────────────────
4545
- async sendData(neighbourhoodUrl, roomName, channelLabel, data, binary = false) {
4546
- return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuSendData(neighbourhoodUrl, roomName, channelLabel, data, binary);
5016
+ async sendData(neighbourhoodUrl, roomName, participantId, channelLabel, data, binary = false) {
5017
+ return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuSendData(neighbourhoodUrl, roomName, participantId, channelLabel, data, binary);
4547
5018
  }
4548
5019
  subscribeDataChannel(callback) {
4549
5020
  return __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").subscribeSfuDataChannel(callback);
@@ -10217,13 +10688,24 @@ var __classPrivateFieldGet$6 = (undefined && undefined.__classPrivateFieldGet) |
10217
10688
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10218
10689
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
10219
10690
  };
10220
- var _PerspectiveClient_apiClient, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient;
10691
+ var _PerspectiveClient_instances, _PerspectiveClient_apiClient, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient, _PerspectiveClient_released;
10221
10692
  /** The wire form of a model query's classes: `class_name` for one, `class_names` for a union. */
10222
10693
  function classParams(className) {
10223
10694
  return Array.isArray(className) ? { class_names: className } : { class_name: className };
10224
10695
  }
10696
+ /** A new live query's id (a UUID v4). The client mints it, so it can end the
10697
+ * subscription without the subscribe call's reply. `getRandomValues`, not
10698
+ * `randomUUID`: a page served over plain HTTP has only the former. */
10699
+ function mintSubscriptionId() {
10700
+ const b = globalThis.crypto.getRandomValues(new Uint8Array(16));
10701
+ b[6] = (b[6] & 0x0f) | 0x40;
10702
+ b[8] = (b[8] & 0x3f) | 0x80;
10703
+ const hex = Array.from(b, x => x.toString(16).padStart(2, '0')).join('');
10704
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
10705
+ }
10225
10706
  class PerspectiveClient {
10226
10707
  constructor(baseUrl, token, sharedApiClient) {
10708
+ _PerspectiveClient_instances.add(this);
10227
10709
  _PerspectiveClient_apiClient.set(this, void 0);
10228
10710
  _PerspectiveClient_expressionClient.set(this, void 0);
10229
10711
  _PerspectiveClient_neighbourhoodClient.set(this, void 0);
@@ -10294,7 +10776,8 @@ class PerspectiveClient {
10294
10776
  /** Open a live SPARQL query. Updates arrive through {@link onQueryUpdate}. */
10295
10777
  /** `options.signal` cancels the call, and the executor stops computing the first result. */
10296
10778
  async subscribeQuery(uuid, query, options) {
10297
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.subscribeQuery', { uuid, query }, options);
10779
+ const subscriptionId = mintSubscriptionId();
10780
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_released).call(this, uuid, subscriptionId, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.subscribeQuery', { uuid, query, subscriptionId }, options));
10298
10781
  }
10299
10782
  /** Every `query-subscription-update` event on this client's socket. */
10300
10783
  onQueryUpdate(cb) {
@@ -10329,7 +10812,8 @@ class PerspectiveClient {
10329
10812
  /** Open a live model query over one class or several. Updates arrive through {@link onQueryUpdate}. */
10330
10813
  /** `options.signal` cancels the call, and the executor stops computing the first result. */
10331
10814
  async modelSubscribe(uuid, className, queryJson, options) {
10332
- return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, ...classParams(className), query_json: queryJson }, options);
10815
+ const subscriptionId = mintSubscriptionId();
10816
+ return __classPrivateFieldGet$6(this, _PerspectiveClient_instances, "m", _PerspectiveClient_released).call(this, uuid, subscriptionId, __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, ...classParams(className), query_json: queryJson, subscriptionId }, options));
10333
10817
  }
10334
10818
  async add(name) {
10335
10819
  const handle = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.create', { name });
@@ -10600,7 +11084,23 @@ class PerspectiveClient {
10600
11084
  return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").onReconnect(callback);
10601
11085
  }
10602
11086
  }
10603
- _PerspectiveClient_apiClient = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap();
11087
+ _PerspectiveClient_apiClient = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap(), _PerspectiveClient_instances = new WeakSet(), _PerspectiveClient_released =
11088
+ /** A subscribe call that failed (timed out, aborted, refused) leaves no live
11089
+ * query on the executor that nobody holds. The client minted its id, so it
11090
+ * disposes it without the reply. A timeout or an abort sends `request.cancel`
11091
+ * first, and the executor handles a cancel before the calls after it: the
11092
+ * cancel either stops the call before it registers, or the dispose finds the
11093
+ * subscription. The dispose goes out before the call's error is thrown, and
11094
+ * is not awaited; one that fails changes nothing. */
11095
+ async function _PerspectiveClient_released(uuid, subscriptionId, call) {
11096
+ try {
11097
+ return await call;
11098
+ }
11099
+ catch (e) {
11100
+ this.disposeQuerySubscription(uuid, subscriptionId).catch(() => { });
11101
+ throw e;
11102
+ }
11103
+ };
10604
11104
 
10605
11105
  var __classPrivateFieldSet$5 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
10606
11106
  if (kind === "m") throw new TypeError("Private method is not writable");
@@ -25049,6 +25549,8 @@ const SCOPED_EVENTS = new Set([
25049
25549
  ]);
25050
25550
 
25051
25551
  exports.ACCEPTED_BY_GETTER = ACCEPTED_BY_GETTER;
25552
+ exports.AGENT_KIND = AGENT_KIND;
25553
+ exports.AGENT_KIND_BOT = AGENT_KIND_BOT;
25052
25554
  exports.AIClient = AIClient;
25053
25555
  exports.AIModel = Model;
25054
25556
  exports.AIModelLoadingStatus = AIModelLoadingStatus;
@@ -25130,6 +25632,7 @@ exports.NeighbourhoodProxy = NeighbourhoodProxy;
25130
25632
  exports.Notification = Notification;
25131
25633
  exports.NotificationInput = NotificationInput;
25132
25634
  exports.NullCache = NullCache;
25635
+ exports.OPENS_METHODS = OPENS_METHODS;
25133
25636
  exports.OnlineAgent = OnlineAgent;
25134
25637
  exports.Optional = Optional;
25135
25638
  exports.PROPOSER_GETTER = PROPOSER_GETTER;
@@ -25167,6 +25670,7 @@ exports.UserStatistics = UserStatistics;
25167
25670
  exports.VerificationRequestResult = VerificationRequestResult;
25168
25671
  exports.VoiceActivityParamsInput = VoiceActivityParamsInput;
25169
25672
  exports.WakerSubscriptionManager = WakerSubscriptionManager;
25673
+ exports.agentKind = agentKind;
25170
25674
  exports.applyUpdate = applyUpdate;
25171
25675
  exports.buildConformanceFilter = buildConformanceFilter;
25172
25676
  exports.buildModelFromJSONSchema = buildModelFromJSONSchema;
@@ -25206,6 +25710,7 @@ exports.holdsAWholeWordTerm = holdsAWholeWordTerm;
25206
25710
  exports.ifExpr = ifExpr;
25207
25711
  exports.invalidatePerspectiveCache = invalidatePerspectiveCache;
25208
25712
  exports.isArrayType = isArrayType;
25713
+ exports.isBot = isBot;
25209
25714
  exports.isContainedScope = isContainedScope;
25210
25715
  exports.isContainmentTraversal = isContainmentTraversal;
25211
25716
  exports.isExpression = isExpression;