Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

feat(live): opt-in GPT-Live standby over WebRTC (#6913)

vincent2c4d7c9bfede
diff --git a/docs/verification/live-calls.md b/docs/verification/live-calls.md
index a766b2df45..b491d26f9e 100644
--- a/docs/verification/live-calls.md
+++ b/docs/verification/live-calls.md
@@ -210,6 +210,19 @@ the delegate result, End and Fish's own end), `server/routes/live.test.ts`
`src/components/keys/KeysPage.dom.test.ts`. No call has been placed against
Fish Audio's live service.
+## GPT-Live standby
+
+The Live settings dialog can opt direct OpenAI GPT-Live WebRTC calls into standby. It sends `session.wake_policy.type: "speech"` and `session.idle_timeout_s` (whole seconds, 5–60; default 15), as [OpenAI documents](https://developers.openai.com/api/docs/guides/live-conversations#configure-standby). Standby is off by default and does not apply to Azure or custom endpoints. The microphone track and WebRTC session remain connected; `idleMinutes` still controls the app's own idle hang-up.
+
+```sh
+OMB_VITEST_WORKERS=3 pnpm exec vitest run server/live-call.test.ts server/live-settings.test.ts server/routes/live.test.ts server/config.test.ts server/live-call-controller.test.ts src/components/LiveCallBar.render.test.ts
+OMB_VITEST_WORKERS=3 pnpm exec vitest run server/live-call.e2e.test.ts
+pnpm typecheck
+pnpm i18n:check
+```
+
+The e2e uses the fake provider to check the request payload, persisted settings, `session.paused`/`session.resumed`, the call remaining live while a bot reply is appended during standby, and reuse of the same provider session afterward. OpenAI documents that the same session retains conversation history on resume; this fixture does not contact OpenAI to verify that behavior, billing or microphone audio.
+
## User path
Start a Live call from the call button's menu, say something the bot must act
diff --git a/packages/phone-protocol/src/live-call-wire.ts b/packages/phone-protocol/src/live-call-wire.ts
index 90367e23cd..f8ccb65667 100644
--- a/packages/phone-protocol/src/live-call-wire.ts
+++ b/packages/phone-protocol/src/live-call-wire.ts
@@ -88,6 +88,10 @@ export interface LiveSettings {
geminiVoice?: string;
readTypedReplies: boolean;
idleMinutes: number;
+ /** Opts direct OpenAI GPT-Live WebRTC calls into speech-wake standby; absent or false keeps active inference. */
+ standby?: boolean;
+ /** Whole seconds before standby, from 5 to 60; defaults to 15 when enabled. */
+ standbyIdleSeconds?: number;
}
/** The single-use token Fish Audio returns for one agent session (Fish API v1 `LiveKitSessionToken`), passed verbatim to
diff --git a/server/config.test.ts b/server/config.test.ts
index 32aee1cb98..4dd3ed312f 100644
--- a/server/config.test.ts
+++ b/server/config.test.ts
@@ -2227,6 +2227,12 @@ describe("live settings", () => {
expect(() => parseConfigPatch({ live: { idleMinutes: 2.5 } })).toThrow();
expect(parseConfigPatch({ live: { idleMinutes: 60, readTypedReplies: false } })).toMatchObject({ live: { idleMinutes: 60, readTypedReplies: false } });
});
+ it("accepts the OpenAI standby idle timeout only from 5 to 60 whole seconds", () => {
+ expect(() => parseConfigPatch({ live: { standbyIdleSeconds: 4 } })).toThrow();
+ expect(() => parseConfigPatch({ live: { standbyIdleSeconds: 61 } })).toThrow();
+ expect(() => parseConfigPatch({ live: { standbyIdleSeconds: 15.5 } })).toThrow();
+ expect(parseConfigPatch({ live: { standby: true, standbyIdleSeconds: 60 } })).toMatchObject({ live: { standby: true, standbyIdleSeconds: 60 } });
+ });
it("does not reload providers for live changes", () => {
expect(reloaded({ live: { idleMinutes: 3 } })).toEqual([]);
});
diff --git a/server/live-call-controller.test.ts b/server/live-call-controller.test.ts
index c1c4c0262d..5b3f1d6bef 100644
--- a/server/live-call-controller.test.ts
+++ b/server/live-call-controller.test.ts
@@ -491,6 +491,18 @@ describe("LiveCallController lifecycle", () => {
expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "idle" });
});
+ it("keeps a standby call live while paused, then applies the app idle hang-up", async () => {
+ const t = setup();
+ t.settings.idleMinutes = 1;
+ const { call } = await t.start();
+ t.socket().receive({ type: "session.paused" });
+ expect(t.controller.current()).toMatchObject({ callId: call.callId, status: "live" });
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(t.socket().sent.at(-1)).toMatchObject({ type: "session.close" });
+ t.socket().receive({ type: "session.closed", reason: "close_requested" });
+ expect(t.frames.at(-1)).toMatchObject({ callId: call.callId, status: "ended", endReason: "idle" });
+ });
+
it("does not hang up while the bot works, but does while an approval waits", async () => {
const t = setup();
await t.start();
diff --git a/server/live-call-controller.ts b/server/live-call-controller.ts
index 520a06ebae..cbc8f086de 100644
--- a/server/live-call-controller.ts
+++ b/server/live-call-controller.ts
@@ -72,7 +72,7 @@ export interface LiveCallDeps {
activity(botId: string, threadId: string): LiveActivity;
broadcast(frame: { kind: "live.call"; botId: string; threadId: string; call: LiveCallState | null }): void;
/** `endpoint` null, or a `setupProblem`, refuses the call with that message (409). */
- settings(): { key: string; endpoint: LiveEndpoint | null; setupProblem?: string | null; provider?: LiveProvider; voice: string; geminiVoice?: string; readTypedReplies: boolean; idleMinutes: number };
+ settings(): { key: string; endpoint: LiveEndpoint | null; setupProblem?: string | null; provider?: LiveProvider; voice: string; geminiVoice?: string; readTypedReplies: boolean; idleMinutes: number; standby?: boolean; standbyIdleSeconds?: number };
/** The called bot's own Live call voice, used over the app's when it is the call provider's. */
botVoice?(botId: string): string | undefined;
/** Why this caller may not hold a call through Azure OpenAI; null when they may. Required, so no wiring can leave it out. */
@@ -82,7 +82,7 @@ export interface LiveCallDeps {
geminiRefusal(auth: RequestAuth): string | null;
elevenlabsRefusal(auth: RequestAuth): string | null;
/** `sdp` is "" on relayed calls, which answer with `fish`, `gemini` or `elevenlabs` instead of an SDP answer. */
- createSession(input: { key: string; endpoint: LiveEndpoint; sdp: string; botId: string; threadId: string; voice: string }): Promise<LiveSessionAnswer>;
+ createSession(input: { key: string; endpoint: LiveEndpoint; sdp: string; botId: string; threadId: string; voice: string; standby?: boolean; standbyIdleSeconds?: number }): Promise<LiveSessionAnswer>;
openSocket(url: string, key: string, endpoint: LiveEndpoint): LiveSocket;
attachUrl(sessionId: string, endpoint: LiveEndpoint): string;
speakable(text: string): string[];
@@ -222,7 +222,8 @@ export class LiveCallController {
this.call = call;
let session: LiveSessionAnswer;
try {
- session = await this.deps.createSession({ key, endpoint, sdp: relayed ? "" : input.sdp ?? "", botId: input.botId, threadId: input.threadId, voice });
+ session = await this.deps.createSession({ key, endpoint, sdp: relayed ? "" : input.sdp ?? "", botId: input.botId, threadId: input.threadId, voice,
+ ...(endpoint.provider === "openai" && settings.standby ? { standby: true, standbyIdleSeconds: settings.standbyIdleSeconds } : {}) });
} catch (error) {
if (this.call === call) this.call = null;
this.deps.log(`[live] call failed bot=${input.botId} client=${input.client} status=${error instanceof LiveSessionError ? error.status : "error"}`);
diff --git a/server/live-call.e2e.test.ts b/server/live-call.e2e.test.ts
index 2a400ac2f1..07be3d705c 100644
--- a/server/live-call.e2e.test.ts
+++ b/server/live-call.e2e.test.ts
@@ -195,6 +195,65 @@ posixOnly("Live call e2e", () => {
}
}, 40_000);
+ it("keeps the opted-in OpenAI session through standby while the bot replies", async () => {
+ rmSync(steerGate, { force: true });
+ const bot = await createBot("steer", "claude-fake");
+ const sse = await openSse(`${base}/api/events`);
+ let callId = "";
+ try {
+ const saved = await fetch(`${base}/api/live/settings`, {
+ method: "PATCH", headers: { "content-type": "application/json" },
+ body: JSON.stringify({ standby: true, standbyIdleSeconds: 10 }),
+ });
+ expect(saved.status).toBe(200);
+ expect(await saved.json()).toMatchObject({ live: { standby: true, standbyIdleSeconds: 10 } });
+ expect(await (await fetch(`${base}/api/config`)).json()).toMatchObject({ live: { standby: true, standbyIdleSeconds: 10 } });
+
+ const before = live.sessions.length;
+ const { call, session } = await startCall(bot.id);
+ callId = call.callId;
+ expect(session.body.session).toMatchObject({ wake_policy: { type: "speech" }, idle_timeout_s: 10 });
+ expect(live.sessions).toHaveLength(before + 1);
+ await live.waitForAttach(session.id);
+ live.emit(session.id, { type: "session.input_transcript.delta", delta: "check the standby report", start_ms: 100, end_ms: 900 });
+ live.emit(session.id, { type: "session.delegation.created", offset_ms: 950, delegation: { id: "del_standby", target: "client", type: "delegation" } });
+ const asked = await sse.until((frame) => frame.kind === "message" && frame.threadId === bot.threadId && frame.message?.role === "user" && frame.message?.via === "call");
+ expect(asked.message.text).toBe("check the standby report");
+ await expect.poll(() => isBusy(bot.id), { timeout: 20_000 }).toBe(true);
+
+ live.emit(session.id, { type: "session.paused" });
+ expect(session.paused).toBe(true);
+ expect(session.closed).toBe(false);
+ expect(await (await fetch(`${base}/api/live/call`)).json()).toMatchObject({ call: { callId, status: "live" } });
+ expect(live.sessions).toHaveLength(before + 1);
+
+ writeFileSync(steerGate, "finish");
+ const spoken = await live.waitForCommand(session.id, (command) => command.type === "session.commentary.append" && command.delegation_id === "del_standby", 20_000);
+ expect(spoken.content).toContain("check the standby report");
+ expect(await (await fetch(`${base}/api/live/call`)).json()).toMatchObject({ call: { callId, status: "live" } });
+ expect(session.closed).toBe(false);
+ expect(live.sessions).toHaveLength(before + 1);
+
+ live.emit(session.id, { type: "session.resumed" });
+ expect(session.paused).toBe(false);
+ live.emit(session.id, { type: "session.input_transcript.delta", delta: "continue after standby", start_ms: 2_000, end_ms: 2_800 });
+ live.emit(session.id, { type: "session.delegation.created", offset_ms: 2_850, delegation: { id: "del_resumed", target: "client", type: "delegation" } });
+ await sse.until((frame) => frame.kind === "message" && frame.threadId === bot.threadId && frame.message?.role === "user" && frame.message?.text === "continue after standby");
+ await live.waitForCommand(session.id, (command) => command.type === "session.commentary.append" && command.delegation_id === "del_resumed", 20_000);
+ expect(await (await fetch(`${base}/api/live/call`)).json()).toMatchObject({ call: { callId, status: "live" } });
+ expect(live.sessions).toHaveLength(before + 1);
+ } finally {
+ writeFileSync(steerGate, "finish");
+ if (callId) await post("/api/live/call/end", { callId });
+ await post(`/api/bots/${bot.id}/interrupt`, {});
+ await expect.poll(() => isBusy(bot.id), { timeout: 20_000 }).toBe(false);
+ await fetch(`${base}/api/live/settings`, {
+ method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify({ standby: false }),
+ });
+ sse.close();
+ }
+ }, 60_000);
+
it("answers 409 with the running call to a second client", async () => {
const bot = await createBot();
const { call, session } = await startCall(bot.id, "web");
diff --git a/server/live-call.test.ts b/server/live-call.test.ts
index e01043f2db..621bd0b5ce 100644
--- a/server/live-call.test.ts
+++ b/server/live-call.test.ts
@@ -53,6 +53,8 @@ describe("createLiveSession", () => {
const body = JSON.parse(String(init?.body));
expect(body.transport).toEqual({ type: "webrtc", sdp: OFFER });
expect(body.session.model).toBe(LIVE_MODEL);
+ expect(body.session).not.toHaveProperty("wake_policy");
+ expect(body.session).not.toHaveProperty("idle_timeout_s");
expect(body.session.delegation).toEqual({ type: "client" });
expect(body.session.audio).toEqual({ output: { voice: "cedar" } });
expect(body.session.instructions).toContain("You are Ada, Tech Lead");
@@ -64,6 +66,20 @@ describe("createLiveSession", () => {
expect(String(init?.body)).not.toContain("sk-live-secret");
});
+ it("opts direct OpenAI WebRTC sessions into speech standby with a bounded idle timeout", async () => {
+ const fetchImpl = okFetch();
+ await createLiveSession({ key: "k", sdp: OFFER, bot: BOT, history: [], cloudHome: false, standby: true, standbyIdleSeconds: 12, fetchImpl });
+ const body = JSON.parse(String(fetchImpl.mock.calls[0][1]?.body));
+ expect(body.transport).toEqual({ type: "webrtc", sdp: OFFER });
+ expect(body.session).toMatchObject({ wake_policy: { type: "speech" }, idle_timeout_s: 12 });
+
+ const azure = okFetch();
+ await createLiveSession({ key: "k", endpoint: azureLiveEndpoint("https://my-res.openai.azure.com", "live-prod")!, sdp: OFFER, bot: BOT, history: [], cloudHome: false, standby: true, standbyIdleSeconds: 12, fetchImpl: azure });
+ const azureSession = JSON.parse(String(azure.mock.calls[0][1]?.body)).session;
+ expect(azureSession).not.toHaveProperty("wake_policy");
+ expect(azureSession).not.toHaveProperty("idle_timeout_s");
+ });
+
it("tells the voice where it runs: the user's own computer, or their My Cloud", async () => {
const fetchImpl = okFetch();
await createLiveSession({ key: "k", sdp: OFFER, bot: BOT, history: [], cloudHome: true, fetchImpl });
diff --git a/server/live-call.ts b/server/live-call.ts
index f00f582834..573012dbfe 100644
--- a/server/live-call.ts
+++ b/server/live-call.ts
@@ -2,6 +2,7 @@
import { CLOUD_HOME_PLACE } from "./system-prompt.ts";
import type { LiveProvider } from "../shared/wire.ts";
import type { Message } from "./store.ts";
+import { LIVE_STANDBY_IDLE_SECONDS_DEFAULT } from "../shared/live-call.ts";
export const LIVE_MODEL = "gpt-live-1";
const OPENAI_BASE = "https://api.openai.com";
@@ -259,6 +260,8 @@ export interface CreateLiveSessionInput {
cloudHome: boolean;
voice?: string;
endpoint?: LiveEndpoint;
+ standby?: boolean;
+ standbyIdleSeconds?: number;
fetchImpl?: typeof fetch;
timeoutMs?: number;
}
@@ -279,6 +282,10 @@ export async function createLiveSession(input: CreateLiveSessionInput): Promise<
instructions: liveInstructions(input.bot, { cloudHome: input.cloudHome }),
delegation: { type: "client" },
audio: { output: { voice: liveVoice(input.voice) } },
+ ...(endpoint.provider === "openai" && input.standby ? {
+ wake_policy: { type: "speech" },
+ idle_timeout_s: input.standbyIdleSeconds ?? LIVE_STANDBY_IDLE_SECONDS_DEFAULT,
+ } : {}),
// Azure's GPT-Live refuses `session.client` ("Unknown parameter"): see LIVE_DATA_CHANNEL for who may hold such a call.
...(endpoint.provider === "azure" ? {} : { client: { data_channel: LIVE_DATA_CHANNEL } }),
...(initialInput.length ? { input: initialInput } : {}),
diff --git a/server/live-config.ts b/server/live-config.ts
index 6a1a448a59..c7c9d18fa5 100644
--- a/server/live-config.ts
+++ b/server/live-config.ts
@@ -4,8 +4,10 @@ import { z } from "zod";
export const LIVE_KEY_NEEDS_ENDPOINT = "Save the Azure endpoint first: a Live key works only with the endpoint it was saved for.";
export const LIVE_KEY_NEEDS_CUSTOM_ENDPOINT = "Save the custom endpoint first: a Live key works only with the endpoint it was saved for.";
const NOWHERE = "nowhere";
+export const LIVE_STANDBY_IDLE_SECONDS_MIN = 5;
+export const LIVE_STANDBY_IDLE_SECONDS_MAX = 60;
-/** Live calls: `key` is a key for Live calls only; with `provider` "openai" (the default) a call without one uses `openai.key`, with "azure" it is the Azure resource's key and is required, with "fish", "gemini" or "elevenlabs" it is not used: Fish Audio calls use the Fish Audio key (`tts.fishKey`), Gemini calls the Gemini key (`tts.geminiKey`) and ElevenLabs calls the ElevenLabs key (`tts.key`). `keyFor` says where `key` may go (`liveKeyTarget`): the server sets it when the key is saved and never takes it from a request; absent, the key is from before Azure was offered, so OpenAI's. `azureEndpoint` is the resource URL and `azureDeployment` the gpt-live-1 deployment name; with "custom", `key` is the key of the OpenAI-compatible server at `customEndpoint` and is required, and `customModel` its model. `fishAgentId` is the Fish Audio agent a "fish" call starts, which the harness sets up on the account of the key whose `fishKeyPrint` is `fishAgentFor`; without `fishAgentFor` (an operator's OMB_FISH_LIVE_AGENT_ID) it is used with any key, and `fishAgentLanguage` is the language the harness last set it to speak (absent: English, as agents were first set up). `elevenlabsAgentId` and `elevenlabsAgentFor` are the same for an "elevenlabs" call's ElevenLabs agent. `voice` is a GPT-Live voice, `geminiVoice` a Gemini Live voice. */
+/** Live calls: `key` is a key for Live calls only; with `provider` "openai" (the default) a call without one uses `openai.key`, with "azure" it is the Azure resource's key and is required, with "fish", "gemini" or "elevenlabs" it is not used: Fish Audio calls use the Fish Audio key (`tts.fishKey`), Gemini calls the Gemini key (`tts.geminiKey`) and ElevenLabs calls the ElevenLabs key (`tts.key`). `keyFor` says where `key` may go (`liveKeyTarget`): the server sets it when the key is saved and never takes it from a request; absent, the key is from before Azure was offered, so OpenAI's. `azureEndpoint` is the resource URL and `azureDeployment` the gpt-live-1 deployment name; with "custom", `key` is the key of the OpenAI-compatible server at `customEndpoint` and is required, and `customModel` its model. `fishAgentId` is the Fish Audio agent a "fish" call starts, which the harness sets up on the account of the key whose `fishKeyPrint` is `fishAgentFor`; without `fishAgentFor` (an operator's OMB_FISH_LIVE_AGENT_ID) it is used with any key, and `fishAgentLanguage` is the language the harness last set it to speak (absent: English, as agents were first set up). `elevenlabsAgentId` and `elevenlabsAgentFor` are the same for an "elevenlabs" call's ElevenLabs agent. `voice` is a GPT-Live voice, `geminiVoice` a Gemini Live voice, `standby` opts direct OpenAI GPT-Live WebRTC calls into speech wake, and `standbyIdleSeconds` sets the 5–60 second pause timeout. */
export const liveConfigSchema = z.object({
key: z.string().optional(),
keyFor: z.string().max(300).optional(),
@@ -23,6 +25,8 @@ export const liveConfigSchema = z.object({
geminiVoice: z.string().trim().max(40).regex(/^[A-Za-z]*$/, "a Gemini Live voice is a built-in voice name").optional(),
readTypedReplies: z.boolean().optional(),
idleMinutes: z.number().int().min(1).max(60).optional(),
+ standby: z.boolean().optional(),
+ standbyIdleSeconds: z.number().int().min(LIVE_STANDBY_IDLE_SECONDS_MIN).max(LIVE_STANDBY_IDLE_SECONDS_MAX).optional(),
});
export interface LiveConfig {
@@ -42,6 +46,8 @@ export interface LiveConfig {
geminiVoice?: string;
readTypedReplies?: boolean;
idleMinutes?: number;
+ standby?: boolean;
+ standbyIdleSeconds?: number;
}
/** Where a key saved now may go: "openai", "azure:<host>" or "custom:<host>"; null while Azure or a custom endpoint is chosen
diff --git a/server/live-session-wiring.ts b/server/live-session-wiring.ts
index 936498d8aa..3b2e8aa097 100644
--- a/server/live-session-wiring.ts
+++ b/server/live-session-wiring.ts
@@ -101,7 +101,7 @@ export function liveSessionWiring(input: LiveSessionWiringInput): {
fishRefusal: (auth) => fishLiveCallRefusal(auth, { othersOnLoopback: input.othersOnLoopback() }),
geminiRefusal: (auth) => geminiLiveCallRefusal(auth, { othersOnLoopback: input.othersOnLoopback() }),
elevenlabsRefusal: (auth) => elevenLabsLiveCallRefusal(auth, { othersOnLoopback: input.othersOnLoopback() }),
- createSession: async ({ key, endpoint, sdp, botId, threadId, voice }) => {
+ createSession: async ({ key, endpoint, sdp, botId, threadId, voice, standby, standbyIdleSeconds }) => {
if (endpoint.provider === "gemini") {
const session = await createGeminiLiveSession({ key, endpoint, voice, bot: input.bot(botId), history: input.history(threadId), cloudHome: input.cloudHome, fetchImpl });
// Gemini has nothing to end: the session ends when the client closes it, and the token is single use.
@@ -115,7 +115,7 @@ export function liveSessionWiring(input: LiveSessionWiringInput): {
return { sessionId: session.session_id, elevenlabs: { type: "elevenlabs", session, relayToken: token } };
}
if (endpoint.provider !== "fish") {
- return createLiveSession({ key, endpoint, sdp, voice, bot: input.bot(botId), history: input.history(threadId), cloudHome: input.cloudHome });
+ return createLiveSession({ key, endpoint, sdp, voice, standby, standbyIdleSeconds, bot: input.bot(botId), history: input.history(threadId), cloudHome: input.cloudHome });
}
const { agent, token: session } = await startFish(key, endpoint, botId, threadId);
const { token } = relays.open(session.session_id, () => endFishLiveSession(session.session_id, key, agent, fetchImpl));
diff --git a/server/live-settings.test.ts b/server/live-settings.test.ts
index 32b3a658e5..44953118f8 100644
--- a/server/live-settings.test.ts
+++ b/server/live-settings.test.ts
@@ -12,6 +12,13 @@ describe("live settings", () => {
expect(liveSettingsFor({} as AppConfig)).toEqual({ configured: false, voice: "", readTypedReplies: true, idleMinutes: 5 });
});
+ it("defaults the standby timeout only when standby is opted into", () => {
+ expect(liveSettingsFor({} as AppConfig)).not.toHaveProperty("standby");
+ expect(liveSettingsFor({ live: { standby: true } } as AppConfig)).toMatchObject({ standby: true, standbyIdleSeconds: 15 });
+ expect(liveSettingsFor({ live: { standby: true, standbyIdleSeconds: 60 } } as AppConfig)).toMatchObject({ standby: true, standbyIdleSeconds: 60 });
+ expect(liveSettingsFor({ live: { standbyIdleSeconds: 30 } } as AppConfig)).toMatchObject({ standbyIdleSeconds: 30 });
+ });
+
it("reports saved values and where the key comes from, never the key", () => {
const settings = liveSettingsFor({ live: { key: "sk-test", voice: "sol", readTypedReplies: false, idleMinutes: 12 } } as AppConfig);
expect(settings).toEqual({ configured: true, keySource: "live", voice: "sol", readTypedReplies: false, idleMinutes: 12 });
diff --git a/server/live-settings.ts b/server/live-settings.ts
index 6224d4d612..66896ef5c9 100644
--- a/server/live-settings.ts
+++ b/server/live-settings.ts
@@ -1,7 +1,8 @@
import type { LiveKeySource, LiveSettings } from "../shared/wire.ts";
import { saveConfig, syncCredentialEnv, type AppConfig } from "./config.ts";
import { azureLiveEndpoint, customLiveEndpoint, LIVE_NEEDS_AZURE, LIVE_NEEDS_CUSTOM, LIVE_NEEDS_ELEVENLABS, LIVE_NEEDS_FISH, LIVE_NEEDS_GEMINI, LIVE_NEEDS_KEY, openAiLiveEndpoint, type LiveEndpoint } from "./live-call.ts";
-import { liveSavePatch, usableLiveKey, type LiveConfig as LiveConfigSection } from "./live-config.ts";
+import { LIVE_STANDBY_IDLE_SECONDS_MAX, LIVE_STANDBY_IDLE_SECONDS_MIN, liveSavePatch, usableLiveKey, type LiveConfig as LiveConfigSection } from "./live-config.ts";
+import { LIVE_STANDBY_IDLE_SECONDS_DEFAULT } from "../shared/live-call.ts";
import { fishLiveEndpoint, usableFishAgent } from "./live-fish.ts";
import { voiceCredential } from "./included-services.ts";
import { elevenLabsLiveEndpoint, usableElevenLabsAgent } from "./live-elevenlabs.ts";
@@ -87,5 +88,10 @@ export function liveSettingsFor(cfg: AppConfig): LiveSettings {
...(cfg.live?.geminiVoice ? { geminiVoice: cfg.live.geminiVoice } : {}),
readTypedReplies: cfg.live?.readTypedReplies ?? true,
idleMinutes: Number.isInteger(minutes) && minutes! >= 1 && minutes! <= 60 ? minutes! : LIVE_IDLE_MINUTES_DEFAULT,
+ ...(cfg.live?.standby === true ? { standby: true } : {}),
+ ...(cfg.live?.standby === true || cfg.live?.standbyIdleSeconds !== undefined ? {
+ standbyIdleSeconds: Number.isInteger(cfg.live.standbyIdleSeconds) && cfg.live.standbyIdleSeconds! >= LIVE_STANDBY_IDLE_SECONDS_MIN && cfg.live.standbyIdleSeconds! <= LIVE_STANDBY_IDLE_SECONDS_MAX
+ ? cfg.live.standbyIdleSeconds! : LIVE_STANDBY_IDLE_SECONDS_DEFAULT,
+ } : {}),
};
}
diff --git a/server/routes/live.test.ts b/server/routes/live.test.ts
index 1d1f948b6b..0b65b5ef5c 100644
--- a/server/routes/live.test.ts
+++ b/server/routes/live.test.ts
@@ -149,7 +149,9 @@ describe("live routes", () => {
expect((await request(d, "PATCH", "/api/live/settings", { geminiVoice: "marin" })).status).toBe(400);
expect((await request(d, "PATCH", "/api/live/settings", { geminiVoice: "Kore" })).status).toBe(200);
expect((await request(d, "PATCH", "/api/live/settings", { geminiVoice: "" })).status).toBe(200);
- expect(d.saved).toEqual([{ idleMinutes: 10, readTypedReplies: false }, { geminiVoice: "Kore" }, { geminiVoice: "" }]);
+ expect(await request(d, "PATCH", "/api/live/settings", { standby: true, standbyIdleSeconds: 15 })).toMatchObject({ status: 200, body: { live: { standby: true, standbyIdleSeconds: 15 } } });
+ for (const standbyIdleSeconds of [4, 61, 10.5]) expect((await request(d, "PATCH", "/api/live/settings", { standbyIdleSeconds })).status).toBe(400);
+ expect(d.saved).toEqual([{ idleMinutes: 10, readTypedReplies: false }, { geminiVoice: "Kore" }, { geminiVoice: "" }, { standby: true, standbyIdleSeconds: 15 }]);
});
it("saves an Azure provider, endpoint and deployment, refusing a host the key must not reach", async () => {
const d = deps();
diff --git a/server/routes/live.ts b/server/routes/live.ts
index c538333d7d..0354ec1e51 100644
--- a/server/routes/live.ts
+++ b/server/routes/live.ts
@@ -4,6 +4,7 @@ import { z } from "zod";
import type { LiveFishRelayCommand, LiveFishRelayEvent, LiveProvider, LiveSettings } from "../../shared/wire.ts";
import { GEMINI_LIVE_VOICE_OPTIONS } from "../../shared/live-call.ts";
import { azureLiveDeployment, azureOpenAiRoot, customLiveApiBase, customLiveModel, LiveSessionError, MAX_SDP_BYTES } from "../live-call.ts";
+import { LIVE_STANDBY_IDLE_SECONDS_MAX, LIVE_STANDBY_IDLE_SECONDS_MIN } from "../live-config.ts";
import { LiveCallBusyError, type LiveCallController } from "../live-call-controller.ts";
import { RELAY_POLL_MS } from "../live-fish.ts";
import { PASS, type RouteContext, type RouteHandler } from "./table.ts";
@@ -14,7 +15,7 @@ export interface LiveRouteDeps {
deviceRevoked?: (device: string) => void;
resolveTarget(botId: string, threadId: string | undefined): { botId: string; botName: string; threadId: string } | null;
settings(): LiveSettings;
- saveSettings(patch: { provider?: LiveProvider; azureEndpoint?: string; azureDeployment?: string; customEndpoint?: string; customModel?: string; voice?: string; geminiVoice?: string; readTypedReplies?: boolean; idleMinutes?: number }): Promise<LiveSettings>;
+ saveSettings(patch: { provider?: LiveProvider; azureEndpoint?: string; azureDeployment?: string; customEndpoint?: string; customModel?: string; voice?: string; geminiVoice?: string; readTypedReplies?: boolean; idleMinutes?: number; standby?: boolean; standbyIdleSeconds?: number }): Promise<LiveSettings>;
/** A running relayed (Fish Audio, Gemini or ElevenLabs) call's relay, only for the token its start answered with. */
fishRelay(sessionId: string, token: string): { receive(events: LiveFishRelayEvent[], from?: number): void; poll(waitMs: number): Promise<{ commands: LiveFishRelayCommand[]; closed: boolean }> } | null;
}
@@ -60,6 +61,8 @@ const settingsBody = z.object({
geminiVoice: z.string().trim().refine((name) => name === "" || GEMINI_LIVE_VOICE_OPTIONS.some((option) => option.id === name)).optional(),
readTypedReplies: z.boolean().optional(),
idleMinutes: z.number().int().min(1).max(60).optional(),
+ standby: z.boolean().optional(),
+ standbyIdleSeconds: z.number().int().min(LIVE_STANDBY_IDLE_SECONDS_MIN).max(LIVE_STANDBY_IDLE_SECONDS_MAX).optional(),
}).strict();
const DEVICE_ID = /^[\w-]{1,128}$/;
diff --git a/server/testing/fake-openai-live.ts b/server/testing/fake-openai-live.ts
index 410c72a349..6e1b8c57c7 100644
--- a/server/testing/fake-openai-live.ts
+++ b/server/testing/fake-openai-live.ts
@@ -12,6 +12,7 @@ export interface FakeLiveSession {
body: Record<string, unknown>;
commands: Array<Record<string, unknown>>;
attached: boolean;
+ paused: boolean;
closed: boolean;
}
@@ -152,7 +153,7 @@ export async function startFakeOpenAiLive(options: { port?: number; closeOnReque
}
let body: Record<string, unknown> = {};
try { body = JSON.parse(Buffer.concat(chunks).toString("utf8")) as Record<string, unknown>; } catch {}
- const session: FakeLiveSession = { id: `sess_fake_${++counter}`, key: bearer(req), body, commands: [], attached: false, closed: false };
+ const session: FakeLiveSession = { id: `sess_fake_${++counter}`, key: bearer(req), body, commands: [], attached: false, paused: false, closed: false };
sessions.push(session);
wake();
res.writeHead(201, { "content-type": "application/json" }).end(JSON.stringify({
@@ -223,6 +224,9 @@ export async function startFakeOpenAiLive(options: { port?: number; closeOnReque
emit(sessionId, event) {
const socket = sockets.get(sessionId);
if (!socket) throw new Error(`fake GPT-Live: ${sessionId} has no sideband`);
+ const session = sessions.find((candidate) => candidate.id === sessionId)!;
+ if (event.type === "session.paused") session.paused = true;
+ if (event.type === "session.resumed") session.paused = false;
send(socket, event);
},
waitForAttach(sessionId, timeoutMs = 5_000) {
diff --git a/shared/live-call.ts b/shared/live-call.ts
index 7e092562f3..33adf77f5f 100644
--- a/shared/live-call.ts
+++ b/shared/live-call.ts
@@ -2,6 +2,8 @@ import { FULL_ANSWER_IN_CHAT } from "../packages/phone-protocol/src/live-call.ts
export * from "../packages/phone-protocol/src/live-call.ts";
+export const LIVE_STANDBY_IDLE_SECONDS_DEFAULT = 15;
+
/** GPT-Live caps each append at 500 tokens. A 500 UTF-8 byte budget is
* conservative even for emoji/CJK, unlike a prose-only character estimate.
* Byte-level tokenization cannot produce more tokens than input bytes. */
diff --git a/src/components/LiveCallBar.render.test.ts b/src/components/LiveCallBar.render.test.ts
index b4a57aabb3..192e7ce4bb 100644
--- a/src/components/LiveCallBar.render.test.ts
+++ b/src/components/LiveCallBar.render.test.ts
@@ -136,6 +136,8 @@ describe("LiveCallSettings", () => {
expect(markup).toContain('aria-label="Call settings"');
expect(markup).toContain("Marin (default)");
expect(markup).toContain("Read replies to typed messages");
+ expect(markup).toContain("Use lower-cost standby during silence");
+ expect(markup).not.toContain("Pause after this many seconds");
expect(markup).toContain(`When this is off, messages you type during a call and the bot&#x27;s answers to them are not sent to OpenAI.`);
expect(markup).toContain(`A Live call sends your voice to OpenAI, along with the chat&#x27;s recent messages, the bot&#x27;s answers and the details of any approval it asks for. The OpenAI key stays on your computer.`);
expect(markup).toMatch(/<option value="5" selected="">5<\/option>/);
@@ -144,6 +146,16 @@ describe("LiveCallSettings", () => {
expect(markup).toMatch(/role="dialog" tabindex="-1"/);
});
+ it("offers a bounded standby timeout only for OpenAI calls", () => {
+ const withLive = (live: LiveSettings) => {
+ const value = { state: { ...initialState, config: { live } as AppState["config"] }, dispatch: vi.fn(), flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };
+ return renderToStaticMarkup(createElement(BotEditorStore, { value, children: createElement(LiveCallSettings, { onClose: vi.fn() }) }));
+ };
+ const base = { configured: true, voice: "marin", readTypedReplies: true, idleMinutes: 5 };
+ expect(withLive({ ...base, standby: true, standbyIdleSeconds: 10 })).toMatch(/<option value="10" selected="">10s<\/option>/);
+ expect(withLive({ ...base, provider: "azure", standby: true, standbyIdleSeconds: 10 })).not.toContain("Use lower-cost standby during silence");
+ });
+
it("says which key Live calls use, and removes only a separate Live key", () => {
const withLive = (live: LiveSettings) => {
const value = { state: { ...initialState, config: { live } as AppState["config"] }, dispatch: vi.fn(), flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };
diff --git a/src/components/LiveCallSettings.tsx b/src/components/LiveCallSettings.tsx
index bd9bfcf7ba..e5daac6204 100644
--- a/src/components/LiveCallSettings.tsx
+++ b/src/components/LiveCallSettings.tsx
@@ -1,6 +1,6 @@
import { useCallback, useId, useState } from "react";
-import { GEMINI_LIVE_VOICE_OPTIONS, geminiLiveVoice, LIVE_VOICE_OPTIONS } from "../../shared/live-call";
+import { GEMINI_LIVE_VOICE_OPTIONS, geminiLiveVoice, LIVE_STANDBY_IDLE_SECONDS_DEFAULT, LIVE_VOICE_OPTIONS } from "../../shared/live-call";
import { t } from "@/lib/i18n";
import { liveDisclosure, liveKeyCopy, liveKeyFormKey } from "@/lib/call-mode";
import { api, useStore, type Bot, type ConfigStatus } from "@/state/store";
@@ -12,6 +12,7 @@ import { KeysLink } from "./keys/KeysLink";
import { Select } from "./Select";
const IDLE_CHOICES = [1, 2, 3, 5, 10, 15, 30, 60];
+const STANDBY_CHOICES = Array.from({ length: 56 }, (_, index) => index + 5);
/** With `bot`, the bot on the call: it can have a voice of its own, and the other voice is the default for every other bot. */
export function LiveCallSettings({ bot, onClose }: { bot?: Pick<Bot, "id" | "name" | "liveVoice">; onClose: () => void }) {
@@ -23,6 +24,7 @@ export function LiveCallSettings({ bot, onClose }: { bot?: Pick<Bot, "id" | "nam
const [providerSaving, setProviderSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const typedHintId = useId();
+ const standbyHintId = useId();
// Stable, so this callback ref runs once when the popover mounts, not on every save.
const focusOnOpen = useCallback((dialog: HTMLDivElement | null) => {
dialog?.querySelector<HTMLElement>("select, input, button")?.focus();
@@ -32,6 +34,7 @@ export function LiveCallSettings({ bot, onClose }: { bot?: Pick<Bot, "id" | "nam
const fish = live.provider === "fish";
const gemini = live.provider === "gemini";
const elevenlabs = live.provider === "elevenlabs";
+ const openai = (live.provider ?? "openai") === "openai";
const copy = liveKeyCopy(live.provider);
const hasKey = live.keySource === (fish ? "fishAudio" : gemini ? "gemini" : elevenlabs ? "elevenlabs" : "live");
// Gemini has its own voices, kept apart from the GPT-Live one.
@@ -39,7 +42,7 @@ export function LiveCallSettings({ bot, onClose }: { bot?: Pick<Bot, "id" | "nam
const voice = gemini ? geminiLiveVoice(live.geminiVoice) : live.voice || "marin";
const known = voiceOptions.some((option) => option.id === voice);
- const save = async (patch: Partial<Pick<LiveSettings, "voice" | "geminiVoice" | "readTypedReplies" | "idleMinutes">>) => {
+ const save = async (patch: Partial<Pick<LiveSettings, "voice" | "geminiVoice" | "readTypedReplies" | "idleMinutes" | "standby" | "standbyIdleSeconds">>) => {
setSaving(true);
setError(null);
try {
@@ -124,6 +127,32 @@ export function LiveCallSettings({ bot, onClose }: { bot?: Pick<Bot, "id" | "nam
))}
</Select>
</label>
+ {openai && <>
+ <label className="flex items-center justify-between gap-2">
+ <span className="text-ink-secondary">{t("call.live.standby")}</span>
+ <input
+ type="checkbox"
+ checked={live.standby === true}
+ disabled={saving}
+ aria-describedby={standbyHintId}
+ onChange={(event) => void save({ standby: event.target.checked, ...(event.target.checked ? { standbyIdleSeconds: live.standbyIdleSeconds ?? LIVE_STANDBY_IDLE_SECONDS_DEFAULT } : {}) })}
+ />
+ </label>
+ <div id={standbyHintId} className="-mt-2 text-[12px] text-ink-tertiary">{t("call.live.standbyHint")}</div>
+ {live.standby === true && <label className="flex items-center justify-between gap-2">
+ <span className="text-ink-secondary">{t("call.live.standbyTimeout")}</span>
+ <Select
+ size="sm"
+ value={live.standbyIdleSeconds ?? LIVE_STANDBY_IDLE_SECONDS_DEFAULT}
+ disabled={saving}
+ onChange={(event) => void save({ standbyIdleSeconds: Number(event.target.value) })}
+ >
+ {STANDBY_CHOICES.map((seconds) => (
+ <option key={seconds} value={seconds}>{seconds}s</option>
+ ))}
+ </Select>
+ </label>}
+ </>}
<div className="flex items-center justify-between gap-2 border-t border-hairline/60 pt-2">
<span className="text-ink-secondary">{t(copy.key)}</span>
<span className="flex gap-2">
diff --git a/src/locales/en.json b/src/locales/en.json
index cf38252006..cbbc905b54 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -7079,6 +7079,9 @@
"call.live.readTyped": "Read replies to typed messages",
"call.live.readTypedHint": "When this is off, messages you type during a call and the bot's answers to them are not sent to OpenAI.",
"call.live.idle": "Hang up after this many minutes of silence",
+ "call.live.standby": "Use lower-cost standby during silence",
+ "call.live.standbyHint": "OpenAI pauses inference at a lower rate after this delay. Your microphone and call stay connected; speaking resumes the same conversation.",
+ "call.live.standbyTimeout": "Pause after this many seconds",
"call.live.key": "OpenAI key",
"call.live.keyChange": "Change key",
"call.live.keyRemove": "Remove key",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 0dd3959498..c30e5f018d 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -6708,6 +6708,9 @@
"call.live.readTyped": "Ler em voz alta as respostas a mensagens digitadas",
"call.live.readTypedHint": "Com esta opção desligada, as mensagens que você digita durante uma chamada e as respostas do bot a elas não são enviadas à OpenAI.",
"call.live.idle": "Minutos de silêncio até desligar",
+ "call.live.standby": "Usar modo de espera de menor custo durante o silêncio",
+ "call.live.standbyHint": "Após esse tempo, a OpenAI pausa a inferência e cobra uma tarifa menor. O microfone continua ligado e a chamada permanece conectada. Ao falar, você retoma a mesma conversa.",
+ "call.live.standbyTimeout": "Segundos de silêncio até pausar",
"call.live.key": "Chave da OpenAI",
"call.live.keyChange": "Trocar chave",
"call.live.keyRemove": "Remover chave",