Skip to content

Commit a2679ca

Browse files
fix(ui): close superseded Talk allocations
Co-authored-by: NianJiuZst <[email protected]>
1 parent 12297b7 commit a2679ca

2 files changed

Lines changed: 124 additions & 9 deletions

File tree

‎ui/src/pages/chat/realtime-talk.test.ts‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,14 @@ function transportContext(transport: object | undefined): RealtimeTalkTransportC
4747
return (transport as { ctx: RealtimeTalkTransportContext }).ctx;
4848
}
4949

50+
function createDeferred<T>() {
51+
let resolve!: (value: T) => void;
52+
const promise = new Promise<T>((resolvePromise) => {
53+
resolve = resolvePromise;
54+
});
55+
return { promise, resolve };
56+
}
57+
5058
describe("RealtimeTalkSession", () => {
5159
beforeEach(() => {
5260
googleStart.mockClear();
@@ -209,6 +217,97 @@ describe("RealtimeTalkSession", () => {
209217
expect(webRtcInstances).toHaveLength(0);
210218
});
211219

220+
it("closes a Gateway relay allocated after the session stops", async () => {
221+
const create = createDeferred<{
222+
provider: string;
223+
transport: "gateway-relay";
224+
relaySessionId: string;
225+
audio: {
226+
inputEncoding: "pcm16";
227+
inputSampleRateHz: number;
228+
outputEncoding: "pcm16";
229+
outputSampleRateHz: number;
230+
};
231+
}>();
232+
const request = vi.fn((method: string) => {
233+
if (method === "talk.client.create") {
234+
return create.promise;
235+
}
236+
if (method === "talk.session.close") {
237+
return Promise.resolve({ ok: true });
238+
}
239+
throw new Error(`Unexpected request: ${method}`);
240+
});
241+
const session = new RealtimeTalkSession({ request } as never, "main");
242+
243+
const starting = session.start();
244+
await vi.waitFor(() =>
245+
expect(request).toHaveBeenCalledWith("talk.client.create", expect.anything()),
246+
);
247+
session.stop();
248+
create.resolve({
249+
provider: "openai",
250+
transport: "gateway-relay",
251+
relaySessionId: "relay-stale",
252+
audio: {
253+
inputEncoding: "pcm16",
254+
inputSampleRateHz: 24_000,
255+
outputEncoding: "pcm16",
256+
outputSampleRateHz: 24_000,
257+
},
258+
});
259+
await starting;
260+
261+
expect(request).toHaveBeenCalledWith("talk.session.close", { sessionId: "relay-stale" });
262+
expect(relayInstances).toHaveLength(0);
263+
});
264+
265+
it("closes a superseded client-owned allocation without replacing the active call", async () => {
266+
const creates: Array<ReturnType<typeof createDeferred<unknown>>> = [];
267+
const request = vi.fn((method: string) => {
268+
if (method === "talk.client.create") {
269+
const create = createDeferred<unknown>();
270+
creates.push(create);
271+
return create.promise;
272+
}
273+
if (method === "talk.client.close") {
274+
return Promise.resolve({ ok: true });
275+
}
276+
throw new Error(`Unexpected request: ${method}`);
277+
});
278+
const session = new RealtimeTalkSession({ request } as never, "main");
279+
280+
const firstStart = session.start();
281+
await vi.waitFor(() => expect(creates).toHaveLength(1));
282+
session.stop();
283+
const secondStart = session.start();
284+
await vi.waitFor(() => expect(creates).toHaveLength(2));
285+
creates[1]!.resolve({
286+
provider: "openai",
287+
transport: "webrtc",
288+
voiceSessionId: "voice-current",
289+
clientSecret: "secret",
290+
});
291+
await secondStart;
292+
creates[0]!.resolve({
293+
provider: "openai",
294+
transport: "webrtc",
295+
voiceSessionId: "voice-stale",
296+
clientSecret: "secret",
297+
});
298+
await firstStart;
299+
300+
await vi.waitFor(() =>
301+
expect(request).toHaveBeenCalledWith("talk.client.close", {
302+
sessionKey: "main",
303+
voiceSessionId: "voice-stale",
304+
}),
305+
);
306+
expect(webRtcInstances).toHaveLength(1);
307+
expect(webRtcStart).toHaveBeenCalledTimes(1);
308+
session.stop();
309+
});
310+
212311
it("falls back to talk.session.create when gateway-relay is rejected by talk.client.create", async () => {
213312
const request = vi
214313
.fn()

‎ui/src/pages/chat/realtime-talk.ts‎

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ type RealtimeTalkLaunchTransport = NonNullable<RealtimeTalkLaunchOptions["transp
6161
type DetachedVoiceSession = {
6262
voiceSessionId: string;
6363
serverOwned: boolean;
64-
generation: number;
64+
generation?: number;
6565
transcriptWrites: Promise<void>;
6666
};
6767

@@ -137,6 +137,7 @@ function compactLaunchParams(
137137
export class RealtimeTalkSession {
138138
private transport: RealtimeTalkTransport | null = null;
139139
private closed = false;
140+
private lifecycleGeneration = 0;
140141
private videoEnabled = false;
141142
private videoOperation = 0;
142143
private voiceSessionId: string | undefined;
@@ -155,10 +156,11 @@ export class RealtimeTalkSession {
155156
) {}
156157

157158
async start(): Promise<void> {
159+
const lifecycleGeneration = ++this.lifecycleGeneration;
158160
this.closed = false;
159161
this.callbacks.onStatus?.("connecting");
160162
const providerVideoCapable = await this.resolveVideoCapability();
161-
if (this.closed) {
163+
if (this.closed || lifecycleGeneration !== this.lifecycleGeneration) {
162164
return;
163165
}
164166
// Declaring voice-transcript arms the server-side spoken-confirmation gate;
@@ -182,16 +184,13 @@ export class RealtimeTalkSession {
182184
if (!voiceSessionId) {
183185
throw new Error("Realtime Talk session did not return a voice session id");
184186
}
187+
if (this.closed || lifecycleGeneration !== this.lifecycleGeneration) {
188+
this.closeUnadoptedVoiceSession(voiceSessionId, transport);
189+
return;
190+
}
185191
this.voiceSessionId = voiceSessionId;
186192
this.acceptingTranscripts = true;
187193
this.serverOwnedVoiceSession = transport === "gateway-relay";
188-
if (this.closed) {
189-
const detached = this.detachVoiceSession();
190-
if (detached) {
191-
this.closeLogicalVoiceSession(detached);
192-
}
193-
return;
194-
}
195194
this.transportGeneration += 1;
196195
const callbacks =
197196
transport === "gateway-relay"
@@ -300,6 +299,7 @@ export class RealtimeTalkSession {
300299
}
301300

302301
stop(): void {
302+
this.lifecycleGeneration += 1;
303303
this.closed = true;
304304
this.videoOperation += 1;
305305
this.videoEnabled = false;
@@ -313,6 +313,22 @@ export class RealtimeTalkSession {
313313
}
314314
}
315315

316+
private closeUnadoptedVoiceSession(voiceSessionId: string, transport: string): void {
317+
// A stopped or superseded create still owns the allocation returned to it.
318+
// Close at the provider boundary without installing a stale transport.
319+
if (transport === "gateway-relay") {
320+
void this.client
321+
.request("talk.session.close", { sessionId: voiceSessionId })
322+
.catch(() => undefined);
323+
return;
324+
}
325+
this.closeLogicalVoiceSession({
326+
voiceSessionId,
327+
serverOwned: false,
328+
transcriptWrites: Promise.resolve(),
329+
});
330+
}
331+
316332
private clientOwnedTranscriptCallbacks(
317333
owningVoiceSessionId: string,
318334
owningGeneration: number,

0 commit comments

Comments
 (0)