agora-appbuilder-core 4.1.30-beta.2 → 4.1.31-beta.1

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.
@@ -6,6 +6,7 @@ interface CoordinatorDependencies {
6
6
  getClient: () => Pick<RTMClient, 'storage' | 'presence'>;
7
7
  createId: () => string;
8
8
  wait: (milliseconds: number) => Promise<void>;
9
+ log?: (event: string, details: Record<string, unknown>) => void;
9
10
  }
10
11
 
11
12
  export const createSTTSessionCoordinator = (
@@ -13,6 +14,23 @@ export const createSTTSessionCoordinator = (
13
14
  ) => {
14
15
  const sessionIds = new Map<string, string>();
15
16
  const pendingResolutions = new Map<string, Promise<string>>();
17
+ const pendingRotations = new Map<string, Promise<string>>();
18
+ // Channels whose current cached session_id was minted by this FE (either
19
+ // via initial createId or via rotateSessionId), until their first start.
20
+ // Later starts must validate reused IDs even if this FE originally minted them.
21
+ const freshlyCreatedChannels = new Set<string>();
22
+
23
+ // Observability must not affect session coordination.
24
+ const logSessionEvent = (
25
+ event: string,
26
+ details: Record<string, unknown>,
27
+ ): void => {
28
+ try {
29
+ dependencies.log?.(event, details);
30
+ } catch {
31
+ // A failed logging transport must not fail an STT operation.
32
+ }
33
+ };
16
34
 
17
35
  const getAndLogChannelMetadata = async (
18
36
  channelName: string,
@@ -103,7 +121,14 @@ export const createSTTSessionCoordinator = (
103
121
  revision: existing.revision,
104
122
  },
105
123
  );
124
+ logSessionEvent('STT session resolved', {
125
+ channelName,
126
+ sessionId: existing.value,
127
+ source: 'rtm',
128
+ revision: existing.revision,
129
+ });
106
130
  sessionIds.set(channelName, existing.value);
131
+ freshlyCreatedChannels.delete(channelName);
107
132
  return existing.value;
108
133
  }
109
134
 
@@ -135,7 +160,13 @@ export const createSTTSessionCoordinator = (
135
160
  channelName,
136
161
  'after session ID creation',
137
162
  );
163
+ logSessionEvent('STT session resolved', {
164
+ channelName,
165
+ sessionId: candidate,
166
+ source: 'created',
167
+ });
138
168
  sessionIds.set(channelName, candidate);
169
+ freshlyCreatedChannels.add(channelName);
139
170
  return candidate;
140
171
  } catch (error) {
141
172
  lastError = error;
@@ -156,7 +187,14 @@ export const createSTTSessionCoordinator = (
156
187
  revision: winner.revision,
157
188
  },
158
189
  );
190
+ logSessionEvent('STT session resolved', {
191
+ channelName,
192
+ sessionId: winner.value,
193
+ source: 'creation_peer',
194
+ revision: winner.revision,
195
+ });
159
196
  sessionIds.set(channelName, winner.value);
197
+ freshlyCreatedChannels.delete(channelName);
160
198
  return winner.value;
161
199
  }
162
200
  }
@@ -171,12 +209,21 @@ export const createSTTSessionCoordinator = (
171
209
  };
172
210
 
173
211
  const ensureSTTSessionId = async (channelName: string): Promise<string> => {
212
+ const rotation = pendingRotations.get(channelName);
213
+ if (rotation) {
214
+ return rotation;
215
+ }
174
216
  const cached = sessionIds.get(channelName);
175
217
  if (cached) {
176
218
  console.log('[STT_SESSION_ID] Using locally cached session ID', {
177
219
  channelName,
178
220
  sessionId: cached,
179
221
  });
222
+ logSessionEvent('STT session resolved', {
223
+ channelName,
224
+ sessionId: cached,
225
+ source: 'cache',
226
+ });
180
227
  return cached;
181
228
  }
182
229
 
@@ -299,10 +346,165 @@ export const createSTTSessionCoordinator = (
299
346
  if (channelName) {
300
347
  sessionIds.delete(channelName);
301
348
  pendingResolutions.delete(channelName);
349
+ freshlyCreatedChannels.delete(channelName);
302
350
  return;
303
351
  }
304
352
  sessionIds.clear();
305
353
  pendingResolutions.clear();
354
+ freshlyCreatedChannels.clear();
355
+ };
356
+
357
+ const wasSessionIdFreshlyCreated = (channelName: string): boolean =>
358
+ freshlyCreatedChannels.has(channelName);
359
+
360
+ const markSessionIdUsed = (channelName: string, sessionId: string): void => {
361
+ if (sessionIds.get(channelName) === sessionId) {
362
+ freshlyCreatedChannels.delete(channelName);
363
+ }
364
+ };
365
+
366
+ const replaceSessionId = async (
367
+ channelName: string,
368
+ staleSessionId: string,
369
+ ): Promise<string> => {
370
+ console.log('[STT_SESSION_ID] Rotating session ID due to stale value', {
371
+ channelName,
372
+ staleSessionId,
373
+ });
374
+
375
+ // Finish any older lookup before replacing its value, so it cannot later
376
+ // restore the stale ID in the local cache.
377
+ await pendingResolutions.get(channelName)?.catch(() => undefined);
378
+ sessionIds.delete(channelName);
379
+ freshlyCreatedChannels.delete(channelName);
380
+
381
+ const existing = await readSessionItem(
382
+ channelName,
383
+ 'before session ID rotation',
384
+ );
385
+
386
+ if (
387
+ existing?.value &&
388
+ staleSessionId &&
389
+ existing.value !== staleSessionId
390
+ ) {
391
+ console.log(
392
+ '[STT_SESSION_ID] Another peer already rotated; adopting their value',
393
+ {
394
+ channelName,
395
+ sessionId: existing.value,
396
+ revision: existing.revision,
397
+ staleSessionId,
398
+ },
399
+ );
400
+ logSessionEvent('STT session rotation adopted', {
401
+ channelName,
402
+ staleSessionId,
403
+ sessionId: existing.value,
404
+ revision: existing.revision,
405
+ source: 'rtm',
406
+ });
407
+ sessionIds.set(channelName, existing.value);
408
+ return existing.value;
409
+ }
410
+
411
+ const candidate = dependencies.createId();
412
+ const expectedRevision = existing?.revision ?? 0;
413
+ console.log('[STT_SESSION_ID] Attempting revision-checked replacement', {
414
+ channelName,
415
+ currentSessionId: existing?.value ?? null,
416
+ nextSessionId: candidate,
417
+ expectedRevision,
418
+ });
419
+
420
+ try {
421
+ await dependencies.getClient().storage.setChannelMetadata(
422
+ channelName,
423
+ 1,
424
+ {
425
+ items: [
426
+ {
427
+ key: STT_SESSION_ID_KEY,
428
+ value: candidate,
429
+ revision: expectedRevision,
430
+ },
431
+ ],
432
+ },
433
+ {addUserId: true, addTimeStamp: true},
434
+ );
435
+ console.log(
436
+ '[STT_SESSION_ID] Rotated session ID in RTM channel metadata',
437
+ {channelName, sessionId: candidate},
438
+ );
439
+ logSessionEvent('STT session rotated', {
440
+ channelName,
441
+ staleSessionId,
442
+ sessionId: candidate,
443
+ expectedRevision,
444
+ });
445
+ sessionIds.set(channelName, candidate);
446
+ freshlyCreatedChannels.add(channelName);
447
+ await logChannelMetadataBestEffort(
448
+ channelName,
449
+ 'after session ID rotation',
450
+ );
451
+ return candidate;
452
+ } catch (error) {
453
+ console.log(
454
+ '[STT_SESSION_ID] Rotation lost the race; reading shared value',
455
+ {channelName, attemptedSessionId: candidate, error},
456
+ );
457
+ const winner = await readSessionItem(
458
+ channelName,
459
+ 'after rotation conflict',
460
+ );
461
+ if (winner?.value && winner.value !== staleSessionId) {
462
+ console.log(
463
+ '[STT_SESSION_ID] Adopting session ID rotated by another participant',
464
+ {
465
+ channelName,
466
+ sessionId: winner.value,
467
+ revision: winner.revision,
468
+ },
469
+ );
470
+ logSessionEvent('STT session rotation adopted', {
471
+ channelName,
472
+ staleSessionId,
473
+ sessionId: winner.value,
474
+ revision: winner.revision,
475
+ source: 'write_recovery',
476
+ });
477
+ sessionIds.set(channelName, winner.value);
478
+ freshlyCreatedChannels.delete(channelName);
479
+ return winner.value;
480
+ }
481
+ logSessionEvent('STT session rotation failed', {
482
+ channelName,
483
+ staleSessionId,
484
+ attemptedSessionId: candidate,
485
+ expectedRevision,
486
+ });
487
+ throw error;
488
+ }
489
+ };
490
+
491
+ const rotateSessionId = async (
492
+ channelName: string,
493
+ staleSessionId: string,
494
+ ): Promise<string> => {
495
+ // Serialize local recoveries as well as using RTM revisions across peers.
496
+ while (pendingRotations.has(channelName)) {
497
+ await pendingRotations.get(channelName)!.catch(() => undefined);
498
+ }
499
+ const rotation = replaceSessionId(channelName, staleSessionId);
500
+ pendingRotations.set(channelName, rotation);
501
+ try {
502
+ return await rotation;
503
+ } finally {
504
+ if (pendingRotations.get(channelName) === rotation) {
505
+ pendingRotations.delete(channelName);
506
+ }
507
+ }
306
508
  };
307
509
 
308
510
  return {
@@ -311,5 +513,8 @@ export const createSTTSessionCoordinator = (
311
513
  clearSTTSessionIdIfLast,
312
514
  cleanupSTTSessionOnEnd,
313
515
  resetSTTSessionIdCache,
516
+ rotateSessionId,
517
+ wasSessionIdFreshlyCreated,
518
+ markSessionIdUsed,
314
519
  };
315
520
  };
@@ -1,3 +1,5 @@
1
+ import {logger, LogSource} from '../../logger/AppBuilderLogger';
2
+ import {TRANSCRIPT_JOURNEY} from './transcriptJourney';
1
3
  import RTMEngine from '../../rtm/RTMEngine';
2
4
  import getUniqueID from '../../utils/getUniqueID';
3
5
  import {createSTTSessionCoordinator} from './sttSessionCoordinator';
@@ -10,6 +12,13 @@ export {
10
12
  const coordinator = createSTTSessionCoordinator({
11
13
  getClient: () => RTMEngine.getInstance().engine,
12
14
  createId: getUniqueID,
15
+ log: (event, details) =>
16
+ logger.log(
17
+ LogSource.Internals,
18
+ 'STT',
19
+ `${TRANSCRIPT_JOURNEY} ${event}`,
20
+ details,
21
+ ),
13
22
  wait: milliseconds =>
14
23
  new Promise(resolve => setTimeout(resolve, milliseconds)),
15
24
  });
@@ -19,3 +28,8 @@ export const isOnlyLocalRTMParticipant = coordinator.isOnlyLocalRTMParticipant;
19
28
  export const clearSTTSessionIdIfLast = coordinator.clearSTTSessionIdIfLast;
20
29
  export const cleanupSTTSessionOnEnd = coordinator.cleanupSTTSessionOnEnd;
21
30
  export const resetSTTSessionIdCache = coordinator.resetSTTSessionIdCache;
31
+ export const rotateSTTSessionId = coordinator.rotateSessionId;
32
+ export const wasSTTSessionIdFreshlyCreated =
33
+ coordinator.wasSessionIdFreshlyCreated;
34
+
35
+ export const markSTTSessionIdUsed = coordinator.markSessionIdUsed;
@@ -1,3 +1,5 @@
1
+ import {logger, LogSource} from '../../logger/AppBuilderLogger';
2
+ import {TRANSCRIPT_JOURNEY} from './transcriptJourney';
1
3
  import RTMEngine from '../../rtm/RTMEngine';
2
4
  import getUniqueID from '../../utils/getUniqueID';
3
5
  import {createSTTSessionCoordinator} from './sttSessionCoordinator';
@@ -10,6 +12,13 @@ export {
10
12
  const coordinator = createSTTSessionCoordinator({
11
13
  getClient: () => RTMEngine.getInstance().engine,
12
14
  createId: getUniqueID,
15
+ log: (event, details) =>
16
+ logger.log(
17
+ LogSource.Internals,
18
+ 'STT',
19
+ `${TRANSCRIPT_JOURNEY} ${event}`,
20
+ details,
21
+ ),
13
22
  wait: milliseconds =>
14
23
  new Promise(resolve => setTimeout(resolve, milliseconds)),
15
24
  });
@@ -19,3 +28,8 @@ export const isOnlyLocalRTMParticipant = coordinator.isOnlyLocalRTMParticipant;
19
28
  export const clearSTTSessionIdIfLast = coordinator.clearSTTSessionIdIfLast;
20
29
  export const cleanupSTTSessionOnEnd = coordinator.cleanupSTTSessionOnEnd;
21
30
  export const resetSTTSessionIdCache = coordinator.resetSTTSessionIdCache;
31
+ export const rotateSTTSessionId = coordinator.rotateSessionId;
32
+ export const wasSTTSessionIdFreshlyCreated =
33
+ coordinator.wasSessionIdFreshlyCreated;
34
+
35
+ export const markSTTSessionIdUsed = coordinator.markSessionIdUsed;
@@ -47,6 +47,12 @@ type SttQueueItem = {
47
47
  state: GlobalSttState;
48
48
  isLocal: boolean;
49
49
  targetChange?: TargetChange;
50
+ // Deferred callbacks resolved by processSttEventQueue so callers of
51
+ // enqueueSttEvent can observe whether the queued local operation
52
+ // actually succeeded. Items pushed outside enqueueSttEvent (e.g. the
53
+ // auto-start injection) leave these undefined; the processor no-ops.
54
+ resolve?: () => void;
55
+ reject?: (err: unknown) => void;
50
56
  };
51
57
 
52
58
  export type LanguageTranslationConfig = {
@@ -632,6 +638,7 @@ const CaptionProvider: React.FC<CaptionProviderProps> = ({
632
638
  'stt',
633
639
  `${TRANSCRIPT_JOURNEY} STT started successfully`,
634
640
  result.data ?? null,
641
+ {sessionId: result.sessionId ?? null},
635
642
  );
636
643
  } else {
637
644
  setIsSTTError(true);
@@ -640,16 +647,23 @@ const CaptionProvider: React.FC<CaptionProviderProps> = ({
640
647
  'stt',
641
648
  `${TRANSCRIPT_JOURNEY} failed to start STT`,
642
649
  result.error ?? null,
650
+ {sessionId: result.sessionId ?? null},
643
651
  );
644
- Toast.show({
645
- leadingIconName: 'alert',
646
- type: 'error',
647
- text1: startErrorLabel,
648
- text2: result.error?.message || 'Unknown error occurred',
649
- visibilityTime: 4000,
650
- primaryBtn: null,
651
- secondaryBtn: null,
652
- });
652
+ // Suppress the user-facing toast for terminal-reuse errors (code 631).
653
+ // The 631 path is a transient coordination failure that the rotate +
654
+ // retry inside useSTTAPI already handles; if a 631 still surfaces
655
+ // here, it has already been structurally logged above.
656
+ if (result.error?.code !== 631) {
657
+ Toast.show({
658
+ leadingIconName: 'alert',
659
+ type: 'error',
660
+ text1: startErrorLabel,
661
+ text2: result.error?.message || 'Unknown error occurred',
662
+ visibilityTime: 4000,
663
+ primaryBtn: null,
664
+ secondaryBtn: null,
665
+ });
666
+ }
653
667
  }
654
668
  setIsLangChangeInProgress(false);
655
669
  return result;
@@ -872,8 +886,6 @@ const CaptionProvider: React.FC<CaptionProviderProps> = ({
872
886
  };
873
887
  }
874
888
  }
875
- // Queue
876
- enqueueSttEvent(updatedState, true, targetChange);
877
889
 
878
890
  logger.log(
879
891
  LogSource.Internals,
@@ -887,6 +899,11 @@ const CaptionProvider: React.FC<CaptionProviderProps> = ({
887
899
  updatedState.globalTranslationTargets.length,
888
900
  },
889
901
  );
902
+
903
+ // Await the queued processing so the UI caller (e.g. Show Caption)
904
+ // can observe whether the start actually succeeded, and revert its
905
+ // optimistic state on failure.
906
+ await enqueueSttEvent(updatedState, true, targetChange);
890
907
  } catch (error) {
891
908
  logger.error(
892
909
  LogSource.Internals,
@@ -898,6 +915,7 @@ const CaptionProvider: React.FC<CaptionProviderProps> = ({
898
915
  error: error ?? null,
899
916
  },
900
917
  );
918
+ throw error;
901
919
  }
902
920
  },
903
921
  [localUid], // only real dependency
@@ -939,40 +957,55 @@ const CaptionProvider: React.FC<CaptionProviderProps> = ({
939
957
  globalSpokenLanguage: globalSttStateRef.current.globalSpokenLanguage,
940
958
  globalTranslationTargets: newTargets,
941
959
  };
942
- // 5. Queue event
960
+ // 5. Queue event. Caller doesn't surface failure to UI today; swallow
961
+ // rejections to avoid unhandled-promise-rejection warnings.
943
962
  const prevTargetLang = selectedTranslationLanguageRef.current;
944
963
  enqueueSttEvent(updatedState, true, {
945
964
  prev: prevTargetLang,
946
965
  next: newTargetLang,
966
+ }).catch(() => {
967
+ /* already logged by processSttEventQueue */
947
968
  });
948
969
  },
949
970
  [selectedTranslationLanguage], // only real state dependency
950
971
  );
951
972
 
952
- // Queues all local + remote stt events
973
+ // Queues all local + remote stt events.
974
+ // Returns a promise that resolves once the queued item has been processed
975
+ // (whether no-op, applied, or skipped). Rejects if the underlying STT API
976
+ // call fails for a local item, so the UI caller can revert optimistic
977
+ // state (e.g. the Show Caption / Hide Caption label).
953
978
  const enqueueSttEvent = React.useCallback(
954
- (state: GlobalSttState, isLocal: boolean, targetChange?: TargetChange) => {
955
- sttEventQueueRef.current.push({
956
- state,
957
- isLocal,
958
- targetChange,
979
+ (
980
+ state: GlobalSttState,
981
+ isLocal: boolean,
982
+ targetChange?: TargetChange,
983
+ ): Promise<void> => {
984
+ return new Promise<void>((resolve, reject) => {
985
+ sttEventQueueRef.current.push({
986
+ state,
987
+ isLocal,
988
+ targetChange,
989
+ resolve,
990
+ reject,
991
+ });
992
+ logger.log(
993
+ LogSource.Internals,
994
+ 'TRANSCRIPT',
995
+ `${TRANSCRIPT_JOURNEY} STT global state queued`,
996
+ {
997
+ stage: 'global_state_queue',
998
+ outcome: 'queued',
999
+ stateOrigin: isLocal ? 'local' : 'remote',
1000
+ sttEnabled: state.globalSttEnabled,
1001
+ sttDepsReady: sttDepsReadyRef.current,
1002
+ queueSize: sttEventQueueRef.current.length,
1003
+ },
1004
+ );
1005
+ if (sttDepsReadyRef.current) {
1006
+ processSttEventQueue();
1007
+ }
959
1008
  });
960
- logger.log(
961
- LogSource.Internals,
962
- 'TRANSCRIPT',
963
- `${TRANSCRIPT_JOURNEY} STT global state queued`,
964
- {
965
- stage: 'global_state_queue',
966
- outcome: 'queued',
967
- stateOrigin: isLocal ? 'local' : 'remote',
968
- sttEnabled: state.globalSttEnabled,
969
- sttDepsReady: sttDepsReadyRef.current,
970
- queueSize: sttEventQueueRef.current.length,
971
- },
972
- );
973
- if (sttDepsReadyRef.current) {
974
- processSttEventQueue();
975
- }
976
1009
  },
977
1010
  [],
978
1011
  );
@@ -1025,7 +1058,7 @@ const CaptionProvider: React.FC<CaptionProviderProps> = ({
1025
1058
  if (!item) {
1026
1059
  break;
1027
1060
  }
1028
- const {state: newState, isLocal, targetChange} = item;
1061
+ const {state: newState, isLocal, targetChange, resolve, reject} = item;
1029
1062
  const prevState = globalSttStateRef.current;
1030
1063
  if (isSameState(prevState, newState)) {
1031
1064
  logger.log(
@@ -1034,7 +1067,8 @@ const CaptionProvider: React.FC<CaptionProviderProps> = ({
1034
1067
  `${TRANSCRIPT_JOURNEY} duplicate STT global state skipped`,
1035
1068
  {stage: 'global_state_queue', outcome: 'skipped'},
1036
1069
  );
1037
- continue; // no call to processGlobalSttSingleEvent
1070
+ resolve?.(); // no-op from the caller's perspective, but a success
1071
+ continue;
1038
1072
  }
1039
1073
  const ok = await processGlobalSttSingleEvent(
1040
1074
  newState,
@@ -1049,6 +1083,7 @@ const CaptionProvider: React.FC<CaptionProviderProps> = ({
1049
1083
  `${TRANSCRIPT_JOURNEY} local global state update skipped because API failed`,
1050
1084
  {stage: 'global_state_apply', outcome: 'skipped'},
1051
1085
  );
1086
+ reject?.(new Error('STT API call failed'));
1052
1087
  continue;
1053
1088
  }
1054
1089
  // A received RTM event is authoritative for the meeting-level state.
@@ -1064,6 +1099,7 @@ const CaptionProvider: React.FC<CaptionProviderProps> = ({
1064
1099
  // update global state AFTER processing
1065
1100
  setGlobalSttState(newState);
1066
1101
  globalSttStateRef.current = newState;
1102
+ resolve?.();
1067
1103
  }
1068
1104
  isProcessingSttEventRef.current = false;
1069
1105
  }, []);
@@ -1301,7 +1337,11 @@ const CaptionProvider: React.FC<CaptionProviderProps> = ({
1301
1337
  );
1302
1338
  return;
1303
1339
  }
1304
- enqueueSttEvent(newState, false);
1340
+ // Remote events are informational for the caller; we don't surface
1341
+ // their failure. Swallow rejections so they don't become unhandled.
1342
+ enqueueSttEvent(newState, false).catch(() => {
1343
+ /* already logged by processSttEventQueue */
1344
+ });
1305
1345
  };
1306
1346
 
1307
1347
  events.on(EventNames.STT_GLOBAL_STATE, handleGlobalSTTChange);