Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(speech): reading aloud and voice typing use the voice you chose, Gemini included

Salman Qureshi06d451d285d7
diff --git a/apps/desktop/src/components/dictation/Dictation.tsx b/apps/desktop/src/components/dictation/Dictation.tsx
index 45b61ae9..49e2254c 100644
--- a/apps/desktop/src/components/dictation/Dictation.tsx
+++ b/apps/desktop/src/components/dictation/Dictation.tsx
@@ -68,13 +68,12 @@ export function DictationNotice({ d, className }: { d: Dictation; className?: st
<Mic size={13} className="shrink-0 text-amber" />
<span className="min-w-0 flex-1">
{d.phase === "needs-setup"
- ? "Voice typing needs a speech service. Add an OpenAI key under Models, or a Deepgram or ElevenLabs key under Voice."
+ ? "Voice typing needs a speech service. Choose one under Voice (Gemini, OpenAI, Deepgram or ElevenLabs) and add its key; Mercury uses it everywhere."
: d.error}
</span>
{d.phase === "needs-setup" && (
<>
- <Button type="button" size="sm" variant="primary" onClick={() => { d.dismiss(); openSettings("models"); }}>Add OpenAI key</Button>
- <Button type="button" size="sm" variant="outline" onClick={() => { d.dismiss(); openSettings("voice"); }}>Voice settings</Button>
+ <Button type="button" size="sm" variant="primary" onClick={() => { d.dismiss(); openSettings("voice"); }}>Voice settings</Button>
</>
)}
<button type="button" onClick={d.dismiss} className="text-ink4 hover:text-ink" aria-label="Dismiss"><X size={13} /></button>
diff --git a/apps/desktop/src/components/readAloud/ReadAloud.tsx b/apps/desktop/src/components/readAloud/ReadAloud.tsx
index 59af363d..6e0e2021 100644
--- a/apps/desktop/src/components/readAloud/ReadAloud.tsx
+++ b/apps/desktop/src/components/readAloud/ReadAloud.tsx
@@ -40,12 +40,11 @@ export function ReadAloudNotice({ id }: { id: string }) {
<div className="mt-2 flex flex-wrap items-center gap-2 rounded-lg border border-amber/40 bg-amber/[0.06] px-3 py-2 text-xs text-ink2" role="alert">
<Volume2 size={13} className="shrink-0 text-amber" />
<span className="min-w-0 flex-1">
- {phase === "needs-setup" ? "Reading aloud needs a speech service. Add an OpenAI key under Models, or a Deepgram or ElevenLabs key under Voice." : error}
+ {phase === "needs-setup" ? "Reading aloud needs a speech service. Choose one under Voice (Gemini, OpenAI, Deepgram or ElevenLabs) and add its key; Mercury uses it everywhere." : error}
</span>
{phase === "needs-setup" && (
<>
- <Button type="button" size="sm" variant="primary" onClick={() => { dismiss(); openSettings("models"); }}>Add OpenAI key</Button>
- <Button type="button" size="sm" variant="outline" onClick={() => { dismiss(); openSettings("voice"); }}>Voice settings</Button>
+ <Button type="button" size="sm" variant="primary" onClick={() => { dismiss(); openSettings("voice"); }}>Voice settings</Button>
</>
)}
<button type="button" onClick={dismiss} className="text-ink4 hover:text-ink" aria-label="Dismiss"><X size={13} /></button>
diff --git a/src/plugins/manager.ts b/src/plugins/manager.ts
index f21cb4f8..f2817466 100644
--- a/src/plugins/manager.ts
+++ b/src/plugins/manager.ts
@@ -33,7 +33,8 @@ import { setToolOutcomeSink, unpublishPlugin, listLiveTools, listPluginCommands
import { InProcessRuntime, inProcessLogger } from './runtime/in-process.js';
import { OutOfProcessRuntime } from './runtime/out-of-process.js';
import { PluginChannel, type ChannelStatus } from './channel-bridge.js';
-import { transcribeAudio } from './transcribe.js';
+import { transcribeFile } from './transcribe.js';
+import { currentSpeechEngine } from './speech-choice.js';
import { CallScheduler, registerCallScheduler } from './call-schedule.js';
import type { PluginRuntime } from './runtime/types.js';
import { providerSecretNames, whenMatches, type WhenCondition, type CatalogEntry, type DisabledCode, type PluginListItem, type PluginManifest, type PluginProviderId, type PluginsState } from './types.js';
@@ -277,10 +278,11 @@ export class PluginManager {
() => resolvedSettings(manifest),
(m) => { void this.notifyFn(m); },
(key, value) => this.setSetting(id, key, value),
- // Voice notes: transcribed with the owner's OpenAI provider, when there is one.
+ // Voice notes: transcribed with the owner's speech service (the voice
+ // chosen in Settings → Voice, else OpenAI, Gemini, Deepgram, ElevenLabs).
(() => {
- const openai = providerLookup('openai');
- return openai?.apiKey ? (path: string) => transcribeAudio(path, { apiKey: openai.apiKey!, baseUrl: openai.baseUrl }) : null;
+ const engine = currentSpeechEngine('listen');
+ return engine ? (path: string) => transcribeFile(path, currentSpeechEngine('listen') ?? engine) : null;
})(),
);
}
diff --git a/src/plugins/speak.ts b/src/plugins/speak.ts
index 7d0e663c..0592f7d2 100644
--- a/src/plugins/speak.ts
+++ b/src/plugins/speak.ts
@@ -1,9 +1,10 @@
/**
* Text to speech, with the speech service the owner already set up (the
* same one voice typing uses, see pickSpeechEngine): OpenAI
- * (gpt-4o-mini-tts, falling back to tts-1), Deepgram (Aura 2) or
- * ElevenLabs (Flash v2.5). Always MP3, so every client can play it.
- * Used to read Mercury's replies aloud in the apps.
+ * (gpt-4o-mini-tts, falling back to tts-1), Gemini (Flash TTS), Deepgram
+ * (Aura 2) or ElevenLabs (Flash v2.5). MP3, or WAV from Gemini (speechMime
+ * says which); every client plays both. Used to read Mercury's replies aloud
+ * in the apps.
*/
import type { SpeechEngine } from './transcribe.js';
@@ -16,6 +17,14 @@ const OPENAI_VOICE = 'coral';
const DEEPGRAM_MODEL = 'aura-2-thalia-en';
const ELEVENLABS_VOICE = 'JBFqnCBsd6RMkjVDRZzb';
const ELEVENLABS_MODEL = 'eleven_flash_v2_5';
+const GEMINI_VOICE = 'Kore';
+/** Speaking models, newest first; the next is tried when one isn't offered or is busy. */
+const GEMINI_SPEAK_MODELS = ['gemini-3.8-flash-tts', 'gemini-2.5-flash-preview-tts'];
+
+/** The audio type synthesizeSpeech returns for an engine. */
+export function speechMime(engine: SpeechEngine): string {
+ return engine.kind === 'gemini' ? 'audio/wav' : 'audio/mpeg';
+}
type Fetch = typeof fetch;
@@ -24,7 +33,7 @@ export interface SpeakOptions {
signal?: AbortSignal;
}
-/** Speak `text` with `engine`; resolves with MP3 bytes. */
+/** Speak `text` with `engine`; resolves with audio bytes of type speechMime(engine). */
export async function synthesizeSpeech(text: string, engine: SpeechEngine, opts: SpeakOptions = {}): Promise<Uint8Array> {
const input = text.trim();
if (!input) throw new Error('nothing to say');
@@ -41,6 +50,30 @@ export async function synthesizeSpeech(text: string, engine: SpeechEngine, opts:
return audioOf(res, 'Deepgram');
}
+ if (engine.kind === 'gemini') {
+ let last: Response | null = null;
+ for (const model of GEMINI_SPEAK_MODELS) {
+ const res = await f(`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent`, {
+ method: 'POST',
+ headers: { 'x-goog-api-key': engine.apiKey, 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ contents: [{ parts: [{ text: input.slice(0, SPEAK_MAX_CHARS) }] }],
+ generationConfig: { responseModalities: ['AUDIO'], speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: GEMINI_VOICE } } } },
+ }),
+ signal,
+ });
+ if (res.ok) {
+ const body = (await res.json().catch(() => ({}))) as { candidates?: Array<{ content?: { parts?: Array<{ inlineData?: { mimeType?: string; data?: string } }> } }> };
+ const part = body.candidates?.[0]?.content?.parts?.find((p) => p.inlineData?.data)?.inlineData;
+ if (!part?.data) throw new Error('Gemini sent no audio');
+ return asWav(Buffer.from(part.data, 'base64'), part.mimeType ?? '');
+ }
+ last = res;
+ if (res.status !== 404 && res.status < 500) break;
+ }
+ return audioOf(last!, 'Gemini');
+ }
+
if (engine.kind === 'elevenlabs') {
const res = await f(`https://api.elevenlabs.io/v1/text-to-speech/${ELEVENLABS_VOICE}?output_format=mp3_44100_128`, {
method: 'POST',
@@ -64,6 +97,30 @@ export async function synthesizeSpeech(text: string, engine: SpeechEngine, opts:
return audioOf(res, 'OpenAI');
}
+/**
+ * Gemini sends a WAV file, or raw 16-bit PCM ("audio/L16;rate=24000"):
+ * the latter gets a WAV header so every player takes it.
+ */
+export function asWav(bytes: Uint8Array, mime: string): Uint8Array {
+ if (bytes.byteLength >= 12 && Buffer.from(bytes.subarray(0, 4)).toString('latin1') === 'RIFF') return bytes;
+ const rate = Number(/rate=(\d+)/i.exec(mime)?.[1] ?? 24000);
+ const header = Buffer.alloc(44);
+ header.write('RIFF', 0, 'latin1');
+ header.writeUInt32LE(36 + bytes.byteLength, 4);
+ header.write('WAVE', 8, 'latin1');
+ header.write('fmt ', 12, 'latin1');
+ header.writeUInt32LE(16, 16);
+ header.writeUInt16LE(1, 20); // PCM
+ header.writeUInt16LE(1, 22); // mono
+ header.writeUInt32LE(rate, 24);
+ header.writeUInt32LE(rate * 2, 28);
+ header.writeUInt16LE(2, 32);
+ header.writeUInt16LE(16, 34);
+ header.write('data', 36, 'latin1');
+ header.writeUInt32LE(bytes.byteLength, 40);
+ return new Uint8Array(Buffer.concat([header, Buffer.from(bytes)]));
+}
+
async function audioOf(res: Response, vendor: string): Promise<Uint8Array> {
if (!res.ok) {
let detail = '';
diff --git a/src/plugins/speech-choice.ts b/src/plugins/speech-choice.ts
new file mode 100644
index 00000000..96ada7bf
--- /dev/null
+++ b/src/plugins/speech-choice.ts
@@ -0,0 +1,19 @@
+import { loadConfig } from '../utils/config.js';
+import { readSettings, secretValue } from './store.js';
+import { pickSpeechEngine, preferredSpeech, type SpeechEngine } from './transcribe.js';
+
+/**
+ * The speech service Mercury uses right now, for every feature that
+ * listens (voice typing, voice notes) or speaks (reading replies aloud):
+ * the voice the owner chose in Settings → Voice when it has a key, else the
+ * first service that has one. Read on each use, so a change applies at once.
+ */
+export function currentSpeechEngine(use: 'listen' | 'speak'): SpeechEngine | null {
+ let voice: Record<string, unknown> = {};
+ try { voice = readSettings('optimus'); } catch { /* no Optimus settings: no preference */ }
+ return pickSpeechEngine(loadConfig().providers.openai, secretValue, preferredSpeech(voice, use));
+}
+
+/** What to tell someone with no speech service yet. */
+export const NO_SPEECH_SERVICE =
+ 'a speech service: an OpenAI key (Settings → Models), or a Gemini, Deepgram or ElevenLabs key (Settings → Voice).';
diff --git a/src/plugins/transcribe.ts b/src/plugins/transcribe.ts
index 0a29295b..2c277ac4 100644
--- a/src/plugins/transcribe.ts
+++ b/src/plugins/transcribe.ts
@@ -1,9 +1,10 @@
/**
- * Speech to text, with services the owner already set up in Mercury:
- * 1. the OpenAI provider (gpt-4o-mini-transcribe, falling back to whisper-1),
- * 2. else a Deepgram key (nova-3) or an ElevenLabs key (scribe_v1) saved
- * for voice (Settings → Voice / the Optimus plugin).
- * Used for voice notes from channels and for dictation in the apps.
+ * Speech to text, with a service the owner already set up in Mercury: the
+ * OpenAI provider (gpt-4o-mini-transcribe, falling back to whisper-1), or a
+ * Gemini, Deepgram (nova-3) or ElevenLabs (scribe_v1) key saved for voice
+ * (Settings → Voice / the Optimus plugin). The voice the owner chose there
+ * decides which one (see pickSpeechEngine). Used for voice notes from
+ * channels and for dictation in the apps.
*/
import { readFileSync, statSync } from 'node:fs';
import { basename } from 'node:path';
@@ -18,7 +19,17 @@ export interface TranscribeCreds {
export type SpeechEngine =
| { kind: 'openai'; label: string; apiKey: string; baseUrl?: string }
| { kind: 'deepgram'; label: string; apiKey: string }
- | { kind: 'elevenlabs'; label: string; apiKey: string };
+ | { kind: 'elevenlabs'; label: string; apiKey: string }
+ | { kind: 'gemini'; label: string; apiKey: string };
+
+export type SpeechKind = SpeechEngine['kind'];
+
+const GEMINI_API = 'https://generativelanguage.googleapis.com/v1beta/models';
+/**
+ * Listening models, fastest first (measured: a few seconds for a short
+ * recording); the next is tried when one isn't offered (404) or is busy (5xx).
+ */
+const GEMINI_LISTEN_MODELS = ['gemini-2.5-flash-lite', 'gemini-flash-lite-latest', 'gemini-flash-latest'];
type Fetch = typeof fetch;
@@ -28,6 +39,12 @@ export async function transcribeAudio(path: string, creds: TranscribeCreds, sign
return transcribeBytes(bytes, 'audio/ogg', basename(path).replace(/\.[^.]+$/, '') + '.ogg', { kind: 'openai', label: 'OpenAI', ...creds }, { signal });
}
+/** A voice note on disk (channels send Ogg/Opus), with any speech service. */
+export async function transcribeFile(path: string, engine: SpeechEngine, signal?: AbortSignal): Promise<string> {
+ if (statSync(path).size > MAX_BYTES) throw new Error('the voice note is longer than the 25 MB transcription limit');
+ return transcribeBytes(readFileSync(path), 'audio/ogg', basename(path).replace(/\.[^.]+$/, '') + '.ogg', engine, { signal });
+}
+
/** File extension a speech API expects for a recorder's mime type. */
export function audioExtension(mime: string): string {
const m = mime.toLowerCase();
@@ -66,6 +83,29 @@ export async function transcribeBytes(
return (body.results?.channels?.[0]?.alternatives?.[0]?.transcript ?? '').trim();
}
+ if (engine.kind === 'gemini') {
+ let lastError = '';
+ for (const model of GEMINI_LISTEN_MODELS) {
+ const res = await f(`${GEMINI_API}/${model}:generateContent`, {
+ method: 'POST',
+ headers: { 'x-goog-api-key': engine.apiKey, 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ contents: [{ parts: [
+ { inlineData: { mimeType: type, data: Buffer.from(bytes).toString('base64') } },
+ { text: `Transcribe this recording exactly${opts.language ? ` (language: ${opts.language})` : ', in the language it is spoken in'}. Reply with only the transcript, nothing else. If nothing is said, reply with nothing.` },
+ ] }],
+ generationConfig: { temperature: 0 },
+ }),
+ signal,
+ });
+ const body = (await res.json().catch(() => ({}))) as { candidates?: Array<{ content?: { parts?: Array<{ text?: string }> } }>; error?: { message?: string } };
+ if (res.ok) return (body.candidates?.[0]?.content?.parts ?? []).map((p) => p.text ?? '').join('').trim();
+ lastError = vendorError('Gemini', res.status, body.error?.message);
+ if (res.status !== 404 && res.status < 500) break;
+ }
+ throw new Error(lastError);
+ }
+
if (engine.kind === 'elevenlabs') {
const form = new FormData();
form.append('model_id', 'scribe_v1');
@@ -101,17 +141,44 @@ function vendorError(vendor: string, status: number, detail?: string): string {
}
/**
- * Which speech service to use, from what's configured. OpenAI first (best
- * at mixed languages and punctuation), then Deepgram, then ElevenLabs.
+ * Which speech service to use, from what's configured. The voice the owner
+ * picked (Settings → Voice: Optimus's voice engine, or its listening and
+ * speaking services) comes first when it has a key, so choosing Gemini there
+ * means Mercury reads aloud and listens with Gemini too. Otherwise the first
+ * service that has a key: OpenAI, Gemini, Deepgram, ElevenLabs.
*/
export function pickSpeechEngine(
openai: { apiKey?: string; baseUrl?: string; enabled?: boolean } | undefined,
secret: (name: string) => string | undefined,
+ preferred: ReadonlyArray<string | undefined> = [],
): SpeechEngine | null {
- if (openai?.apiKey && openai.enabled !== false) return { kind: 'openai', label: 'OpenAI', apiKey: openai.apiKey, baseUrl: openai.baseUrl };
+ const available: Partial<Record<SpeechKind, SpeechEngine>> = {};
+ if (openai?.apiKey && openai.enabled !== false) available.openai = { kind: 'openai', label: 'OpenAI', apiKey: openai.apiKey, baseUrl: openai.baseUrl };
+ const gemini = secret('GEMINI_API_KEY');
+ if (gemini) available.gemini = { kind: 'gemini', label: 'Gemini', apiKey: gemini };
const deepgram = secret('DEEPGRAM_API_KEY');
- if (deepgram) return { kind: 'deepgram', label: 'Deepgram', apiKey: deepgram };
+ if (deepgram) available.deepgram = { kind: 'deepgram', label: 'Deepgram', apiKey: deepgram };
const eleven = secret('ELEVENLABS_API_KEY');
- if (eleven) return { kind: 'elevenlabs', label: 'ElevenLabs', apiKey: eleven };
- return null;
+ if (eleven) available.elevenlabs = { kind: 'elevenlabs', label: 'ElevenLabs', apiKey: eleven };
+ for (const p of preferred) {
+ const hit = p ? available[p as SpeechKind] : undefined;
+ if (hit) return hit;
+ }
+ return available.openai ?? available.gemini ?? available.deepgram ?? available.elevenlabs ?? null;
+}
+
+/**
+ * The owner's voice choice, as speech services to prefer: Optimus's voice
+ * engine (gemini, openai, elevenlabs…), then its listening or speaking
+ * service when the engine is Mercury's own pipeline.
+ */
+export function preferredSpeech(settings: Record<string, unknown>, use: 'listen' | 'speak'): string[] {
+ const engine = typeof settings.voiceEngine === 'string' ? settings.voiceEngine : undefined;
+ const stt = typeof settings.sttProvider === 'string' ? settings.sttProvider : undefined;
+ const tts = typeof settings.ttsProvider === 'string' ? settings.ttsProvider : undefined;
+ const out: string[] = [];
+ if (engine) out.push(engine);
+ if (use === 'listen' && stt) out.push(stt);
+ if (use === 'speak' && tts) out.push(tts);
+ return out;
}
diff --git a/src/web/api/speak-route.test.ts b/src/web/api/speak-route.test.ts
index 617dfb4e..8ac1e441 100644
--- a/src/web/api/speak-route.test.ts
+++ b/src/web/api/speak-route.test.ts
@@ -1,4 +1,4 @@
-import { writeFileSync } from 'node:fs';
+import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -6,7 +6,7 @@ const home = await vi.hoisted(async () => {
const fs = await import('node:fs');
const os = await import('node:os');
const path = await import('node:path');
- for (const k of ['OPENAI_API_KEY', 'DEEPGRAM_API_KEY', 'ELEVENLABS_API_KEY']) delete process.env[k];
+ for (const k of ['OPENAI_API_KEY', 'GEMINI_API_KEY', 'DEEPGRAM_API_KEY', 'ELEVENLABS_API_KEY']) delete process.env[k];
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-speak-'));
fs.writeFileSync(path.join(dir, 'mercury.yaml'), 'identity:\n owner: Test\n');
process.env.MERCURY_HOME = dir;
@@ -22,7 +22,23 @@ const withOpenAI = () => writeFileSync(join(home, 'mercury.yaml'), [
'identity:', ' owner: Test', 'providers:', ' openai:', ' name: openai', ' apiKey: sk-test-openai-000000000000', ' baseUrl: https://api.openai.com/v1', ' model: gpt-4o-mini', ' enabled: true', '',
].join('\n'));
-afterEach(() => { setSpeakFetch(undefined); delete process.env.DEEPGRAM_API_KEY; delete process.env.ELEVENLABS_API_KEY; });
+afterEach(() => {
+ setSpeakFetch(undefined);
+ delete process.env.DEEPGRAM_API_KEY; delete process.env.ELEVENLABS_API_KEY; delete process.env.GEMINI_API_KEY;
+ rmSync(join(home, 'plugins'), { recursive: true, force: true });
+ writeFileSync(join(home, 'mercury.yaml'), 'identity:\n owner: Test\n');
+});
+
+/** Settings → Voice: what the owner picked for Optimus's voice. */
+const chooseVoice = (values: Record<string, string>) => {
+ mkdirSync(join(home, 'plugins', 'optimus'), { recursive: true });
+ writeFileSync(join(home, 'plugins', 'optimus', 'settings.json'), JSON.stringify({ settingsVersion: 1, values }));
+};
+const wav = new Uint8Array([0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x41, 0x56, 0x45, 1, 2]);
+const geminiReply = (bytes: Uint8Array, mimeType = 'audio/wav') => ({
+ ok: true, status: 200,
+ json: async () => ({ candidates: [{ content: { parts: [{ inlineData: { mimeType, data: Buffer.from(bytes).toString('base64') } }] } }] }),
+});
describe('read aloud', () => {
it('with no speech service, says how to turn one on', async () => {
@@ -76,4 +92,48 @@ describe('read aloud', () => {
expect(res.status).toBe(502);
expect(await res.json()).toMatchObject({ error: expect.stringMatching(/rejected the key/) });
});
+
+ it('speaks with a Gemini key and returns WAV', async () => {
+ process.env.GEMINI_API_KEY = 'gm-test-key';
+ const f = vi.fn().mockResolvedValue(geminiReply(wav));
+ setSpeakFetch(f as never);
+ expect(await (await speak.request('http://127.0.0.1/api/speak')).json()).toMatchObject({ available: true, engine: 'Gemini' });
+ const res = await post('Hello from Mercury.');
+ expect(res.status).toBe(200);
+ expect(res.headers.get('Content-Type')).toBe('audio/wav');
+ expect(new Uint8Array(await res.arrayBuffer())).toEqual(wav);
+ const [url, init] = f.mock.calls[0] as [string, RequestInit];
+ expect(url).toMatch(/generativelanguage\.googleapis\.com\/v1beta\/models\/gemini-[^:]+tts:generateContent$/);
+ expect((init.headers as Record<string, string>)['x-goog-api-key']).toBe('gm-test-key');
+ expect(JSON.parse(String(init.body)).generationConfig.responseModalities).toEqual(['AUDIO']);
+ });
+
+ it('raw PCM from Gemini gets a WAV header', async () => {
+ process.env.GEMINI_API_KEY = 'gm-test-key';
+ setSpeakFetch(vi.fn().mockResolvedValue(geminiReply(new Uint8Array([1, 2, 3, 4]), 'audio/L16;codec=pcm;rate=24000')) as never);
+ const bytes = new Uint8Array(await (await post('Hi')).arrayBuffer());
+ expect(Buffer.from(bytes.subarray(0, 4)).toString('latin1')).toBe('RIFF');
+ expect(Buffer.from(bytes).readUInt32LE(24)).toBe(24000);
+ expect(bytes.byteLength).toBe(44 + 4);
+ });
+
+ it('the voice chosen in Settings → Voice comes first: Gemini over OpenAI', async () => {
+ withOpenAI();
+ process.env.GEMINI_API_KEY = 'gm-test-key';
+ chooseVoice({ voiceEngine: 'gemini' });
+ expect(await (await speak.request('http://127.0.0.1/api/speak')).json()).toMatchObject({ engine: 'Gemini' });
+ chooseVoice({ voiceEngine: 'openai' });
+ expect(await (await speak.request('http://127.0.0.1/api/speak')).json()).toMatchObject({ engine: 'OpenAI' });
+ });
+
+ it('a chosen voice without a key falls back to one that has a key', async () => {
+ process.env.GEMINI_API_KEY = 'gm-test-key';
+ chooseVoice({ voiceEngine: 'openai' });
+ expect(await (await speak.request('http://127.0.0.1/api/speak')).json()).toMatchObject({ engine: 'Gemini' });
+ });
+
+ it('says Gemini is an option when nothing is set up', async () => {
+ const res = await post('Hello');
+ expect(((await res.json()) as { error: string }).error).toMatch(/Gemini/);
+ });
});
diff --git a/src/web/api/speak.ts b/src/web/api/speak.ts
index 26a37138..1ce72a2c 100644
--- a/src/web/api/speak.ts
+++ b/src/web/api/speak.ts
@@ -1,17 +1,15 @@
import { Hono } from 'hono';
-import { loadConfig } from '../../utils/config.js';
-import { secretValue } from '../../plugins/store.js';
-import { pickSpeechEngine } from '../../plugins/transcribe.js';
-import { SPEAK_MAX_CHARS, synthesizeSpeech } from '../../plugins/speak.js';
+import { currentSpeechEngine, NO_SPEECH_SERVICE } from '../../plugins/speech-choice.js';
+import { SPEAK_MAX_CHARS, speechMime, synthesizeSpeech } from '../../plugins/speak.js';
/**
* Read aloud for every client: text in, speech out.
*
* GET /api/speak { available, engine, maxChars } — which speech service would be used
- * POST /api/speak { text } → audio/mpeg
+ * POST /api/speak { text } → audio/mpeg (audio/wav from Gemini)
*
- * Uses the speech service voice typing uses (OpenAI provider, else a
- * Deepgram or ElevenLabs voice key). With none, 412 { needs: 'speech' } so
+ * Uses the speech service voice typing uses (the voice chosen in Settings →
+ * Voice when it has a key, else OpenAI, Gemini, Deepgram or ElevenLabs). With none, 412 { needs: 'speech' } so
* the app can say how to turn it on. Clients send a long reply in parts of
* at most `maxChars`, so the first words play while the rest is made.
*/
@@ -22,7 +20,7 @@ let doFetch: Fetch | undefined;
export function setSpeakFetch(f: Fetch | undefined): void { doFetch = f; }
function engine() {
- return pickSpeechEngine(loadConfig().providers.openai, secretValue);
+ return currentSpeechEngine('speak');
}
const speak = new Hono();
@@ -35,7 +33,7 @@ speak.get('/api/speak', (c) => {
speak.post('/api/speak', async (c) => {
const e = engine();
if (!e) {
- return c.json({ error: 'Reading aloud needs a speech service: an OpenAI key (Settings → Models), or a Deepgram or ElevenLabs key (Settings → Voice).', needs: 'speech' }, 412);
+ return c.json({ error: `Reading aloud needs ${NO_SPEECH_SERVICE}`, needs: 'speech' }, 412);
}
const body = (await c.req.json().catch(() => ({}))) as { text?: unknown };
const text = typeof body.text === 'string' ? body.text.trim() : '';
@@ -43,7 +41,7 @@ speak.post('/api/speak', async (c) => {
if (text.length > SPEAK_MAX_CHARS) return c.json({ error: `Send at most ${SPEAK_MAX_CHARS} characters at a time.`, maxChars: SPEAK_MAX_CHARS }, 413);
try {
const audio = await synthesizeSpeech(text, e, { fetch: doFetch, signal: c.req.raw.signal });
- return new Response(audio, { headers: { 'Content-Type': 'audio/mpeg', 'Cache-Control': 'no-store', 'X-Speech-Engine': e.label } });
+ return new Response(audio, { headers: { 'Content-Type': speechMime(e), 'Cache-Control': 'no-store', 'X-Speech-Engine': e.label } });
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
return c.json({ error: `Couldn't read that aloud: ${message}`, engine: e.label }, 502);
diff --git a/src/web/api/transcribe-route.test.ts b/src/web/api/transcribe-route.test.ts
index a43062fd..5afc92e2 100644
--- a/src/web/api/transcribe-route.test.ts
+++ b/src/web/api/transcribe-route.test.ts
@@ -6,7 +6,7 @@ const home = await vi.hoisted(async () => {
const fs = await import('node:fs');
const os = await import('node:os');
const path = await import('node:path');
- for (const k of ['OPENAI_API_KEY', 'DEEPGRAM_API_KEY', 'ELEVENLABS_API_KEY']) delete process.env[k];
+ for (const k of ['OPENAI_API_KEY', 'GEMINI_API_KEY', 'DEEPGRAM_API_KEY', 'ELEVENLABS_API_KEY']) delete process.env[k];
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-transcribe-'));
fs.writeFileSync(path.join(dir, 'mercury.yaml'), 'identity:\n owner: Test\n');
process.env.MERCURY_HOME = dir;
@@ -22,7 +22,10 @@ const withOpenAI = () => writeFileSync(join(home, 'mercury.yaml'), [
'identity:', ' owner: Test', 'providers:', ' openai:', ' name: openai', ' apiKey: sk-test-openai-000000000000', ' baseUrl: https://api.openai.com/v1', ' model: gpt-4o-mini', ' enabled: true', '',
].join('\n'));
-afterEach(() => { setTranscribeFetch(undefined); delete process.env.DEEPGRAM_API_KEY; });
+afterEach(() => {
+ setTranscribeFetch(undefined); delete process.env.DEEPGRAM_API_KEY; delete process.env.GEMINI_API_KEY;
+ writeFileSync(join(home, 'mercury.yaml'), 'identity:\n owner: Test\n');
+});
describe('dictation', () => {
it('with no speech service, says how to turn one on', async () => {
@@ -66,4 +69,28 @@ describe('dictation', () => {
withOpenAI();
expect((await post(audio, 'application/json')).status).toBe(415);
});
+
+ it('listens with a Gemini key: the recording goes inline, the transcript comes back', async () => {
+ process.env.GEMINI_API_KEY = 'gm-test-key';
+ const f = vi.fn().mockResolvedValue({ ok: true, status: 200, json: async () => ({ candidates: [{ content: { parts: [{ text: ' Hello from Mercury \n' }] } }] }) });
+ setTranscribeFetch(f as never);
+ const res = await post();
+ expect(res.status).toBe(200);
+ expect(await res.json()).toMatchObject({ text: 'Hello from Mercury', engine: 'Gemini' });
+ const [url, init] = f.mock.calls[0] as [string, RequestInit];
+ expect(url).toMatch(/models\/gemini-2\.5-flash-lite:generateContent$/);
+ const part = JSON.parse(String(init.body)).contents[0].parts[0];
+ expect(part.inlineData.mimeType).toBe('audio/webm');
+ expect(Buffer.from(part.inlineData.data, 'base64')).toEqual(Buffer.from(audio));
+ });
+
+ it('a Gemini model that is busy or gone falls through to the next', async () => {
+ process.env.GEMINI_API_KEY = 'gm-test-key';
+ const f = vi.fn()
+ .mockResolvedValueOnce({ ok: false, status: 503, json: async () => ({ error: { message: 'overloaded' } }) })
+ .mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ candidates: [{ content: { parts: [{ text: 'ok' }] } }] }) });
+ setTranscribeFetch(f as never);
+ expect(await (await post()).json()).toMatchObject({ text: 'ok' });
+ expect(f).toHaveBeenCalledTimes(2);
+ });
});
diff --git a/src/web/api/transcribe.ts b/src/web/api/transcribe.ts
index 20f515fa..f7df3de8 100644
--- a/src/web/api/transcribe.ts
+++ b/src/web/api/transcribe.ts
@@ -1,7 +1,6 @@
import { Hono } from 'hono';
-import { loadConfig } from '../../utils/config.js';
-import { secretValue } from '../../plugins/store.js';
-import { audioExtension, pickSpeechEngine, transcribeBytes } from '../../plugins/transcribe.js';
+import { currentSpeechEngine, NO_SPEECH_SERVICE } from '../../plugins/speech-choice.js';
+import { audioExtension, transcribeBytes } from '../../plugins/transcribe.js';
/**
* Dictation for every client: speak instead of typing.
@@ -9,8 +8,8 @@ import { audioExtension, pickSpeechEngine, transcribeBytes } from '../../plugins
* GET /api/transcribe { available, engine } — which speech service would be used
* POST /api/transcribe[?language=] raw audio body (audio/webm, audio/mp4, …) → { text, engine }
*
- * Uses a service the owner already set up (OpenAI provider, else a Deepgram
- * or ElevenLabs voice key). With none, 412 { needs: 'speech' } so the app can
+ * Uses a service the owner already set up (the voice chosen in Settings →
+ * Voice when it has a key, else OpenAI, Gemini, Deepgram or ElevenLabs). With none, 412 { needs: 'speech' } so the app can
* say how to turn it on. Audio is sent once and not kept.
*/
@@ -22,7 +21,7 @@ let doFetch: Fetch | undefined;
export function setTranscribeFetch(f: Fetch | undefined): void { doFetch = f; }
function engine() {
- return pickSpeechEngine(loadConfig().providers.openai, secretValue);
+ return currentSpeechEngine('listen');
}
const transcribe = new Hono();
@@ -35,7 +34,7 @@ transcribe.get('/api/transcribe', (c) => {
transcribe.post('/api/transcribe', async (c) => {
const e = engine();
if (!e) {
- return c.json({ error: 'Voice typing needs a speech service: an OpenAI key (Settings → Models), or a Deepgram or ElevenLabs key (Settings → Voice).', needs: 'speech' }, 412);
+ return c.json({ error: `Voice typing needs ${NO_SPEECH_SERVICE}`, needs: 'speech' }, 412);
}
const declared = Number(c.req.header('content-length') ?? 0);
if (declared > MAX_BYTES) return c.json({ error: 'That recording is too long (over 25 MB). Keep dictation under about 20 minutes.' }, 413);