agora-appbuilder-core 4.1.30 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agora-appbuilder-core",
3
- "version": "4.1.30",
3
+ "version": "4.1.31-beta.1",
4
4
  "description": "React Native template for RTE app builder",
5
5
  "main": "index.js",
6
6
  "files": [
@@ -77,8 +77,8 @@ const DefaultConfig = {
77
77
  CHAT_ORG_NAME: "",
78
78
  CHAT_APP_NAME: "",
79
79
  CHAT_URL: "",
80
- CLI_VERSION: "3.1.30",
81
- CORE_VERSION: "4.1.30",
80
+ CLI_VERSION: "3.1.31-beta.1",
81
+ CORE_VERSION: "4.1.31-beta.1",
82
82
  DISABLE_LANDSCAPE_MODE: false,
83
83
  STT_AUTO_START: false,
84
84
  CLOUD_RECORDING_AUTO_START: false,
@@ -9,6 +9,11 @@ const mockPresence = {
9
9
  getOnlineUsers: jest.fn<any>(),
10
10
  };
11
11
 
12
+ jest.mock('../../../logger/AppBuilderLogger', () => ({
13
+ LogSource: {Internals: 'Internals'},
14
+ logger: {log: jest.fn()},
15
+ }));
16
+
12
17
  jest.mock('../../../rtm/RTMEngine', () => ({
13
18
  __esModule: true,
14
19
  default: {
@@ -1,5 +1,10 @@
1
1
  import {beforeEach, describe, expect, it, jest} from '@jest/globals';
2
2
 
3
+ jest.mock('../../../logger/AppBuilderLogger', () => ({
4
+ LogSource: {Internals: 'Internals'},
5
+ logger: {log: jest.fn()},
6
+ }));
7
+
3
8
  jest.mock('../../../rtm/RTMEngine', () => ({
4
9
  __esModule: true,
5
10
  default: {
@@ -58,13 +63,15 @@ const createHarness = () => {
58
63
  };
59
64
  const createId = jest.fn(() => 'candidate');
60
65
  const wait = jest.fn(async () => {});
66
+ const log = jest.fn();
61
67
  const coordinator = createSTTSessionCoordinator({
68
+ log,
62
69
  getClient: () => ({storage, presence: rtmPresence} as any),
63
70
  createId,
64
71
  wait,
65
72
  });
66
73
 
67
- return {coordinator, createId, rtmPresence, storage, wait};
74
+ return {coordinator, createId, rtmPresence, storage, wait, log};
68
75
  };
69
76
 
70
77
  describe('web STT session coordinator', () => {
@@ -72,6 +79,96 @@ describe('web STT session coordinator', () => {
72
79
  jest.clearAllMocks();
73
80
  });
74
81
 
82
+ it('two peers converge on one replacement and delayed errors adopt it', async () => {
83
+ const {storage, rtmPresence} = createHarness();
84
+ let value = 'stale';
85
+ let revision = 9;
86
+ storage.getChannelMetadata.mockImplementation(async () =>
87
+ channelMetadata(value, revision),
88
+ );
89
+ storage.setChannelMetadata.mockImplementation(
90
+ async (_channel, _type, data) => {
91
+ if (data.items[0].revision !== revision) {
92
+ throw new Error('revision conflict');
93
+ }
94
+ value = data.items[0].value;
95
+ revision += 1;
96
+ return {};
97
+ },
98
+ );
99
+ const makePeer = (candidate: string, log = jest.fn()) =>
100
+ createSTTSessionCoordinator({
101
+ getClient: () => ({storage, presence: rtmPresence} as any),
102
+ createId: () => candidate,
103
+ wait: async () => {},
104
+ log,
105
+ });
106
+ const logB = jest.fn();
107
+ const a = makePeer('new-a');
108
+ const b = makePeer('new-b', logB);
109
+ const ids = await Promise.all([
110
+ a.rotateSessionId('room', 'stale'),
111
+ b.rotateSessionId('room', 'stale'),
112
+ ]);
113
+ expect(ids).toEqual(['new-a', 'new-a']);
114
+ expect(await a.ensureSTTSessionId('room')).toBe('new-a');
115
+ expect(await b.ensureSTTSessionId('room')).toBe('new-a');
116
+ expect(logB).toHaveBeenCalledWith(
117
+ 'STT session rotation adopted',
118
+ expect.objectContaining({sessionId: 'new-a', staleSessionId: 'stale'}),
119
+ );
120
+ storage.setChannelMetadata.mockClear();
121
+ expect(await b.rotateSessionId('room', 'stale')).toBe('new-a');
122
+ expect(storage.setChannelMetadata).not.toHaveBeenCalled();
123
+ });
124
+
125
+ it('surfaces a failed rotation instead of adopting the unchanged stale value', async () => {
126
+ const {coordinator, storage} = createHarness();
127
+ storage.getChannelMetadata.mockResolvedValue(channelMetadata('stale'));
128
+ storage.setChannelMetadata.mockRejectedValue(
129
+ new Error('permission denied'),
130
+ );
131
+ await expect(coordinator.rotateSessionId('room', 'stale')).rejects.toThrow(
132
+ 'permission denied',
133
+ );
134
+ });
135
+
136
+ it('does not let an older lookup restore a stale value after recovery', async () => {
137
+ const {coordinator, storage} = createHarness();
138
+ let finishRead!: (value: any) => void;
139
+ storage.getChannelMetadata
140
+ .mockImplementationOnce(
141
+ () =>
142
+ new Promise(resolve => {
143
+ finishRead = resolve;
144
+ }),
145
+ )
146
+ .mockResolvedValue(channelMetadata('stale'));
147
+ storage.setChannelMetadata.mockResolvedValue({});
148
+ const lookup = coordinator.ensureSTTSessionId('room');
149
+ const rotation = coordinator.rotateSessionId('room', 'stale');
150
+ finishRead(channelMetadata('stale'));
151
+ await lookup;
152
+ expect(await rotation).toBe('candidate');
153
+ expect(await coordinator.ensureSTTSessionId('room')).toBe('candidate');
154
+ });
155
+
156
+ it('only skips validation until a locally created ID is first used', async () => {
157
+ const {coordinator, storage, log} = createHarness();
158
+ storage.getChannelMetadata.mockResolvedValue(channelMetadata());
159
+ storage.setChannelMetadata.mockResolvedValue({});
160
+ log.mockImplementation(() => {
161
+ throw new Error('transport failed');
162
+ });
163
+ expect(await coordinator.ensureSTTSessionId('room')).toBe('candidate');
164
+ expect(coordinator.wasSessionIdFreshlyCreated('room')).toBe(true);
165
+ coordinator.markSessionIdUsed('room', 'other-id');
166
+ expect(coordinator.wasSessionIdFreshlyCreated('room')).toBe(true);
167
+ coordinator.markSessionIdUsed('room', 'candidate');
168
+ expect(coordinator.wasSessionIdFreshlyCreated('room')).toBe(false);
169
+ expect(await coordinator.ensureSTTSessionId('room')).toBe('candidate');
170
+ });
171
+
75
172
  it('reuses existing channel metadata without writing', async () => {
76
173
  const {coordinator, storage} = createHarness();
77
174
  storage.getChannelMetadata.mockResolvedValue(
@@ -4,6 +4,9 @@ import {beforeEach, describe, expect, it, jest} from '@jest/globals';
4
4
 
5
5
  jest.mock('../sttSessionId', () => ({
6
6
  ensureSTTSessionId: jest.fn(),
7
+ rotateSTTSessionId: jest.fn(),
8
+ wasSTTSessionIdFreshlyCreated: jest.fn(() => true),
9
+ markSTTSessionIdUsed: jest.fn(),
7
10
  }));
8
11
 
9
12
  jest.mock('../../../components/StorageContext', () => {
@@ -34,6 +37,7 @@ jest.mock('../../../logger/AppBuilderLogger', () => ({
34
37
  getSessionId: () => 'logging-session',
35
38
  log: jest.fn(),
36
39
  error: jest.fn(),
40
+ warn: jest.fn(),
37
41
  },
38
42
  }));
39
43
 
@@ -43,7 +47,13 @@ jest.mock('../../../utils/getUniqueID', () => ({
43
47
  }));
44
48
 
45
49
  import useSTTAPI from '../useSTTAPI';
46
- import {ensureSTTSessionId} from '../sttSessionId';
50
+ import {
51
+ ensureSTTSessionId,
52
+ rotateSTTSessionId,
53
+ wasSTTSessionIdFreshlyCreated,
54
+ markSTTSessionIdUsed,
55
+ } from '../sttSessionId';
56
+ import {logger} from '../../../logger/AppBuilderLogger';
47
57
 
48
58
  const mockEnsureSTTSessionId = ensureSTTSessionId as jest.Mock<any>;
49
59
 
@@ -73,6 +83,9 @@ const renderHook = async () => {
73
83
  describe('useSTTAPI session coordination', () => {
74
84
  beforeEach(() => {
75
85
  jest.clearAllMocks();
86
+ (wasSTTSessionIdFreshlyCreated as jest.Mock<any>).mockReturnValue(true);
87
+ (rotateSTTSessionId as jest.Mock<any>).mockReset();
88
+ (markSTTSessionIdUsed as jest.Mock<any>).mockReset();
76
89
  global.fetch = jest.fn<any>(async () => ({
77
90
  json: async () => ({}),
78
91
  }));
@@ -107,7 +120,7 @@ describe('useSTTAPI session coordination', () => {
107
120
  });
108
121
 
109
122
  expect(global.fetch).toHaveBeenCalledTimes(3);
110
- expect(mockEnsureSTTSessionId).toHaveBeenCalledTimes(3);
123
+ expect(mockEnsureSTTSessionId).toHaveBeenCalledTimes(4);
111
124
  const fetchCalls = (global.fetch as jest.Mock<any>).mock.calls as [
112
125
  string,
113
126
  {body: string; headers: Record<string, string>},
@@ -126,4 +139,257 @@ describe('useSTTAPI session coordination', () => {
126
139
  ]);
127
140
  renderer.unmount();
128
141
  });
142
+
143
+ it('correlates 631 recovery with the failed request ID even if the cache changed', async () => {
144
+ mockEnsureSTTSessionId.mockResolvedValue('old-session');
145
+ (rotateSTTSessionId as jest.Mock<any>).mockResolvedValue('new-session');
146
+ (global.fetch as jest.Mock<any>)
147
+ .mockImplementationOnce(async () => {
148
+ // A peer replaced the local cached value while the old request was pending.
149
+ mockEnsureSTTSessionId.mockResolvedValue('new-session');
150
+ return {
151
+ ok: false,
152
+ status: 409,
153
+ json: async () => ({error: {code: 631, message: 'session ended'}}),
154
+ };
155
+ })
156
+ .mockResolvedValueOnce({ok: true, status: 200, json: async () => ({})});
157
+ const {api, renderer} = await renderHook();
158
+ let response;
159
+ await act(async () => {
160
+ response = await api.start(900000123, translationConfig);
161
+ });
162
+ expect(rotateSTTSessionId).toHaveBeenCalledWith('room', 'old-session');
163
+ expect(response).toMatchObject({success: true, sessionId: 'new-session'});
164
+ const attempts = (logger.log as jest.Mock<any>).mock.calls.filter(call =>
165
+ call[2].endsWith('STT start attempt'),
166
+ );
167
+ expect(attempts.map(call => call[3])).toEqual([
168
+ expect.objectContaining({
169
+ attempt: 1,
170
+ sessionId: 'old-session',
171
+ channelName: 'room',
172
+ requestId: 'request-id',
173
+ }),
174
+ expect.objectContaining({
175
+ attempt: 2,
176
+ sessionId: 'new-session',
177
+ channelName: 'room',
178
+ requestId: 'request-id',
179
+ }),
180
+ ]);
181
+ expect(JSON.stringify(attempts)).not.toContain('phrase');
182
+ expect(JSON.stringify(attempts)).not.toContain('Bearer');
183
+ expect(logger.error).toHaveBeenCalledWith(
184
+ expect.anything(),
185
+ 'stt',
186
+ expect.stringContaining('STT API Failure'),
187
+ expect.anything(),
188
+ expect.objectContaining({sessionId: 'old-session', httpStatus: 409}),
189
+ );
190
+ renderer.unmount();
191
+ });
192
+
193
+ it('retains the sent session ID when a network request fails', async () => {
194
+ mockEnsureSTTSessionId.mockResolvedValue('sent-session');
195
+ (global.fetch as jest.Mock<any>).mockRejectedValue(new Error('offline'));
196
+ const {api, renderer} = await renderHook();
197
+ let response;
198
+ await act(async () => {
199
+ response = await api.start(900000123, translationConfig);
200
+ });
201
+ expect(response).toMatchObject({success: false, sessionId: 'sent-session'});
202
+ expect(logger.error).toHaveBeenCalledWith(
203
+ expect.anything(),
204
+ 'stt',
205
+ expect.stringContaining('STT API Failure'),
206
+ expect.anything(),
207
+ expect.objectContaining({
208
+ sessionId: 'sent-session',
209
+ requestId: 'request-id',
210
+ }),
211
+ );
212
+ renderer.unmount();
213
+ });
214
+
215
+ it.each([
216
+ 'COMPLETED',
217
+ 'FAILED',
218
+ 'ARTIFACTS_PENDING',
219
+ 'PROCESSING',
220
+ 'STARTED',
221
+ 'INPROGRESS',
222
+ 'NOT_LISTED',
223
+ ])('preflights a reused ID in state %s before start', async status => {
224
+ mockEnsureSTTSessionId.mockResolvedValue('stored-session');
225
+ (wasSTTSessionIdFreshlyCreated as jest.Mock<any>).mockReturnValue(false);
226
+ const shouldRotate = [
227
+ 'COMPLETED',
228
+ 'FAILED',
229
+ 'ARTIFACTS_PENDING',
230
+ 'PROCESSING',
231
+ ].includes(status);
232
+ (rotateSTTSessionId as jest.Mock<any>).mockImplementation(async () => {
233
+ mockEnsureSTTSessionId.mockResolvedValue('replacement');
234
+ return 'replacement';
235
+ });
236
+ (global.fetch as jest.Mock<any>)
237
+ .mockResolvedValueOnce({
238
+ ok: true,
239
+ status: 200,
240
+ json: async () => ({
241
+ stts:
242
+ status === 'NOT_LISTED'
243
+ ? []
244
+ : [{session_id: 'stored-session', status}],
245
+ }),
246
+ })
247
+ .mockResolvedValueOnce({ok: true, status: 200, json: async () => ({})});
248
+ const {api, renderer} = await renderHook();
249
+ await act(async () => {
250
+ await api.start(900000123, translationConfig);
251
+ });
252
+ const calls = (global.fetch as jest.Mock<any>).mock.calls;
253
+ expect(calls[0][0]).toMatch(/\/v1\/stt-transcript$/);
254
+ expect(JSON.parse(calls[0][1].body)).toEqual({
255
+ passphrase: 'phrase',
256
+ page: 1,
257
+ limit: 50,
258
+ });
259
+ expect(JSON.parse(calls[1][1].body).session_id).toBe(
260
+ shouldRotate ? 'replacement' : 'stored-session',
261
+ );
262
+ expect(rotateSTTSessionId).toHaveBeenCalledTimes(shouldRotate ? 1 : 0);
263
+ renderer.unmount();
264
+ });
265
+
266
+ it('checks a locally minted ID on a later start after it has been used', async () => {
267
+ mockEnsureSTTSessionId.mockResolvedValue('minted-session');
268
+ (markSTTSessionIdUsed as jest.Mock<any>).mockImplementation(() => {
269
+ (wasSTTSessionIdFreshlyCreated as jest.Mock<any>).mockReturnValue(false);
270
+ });
271
+ (global.fetch as jest.Mock<any>).mockResolvedValue({
272
+ ok: true,
273
+ status: 200,
274
+ json: async () => ({stts: []}),
275
+ });
276
+ const {api, renderer} = await renderHook();
277
+ await act(async () => {
278
+ await api.start(900000123, translationConfig);
279
+ await api.start(900000123, translationConfig);
280
+ });
281
+ expect(
282
+ (global.fetch as jest.Mock<any>).mock.calls.map(call => call[0]),
283
+ ).toEqual([
284
+ expect.stringMatching(/\/startv7$/),
285
+ expect.stringMatching(/\/stt-transcript$/),
286
+ expect.stringMatching(/\/startv7$/),
287
+ ]);
288
+ renderer.unmount();
289
+ });
290
+
291
+ it('retries start once after a 631 on the last transient retry', async () => {
292
+ jest.useFakeTimers();
293
+ try {
294
+ mockEnsureSTTSessionId.mockResolvedValue('old-session');
295
+ (rotateSTTSessionId as jest.Mock<any>).mockImplementation(async () => {
296
+ mockEnsureSTTSessionId.mockResolvedValue('new-session');
297
+ return 'new-session';
298
+ });
299
+ (global.fetch as jest.Mock<any>)
300
+ .mockResolvedValueOnce({
301
+ ok: false,
302
+ status: 500,
303
+ json: async () => ({error: {code: 610, message: 'temporary'}}),
304
+ })
305
+ .mockResolvedValueOnce({
306
+ ok: false,
307
+ status: 500,
308
+ json: async () => ({error: {code: 610, message: 'temporary'}}),
309
+ })
310
+ .mockResolvedValueOnce({
311
+ ok: false,
312
+ status: 500,
313
+ json: async () => ({error: {code: 610, message: 'temporary'}}),
314
+ })
315
+ .mockResolvedValueOnce({
316
+ ok: false,
317
+ status: 500,
318
+ json: async () => ({error: {code: 610, message: 'temporary'}}),
319
+ })
320
+ .mockResolvedValueOnce({
321
+ ok: false,
322
+ status: 409,
323
+ json: async () => ({error: {code: 631, message: 'session ended'}}),
324
+ })
325
+ .mockResolvedValueOnce({ok: true, status: 200, json: async () => ({})});
326
+ const {api, renderer} = await renderHook();
327
+ let response;
328
+ await act(async () => {
329
+ const pending = api.start(900000123, translationConfig);
330
+ await jest.runAllTimersAsync();
331
+ response = await pending;
332
+ });
333
+ expect(response).toMatchObject({success: true, sessionId: 'new-session'});
334
+ expect(global.fetch).toHaveBeenCalledTimes(6);
335
+ expect(rotateSTTSessionId).toHaveBeenCalledTimes(1);
336
+ renderer.unmount();
337
+ } finally {
338
+ jest.useRealTimers();
339
+ }
340
+ });
341
+
342
+ it('falls through to start when the optional preflight times out', async () => {
343
+ jest.useFakeTimers();
344
+ try {
345
+ mockEnsureSTTSessionId.mockResolvedValue('stored-session');
346
+ (wasSTTSessionIdFreshlyCreated as jest.Mock<any>).mockReturnValue(false);
347
+ (global.fetch as jest.Mock<any>)
348
+ .mockImplementationOnce(
349
+ (_url, options) =>
350
+ new Promise((_resolve, reject) => {
351
+ options.signal.addEventListener('abort', () =>
352
+ reject(new Error('aborted')),
353
+ );
354
+ }),
355
+ )
356
+ .mockResolvedValueOnce({ok: true, status: 200, json: async () => ({})});
357
+ const {api, renderer} = await renderHook();
358
+ let response;
359
+ await act(async () => {
360
+ const pending = api.start(900000123, translationConfig);
361
+ await jest.runAllTimersAsync();
362
+ response = await pending;
363
+ });
364
+ expect(response).toMatchObject({
365
+ success: true,
366
+ sessionId: 'stored-session',
367
+ });
368
+ expect(rotateSTTSessionId).not.toHaveBeenCalled();
369
+ expect(global.fetch).toHaveBeenCalledTimes(2);
370
+ expect(jest.getTimerCount()).toBe(0);
371
+ renderer.unmount();
372
+ } finally {
373
+ jest.useRealTimers();
374
+ }
375
+ });
376
+
377
+ it('returns a repeated 631 after one recovery instead of rotating forever', async () => {
378
+ mockEnsureSTTSessionId.mockResolvedValue('old-session');
379
+ (rotateSTTSessionId as jest.Mock<any>).mockResolvedValue('replacement');
380
+ (global.fetch as jest.Mock<any>).mockResolvedValue({
381
+ ok: false,
382
+ status: 409,
383
+ json: async () => ({error: {code: 631, message: 'session ended'}}),
384
+ });
385
+ const {api, renderer} = await renderHook();
386
+ let response;
387
+ await act(async () => {
388
+ response = await api.start(900000123, translationConfig);
389
+ });
390
+ expect(response).toMatchObject({success: false, error: {code: 631}});
391
+ expect(global.fetch).toHaveBeenCalledTimes(2);
392
+ expect(rotateSTTSessionId).toHaveBeenCalledTimes(1);
393
+ renderer.unmount();
394
+ });
129
395
  });
@@ -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);
@@ -6,13 +6,23 @@ import {PropsContext, useLocalUid} from '../../../agora-rn-uikit';
6
6
  import {logger, LogSource} from '../../logger/AppBuilderLogger';
7
7
  import getUniqueID from '../../utils/getUniqueID';
8
8
  import {buildSTTRequestBody, type STTMethod} from './sttRequestBody';
9
- import {ensureSTTSessionId} from './sttSessionId';
9
+ import {
10
+ ensureSTTSessionId,
11
+ rotateSTTSessionId,
12
+ wasSTTSessionIdFreshlyCreated,
13
+ markSTTSessionIdUsed,
14
+ } from './sttSessionId';
10
15
  import {TRANSCRIPT_JOURNEY} from './transcriptJourney';
11
16
 
12
17
  export interface STTAPIResponse {
13
18
  success: boolean;
14
19
  data?: any;
15
20
  httpStatus?: number;
21
+ // session_id that was sent on this request. Included so callers can
22
+ // emit the id in their own Datadog breadcrumbs without having to
23
+ // re-read the coordinator cache (which may have rotated between the
24
+ // request leaving and the caller reading).
25
+ sessionId?: string;
16
26
  error?: {
17
27
  message: string;
18
28
  code?: number;
@@ -32,6 +42,25 @@ const getStartRetryDelay = (botUid: number) =>
32
42
  const shouldRetryStart = (result: STTAPIResponse) =>
33
43
  result.httpStatus === 429 || result.error?.code === 610;
34
44
 
45
+ const shouldRotateSessionId = (result: STTAPIResponse) =>
46
+ result.error?.code === 631;
47
+
48
+ // Status values returned by /v1/stt-transcript that mean the session_id
49
+ // has moved past 'active' in the backend's ledger and should not be reused
50
+ // for a new startv7. See managed-service `storage/postgres/stt.go` status
51
+ // enum: STARTED/INPROGRESS are active; the remaining states below are
52
+ // stopped or processing artifacts and cannot resume live transcription.
53
+ const ENDED_STT_STATUSES = new Set<string>([
54
+ 'COMPLETED',
55
+ 'FAILED',
56
+ 'ARTIFACTS_PENDING',
57
+ 'PROCESSING',
58
+ ]);
59
+ // Bound the optional lookup to the latest 50 sessions. Older entries can be
60
+ // missed, so startv7's 631 response remains the authoritative fallback.
61
+ const PREFLIGHT_PAGE_LIMIT = 50;
62
+ const PREFLIGHT_TIMEOUT_MS = 3000;
63
+
35
64
  interface IuseSTTAPI {
36
65
  start: (
37
66
  botUid: number,
@@ -77,9 +106,20 @@ const useSTTAPI = (): IuseSTTAPI => {
77
106
  method: STTMethod,
78
107
  botUid: number,
79
108
  translationConfig?: LanguageTranslationConfig,
109
+ attempt?: number,
80
110
  ): Promise<STTAPIResponse> => {
81
111
  const requestId = getUniqueID();
82
112
  const startReqTs = Date.now();
113
+ const channelName = rtcPropsRef?.current?.channel || '';
114
+ let sessionId: string | undefined;
115
+ const requestContext = () => ({
116
+ channelName,
117
+ sessionId: sessionId ?? null,
118
+ botUid,
119
+ method,
120
+ attempt: attempt ?? null,
121
+ requestId,
122
+ });
83
123
 
84
124
  try {
85
125
  // Calculate which user this bot belongs to
@@ -99,6 +139,19 @@ const useSTTAPI = (): IuseSTTAPI => {
99
139
  resolveSessionId: ensureSTTSessionId,
100
140
  });
101
141
 
142
+ sessionId = requestBody.session_id;
143
+ if (method === 'startv7') {
144
+ logger.log(
145
+ LogSource.NetworkRest,
146
+ 'stt',
147
+ `${TRANSCRIPT_JOURNEY} STT start attempt`,
148
+ {
149
+ ...requestContext(),
150
+ isFreshlyCreated: wasSTTSessionIdFreshlyCreated(channelName),
151
+ },
152
+ );
153
+ }
154
+
102
155
  console.log(
103
156
  `${TRANSCRIPT_JOURNEY} [STT_BOT_SUBSCRIPTION] ${method.toUpperCase()} - Bot UID: ${botUid} will subscribe to User UID: ${ownerUid}`,
104
157
  {
@@ -108,6 +161,9 @@ const useSTTAPI = (): IuseSTTAPI => {
108
161
  translationConfig: translationConfig ?? null,
109
162
  },
110
163
  );
164
+ if (method === 'startv7' && sessionId) {
165
+ markSTTSessionIdUsed(channelName, sessionId);
166
+ }
111
167
  const response = await fetch(`${STT_API_URL}/${method}`, {
112
168
  method: 'POST',
113
169
  headers: {
@@ -152,7 +208,7 @@ const useSTTAPI = (): IuseSTTAPI => {
152
208
  {
153
209
  responseData: res ?? null,
154
210
  httpStatus,
155
- requestId,
211
+ ...requestContext(),
156
212
  startReqTs,
157
213
  endReqTs,
158
214
  latency,
@@ -161,6 +217,7 @@ const useSTTAPI = (): IuseSTTAPI => {
161
217
 
162
218
  return {
163
219
  success: false,
220
+ sessionId,
164
221
  httpStatus,
165
222
  error: {
166
223
  message,
@@ -177,7 +234,7 @@ const useSTTAPI = (): IuseSTTAPI => {
177
234
  {
178
235
  responseData: res ?? null,
179
236
  httpStatus,
180
- requestId,
237
+ ...requestContext(),
181
238
  startReqTs,
182
239
  endReqTs,
183
240
  latency,
@@ -186,6 +243,7 @@ const useSTTAPI = (): IuseSTTAPI => {
186
243
 
187
244
  return {
188
245
  success: true,
246
+ sessionId,
189
247
  httpStatus,
190
248
  data: res,
191
249
  };
@@ -198,7 +256,7 @@ const useSTTAPI = (): IuseSTTAPI => {
198
256
  `${TRANSCRIPT_JOURNEY} STT API Failure - Called ${method}`,
199
257
  error ?? null,
200
258
  {
201
- requestId,
259
+ ...requestContext(),
202
260
  startReqTs,
203
261
  endReqTs,
204
262
  latency,
@@ -207,6 +265,7 @@ const useSTTAPI = (): IuseSTTAPI => {
207
265
 
208
266
  return {
209
267
  success: false,
268
+ sessionId,
210
269
  error: {
211
270
  message: error?.message || 'Unknown error occurred',
212
271
  code: error?.code,
@@ -215,21 +274,204 @@ const useSTTAPI = (): IuseSTTAPI => {
215
274
  }
216
275
  };
217
276
 
277
+ const preflightSessionStatus = async (
278
+ passphrase: string,
279
+ channelName: string,
280
+ sessionId: string,
281
+ ): Promise<void> => {
282
+ if (!passphrase || !channelName || !sessionId) {
283
+ return;
284
+ }
285
+ const url = `${$config.BACKEND_ENDPOINT}/v1/stt-transcript`;
286
+ const body = JSON.stringify({
287
+ passphrase,
288
+ limit: PREFLIGHT_PAGE_LIMIT,
289
+ page: 1,
290
+ });
291
+ const controller = new AbortController();
292
+ const timeout = setTimeout(() => controller.abort(), PREFLIGHT_TIMEOUT_MS);
293
+ try {
294
+ let response: Response;
295
+ try {
296
+ response = await fetch(url, {
297
+ method: 'POST',
298
+ signal: controller.signal,
299
+ headers: {
300
+ 'Content-Type': 'application/json',
301
+ authorization: tokenRef?.current
302
+ ? `Bearer ${tokenRef?.current}`
303
+ : '',
304
+ },
305
+ body,
306
+ });
307
+ } catch (fetchError) {
308
+ logger.warn(
309
+ LogSource.NetworkRest,
310
+ 'stt',
311
+ `${TRANSCRIPT_JOURNEY} STT session pre-flight network error`,
312
+ fetchError ?? null,
313
+ );
314
+ return;
315
+ }
316
+ if (!response.ok) {
317
+ logger.warn(
318
+ LogSource.NetworkRest,
319
+ 'stt',
320
+ `${TRANSCRIPT_JOURNEY} STT session pre-flight non-OK response`,
321
+ {httpStatus: response.status},
322
+ );
323
+ return;
324
+ }
325
+ let data: {stts?: Array<{session_id?: string; status?: string}>};
326
+ try {
327
+ data = await response.json();
328
+ } catch (parseError) {
329
+ logger.warn(
330
+ LogSource.NetworkRest,
331
+ 'stt',
332
+ `${TRANSCRIPT_JOURNEY} STT session pre-flight body parse error`,
333
+ parseError ?? null,
334
+ );
335
+ return;
336
+ }
337
+ const match = Array.isArray(data?.stts)
338
+ ? data.stts.find(
339
+ entry =>
340
+ entry?.session_id === sessionId &&
341
+ typeof entry.status === 'string' &&
342
+ ENDED_STT_STATUSES.has(entry.status),
343
+ )
344
+ : undefined;
345
+ if (!match) {
346
+ return; // No evidence of staleness on this page; startv7 still validates.
347
+ }
348
+ logger.log(
349
+ LogSource.NetworkRest,
350
+ 'stt',
351
+ `${TRANSCRIPT_JOURNEY} STT session pre-flight detected stale id; rotating`,
352
+ {
353
+ channelName,
354
+ staleSessionId: sessionId,
355
+ beStatus: match.status,
356
+ },
357
+ );
358
+ try {
359
+ await rotateSTTSessionId(channelName, sessionId);
360
+ } catch (rotateError) {
361
+ logger.error(
362
+ LogSource.NetworkRest,
363
+ 'stt',
364
+ `${TRANSCRIPT_JOURNEY} STT session pre-flight rotation failed`,
365
+ rotateError as any,
366
+ );
367
+ }
368
+ } finally {
369
+ clearTimeout(timeout);
370
+ }
371
+ };
372
+
218
373
  const start = async (
219
374
  botUid: number,
220
375
  translationConfig: LanguageTranslationConfig,
221
376
  ): Promise<STTAPIResponse> => {
222
377
  const retryDelayMs = getStartRetryDelay(botUid);
378
+ const channelName = rtcPropsRef?.current?.channel || '';
379
+ const passphrase =
380
+ roomIdRef?.current?.host || roomIdRef?.current?.attendee || '';
223
381
  let result: STTAPIResponse;
382
+ let rotatedOnce = false;
383
+ let requestAttempt = 0;
384
+
385
+ // Pre-flight: if we are about to send a session_id that already existed
386
+ // in RTM channel metadata (not one we just minted), check with the
387
+ // backend whether it has moved past 'active' in the ledger. If so, we
388
+ // rotate here to avoid a guaranteed-to-fail startv7 round-trip.
389
+ if (channelName && passphrase) {
390
+ try {
391
+ const cachedSessionId = await ensureSTTSessionId(channelName);
392
+ const isFreshlyCreated = wasSTTSessionIdFreshlyCreated(channelName);
393
+ if (cachedSessionId && !isFreshlyCreated) {
394
+ await preflightSessionStatus(
395
+ passphrase,
396
+ channelName,
397
+ cachedSessionId,
398
+ );
399
+ }
400
+ } catch (preflightError) {
401
+ logger.warn(
402
+ LogSource.NetworkRest,
403
+ 'stt',
404
+ `${TRANSCRIPT_JOURNEY} STT session pre-flight skipped`,
405
+ preflightError ?? null,
406
+ );
407
+ }
408
+ }
224
409
 
225
410
  for (let attempt = 1; attempt <= STT_START_MAX_ATTEMPTS; attempt += 1) {
226
- result = await apiCall('startv7', botUid, translationConfig);
411
+ requestAttempt += 1;
412
+ result = await apiCall(
413
+ 'startv7',
414
+ botUid,
415
+ translationConfig,
416
+ requestAttempt,
417
+ );
418
+
419
+ if (result.success) {
420
+ return result;
421
+ }
227
422
 
228
423
  if (
229
- result.success ||
230
- !shouldRetryStart(result) ||
231
- attempt === STT_START_MAX_ATTEMPTS
424
+ shouldRotateSessionId(result) &&
425
+ !rotatedOnce &&
426
+ channelName &&
427
+ result.sessionId
232
428
  ) {
429
+ const staleSessionId = result.sessionId;
430
+ logger.log(
431
+ LogSource.NetworkRest,
432
+ 'stt',
433
+ `${TRANSCRIPT_JOURNEY} Rotating STT session ID after terminal-reuse error`,
434
+ {
435
+ attempt: requestAttempt,
436
+ channelName,
437
+ botUid,
438
+ httpStatus: result.httpStatus ?? null,
439
+ errorCode: result.error?.code ?? null,
440
+ staleSessionId: staleSessionId ?? null,
441
+ },
442
+ );
443
+ try {
444
+ const newSessionId = await rotateSTTSessionId(
445
+ channelName,
446
+ staleSessionId,
447
+ );
448
+ logger.log(
449
+ LogSource.NetworkRest,
450
+ 'stt',
451
+ `${TRANSCRIPT_JOURNEY} STT session ID rotated; retrying start`,
452
+ {
453
+ attempt: requestAttempt,
454
+ channelName,
455
+ botUid,
456
+ staleSessionId: staleSessionId ?? null,
457
+ newSessionId,
458
+ },
459
+ );
460
+ rotatedOnce = true;
461
+ attempt -= 1; // Always send a start after rotation, even at the retry limit.
462
+ continue;
463
+ } catch (rotateError) {
464
+ logger.error(
465
+ LogSource.NetworkRest,
466
+ 'stt',
467
+ `${TRANSCRIPT_JOURNEY} Failed to rotate STT session ID`,
468
+ rotateError as any,
469
+ );
470
+ return result;
471
+ }
472
+ }
473
+
474
+ if (!shouldRetryStart(result) || attempt === STT_START_MAX_ATTEMPTS) {
233
475
  return result;
234
476
  }
235
477
 
@@ -238,9 +480,11 @@ const useSTTAPI = (): IuseSTTAPI => {
238
480
  'stt',
239
481
  `${TRANSCRIPT_JOURNEY} Retrying STT start after transient failure`,
240
482
  {
241
- attempt,
483
+ attempt: requestAttempt,
242
484
  maxAttempts: STT_START_MAX_ATTEMPTS,
243
485
  retryDelayMs,
486
+ channelName,
487
+ sessionId: result.sessionId ?? null,
244
488
  botUid,
245
489
  httpStatus: result.httpStatus ?? null,
246
490
  errorCode: result.error?.code ?? null,