@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.
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
@@ -9,7 +9,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  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");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _PerspectiveClient_apiClient, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient;
12
+ var _PerspectiveClient_instances, _PerspectiveClient_apiClient, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient, _PerspectiveClient_released;
13
13
  import { ApiClient, RpcError } from '../apiClient';
14
14
  import { LinkExpression, LinkExpressionMutations, linkExpressionInputToWire, linkExpressionToWire, linkMutationsToWire, } from "../links/Links";
15
15
  import { NeighbourhoodProxy } from "../neighbourhood/NeighbourhoodProxy";
@@ -20,8 +20,19 @@ import { PerspectiveProxy } from './PerspectiveProxy';
20
20
  function classParams(className) {
21
21
  return Array.isArray(className) ? { class_names: className } : { class_name: className };
22
22
  }
23
+ /** A new live query's id (a UUID v4). The client mints it, so it can end the
24
+ * subscription without the subscribe call's reply. `getRandomValues`, not
25
+ * `randomUUID`: a page served over plain HTTP has only the former. */
26
+ function mintSubscriptionId() {
27
+ const b = globalThis.crypto.getRandomValues(new Uint8Array(16));
28
+ b[6] = (b[6] & 0x0f) | 0x40;
29
+ b[8] = (b[8] & 0x3f) | 0x80;
30
+ const hex = Array.from(b, x => x.toString(16).padStart(2, '0')).join('');
31
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
32
+ }
23
33
  export class PerspectiveClient {
24
34
  constructor(baseUrl, token, sharedApiClient) {
35
+ _PerspectiveClient_instances.add(this);
25
36
  _PerspectiveClient_apiClient.set(this, void 0);
26
37
  _PerspectiveClient_expressionClient.set(this, void 0);
27
38
  _PerspectiveClient_neighbourhoodClient.set(this, void 0);
@@ -92,7 +103,8 @@ export class PerspectiveClient {
92
103
  /** Open a live SPARQL query. Updates arrive through {@link onQueryUpdate}. */
93
104
  /** `options.signal` cancels the call, and the executor stops computing the first result. */
94
105
  async subscribeQuery(uuid, query, options) {
95
- return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.subscribeQuery', { uuid, query }, options);
106
+ const subscriptionId = mintSubscriptionId();
107
+ return __classPrivateFieldGet(this, _PerspectiveClient_instances, "m", _PerspectiveClient_released).call(this, uuid, subscriptionId, __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.subscribeQuery', { uuid, query, subscriptionId }, options));
96
108
  }
97
109
  /** Every `query-subscription-update` event on this client's socket. */
98
110
  onQueryUpdate(cb) {
@@ -127,7 +139,8 @@ export class PerspectiveClient {
127
139
  /** Open a live model query over one class or several. Updates arrive through {@link onQueryUpdate}. */
128
140
  /** `options.signal` cancels the call, and the executor stops computing the first result. */
129
141
  async modelSubscribe(uuid, className, queryJson, options) {
130
- return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, ...classParams(className), query_json: queryJson }, options);
142
+ const subscriptionId = mintSubscriptionId();
143
+ return __classPrivateFieldGet(this, _PerspectiveClient_instances, "m", _PerspectiveClient_released).call(this, uuid, subscriptionId, __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.modelSubscribe', { uuid, ...classParams(className), query_json: queryJson, subscriptionId }, options));
131
144
  }
132
145
  async add(name) {
133
146
  const handle = await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.create', { name });
@@ -398,4 +411,20 @@ export class PerspectiveClient {
398
411
  return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").onReconnect(callback);
399
412
  }
400
413
  }
401
- _PerspectiveClient_apiClient = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap();
414
+ _PerspectiveClient_apiClient = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap(), _PerspectiveClient_instances = new WeakSet(), _PerspectiveClient_released =
415
+ /** A subscribe call that failed (timed out, aborted, refused) leaves no live
416
+ * query on the executor that nobody holds. The client minted its id, so it
417
+ * disposes it without the reply. A timeout or an abort sends `request.cancel`
418
+ * first, and the executor handles a cancel before the calls after it: the
419
+ * cancel either stops the call before it registers, or the dispose finds the
420
+ * subscription. The dispose goes out before the call's error is thrown, and
421
+ * is not awaited; one that fails changes nothing. */
422
+ async function _PerspectiveClient_released(uuid, subscriptionId, call) {
423
+ try {
424
+ return await call;
425
+ }
426
+ catch (e) {
427
+ this.disposeQuerySubscription(uuid, subscriptionId).catch(() => { });
428
+ throw e;
429
+ }
430
+ };
package/package.json CHANGED
@@ -53,8 +53,8 @@
53
53
  "ws": "8.13.0"
54
54
  },
55
55
  "patchedDependencies": {},
56
- "version": "0.13.1-staging.7",
57
- "gitHead": "e2f1ab8f40663819f00b3fad1c5c8392e2885fca",
56
+ "version": "0.13.1-staging.9",
57
+ "gitHead": "99f10808f17ef318ba53146e279220749a7e7662",
58
58
  "scripts": {
59
59
  "build": "patch-package && tsc && pnpm run bundle",
60
60
  "bundle": "rollup -c rollup.config.js",
@@ -1054,19 +1054,19 @@ describe('NeighbourhoodClient', () => {
1054
1054
  expect(ws.rpc[0].params).toEqual({ 'sfu-call-renegotiation-offer': null, 'sfu-data': null, 'sfu-migrate': null });
1055
1055
 
1056
1056
  const room = { neighbourhoodUrl: 'neighbourhood://n', roomName: 'r' };
1057
- ws.emit(event('sfu-call-renegotiation-offer', { targetDid: 'did:other', ...room, sdpOffer: '{}' }));
1058
- ws.emit(event('sfu-call-renegotiation-offer', { targetDid: 'did:me', ...room, sdpOffer: '{"x":1}' }));
1057
+ ws.emit(event('sfu-call-renegotiation-offer', { targetDid: 'did:other', participantId: 'P2', ...room, sdpOffer: '{}' }));
1058
+ ws.emit(event('sfu-call-renegotiation-offer', { targetDid: 'did:me', participantId: 'P1', ...room, sdpOffer: '{"x":1}' }));
1059
1059
  ws.emit(event('sfu-migrate', { targetDid: 'did:me', ...room, migrateToDid: 'did:node' }));
1060
- const message = { senderDid: 'did:other', ...room, channelLabel: 'chat', binary: false, data: 'hi' };
1060
+ const message = { senderDid: 'did:other', senderParticipantId: 'P2', ...room, channelLabel: 'chat', binary: false, data: 'hi' };
1061
1061
  ws.emit(event('sfu-data', message));
1062
1062
 
1063
1063
  expect(offers).toHaveBeenCalledTimes(1);
1064
- expect(offers).toHaveBeenCalledWith({ targetDid: 'did:me', ...room, sdpOffer: '{"x":1}', trackMapping: undefined });
1064
+ expect(offers).toHaveBeenCalledWith({ targetDid: 'did:me', participantId: 'P1', ...room, sdpOffer: '{"x":1}', trackMapping: undefined });
1065
1065
  expect(migrations).toHaveBeenCalledWith({ targetDid: 'did:me', ...room, migrateToDid: 'did:node' });
1066
1066
  expect(data).toHaveBeenCalledWith(expect.objectContaining(message));
1067
1067
 
1068
1068
  releaseOffers();
1069
- ws.emit(event('sfu-call-renegotiation-offer', { targetDid: 'did:me', ...room, sdpOffer: '{}' }));
1069
+ ws.emit(event('sfu-call-renegotiation-offer', { targetDid: 'did:me', participantId: 'P1', ...room, sdpOffer: '{}' }));
1070
1070
  expect(offers).toHaveBeenCalledTimes(1);
1071
1071
  });
1072
1072
  });
@@ -10,6 +10,7 @@ import {
10
10
  } from "./Agent";
11
11
  import { HostingUserInfo, PaymentRequestResult, ComputeLogEntry } from "../runtime/RuntimeTypes";
12
12
  import { AgentStatus } from "./AgentStatus";
13
+ import { AGENT_KIND } from "./AgentKind";
13
14
  import { LinkMutations, LinkExpression, LinkInput, linkEqual } from "../links/Links";
14
15
  import { VerificationRequestResult } from "../runtime/RuntimeTypes";
15
16
  import { PersistentCache, createPersistentCache } from "../cache/PersistentCache";
@@ -189,6 +190,25 @@ export class AgentClient {
189
190
  return this.updatePublicPerspective({ links: [...kept, ...added] } as PerspectiveInput);
190
191
  }
191
192
 
193
+ /**
194
+ * Say what kind of agent this is in its public perspective (`AGENT_KIND`; a bot is
195
+ * `AGENT_KIND_BOT`), replacing any kind it said before, or say none with `null`. Changes
196
+ * nothing when the perspective already says exactly that, so it can be called on every start.
197
+ */
198
+ async setKind(kind: string | null): Promise<Agent> {
199
+ const me = await this.me();
200
+ const said = (me.perspective?.links ?? []).filter(
201
+ (l) => l.data.source === me.did && l.data.predicate === AGENT_KIND,
202
+ );
203
+ if ((kind === null && said.length === 0) || (said.length === 1 && said[0].data.target === kind)) {
204
+ return me;
205
+ }
206
+ return this.mutatePublicPerspective({
207
+ additions: kind === null ? [] : [{ source: me.did, predicate: AGENT_KIND, target: kind } as LinkInput],
208
+ removals: said as LinkMutations['removals'],
209
+ });
210
+ }
211
+
192
212
  /** Has the executor sign `links` as this agent, in a throwaway perspective. */
193
213
  async #signLinks(links: LinkInput[]): Promise<LinkExpression[]> {
194
214
  const { uuid } = await this.#apiClient.call('perspective.create', { name: 'Agent Perspective Proxy' });
@@ -0,0 +1,28 @@
1
+ import type { Agent } from "./Agent";
2
+
3
+ /**
4
+ * What kind of agent this is, as the agent says itself: one link in its public perspective,
5
+ * `<its did> ad4m://agent_kind <kind>`.
6
+ *
7
+ * Only the agent can write its public perspective, so the kind is its own claim, the same in
8
+ * every space and every app. Nothing checks it: a bot that leaves it out reads as an agent of no
9
+ * declared kind. It exists so an app can tell a program speaking from a person without each
10
+ * community marking its bots by hand.
11
+ */
12
+ export const AGENT_KIND = "ad4m://agent_kind";
13
+
14
+ /** The kind of an agent that is a program acting by itself: a bot, an AI agent, an integration. */
15
+ export const AGENT_KIND_BOT = "ad4m://bot";
16
+
17
+ /** The kind `agent` declares in its public perspective, or `undefined` when it declares none. */
18
+ export function agentKind(agent: Pick<Agent, "did" | "perspective"> | null | undefined): string | undefined {
19
+ const link = agent?.perspective?.links?.find(
20
+ (l) => l.data.source === agent.did && l.data.predicate === AGENT_KIND,
21
+ );
22
+ return link?.data.target || undefined;
23
+ }
24
+
25
+ /** Whether `agent` says it is a bot. */
26
+ export function isBot(agent: Pick<Agent, "did" | "perspective"> | null | undefined): boolean {
27
+ return agentKind(agent) === AGENT_KIND_BOT;
28
+ }
@@ -1,5 +1,6 @@
1
1
  import { Ad4mClient } from '../Ad4mClient';
2
2
  import { Link, LinkExpression } from '../links/Links';
3
+ import { AGENT_KIND, AGENT_KIND_BOT, agentKind, isBot } from './AgentKind';
3
4
 
4
5
  /**
5
6
  * `AgentClient.mutatePublicPerspective` against an in-memory executor
@@ -108,3 +109,74 @@ describe('AgentClient.mutatePublicPerspective (L4)', () => {
108
109
  client.close();
109
110
  });
110
111
  });
112
+
113
+ describe('AgentClient.setKind', () => {
114
+ it('says the agent is a bot, keeping the rest of its profile, and reads back as one', async () => {
115
+ const executor = new Executor();
116
+ (globalThis as any).WebSocket = makeFakeWebSocket(executor);
117
+ const client = new Ad4mClient('http://localhost:12000', 'token');
118
+
119
+ const agent = await client.agent.setKind(AGENT_KIND_BOT);
120
+
121
+ expect(isBot(agent)).toBe(true);
122
+ expect(agentKind(agent)).toBe(AGENT_KIND_BOT);
123
+ expect(agent.perspective!.links.slice(0, 2)).toEqual([L1, L2] as unknown as LinkExpression[]);
124
+ expect(executor.perspectives.size).toBe(0);
125
+ client.close();
126
+ });
127
+
128
+ it('changes nothing when the agent already says so, and replaces a kind it said before', async () => {
129
+ const executor = new Executor();
130
+ executor.profile = {
131
+ links: [L1, signed({ source: DID, predicate: AGENT_KIND, target: AGENT_KIND_BOT }, 2)],
132
+ };
133
+ (globalThis as any).WebSocket = makeFakeWebSocket(executor);
134
+ const client = new Ad4mClient('http://localhost:12000', 'token');
135
+ const calls: string[] = [];
136
+ const original = executor.handle.bind(executor);
137
+ executor.handle = (type, p) => {
138
+ calls.push(type);
139
+ return original(type, p);
140
+ };
141
+
142
+ await client.agent.setKind(AGENT_KIND_BOT);
143
+ expect(calls).not.toContain('agent.updateProfile');
144
+
145
+ const other = await client.agent.setKind('app://other-kind');
146
+ expect(agentKind(other)).toBe('app://other-kind');
147
+ expect(other.perspective!.links.filter((l) => l.data.predicate === AGENT_KIND)).toHaveLength(1);
148
+
149
+ const none = await client.agent.setKind(null);
150
+ expect(agentKind(none)).toBeUndefined();
151
+ expect(none.perspective!.links).toEqual([L1] as unknown as LinkExpression[]);
152
+ client.close();
153
+ });
154
+
155
+ it('leaves one kind when the profile says two', async () => {
156
+ const executor = new Executor();
157
+ executor.profile = {
158
+ links: [
159
+ L1,
160
+ signed({ source: DID, predicate: AGENT_KIND, target: AGENT_KIND_BOT }, 2),
161
+ signed({ source: DID, predicate: AGENT_KIND, target: 'app://other-kind' }, 3),
162
+ ],
163
+ };
164
+ (globalThis as any).WebSocket = makeFakeWebSocket(executor);
165
+ const client = new Ad4mClient('http://localhost:12000', 'token');
166
+
167
+ const agent = await client.agent.setKind(AGENT_KIND_BOT);
168
+
169
+ const kinds = agent.perspective!.links.filter((l) => l.data.predicate === AGENT_KIND);
170
+ expect(kinds.map((l) => l.data.target)).toEqual([AGENT_KIND_BOT]);
171
+ client.close();
172
+ });
173
+
174
+ it('reads only the kind an agent says of itself', () => {
175
+ const someoneElse = {
176
+ did: DID,
177
+ perspective: { links: [signed({ source: 'did:test:other', predicate: AGENT_KIND, target: AGENT_KIND_BOT }, 1)] },
178
+ } as any;
179
+ expect(isBot(someoneElse)).toBe(false);
180
+ expect(isBot(undefined)).toBe(false);
181
+ });
182
+ });
@@ -162,6 +162,52 @@ describe('ApiClient calls', () => {
162
162
  })
163
163
  })
164
164
 
165
+ describe('ApiClient calls that open something on the executor (OPENS_METHODS)', () => {
166
+ it('sends request.cancel when such a call times out', async () => {
167
+ const promise = call('perspective.modelSubscribe', { uuid: 'u' }, { timeoutMs: 50 })
168
+ await flush()
169
+ const req = socket(0).sent[0]
170
+ await expect(promise).rejects.toMatchObject({ name: 'RpcError', status: 408 })
171
+ expect(socket(0).sent[1]).toMatchObject({ type: 'request.cancel', params: { targetId: req.id } })
172
+ })
173
+
174
+ it('sends no request.cancel when a call without it times out', async () => {
175
+ // A write that timed out still runs to its end on the executor.
176
+ const promise = call('perspective.addLink', { uuid: 'u' }, { timeoutMs: 50 })
177
+ await flush()
178
+ await expect(promise).rejects.toMatchObject({ status: 408 })
179
+ expect(socket(0).sent.map((m) => m.type)).toEqual(['perspective.addLink'])
180
+ })
181
+
182
+ it('sends request.cancel for a timed-out subscribeQuery too', async () => {
183
+ const promise = call('perspective.subscribeQuery', { uuid: 'u' }, { timeoutMs: 50 })
184
+ await flush()
185
+ const req = socket(0).sent[0]
186
+ await expect(promise).rejects.toMatchObject({ status: 408 })
187
+ expect(socket(0).sent[1]).toMatchObject({ type: 'request.cancel', params: { targetId: req.id } })
188
+ })
189
+
190
+ it('drops a reply that crossed the cancel: the caller owns the id it sent', async () => {
191
+ const events: unknown[] = []
192
+ client.on('agent-updated', (e) => { events.push(e) })
193
+ const promise = call('perspective.modelSubscribe', { uuid: 'u', subscriptionId: 's1' }, { timeoutMs: 50 })
194
+ await flush()
195
+ const req = socket(0).sent.find((m) => m.type === 'perspective.modelSubscribe')!
196
+ await expect(promise).rejects.toMatchObject({ status: 408 })
197
+
198
+ const cancel = socket(0).sent.find((m) => m.type === 'request.cancel')!
199
+ socket(0).reply({ id: cancel.id, result: { cancelled: false, targetId: req.id } })
200
+ socket(0).reply({ id: req.id, result: { subscriptionId: 's1' } })
201
+ expect(events).toEqual([])
202
+ // The client stays usable: the next call is answered as usual.
203
+ const next = call('agent.get')
204
+ await flush()
205
+ const nextReq = socket(0).sent[socket(0).sent.length - 1]
206
+ socket(0).reply({ id: nextReq.id, result: { did: 'd' } })
207
+ await expect(next).resolves.toEqual({ did: 'd' })
208
+ })
209
+ })
210
+
165
211
  describe('ApiClient connect-phase failures', () => {
166
212
  beforeEach(() => { TestSocket.autoOpen = false })
167
213
 
package/src/apiClient.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { callSafely } from './notifyListeners'
2
- import { LONG_METHODS, READ_METHODS } from './generated/api/RpcMethods'
2
+ import { LONG_METHODS, OPENS_METHODS, READ_METHODS } from './generated/api/RpcMethods'
3
3
  import type { RpcMethod, RpcMethods } from './generated/api/RpcMethods'
4
4
  import type { EventMap, EventName } from './generated/api/Events'
5
5
 
@@ -32,7 +32,10 @@ export interface CallOptions {
32
32
  */
33
33
  signal?: AbortSignal
34
34
  /** Timeout in ms, from the call to the reply. Defaults to 30 s, or
35
- * {@link LONG_TIMEOUT_MS} for a method the executor marks long. */
35
+ * {@link LONG_TIMEOUT_MS} for a method the executor marks long. A call
36
+ * that opens something on the executor (`OPENS_METHODS`, a live query) is
37
+ * cancelled there when it times out, as when `signal` aborts it; any other
38
+ * call that times out still runs to its end. */
36
39
  timeoutMs?: number
37
40
  }
38
41
 
@@ -545,7 +548,17 @@ export class ApiClient {
545
548
  signal?.removeEventListener('abort', onAbort)
546
549
  fn()
547
550
  }
551
+ // Tell the executor the call is no longer wanted, so it stops the work. A late
552
+ // reply finds no pending call and is dropped.
553
+ const cancel = () => {
554
+ if (pending.sent && this._ws?.readyState === 1 /* OPEN */) {
555
+ this._send(this._ws, JSON.stringify({ id: nextId(), type: 'request.cancel', params: { targetId: id } }))
556
+ }
557
+ }
548
558
  const timer = setTimeout(() => {
559
+ // Only a call that opens something is cancelled on timeout: a write that
560
+ // timed out still runs to its end on the executor, as it always has.
561
+ if ((OPENS_METHODS as ReadonlySet<string>).has(type)) cancel()
549
562
  settle(() => reject(new RpcError(408, `RPC call '${type}' timed out after ${timeoutMs}ms`)))
550
563
  // A connect that never completes (a black-holed port) would hold every later
551
564
  // call. Drop it once no call waits on it, so the next call dials again.
@@ -555,9 +568,7 @@ export class ApiClient {
555
568
  }
556
569
  }, timeoutMs)
557
570
  const onAbort = () => {
558
- if (pending.sent && this._ws?.readyState === 1 /* OPEN */) {
559
- this._send(this._ws, JSON.stringify({ id: nextId(), type: 'request.cancel', params: { targetId: id } }))
560
- }
571
+ cancel()
561
572
  settle(() => reject(new DOMException('Aborted', 'AbortError')))
562
573
  }
563
574
  const pending: PendingCall = {
@@ -13,7 +13,7 @@ export type CallSessionInfo = { roomName: string, neighbourhoodUrl: string, part
13
13
  redirectTo?: string,
14
14
  /**
15
15
  * Roster of existing participants at join time, format:
16
- * `"participantId:did"` (local) or `"remote-did:did"` (cascade).
16
+ * `"participantId:did"`.
17
17
  * For track-to-DID attribution, use the `track_mapping` field on
18
18
  * each renegotiation offer — the SDP mids are assigned there.
19
19
  */
@@ -23,6 +23,7 @@ import type { SfuCallRenegotiationOffer } from "./SfuCallRenegotiationOffer";
23
23
  import type { SfuDataMessage } from "./SfuDataMessage";
24
24
  import type { SfuMigrateEvent } from "./SfuMigrateEvent";
25
25
  import type { SfuRoomRoster } from "./SfuRoomRoster";
26
+ import type { SfuSessionReplaced } from "./SfuSessionReplaced";
26
27
  import type { TranscriptionTextFilter } from "./TranscriptionTextFilter";
27
28
 
28
29
  /** Every event the executor emits: its payload (the message without `type`). */
@@ -50,6 +51,7 @@ export interface EventMap {
50
51
  "sfu-migrate": SfuMigrateEvent;
51
52
  "sfu-data": SfuDataMessage;
52
53
  "sfu-room-roster": SfuRoomRoster;
54
+ "sfu-session-replaced": SfuSessionReplaced;
53
55
  "flow-state-changed": FlowStateChangedEvent;
54
56
  "identity-fork": IdentityForkEvent;
55
57
  }
@@ -0,0 +1,7 @@
1
+ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
+
3
+ /**
4
+ * `perspective.modelSubscribe`: [`PerspectiveModelQueryParams`] and the client's
5
+ * subscription id (see [`PerspectiveSubscribeQueryParams`]).
6
+ */
7
+ export type PerspectiveModelSubscribeParams = { uuid: string, class_name?: string, class_names?: Array<string>, query_json: string, subscriptionId: string, };
@@ -0,0 +1,7 @@
1
+ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
+
3
+ /**
4
+ * `perspective.subscribeQuery`: the subscription id is the client's, so it can end the
5
+ * subscription without the reply (after a timeout or an abort).
6
+ */
7
+ export type PerspectiveSubscribeQueryParams = { uuid: string, query: string, subscriptionId: string, };
@@ -116,6 +116,7 @@ import type { PerspectiveLinkMutationsParams } from "./PerspectiveLinkMutationsP
116
116
  import type { PerspectiveMintFlowReceiptParams } from "./PerspectiveMintFlowReceiptParams";
117
117
  import type { PerspectiveMintFlowReceiptResult } from "./PerspectiveMintFlowReceiptResult";
118
118
  import type { PerspectiveModelQueryParams } from "./PerspectiveModelQueryParams";
119
+ import type { PerspectiveModelSubscribeParams } from "./PerspectiveModelSubscribeParams";
119
120
  import type { PerspectiveNamedShacl } from "./PerspectiveNamedShacl";
120
121
  import type { PerspectiveProposeFlowTransitionParams } from "./PerspectiveProposeFlowTransitionParams";
121
122
  import type { PerspectiveQueryLinksParams } from "./PerspectiveQueryLinksParams";
@@ -131,6 +132,7 @@ import type { PerspectiveShacl } from "./PerspectiveShacl";
131
132
  import type { PerspectiveShaclNameParams } from "./PerspectiveShaclNameParams";
132
133
  import type { PerspectiveSparqlParams } from "./PerspectiveSparqlParams";
133
134
  import type { PerspectiveSubjectClassesOfParams } from "./PerspectiveSubjectClassesOfParams";
135
+ import type { PerspectiveSubscribeQueryParams } from "./PerspectiveSubscribeQueryParams";
134
136
  import type { PerspectiveSubscribed } from "./PerspectiveSubscribed";
135
137
  import type { PerspectiveSubscriptionParams } from "./PerspectiveSubscriptionParams";
136
138
  import type { PerspectiveUpdateLinkParams } from "./PerspectiveUpdateLinkParams";
@@ -171,6 +173,7 @@ import type { SetUserFreeAccessRequest } from "./SetUserFreeAccessRequest";
171
173
  import type { SfuAddIceCandidateParams } from "./SfuAddIceCandidateParams";
172
174
  import type { SfuAnswerServerOfferParams } from "./SfuAnswerServerOfferParams";
173
175
  import type { SfuCallJoinParams } from "./SfuCallJoinParams";
176
+ import type { SfuCallLeaveParams } from "./SfuCallLeaveParams";
174
177
  import type { SfuCascadeStatus } from "./SfuCascadeStatus";
175
178
  import type { SfuConfig } from "./SfuConfig";
176
179
  import type { SfuEnsureMembershipParams } from "./SfuEnsureMembershipParams";
@@ -178,6 +181,7 @@ import type { SfuNeighbourhoodParams } from "./SfuNeighbourhoodParams";
178
181
  import type { SfuParticipantQualityPreference } from "./SfuParticipantQualityPreference";
179
182
  import type { SfuPerspectiveParams } from "./SfuPerspectiveParams";
180
183
  import type { SfuQualityPreferenceParams } from "./SfuQualityPreferenceParams";
184
+ import type { SfuRestartIceParams } from "./SfuRestartIceParams";
181
185
  import type { SfuRoomInfo } from "./SfuRoomInfo";
182
186
  import type { SfuRoomParams } from "./SfuRoomParams";
183
187
  import type { SfuSendDataParams } from "./SfuSendDataParams";
@@ -316,7 +320,7 @@ export interface RpcMethods {
316
320
  "perspective.linkMutations": { params: PerspectiveLinkMutationsParams; result: PerspectiveLinkDiff };
317
321
  "perspective.mintFlowReceipt": { params: PerspectiveMintFlowReceiptParams; result: PerspectiveMintFlowReceiptResult };
318
322
  "perspective.modelQuery": { params: PerspectiveModelQueryParams; result: string };
319
- "perspective.modelSubscribe": { params: PerspectiveModelQueryParams; result: PerspectiveSubscribed };
323
+ "perspective.modelSubscribe": { params: PerspectiveModelSubscribeParams; result: PerspectiveSubscribed };
320
324
  "perspective.proposeFlowTransition": { params: PerspectiveProposeFlowTransitionParams; result: ProposeOutcome };
321
325
  "perspective.publishSnapshot": { params: PerspectiveUuidParams; result: string };
322
326
  "perspective.queryLinks": { params: PerspectiveQueryLinksParams; result: Array<DecoratedLinkExpression> };
@@ -335,7 +339,7 @@ export interface RpcMethods {
335
339
  "perspective.runInterpretationWithHarness": { params: RunInterpretationWithHarnessRequest; result: Array<string> };
336
340
  "perspective.snapshot": { params: PerspectiveUuidParams; result: DecoratedPerspective | null };
337
341
  "perspective.subjectClassesOf": { params: PerspectiveSubjectClassesOfParams; result: { [key in string]: Array<string> } };
338
- "perspective.subscribeQuery": { params: PerspectiveQueryParams; result: PerspectiveSubscribed };
342
+ "perspective.subscribeQuery": { params: PerspectiveSubscribeQueryParams; result: PerspectiveSubscribed };
339
343
  "perspective.subscribeSparql": { params: PerspectiveQueryParams; result: PerspectiveSubscribed };
340
344
  "perspective.update": { params: PerspectiveUpdateParams; result: PerspectiveHandle };
341
345
  "perspective.updateLink": { params: PerspectiveUpdateLinkParams; result: DecoratedLinkExpression };
@@ -384,8 +388,8 @@ export interface RpcMethods {
384
388
  "sfu.addIceCandidate": { params: SfuAddIceCandidateParams; result: boolean };
385
389
  "sfu.callAnswerServerOffer": { params: SfuAnswerServerOfferParams; result: boolean };
386
390
  "sfu.callJoin": { params: SfuCallJoinParams; result: CallSessionInfo };
387
- "sfu.callLeave": { params: SfuRoomParams; result: boolean };
388
- "sfu.callRestartIce": { params: SfuRoomParams; result: boolean };
391
+ "sfu.callLeave": { params: SfuCallLeaveParams; result: boolean };
392
+ "sfu.callRestartIce": { params: SfuRestartIceParams; result: boolean };
389
393
  "sfu.callSetQualityPreference": { params: SfuQualityPreferenceParams; result: boolean };
390
394
  "sfu.cascadeStatus": { params: Record<string, never>; result: SfuCascadeStatus };
391
395
  "sfu.ensureMembership": { params: SfuEnsureMembershipParams; result: boolean };
@@ -521,3 +525,9 @@ export const LONG_METHODS: ReadonlySet<RpcMethod> = new Set<RpcMethod>([
521
525
  "perspective.runInterpretationWithHarness",
522
526
  "runtime.restartHolochain",
523
527
  ]);
528
+
529
+ /** Calls that open something on the executor that outlives them (a live query): the client cancels one that timed out, as one it aborted. */
530
+ export const OPENS_METHODS: ReadonlySet<RpcMethod> = new Set<RpcMethod>([
531
+ "perspective.modelSubscribe",
532
+ "perspective.subscribeQuery",
533
+ ]);
@@ -1,6 +1,10 @@
1
1
  // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
2
 
3
3
  export type SfuAddIceCandidateParams = { neighbourhoodUrl: string, roomName: string,
4
+ /**
5
+ * The caller's session, as its join returned it.
6
+ */
7
+ participantId: string,
4
8
  /**
5
9
  * The candidate's SDP attribute line.
6
10
  */
@@ -1,6 +1,10 @@
1
1
  // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
2
 
3
3
  export type SfuAnswerServerOfferParams = { neighbourhoodUrl: string, roomName: string,
4
+ /**
5
+ * The caller's session, as its join returned it.
6
+ */
7
+ participantId: string,
4
8
  /**
5
9
  * JSON-encoded `RTCSessionDescriptionInit`.
6
10
  */
@@ -5,6 +5,19 @@ export type SfuCallJoinParams = { neighbourhoodUrl: string, roomName: string,
5
5
  * JSON-encoded `RTCSessionDescriptionInit`.
6
6
  */
7
7
  sdpOffer: string,
8
+ /**
9
+ * The device the caller joins from (an opaque id, 1 to 128 characters).
10
+ * The caller's session from the same device is replaced; one from
11
+ * another device stays beside it.
12
+ */
13
+ deviceId: string,
14
+ /**
15
+ * The client's random key for this call session (1 to 128 characters,
16
+ * never published). A rebuild of the session sends it again and
17
+ * replaces its own dead session; a join whose key a later join from the
18
+ * same device replaced is refused with 409: that session must stop.
19
+ */
20
+ sessionKey: string,
8
21
  /**
9
22
  * The caller can reach other cascade nodes, so a busy room may answer
10
23
  * with `redirectTo` instead of a session. Off by default: an SDK client
@@ -0,0 +1,11 @@
1
+ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
+
3
+ /**
4
+ * `sfu.callLeave`: the session to leave, as its join returned it.
5
+ */
6
+ export type SfuCallLeaveParams = { neighbourhoodUrl: string, roomName: string,
7
+ /**
8
+ * The `participantId` the join returned. Only the caller's own session
9
+ * is left; any other id leaves nothing (`false`).
10
+ */
11
+ participantId: string, };
@@ -14,7 +14,12 @@ export type SfuCallRenegotiationOffer = {
14
14
  * DID of the participant this offer is addressed to. Used by the
15
15
  * events_ws fanout to filter per-user.
16
16
  */
17
- targetDid: string, neighbourhoodUrl: string, roomName: string,
17
+ targetDid: string,
18
+ /**
19
+ * The session the offer is for. Every session of `target_did` gets
20
+ * it; only this one applies it.
21
+ */
22
+ participantId: string, neighbourhoodUrl: string, roomName: string,
18
23
  /**
19
24
  * JSON-encoded `RTCSessionDescriptionInit` for the new offer.
20
25
  */
@@ -8,7 +8,13 @@ export type SfuDataMessage = {
8
8
  /**
9
9
  * DID of the participant who sent the data.
10
10
  */
11
- senderDid: string, neighbourhoodUrl: string, roomName: string,
11
+ senderDid: string,
12
+ /**
13
+ * The session that sent it. A message reaches the sender's agent when
14
+ * it is in the call on another device too; the sending session itself
15
+ * drops it by this id.
16
+ */
17
+ senderParticipantId: string, neighbourhoodUrl: string, roomName: string,
12
18
  /**
13
19
  * Label of the data channel.
14
20
  */
@@ -1,6 +1,10 @@
1
1
  // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
2
 
3
3
  export type SfuQualityPreferenceParams = { neighbourhoodUrl: string, roomName: string,
4
+ /**
5
+ * The caller's session, as its join returned it.
6
+ */
7
+ participantId: string,
4
8
  /**
5
9
  * The service rejects any other value.
6
10
  */
@@ -0,0 +1,11 @@
1
+ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
+
3
+ /**
4
+ * `sfu.callRestartIce`: the session whose ICE to restart.
5
+ */
6
+ export type SfuRestartIceParams = { neighbourhoodUrl: string, roomName: string,
7
+ /**
8
+ * The caller's session, as its join returned it. Any other id, even
9
+ * another device of the same agent, is refused.
10
+ */
11
+ participantId: string, };
@@ -5,4 +5,8 @@
5
5
  * `SfuRoomParticipantInfo`: its `SfuParticipantInfo` carries a live
6
6
  * `MediaStream`.
7
7
  */
8
- export type SfuRoomParticipantInfo = { agentDid: string, hasAudio: boolean, hasVideo: boolean, isActiveSpeaker: boolean, };
8
+ export type SfuRoomParticipantInfo = {
9
+ /**
10
+ * The session: an agent in the call from two devices is two participants.
11
+ */
12
+ participantId: string, agentDid: string, hasAudio: boolean, hasVideo: boolean, isActiveSpeaker: boolean, };
@@ -1,4 +1,5 @@
1
1
  // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
+ import type { SfuRosterParticipant } from "./SfuRosterParticipant";
2
3
 
3
4
  /**
4
5
  * Who is in a call room now. Published whenever the room's participants
@@ -7,6 +8,9 @@
7
8
  */
8
9
  export type SfuRoomRoster = { neighbourhoodUrl: string, roomName: string,
9
10
  /**
10
- * DIDs of the room's participants on this node, sorted.
11
+ * The room's sessions, sorted by DID, then participant id: this node's,
12
+ * and those the other cascade nodes in the room announced, whose ids
13
+ * name their node (`P3@did:key:...`). An agent in the call from two
14
+ * devices is listed twice.
11
15
  */
12
- participants: Array<string>, };
16
+ participants: Array<SfuRosterParticipant>, };
@@ -0,0 +1,6 @@
1
+ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
+
3
+ /**
4
+ * One session in an [`SfuRoomRoster`].
5
+ */
6
+ export type SfuRosterParticipant = { agentDid: string, participantId: string, };
@@ -1,6 +1,10 @@
1
1
  // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
2
 
3
- export type SfuSendDataParams = { neighbourhoodUrl: string, roomName: string, channelLabel: string,
3
+ export type SfuSendDataParams = { neighbourhoodUrl: string, roomName: string,
4
+ /**
5
+ * The caller's session, as its join returned it.
6
+ */
7
+ participantId: string, channelLabel: string,
4
8
  /**
5
9
  * UTF-8 text, or base64 when `binary` is true.
6
10
  */