@webex/internal-plugin-llm 3.12.0-webex-services-ready.4 → 3.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,21 +2,20 @@ import MockWebex from '@webex/test-helper-mock-webex';
2
2
  import {assert} from '@webex/test-helper-chai';
3
3
  import sinon from 'sinon';
4
4
  import Mercury from '@webex/internal-plugin-mercury';
5
- import LLMService from '@webex/internal-plugin-llm';
6
5
  import LLMChannel from '@webex/internal-plugin-llm/src/llm';
7
6
 
8
7
  describe('plugin-llm', () => {
9
8
  const locusUrl = 'locusUrl';
10
9
  const datachannelUrl = 'datachannelUrl';
11
10
 
12
- describe('llm', () => {
13
- let webex, llmService;
11
+ describe('LLMChannel', () => {
12
+ let webex, llmChannel;
14
13
 
15
14
  beforeEach(() => {
16
15
  webex = new MockWebex({
17
16
  children: {
18
17
  mercury: Mercury,
19
- llm: LLMService,
18
+ llm: LLMChannel,
20
19
  },
21
20
  });
22
21
 
@@ -25,265 +24,261 @@ describe('plugin-llm', () => {
25
24
  getFeature: sinon.stub().resolves(true),
26
25
  };
27
26
 
28
- llmService = webex.internal.llm;
29
- llmService.webSocketUrl = 'wss://example.com/socket';
30
- llmService.disconnect = sinon.stub().resolves(true);
31
- llmService.request = sinon.stub().resolves({
27
+ llmChannel = webex.internal.llm;
28
+ // Stub Mercury's prototype disconnect so super.disconnect() works in tests.
29
+ // The real Mercury emits 'disconnected' after disconnect completes, so we simulate that.
30
+ sinon
31
+ .stub(Object.getPrototypeOf(Object.getPrototypeOf(llmChannel)), 'disconnect')
32
+ .callsFake(function () {
33
+ this.connected = false;
34
+ this._emit('disconnected');
35
+
36
+ return Promise.resolve();
37
+ });
38
+ llmChannel.request = sinon.stub().resolves({
32
39
  headers: {},
33
40
  body: {
34
41
  binding: 'binding',
35
42
  webSocketUrl: 'wss://example.com/socket',
36
43
  },
37
44
  });
38
- const sockets = new Map();
39
-
40
- llmService.connect = sinon.stub().callsFake((url, sessionId) => {
41
- sockets.set(sessionId, {connected: true});
42
- llmService.getSocket = sinon.stub().callsFake((sid) => sockets.get(sid));
45
+ llmChannel.connect = sinon.stub().callsFake(() => {
46
+ llmChannel.connected = true;
43
47
  });
44
- llmService.connections.set('llm-default-session',{
45
- webSocketUrl: 'wss://example.com/socket',
46
- })
47
48
  });
48
49
 
49
50
  afterEach(() => sinon.restore());
50
51
 
51
52
  describe('#registerAndConnect', () => {
52
- it('registers connection', async () => {
53
- llmService.register = sinon.stub().callsFake(async () => {
54
- llmService.binding = 'binding';
55
- llmService.webSocketUrl = 'wss://example.com/socket';
56
- return {
57
- body: {
58
- binding: 'binding',
59
- webSocketUrl: 'wss://example.com/socket',
60
- },
61
- };
62
- });
63
-
64
- assert.equal(llmService.isConnected('llm-default-session'), false);
65
- await llmService.registerAndConnect(locusUrl, datachannelUrl,undefined);
66
- assert.equal(llmService.isConnected('llm-default-session'), true);
53
+ it('registers and connects', async () => {
54
+ assert.equal(llmChannel.isConnected(), false);
55
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
56
+ assert.equal(llmChannel.isConnected(), true);
57
+ assert.equal(llmChannel.getLocusUrl(), locusUrl);
58
+ assert.equal(llmChannel.getDatachannelUrl(), datachannelUrl);
67
59
  });
68
60
 
69
- it("doesn't register connection for invalid input", async () => {
70
- llmService.register = sinon.stub().callsFake(async () => {
71
- llmService.binding = 'binding';
72
- llmService.webSocketUrl = 'wss://example.com/socket';
73
- return {
74
- body: {
75
- binding: 'binding',
76
- webSocketUrl: 'wss://example.com/socket',
77
- },
78
- };
79
- });
61
+ it('connects with subscriptionAwareSubchannels when token enabled', async () => {
62
+ llmChannel.isDataChannelTokenEnabled = sinon.stub().resolves(true);
63
+
64
+ const buildSpy = sinon.spy(LLMChannel, 'buildUrlWithAwareSubchannels');
65
+
66
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl, 'abc123');
67
+
68
+ sinon.assert.calledOnce(buildSpy);
69
+ sinon.assert.calledOnce(llmChannel.connect);
80
70
 
81
- await llmService.registerAndConnect();
82
- assert.equal(llmService.isConnected(), false);
71
+ const calledUrl = llmChannel.connect.getCall(0).args[0];
72
+ assert.include(calledUrl, 'subscriptionAwareSubchannels=');
83
73
  });
84
74
 
85
- it('registers connection with token', async () => {
86
- llmService.register = sinon.stub().callsFake(async () => {
87
- llmService.binding = 'binding';
88
- llmService.webSocketUrl = 'wss://example.com/socket';
89
- return {
90
- body: {
91
- binding: 'binding',
92
- webSocketUrl: 'wss://example.com/socket',
93
- },
94
- };
95
- });
75
+ it('connects without subscriptionAwareSubchannels when token disabled', async () => {
76
+ llmChannel.isDataChannelTokenEnabled = sinon.stub().resolves(false);
96
77
 
97
- assert.equal(llmService.isConnected(), false);
78
+ const buildSpy = sinon.spy(LLMChannel, 'buildUrlWithAwareSubchannels');
98
79
 
99
- await llmService.registerAndConnect(locusUrl, datachannelUrl,'abc123');
80
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
100
81
 
101
- sinon.assert.calledOnceWithExactly(
102
- llmService.register,
103
- datachannelUrl,
104
- 'abc123',
105
- 'llm-default-session'
106
- );
82
+ sinon.assert.notCalled(buildSpy);
83
+ sinon.assert.calledOnce(llmChannel.connect);
107
84
 
108
- assert.equal(llmService.isConnected(), true);
85
+ const calledUrl = llmChannel.connect.getCall(0).args[0];
86
+ assert.equal(calledUrl, 'wss://example.com/socket');
109
87
  });
110
88
 
111
- it('connects with subscriptionAwareSubchannels when token enabled', async () => {
112
- llmService.isDataChannelTokenEnabled = sinon.stub().returns(true);
113
-
114
- llmService.register = sinon.stub().callsFake(async () => {
115
- llmService.binding = 'binding';
116
- llmService.webSocketUrl = 'wss://example.com/socket';
117
- return {
118
- body: {
119
- binding: 'binding',
120
- webSocketUrl: 'wss://example.com/socket',
121
- },
122
- };
123
- });
89
+ it('connects with subscriptionAwareSubchannels when token enabled but token missing', async () => {
90
+ llmChannel.isDataChannelTokenEnabled = sinon.stub().resolves(true);
124
91
 
125
- const buildSpy = sinon.spy(LLMService, 'buildUrlWithAwareSubchannels');
92
+ const buildSpy = sinon.spy(LLMChannel, 'buildUrlWithAwareSubchannels');
126
93
 
127
- await llmService.registerAndConnect(locusUrl, datachannelUrl,'abc123');
94
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl, undefined);
128
95
 
129
96
  sinon.assert.calledOnce(buildSpy);
130
- sinon.assert.calledOnce(llmService.connect);
97
+ sinon.assert.calledOnce(llmChannel.connect);
131
98
 
132
- const calledUrl = llmService.connect.getCall(0).args[0];
99
+ const calledUrl = llmChannel.connect.getCall(0).args[0];
133
100
  assert.include(calledUrl, 'subscriptionAwareSubchannels=');
134
- });
135
-
136
- it('connects without subscriptionAwareSubchannels when token disabled', async () => {
137
- llmService.isDataChannelTokenEnabled = sinon.stub().returns(false);
138
101
 
139
- llmService.register = sinon.stub().callsFake(async () => {
140
- llmService.binding = 'binding';
141
- llmService.webSocketUrl = 'wss://example.com/socket';
142
- return {
143
- body: {
144
- binding: 'binding',
145
- webSocketUrl: 'wss://example.com/socket',
146
- },
147
- };
148
- });
102
+ buildSpy.restore();
103
+ });
149
104
 
150
- const buildSpy = sinon.spy(LLMService, 'buildUrlWithAwareSubchannels');
105
+ it('deduplicates concurrent calls', async () => {
106
+ const promise1 = llmChannel.registerAndConnect(locusUrl, datachannelUrl);
107
+ const promise2 = llmChannel.registerAndConnect(locusUrl, datachannelUrl);
151
108
 
152
- await llmService.registerAndConnect(locusUrl, datachannelUrl);
109
+ assert.strictEqual(promise1, promise2);
110
+ await promise1;
111
+ });
153
112
 
154
- sinon.assert.notCalled(buildSpy);
155
- sinon.assert.calledOnce(llmService.connect);
113
+ it('avoids reconnect if already connected to same URLs', async () => {
114
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
115
+ sinon.assert.calledOnce(llmChannel.connect);
156
116
 
157
- const calledUrl = llmService.connect.getCall(0).args[0];
158
- assert.equal(calledUrl, llmService.webSocketUrl);
117
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
118
+ sinon.assert.calledOnce(llmChannel.connect);
159
119
  });
160
120
 
161
- it('connects without subscriptionAwareSubchannels when token enabled BUT token missing', async () => {
162
- llmService.isDataChannelTokenEnabled = sinon.stub().resolves(true);
121
+ it('propagates error when registration request fails', async () => {
122
+ const error = new Error('Network failure');
123
+ llmChannel.request = sinon.stub().rejects(error);
163
124
 
164
- const buildSpy = sinon.spy(LLMService, 'buildUrlWithAwareSubchannels');
125
+ try {
126
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
127
+ assert.fail('should have thrown');
128
+ } catch (e) {
129
+ assert.equal(e.message, 'Network failure');
130
+ }
165
131
 
166
- await llmService.registerAndConnect(locusUrl, datachannelUrl, undefined);
132
+ sinon.assert.notCalled(llmChannel.connect);
133
+ });
167
134
 
168
- sinon.assert.calledOnce(buildSpy);
169
- sinon.assert.calledOnce(llmService.connect);
135
+ it('returns timing data on successful connection', async () => {
136
+ const clock = sinon.useFakeTimers();
170
137
 
171
- const calledUrl = llmService.connect.getCall(0).args[0];
172
- assert.include(calledUrl, 'subscriptionAwareSubchannels=');
138
+ llmChannel.request = sinon.stub().callsFake(async () => {
139
+ clock.tick(37);
173
140
 
174
- buildSpy.restore();
175
- });
141
+ return {
142
+ headers: {},
143
+ body: {
144
+ binding: 'binding',
145
+ webSocketUrl: 'wss://example.com/socket',
146
+ },
147
+ };
148
+ });
149
+ llmChannel.connect = sinon.stub().callsFake(async () => {
150
+ clock.tick(23);
151
+ llmChannel.connected = true;
152
+ });
176
153
 
177
- it('rejects when the registration response has no websocket URL', async () => {
178
- llmService.connections.set('llm-default-session', {});
179
- llmService.register = sinon.stub().resolves();
154
+ const result = await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
180
155
 
181
- await assert.isRejected(
182
- llmService.registerAndConnect(locusUrl, datachannelUrl),
183
- /returned no websocket URL/
184
- );
156
+ assert.deepEqual(result, {
157
+ clientLLMDatachannelResponseTime: 37,
158
+ clientLLMWebSocketConnectTime: 23,
159
+ });
185
160
 
186
- sinon.assert.notCalled(llmService.connect);
187
- assert.equal(llmService.isConnected(), false);
161
+ clock.restore();
188
162
  });
189
163
 
190
- it('attaches the measured datachannel timing to the error when the websocket connect fails', async () => {
164
+ it('attaches timing to error when connect fails', async () => {
191
165
  const clock = sinon.useFakeTimers();
192
166
 
193
- llmService.isDataChannelTokenEnabled = sinon.stub().resolves(false);
194
- llmService.register = sinon.stub().callsFake(async () => {
167
+ llmChannel.request = sinon.stub().callsFake(async () => {
195
168
  clock.tick(37);
196
- const sessionData = llmService.connections.get('llm-default-session') || {};
197
- sessionData.webSocketUrl = 'wss://example.com/socket';
198
- sessionData.binding = 'binding';
199
- llmService.connections.set('llm-default-session', sessionData);
169
+
170
+ return {
171
+ headers: {},
172
+ body: {
173
+ binding: 'binding',
174
+ webSocketUrl: 'wss://example.com/socket',
175
+ },
176
+ };
200
177
  });
201
178
 
202
179
  const connectError = new Error('websocket connect failed');
203
- llmService.connect = sinon.stub().rejects(connectError);
180
+ llmChannel.connect = sinon.stub().rejects(connectError);
204
181
 
205
182
  let caughtError;
206
183
  try {
207
- await llmService.registerAndConnect(locusUrl, datachannelUrl);
184
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
208
185
  } catch (error) {
209
186
  caughtError = error;
210
187
  }
211
188
 
212
189
  assert.equal(caughtError, connectError);
213
190
  assert.deepEqual(caughtError.timing, {clientLLMDatachannelResponseTime: 37});
191
+
192
+ clock.restore();
214
193
  });
215
194
 
216
- it('attaches the measured datachannel timing to the error when the response has no websocket URL', async () => {
217
- const clock = sinon.useFakeTimers();
195
+ it('clears connectingPromise after successful connection', async () => {
196
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
218
197
 
219
- llmService.register = sinon.stub().callsFake(async () => {
220
- clock.tick(29);
221
- // register() resolves but the response leaves the session without a websocket URL.
222
- llmService.connections.set('llm-default-session', {
223
- locusUrl,
224
- datachannelUrl,
225
- });
226
- });
198
+ // After completion, a new call should create a fresh promise (not deduplicated)
199
+ llmChannel.connect.resetHistory();
200
+ llmChannel.request.resetHistory();
227
201
 
228
- llmService.connect = sinon.stub();
202
+ // Simulate different URLs to force new connection
203
+ await llmChannel.registerAndConnect('newLocusUrl', 'newDatachannelUrl');
204
+
205
+ // Should have called request again since connectingPromise was cleared
206
+ sinon.assert.calledOnce(llmChannel.request);
207
+ });
208
+
209
+ it('clears connectingPromise after failed connection', async () => {
210
+ llmChannel.connect = sinon.stub().rejects(new Error('connect failed'));
229
211
 
230
- let caughtError;
231
212
  try {
232
- await llmService.registerAndConnect(locusUrl, datachannelUrl);
233
- } catch (error) {
234
- caughtError = error;
213
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
214
+ } catch (e) {
215
+ // expected
235
216
  }
236
217
 
237
- sinon.assert.notCalled(llmService.connect);
238
- assert.instanceOf(caughtError, Error);
239
- assert.match(caughtError.message, /returned no websocket URL/);
240
- assert.deepEqual(caughtError.timing, {clientLLMDatachannelResponseTime: 29});
218
+ // Reset and try again - should not deduplicate since promise was cleared
219
+ llmChannel.connect = sinon.stub().callsFake(() => {
220
+ llmChannel.connected = true;
221
+ });
222
+ llmChannel.request.resetHistory();
223
+
224
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
225
+
226
+ // Should have called request again
227
+ sinon.assert.calledOnce(llmChannel.request);
241
228
  });
242
- });
243
229
 
244
- describe('#register', () => {
245
- beforeEach(() => {
246
- llmService.isDataChannelTokenEnabled = sinon.stub();
230
+ it('returns undefined when already connected to same URLs', async () => {
231
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
232
+
233
+ const result = await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
234
+
235
+ assert.equal(result, undefined);
247
236
  });
237
+ });
238
+
239
+ describe('#register (via registerAndConnect)', () => {
240
+ it('sends request with token header when token enabled and provided', async () => {
241
+ llmChannel.isDataChannelTokenEnabled = sinon.stub().resolves(true);
248
242
 
249
- it('registers connection with token header', async () => {
250
- llmService.isDataChannelTokenEnabled.resolves(true);
251
- await llmService.register(datachannelUrl, 'abc123');
243
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl, 'abc123');
252
244
 
253
245
  sinon.assert.calledOnceWithExactly(
254
- llmService.request,
246
+ llmChannel.request,
255
247
  sinon.match({
256
248
  method: 'POST',
257
- url: `${datachannelUrl}`,
249
+ url: datachannelUrl,
258
250
  body: {deviceUrl: webex.internal.device.url},
259
251
  headers: {'Data-Channel-Auth-Token': 'abc123'},
260
252
  })
261
253
  );
262
254
  });
263
255
 
264
- it('registers connection without token header when none provided', async () => {
265
- await llmService.register(datachannelUrl);
256
+ it('sends request without token header when none provided', async () => {
257
+ llmChannel.isDataChannelTokenEnabled = sinon.stub().resolves(true);
258
+
259
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
266
260
 
267
261
  sinon.assert.calledOnceWithExactly(
268
- llmService.request,
262
+ llmChannel.request,
269
263
  sinon.match({
270
264
  method: 'POST',
271
- url: `${datachannelUrl}`,
265
+ url: datachannelUrl,
272
266
  body: {deviceUrl: webex.internal.device.url},
273
267
  headers: {},
274
268
  })
275
269
  );
276
270
  });
277
271
 
278
- it('registers connection without token header when toggle disabled', async () => {
279
- llmService.isDataChannelTokenEnabled.resolves(false);
272
+ it('sends request without token header when toggle disabled', async () => {
273
+ llmChannel.isDataChannelTokenEnabled = sinon.stub().resolves(false);
274
+
275
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl, 'abc123');
280
276
 
281
- await llmService.register(datachannelUrl,'abc123');
282
277
  sinon.assert.calledOnceWithExactly(
283
- llmService.request,
278
+ llmChannel.request,
284
279
  sinon.match({
285
280
  method: 'POST',
286
- url: `${datachannelUrl}`,
281
+ url: datachannelUrl,
287
282
  body: {deviceUrl: webex.internal.device.url},
288
283
  headers: {},
289
284
  })
@@ -293,544 +288,422 @@ describe('plugin-llm', () => {
293
288
 
294
289
  describe('#getLocusUrl', () => {
295
290
  it('gets LocusUrl', async () => {
296
- llmService.register = sinon.stub().callsFake(async () => {
297
- llmService.binding = 'binding';
298
- llmService.webSocketUrl = 'wss://example.com/socket';
299
- return {
300
- body: {
301
- binding: 'binding',
302
- webSocketUrl: 'wss://example.com/socket',
303
- },
304
- };
305
- });
291
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
292
+ assert.equal(llmChannel.getLocusUrl(), locusUrl);
293
+ });
306
294
 
307
- await llmService.registerAndConnect(locusUrl, datachannelUrl);
308
- assert.equal(llmService.getLocusUrl(), locusUrl);
295
+ it('returns undefined before connection', () => {
296
+ assert.equal(llmChannel.getLocusUrl(), undefined);
309
297
  });
310
298
  });
311
299
 
312
300
  describe('#getDatachannelUrl', () => {
313
301
  it('gets dataChannel Url', async () => {
314
- llmService.register = sinon.stub().callsFake(async () => {
315
- llmService.binding = 'binding';
316
- llmService.webSocketUrl = 'wss://example.com/socket';
317
- return {
318
- body: {
319
- binding: 'binding',
320
- webSocketUrl: 'wss://example.com/socket',
321
- },
322
- };
323
- });
324
- await llmService.registerAndConnect(locusUrl, datachannelUrl);
325
- assert.equal(llmService.getDatachannelUrl(), datachannelUrl);
302
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
303
+ assert.equal(llmChannel.getDatachannelUrl(), datachannelUrl);
326
304
  });
327
- });
328
305
 
329
- describe('#disconnect', () => {
330
- it('disconnects mercury', async () => {
331
- await llmService.disconnect();
332
- sinon.assert.calledOnce(llmService.disconnect);
333
- assert.equal(llmService.isConnected(), false);
334
- assert.equal(llmService.getLocusUrl(), undefined);
335
- assert.equal(llmService.getDatachannelUrl(), undefined);
336
- assert.equal(llmService.getBinding(), undefined);
306
+ it('returns undefined before connection', () => {
307
+ assert.equal(llmChannel.getDatachannelUrl(), undefined);
337
308
  });
338
309
  });
339
310
 
340
- describe('#disconnectLLM', () => {
341
- let instance;
342
-
343
- beforeEach(() => {
344
- instance = {
345
- disconnect: jest.fn(() => Promise.resolve()),
346
- connections: new Map([
347
- ['llm-default-session', { foo: 'bar', datachannelToken: 'session-token' }],
348
- ]),
349
-
350
- disconnectLLM: function (
351
- options,
352
- sessionId = 'llm-default-session',
353
- ownerMeetingId = 'meeting-1'
354
- ) {
355
- if (!ownerMeetingId) {
356
- return Promise.reject(new Error('ownerMeetingId is required'));
357
- }
358
-
359
- return this.disconnect(options, sessionId).then(() => {
360
- this.connections.delete(sessionId);
361
- });
362
- },
363
- };
364
- });
365
-
366
- it('calls disconnect and clears session connection (including token stored in session)', async () => {
367
- await instance.disconnectLLM({ code: 3000, reason: 'bye' }, 'llm-default-session', 'meeting-1');
368
-
369
- expect(instance.disconnect).toHaveBeenCalledWith(
370
- { code: 3000, reason: 'bye' },
371
- 'llm-default-session'
372
- );
373
-
374
- expect(instance.connections.has('llm-default-session')).toBe(false);
311
+ describe('#getBinding', () => {
312
+ it('gets binding after connection', async () => {
313
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
314
+ assert.equal(llmChannel.getBinding(), 'binding');
375
315
  });
376
316
 
377
- it('disconnectLLM supports legacy call with options only', async () => {
378
- llmService.disconnect = sinon.stub().resolves(true);
379
-
380
- await llmService.registerAndConnect(locusUrl, datachannelUrl, undefined, 'llm-default-session');
381
-
382
- const options = {code: 1000, reason: 'legacy'};
383
- const disconnected = await llmService.disconnectLLM(options);
384
-
385
- assert.equal(disconnected, true);
386
- sinon.assert.calledOnceWithExactly(llmService.disconnect, options, 'llm-default-session');
387
- assert.equal(llmService.getAllConnections().has('llm-default-session'), false);
317
+ it('returns undefined before connection', () => {
318
+ assert.equal(llmChannel.getBinding(), undefined);
388
319
  });
320
+ });
389
321
 
390
- it('disconnectLLM supports legacy call with options and sessionId', async () => {
391
- llmService.disconnect = sinon.stub().resolves(true);
392
-
393
- await llmService.registerAndConnect(locusUrl, datachannelUrl, undefined, 's1');
394
-
395
- const options = {code: 1000, reason: 'legacy'};
396
- const disconnected = await llmService.disconnectLLM(options, 's1');
322
+ describe('#isConnecting', () => {
323
+ it('returns true while connection is in progress', () => {
324
+ // Start connection but don't await
325
+ llmChannel.registerAndConnect(locusUrl, datachannelUrl);
397
326
 
398
- assert.equal(disconnected, true);
399
- sinon.assert.calledOnceWithExactly(llmService.disconnect, options, 's1');
400
- assert.equal(llmService.getAllConnections().has('s1'), false);
327
+ assert.equal(llmChannel.isConnecting(), true);
401
328
  });
402
329
 
403
- it('disconnectLLM treats null sessionId as default session', async () => {
404
- llmService.disconnect = sinon.stub().resolves(true);
405
-
406
- await llmService.registerAndConnect(
407
- locusUrl,
408
- datachannelUrl,
409
- undefined,
410
- 'llm-default-session'
411
- );
412
-
413
- const options = {code: 1000, reason: 'legacy-null-session'};
414
- const disconnected = await llmService.disconnectLLM(options, null);
330
+ it('returns false after connection completes', async () => {
331
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
415
332
 
416
- assert.equal(disconnected, true);
417
- sinon.assert.calledOnceWithExactly(llmService.disconnect, options, 'llm-default-session');
418
- assert.equal(llmService.getAllConnections().has('llm-default-session'), false);
333
+ assert.equal(llmChannel.isConnecting(), false);
419
334
  });
420
335
 
421
- it('propagates disconnect errors', async () => {
422
- instance.disconnect.mockRejectedValue(new Error('disconnect failed'));
423
-
424
- await expect(
425
- instance.disconnectLLM({ code: 3000, reason: 'bye' }, 'llm-default-session', 'meeting-1')
426
- ).rejects.toThrow('disconnect failed');
336
+ it('returns false before any connection attempt', () => {
337
+ assert.equal(llmChannel.isConnecting(), false);
427
338
  });
428
339
  });
429
340
 
430
- describe('#setRefreshHandler', () => {
431
- beforeEach(() => {
432
- llmService.setRefreshHandler = LLMChannel.prototype.setRefreshHandler.bind(llmService);
433
- llmService.refreshDataChannelToken = LLMChannel.prototype.refreshDataChannelToken.bind(llmService);
434
- });
341
+ describe('#disconnect', () => {
342
+ it('calls super.disconnect and clears all connection state', async () => {
343
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
344
+ llmChannel.setDatachannelToken('token123');
435
345
 
436
- it('defaults to llm-default-session when sessionId is omitted', () => {
437
- const handler = sinon.stub().resolves({ body: { datachannelToken: 'legacyToken' } });
346
+ assert.equal(llmChannel.isConnected(), true);
347
+ assert.equal(llmChannel.getLocusUrl(), locusUrl);
348
+ assert.equal(llmChannel.getDatachannelUrl(), datachannelUrl);
349
+ assert.equal(llmChannel.getBinding(), 'binding');
350
+ assert.equal(llmChannel.getDatachannelToken(), 'token123');
438
351
 
439
- llmService.setRefreshHandler(handler);
352
+ await llmChannel.disconnect({code: 1000, reason: 'test'});
440
353
 
441
- return llmService.refreshDataChannelToken().then((result) => {
442
- assert.equal(result.body.datachannelToken, 'legacyToken');
443
- sinon.assert.calledOnce(handler);
444
- });
354
+ assert.equal(llmChannel.getLocusUrl(), undefined);
355
+ assert.equal(llmChannel.getDatachannelUrl(), undefined);
356
+ assert.equal(llmChannel.getBinding(), undefined);
357
+ assert.equal(llmChannel.getDatachannelToken(), undefined);
358
+ assert.equal(llmChannel.isConnecting(), false);
445
359
  });
446
360
 
447
- it('stores the provided handler', () => {
448
- const handler = sinon.stub().resolves({ body: { datachannelToken: 'newToken' } });
449
- llmService.setRefreshHandler(handler, 'llm-default-session');
361
+ it('works without options', async () => {
362
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
450
363
 
451
- return llmService.refreshDataChannelToken().then((result) => {
452
- assert.equal(result.body.datachannelToken, 'newToken');
453
- sinon.assert.calledOnce(handler);
454
- });
455
- });
364
+ await llmChannel.disconnect();
456
365
 
457
- it('stores handlers per session id', () => {
458
- const handlerS1 = sinon.stub().resolves({ body: { datachannelToken: 'token-s1' } });
459
- const handlerS2 = sinon.stub().resolves({ body: { datachannelToken: 'token-s2' } });
366
+ assert.equal(llmChannel.getLocusUrl(), undefined);
367
+ });
460
368
 
461
- llmService.setRefreshHandler(handlerS1, 's1');
462
- llmService.setRefreshHandler(handlerS2, 's2');
369
+ it('propagates disconnect errors', async () => {
370
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
371
+ // Change the existing stub to reject
372
+ Object.getPrototypeOf(Object.getPrototypeOf(llmChannel)).disconnect.rejects(
373
+ new Error('disconnect failed')
374
+ );
463
375
 
464
- return Promise.all([
465
- llmService.refreshDataChannelToken('s1'),
466
- llmService.refreshDataChannelToken('s2'),
467
- ]).then(([resultS1, resultS2]) => {
468
- assert.equal(resultS1.body.datachannelToken, 'token-s1');
469
- assert.equal(resultS2.body.datachannelToken, 'token-s2');
470
- });
376
+ try {
377
+ await llmChannel.disconnect({code: 1000, reason: 'test'});
378
+ assert.fail('should have thrown');
379
+ } catch (error) {
380
+ assert.equal(error.message, 'disconnect failed');
381
+ }
471
382
  });
472
- });
473
383
 
474
- describe('#isDataChannelTokenEnabled', () => {
475
- it('works correctly', async () => {
476
- webex.internal.feature.getFeature.returns(true);
384
+ it('emits disconnected event', async () => {
385
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
386
+ const disconnectedSpy = sinon.spy();
477
387
 
478
- const result = await llmService.isDataChannelTokenEnabled();
388
+ llmChannel.on('disconnected', disconnectedSpy);
479
389
 
480
- sinon.assert.calledOnceWithExactly(
481
- webex.internal.feature.getFeature,
482
- 'developer',
483
- 'data-channel-with-jwt-token'
484
- );
390
+ await llmChannel.disconnect({code: 1000, reason: 'test'});
485
391
 
486
- assert.equal(result, true);
392
+ sinon.assert.calledOnce(disconnectedSpy);
487
393
  });
488
- });
489
394
 
490
- describe('#refreshDataChannelToken', () => {
491
- beforeEach(() => {
492
- llmService.setRefreshHandler = LLMChannel.prototype.setRefreshHandler.bind(llmService);
493
- llmService.refreshDataChannelToken = LLMChannel.prototype.refreshDataChannelToken.bind(llmService);
494
- });
395
+ it('clears state before disconnected event fires', async () => {
396
+ await llmChannel.registerAndConnect(locusUrl, datachannelUrl);
397
+ llmChannel.setDatachannelToken('token123');
495
398
 
496
- it('returns null and logs warn if no handler is set', async () => {
497
- const warnSpy = llmService.logger.warn
399
+ let stateAtEventTime;
498
400
 
499
- const result = await llmService.refreshDataChannelToken();
401
+ llmChannel.on('disconnected', () => {
402
+ // Capture state when event fires - should already be cleared
403
+ stateAtEventTime = {
404
+ locusUrl: llmChannel.getLocusUrl(),
405
+ datachannelUrl: llmChannel.getDatachannelUrl(),
406
+ binding: llmChannel.getBinding(),
407
+ datachannelToken: llmChannel.getDatachannelToken(),
408
+ isConnecting: llmChannel.isConnecting(),
409
+ };
410
+ });
500
411
 
501
- assert.equal(result, null);
412
+ await llmChannel.disconnect({code: 1000, reason: 'test'});
502
413
 
503
- sinon.assert.calledOnce(warnSpy);
504
- sinon.assert.calledWithMatch(
505
- warnSpy,
506
- sinon.match('LLM refreshHandler is not set for session')
507
- );
414
+ // State should have been undefined when the event fired
415
+ assert.deepEqual(stateAtEventTime, {
416
+ locusUrl: undefined,
417
+ datachannelUrl: undefined,
418
+ binding: undefined,
419
+ datachannelToken: undefined,
420
+ isConnecting: false,
421
+ });
508
422
  });
509
423
 
510
- it('returns token when handler resolves', async () => {
511
- const mockToken = { body: { datachannelToken: 'newToken', isPracticeSession: false } };
512
- const handler = sinon.stub().resolves(mockToken);
424
+ it('invalidates in-flight connection via promise identity', async () => {
425
+ let resolveRequest;
426
+ llmChannel.request = sinon.stub().returns(
427
+ new Promise((resolve) => {
428
+ resolveRequest = resolve;
429
+ })
430
+ );
513
431
 
514
- llmService.setRefreshHandler(handler, 'llm-default-session');
432
+ // Start connection but don't await - request is pending
433
+ const connectPromise = llmChannel.registerAndConnect(locusUrl, datachannelUrl);
515
434
 
516
- const token = await llmService.refreshDataChannelToken();
435
+ assert.equal(llmChannel.isConnecting(), true);
517
436
 
518
- assert.equal(token, mockToken);
519
- sinon.assert.calledOnce(handler);
520
- });
437
+ // Disconnect while connection is in-flight - should complete immediately
438
+ await llmChannel.disconnect({code: 1000, reason: 'test'});
521
439
 
522
- it('uses the handler for the provided session id', async () => {
523
- const mockToken = { body: { datachannelToken: 'session-token', isPracticeSession: true } };
524
- const handler = sinon.stub().resolves(mockToken);
440
+ // State should be cleared immediately, not waiting for connection
441
+ assert.equal(llmChannel.getLocusUrl(), undefined);
442
+ assert.equal(llmChannel.isConnecting(), false);
525
443
 
526
- llmService.setRefreshHandler(handler, 's2');
444
+ // Now resolve the pending request - stale operation should not overwrite state
445
+ resolveRequest({
446
+ headers: {},
447
+ body: {binding: 'stale-binding', webSocketUrl: 'wss://example.com/stale'},
448
+ });
527
449
 
528
- const token = await llmService.refreshDataChannelToken('s2');
450
+ // Wait for the stale promise to settle
451
+ await connectPromise;
529
452
 
530
- assert.equal(token, mockToken);
531
- sinon.assert.calledOnce(handler);
453
+ // State should still be undefined - stale operation detected invalidation
454
+ assert.equal(llmChannel.getBinding(), undefined);
455
+ assert.equal(llmChannel.isConnecting(), false);
532
456
  });
533
457
 
534
- it('logs warn and returns null when handler rejects', async () => {
535
- const handler = sinon.stub().rejects(new Error('throw error'));
536
- llmService.setRefreshHandler(handler, 'llm-default-session');
537
-
538
- const warnSpy = llmService.logger.warn
458
+ it('stale operation does not clear new connectingPromise', async () => {
459
+ let resolveFirstRequest;
460
+ let resolveSecondRequest;
461
+ llmChannel.request = sinon.stub().returns(
462
+ new Promise((resolve) => {
463
+ resolveFirstRequest = resolve;
464
+ })
465
+ );
539
466
 
540
- const result = await llmService.refreshDataChannelToken();
467
+ // Start first connection
468
+ const firstConnectPromise = llmChannel.registerAndConnect(locusUrl, datachannelUrl);
541
469
 
542
- assert.equal(result, null);
470
+ // Disconnect invalidates the first connection
471
+ await llmChannel.disconnect({code: 1000, reason: 'test'});
543
472
 
544
- sinon.assert.calledOnce(warnSpy);
545
- sinon.assert.calledWithMatch(
546
- warnSpy,
547
- sinon.match('DataChannel token refresh failed'),
473
+ // Start second connection before first resolves
474
+ llmChannel.request = sinon.stub().returns(
475
+ new Promise((resolve) => {
476
+ resolveSecondRequest = resolve;
477
+ })
478
+ );
479
+ const secondConnectPromise = llmChannel.registerAndConnect(
480
+ 'newLocusUrl',
481
+ 'newDatachannelUrl'
548
482
  );
549
- });
550
- });
551
483
 
552
- describe('#getDatachannelToken / #setDatachannelToken', () => {
553
- it('sets and gets datachannel token', () => {
554
- llmService.setDatachannelToken('abc123','llm-default-session');
555
- assert.equal(llmService.getDatachannelToken('llm-default-session'), 'abc123');
556
- llmService.setDatachannelToken('123abc','llm-practice-session');
557
- assert.equal(llmService.getDatachannelToken('llm-practice-session'), '123abc');
558
- });
484
+ assert.equal(llmChannel.isConnecting(), true);
559
485
 
560
- it('supports arbitrary session id token keys', () => {
561
- llmService.setDatachannelToken('token-s1', 'session-custom-1');
486
+ // Resolve the first (stale) request
487
+ resolveFirstRequest({
488
+ headers: {},
489
+ body: {binding: 'stale-binding', webSocketUrl: 'wss://example.com/stale'},
490
+ });
562
491
 
563
- assert.equal(llmService.getDatachannelToken('session-custom-1'), 'token-s1');
564
- });
492
+ await firstConnectPromise;
565
493
 
566
- });
494
+ // isConnecting should still be true because second connection is in progress
495
+ assert.equal(llmChannel.isConnecting(), true);
567
496
 
568
- describe('#setOwnerMeetingId / #getOwnerMeetingId', () => {
569
- it('stores and returns the owner meeting id for the default session', () => {
570
- // beforeEach seeds connections with the default session entry
571
- llmService.setOwnerMeetingId('meeting-1');
497
+ // State should not have been overwritten by stale operation
498
+ assert.equal(llmChannel.getBinding(), undefined);
572
499
 
573
- assert.equal(llmService.getOwnerMeetingId(), 'meeting-1');
574
- });
500
+ // Complete second connection
501
+ resolveSecondRequest({
502
+ headers: {},
503
+ body: {binding: 'new-binding', webSocketUrl: 'wss://example.com/new'},
504
+ });
505
+ await secondConnectPromise;
575
506
 
576
- it('returns undefined when no owner has been set yet', () => {
577
- assert.equal(llmService.getOwnerMeetingId(), undefined);
507
+ // Now isConnecting should be false and state should reflect second connection
508
+ assert.equal(llmChannel.isConnecting(), false);
509
+ assert.equal(llmChannel.getBinding(), 'new-binding');
578
510
  });
579
511
 
580
- it('is a no-op when there is no session data for the given sessionId', () => {
581
- // Default session exists (seeded in beforeEach), but an arbitrary
582
- // session id does not — setOwnerMeetingId must not create entries.
583
- llmService.setOwnerMeetingId('meeting-1', 'unknown-session');
584
-
585
- assert.equal(llmService.getOwnerMeetingId('unknown-session'), undefined);
586
- });
512
+ it('does not call connect() if disconnect runs during isDataChannelTokenEnabled await', async () => {
513
+ let resolveFeatureToggle;
514
+ const featureTogglePromise = new Promise((resolve) => {
515
+ resolveFeatureToggle = resolve;
516
+ });
587
517
 
588
- it('allows clearing ownership by passing undefined', () => {
589
- llmService.setOwnerMeetingId('meeting-1');
590
- assert.equal(llmService.getOwnerMeetingId(), 'meeting-1');
518
+ // Request resolves immediately
519
+ llmChannel.request = sinon.stub().resolves({
520
+ headers: {},
521
+ body: {binding: 'binding', webSocketUrl: 'wss://example.com/socket'},
522
+ });
591
523
 
592
- llmService.setOwnerMeetingId(undefined);
524
+ // Feature toggle will block
525
+ webex.internal.feature.getFeature = sinon
526
+ .stub()
527
+ .onFirstCall()
528
+ .resolves(true) // First call in register()
529
+ .onSecondCall()
530
+ .returns(featureTogglePromise); // Second call blocks
593
531
 
594
- assert.equal(llmService.getOwnerMeetingId(), undefined);
595
- });
532
+ // Start connection
533
+ const connectPromise = llmChannel.registerAndConnect(locusUrl, datachannelUrl);
596
534
 
597
- it('tracks ownership per session id', () => {
598
- llmService.connections.set('session-A', {webSocketUrl: 'wss://a'});
599
- llmService.connections.set('session-B', {webSocketUrl: 'wss://b'});
535
+ // Wait for register() to complete and state to be set
536
+ await new Promise((resolve) => setImmediate(resolve));
600
537
 
601
- llmService.setOwnerMeetingId('meeting-A', 'session-A');
602
- llmService.setOwnerMeetingId('meeting-B', 'session-B');
538
+ // Binding should be set after register() completes
539
+ assert.equal(llmChannel.getBinding(), 'binding');
603
540
 
604
- assert.equal(llmService.getOwnerMeetingId('session-A'), 'meeting-A');
605
- assert.equal(llmService.getOwnerMeetingId('session-B'), 'meeting-B');
606
- });
541
+ // Disconnect while isDataChannelTokenEnabled() is pending
542
+ await llmChannel.disconnect({code: 1000, reason: 'test'});
607
543
 
608
- it('clears ownerMeetingId naturally when disconnectLLM deletes the session entry', async () => {
609
- llmService.register = sinon.stub().callsFake(async () => ({
610
- body: {binding: 'binding', webSocketUrl: 'wss://example.com/socket'},
611
- }));
544
+ // State should be cleared
545
+ assert.equal(llmChannel.getBinding(), undefined);
612
546
 
613
- await llmService.registerAndConnect(locusUrl, datachannelUrl);
614
- llmService.setOwnerMeetingId('meeting-1');
615
- assert.equal(llmService.getOwnerMeetingId(), 'meeting-1');
547
+ // Now resolve the feature toggle - stale operation should NOT call connect()
548
+ resolveFeatureToggle(true);
616
549
 
617
- await llmService.disconnectLLM(
618
- {code: 3050, reason: 'done (permanent)'},
619
- 'llm-default-session',
620
- 'meeting-1'
621
- );
550
+ await connectPromise;
622
551
 
623
- // Session entry was deleted, so ownerMeetingId is gone.
624
- assert.equal(llmService.getOwnerMeetingId(), undefined);
552
+ // connect() should NOT have been called - identity check after await should have aborted
553
+ sinon.assert.notCalled(llmChannel.connect);
625
554
  });
626
555
  });
627
556
 
628
- describe('multi-connection logic', () => {
629
- const locusUrl2 = 'locusUrl2';
630
- const datachannelUrl2 = 'datachannelUrl2';
631
-
632
- it('tracks multiple sessions independently', async () => {
633
- await llmService.registerAndConnect(locusUrl, datachannelUrl, undefined, 's1');
634
- await llmService.registerAndConnect(locusUrl2, datachannelUrl2, undefined, 's2');
557
+ describe('#setRefreshHandler', () => {
558
+ it('stores the provided handler', async () => {
559
+ const handler = sinon.stub().resolves({body: {datachannelToken: 'newToken'}});
560
+ llmChannel.setRefreshHandler(handler);
635
561
 
636
- assert.equal(llmService.isConnected('s1'), true);
637
- assert.equal(llmService.isConnected('s2'), true);
638
- assert.equal(llmService.getLocusUrl('s1'), locusUrl);
639
- assert.equal(llmService.getLocusUrl('s2'), locusUrl2);
640
- assert.equal(llmService.getDatachannelUrl('s1'), datachannelUrl);
641
- assert.equal(llmService.getDatachannelUrl('s2'), datachannelUrl2);
562
+ const result = await llmChannel.refreshDataChannelToken();
642
563
 
643
- const all = llmService.getAllConnections();
644
- assert.equal(all.has('s1'), true);
645
- assert.equal(all.has('s2'), true);
564
+ assert.equal(result.body.datachannelToken, 'newToken');
565
+ sinon.assert.calledOnce(handler);
646
566
  });
567
+ });
647
568
 
648
- it('disconnectLLM clears only the targeted session', async () => {
649
- llmService.disconnect = sinon.stub().resolves(true);
650
-
651
- await llmService.registerAndConnect(locusUrl, datachannelUrl, undefined, 's1');
652
- await llmService.registerAndConnect(locusUrl2, datachannelUrl2, undefined, 's2');
569
+ describe('#isDataChannelTokenEnabled', () => {
570
+ it('returns value from feature toggle', async () => {
571
+ webex.internal.feature.getFeature.resolves(true);
653
572
 
654
- const options = {code: 1000, reason: 'test'};
655
- const disconnected = await llmService.disconnectLLM(options, 's1', 'meeting-1');
573
+ const result = await llmChannel.isDataChannelTokenEnabled();
656
574
 
657
- assert.equal(disconnected, true);
658
- sinon.assert.calledOnceWithExactly(llmService.disconnect, options, 's1');
575
+ sinon.assert.calledOnceWithExactly(
576
+ webex.internal.feature.getFeature,
577
+ 'developer',
578
+ 'data-channel-with-jwt-token'
579
+ );
659
580
 
660
- const all = llmService.getAllConnections();
661
- assert.equal(all.has('s1'), false);
662
- assert.equal(all.has('s2'), true);
663
- assert.equal(llmService.getDatachannelToken('s1'), undefined);
581
+ assert.equal(result, true);
664
582
  });
583
+ });
665
584
 
666
- it('disconnectLLM skips disconnect when ownerMeetingId does not match', async () => {
667
- llmService.disconnect = sinon.stub().resolves(true);
585
+ describe('#refreshDataChannelToken', () => {
586
+ it('returns null and logs warn if no handler is set', async () => {
587
+ const warnSpy = llmChannel.logger.warn;
668
588
 
669
- await llmService.registerAndConnect(locusUrl, datachannelUrl, undefined, 's1');
670
- llmService.setOwnerMeetingId('meeting-1', 's1');
589
+ const result = await llmChannel.refreshDataChannelToken();
671
590
 
672
- const options = {code: 1000, reason: 'test'};
673
- const disconnected = await llmService.disconnectLLM(options, 's1', 'meeting-2');
591
+ assert.equal(result, null);
674
592
 
675
- assert.equal(disconnected, false);
676
- sinon.assert.notCalled(llmService.disconnect);
677
- assert.equal(llmService.getAllConnections().has('s1'), true);
593
+ sinon.assert.calledOnce(warnSpy);
594
+ sinon.assert.calledWithMatch(warnSpy, sinon.match('LLM refreshHandler is not set'));
678
595
  });
679
596
 
680
- it('disconnectAllLLM clears all sessions', async () => {
681
- llmService.disconnectAll = sinon.stub().resolves(true);
597
+ it('returns token when handler resolves', async () => {
598
+ const mockToken = {body: {datachannelToken: 'newToken', datachannelTokenType: 'default'}};
599
+ const handler = sinon.stub().resolves(mockToken);
682
600
 
683
- await llmService.registerAndConnect(locusUrl, datachannelUrl, undefined, 's1');
684
- await llmService.registerAndConnect(locusUrl2, datachannelUrl2, undefined, 's2');
601
+ llmChannel.setRefreshHandler(handler);
685
602
 
686
- await llmService.disconnectAllLLM({code: 1000, reason: 'all'});
603
+ const token = await llmChannel.refreshDataChannelToken();
687
604
 
688
- sinon.assert.calledOnce(llmService.disconnectAll);
689
- assert.equal(llmService.getAllConnections().size, 0);
605
+ assert.equal(token, mockToken);
606
+ sinon.assert.calledOnce(handler);
690
607
  });
691
- });
692
608
 
693
- describe('#getLocusUrlByDatachannelUrl', () => {
694
- const locusUrl2 = 'https://locus-b.wbx2.com/locus/api/v1/loci/456';
695
- const datachannelUrl2 = 'https://board-b.wbx2.com/datachannel/api/v1/locus/ps-encoded/registrations';
609
+ it('logs warn and returns null when handler rejects', async () => {
610
+ const handler = sinon.stub().rejects(new Error('throw error'));
611
+ llmChannel.setRefreshHandler(handler);
696
612
 
697
- // Ampersand State.extend() does not always propagate prototype methods
698
- // added to child classes, so we bind the method from the class prototype
699
- // directly onto the test instance.
700
- beforeEach(() => {
701
- llmService.getLocusUrlByDatachannelUrl = LLMChannel.prototype.getLocusUrlByDatachannelUrl.bind(llmService);
702
- });
613
+ const warnSpy = llmChannel.logger.warn;
703
614
 
704
- it('returns locusUrl when request URL matches a session datachannelUrl', async () => {
705
- await llmService.registerAndConnect(locusUrl, datachannelUrl, undefined, 's1');
706
- await llmService.registerAndConnect(locusUrl2, datachannelUrl2, undefined, 's2');
615
+ const result = await llmChannel.refreshDataChannelToken();
707
616
 
708
- const result = llmService.getLocusUrlByDatachannelUrl(datachannelUrl2 + '/some-path');
617
+ assert.equal(result, null);
709
618
 
710
- assert.equal(result, locusUrl2);
619
+ sinon.assert.calledOnce(warnSpy);
620
+ sinon.assert.calledWithMatch(warnSpy, sinon.match('DataChannel token refresh failed'));
711
621
  });
622
+ });
712
623
 
713
- it('returns undefined when no session matches the request URL', async () => {
714
- await llmService.registerAndConnect(locusUrl, datachannelUrl, undefined, 's1');
715
-
716
- const result = llmService.getLocusUrlByDatachannelUrl('https://unknown.example.com/path');
717
-
718
- assert.equal(result, undefined);
624
+ describe('#getDatachannelToken / #setDatachannelToken / #clearDatachannelToken', () => {
625
+ it('sets and gets datachannel token', () => {
626
+ llmChannel.setDatachannelToken('abc123');
627
+ assert.equal(llmChannel.getDatachannelToken(), 'abc123');
719
628
  });
720
629
 
721
- it('matches locusUrl when request host is rewritten but pathname matches', async () => {
722
- await llmService.registerAndConnect(locusUrl2, datachannelUrl2, undefined, 's2');
723
-
724
- const rewrittenHostRequestUrl =
725
- 'https://hostmap-rewritten.example.com/datachannel/api/v1/locus/ps-encoded/registrations/events';
726
- const result = llmService.getLocusUrlByDatachannelUrl(rewrittenHostRequestUrl);
727
-
728
- assert.equal(result, locusUrl2);
630
+ it('returns undefined when no token is set', () => {
631
+ assert.equal(llmChannel.getDatachannelToken(), undefined);
729
632
  });
730
633
 
731
- it('returns undefined when no connections exist', () => {
732
- const result = llmService.getLocusUrlByDatachannelUrl(datachannelUrl);
634
+ it('clears datachannel token', () => {
635
+ llmChannel.setDatachannelToken('abc123');
636
+ assert.equal(llmChannel.getDatachannelToken(), 'abc123');
733
637
 
734
- assert.equal(result, undefined);
638
+ llmChannel.clearDatachannelToken();
639
+ assert.equal(llmChannel.getDatachannelToken(), undefined);
735
640
  });
736
641
  });
737
642
 
738
- describe('#getSessionIdByDatachannelUrl', () => {
739
- const datachannelUrl2 = 'https://board-b.wbx2.com/datachannel/api/v1/locus/ps-encoded/registrations';
643
+ describe('.matchesDatachannelRequestUrl', () => {
644
+ it('returns true when request URL starts with registration URL', () => {
645
+ const registrationUrl =
646
+ 'https://board.wbx2.com/datachannel/api/v1/locus/ps-encoded/registrations';
647
+ const requestUrl = registrationUrl + '/some-path';
740
648
 
741
- beforeEach(() => {
742
- llmService.getSessionIdByDatachannelUrl = LLMChannel.prototype.getSessionIdByDatachannelUrl.bind(llmService);
743
- });
649
+ const result = LLMChannel.matchesDatachannelRequestUrl(requestUrl, registrationUrl);
744
650
 
745
- it('returns sessionId when request URL matches a session datachannelUrl', async () => {
746
- await llmService.registerAndConnect(locusUrl, datachannelUrl, undefined, 's1');
747
- await llmService.registerAndConnect('https://locus-b.wbx2.com/locus/api/v1/loci/456', datachannelUrl2, undefined, 's2');
748
-
749
- const result = llmService.getSessionIdByDatachannelUrl(datachannelUrl2 + '/some-path');
750
-
751
- assert.equal(result, 's2');
651
+ assert.equal(result, true);
752
652
  });
753
653
 
754
- it('returns undefined when no session matches the request URL', async () => {
755
- await llmService.registerAndConnect(locusUrl, datachannelUrl, undefined, 's1');
654
+ it('returns false when URLs do not match', () => {
655
+ const registrationUrl =
656
+ 'https://board.wbx2.com/datachannel/api/v1/locus/ps-encoded/registrations';
657
+ const requestUrl = 'https://unknown.example.com/path';
756
658
 
757
- const result = llmService.getSessionIdByDatachannelUrl('https://unknown.example.com/path');
659
+ const result = LLMChannel.matchesDatachannelRequestUrl(requestUrl, registrationUrl);
758
660
 
759
- assert.equal(result, undefined);
661
+ assert.equal(result, false);
760
662
  });
761
663
 
762
- it('matches sessionId when request host is rewritten but pathname matches', async () => {
763
- await llmService.registerAndConnect(
764
- 'https://locus-b.wbx2.com/locus/api/v1/loci/456',
765
- datachannelUrl2,
766
- undefined,
767
- 's2'
768
- );
664
+ it('returns true when request host is rewritten but pathname matches', () => {
665
+ const registrationUrl =
666
+ 'https://board-b.wbx2.com/datachannel/api/v1/locus/ps-encoded/registrations';
667
+ const requestUrl =
668
+ 'https://hostmap-rewritten.example.com/datachannel/api/v1/locus/ps-encoded/registrations/events';
769
669
 
770
- const rewrittenHostRequestUrl =
771
- 'https://hostmap-rewritten.example.com/datachannel/api/v1/locus/ps-encoded/registrations/messages';
772
- const result = llmService.getSessionIdByDatachannelUrl(rewrittenHostRequestUrl);
670
+ const result = LLMChannel.matchesDatachannelRequestUrl(requestUrl, registrationUrl);
773
671
 
774
- assert.equal(result, 's2');
672
+ assert.equal(result, true);
775
673
  });
776
- });
777
-
778
- describe('#registerAndConnect timing', () => {
779
- it('returns timing data on successful connection', async () => {
780
- const clock = sinon.useFakeTimers();
781
-
782
- llmService.isDataChannelTokenEnabled = sinon.stub().resolves(false);
783
- llmService.register = sinon.stub().callsFake(async () => {
784
- clock.tick(37);
785
-
786
- const sessionData = llmService.connections.get('llm-default-session') || {};
787
674
 
788
- sessionData.webSocketUrl = 'wss://example.com/socket';
789
- sessionData.binding = 'binding';
790
- llmService.connections.set('llm-default-session', sessionData);
791
- });
792
- llmService.connect = sinon.stub().callsFake(async () => {
793
- clock.tick(23);
794
- });
795
-
796
- const result = await llmService.registerAndConnect(locusUrl, datachannelUrl, undefined);
797
-
798
- assert.deepEqual(result, {
799
- clientLLMDatachannelResponseTime: 37,
800
- clientLLMWebSocketConnectTime: 23,
801
- });
675
+ it('returns false for empty or null URLs', () => {
676
+ assert.equal(LLMChannel.matchesDatachannelRequestUrl('', 'https://example.com'), false);
677
+ assert.equal(LLMChannel.matchesDatachannelRequestUrl('https://example.com', ''), false);
678
+ assert.equal(LLMChannel.matchesDatachannelRequestUrl(null, 'https://example.com'), false);
679
+ assert.equal(LLMChannel.matchesDatachannelRequestUrl('https://example.com', null), false);
802
680
  });
803
681
 
804
- it('returns undefined when locusUrl is empty', async () => {
805
- llmService.register = sinon.stub().resolves();
682
+ it('returns false for invalid URLs', () => {
683
+ const result = LLMChannel.matchesDatachannelRequestUrl('not-a-url', 'also-not-a-url');
806
684
 
807
- const result = await llmService.registerAndConnect('', datachannelUrl, undefined);
808
-
809
- assert.isUndefined(result);
685
+ assert.equal(result, false);
810
686
  });
811
687
  });
812
688
 
813
- describe('#getWebSocketUrl', () => {
814
- it('returns the websocket URL for default session', () => {
815
- llmService.connections.set('llm-default-session', {
816
- webSocketUrl: 'wss://test.example.com/ws',
817
- });
818
-
819
- assert.equal(llmService.getWebSocketUrl(), 'wss://test.example.com/ws');
820
- });
689
+ describe('.buildUrlWithAwareSubchannels', () => {
690
+ it('adds subscriptionAwareSubchannels query param', () => {
691
+ const baseUrl = 'wss://example.com/socket';
692
+ const subchannels = ['channel1', 'channel2'];
821
693
 
822
- it('returns undefined when no connection exists', () => {
823
- llmService.connections.clear();
694
+ const result = LLMChannel.buildUrlWithAwareSubchannels(baseUrl, subchannels);
824
695
 
825
- assert.isUndefined(llmService.getWebSocketUrl());
696
+ assert.include(result, 'subscriptionAwareSubchannels=channel1%2Cchannel2');
826
697
  });
827
698
 
828
- it('returns the websocket URL for custom session', () => {
829
- llmService.connections.set('custom-session', {
830
- webSocketUrl: 'wss://custom.example.com/ws',
831
- });
699
+ it('preserves existing query params', () => {
700
+ const baseUrl = 'wss://example.com/socket?existing=param';
701
+ const subchannels = ['channel1'];
702
+
703
+ const result = LLMChannel.buildUrlWithAwareSubchannels(baseUrl, subchannels);
832
704
 
833
- assert.equal(llmService.getWebSocketUrl('custom-session'), 'wss://custom.example.com/ws');
705
+ assert.include(result, 'existing=param');
706
+ assert.include(result, 'subscriptionAwareSubchannels=channel1');
834
707
  });
835
708
  });
836
709