Files
openchamber/packages/web/server/lib/tts-service.js
T
gsxdsmandBohdan Triapitsyn 1ed5316ac7 feat(voice): add voice input/output support with multiple providers (#281)
* feat(voice): add voice input/output support with multiple providers

- Add BrowserVoiceButton component for Web Speech API voice input
- Add VoiceProvider context for managing voice state across the app
- Add TTS (Text-to-Speech) support with browser, macOS Say, and OpenAI providers
- Add message TTS buttons to read assistant messages aloud
- Add VoiceSettings page in OpenChamber settings
- Add server endpoints for TTS and summarization services
- Include slider component for voice rate/pitch/volume controls
- Add hidden session support for background voice operations
- Add Caddyfile for HTTPS support (required for microphone access)

* fix: Build errors fixed and removed outdated ElevenLabs test code.

* refactor(voice): use zen API with gpt-5-nano for TTS summarization

Replace the hidden session + OpenCode SDK approach with direct calls
to the opencode.ai zen API (same pattern used for commit message and
PR description generation).

- Rewrite summarization-service.js to call zen/v1/responses with gpt-5-nano
- Remove hidden session logic (hiddenSession.ts, sessionStore filtering)
- Remove summarizeModel setting and model selector from VoiceSettings
- Simplify client-side summarize.ts to no longer pass model params
- Clean up callers in useMessageTTS and useBrowserVoice

* fix(voice): remove false 'voice not supported' warning in settings

Mobile Safari does support voice but the isSupported check was
incorrectly flagging it. Remove the warning banner entirely.

* feat(voice): add configurable summary length limit for TTS output

Add a slider (50-2000 chars) in voice settings to control max summary
length. The limit is passed through the summarize endpoint and speak
endpoint to the zen API prompt, with token budget scaled accordingly.

* fix(voice): add diagnostic logging and sanitize TTS fallback

Add console logging throughout the summarization flow (client + server)
to trace why text may not be summarized. Fix silent error swallowing in
/api/tts/speak. Always apply sanitizeForTTS even when summarization is
disabled so raw markdown/code is never spoken verbatim.

* fix(voice): fix token budget starving model of output tokens

max_output_tokens includes both reasoning and output tokens. With
effort:'low', reasoning alone consumes ~128 tokens, so a budget of
100 left zero tokens for the actual summary text. Use a fixed 1000
token budget (matching commit message generation) and control output
length via the prompt's character limit instruction instead.

* chore(voice): remove diagnostic logging from summarization flow

* fix(voice): don't request mic permission on mobile page load

Remove the useEffect that pre-requested microphone permission when the
BrowserVoiceButton component mounted on mobile. This caused an unwanted
permission prompt immediately on page load before the user tapped the
mic icon. Permission is now only requested on explicit user interaction.

* fix(voice): remove unused BrowserVoiceButton binding

* fix(voice): desktop mic flow + non-continuous draft mode

* fix(voice): stabilize continuous loop and polish controls

* feat(settings): mark voice section experimental

---------

Co-authored-by: Bohdan Triapitsyn <artmore@protonmail.com>
2026-02-09 23:55:10 +02:00

163 lines
4.0 KiB
JavaScript

/**
* Server-side Text-to-Speech Service
*
* Uses OpenAI's TTS API to generate audio on the server and stream it to clients.
* This bypasses mobile Safari's audio context restrictions.
*/
import OpenAI from 'openai';
import { readAuthFile } from './opencode-auth.js';
// Voice options from OpenAI
export const TTS_VOICES = [
'alloy', 'ash', 'ballad', 'coral', 'echo', 'fable',
'nova', 'onyx', 'sage', 'shimmer', 'verse', 'marin', 'cedar'
];
function getOpenAIApiKey() {
// First check environment variable
const envKey = process.env.OPENAI_API_KEY;
if (envKey) {
return envKey;
}
// Then check opencode auth file (same as usage tracker)
try {
const auth = readAuthFile();
// Check for openai, codex, or chatgpt aliases
const openaiAuth = auth.openai || auth.codex || auth.chatgpt;
if (openaiAuth) {
// Handle both string format (just the token) and object format
if (typeof openaiAuth === 'string') {
return openaiAuth;
}
// Try access token first (OAuth), then regular token
if (openaiAuth.access) {
return openaiAuth.access;
}
if (openaiAuth.token) {
return openaiAuth.token;
}
}
} catch (error) {
console.warn('[TTSService] Failed to read auth file:', error.message);
}
return null;
}
class TTSService {
constructor() {
this._client = null;
this._lastApiKey = null;
}
_getClient() {
const apiKey = getOpenAIApiKey();
// If API key changed or client doesn't exist, create new client
if (apiKey && (!this._client || this._lastApiKey !== apiKey)) {
this._client = new OpenAI({ apiKey });
this._lastApiKey = apiKey;
}
return this._client;
}
isAvailable() {
return this._getClient() !== null;
}
/**
* Generate speech and return as a stream
*/
async generateSpeechStream(options) {
const {
text,
voice = 'coral',
model = 'gpt-4o-mini-tts',
speed = 1.0,
instructions,
apiKey
} = options;
// Use provided API key or fall back to configured key
let client;
if (apiKey) {
client = new OpenAI({ apiKey });
} else {
client = this._getClient();
}
if (!client) {
throw new Error('OpenAI API key not configured. Set OPENAI_API_KEY environment variable, configure OpenAI in OpenCode, or provide an API key in settings.');
}
if (!text.trim()) {
throw new Error('Text is required for TTS');
}
try {
console.log('[TTSService] Generating speech with voice:', voice, 'model:', model);
const response = await client.audio.speech.create({
model,
voice,
input: text,
speed,
...(instructions && { instructions }),
response_format: 'mp3',
});
// Convert the response to a web stream
const stream = response.body;
return {
stream,
contentType: 'audio/mpeg',
};
} catch (error) {
console.error('[TTSService] Error generating speech:', error);
throw new Error(`Failed to generate speech: ${error.message || 'Unknown error'}`);
}
}
/**
* Generate speech and return as a buffer (for caching)
*/
async generateSpeechBuffer(options) {
const client = this._getClient();
if (!client) {
throw new Error('OpenAI API key not configured. Set OPENAI_API_KEY environment variable or configure OpenAI in OpenCode.');
}
const {
text,
voice = 'coral',
model = 'gpt-4o-mini-tts',
speed = 1.0,
instructions
} = options;
try {
const response = await client.audio.speech.create({
model,
voice,
input: text,
speed,
...(instructions && { instructions }),
response_format: 'mp3',
});
const arrayBuffer = await response.arrayBuffer();
return Buffer.from(arrayBuffer);
} catch (error) {
console.error('[TTSService] Error generating speech buffer:', error);
throw error;
}
}
}
// Export singleton instance
export const ttsService = new TTSService();
export { TTSService };