Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(live): add Gemini Live model setting and voiceActivity notice
jonathanwxh-cell977b5fd20a44
diff --git a/packages/phone-protocol/src/live-call-wire.ts b/packages/phone-protocol/src/live-call-wire.tsindex 90367e23cd..7c4e8659b5 100644--- a/packages/phone-protocol/src/live-call-wire.ts+++ b/packages/phone-protocol/src/live-call-wire.ts@@ -86,6 +86,8 @@ export interface LiveSettings {voice: string;/** The Gemini Live voice for "gemini" calls; absent means Gemini's default. */geminiVoice?: string;+ /** The Gemini Live model for "gemini" calls; absent means Gemini's default. */+ geminiModel?: string;readTypedReplies: boolean;idleMinutes: number;}diff --git a/packages/phone-protocol/src/live-call.ts b/packages/phone-protocol/src/live-call.tsindex becbae8022..eb78cd5057 100644--- a/packages/phone-protocol/src/live-call.ts+++ b/packages/phone-protocol/src/live-call.ts@@ -194,6 +194,24 @@ export const GEMINI_LIVE_VOICE_OPTIONS: ReadonlyArray<{ id: string; label: strin];export const GEMINI_LIVE_DEFAULT_VOICE = "Puck";+export const GEMINI_LIVE_DEFAULT_MODEL = "gemini-3.8-live";+export const GEMINI_LIVE_MODEL_PATTERN = /^[\w.-]{1,80}$/;++export const GEMINI_LIVE_MODEL_OPTIONS: ReadonlyArray<{ id: string; label: string }> = [+ { id: "gemini-3.8-live", label: "gemini-3.8-live (default)" },+ { id: "gemini-3.1-flash-live-preview", label: "gemini-3.1-flash-live-preview" },+];++/** A valid Gemini Live model id (with any leading `models/` stripped), else undefined. */+export function parseGeminiLiveModel(raw: string | undefined): string | undefined {+ const model = raw?.trim().replace(/^models\//, "") ?? "";+ return GEMINI_LIVE_MODEL_PATTERN.test(model) ? model : undefined;+}++/** A saved or overridden Gemini Live model when valid, else the default. */+export function geminiLiveModel(model: string | undefined): string {+ return parseGeminiLiveModel(model) ?? GEMINI_LIVE_DEFAULT_MODEL;+}/** A saved Gemini voice when it is one of Gemini's, else the default. */export function geminiLiveVoice(voice: string | undefined): string {diff --git a/server/live-config.ts b/server/live-config.tsindex 6a1a448a59..005a626258 100644--- a/server/live-config.ts+++ b/server/live-config.ts@@ -1,5 +1,6 @@// Live calls' settings in config.json: schema, type and environment overrides, kept out of server/config.ts.import { z } from "zod";+import { parseGeminiLiveModel } from "../shared/live-call.ts";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.";@@ -21,6 +22,7 @@ export const liveConfigSchema = z.object({elevenlabsAgentFor: z.string().max(64).optional(),voice: z.string().trim().max(40).regex(/^[a-z]*$/, "a Live voice is a lowercase built-in voice name").optional(),geminiVoice: z.string().trim().max(40).regex(/^[A-Za-z]*$/, "a Gemini Live voice is a built-in voice name").optional(),+ geminiModel: z.string().trim().max(80).transform((name) => name.replace(/^models\//, "")).refine((name) => name === "" || parseGeminiLiveModel(name) !== undefined, "a Gemini Live model is a Gemini model id").optional(),readTypedReplies: z.boolean().optional(),idleMinutes: z.number().int().min(1).max(60).optional(),});@@ -40,6 +42,7 @@ export interface LiveConfig {elevenlabsAgentFor?: string;voice?: string;geminiVoice?: string;+ geminiModel?: string;readTypedReplies?: boolean;idleMinutes?: number;}diff --git a/server/live-gemini.test.ts b/server/live-gemini.test.tsindex fcb8cf8061..d8df66b97b 100644--- a/server/live-gemini.test.ts+++ b/server/live-gemini.test.ts@@ -17,9 +17,13 @@ describe("Gemini Live endpoint", () => {expect(ENDPOINT).toEqual({ provider: "gemini", apiBase: "https://generativelanguage.googleapis.com/v1beta", model: GEMINI_LIVE_MODEL });});- it("takes a model id from OMB_GEMINI_LIVE_MODEL and ignores anything else", () => {- expect(geminiLiveEndpoint({ OMB_GEMINI_LIVE_MODEL: "models/gemini-3.8-live-extended-thinking" }).model).toBe("gemini-3.8-live-extended-thinking");- expect(geminiLiveEndpoint({ OMB_GEMINI_LIVE_MODEL: "../evil?x=1" }).model).toBe(GEMINI_LIVE_MODEL);+ it("takes a model id from OMB_GEMINI_LIVE_MODEL, else the configured model, and ignores anything else", () => {+ expect(geminiLiveEndpoint({ OMB_GEMINI_LIVE_MODEL: "models/gemini-3.8-live-extended-thinking" }, "gemini-3.1-flash-live-preview").model)+ .toBe("gemini-3.8-live-extended-thinking");+ expect(geminiLiveEndpoint({}, "models/gemini-3.1-flash-live-preview").model).toBe("gemini-3.1-flash-live-preview");+ expect(geminiLiveEndpoint({}, "../evil?x=1").model).toBe(GEMINI_LIVE_MODEL);+ expect(geminiLiveEndpoint({ OMB_GEMINI_LIVE_MODEL: "../evil?x=1" }, "gemini-3.1-flash-live-preview").model)+ .toBe("gemini-3.1-flash-live-preview");});it("accepts only a loopback override of the API's address", () => {diff --git a/server/live-gemini.ts b/server/live-gemini.tsindex 90821b682b..d03bc12c35 100644--- a/server/live-gemini.ts+++ b/server/live-gemini.ts@@ -1,15 +1,14 @@// Gemini Live calls. The Gemini key never leaves the harness: the client gets only a single-use ephemeral token whose setup// (model, instructions, the `delegate` tool) the harness locks here, and it relays what was said as a Fish Audio call does.import { randomBytes } from "node:crypto";-import { geminiLiveVoice } from "../shared/live-call.ts";+import { GEMINI_LIVE_DEFAULT_MODEL, geminiLiveVoice, parseGeminiLiveModel } from "../shared/live-call.ts";import type { LiveGeminiSession } from "../shared/wire.ts";import { LiveSessionError, type LiveBot, type LiveEndpoint, type LiveHistoryMessage } from "./live-call.ts";import { FISH_DELEGATE_TOOL, fishInstructions } from "./live-fish.ts";const GEMINI_BASE = "https://generativelanguage.googleapis.com";const API_VERSION = "v1beta";-export const GEMINI_LIVE_MODEL = "gemini-3.8-live";-const MODEL = /^[\w.-]{1,80}$/;+export const GEMINI_LIVE_MODEL = GEMINI_LIVE_DEFAULT_MODEL;const CREATE_TIMEOUT_MS = 20_000;/** How long the client has to connect, and how long the call may then run, reconnecting with session resumption. */const CONNECT_WITHIN_MS = 60_000;@@ -22,10 +21,10 @@ export function geminiLiveBaseUrl(env: NodeJS.ProcessEnv = process.env): stringreturn /^http:\/\/127\.0\.0\.1:\d{1,5}$/.test(override) ? override : GEMINI_BASE;}-/** `model` is OMB_GEMINI_LIVE_MODEL when that is a model id, else the default Live model. */-export function geminiLiveEndpoint(env: NodeJS.ProcessEnv = process.env): LiveEndpoint {- const model = env.OMB_GEMINI_LIVE_MODEL?.trim().replace(/^models\//, "") ?? "";- return { provider: "gemini", apiBase: `${geminiLiveBaseUrl(env)}/${API_VERSION}`, model: MODEL.test(model) ? model : GEMINI_LIVE_MODEL };+/** `model` is OMB_GEMINI_LIVE_MODEL when that is a model id, else the configured model, else the default Live model. */+export function geminiLiveEndpoint(env: NodeJS.ProcessEnv = process.env, configuredModel?: string): LiveEndpoint {+ const model = parseGeminiLiveModel(env.OMB_GEMINI_LIVE_MODEL) ?? parseGeminiLiveModel(configuredModel) ?? GEMINI_LIVE_MODEL;+ return { provider: "gemini", apiBase: `${geminiLiveBaseUrl(env)}/${API_VERSION}`, model };}/** The setup every connection of the call gets, whatever the client sends: Gemini Live API `BidiGenerateContentSetup`. */diff --git a/server/live-settings.test.ts b/server/live-settings.test.tsindex 32b3a658e5..fdee874a75 100644--- a/server/live-settings.test.ts+++ b/server/live-settings.test.ts@@ -18,9 +18,13 @@ describe("live settings", () => {expect(JSON.stringify(settings)).not.toContain("sk-test");});- it("reports a saved Gemini voice beside the GPT-Live one, and nothing when it is cleared", () => {- expect(liveSettingsFor({ live: { voice: "cedar", geminiVoice: "Kore" } } as AppConfig)).toMatchObject({ voice: "cedar", geminiVoice: "Kore" });- expect(liveSettingsFor({ live: { geminiVoice: "" } } as AppConfig)).not.toHaveProperty("geminiVoice");+ it("reports a saved Gemini voice and model beside the GPT-Live one, and nothing when cleared", () => {+ expect(liveSettingsFor({ live: { voice: "cedar", geminiVoice: "Kore", geminiModel: "gemini-3.1-flash-live-preview" } } as AppConfig))+ .toMatchObject({ voice: "cedar", geminiVoice: "Kore", geminiModel: "gemini-3.1-flash-live-preview" });+ expect(liveSettingsFor({ live: { geminiVoice: "", geminiModel: "" } } as AppConfig)).not.toHaveProperty("geminiVoice");+ expect(liveSettingsFor({ live: { geminiModel: "" } } as AppConfig)).not.toHaveProperty("geminiModel");+ expect(liveCallEndpoint({ live: { provider: "gemini", geminiModel: "gemini-3.1-flash-live-preview" } } as AppConfig, {})?.model)+ .toBe("gemini-3.1-flash-live-preview");});});diff --git a/server/live-settings.ts b/server/live-settings.tsindex 6224d4d612..2bc5f351e6 100644--- a/server/live-settings.ts+++ b/server/live-settings.ts@@ -41,7 +41,7 @@ export function liveCallEndpoint(cfg: LiveConfig, env: NodeJS.ProcessEnv = proceif (cfg.live?.provider === "azure") return azureLiveEndpoint(cfg.live.azureEndpoint, cfg.live.azureDeployment);if (cfg.live?.provider === "custom") return customLiveEndpoint(cfg.live.customEndpoint, cfg.live.customModel);if (cfg.live?.provider === "fish") return fishLiveEndpoint(usableFishAgent(cfg.live, cfg.tts?.fishKey ?? ""), env);- if (cfg.live?.provider === "gemini") return geminiLiveEndpoint(env);+ if (cfg.live?.provider === "gemini") return geminiLiveEndpoint(env, cfg.live.geminiModel);if (cfg.live?.provider === "elevenlabs") return elevenLabsLiveEndpoint(usableElevenLabsAgent(cfg.live, cfg.tts?.key ?? ""), env);return openAiLiveEndpoint(env);}@@ -85,6 +85,7 @@ export function liveSettingsFor(cfg: AppConfig): LiveSettings {...(cfg.live?.customModel ? { customModel: cfg.live.customModel } : {}),voice: cfg.live?.voice ?? "",...(cfg.live?.geminiVoice ? { geminiVoice: cfg.live.geminiVoice } : {}),+ ...(cfg.live?.geminiModel ? { geminiModel: cfg.live.geminiModel } : {}),readTypedReplies: cfg.live?.readTypedReplies ?? true,idleMinutes: Number.isInteger(minutes) && minutes! >= 1 && minutes! <= 60 ? minutes! : LIVE_IDLE_MINUTES_DEFAULT,};diff --git a/server/routes/live.test.ts b/server/routes/live.test.tsindex 042a10d291..0caacdb502 100644--- a/server/routes/live.test.ts+++ b/server/routes/live.test.ts@@ -142,7 +142,16 @@ 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", { geminiModel: "../bad" })).status).toBe(400);+ expect((await request(d, "PATCH", "/api/live/settings", { geminiModel: "models/gemini-3.1-flash-live-preview" })).status).toBe(200);+ expect((await request(d, "PATCH", "/api/live/settings", { geminiModel: "" })).status).toBe(200);+ expect(d.saved).toEqual([+ { idleMinutes: 10, readTypedReplies: false },+ { geminiVoice: "Kore" },+ { geminiVoice: "" },+ { geminiModel: "gemini-3.1-flash-live-preview" },+ { geminiModel: "" },+ ]);});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.tsindex 5a00df5aac..1d32b31f22 100644--- a/server/routes/live.ts+++ b/server/routes/live.ts@@ -2,7 +2,7 @@import type { IncomingMessage } from "node:http";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 { GEMINI_LIVE_VOICE_OPTIONS, parseGeminiLiveModel } from "../../shared/live-call.ts";import { azureLiveDeployment, azureOpenAiRoot, customLiveApiBase, customLiveModel, LiveSessionError, MAX_SDP_BYTES } from "../live-call.ts";import { LiveCallBusyError, type LiveCallController } from "../live-call-controller.ts";import { RELAY_POLL_MS } from "../live-fish.ts";@@ -14,7 +14,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; geminiModel?: string; readTypedReplies?: boolean; idleMinutes?: 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;}@@ -56,6 +56,8 @@ const settingsBody = z.object({voice: z.string().trim().max(40).regex(/^[a-z]*$/).optional(),// "" goes back to the default voice.geminiVoice: z.string().trim().refine((name) => name === "" || GEMINI_LIVE_VOICE_OPTIONS.some((option) => option.id === name)).optional(),+ // "" goes back to the default model.+ geminiModel: z.string().trim().max(80).transform((name) => name.replace(/^models\//, "")).refine((name) => name === "" || parseGeminiLiveModel(name) !== undefined).optional(),readTypedReplies: z.boolean().optional(),idleMinutes: z.number().int().min(1).max(60).optional(),}).strict();diff --git a/src/components/LiveCallBar.render.test.ts b/src/components/LiveCallBar.render.test.tsindex b4a57aabb3..10855cdb8b 100644--- a/src/components/LiveCallBar.render.test.ts+++ b/src/components/LiveCallBar.render.test.ts@@ -171,7 +171,9 @@ describe("LiveCallSettings", () => {expect(plain).toMatch(/<option value="Puck" selected="">Puck — upbeat \(default\)<\/option>/);expect(plain).toContain("Charon — informative");expect(plain).not.toContain("Marin (default)");- expect(withLive({ ...base, geminiVoice: "Kore" })).toMatch(/<option value="Kore" selected="">/);+ expect(plain).toMatch(/<option value="gemini-3\.8-live" selected="">gemini-3\.8-live \(default\)<\/option>/);+ expect(withLive({ ...base, geminiVoice: "Kore", geminiModel: "gemini-3.1-flash-live-preview" })).toMatch(/<option value="Kore" selected="">/);+ expect(withLive({ ...base, geminiModel: "gemini-3.1-flash-live-preview" })).toMatch(/<option value="gemini-3\.1-flash-live-preview" selected="">/);});it("offers the bot on the call a voice of its own beside the default for every other bot", () => {diff --git a/src/components/LiveCallSettings.tsx b/src/components/LiveCallSettings.tsxindex bd9bfcf7ba..3a8c7eed19 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_MODEL_OPTIONS, GEMINI_LIVE_VOICE_OPTIONS, geminiLiveModel, geminiLiveVoice, 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";@@ -38,8 +38,10 @@ export function LiveCallSettings({ bot, onClose }: { bot?: Pick<Bot, "id" | "namconst voiceOptions = gemini ? GEMINI_LIVE_VOICE_OPTIONS : LIVE_VOICE_OPTIONS;const voice = gemini ? geminiLiveVoice(live.geminiVoice) : live.voice || "marin";const known = voiceOptions.some((option) => option.id === voice);+ const geminiModel = geminiLiveModel(live.geminiModel);+ const knownGeminiModel = GEMINI_LIVE_MODEL_OPTIONS.some((option) => option.id === geminiModel);- const save = async (patch: Partial<Pick<LiveSettings, "voice" | "geminiVoice" | "readTypedReplies" | "idleMinutes">>) => {+ const save = async (patch: Partial<Pick<LiveSettings, "voice" | "geminiVoice" | "geminiModel" | "readTypedReplies" | "idleMinutes">>) => {setSaving(true);setError(null);try {@@ -99,6 +101,20 @@ export function LiveCallSettings({ bot, onClose }: { bot?: Pick<Bot, "id" | "nam</Select></label><div className="-mt-2 text-[12px] text-ink-tertiary">{t("call.live.voiceNext")}</div>+ {gemini && (+ <label className="flex items-center justify-between gap-2">+ <span className="text-ink-secondary">{t("call.live.geminiModel")}</span>+ <Select+ size="sm"+ value={geminiModel}+ disabled={saving}+ onChange={(event) => void save({ geminiModel: event.target.value })}+ >+ {!knownGeminiModel && <option value={geminiModel}>{geminiModel}</option>}+ {GEMINI_LIVE_MODEL_OPTIONS.map((option) => <option key={option.id} value={option.id}>{option.label}</option>)}+ </Select>+ </label>+ )}</>}<label className="flex items-center justify-between gap-2"><span className="text-ink-secondary">{t("call.live.readTyped")}</span>diff --git a/src/lib/live-call-fish.ts b/src/lib/live-call-fish.tsindex 9324cf675a..4d4b8c6b8b 100644--- a/src/lib/live-call-fish.ts+++ b/src/lib/live-call-fish.ts@@ -33,6 +33,7 @@ export interface FishSessionOptions<S extends RelaySession = LiveFishSessionTokeonModeChange(mode: string): void;onUserTranscript(event: { segmentId: string; text: string; final: boolean }): void;onAgentResponseDelta(event: { segmentId: string; text: string }): void;+ onNotice?(text: string | null): void;onError(error: { code?: string }): void;};}@@ -56,6 +57,8 @@ export interface FishCallHooks {heard(text: string): void;/** What the agent is saying, for the caption. */said(text: string): void;+ /** Live call notice shown while the call is active, or null to clear it. */+ notice?(text: string | null): void;/** The provider ended the session. */ended(reason: string): void;now(): number;@@ -104,6 +107,7 @@ export class FishCall<S extends RelaySession = LiveFishSessionToken> {onModeChange: (mode) => this.onMode(mode),onUserTranscript: (event) => this.onTranscript(event),onAgentResponseDelta: (event) => this.hooks.said(event.text),+ onNotice: (text) => this.hooks.notice?.(text),onError: (error) => this.relay({ type: "error", code: /^[\w.-]{1,40}$/.test(error.code ?? "") ? error.code! : "error" }),},});diff --git a/src/lib/live-call-gemini.test.ts b/src/lib/live-call-gemini.test.tsindex 8dfe005702..a131fcf5a5 100644--- a/src/lib/live-call-gemini.test.ts+++ b/src/lib/live-call-gemini.test.ts@@ -51,15 +51,16 @@ class FakeAudio implements GeminiAudio {close() { this.closed = true; }}-function harness({ denied = false } = {}) {+function harness({ denied = false, activityStuckMs }: { denied?: boolean; activityStuckMs?: number } = {}) {const sockets: FakeSocket[] = [];const audios: FakeAudio[] = [];const start = geminiSessionStarter({openSocket: (url) => { const socket = new FakeSocket(url); sockets.push(socket); return socket; },audio: () => { const audio = new FakeAudio(denied); audios.push(audio); return audio; },+ ...(activityStuckMs !== undefined ? { activityStuckMs } : {}),});const callbacks = {- onConnect: vi.fn(), onDisconnect: vi.fn(), onModeChange: vi.fn(), onUserTranscript: vi.fn(), onAgentResponseDelta: vi.fn(), onError: vi.fn(),+ onConnect: vi.fn(), onDisconnect: vi.fn(), onModeChange: vi.fn(), onUserTranscript: vi.fn(), onAgentResponseDelta: vi.fn(), onNotice: vi.fn(), onError: vi.fn(),};const delegate = vi.fn(async (_params: Record<string, unknown>, _context: { callId: string }) => "On it.");const options: FishSessionOptions<LiveGeminiSession> = { sessionToken: SESSION, clientTools: { [FISH_DELEGATE_TOOL]: delegate }, clientToolTimeoutMs: 12_000, callbacks };@@ -399,6 +400,30 @@ describe("a Gemini Live session", () => {expect(t.socket().sent.at(-1)).not.toHaveProperty("clientContent");expect(t.callbacks.onDisconnect).not.toHaveBeenCalled();});++ it("shows a notice when ACTIVITY_START is not followed by ACTIVITY_END, and clears it once heard", async () => {+ vi.useFakeTimers();+ try {+ const t = harness({ activityStuckMs: 5_000 });+ await t.connect();+ t.socket().receive({ voiceActivity: { voiceActivityType: "ACTIVITY_START" } });+ await vi.advanceTimersByTimeAsync(4_999);+ expect(t.callbacks.onNotice).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect(t.callbacks.onNotice).toHaveBeenCalledWith(expect.stringContaining("Gemini Live model"));+ t.socket().receive({ voiceActivity: { voiceActivityType: "ACTIVITY_END" } });+ expect(t.callbacks.onNotice).toHaveBeenLastCalledWith(null);++ t.callbacks.onNotice.mockClear();+ t.socket().receive({ voiceActivity: { voiceActivityType: "ACTIVITY_START" } });+ await vi.advanceTimersByTimeAsync(5_000);+ expect(t.callbacks.onNotice).toHaveBeenCalledTimes(1);+ t.socket().receive({ serverContent: { inputTranscription: { text: "hello" } } });+ expect(t.callbacks.onNotice).toHaveBeenLastCalledWith(null);+ } finally {+ vi.useRealTimers();+ }+ });});describe("Gemini call audio", () => {diff --git a/src/lib/live-call-gemini.ts b/src/lib/live-call-gemini.tsindex a91842dbdf..186d068ae8 100644--- a/src/lib/live-call-gemini.ts+++ b/src/lib/live-call-gemini.ts@@ -2,12 +2,15 @@// was said to the harness as on a Fish Audio call. The token's setup is locked by the harness (server/live-gemini.ts), so// the setup sent here only names the model and the session to resume.import type { LiveGeminiSession } from "../../shared/wire";+import { t } from "./i18n";import { browserGeminiAudio, type GeminiAudio } from "./live-call-gemini-audio";import { FISH_UPDATE_PREFIX, type FishAgentSession, type FishSessionOptions, type FishSessionStarter } from "./live-call-fish";const MIC_MIME = "audio/pcm;rate=16000";/** Gemini ends each connection after about 10 minutes; the call goes on over a new one, this many times at most. */const MAX_RECONNECTS = 12;+/** How long Gemini may stay in ACTIVITY_START with no ACTIVITY_END or reply before we hint to switch Live models. */+export const GEMINI_ACTIVITY_STUCK_MS = 8_000;/** Gemini can call a tool before it sends what it heard; the call waits this long after the last words heard... */const HEARD_QUIET_MS = 400;/** ...and this long at most, since a call can come without words, e.g. on the bot's update. */@@ -31,6 +34,7 @@ export interface GeminiSocket {export interface GeminiSessionDeps {openSocket(url: string): GeminiSocket;audio(): GeminiAudio;+ activityStuckMs?: number;}const browserDeps: GeminiSessionDeps = {@@ -49,6 +53,7 @@ type ServerMessage = {};toolCall?: { functionCalls?: ToolCall[] };toolCallCancellation?: { ids?: string[] };+ voiceActivity?: { voiceActivityType?: string };goAway?: unknown;sessionResumptionUpdate?: { newHandle?: string; resumable?: boolean };};@@ -105,6 +110,8 @@ class GeminiLiveSession implements FishAgentSession {private heldCalls: ToolCall[] = [];private heldQuiet: ReturnType<typeof setTimeout> | null = null;private heldLimit: ReturnType<typeof setTimeout> | null = null;+ private activityTimer: ReturnType<typeof setTimeout> | null = null;+ private activityNoticeShown = false;/** Calls Gemini cancelled, e.g. when the person talked over the agent: they do not run, or their answer is not sent. */private cancelledCalls = new Set<string>();@@ -139,7 +146,10 @@ class GeminiLiveSession implements FishAgentSession {}async setMicMuted(muted: boolean): Promise<void> {- if (muted && !this.muted) this.send({ realtimeInput: { audioStreamEnd: true } });+ if (muted && !this.muted) {+ this.clearActivityNotice();+ this.send({ realtimeInput: { audioStreamEnd: true } });+ }// Audio captured while muted that has not made a whole chunk yet is never sent.if (!muted && this.muted) this.audio?.dropMic();this.muted = muted;@@ -152,6 +162,7 @@ class GeminiLiveSession implements FishAgentSession {private shut(): void {this.clearHeldTimers();+ this.clearActivityTimer();const socket = this.socket;this.socket = null;if (socket) {@@ -199,6 +210,7 @@ class GeminiLiveSession implements FishAgentSession {/** A connection Gemini ended goes on over a new one while the session can be resumed. */private lost(resumable: boolean): void {if (this.ended) return;+ this.clearActivityTimer();if (resumable && this.handle && this.reconnects < MAX_RECONNECTS) {this.reconnects += 1;this.resumingAfterGoAway = this.wentAway;@@ -224,16 +236,21 @@ class GeminiLiveSession implements FishAgentSession {}private onMessage(message: ServerMessage): void {+ const activity = message.voiceActivity?.voiceActivityType;+ if (activity === "ACTIVITY_START") this.startActivityTimer();+ else if (activity === "ACTIVITY_END") this.clearActivityNotice();const content = message.serverContent;if (content) {const heard = content.inputTranscription?.text;if (heard) {+ this.clearActivityNotice();this.heard += heard;this.options.callbacks.onUserTranscript({ segmentId: `s${this.segment}`, text: this.heard, final: false });if (this.heldCalls.length) this.releaseWhenQuiet();}for (const part of content.modelTurn?.parts ?? []) {if (!part.inlineData?.data || !part.inlineData.mimeType?.startsWith("audio/")) continue;+ this.clearActivityNotice();this.finishHeardUnlessHeld();this.turnDone = false;this.audio?.play(decodeBase64(part.inlineData.data));@@ -244,6 +261,7 @@ class GeminiLiveSession implements FishAgentSession {}const said = content.outputTranscription?.text;if (said) {+ this.clearActivityNotice();this.finishHeardUnlessHeld();this.said += said;this.options.callbacks.onAgentResponseDelta({ segmentId: `a${this.segment}`, text: this.said });@@ -265,7 +283,10 @@ class GeminiLiveSession implements FishAgentSession {const cancelled = message.toolCallCancellation?.ids ?? [];if (cancelled.length) this.cancelCalls(cancelled);const calls = message.toolCall?.functionCalls ?? [];- if (calls.length) this.onToolCalls(calls);+ if (calls.length) {+ this.clearActivityNotice();+ this.onToolCalls(calls);+ }if (message.goAway !== undefined) this.wentAway = true;const update = message.sessionResumptionUpdate;if (update?.resumable && typeof update.newHandle === "string" && update.newHandle) {@@ -337,6 +358,29 @@ class GeminiLiveSession implements FishAgentSession {this.heldLimit = null;}+ private startActivityTimer(): void {+ if (this.ended || this.muted || this.activityTimer || this.activityNoticeShown) return;+ const waitMs = this.deps.activityStuckMs ?? GEMINI_ACTIVITY_STUCK_MS;+ this.activityTimer = setTimeout(() => {+ this.activityTimer = null;+ if (this.ended || this.muted) return;+ this.activityNoticeShown = true;+ this.options.callbacks.onNotice?.(t("call.live.geminiNoSpeechEnd"));+ }, waitMs);+ }++ private clearActivityTimer(): void {+ if (this.activityTimer) clearTimeout(this.activityTimer);+ this.activityTimer = null;+ }++ private clearActivityNotice(): void {+ this.clearActivityTimer();+ if (!this.activityNoticeShown) return;+ this.activityNoticeShown = false;+ this.options.callbacks.onNotice?.(null);+ }+private runToolCall(call: ToolCall): void {if (this.ended) return;const id = call.id ?? "";diff --git a/src/lib/live-call-media.ts b/src/lib/live-call-media.tsindex 15591aa2e0..057d37b22c 100644--- a/src/lib/live-call-media.ts+++ b/src/lib/live-call-media.ts@@ -308,6 +308,9 @@ async function startFishCall(target: { botId: string; threadId: string }, mine:said: (text) => {if (mine === generation) set({ caption: text.slice(-CAPTION_CHARS), heard: "" });},+ notice: (text) => {+ if (mine === generation && isLiveCallRunning(state.phase)) set({ notice: text });+ },ended: () => {if (mine !== generation) return;// Closing the call drops its queued `ended` report, so the server hears of it here.diff --git a/src/locales/en.json b/src/locales/en.jsonindex 0efb4ccdd6..0d6409806a 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -7075,6 +7075,8 @@"call.live.needsGemini": "Live calls through Gemini need your Gemini API key.","call.live.disclosureGemini": "A Live call sends your voice to Google's Gemini API, along with the chat's recent messages, the bot's answers and the details of any approval it asks for. This app passes what Gemini hears on to the bot. The Gemini key stays on your computer; the call gets a short-lived token only.","call.live.disclosureGeminiCloud": "A Live call sends your voice to Google's Gemini API, along with the chat's recent messages, the bot's answers and the details of any approval it asks for. This app passes what Gemini hears on to the bot. The Gemini key stays in the Cloud; the call gets a short-lived token only.",+ "call.live.geminiModel": "Model",+ "call.live.geminiNoSpeechEnd": "Gemini heard speech start but hasn't finished listening. If it doesn't reply, try switching the Gemini Live model in call settings.","call.live.provider.elevenlabs": "ElevenLabs Agents","call.live.elevenLabsHint": "ElevenLabs Live calls work in the desktop app and in a browser, for the owner of this computer. They use the ElevenLabs API key that ElevenLabs voices use, and set up one agent for calls on that account.","call.live.elevenLabsKey": "ElevenLabs key",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 213b6cf5a9..6115516349 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -6708,6 +6708,8 @@"call.live.needsGemini": "Chamadas ao vivo pelo Gemini precisam da sua chave de API do Gemini.","call.live.disclosureGemini": "Uma chamada ao vivo envia sua voz para a API do Gemini, do Google, junto com as mensagens recentes da conversa, as respostas do bot e os detalhes de qualquer aprovação que ele pedir. Este app repassa ao bot o que o Gemini ouve. A chave do Gemini fica no seu computador; a chamada recebe apenas um token de curta duração.","call.live.disclosureGeminiCloud": "Uma chamada ao vivo envia sua voz para a API do Gemini, do Google, junto com as mensagens recentes da conversa, as respostas do bot e os detalhes de qualquer aprovação que ele pedir. Este app repassa ao bot o que o Gemini ouve. A chave do Gemini fica no Cloud; a chamada recebe apenas um token de curta duração.",+ "call.live.geminiModel": "Modelo",+ "call.live.geminiNoSpeechEnd": "O Gemini detectou início de fala, mas ainda não ouviu o fim dela. Se não houver resposta, tente trocar o modelo do Gemini Live nas configurações da chamada.","call.live.provider.elevenlabs": "ElevenLabs Agents","call.live.elevenLabsHint": "As chamadas pelo ElevenLabs funcionam no app para computador e no navegador, para o dono deste computador. Elas usam a chave de API do ElevenLabs que as vozes do ElevenLabs usam e criam um agente para chamadas nessa conta.","call.live.elevenLabsKey": "Chave do ElevenLabs",