@coasys/ad4m 0.13.1-staging.7 → 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.
- package/lib/index.cjs +652 -147
- package/lib/index.js +648 -148
- package/lib/src/agent/AgentClient.d.ts +6 -0
- package/lib/src/agent/AgentClient.js +17 -0
- package/lib/src/agent/AgentKind.d.ts +17 -0
- package/lib/src/agent/AgentKind.js +21 -0
- package/lib/src/apiClient.d.ts +4 -1
- package/lib/src/apiClient.js +13 -4
- package/lib/src/generated/api/CallSessionInfo.d.ts +1 -1
- package/lib/src/generated/api/Events.d.ts +2 -0
- package/lib/src/generated/api/PerspectiveModelSubscribeParams.d.ts +11 -0
- package/lib/src/generated/api/PerspectiveModelSubscribeParams.js +2 -0
- package/lib/src/generated/api/PerspectiveSubscribeQueryParams.d.ts +9 -0
- package/lib/src/generated/api/PerspectiveSubscribeQueryParams.js +2 -0
- package/lib/src/generated/api/RpcMethods.d.ts +10 -4
- package/lib/src/generated/api/RpcMethods.js +5 -0
- package/lib/src/generated/api/SfuAddIceCandidateParams.d.ts +4 -0
- package/lib/src/generated/api/SfuAnswerServerOfferParams.d.ts +4 -0
- package/lib/src/generated/api/SfuCallJoinParams.d.ts +13 -0
- package/lib/src/generated/api/SfuCallLeaveParams.d.ts +12 -0
- package/lib/src/generated/api/SfuCallLeaveParams.js +2 -0
- package/lib/src/generated/api/SfuCallRenegotiationOffer.d.ts +5 -0
- package/lib/src/generated/api/SfuDataMessage.d.ts +6 -0
- package/lib/src/generated/api/SfuQualityPreferenceParams.d.ts +4 -0
- package/lib/src/generated/api/SfuRestartIceParams.d.ts +12 -0
- package/lib/src/generated/api/SfuRestartIceParams.js +2 -0
- package/lib/src/generated/api/SfuRoomParticipantInfo.d.ts +4 -0
- package/lib/src/generated/api/SfuRoomRoster.d.ts +6 -2
- package/lib/src/generated/api/SfuRoomRoster.js +0 -1
- package/lib/src/generated/api/SfuRosterParticipant.d.ts +7 -0
- package/lib/src/generated/api/SfuRosterParticipant.js +2 -0
- package/lib/src/generated/api/SfuSendDataParams.d.ts +4 -0
- package/lib/src/generated/api/SfuSessionReplaced.d.ts +15 -0
- package/lib/src/generated/api/SfuSessionReplaced.js +2 -0
- package/lib/src/generated/api/SubscribeQueryRequest.d.ts +4 -0
- package/lib/src/generated/api/TrackMapEntry.d.ts +6 -1
- package/lib/src/generated/api/index.d.ts +1 -1
- package/lib/src/generated/api/index.js +1 -1
- package/lib/src/index.d.ts +1 -0
- package/lib/src/index.js +1 -0
- package/lib/src/neighbourhood/MeshManager.d.ts +19 -2
- package/lib/src/neighbourhood/MeshManager.js +55 -8
- package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +34 -13
- package/lib/src/neighbourhood/NeighbourhoodClient.js +44 -14
- package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +15 -7
- package/lib/src/neighbourhood/NeighbourhoodProxy.js +26 -13
- package/lib/src/neighbourhood/Session.d.ts +24 -5
- package/lib/src/neighbourhood/Session.js +179 -35
- package/lib/src/neighbourhood/SfuManager.d.ts +98 -28
- package/lib/src/neighbourhood/SfuManager.js +258 -71
- package/lib/src/neighbourhood/SfuTypes.d.ts +4 -0
- package/lib/src/perspectives/PerspectiveClient.js +33 -4
- package/package.json +2 -2
- package/src/Ad4mClient.test.ts +5 -5
- package/src/agent/AgentClient.ts +20 -0
- package/src/agent/AgentKind.ts +28 -0
- package/src/agent/mutatePublicPerspective.test.ts +72 -0
- package/src/apiClient.test.ts +46 -0
- package/src/apiClient.ts +16 -5
- package/src/generated/api/CallSessionInfo.ts +1 -1
- package/src/generated/api/Events.ts +2 -0
- package/src/generated/api/PerspectiveModelSubscribeParams.ts +7 -0
- package/src/generated/api/PerspectiveSubscribeQueryParams.ts +7 -0
- package/src/generated/api/RpcMethods.ts +14 -4
- package/src/generated/api/SfuAddIceCandidateParams.ts +4 -0
- package/src/generated/api/SfuAnswerServerOfferParams.ts +4 -0
- package/src/generated/api/SfuCallJoinParams.ts +13 -0
- package/src/generated/api/SfuCallLeaveParams.ts +11 -0
- package/src/generated/api/SfuCallRenegotiationOffer.ts +6 -1
- package/src/generated/api/SfuDataMessage.ts +7 -1
- package/src/generated/api/SfuQualityPreferenceParams.ts +4 -0
- package/src/generated/api/SfuRestartIceParams.ts +11 -0
- package/src/generated/api/SfuRoomParticipantInfo.ts +5 -1
- package/src/generated/api/SfuRoomRoster.ts +6 -2
- package/src/generated/api/SfuRosterParticipant.ts +6 -0
- package/src/generated/api/SfuSendDataParams.ts +5 -1
- package/src/generated/api/SfuSessionReplaced.ts +13 -0
- package/src/generated/api/SubscribeQueryRequest.ts +5 -1
- package/src/generated/api/TrackMapEntry.ts +6 -1
- package/src/generated/api/index.ts +1 -1
- package/src/index.ts +1 -0
- package/src/neighbourhood/MeshManager.test.ts +101 -25
- package/src/neighbourhood/MeshManager.ts +56 -7
- package/src/neighbourhood/NeighbourhoodClient.test.ts +45 -15
- package/src/neighbourhood/NeighbourhoodClient.ts +49 -9
- package/src/neighbourhood/NeighbourhoodProxy.ts +29 -6
- package/src/neighbourhood/Session.test.ts +388 -36
- package/src/neighbourhood/Session.ts +185 -38
- package/src/neighbourhood/SfuManager.test.ts +626 -20
- package/src/neighbourhood/SfuManager.ts +275 -67
- package/src/neighbourhood/SfuTypes.ts +4 -0
- package/src/perspectives/PerspectiveClient.ts +36 -4
- package/src/perspectives/abandoned-subscribe.test.ts +219 -0
package/lib/index.js
CHANGED
|
@@ -116,6 +116,11 @@ const LONG_METHODS = new Set([
|
|
|
116
116
|
"perspective.runInterpretationWithHarness",
|
|
117
117
|
"runtime.restartHolochain",
|
|
118
118
|
]);
|
|
119
|
+
/** Calls that open something on the executor that outlives them (a live query): the client cancels one that timed out, as one it aborted. */
|
|
120
|
+
const OPENS_METHODS = new Set([
|
|
121
|
+
"perspective.modelSubscribe",
|
|
122
|
+
"perspective.subscribeQuery",
|
|
123
|
+
]);
|
|
119
124
|
|
|
120
125
|
/** Error thrown by ApiClient when an RPC call fails. */
|
|
121
126
|
class RpcError extends Error {
|
|
@@ -601,7 +606,18 @@ class ApiClient {
|
|
|
601
606
|
signal?.removeEventListener('abort', onAbort);
|
|
602
607
|
fn();
|
|
603
608
|
};
|
|
609
|
+
// Tell the executor the call is no longer wanted, so it stops the work. A late
|
|
610
|
+
// reply finds no pending call and is dropped.
|
|
611
|
+
const cancel = () => {
|
|
612
|
+
if (pending.sent && this._ws?.readyState === 1 /* OPEN */) {
|
|
613
|
+
this._send(this._ws, JSON.stringify({ id: nextId(), type: 'request.cancel', params: { targetId: id } }));
|
|
614
|
+
}
|
|
615
|
+
};
|
|
604
616
|
const timer = setTimeout(() => {
|
|
617
|
+
// Only a call that opens something is cancelled on timeout: a write that
|
|
618
|
+
// timed out still runs to its end on the executor, as it always has.
|
|
619
|
+
if (OPENS_METHODS.has(type))
|
|
620
|
+
cancel();
|
|
605
621
|
settle(() => reject(new RpcError(408, `RPC call '${type}' timed out after ${timeoutMs}ms`)));
|
|
606
622
|
// A connect that never completes (a black-holed port) would hold every later
|
|
607
623
|
// call. Drop it once no call waits on it, so the next call dials again.
|
|
@@ -612,9 +628,7 @@ class ApiClient {
|
|
|
612
628
|
}
|
|
613
629
|
}, timeoutMs);
|
|
614
630
|
const onAbort = () => {
|
|
615
|
-
|
|
616
|
-
this._send(this._ws, JSON.stringify({ id: nextId(), type: 'request.cancel', params: { targetId: id } }));
|
|
617
|
-
}
|
|
631
|
+
cancel();
|
|
618
632
|
settle(() => reject(new DOMException('Aborted', 'AbortError')));
|
|
619
633
|
};
|
|
620
634
|
const pending = {
|
|
@@ -1261,6 +1275,28 @@ class AgentStatus {
|
|
|
1261
1275
|
}
|
|
1262
1276
|
}
|
|
1263
1277
|
|
|
1278
|
+
/**
|
|
1279
|
+
* What kind of agent this is, as the agent says itself: one link in its public perspective,
|
|
1280
|
+
* `<its did> ad4m://agent_kind <kind>`.
|
|
1281
|
+
*
|
|
1282
|
+
* Only the agent can write its public perspective, so the kind is its own claim, the same in
|
|
1283
|
+
* every space and every app. Nothing checks it: a bot that leaves it out reads as an agent of no
|
|
1284
|
+
* declared kind. It exists so an app can tell a program speaking from a person without each
|
|
1285
|
+
* community marking its bots by hand.
|
|
1286
|
+
*/
|
|
1287
|
+
const AGENT_KIND = "ad4m://agent_kind";
|
|
1288
|
+
/** The kind of an agent that is a program acting by itself: a bot, an AI agent, an integration. */
|
|
1289
|
+
const AGENT_KIND_BOT = "ad4m://bot";
|
|
1290
|
+
/** The kind `agent` declares in its public perspective, or `undefined` when it declares none. */
|
|
1291
|
+
function agentKind(agent) {
|
|
1292
|
+
const link = agent?.perspective?.links?.find((l) => l.data.source === agent.did && l.data.predicate === AGENT_KIND);
|
|
1293
|
+
return link?.data.target || undefined;
|
|
1294
|
+
}
|
|
1295
|
+
/** Whether `agent` says it is a bot. */
|
|
1296
|
+
function isBot(agent) {
|
|
1297
|
+
return agentKind(agent) === AGENT_KIND_BOT;
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1264
1300
|
/**
|
|
1265
1301
|
* PersistentCache — two-tier persistent key-value cache abstraction.
|
|
1266
1302
|
*
|
|
@@ -1544,6 +1580,22 @@ class AgentClient {
|
|
|
1544
1580
|
const kept = (perspective?.links ?? []).filter(link => !removals.some(r => linkEqual(link, r)));
|
|
1545
1581
|
return this.updatePublicPerspective({ links: [...kept, ...added] });
|
|
1546
1582
|
}
|
|
1583
|
+
/**
|
|
1584
|
+
* Say what kind of agent this is in its public perspective (`AGENT_KIND`; a bot is
|
|
1585
|
+
* `AGENT_KIND_BOT`), replacing any kind it said before, or say none with `null`. Changes
|
|
1586
|
+
* nothing when the perspective already says exactly that, so it can be called on every start.
|
|
1587
|
+
*/
|
|
1588
|
+
async setKind(kind) {
|
|
1589
|
+
const me = await this.me();
|
|
1590
|
+
const said = (me.perspective?.links ?? []).filter((l) => l.data.source === me.did && l.data.predicate === AGENT_KIND);
|
|
1591
|
+
if ((kind === null && said.length === 0) || (said.length === 1 && said[0].data.target === kind)) {
|
|
1592
|
+
return me;
|
|
1593
|
+
}
|
|
1594
|
+
return this.mutatePublicPerspective({
|
|
1595
|
+
additions: kind === null ? [] : [{ source: me.did, predicate: AGENT_KIND, target: kind }],
|
|
1596
|
+
removals: said,
|
|
1597
|
+
});
|
|
1598
|
+
}
|
|
1547
1599
|
async updateDirectMessageLanguage(directMessageLanguage) {
|
|
1548
1600
|
const agent = toAgent(await __classPrivateFieldGet$d(this, _AgentClient_apiClient, "f").call('agent.updateProfile', { dmLanguage: directMessageLanguage }));
|
|
1549
1601
|
// Immediately update byDID cache so subsequent byDID() calls
|
|
@@ -1886,35 +1938,49 @@ class NeighbourhoodClient {
|
|
|
1886
1938
|
async sfuListRooms() {
|
|
1887
1939
|
return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.listRooms", {});
|
|
1888
1940
|
}
|
|
1889
|
-
|
|
1941
|
+
/**
|
|
1942
|
+
* Join a call from `deviceId`. The executor replaces this agent's session
|
|
1943
|
+
* from the same device (another tab) and keeps those from other devices.
|
|
1944
|
+
* The result's `participantId` names the session in every later call.
|
|
1945
|
+
* `sessionKey` is the caller's random key for the session: a rebuild
|
|
1946
|
+
* sends it again; a key a later join from this device replaced is
|
|
1947
|
+
* refused with `RpcError` status 409, and that session must stop.
|
|
1948
|
+
*/
|
|
1949
|
+
async sfuCallJoin(neighbourhoodUrl, roomName, sdpOffer, deviceId, sessionKey) {
|
|
1890
1950
|
return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callJoin", {
|
|
1891
1951
|
neighbourhoodUrl,
|
|
1892
1952
|
roomName,
|
|
1893
1953
|
sdpOffer,
|
|
1954
|
+
deviceId,
|
|
1955
|
+
sessionKey,
|
|
1894
1956
|
});
|
|
1895
1957
|
}
|
|
1896
|
-
|
|
1897
|
-
|
|
1958
|
+
/** Leave the session `participantId`; `false` when it is not this agent's or is gone already. */
|
|
1959
|
+
async sfuCallLeave(neighbourhoodUrl, roomName, participantId) {
|
|
1960
|
+
return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callLeave", { neighbourhoodUrl, roomName, participantId });
|
|
1898
1961
|
}
|
|
1899
|
-
async sfuCallSetQualityPreference(neighbourhoodUrl, roomName, preference) {
|
|
1962
|
+
async sfuCallSetQualityPreference(neighbourhoodUrl, roomName, participantId, preference) {
|
|
1900
1963
|
return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callSetQualityPreference", {
|
|
1901
1964
|
neighbourhoodUrl,
|
|
1902
1965
|
roomName,
|
|
1966
|
+
participantId,
|
|
1903
1967
|
preference,
|
|
1904
1968
|
});
|
|
1905
1969
|
}
|
|
1906
|
-
async sfuCallAnswerServerOffer(neighbourhoodUrl, roomName, sdpAnswer) {
|
|
1970
|
+
async sfuCallAnswerServerOffer(neighbourhoodUrl, roomName, participantId, sdpAnswer) {
|
|
1907
1971
|
return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callAnswerServerOffer", {
|
|
1908
1972
|
neighbourhoodUrl,
|
|
1909
1973
|
roomName,
|
|
1974
|
+
participantId,
|
|
1910
1975
|
sdpAnswer,
|
|
1911
1976
|
});
|
|
1912
1977
|
}
|
|
1913
|
-
/** Ask the SFU to restart ICE on
|
|
1914
|
-
*
|
|
1915
|
-
*
|
|
1916
|
-
|
|
1917
|
-
|
|
1978
|
+
/** Ask the SFU to restart ICE on the session `participantId` (this
|
|
1979
|
+
* agent's, as its join returned it; any other is refused). The offer
|
|
1980
|
+
* arrives as an `sfu-call-renegotiation-offer` event for that session;
|
|
1981
|
+
* answer it with {@link sfuCallAnswerServerOffer}. */
|
|
1982
|
+
async sfuCallRestartIce(neighbourhoodUrl, roomName, participantId) {
|
|
1983
|
+
return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.callRestartIce", { neighbourhoodUrl, roomName, participantId });
|
|
1918
1984
|
}
|
|
1919
1985
|
/** Fires after a network change, once the client's socket is back on
|
|
1920
1986
|
* the new network. See {@link ApiClient.onNetworkChange}. */
|
|
@@ -1947,10 +2013,11 @@ class NeighbourhoodClient {
|
|
|
1947
2013
|
* complete (which can take up to 8 seconds on restrictive
|
|
1948
2014
|
* networks).
|
|
1949
2015
|
*/
|
|
1950
|
-
async sfuAddIceCandidate(neighbourhoodUrl, roomName, candidate) {
|
|
2016
|
+
async sfuAddIceCandidate(neighbourhoodUrl, roomName, participantId, candidate) {
|
|
1951
2017
|
return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.addIceCandidate", {
|
|
1952
2018
|
neighbourhoodUrl,
|
|
1953
2019
|
roomName,
|
|
2020
|
+
participantId,
|
|
1954
2021
|
candidate,
|
|
1955
2022
|
});
|
|
1956
2023
|
}
|
|
@@ -1960,10 +2027,11 @@ class NeighbourhoodClient {
|
|
|
1960
2027
|
* The server relays it to their matching data channel and
|
|
1961
2028
|
* publishes it as an `sfu-data` event.
|
|
1962
2029
|
*/
|
|
1963
|
-
async sfuSendData(neighbourhoodUrl, roomName, channelLabel, data, binary = false) {
|
|
2030
|
+
async sfuSendData(neighbourhoodUrl, roomName, participantId, channelLabel, data, binary = false) {
|
|
1964
2031
|
return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").call("sfu.sendData", {
|
|
1965
2032
|
neighbourhoodUrl,
|
|
1966
2033
|
roomName,
|
|
2034
|
+
participantId,
|
|
1967
2035
|
channelLabel,
|
|
1968
2036
|
data,
|
|
1969
2037
|
binary,
|
|
@@ -1972,17 +2040,28 @@ class NeighbourhoodClient {
|
|
|
1972
2040
|
/**
|
|
1973
2041
|
* Subscribe to SFU data channel messages. Returns an unsubscribe
|
|
1974
2042
|
* function. Messages arrive for every participant in the room;
|
|
1975
|
-
* filter by `senderDid` if needed.
|
|
2043
|
+
* filter by `senderDid` or `senderParticipantId` if needed. One sent by
|
|
2044
|
+
* a session of this agent arrives here when the agent is in the call on
|
|
2045
|
+
* another device too: it carries the sending session's participant id.
|
|
1976
2046
|
*/
|
|
1977
2047
|
subscribeSfuDataChannel(callback) {
|
|
1978
2048
|
// A fresh handler per call: `on` merges a repeated handler, and
|
|
1979
2049
|
// each subscription must own its unsubscribe.
|
|
1980
2050
|
return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").on("sfu-data", (message) => callback(message));
|
|
1981
2051
|
}
|
|
1982
|
-
/** Subscribe to the rosters of the call rooms this agent is in: who is in each, whenever that changes. */
|
|
2052
|
+
/** Subscribe to the rosters of the call rooms this agent is in: who is in each, by session, whenever that changes. */
|
|
1983
2053
|
subscribeSfuRoomRoster(callback) {
|
|
1984
2054
|
return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").on("sfu-room-roster", (roster) => callback(roster));
|
|
1985
2055
|
}
|
|
2056
|
+
/**
|
|
2057
|
+
* Subscribe to the executor's notice that a session of this agent was
|
|
2058
|
+
* replaced: a later join from the same device took its call over. The
|
|
2059
|
+
* notice names the replaced session's participant id; the session that
|
|
2060
|
+
* holds it stops and does not rejoin.
|
|
2061
|
+
*/
|
|
2062
|
+
subscribeSfuSessionReplaced(callback) {
|
|
2063
|
+
return __classPrivateFieldGet$b(this, _NeighbourhoodClient_apiClient, "f").on("sfu-session-replaced", (event) => callback(event));
|
|
2064
|
+
}
|
|
1986
2065
|
/**
|
|
1987
2066
|
* Subscribe to server-pushed SFU SDP renegotiation offers. The
|
|
1988
2067
|
* server publishes an `sfu-call-renegotiation-offer` event every
|
|
@@ -1992,6 +2071,8 @@ class NeighbourhoodClient {
|
|
|
1992
2071
|
*
|
|
1993
2072
|
* The executor already sends each socket only its own DID's offers;
|
|
1994
2073
|
* this subscription additionally filters on `targetDid` for safety.
|
|
2074
|
+
* An agent in the call on two devices gets the offers of both: each
|
|
2075
|
+
* names the session it is for (`participantId`).
|
|
1995
2076
|
* Returns an unsubscribe function.
|
|
1996
2077
|
*/
|
|
1997
2078
|
subscribeSfuCallRenegotiationOffer(targetDid, callback) {
|
|
@@ -2000,6 +2081,7 @@ class NeighbourhoodClient {
|
|
|
2000
2081
|
return;
|
|
2001
2082
|
callback({
|
|
2002
2083
|
targetDid: event.targetDid,
|
|
2084
|
+
participantId: event.participantId,
|
|
2003
2085
|
neighbourhoodUrl: event.neighbourhoodUrl,
|
|
2004
2086
|
roomName: event.roomName,
|
|
2005
2087
|
sdpOffer: event.sdpOffer,
|
|
@@ -2092,6 +2174,15 @@ _NeighbourhoodClient_apiClient = new WeakMap(), _NeighbourhoodClient_signalHandl
|
|
|
2092
2174
|
* through cascade pipes between executors, so the client never follows
|
|
2093
2175
|
* a redirect or a rebalance to another node — it has no way to reach one.
|
|
2094
2176
|
*
|
|
2177
|
+
* One session per device: a join names this device (`deviceId`), and the
|
|
2178
|
+
* executor gives it a participant id that every later call about the
|
|
2179
|
+
* session names. The same agent on another device is another participant;
|
|
2180
|
+
* a later join from this device — another tab — replaces this session, and
|
|
2181
|
+
* the manager stops (`replaced`) rather than taking the call back. Each
|
|
2182
|
+
* user join sends a random session key that the rebuilds of that call send
|
|
2183
|
+
* again; the executor refuses (409) a key another tab's join replaced, so a
|
|
2184
|
+
* tab that missed its `sfu-session-replaced` notice stops all the same.
|
|
2185
|
+
*
|
|
2095
2186
|
* Applications (Flux, WE, or any other) wrap this class with their
|
|
2096
2187
|
* own reactive store and UI layer. The manager itself only touches
|
|
2097
2188
|
* Web APIs (RTCPeerConnection, MediaStream) and the AD4M
|
|
@@ -2101,9 +2192,58 @@ _NeighbourhoodClient_apiClient = new WeakMap(), _NeighbourhoodClient_signalHandl
|
|
|
2101
2192
|
const DEFAULT_ICE_SERVERS$1 = [
|
|
2102
2193
|
{ urls: "stun:stun.l.google.com:19302" },
|
|
2103
2194
|
];
|
|
2195
|
+
/**
|
|
2196
|
+
* Where a browser profile keeps its device id. The prefix versions the
|
|
2197
|
+
* stored value, as `connect`'s `{version}/ad4m-token` does; it is not the
|
|
2198
|
+
* SDK release, so an upgrade does not make every browser a new device.
|
|
2199
|
+
*/
|
|
2200
|
+
const DEVICE_ID_KEY = "v1/ad4m-sfu-device-id";
|
|
2201
|
+
/** Outside a browser: one device id for the life of the process. */
|
|
2202
|
+
let processDeviceId = null;
|
|
2203
|
+
function randomId() {
|
|
2204
|
+
const crypto = globalThis.crypto;
|
|
2205
|
+
if (crypto?.randomUUID)
|
|
2206
|
+
return crypto.randomUUID();
|
|
2207
|
+
return Array.from({ length: 4 }, () => Math.random().toString(36).slice(2, 10)).join("");
|
|
2208
|
+
}
|
|
2209
|
+
/**
|
|
2210
|
+
* This device's id for SFU calls, unless the app gives one. In a browser it
|
|
2211
|
+
* is kept in `localStorage`, which every tab of one profile shares, so the
|
|
2212
|
+
* tabs of one browser are one device; outside a browser (Node), the process
|
|
2213
|
+
* is the device.
|
|
2214
|
+
*/
|
|
2215
|
+
function defaultDeviceId() {
|
|
2216
|
+
let storage;
|
|
2217
|
+
try {
|
|
2218
|
+
storage = globalThis.localStorage;
|
|
2219
|
+
}
|
|
2220
|
+
catch {
|
|
2221
|
+
storage = undefined; // storage denied (sandboxed frame, privacy settings)
|
|
2222
|
+
}
|
|
2223
|
+
if (storage) {
|
|
2224
|
+
try {
|
|
2225
|
+
let id = storage.getItem(DEVICE_ID_KEY);
|
|
2226
|
+
if (!id) {
|
|
2227
|
+
id = randomId();
|
|
2228
|
+
storage.setItem(DEVICE_ID_KEY, id);
|
|
2229
|
+
}
|
|
2230
|
+
return id;
|
|
2231
|
+
}
|
|
2232
|
+
catch {
|
|
2233
|
+
/* unusable storage: fall back to the process */
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
return (processDeviceId ?? (processDeviceId = randomId()));
|
|
2237
|
+
}
|
|
2104
2238
|
// ── SFU Manager ───────────────────────────────────────────────────
|
|
2105
2239
|
class SfuManager {
|
|
2106
|
-
constructor(neighbourhood, roomId, agentDid, neighbourhoodUrl, iceConfig, sfuConfig
|
|
2240
|
+
constructor(neighbourhood, roomId, agentDid, neighbourhoodUrl, iceConfig, sfuConfig,
|
|
2241
|
+
/** This device; unset, `defaultDeviceId()`. Apps outside a browser profile (Electron, tests) pass their own. */
|
|
2242
|
+
deviceId) {
|
|
2243
|
+
/** This call session's key: a rebuild joins with it again, a user's join
|
|
2244
|
+
* makes a new one. The executor refuses a key a later join from this
|
|
2245
|
+
* device replaced, so a tab that missed its notice cannot take the call back. */
|
|
2246
|
+
this.sessionKey = randomId();
|
|
2107
2247
|
this.callbacks = new Map();
|
|
2108
2248
|
/** Reconnects since ICE last reached connected — not since a join: a
|
|
2109
2249
|
* join can succeed while the media path never comes up. */
|
|
@@ -2112,9 +2252,9 @@ class SfuManager {
|
|
|
2112
2252
|
this.reconnecting = false;
|
|
2113
2253
|
/** Bumped by `leave()`, so a reconnect in flight stops before rejoining. */
|
|
2114
2254
|
this.generation = 0;
|
|
2115
|
-
/** Which participant each received media section carries, from the server's mappings. */
|
|
2255
|
+
/** Which participant (session and agent) each received media section carries, from the server's mappings. */
|
|
2116
2256
|
this.midToParticipant = new Map();
|
|
2117
|
-
/**
|
|
2257
|
+
/** Participant ids the roster removed and has not listed since. */
|
|
2118
2258
|
this.departed = new Set();
|
|
2119
2259
|
/** The sender of each kind of local media: declared at join, so a later camera or screen needs no renegotiation. */
|
|
2120
2260
|
this.senders = new Map();
|
|
@@ -2130,17 +2270,24 @@ class SfuManager {
|
|
|
2130
2270
|
this.answeredOffer = null;
|
|
2131
2271
|
this.renegotiationUnsubscribe = null;
|
|
2132
2272
|
this.rosterUnsubscribe = null;
|
|
2273
|
+
/** For the manager's call, not one join: a reconnect between its leave and its join still hears a notice. */
|
|
2274
|
+
this.replacedUnsubscribe = null;
|
|
2275
|
+
/** Participant ids of this call a notice can still name: the current one, and any whose leave found it gone. */
|
|
2276
|
+
this.heldIds = new Set();
|
|
2277
|
+
/** Settles when the latest join has its participant id, or failed. */
|
|
2278
|
+
this.joinSettled = Promise.resolve();
|
|
2133
2279
|
this.dataChannelUnsubscribe = null;
|
|
2134
2280
|
/** An ICE restart is in flight until this fires: ICE going disconnected
|
|
2135
2281
|
* again joins it, a network change replaces it. */
|
|
2136
2282
|
this.restartTimer = null;
|
|
2137
2283
|
this.networkUnsubscribe = null;
|
|
2138
|
-
/** Running while the room's roster leaves this
|
|
2284
|
+
/** Running while the room's roster leaves this session out: see `noticeRoster`. */
|
|
2139
2285
|
this.unlistedTimer = null;
|
|
2140
2286
|
this.neighbourhood = neighbourhood;
|
|
2141
2287
|
this.neighbourhoodUrl = neighbourhoodUrl || "";
|
|
2142
2288
|
this.roomId = roomId;
|
|
2143
2289
|
this.agentDid = agentDid;
|
|
2290
|
+
this.deviceId = deviceId || defaultDeviceId();
|
|
2144
2291
|
this.state = {
|
|
2145
2292
|
topology: "sfu",
|
|
2146
2293
|
roomId,
|
|
@@ -2169,8 +2316,13 @@ class SfuManager {
|
|
|
2169
2316
|
}
|
|
2170
2317
|
/**
|
|
2171
2318
|
* Rebuild the call after its connection failed: leave, then join again
|
|
2172
|
-
* on this executor. Leaving first
|
|
2173
|
-
*
|
|
2319
|
+
* on this executor. Leaving first frees the old session's slot at once;
|
|
2320
|
+
* the join would replace it anyway, as it comes from this device.
|
|
2321
|
+
* Another tab's join can still replace the old session before the leave
|
|
2322
|
+
* lands: that notice stops the rebuild wherever it is, and a session its
|
|
2323
|
+
* join already got is left. A tab that missed the notice learns it from
|
|
2324
|
+
* the rejoin: the executor refuses the replaced session key (409), and
|
|
2325
|
+
* the manager stops as the notice would have stopped it, without retrying.
|
|
2174
2326
|
*
|
|
2175
2327
|
* Two budgets. A rebuild whose join works but whose connection fails
|
|
2176
2328
|
* again counts once against `MAX_RECONNECTS`, reset when ICE connects.
|
|
@@ -2190,6 +2342,7 @@ class SfuManager {
|
|
|
2190
2342
|
console.info(`SFU: connection failed, reconnecting (${this.reconnectAttempts}/${SfuManager.MAX_RECONNECTS})`);
|
|
2191
2343
|
this.reconnecting = true;
|
|
2192
2344
|
this.endRestart();
|
|
2345
|
+
const previous = this.state.participantId;
|
|
2193
2346
|
try {
|
|
2194
2347
|
const deadline = Date.now() + SfuManager.REJOIN_WINDOW_MS;
|
|
2195
2348
|
for (let delay = 1000;; delay = Math.min(delay * 2, 10000)) {
|
|
@@ -2198,14 +2351,9 @@ class SfuManager {
|
|
|
2198
2351
|
this.state.peerConnection.close();
|
|
2199
2352
|
this.state.peerConnection = null;
|
|
2200
2353
|
}
|
|
2201
|
-
|
|
2202
|
-
await this.neighbourhood.sfuCallLeave(this.neighbourhoodUrl, this.roomId);
|
|
2203
|
-
}
|
|
2204
|
-
catch {
|
|
2205
|
-
/* best-effort: the executor frees a dead session on its own */
|
|
2206
|
-
}
|
|
2354
|
+
await this.leaveSession();
|
|
2207
2355
|
if (generation !== this.generation)
|
|
2208
|
-
return; // left meanwhile
|
|
2356
|
+
return; // left or replaced meanwhile
|
|
2209
2357
|
this.resetParticipants();
|
|
2210
2358
|
try {
|
|
2211
2359
|
await this.join(stream);
|
|
@@ -2216,6 +2364,15 @@ class SfuManager {
|
|
|
2216
2364
|
catch (e) {
|
|
2217
2365
|
if (generation !== this.generation)
|
|
2218
2366
|
return;
|
|
2367
|
+
if (e instanceof RpcError && e.status === 409) {
|
|
2368
|
+
this.stopReplaced({
|
|
2369
|
+
targetDid: this.agentDid,
|
|
2370
|
+
neighbourhoodUrl: this.neighbourhoodUrl,
|
|
2371
|
+
roomName: this.roomId,
|
|
2372
|
+
participantId: previous ?? "",
|
|
2373
|
+
});
|
|
2374
|
+
return;
|
|
2375
|
+
}
|
|
2219
2376
|
if (Date.now() + delay > deadline) {
|
|
2220
2377
|
console.error("SFU reconnect failed:", e);
|
|
2221
2378
|
this.emit("error", e);
|
|
@@ -2239,22 +2396,30 @@ class SfuManager {
|
|
|
2239
2396
|
* DTLS, tracks and the room slot stay. If the connection is not back
|
|
2240
2397
|
* within `RESTART_TIMEOUT_MS`, the call is rebuilt. One restart at a
|
|
2241
2398
|
* time: a call while one is in flight does nothing.
|
|
2399
|
+
*
|
|
2400
|
+
* The restart names this manager's session, the participant id its
|
|
2401
|
+
* current join returned: the executor restarts that session only, never
|
|
2402
|
+
* another device's of the same agent. A manager with no session — its
|
|
2403
|
+
* join not back yet, between a rebuild's leave and join, left, or
|
|
2404
|
+
* replaced by another tab — sends nothing.
|
|
2242
2405
|
*/
|
|
2243
2406
|
restartIce(pc) {
|
|
2244
|
-
|
|
2407
|
+
const participantId = this.state.participantId;
|
|
2408
|
+
if (this.restartTimer || this.reconnecting || this.state.peerConnection !== pc || !participantId)
|
|
2245
2409
|
return;
|
|
2410
|
+
const generation = this.generation;
|
|
2246
2411
|
console.info("SFU: restarting ICE");
|
|
2247
2412
|
this.restartTimer = setTimeout(() => {
|
|
2248
2413
|
this.restartTimer = null;
|
|
2249
|
-
if (this.state.peerConnection !== pc)
|
|
2414
|
+
if (generation !== this.generation || this.state.peerConnection !== pc)
|
|
2250
2415
|
return;
|
|
2251
2416
|
if (pc.iceConnectionState === "connected" || pc.iceConnectionState === "completed")
|
|
2252
2417
|
return;
|
|
2253
2418
|
void this.reconnect();
|
|
2254
2419
|
}, SfuManager.RESTART_TIMEOUT_MS);
|
|
2255
|
-
// A refusal (an executor
|
|
2256
|
-
//
|
|
2257
|
-
this.neighbourhood.sfuCallRestartIce(this.neighbourhoodUrl, this.roomId).catch((err) => {
|
|
2420
|
+
// A refusal (an executor that lost this session) leaves the decision
|
|
2421
|
+
// to the timeout: a blip may still heal.
|
|
2422
|
+
this.neighbourhood.sfuCallRestartIce(this.neighbourhoodUrl, this.roomId, participantId).catch((err) => {
|
|
2258
2423
|
console.warn("SFU: ICE restart refused:", err);
|
|
2259
2424
|
});
|
|
2260
2425
|
}
|
|
@@ -2299,6 +2464,9 @@ class SfuManager {
|
|
|
2299
2464
|
}
|
|
2300
2465
|
/** Join the SFU call with simulcast support. */
|
|
2301
2466
|
async join(localStream) {
|
|
2467
|
+
const generation = this.generation;
|
|
2468
|
+
if (!this.reconnecting)
|
|
2469
|
+
this.sessionKey = randomId();
|
|
2302
2470
|
this.state.localStream = localStream;
|
|
2303
2471
|
const pc = new RTCPeerConnection({ iceServers: this.iceServers });
|
|
2304
2472
|
this.state.peerConnection = pc;
|
|
@@ -2372,11 +2540,11 @@ class SfuManager {
|
|
|
2372
2540
|
if (this.state.peerConnection !== pc)
|
|
2373
2541
|
return;
|
|
2374
2542
|
const mid = event.transceiver?.mid;
|
|
2375
|
-
const
|
|
2543
|
+
const owner = mid ? this.midToParticipant.get(mid) : undefined;
|
|
2376
2544
|
// Someone the roster said left stays gone: a late offer can still name them.
|
|
2377
|
-
if (!
|
|
2545
|
+
if (!owner || owner.participantId === this.state.participantId || this.departed.has(owner.participantId))
|
|
2378
2546
|
return;
|
|
2379
|
-
const participant = this.ensureParticipant(did);
|
|
2547
|
+
const participant = this.ensureParticipant(owner.participantId, owner.did);
|
|
2380
2548
|
participant.stream.addTrack(event.track);
|
|
2381
2549
|
this.refreshKinds(participant);
|
|
2382
2550
|
this.emit("stream-added", participant.stream, event.track);
|
|
@@ -2397,7 +2565,9 @@ class SfuManager {
|
|
|
2397
2565
|
if (!event.candidate)
|
|
2398
2566
|
return;
|
|
2399
2567
|
if (joinComplete) {
|
|
2400
|
-
this.
|
|
2568
|
+
if (this.state.peerConnection !== pc || !this.state.participantId)
|
|
2569
|
+
return;
|
|
2570
|
+
this.neighbourhood.sfuAddIceCandidate(this.neighbourhoodUrl, this.roomId, this.state.participantId, event.candidate.candidate).catch((err) => {
|
|
2401
2571
|
console.error("SFU: failed to trickle ICE candidate:", err);
|
|
2402
2572
|
});
|
|
2403
2573
|
}
|
|
@@ -2413,36 +2583,57 @@ class SfuManager {
|
|
|
2413
2583
|
// they wait for it, then apply in order.
|
|
2414
2584
|
let markJoined;
|
|
2415
2585
|
const joined = new Promise((resolve) => { markJoined = resolve; });
|
|
2586
|
+
this.joinSettled = joined;
|
|
2416
2587
|
this.subscribeServerEvents(pc, joined);
|
|
2417
2588
|
let session;
|
|
2418
2589
|
try {
|
|
2419
|
-
session = await this.neighbourhood.sfuCallJoin(this.neighbourhoodUrl, this.roomId, sdpOffer);
|
|
2590
|
+
session = await this.neighbourhood.sfuCallJoin(this.neighbourhoodUrl, this.roomId, sdpOffer, this.deviceId, this.sessionKey);
|
|
2420
2591
|
}
|
|
2421
2592
|
catch (err) {
|
|
2422
2593
|
// Settled either way: offers queued behind this join reach
|
|
2423
2594
|
// `applyServerOffer`, which drops them for the abandoned connection.
|
|
2595
|
+
// The executor holds no session for it, so there is nothing to leave.
|
|
2424
2596
|
markJoined();
|
|
2425
2597
|
this.abandon(pc);
|
|
2426
2598
|
throw err;
|
|
2427
2599
|
}
|
|
2600
|
+
if (generation !== this.generation) {
|
|
2601
|
+
// Left or replaced while the join was out: the session it got is no one's.
|
|
2602
|
+
markJoined();
|
|
2603
|
+
this.abandon(pc);
|
|
2604
|
+
await this.neighbourhood
|
|
2605
|
+
.sfuCallLeave(this.neighbourhoodUrl, this.roomId, session.participantId)
|
|
2606
|
+
.catch((e) => console.warn("SFU: leaving the call failed:", e));
|
|
2607
|
+
return;
|
|
2608
|
+
}
|
|
2428
2609
|
this.state.participantId = session.participantId;
|
|
2610
|
+
this.heldIds.add(session.participantId);
|
|
2429
2611
|
try {
|
|
2430
2612
|
const answer = JSON.parse(session.sdpAnswer);
|
|
2431
2613
|
await pc.setRemoteDescription(new RTCSessionDescription(answer));
|
|
2432
2614
|
}
|
|
2433
2615
|
catch (err) {
|
|
2434
2616
|
markJoined();
|
|
2617
|
+
// Replaced or left while the answer applied: that already closed the
|
|
2618
|
+
// connection and settled the session, so the join just ends.
|
|
2619
|
+
if (generation !== this.generation)
|
|
2620
|
+
return;
|
|
2621
|
+
// The executor holds a session this connection cannot use: leave it.
|
|
2435
2622
|
this.abandon(pc);
|
|
2623
|
+
await this.leaveSession();
|
|
2436
2624
|
throw err;
|
|
2437
2625
|
}
|
|
2438
2626
|
markJoined();
|
|
2439
2627
|
// Who was in the room when this join landed (`participantId:did`).
|
|
2440
2628
|
// The roster event keeps it current from here.
|
|
2441
|
-
this.applyRoster(session.streamMapping.map((entry) =>
|
|
2629
|
+
this.applyRoster(session.streamMapping.map((entry) => {
|
|
2630
|
+
const at = entry.indexOf(":");
|
|
2631
|
+
return { participantId: entry.slice(0, at), agentDid: entry.slice(at + 1) };
|
|
2632
|
+
}), false);
|
|
2442
2633
|
// Flush buffered trickle ICE candidates
|
|
2443
2634
|
joinComplete = true;
|
|
2444
2635
|
for (const candidate of pendingCandidates) {
|
|
2445
|
-
this.neighbourhood.sfuAddIceCandidate(this.neighbourhoodUrl, this.roomId, candidate).catch((err) => {
|
|
2636
|
+
this.neighbourhood.sfuAddIceCandidate(this.neighbourhoodUrl, this.roomId, session.participantId, candidate).catch((err) => {
|
|
2446
2637
|
console.error("SFU: failed to trickle buffered ICE candidate:", err);
|
|
2447
2638
|
});
|
|
2448
2639
|
}
|
|
@@ -2462,16 +2653,22 @@ class SfuManager {
|
|
|
2462
2653
|
}
|
|
2463
2654
|
}
|
|
2464
2655
|
/**
|
|
2465
|
-
* The room's roster no longer lists this
|
|
2466
|
-
* the server has dropped this session, and ICE
|
|
2467
|
-
* (CI job 53158) one of six sessions never started
|
|
2468
|
-
* 20 s outage the server had dropped it for.
|
|
2469
|
-
*
|
|
2470
|
-
*
|
|
2471
|
-
*
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
|
|
2656
|
+
* The room's roster no longer lists this session (its participant id)
|
|
2657
|
+
* while `pc` is the call's: the server has dropped this session, and ICE
|
|
2658
|
+
* may not say so. In E6 (CI job 53158) one of six sessions never started
|
|
2659
|
+
* a rebuild after a 20 s outage the server had dropped it for. The check
|
|
2660
|
+
* is per session, not per agent: another device of this agent keeps the
|
|
2661
|
+
* DID listed. Rebuild once the roster has left this session out for
|
|
2662
|
+
* `UNLISTED_GRACE_MS`; a roster that lists it again in that time
|
|
2663
|
+
* cancels, since one published just before this join landed can arrive
|
|
2664
|
+
* after it. A manager with no session (between leave and join, or
|
|
2665
|
+
* stopped because a later tab replaced it) starts no rebuild: `stop`
|
|
2666
|
+
* clears the timer and drops `pc`, so a replaced session never rejoins
|
|
2667
|
+
* and never takes the call back from the newer tab.
|
|
2668
|
+
*/
|
|
2669
|
+
noticeRoster(pc, sessions) {
|
|
2670
|
+
const participantId = this.state.participantId;
|
|
2671
|
+
if (!participantId || sessions.some((s) => s.participantId === participantId)) {
|
|
2475
2672
|
this.clearUnlistedTimer();
|
|
2476
2673
|
return;
|
|
2477
2674
|
}
|
|
@@ -2479,15 +2676,44 @@ class SfuManager {
|
|
|
2479
2676
|
return;
|
|
2480
2677
|
this.unlistedTimer = setTimeout(() => {
|
|
2481
2678
|
this.unlistedTimer = null;
|
|
2482
|
-
if (this.state.peerConnection !== pc)
|
|
2679
|
+
if (this.state.peerConnection !== pc || this.state.participantId !== participantId)
|
|
2483
2680
|
return;
|
|
2484
2681
|
console.info("SFU: the room no longer lists this session, rebuilding the call");
|
|
2485
2682
|
void this.reconnect();
|
|
2486
2683
|
}, SfuManager.UNLISTED_GRACE_MS);
|
|
2487
2684
|
}
|
|
2488
|
-
/**
|
|
2685
|
+
/**
|
|
2686
|
+
* Leave this manager's session on the executor, if it has one, and forget
|
|
2687
|
+
* it. Only the participant id a join returned is ever left: a manager
|
|
2688
|
+
* that never joined, or whose join was refused, sends nothing, so it can
|
|
2689
|
+
* never end a session another tab of this agent is in.
|
|
2690
|
+
*/
|
|
2691
|
+
async leaveSession() {
|
|
2692
|
+
const participantId = this.state.participantId;
|
|
2693
|
+
if (!participantId)
|
|
2694
|
+
return;
|
|
2695
|
+
this.state.participantId = null;
|
|
2696
|
+
// A session the leave found gone may have been replaced, its notice
|
|
2697
|
+
// still on the way. One the leave ended, or that it never reached, a
|
|
2698
|
+
// notice names only if this manager's own rejoin replaced it.
|
|
2699
|
+
let found = true;
|
|
2700
|
+
try {
|
|
2701
|
+
found = await this.neighbourhood.sfuCallLeave(this.neighbourhoodUrl, this.roomId, participantId);
|
|
2702
|
+
}
|
|
2703
|
+
catch (e) {
|
|
2704
|
+
/* best-effort: the executor frees a dead session on its own */
|
|
2705
|
+
console.warn("SFU: leaving the call failed:", e);
|
|
2706
|
+
}
|
|
2707
|
+
if (found)
|
|
2708
|
+
this.heldIds.delete(participantId);
|
|
2709
|
+
}
|
|
2710
|
+
/** Undo a join that failed part way: its subscriptions and its connection. */
|
|
2489
2711
|
abandon(pc) {
|
|
2490
2712
|
this.releaseServerEvents();
|
|
2713
|
+
if (this.heldIds.size === 0) {
|
|
2714
|
+
this.replacedUnsubscribe?.();
|
|
2715
|
+
this.replacedUnsubscribe = null;
|
|
2716
|
+
}
|
|
2491
2717
|
pc.close();
|
|
2492
2718
|
if (this.state.peerConnection === pc)
|
|
2493
2719
|
this.state.peerConnection = null;
|
|
@@ -2507,12 +2733,18 @@ class SfuManager {
|
|
|
2507
2733
|
// never drops to zero listeners in between.
|
|
2508
2734
|
const previous = [this.renegotiationUnsubscribe, this.rosterUnsubscribe];
|
|
2509
2735
|
const ours = (e) => e.neighbourhoodUrl === this.neighbourhoodUrl && e.roomName === this.roomId;
|
|
2736
|
+
// The executor sends this agent's offers and notices to each of its
|
|
2737
|
+
// sessions; only those naming this session's participant id are ours,
|
|
2738
|
+
// and that id is known once the join returns.
|
|
2510
2739
|
this.renegotiationUnsubscribe = this.neighbourhood.subscribeSfuCallRenegotiationOffer(this.agentDid, (event) => {
|
|
2511
2740
|
if (!ours(event))
|
|
2512
2741
|
return;
|
|
2513
2742
|
this.offerQueue = this.offerQueue
|
|
2514
2743
|
.then(() => joined)
|
|
2515
|
-
.then(() =>
|
|
2744
|
+
.then(() => {
|
|
2745
|
+
if (event.participantId === this.state.participantId)
|
|
2746
|
+
return this.applyServerOffer(pc, event);
|
|
2747
|
+
});
|
|
2516
2748
|
});
|
|
2517
2749
|
this.rosterUnsubscribe = this.neighbourhood.subscribeSfuRoomRoster((roster) => {
|
|
2518
2750
|
if (!ours(roster) || this.state.peerConnection !== pc)
|
|
@@ -2524,6 +2756,17 @@ class SfuManager {
|
|
|
2524
2756
|
this.noticeRoster(pc, roster.participants);
|
|
2525
2757
|
});
|
|
2526
2758
|
});
|
|
2759
|
+
// A notice can name the id the join in flight is about to return.
|
|
2760
|
+
this.replacedUnsubscribe ?? (this.replacedUnsubscribe = this.neighbourhood.subscribeSfuSessionReplaced((event) => {
|
|
2761
|
+
if (!ours(event))
|
|
2762
|
+
return;
|
|
2763
|
+
const stopIfHeld = () => {
|
|
2764
|
+
if (this.heldIds.has(event.participantId))
|
|
2765
|
+
this.stopReplaced(event);
|
|
2766
|
+
};
|
|
2767
|
+
stopIfHeld();
|
|
2768
|
+
void this.joinSettled.then(stopIfHeld);
|
|
2769
|
+
}));
|
|
2527
2770
|
for (const unsubscribe of previous)
|
|
2528
2771
|
unsubscribe?.();
|
|
2529
2772
|
}
|
|
@@ -2533,12 +2776,12 @@ class SfuManager {
|
|
|
2533
2776
|
return;
|
|
2534
2777
|
// The mapping first: the tracks this offer adds arrive while it is applied.
|
|
2535
2778
|
for (const entry of event.trackMapping ?? []) {
|
|
2536
|
-
this.midToParticipant.set(entry.mid, entry.agentDid);
|
|
2779
|
+
this.midToParticipant.set(entry.mid, { participantId: entry.participantId, did: entry.agentDid });
|
|
2537
2780
|
}
|
|
2538
2781
|
try {
|
|
2539
2782
|
await pc.setRemoteDescription(new RTCSessionDescription(JSON.parse(event.sdpOffer)));
|
|
2540
2783
|
await pc.setLocalDescription(await pc.createAnswer());
|
|
2541
|
-
await this.neighbourhood.sfuCallAnswerServerOffer(this.neighbourhoodUrl, event.roomName, JSON.stringify(pc.localDescription));
|
|
2784
|
+
await this.neighbourhood.sfuCallAnswerServerOffer(this.neighbourhoodUrl, event.roomName, event.participantId, JSON.stringify(pc.localDescription));
|
|
2542
2785
|
this.answeredOffer = event.sdpOffer;
|
|
2543
2786
|
}
|
|
2544
2787
|
catch (err) {
|
|
@@ -2553,53 +2796,71 @@ class SfuManager {
|
|
|
2553
2796
|
}
|
|
2554
2797
|
}
|
|
2555
2798
|
/**
|
|
2556
|
-
* Make the participants match `
|
|
2799
|
+
* Make the participants match `sessions`, the room's roster: everyone new
|
|
2557
2800
|
* joins, and — when `complete`, as the roster event is — everyone
|
|
2558
2801
|
* missing leaves. The join's own roster can lag the room, so it only adds.
|
|
2802
|
+
* This session is never a participant; this agent's other devices are.
|
|
2559
2803
|
*/
|
|
2560
|
-
applyRoster(
|
|
2561
|
-
const present =
|
|
2562
|
-
for (const
|
|
2563
|
-
this.departed.delete(
|
|
2564
|
-
this.ensureParticipant(
|
|
2804
|
+
applyRoster(sessions, complete) {
|
|
2805
|
+
const present = sessions.filter((s) => s.participantId !== this.state.participantId);
|
|
2806
|
+
for (const { participantId, agentDid } of present) {
|
|
2807
|
+
this.departed.delete(participantId);
|
|
2808
|
+
this.ensureParticipant(participantId, agentDid);
|
|
2565
2809
|
}
|
|
2566
2810
|
if (!complete)
|
|
2567
2811
|
return;
|
|
2568
|
-
|
|
2569
|
-
|
|
2812
|
+
const listed = new Set(present.map((s) => s.participantId));
|
|
2813
|
+
for (const [participantId, participant] of [...this.state.participants]) {
|
|
2814
|
+
if (listed.has(participantId))
|
|
2570
2815
|
continue;
|
|
2571
|
-
this.state.participants.delete(
|
|
2572
|
-
this.departed.add(
|
|
2816
|
+
this.state.participants.delete(participantId);
|
|
2817
|
+
this.departed.add(participantId);
|
|
2573
2818
|
for (const [mid, owner] of this.midToParticipant) {
|
|
2574
|
-
if (owner ===
|
|
2819
|
+
if (owner.participantId === participantId)
|
|
2575
2820
|
this.midToParticipant.delete(mid);
|
|
2576
2821
|
}
|
|
2577
2822
|
this.emit("participant-left", participant);
|
|
2578
2823
|
}
|
|
2579
2824
|
}
|
|
2580
|
-
/** The participant for `did`, joining them to the call if they are new. */
|
|
2581
|
-
ensureParticipant(did) {
|
|
2582
|
-
let participant = this.state.participants.get(
|
|
2825
|
+
/** The participant for session `participantId` of `did`, joining them to the call if they are new. */
|
|
2826
|
+
ensureParticipant(participantId, did) {
|
|
2827
|
+
let participant = this.state.participants.get(participantId);
|
|
2583
2828
|
if (!participant) {
|
|
2584
2829
|
participant = {
|
|
2830
|
+
participantId,
|
|
2585
2831
|
did,
|
|
2586
2832
|
stream: new MediaStream(),
|
|
2587
2833
|
hasAudio: false,
|
|
2588
2834
|
hasVideo: false,
|
|
2589
2835
|
isActiveSpeaker: false,
|
|
2590
2836
|
};
|
|
2591
|
-
this.state.participants.set(
|
|
2837
|
+
this.state.participants.set(participantId, participant);
|
|
2592
2838
|
this.emit("participant-joined", participant);
|
|
2593
2839
|
}
|
|
2594
2840
|
return participant;
|
|
2595
2841
|
}
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2842
|
+
/**
|
|
2843
|
+
* A later join from this device replaced a session of this call: the
|
|
2844
|
+
* executor has already dropped it. Stop as `leave` does, but never
|
|
2845
|
+
* rejoin — the other tab has the call now — and say so with `replaced`.
|
|
2846
|
+
* A session this manager got since (a reconnect's) is left.
|
|
2847
|
+
*/
|
|
2848
|
+
stopReplaced(event) {
|
|
2849
|
+
console.info("SFU: another tab on this device joined the call; this one stops");
|
|
2850
|
+
if (this.state.participantId === event.participantId)
|
|
2851
|
+
this.state.participantId = null;
|
|
2852
|
+
this.stop();
|
|
2853
|
+
void this.leaveSession();
|
|
2854
|
+
this.resetParticipants();
|
|
2855
|
+
this.emit("replaced", event);
|
|
2599
2856
|
}
|
|
2600
|
-
|
|
2857
|
+
/** End this manager's call locally: no reconnect in flight continues, nothing is sent. */
|
|
2858
|
+
stop() {
|
|
2601
2859
|
this.generation++;
|
|
2602
2860
|
this.releaseServerEvents();
|
|
2861
|
+
this.replacedUnsubscribe?.();
|
|
2862
|
+
this.replacedUnsubscribe = null;
|
|
2863
|
+
this.heldIds.clear();
|
|
2603
2864
|
this.endRestart();
|
|
2604
2865
|
this.networkUnsubscribe?.();
|
|
2605
2866
|
this.networkUnsubscribe = null;
|
|
@@ -2619,12 +2880,16 @@ class SfuManager {
|
|
|
2619
2880
|
this.state.peerConnection.close();
|
|
2620
2881
|
this.state.peerConnection = null;
|
|
2621
2882
|
}
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
2883
|
+
this.state.localStream = null;
|
|
2884
|
+
}
|
|
2885
|
+
refreshKinds(participant) {
|
|
2886
|
+
participant.hasAudio = participant.stream.getAudioTracks().length > 0;
|
|
2887
|
+
participant.hasVideo = participant.stream.getVideoTracks().length > 0;
|
|
2888
|
+
}
|
|
2889
|
+
/** End the call: locally, and on the executor if this manager joined. */
|
|
2890
|
+
async leave() {
|
|
2891
|
+
this.stop();
|
|
2892
|
+
await this.leaveSession();
|
|
2628
2893
|
this.resetParticipants();
|
|
2629
2894
|
}
|
|
2630
2895
|
/** Forget the call's participants, telling listeners each one left. */
|
|
@@ -2633,7 +2898,6 @@ class SfuManager {
|
|
|
2633
2898
|
this.emit("participant-left", participant);
|
|
2634
2899
|
}
|
|
2635
2900
|
this.state.participants.clear();
|
|
2636
|
-
this.state.participantId = null;
|
|
2637
2901
|
this.midToParticipant.clear();
|
|
2638
2902
|
this.departed.clear();
|
|
2639
2903
|
}
|
|
@@ -2644,7 +2908,7 @@ class SfuManager {
|
|
|
2644
2908
|
return;
|
|
2645
2909
|
}
|
|
2646
2910
|
try {
|
|
2647
|
-
await this.neighbourhood.sfuCallSetQualityPreference(this.neighbourhoodUrl, this.roomId, preference);
|
|
2911
|
+
await this.neighbourhood.sfuCallSetQualityPreference(this.neighbourhoodUrl, this.roomId, this.state.participantId, preference);
|
|
2648
2912
|
}
|
|
2649
2913
|
catch (e) {
|
|
2650
2914
|
console.error("Failed to set quality preference:", e);
|
|
@@ -2683,7 +2947,7 @@ class SfuManager {
|
|
|
2683
2947
|
return;
|
|
2684
2948
|
}
|
|
2685
2949
|
try {
|
|
2686
|
-
await this.neighbourhood.sfuSendData(this.neighbourhoodUrl, this.roomId, channelLabel, data, binary);
|
|
2950
|
+
await this.neighbourhood.sfuSendData(this.neighbourhoodUrl, this.roomId, this.state.participantId, channelLabel, data, binary);
|
|
2687
2951
|
}
|
|
2688
2952
|
catch (e) {
|
|
2689
2953
|
console.error("SFU: sendData failed:", e);
|
|
@@ -2691,7 +2955,8 @@ class SfuManager {
|
|
|
2691
2955
|
}
|
|
2692
2956
|
}
|
|
2693
2957
|
/**
|
|
2694
|
-
* Subscribe to data channel messages from other participants
|
|
2958
|
+
* Subscribe to data channel messages from other participants — this
|
|
2959
|
+
* agent's other devices included, this session's own messages not.
|
|
2695
2960
|
* Returns an unsubscribe function. Only one subscription per
|
|
2696
2961
|
* manager instance — a second call replaces the first.
|
|
2697
2962
|
*/
|
|
@@ -2705,8 +2970,11 @@ class SfuManager {
|
|
|
2705
2970
|
/* swallow */
|
|
2706
2971
|
}
|
|
2707
2972
|
}
|
|
2708
|
-
this.dataChannelUnsubscribe =
|
|
2709
|
-
this.
|
|
2973
|
+
this.dataChannelUnsubscribe = this.neighbourhood.subscribeSfuDataChannel((message) => {
|
|
2974
|
+
if (message.senderParticipantId && message.senderParticipantId === this.state.participantId)
|
|
2975
|
+
return;
|
|
2976
|
+
callback(message);
|
|
2977
|
+
});
|
|
2710
2978
|
return () => {
|
|
2711
2979
|
if (this.dataChannelUnsubscribe) {
|
|
2712
2980
|
try {
|
|
@@ -2735,7 +3003,7 @@ SfuManager.MAX_RECONNECTS = 3;
|
|
|
2735
3003
|
SfuManager.REJOIN_WINDOW_MS = 120000;
|
|
2736
3004
|
/** How long an ICE restart has to bring the connection back before a rebuild. */
|
|
2737
3005
|
SfuManager.RESTART_TIMEOUT_MS = 5000;
|
|
2738
|
-
/** How long the roster may leave this
|
|
3006
|
+
/** How long the roster may leave this session out before the call is rebuilt. */
|
|
2739
3007
|
SfuManager.UNLISTED_GRACE_MS = 3000;
|
|
2740
3008
|
|
|
2741
3009
|
/**
|
|
@@ -2872,9 +3140,37 @@ function parseCallMessage(payload) {
|
|
|
2872
3140
|
// ── Signalling channel ──────────────────────────────────────────────
|
|
2873
3141
|
const RTC_PREDICATE = "ad4m://session/rtc";
|
|
2874
3142
|
const TARGET_ALL = "*";
|
|
3143
|
+
/**
|
|
3144
|
+
* A mesh peer: one agent on one device. An agent calling from two devices is
|
|
3145
|
+
* two peers, each with its own connection to everyone else, so neither device's
|
|
3146
|
+
* media or teardown can stand in for the other's.
|
|
3147
|
+
*/
|
|
3148
|
+
function meshPeerId(did, device) {
|
|
3149
|
+
if (!isMeshDevice(device))
|
|
3150
|
+
throw new Error(`mesh: device id must be non-empty and without '#': ${JSON.stringify(device)}`);
|
|
3151
|
+
return `${did}#${device}`;
|
|
3152
|
+
}
|
|
3153
|
+
/** A device id a mesh peer id can carry: `#` would move the split in {@link agentOfMeshPeer}. */
|
|
3154
|
+
function isMeshDevice(device) {
|
|
3155
|
+
return typeof device === "string" && device.length > 0 && !device.includes("#");
|
|
3156
|
+
}
|
|
3157
|
+
/** The agent a mesh peer id belongs to. */
|
|
3158
|
+
function agentOfMeshPeer(peerId) {
|
|
3159
|
+
const at = peerId.lastIndexOf("#");
|
|
3160
|
+
return at === -1 ? peerId : peerId.slice(0, at);
|
|
3161
|
+
}
|
|
2875
3162
|
/**
|
|
2876
3163
|
* Bridge NeighbourhoodProxy telepresence to the SignallingChannel
|
|
2877
|
-
* the mesh consumes
|
|
3164
|
+
* the mesh consumes, as the peer `selfDid` on `selfDevice`.
|
|
3165
|
+
*
|
|
3166
|
+
* ## Peers are devices
|
|
3167
|
+
*
|
|
3168
|
+
* The sender a message reports is a {@link meshPeerId}: the link's author,
|
|
3169
|
+
* which the executor verified, and the device the author's payload names. A
|
|
3170
|
+
* device is only the author's own claim, so it can tell this agent's devices
|
|
3171
|
+
* apart but never speak for another agent. Only this device's own echo is
|
|
3172
|
+
* dropped: a broadcast from another device of this agent — the executor hands
|
|
3173
|
+
* one to every client of the agent — is a peer like any other.
|
|
2878
3174
|
*
|
|
2879
3175
|
* ## Why unicast runs emulated over broadcast
|
|
2880
3176
|
*
|
|
@@ -2884,9 +3180,11 @@ const TARGET_ALL = "*";
|
|
|
2884
3180
|
* receivers drop anything not addressed to them. That provides
|
|
2885
3181
|
* **addressing, not privacy** — every peer still receives the payload.
|
|
2886
3182
|
*/
|
|
2887
|
-
function createTelepresenceChannel(proxy, selfDid) {
|
|
3183
|
+
function createTelepresenceChannel(proxy, selfDid, selfDevice) {
|
|
3184
|
+
const self = meshPeerId(selfDid, selfDevice);
|
|
2888
3185
|
const resultListeners = new Set();
|
|
2889
3186
|
let subscribed = Promise.resolve();
|
|
3187
|
+
let warnedNoDevice = false;
|
|
2890
3188
|
const report = (result) => {
|
|
2891
3189
|
for (const cb of resultListeners) {
|
|
2892
3190
|
try {
|
|
@@ -2906,7 +3204,7 @@ function createTelepresenceChannel(proxy, selfDid) {
|
|
|
2906
3204
|
try {
|
|
2907
3205
|
sent = proxy.sendBroadcastU({
|
|
2908
3206
|
links: [{
|
|
2909
|
-
source: JSON.stringify(payload),
|
|
3207
|
+
source: JSON.stringify({ device: selfDevice, message: payload }),
|
|
2910
3208
|
predicate: RTC_PREDICATE,
|
|
2911
3209
|
target: to?.agentId ?? TARGET_ALL,
|
|
2912
3210
|
}],
|
|
@@ -2943,10 +3241,7 @@ function createTelepresenceChannel(proxy, selfDid) {
|
|
|
2943
3241
|
if (typeof predicate !== "string" || predicate !== RTC_PREDICATE)
|
|
2944
3242
|
return;
|
|
2945
3243
|
// Emulated unicast: drop messages addressed to someone else
|
|
2946
|
-
if (target && target !== TARGET_ALL && target !==
|
|
2947
|
-
return;
|
|
2948
|
-
// Drop our own echo
|
|
2949
|
-
if (link.author === selfDid)
|
|
3244
|
+
if (target && target !== TARGET_ALL && target !== self)
|
|
2950
3245
|
return;
|
|
2951
3246
|
let parsed;
|
|
2952
3247
|
try {
|
|
@@ -2955,7 +3250,22 @@ function createTelepresenceChannel(proxy, selfDid) {
|
|
|
2955
3250
|
catch {
|
|
2956
3251
|
return;
|
|
2957
3252
|
}
|
|
2958
|
-
|
|
3253
|
+
if (typeof parsed !== "object" || parsed === null)
|
|
3254
|
+
return;
|
|
3255
|
+
const { device, message } = parsed;
|
|
3256
|
+
if (!isMeshDevice(device)) {
|
|
3257
|
+
// An SDK from before peers were devices sends none: say so once, or a mixed call just looks empty.
|
|
3258
|
+
if (device === undefined && !warnedNoDevice) {
|
|
3259
|
+
warnedNoDevice = true;
|
|
3260
|
+
console.warn(`mesh: ${link.author} sends no device id (an older SDK); its mesh messages are ignored`);
|
|
3261
|
+
}
|
|
3262
|
+
return;
|
|
3263
|
+
}
|
|
3264
|
+
const from = meshPeerId(link.author, device);
|
|
3265
|
+
// Drop this device's own echo, and only that.
|
|
3266
|
+
if (from === self)
|
|
3267
|
+
return;
|
|
3268
|
+
cb(from, message);
|
|
2959
3269
|
};
|
|
2960
3270
|
subscribed = proxy.addSignalHandler(handler).catch((err) => {
|
|
2961
3271
|
console.warn("mesh: signal handler registration failed — inbound traffic will get missed:", err);
|
|
@@ -3154,6 +3464,9 @@ class MeshManager {
|
|
|
3154
3464
|
});
|
|
3155
3465
|
// A session announces itself once `join` returns; peers offer at once.
|
|
3156
3466
|
await this.channel.listening?.();
|
|
3467
|
+
// Left or destroyed while the channel came up: start nothing.
|
|
3468
|
+
if (this.closed)
|
|
3469
|
+
return;
|
|
3157
3470
|
/*
|
|
3158
3471
|
* Spend the transport's first-send cost on something that does not
|
|
3159
3472
|
* matter. The first broadcast on a freshly joined neighbourhood has
|
|
@@ -3313,6 +3626,8 @@ class MeshManager {
|
|
|
3313
3626
|
handleData(from, message) {
|
|
3314
3627
|
const msg = {
|
|
3315
3628
|
senderDid: from,
|
|
3629
|
+
// The mesh keys its peers by DID: one session per agent.
|
|
3630
|
+
senderParticipantId: from,
|
|
3316
3631
|
neighbourhoodUrl: "",
|
|
3317
3632
|
roomName: this.callId,
|
|
3318
3633
|
channelLabel: message.label,
|
|
@@ -3926,15 +4241,47 @@ class MeshManager {
|
|
|
3926
4241
|
|
|
3927
4242
|
/**
|
|
3928
4243
|
* Call-presence predicate. When the session joins, it publishes an
|
|
3929
|
-
* online-status link with this predicate
|
|
3930
|
-
* Other agents polling `onlineAgents()` use this
|
|
3931
|
-
* roster without a join message
|
|
4244
|
+
* online-status link with this predicate, its mesh peer id as source and
|
|
4245
|
+
* the room id as target. Other agents polling `onlineAgents()` use this
|
|
4246
|
+
* to discover the roster without a join message; one agent's devices each
|
|
4247
|
+
* add a link of their own to the agent's one status.
|
|
3932
4248
|
*/
|
|
3933
4249
|
const CALL_PRESENCE_PREDICATE = "ad4m://session/in-call";
|
|
3934
4250
|
/** How often (ms) the mesh session polls `onlineAgents` for roster changes. */
|
|
3935
4251
|
const ROSTER_POLL_INTERVAL_MS = 3000;
|
|
4252
|
+
/**
|
|
4253
|
+
* The mesh peer a call-presence link of `did` announces, or `null`. A link
|
|
4254
|
+
* counts only for a peer of the agent whose status carries it, so no agent
|
|
4255
|
+
* can place another in a call.
|
|
4256
|
+
*/
|
|
4257
|
+
function presencePeer(did, link, roomId) {
|
|
4258
|
+
if (link?.predicate !== CALL_PRESENCE_PREDICATE || link.target !== roomId)
|
|
4259
|
+
return null;
|
|
4260
|
+
const source = link.source;
|
|
4261
|
+
if (typeof source !== "string" || source === did || agentOfMeshPeer(source) !== did)
|
|
4262
|
+
return null;
|
|
4263
|
+
return source;
|
|
4264
|
+
}
|
|
4265
|
+
/**
|
|
4266
|
+
* Where a mesh session hears that this device joined the same call again,
|
|
4267
|
+
* from another tab. `BroadcastChannel` reaches every tab of one browser
|
|
4268
|
+
* profile — the same reach as the `localStorage` the device id lives in.
|
|
4269
|
+
*/
|
|
4270
|
+
function sameDeviceChannel(agentDid, device, roomId) {
|
|
4271
|
+
const Channel = globalThis.BroadcastChannel;
|
|
4272
|
+
if (typeof Channel !== "function")
|
|
4273
|
+
return null;
|
|
4274
|
+
try {
|
|
4275
|
+
return new Channel(`ad4m-call:${agentDid}:${device}:${roomId}`);
|
|
4276
|
+
}
|
|
4277
|
+
catch {
|
|
4278
|
+
return null;
|
|
4279
|
+
}
|
|
4280
|
+
}
|
|
3936
4281
|
function createSession(config) {
|
|
3937
|
-
const { api, roomId, agentDid, neighbourhoodUrl, topology, sfuConfig, iceServers, channel, setOnlineStatus, ownOnlineStatus, onlineAgents, localSfuStatus, sfuServesAllMembers, } = config;
|
|
4282
|
+
const { api, roomId, agentDid, neighbourhoodUrl, topology, sfuConfig, iceServers, deviceId, channel, setOnlineStatus, ownOnlineStatus, onlineAgents, localSfuStatus, sfuServesAllMembers, } = config;
|
|
4283
|
+
const device = deviceId || defaultDeviceId();
|
|
4284
|
+
const selfPeer = meshPeerId(agentDid, device);
|
|
3938
4285
|
let state = "idle";
|
|
3939
4286
|
let sfuManager = null;
|
|
3940
4287
|
let meshManager = null;
|
|
@@ -3947,6 +4294,8 @@ function createSession(config) {
|
|
|
3947
4294
|
const trackListeners = [];
|
|
3948
4295
|
const dataListeners = [];
|
|
3949
4296
|
let dataUnsubscribe = null;
|
|
4297
|
+
/** The mesh call's line to this device's other tabs; see {@link sameDeviceChannel}. */
|
|
4298
|
+
let sameDevice = null;
|
|
3950
4299
|
function emit(event, ...args) {
|
|
3951
4300
|
const cbs = callbacks.get(event);
|
|
3952
4301
|
if (cbs)
|
|
@@ -3957,6 +4306,13 @@ function createSession(config) {
|
|
|
3957
4306
|
state = next;
|
|
3958
4307
|
emit("state-changed", next);
|
|
3959
4308
|
}
|
|
4309
|
+
/** `destroy()` ran: a join still resolving must not go on to reach the executor. */
|
|
4310
|
+
/** Set when `destroy()` starts, before its awaits: a join that resumes
|
|
4311
|
+
* while the session closes must not go on. */
|
|
4312
|
+
let destroying = false;
|
|
4313
|
+
function destroyed() {
|
|
4314
|
+
return destroying || state === "closed";
|
|
4315
|
+
}
|
|
3960
4316
|
/**
|
|
3961
4317
|
* Resolve the effective topology.
|
|
3962
4318
|
*
|
|
@@ -3990,7 +4346,7 @@ function createSession(config) {
|
|
|
3990
4346
|
* leaving restores if the status cannot be read then. */
|
|
3991
4347
|
let statusBeforeCall = [];
|
|
3992
4348
|
let announced = false;
|
|
3993
|
-
/** This agent's status links, without this
|
|
4349
|
+
/** This agent's status links, without this device's presence link for this call. */
|
|
3994
4350
|
async function ownLinksWithoutCall() {
|
|
3995
4351
|
const status = ownOnlineStatus ? await ownOnlineStatus() : null;
|
|
3996
4352
|
const links = [];
|
|
@@ -3998,7 +4354,7 @@ function createSession(config) {
|
|
|
3998
4354
|
const l = link.data;
|
|
3999
4355
|
if (!l?.source || l.target === undefined)
|
|
4000
4356
|
continue;
|
|
4001
|
-
if (l
|
|
4357
|
+
if (presencePeer(agentDid, l, roomId) === selfPeer)
|
|
4002
4358
|
continue;
|
|
4003
4359
|
links.push({ source: l.source, target: l.target, ...(l.predicate ? { predicate: l.predicate } : {}) });
|
|
4004
4360
|
}
|
|
@@ -4016,7 +4372,7 @@ function createSession(config) {
|
|
|
4016
4372
|
console.warn("session: reading own status failed:", err);
|
|
4017
4373
|
return [];
|
|
4018
4374
|
});
|
|
4019
|
-
const presence = { source:
|
|
4375
|
+
const presence = { source: selfPeer, predicate: CALL_PRESENCE_PREDICATE, target: roomId };
|
|
4020
4376
|
await setOnlineStatus({ links: [...statusBeforeCall, presence] });
|
|
4021
4377
|
announced = true;
|
|
4022
4378
|
}
|
|
@@ -4043,10 +4399,11 @@ function createSession(config) {
|
|
|
4043
4399
|
/**
|
|
4044
4400
|
* Poll online agents and reconcile the mesh roster.
|
|
4045
4401
|
*
|
|
4046
|
-
*
|
|
4047
|
-
* `CALL_PRESENCE_PREDICATE
|
|
4048
|
-
* The poll reads
|
|
4049
|
-
*
|
|
4402
|
+
* Each device in the call carries a link with predicate
|
|
4403
|
+
* `CALL_PRESENCE_PREDICATE`, its peer id as source and the room id as
|
|
4404
|
+
* target, in its agent's status. The poll reads other agents' statuses
|
|
4405
|
+
* from the online-agents list and this agent's own — its other devices —
|
|
4406
|
+
* from `ownOnlineStatus`, and passes the peers to `mesh.setRoster()`.
|
|
4050
4407
|
* That function opens connections to new arrivals and tears down
|
|
4051
4408
|
* connections to departed peers.
|
|
4052
4409
|
*/
|
|
@@ -4057,25 +4414,28 @@ function createSession(config) {
|
|
|
4057
4414
|
polling = true;
|
|
4058
4415
|
try {
|
|
4059
4416
|
const agents = await onlineAgents();
|
|
4417
|
+
const own = ownOnlineStatus ? await ownOnlineStatus() : null;
|
|
4060
4418
|
// The session left while the poll was in flight.
|
|
4061
4419
|
if (meshManager !== mesh)
|
|
4062
4420
|
return;
|
|
4063
|
-
const inCall =
|
|
4064
|
-
|
|
4065
|
-
|
|
4066
|
-
|
|
4067
|
-
|
|
4068
|
-
|
|
4069
|
-
// matching this room.
|
|
4070
|
-
for (const link of agent.status?.data?.links ?? []) {
|
|
4071
|
-
const l = link.data;
|
|
4072
|
-
if (l?.predicate === CALL_PRESENCE_PREDICATE && l.target === roomId) {
|
|
4073
|
-
inCall.push(agent.did);
|
|
4074
|
-
break;
|
|
4075
|
-
}
|
|
4421
|
+
const inCall = new Set();
|
|
4422
|
+
const collect = (did, links) => {
|
|
4423
|
+
for (const link of links ?? []) {
|
|
4424
|
+
const peer = presencePeer(did, link.data, roomId);
|
|
4425
|
+
if (peer && peer !== selfPeer)
|
|
4426
|
+
inCall.add(peer);
|
|
4076
4427
|
}
|
|
4428
|
+
};
|
|
4429
|
+
// Each agent's status is a signed perspective: its links sit
|
|
4430
|
+
// under `data`. Whether an executor lists the caller among the
|
|
4431
|
+
// online agents varies, so this agent's own status is read here
|
|
4432
|
+
// from where it was set, never from the list.
|
|
4433
|
+
for (const agent of agents) {
|
|
4434
|
+
if (agent.did !== agentDid)
|
|
4435
|
+
collect(agent.did, agent.status?.data?.links);
|
|
4077
4436
|
}
|
|
4078
|
-
|
|
4437
|
+
collect(agentDid, own?.data?.links);
|
|
4438
|
+
mesh.setRoster([...inCall]);
|
|
4079
4439
|
}
|
|
4080
4440
|
catch (err) {
|
|
4081
4441
|
console.warn("session: roster poll failed:", err);
|
|
@@ -4097,9 +4457,13 @@ function createSession(config) {
|
|
|
4097
4457
|
}
|
|
4098
4458
|
// ── Mesh wiring helpers ─────────────────────────────────────────
|
|
4099
4459
|
function wireMeshEvents(mesh) {
|
|
4100
|
-
for (const event of ["
|
|
4460
|
+
for (const event of ["peer-state", "peer-recovery", "error"]) {
|
|
4101
4461
|
mesh.on(event, (...args) => emit(event, ...args));
|
|
4102
4462
|
}
|
|
4463
|
+
// As the SFU path reports them: the session (here, the device) and the agent it belongs to.
|
|
4464
|
+
for (const event of ["participant-joined", "participant-left", "participant-updated"]) {
|
|
4465
|
+
mesh.on(event, (p) => emit(event, { ...p, participantId: p.did, did: agentOfMeshPeer(p.did) }));
|
|
4466
|
+
}
|
|
4103
4467
|
mesh.on("stream-added", (stream, track) => {
|
|
4104
4468
|
emit("stream-added", stream, track);
|
|
4105
4469
|
for (const cb of trackListeners)
|
|
@@ -4109,19 +4473,83 @@ function createSession(config) {
|
|
|
4109
4473
|
emit("stream-removed", stream, track);
|
|
4110
4474
|
});
|
|
4111
4475
|
}
|
|
4476
|
+
/**
|
|
4477
|
+
* The mesh another tab of this device took over. A destroy also lets the mesh go, so only
|
|
4478
|
+
* this tells a join that its call moved on, and that the presence link is no longer its own.
|
|
4479
|
+
*/
|
|
4480
|
+
let replacedMesh = null;
|
|
4481
|
+
/**
|
|
4482
|
+
* Listen for this device joining the same mesh call from another tab,
|
|
4483
|
+
* and tell any tab already in it. Both tabs are one peer, so only one
|
|
4484
|
+
* can hold the call: the earlier lets go, without withdrawing the
|
|
4485
|
+
* presence link the two share, and says `replaced`.
|
|
4486
|
+
*/
|
|
4487
|
+
function claimDevice(mesh) {
|
|
4488
|
+
sameDevice = sameDeviceChannel(agentDid, device, roomId);
|
|
4489
|
+
if (!sameDevice)
|
|
4490
|
+
return;
|
|
4491
|
+
const channel = sameDevice;
|
|
4492
|
+
channel.onmessage = (event) => {
|
|
4493
|
+
if (meshManager !== mesh || event.data?.joined !== true)
|
|
4494
|
+
return;
|
|
4495
|
+
replacedMesh = mesh;
|
|
4496
|
+
releaseDevice();
|
|
4497
|
+
stopRosterPolling();
|
|
4498
|
+
if (dataUnsubscribe) {
|
|
4499
|
+
dataUnsubscribe();
|
|
4500
|
+
dataUnsubscribe = null;
|
|
4501
|
+
}
|
|
4502
|
+
meshManager = null;
|
|
4503
|
+
announced = false;
|
|
4504
|
+
void mesh.leave();
|
|
4505
|
+
// Idle before listeners hear it: one may join again at once.
|
|
4506
|
+
setState("idle");
|
|
4507
|
+
emit("replaced", { targetDid: agentDid, neighbourhoodUrl, roomName: roomId, participantId: selfPeer });
|
|
4508
|
+
};
|
|
4509
|
+
channel.postMessage({ joined: true });
|
|
4510
|
+
}
|
|
4511
|
+
function releaseDevice() {
|
|
4512
|
+
if (!sameDevice)
|
|
4513
|
+
return;
|
|
4514
|
+
sameDevice.onmessage = null;
|
|
4515
|
+
sameDevice.close();
|
|
4516
|
+
sameDevice = null;
|
|
4517
|
+
}
|
|
4112
4518
|
// ── SFU wiring helpers ──────────────────────────────────────────
|
|
4113
4519
|
function wireSfuEvents(sfu) {
|
|
4520
|
+
// A manager the session let go of (replaced, or left) may still settle a call it
|
|
4521
|
+
// made before: none of its events reach the session's listeners.
|
|
4522
|
+
const current = () => sfuManager === sfu;
|
|
4114
4523
|
for (const event of ["topology-changed", "participant-joined", "participant-left", "active-speaker", "error"]) {
|
|
4115
|
-
sfu.on(event, (...args) =>
|
|
4524
|
+
sfu.on(event, (...args) => { if (current())
|
|
4525
|
+
emit(event, ...args); });
|
|
4116
4526
|
}
|
|
4117
4527
|
sfu.on("stream-added", (stream, track) => {
|
|
4528
|
+
if (!current())
|
|
4529
|
+
return;
|
|
4118
4530
|
emit("stream-added", stream, track);
|
|
4119
4531
|
for (const cb of trackListeners)
|
|
4120
4532
|
cb(stream, track);
|
|
4121
4533
|
});
|
|
4122
4534
|
sfu.on("stream-removed", (stream, track) => {
|
|
4535
|
+
if (!current())
|
|
4536
|
+
return;
|
|
4123
4537
|
emit("stream-removed", stream, track);
|
|
4124
4538
|
});
|
|
4539
|
+
// Another tab on this device took the call over. The manager has stopped
|
|
4540
|
+
// and will not rejoin; the session is idle and may join again.
|
|
4541
|
+
sfu.on("replaced", (event) => {
|
|
4542
|
+
if (sfuManager !== sfu)
|
|
4543
|
+
return;
|
|
4544
|
+
if (dataUnsubscribe) {
|
|
4545
|
+
dataUnsubscribe();
|
|
4546
|
+
dataUnsubscribe = null;
|
|
4547
|
+
}
|
|
4548
|
+
sfuManager = null;
|
|
4549
|
+
// Idle before listeners hear it: one may join again at once.
|
|
4550
|
+
setState("idle");
|
|
4551
|
+
emit("replaced", event);
|
|
4552
|
+
});
|
|
4125
4553
|
}
|
|
4126
4554
|
// ── Session object ──────────────────────────────────────────────
|
|
4127
4555
|
const session = {
|
|
@@ -4132,6 +4560,8 @@ function createSession(config) {
|
|
|
4132
4560
|
throw new Error("Session already active");
|
|
4133
4561
|
setState("joining");
|
|
4134
4562
|
const topo = await resolveTopology();
|
|
4563
|
+
if (destroyed())
|
|
4564
|
+
throw new Error("Session destroyed");
|
|
4135
4565
|
if (topo === "mesh") {
|
|
4136
4566
|
if (!channel) {
|
|
4137
4567
|
throw new Error("Mesh topology requires a signalling channel — " +
|
|
@@ -4162,7 +4592,7 @@ function createSession(config) {
|
|
|
4162
4592
|
const mesh = new MeshManager({
|
|
4163
4593
|
channel,
|
|
4164
4594
|
callId: roomId,
|
|
4165
|
-
selfId:
|
|
4595
|
+
selfId: selfPeer,
|
|
4166
4596
|
...(meshIce.length > 0 ? { iceServers: meshIce } : {}),
|
|
4167
4597
|
onNetworkChange: (cb) => api.onNetworkChange(cb),
|
|
4168
4598
|
checkConnection: () => api.checkConnection(),
|
|
@@ -4173,11 +4603,29 @@ function createSession(config) {
|
|
|
4173
4603
|
for (const cb of dataListeners)
|
|
4174
4604
|
cb(msg);
|
|
4175
4605
|
});
|
|
4606
|
+
claimDevice(mesh);
|
|
4176
4607
|
await mesh.join(localStream);
|
|
4608
|
+
// Replaced while joining: the session is idle again.
|
|
4609
|
+
if (replacedMesh === mesh)
|
|
4610
|
+
return;
|
|
4611
|
+
// Destroyed while the mesh joined: destroy() already let the
|
|
4612
|
+
// mesh go and found nothing to leave.
|
|
4613
|
+
if (destroyed())
|
|
4614
|
+
throw new Error("Session destroyed");
|
|
4177
4615
|
// Announce this agent's presence in the call, then
|
|
4178
4616
|
// start polling so the mesh reconciles connections
|
|
4179
4617
|
// against whoever else the roster contains.
|
|
4180
4618
|
await announceCallPresence();
|
|
4619
|
+
// Replaced while announcing, destroyed or not: the link stays,
|
|
4620
|
+
// for the tab that took over.
|
|
4621
|
+
if (replacedMesh === mesh) {
|
|
4622
|
+
announced = false;
|
|
4623
|
+
return;
|
|
4624
|
+
}
|
|
4625
|
+
if (destroyed()) {
|
|
4626
|
+
await withdrawCallPresence();
|
|
4627
|
+
throw new Error("Session destroyed");
|
|
4628
|
+
}
|
|
4181
4629
|
startRosterPolling();
|
|
4182
4630
|
emit("topology-changed", "mesh");
|
|
4183
4631
|
setState("active");
|
|
@@ -4187,13 +4635,19 @@ function createSession(config) {
|
|
|
4187
4635
|
const iceConfig = iceServers && iceServers.length > 0
|
|
4188
4636
|
? { servers: iceServers.map(s => ({ urls: s.urls, ...(s.username ? { username: s.username } : {}), ...(s.credential ? { credential: s.credential } : {}) })) }
|
|
4189
4637
|
: undefined;
|
|
4190
|
-
|
|
4191
|
-
|
|
4192
|
-
|
|
4638
|
+
const manager = new SfuManager(api, roomId, agentDid, neighbourhoodUrl, iceConfig, sfuConfig, device);
|
|
4639
|
+
sfuManager = manager;
|
|
4640
|
+
wireSfuEvents(manager);
|
|
4641
|
+
dataUnsubscribe = manager.subscribeDataChannel((msg) => {
|
|
4193
4642
|
for (const cb of dataListeners)
|
|
4194
4643
|
cb(msg);
|
|
4195
4644
|
});
|
|
4196
|
-
await
|
|
4645
|
+
await manager.join(localStream);
|
|
4646
|
+
if (destroyed())
|
|
4647
|
+
throw new Error("Session destroyed");
|
|
4648
|
+
// Replaced while joining: the session is idle again.
|
|
4649
|
+
if (sfuManager !== manager)
|
|
4650
|
+
return;
|
|
4197
4651
|
emit("topology-changed", "sfu");
|
|
4198
4652
|
setState("active");
|
|
4199
4653
|
},
|
|
@@ -4202,6 +4656,7 @@ function createSession(config) {
|
|
|
4202
4656
|
return;
|
|
4203
4657
|
setState("leaving");
|
|
4204
4658
|
stopRosterPolling();
|
|
4659
|
+
releaseDevice();
|
|
4205
4660
|
await withdrawCallPresence();
|
|
4206
4661
|
if (dataUnsubscribe) {
|
|
4207
4662
|
dataUnsubscribe();
|
|
@@ -4220,7 +4675,8 @@ function createSession(config) {
|
|
|
4220
4675
|
get participants() {
|
|
4221
4676
|
if (meshManager) {
|
|
4222
4677
|
return meshManager.getParticipants().map(p => ({
|
|
4223
|
-
|
|
4678
|
+
participantId: p.did,
|
|
4679
|
+
agentDid: agentOfMeshPeer(p.did),
|
|
4224
4680
|
stream: p.stream,
|
|
4225
4681
|
hasAudio: p.hasAudio,
|
|
4226
4682
|
hasVideo: p.hasVideo,
|
|
@@ -4229,6 +4685,7 @@ function createSession(config) {
|
|
|
4229
4685
|
}
|
|
4230
4686
|
if (sfuManager) {
|
|
4231
4687
|
return sfuManager.getParticipants().map(p => ({
|
|
4688
|
+
participantId: p.participantId,
|
|
4232
4689
|
agentDid: p.did,
|
|
4233
4690
|
stream: p.stream,
|
|
4234
4691
|
hasAudio: p.hasAudio,
|
|
@@ -4313,12 +4770,14 @@ function createSession(config) {
|
|
|
4313
4770
|
}
|
|
4314
4771
|
},
|
|
4315
4772
|
async destroy() {
|
|
4773
|
+
destroying = true;
|
|
4316
4774
|
// Capture refs before leave() nulls them
|
|
4317
4775
|
const mesh = meshManager;
|
|
4318
4776
|
const sfu = sfuManager;
|
|
4319
4777
|
if (state === "active" || state === "joining")
|
|
4320
4778
|
await session.leave();
|
|
4321
4779
|
stopRosterPolling();
|
|
4780
|
+
releaseDevice();
|
|
4322
4781
|
if (mesh) {
|
|
4323
4782
|
await mesh.destroy();
|
|
4324
4783
|
}
|
|
@@ -4450,6 +4909,7 @@ class NeighbourhoodProxy {
|
|
|
4450
4909
|
}
|
|
4451
4910
|
}
|
|
4452
4911
|
const proxy = this;
|
|
4912
|
+
const deviceId = options?.deviceId || defaultDeviceId();
|
|
4453
4913
|
const session = createSession({
|
|
4454
4914
|
api: __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f"),
|
|
4455
4915
|
roomId: roomName,
|
|
@@ -4458,12 +4918,13 @@ class NeighbourhoodProxy {
|
|
|
4458
4918
|
topology: options?.topology ?? "auto",
|
|
4459
4919
|
sfuConfig: options?.sfuConfig,
|
|
4460
4920
|
iceServers: options?.iceServers,
|
|
4921
|
+
deviceId,
|
|
4461
4922
|
localSfuStatus: __classPrivateFieldGet$a(this, _NeighbourhoodProxy_sfuStatusCache, "f") ?? undefined,
|
|
4462
4923
|
sfuServesAllMembers: () => __classPrivateFieldGet$a(proxy, _NeighbourhoodProxy_client, "f").sfuServesAllMembers(__classPrivateFieldGet$a(proxy, _NeighbourhoodProxy_pID, "f")),
|
|
4463
4924
|
// Mesh needs a signalling channel and presence callbacks.
|
|
4464
4925
|
// SFU ignores these — they remain unused when the resolved
|
|
4465
4926
|
// topology selects the SFU path.
|
|
4466
|
-
channel: createTelepresenceChannel(proxy, __classPrivateFieldGet$a(proxy, _NeighbourhoodProxy_agentDid, "f")),
|
|
4927
|
+
channel: createTelepresenceChannel(proxy, __classPrivateFieldGet$a(proxy, _NeighbourhoodProxy_agentDid, "f"), deviceId),
|
|
4467
4928
|
ownOnlineStatus: () => proxy.ownOnlineStatus(),
|
|
4468
4929
|
setOnlineStatus: (status) => proxy.setOnlineStatusU(status),
|
|
4469
4930
|
onlineAgents: () => proxy.onlineAgents(),
|
|
@@ -4505,17 +4966,27 @@ class NeighbourhoodProxy {
|
|
|
4505
4966
|
async sfuListRooms() {
|
|
4506
4967
|
return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuListRooms();
|
|
4507
4968
|
}
|
|
4508
|
-
|
|
4509
|
-
|
|
4969
|
+
/** Join from `deviceId`: a join from the same device replaces this agent's session there. */
|
|
4970
|
+
async callJoin(neighbourhoodUrl, roomName, sdpOffer, deviceId, sessionKey) {
|
|
4971
|
+
return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallJoin(neighbourhoodUrl, roomName, sdpOffer, deviceId, sessionKey);
|
|
4510
4972
|
}
|
|
4511
|
-
|
|
4512
|
-
|
|
4973
|
+
/** Leave the session `participantId` (the join's). */
|
|
4974
|
+
async callLeave(neighbourhoodUrl, roomName, participantId) {
|
|
4975
|
+
return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallLeave(neighbourhoodUrl, roomName, participantId);
|
|
4513
4976
|
}
|
|
4514
|
-
async callSetQualityPreference(neighbourhoodUrl, roomName, preference) {
|
|
4515
|
-
return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallSetQualityPreference(neighbourhoodUrl, roomName, preference);
|
|
4977
|
+
async callSetQualityPreference(neighbourhoodUrl, roomName, participantId, preference) {
|
|
4978
|
+
return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallSetQualityPreference(neighbourhoodUrl, roomName, participantId, preference);
|
|
4516
4979
|
}
|
|
4517
|
-
async callAnswerServerOffer(neighbourhoodUrl, roomName, sdpAnswer) {
|
|
4518
|
-
return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallAnswerServerOffer(neighbourhoodUrl, roomName, sdpAnswer);
|
|
4980
|
+
async callAnswerServerOffer(neighbourhoodUrl, roomName, participantId, sdpAnswer) {
|
|
4981
|
+
return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuCallAnswerServerOffer(neighbourhoodUrl, roomName, participantId, sdpAnswer);
|
|
4982
|
+
}
|
|
4983
|
+
/**
|
|
4984
|
+
* Subscribe to the executor's notices that a session of this agent was
|
|
4985
|
+
* replaced by a later join from the same device. Returns an unsubscribe
|
|
4986
|
+
* function.
|
|
4987
|
+
*/
|
|
4988
|
+
subscribeSessionReplaced(callback) {
|
|
4989
|
+
return __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").subscribeSfuSessionReplaced(callback);
|
|
4519
4990
|
}
|
|
4520
4991
|
/**
|
|
4521
4992
|
* Subscribe to server-pushed renegotiation offers for `targetDid`.
|
|
@@ -4534,12 +5005,12 @@ class NeighbourhoodProxy {
|
|
|
4534
5005
|
return __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").subscribeSfuMigrateEvent(targetDid, callback);
|
|
4535
5006
|
}
|
|
4536
5007
|
// ── SFU trickle ICE ─────────────────────────────────────────────────
|
|
4537
|
-
async addIceCandidate(neighbourhoodUrl, roomName, candidate) {
|
|
4538
|
-
return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuAddIceCandidate(neighbourhoodUrl, roomName, candidate);
|
|
5008
|
+
async addIceCandidate(neighbourhoodUrl, roomName, participantId, candidate) {
|
|
5009
|
+
return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuAddIceCandidate(neighbourhoodUrl, roomName, participantId, candidate);
|
|
4539
5010
|
}
|
|
4540
5011
|
// ── SFU data channel relay ────────────────────────────────────────
|
|
4541
|
-
async sendData(neighbourhoodUrl, roomName, channelLabel, data, binary = false) {
|
|
4542
|
-
return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuSendData(neighbourhoodUrl, roomName, channelLabel, data, binary);
|
|
5012
|
+
async sendData(neighbourhoodUrl, roomName, participantId, channelLabel, data, binary = false) {
|
|
5013
|
+
return await __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").sfuSendData(neighbourhoodUrl, roomName, participantId, channelLabel, data, binary);
|
|
4543
5014
|
}
|
|
4544
5015
|
subscribeDataChannel(callback) {
|
|
4545
5016
|
return __classPrivateFieldGet$a(this, _NeighbourhoodProxy_client, "f").subscribeSfuDataChannel(callback);
|
|
@@ -10213,13 +10684,24 @@ var __classPrivateFieldGet$6 = (undefined && undefined.__classPrivateFieldGet) |
|
|
|
10213
10684
|
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");
|
|
10214
10685
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
10215
10686
|
};
|
|
10216
|
-
var _PerspectiveClient_apiClient, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient;
|
|
10687
|
+
var _PerspectiveClient_instances, _PerspectiveClient_apiClient, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient, _PerspectiveClient_released;
|
|
10217
10688
|
/** The wire form of a model query's classes: `class_name` for one, `class_names` for a union. */
|
|
10218
10689
|
function classParams(className) {
|
|
10219
10690
|
return Array.isArray(className) ? { class_names: className } : { class_name: className };
|
|
10220
10691
|
}
|
|
10692
|
+
/** A new live query's id (a UUID v4). The client mints it, so it can end the
|
|
10693
|
+
* subscription without the subscribe call's reply. `getRandomValues`, not
|
|
10694
|
+
* `randomUUID`: a page served over plain HTTP has only the former. */
|
|
10695
|
+
function mintSubscriptionId() {
|
|
10696
|
+
const b = globalThis.crypto.getRandomValues(new Uint8Array(16));
|
|
10697
|
+
b[6] = (b[6] & 0x0f) | 0x40;
|
|
10698
|
+
b[8] = (b[8] & 0x3f) | 0x80;
|
|
10699
|
+
const hex = Array.from(b, x => x.toString(16).padStart(2, '0')).join('');
|
|
10700
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
10701
|
+
}
|
|
10221
10702
|
class PerspectiveClient {
|
|
10222
10703
|
constructor(baseUrl, token, sharedApiClient) {
|
|
10704
|
+
_PerspectiveClient_instances.add(this);
|
|
10223
10705
|
_PerspectiveClient_apiClient.set(this, void 0);
|
|
10224
10706
|
_PerspectiveClient_expressionClient.set(this, void 0);
|
|
10225
10707
|
_PerspectiveClient_neighbourhoodClient.set(this, void 0);
|
|
@@ -10290,7 +10772,8 @@ class PerspectiveClient {
|
|
|
10290
10772
|
/** Open a live SPARQL query. Updates arrive through {@link onQueryUpdate}. */
|
|
10291
10773
|
/** `options.signal` cancels the call, and the executor stops computing the first result. */
|
|
10292
10774
|
async subscribeQuery(uuid, query, options) {
|
|
10293
|
-
|
|
10775
|
+
const subscriptionId = mintSubscriptionId();
|
|
10776
|
+
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));
|
|
10294
10777
|
}
|
|
10295
10778
|
/** Every `query-subscription-update` event on this client's socket. */
|
|
10296
10779
|
onQueryUpdate(cb) {
|
|
@@ -10325,7 +10808,8 @@ class PerspectiveClient {
|
|
|
10325
10808
|
/** Open a live model query over one class or several. Updates arrive through {@link onQueryUpdate}. */
|
|
10326
10809
|
/** `options.signal` cancels the call, and the executor stops computing the first result. */
|
|
10327
10810
|
async modelSubscribe(uuid, className, queryJson, options) {
|
|
10328
|
-
|
|
10811
|
+
const subscriptionId = mintSubscriptionId();
|
|
10812
|
+
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));
|
|
10329
10813
|
}
|
|
10330
10814
|
async add(name) {
|
|
10331
10815
|
const handle = await __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").call('perspective.create', { name });
|
|
@@ -10596,7 +11080,23 @@ class PerspectiveClient {
|
|
|
10596
11080
|
return __classPrivateFieldGet$6(this, _PerspectiveClient_apiClient, "f").onReconnect(callback);
|
|
10597
11081
|
}
|
|
10598
11082
|
}
|
|
10599
|
-
_PerspectiveClient_apiClient = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap()
|
|
11083
|
+
_PerspectiveClient_apiClient = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap(), _PerspectiveClient_instances = new WeakSet(), _PerspectiveClient_released =
|
|
11084
|
+
/** A subscribe call that failed (timed out, aborted, refused) leaves no live
|
|
11085
|
+
* query on the executor that nobody holds. The client minted its id, so it
|
|
11086
|
+
* disposes it without the reply. A timeout or an abort sends `request.cancel`
|
|
11087
|
+
* first, and the executor handles a cancel before the calls after it: the
|
|
11088
|
+
* cancel either stops the call before it registers, or the dispose finds the
|
|
11089
|
+
* subscription. The dispose goes out before the call's error is thrown, and
|
|
11090
|
+
* is not awaited; one that fails changes nothing. */
|
|
11091
|
+
async function _PerspectiveClient_released(uuid, subscriptionId, call) {
|
|
11092
|
+
try {
|
|
11093
|
+
return await call;
|
|
11094
|
+
}
|
|
11095
|
+
catch (e) {
|
|
11096
|
+
this.disposeQuerySubscription(uuid, subscriptionId).catch(() => { });
|
|
11097
|
+
throw e;
|
|
11098
|
+
}
|
|
11099
|
+
};
|
|
10600
11100
|
|
|
10601
11101
|
var __classPrivateFieldSet$5 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
10602
11102
|
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
@@ -25044,4 +25544,4 @@ const SCOPED_EVENTS = new Set([
|
|
|
25044
25544
|
"flow-state-changed",
|
|
25045
25545
|
]);
|
|
25046
25546
|
|
|
25047
|
-
export { ACCEPTED_BY_GETTER, AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, CALL_PROTOCOL_VERSION, Capability, CapabilityInput, ComputeLogEntry, Container, DEFAULT_ICE_SERVERS, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, FlowInstance, FlowInstanceRecord, FlowTransitionProposal, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, IdentityClient, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LONG_METHODS, LONG_TIMEOUT_MS, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LiveQuery, LocalModel, LocalModelInput, MENTION_TEXT_LIMIT, Mentioning, MeshManager, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PROPOSER_GETTER, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, READ_METHODS, REOPEN_BASE_DELAY_MS, REOPEN_MAX_DELAY_MS, ReadOnly, Resource, ResourceInput, RpcError, RuntimeInfo, SCOPED_EVENTS, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TextContent, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, applyUpdate, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, createTelepresenceChannel, determineNamespace, determinePredicate, effectiveLiteralStorage, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, hintFor, holdsAWholeWordTerm, ifExpr, invalidatePerspectiveCache, isArrayType, isContainedScope, isContainmentTraversal, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, isTraverseScope, linkEqual, linkExpressionInputToWire, linkExpressionToWire, linkMutationsToWire, literal, looksLikeUri, mentionOf, neighbourhoodExpressionFromWire, normalizeNamespaceString, normalizeSchemaType, normalizeValue, normalizeWhereForSparql, parseCallMessage, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, reopenDelay, requireSingleParent, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString, valueToLiteralIri };
|
|
25547
|
+
export { ACCEPTED_BY_GETTER, AGENT_KIND, AGENT_KIND_BOT, AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, CALL_PROTOCOL_VERSION, Capability, CapabilityInput, ComputeLogEntry, Container, DEFAULT_ICE_SERVERS, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, FlowInstance, FlowInstanceRecord, FlowTransitionProposal, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, IdentityClient, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LONG_METHODS, LONG_TIMEOUT_MS, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LiveQuery, LocalModel, LocalModelInput, MENTION_TEXT_LIMIT, Mentioning, MeshManager, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OPENS_METHODS, OnlineAgent, Optional, PROPOSER_GETTER, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, READ_METHODS, REOPEN_BASE_DELAY_MS, REOPEN_MAX_DELAY_MS, ReadOnly, Resource, ResourceInput, RpcError, RuntimeInfo, SCOPED_EVENTS, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TextContent, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, agentKind, applyUpdate, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, createTelepresenceChannel, determineNamespace, determinePredicate, effectiveLiteralStorage, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, hintFor, holdsAWholeWordTerm, ifExpr, invalidatePerspectiveCache, isArrayType, isBot, isContainedScope, isContainmentTraversal, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, isTraverseScope, linkEqual, linkExpressionInputToWire, linkExpressionToWire, linkMutationsToWire, literal, looksLikeUri, mentionOf, neighbourhoodExpressionFromWire, normalizeNamespaceString, normalizeSchemaType, normalizeValue, normalizeWhereForSparql, parseCallMessage, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, reopenDelay, requireSingleParent, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString, valueToLiteralIri };
|