The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(voice): make "Test Key" a real dry run instead of a save
M3gA-Mindb750eeb393ab
diff --git a/app/src/components/settings/panels/VoicePanelKeyModal.tsx b/app/src/components/settings/panels/VoicePanelKeyModal.tsxindex c303040d36..1a091b12d2 100644--- a/app/src/components/settings/panels/VoicePanelKeyModal.tsx+++ b/app/src/components/settings/panels/VoicePanelKeyModal.tsx@@ -177,13 +177,22 @@ const VoicePanelKeyModal = ({setIsTestingKey(true);setKeyTestResult(null);try {- await handleEnableExternalProvider(pendingKeySlug, pendingKeyValue);+ // Test is a DRY RUN. It must not call+ // `handleEnableExternalProvider`: that writes the key to+ // the keychain and activates the provider before it is+ // known to work, and it clears `pendingKeySlug`, which+ // unmounts this modal — so the result below would be set+ // on a dead component and the user would never see it+ // (#5896). The candidate key goes to the core for+ // validation only; "Save & Enable" remains the one way to+ // commit it.const meta = BUILTIN_VOICE_PROVIDER_META[pendingKeySlug];const workload = meta?.capability === 'tts' ? 'tts' : 'stt';const result = await testVoiceProvider(workload as 'stt' | 'tts',pendingKeySlug,- true+ true,+ pendingKeyValue);setKeyTestResult(result);} catch (err) {diff --git a/app/src/components/settings/panels/__tests__/VoicePanel.test.tsx b/app/src/components/settings/panels/__tests__/VoicePanel.test.tsxindex 9450f62eff..76385728e0 100644--- a/app/src/components/settings/panels/__tests__/VoicePanel.test.tsx+++ b/app/src/components/settings/panels/__tests__/VoicePanel.test.tsx@@ -776,6 +776,89 @@ describe('VoicePanel', () => {await waitFor(() => expect(vi.mocked(setVoiceProviderKey)).toHaveBeenCalled());});+ // ─── Modal: "Test Key" is a dry run (#5896) ───────────────────────────────+ //+ // The regression these guard: the Test handler used to call+ // `handleEnableExternalProvider` before testing, which (a) wrote the key to+ // the keychain and activated the provider before it was known to work, and+ // (b) cleared `pendingKeySlug` — unmounting the modal, so the result alert+ // it then set could never render.++ it('clicking Test Key validates without saving or activating the provider', async () => {+ vi.mocked(testVoiceProvider).mockResolvedValueOnce({ ok: true, detail: 'Key OK' });++ renderWithProviders(<VoicePanel />, { initialEntries: ['/settings/voice'] });++ await screen.findByTestId('voice-providers-section');+ fireEvent.click(screen.getByTestId('voice-provider-chip-elevenlabs'));+ await screen.findByTestId('voice-provider-key-modal');++ const keyInput = screen.getByPlaceholderText(/sk/i);+ fireEvent.change(keyInput, { target: { value: 'sk-candidate-key-1234567890' } });++ fireEvent.click(screen.getByRole('button', { name: /^Test Key$/i }));++ await waitFor(() => expect(vi.mocked(testVoiceProvider)).toHaveBeenCalled());++ // The candidate key travels to the core for validation only.+ expect(vi.mocked(testVoiceProvider)).toHaveBeenCalledWith(+ 'stt',+ 'elevenlabs',+ true,+ 'sk-candidate-key-1234567890'+ );++ // Nothing is persisted and nothing is activated by a test.+ expect(vi.mocked(setVoiceProviderKey)).not.toHaveBeenCalled();+ expect(vi.mocked(saveVoiceSettings)).not.toHaveBeenCalled();+ });++ it('keeps the modal mounted after Test Key so the result is visible', async () => {+ vi.mocked(testVoiceProvider).mockResolvedValueOnce({+ ok: true,+ detail: 'Provider key is valid (12ms)',+ });++ renderWithProviders(<VoicePanel />, { initialEntries: ['/settings/voice'] });++ await screen.findByTestId('voice-providers-section');+ fireEvent.click(screen.getByTestId('voice-provider-chip-elevenlabs'));+ await screen.findByTestId('voice-provider-key-modal');++ fireEvent.change(screen.getByPlaceholderText(/sk/i), {+ target: { value: 'sk-candidate-key-1234567890' },+ });+ fireEvent.click(screen.getByRole('button', { name: /^Test Key$/i }));++ // The alert is the whole point of the button — if the modal has unmounted+ // by the time the result lands, this text never appears.+ expect(await screen.findByText(/Provider key is valid/i)).toBeInTheDocument();+ expect(screen.getByTestId('voice-provider-key-modal')).toBeInTheDocument();+ });++ it('surfaces a failed Test Key without saving the bad key', async () => {+ vi.mocked(testVoiceProvider).mockResolvedValueOnce({+ ok: false,+ detail: 'Key test failed: API returned 401 Unauthorized',+ });++ renderWithProviders(<VoicePanel />, { initialEntries: ['/settings/voice'] });++ await screen.findByTestId('voice-providers-section');+ fireEvent.click(screen.getByTestId('voice-provider-chip-elevenlabs'));+ await screen.findByTestId('voice-provider-key-modal');++ fireEvent.change(screen.getByPlaceholderText(/sk/i), {+ target: { value: 'sk-wrong-key-1234567890' },+ });+ fireEvent.click(screen.getByRole('button', { name: /^Test Key$/i }));++ expect(await screen.findByText(/401 Unauthorized/i)).toBeInTheDocument();+ // The user is left free to correct the key: it was never written.+ expect(vi.mocked(setVoiceProviderKey)).not.toHaveBeenCalled();+ expect(screen.getByTestId('voice-provider-key-modal')).toBeInTheDocument();+ });+it('the ElevenLabs modal Cancel button closes without saving', async () => {renderWithProviders(<VoicePanel />, { initialEntries: ['/settings/voice'] });diff --git a/app/src/services/api/voiceSettingsApi.ts b/app/src/services/api/voiceSettingsApi.tsindex b8fb93aa88..c6ae74af32 100644--- a/app/src/services/api/voiceSettingsApi.ts+++ b/app/src/services/api/voiceSettingsApi.ts@@ -221,14 +221,32 @@ function stripLogPrefix(s: string): string {return s.replace(/^\[voice-(?:stt|tts|factory)\]\s*/i, '');}+/**+ * Test a voice provider.+ *+ * With `validateOnly`, the core does a lightweight authenticated GET instead of+ * a real transcription/synthesis, and `apiKey` lets the caller check a key the+ * user has typed but not yet saved — the key is validated and discarded, never+ * written to the keychain (#5896).+ */export async function testVoiceProvider(workload: VoiceWorkloadId,provider: string,- validateOnly = false+ validateOnly = false,+ apiKey?: string): Promise<VoiceTestResult> {const result = await callCoreRpc<VoiceTestResult>({method: 'openhuman.voice_test_provider',- params: { workload, provider, validate_only: validateOnly },+ params: {+ workload,+ provider,+ validate_only: validateOnly,+ // Omit rather than send an empty string: the core reads an empty+ // candidate as "fall back to the stored credential", and sending one+ // for a provider with no stored key would report a confusing+ // "no API key configured" instead of the real validation result.+ ...(apiKey?.trim() ? { api_key: apiKey } : {}),+ },timeoutMs: VOICE_TEST_TIMEOUT_MS,});return { ...result, detail: stripLogPrefix(result.detail) };diff --git a/src/openhuman/voice/README.md b/src/openhuman/voice/README.mdindex 3b1192ab4a..96d2e25ba9 100644--- a/src/openhuman/voice/README.md+++ b/src/openhuman/voice/README.md@@ -57,7 +57,7 @@ Namespace `voice` (registered in `all_voice_registered_controllers`):| `voice.set_providers` | Persist STT/TTS provider + model/voice into `config.local_ai.*`. || `voice.update_provider_settings` | Persist the voice provider registry + routing strings (mirrors inference model settings). || `voice.list_models` | List models/voices for a provider (static presets for built-in slugs). |-| `voice.test_provider` | Test/validate a provider endpoint (silent-WAV STT, "Hello" TTS, or key-only validate). |+| `voice.test_provider` | Test/validate a provider endpoint (silent-WAV STT, "Hello" TTS, or key-only validate). `validate_only` is a dry run for **both** workloads and accepts an `api_key` to check a candidate credential without storing it. || `voice.server_start` / `voice.server_stop` / `voice.server_status` | Control the global dictation server. || `voice.overlay_stt_notify` | Bridge chat-button STT state transitions into the dictation/transcription buses. |diff --git a/src/openhuman/voice/schemas/handlers/provider_server.rs b/src/openhuman/voice/schemas/handlers/provider_server.rsindex c007d952f9..b9d039e6a9 100644--- a/src/openhuman/voice/schemas/handlers/provider_server.rs+++ b/src/openhuman/voice/schemas/handlers/provider_server.rs@@ -6,8 +6,8 @@ use crate::core::all::ControllerFuture;use crate::openhuman::config::rpc as config_rpc;use crate::openhuman::voice::schemas::helpers::{- deserialize_params, generate_silent_wav, validate_stt_provider, validate_tts_provider,- validate_tts_provider_key,+ deserialize_params, generate_silent_wav, validate_provider_key, validate_stt_provider,+ validate_tts_provider,};use crate::openhuman::voice::schemas::params::{OverlaySttNotifyParams, OverlaySttState, SetProvidersParams, VoiceListModelsParams,@@ -303,82 +303,97 @@ pub(crate) fn handle_voice_test_provider(params: Map<String, Value>) -> Controlllet start = std::time::Instant::now();log::debug!(- "[voice-factory] voice_test_provider workload={} provider={}",+ "[voice-factory] voice_test_provider workload={} provider={} validate_only={} \+ candidate_key={}",p.workload,- p.provider+ p.provider,+ p.validate_only,+ p.api_key.is_some());- match p.workload.as_str() {- "stt" => {- let provider =- crate::openhuman::voice::create_stt_provider(&p.provider, "", &config)- .map_err(|e| e.to_string())?;-- // 0.1s of silence as WAV (16kHz mono 16-bit PCM) so the local- // The selected engine can transcribe it without an- // external binary (issue #3425).- let silent_wav = generate_silent_wav();- let audio_b64 = {- use base64::Engine;- base64::engine::general_purpose::STANDARD.encode(&silent_wav)- };+ if !matches!(p.workload.as_str(), "stt" | "tts") {+ return Err(format!(+ "invalid workload '{}' (valid: 'stt', 'tts')",+ p.workload+ ));+ }- match provider- .transcribe(&config, &audio_b64, Some("audio/wav"), None, Some("en"))- .await- {- Ok(_outcome) => {- let elapsed = start.elapsed().as_millis();- Ok(serde_json::json!({- "ok": true,- "detail": format!("STT test passed ({elapsed}ms)"),- "latency_ms": elapsed,- }))- }- Err(e) => Ok(serde_json::json!({- "ok": false,- "detail": format!("STT test failed: {e}"),- })),+ let trimmed = p.provider.trim();++ // `validate_only` is a **dry run** and is honoured for both workloads.+ // It used to be checked inside the "tts" arm alone, which made it a+ // silent no-op for STT — and every provider the settings modal can+ // reach maps to the "stt" workload, so the modal's dry-run request was+ // always answered with a live transcription (#5896).+ //+ // Reserved slugs (`cloud`/`openhuman`/`backend`/`piper`/`whisper`/+ // `local`/empty) have no user-held API key to check, so they fall+ // through to the live test, where the factory reports misconfiguration+ // by name.+ if p.validate_only && !crate::openhuman::config::schema::is_voice_slug_reserved(trimmed) {+ return match validate_provider_key(trimmed, &config, p.api_key.as_deref()).await {+ Ok(detail) => {+ let elapsed = start.elapsed().as_millis();+ Ok(serde_json::json!({+ "ok": true,+ "detail": format!("{detail} ({elapsed}ms)"),+ "latency_ms": elapsed,+ }))}- }- "tts" => {- let trimmed = p.provider.trim();- if p.validate_only && !matches!(trimmed, "cloud" | "openhuman" | "piper" | "") {- match validate_tts_provider_key(trimmed, &config).await {- Ok(detail) => {- let elapsed = start.elapsed().as_millis();- Ok(serde_json::json!({- "ok": true,- "detail": format!("{detail} ({elapsed}ms)"),- "latency_ms": elapsed,- }))- }- Err(e) => Ok(serde_json::json!({- "ok": false,- "detail": format!("TTS test failed: {e}"),- })),- }- } else {- let provider =- crate::openhuman::voice::create_tts_provider(trimmed, "", &config)- .map_err(|e| e.to_string())?;- match provider.synthesize(&config, "Hello", None).await {- Ok(_outcome) => {- let elapsed = start.elapsed().as_millis();- Ok(serde_json::json!({- "ok": true,- "detail": format!("TTS test passed ({elapsed}ms)"),- "latency_ms": elapsed,- }))- }- Err(e) => Ok(serde_json::json!({- "ok": false,- "detail": format!("TTS test failed: {e}"),- })),- }+ Err(e) => Ok(serde_json::json!({+ "ok": false,+ "detail": format!("Key test failed: {e}"),+ })),+ };+ }++ if p.workload == "stt" {+ let provider = crate::openhuman::voice::create_stt_provider(&p.provider, "", &config)+ .map_err(|e| e.to_string())?;++ // 0.1s of silence as WAV (16kHz mono 16-bit PCM) so the local+ // The selected engine can transcribe it without an+ // external binary (issue #3425).+ let silent_wav = generate_silent_wav();+ let audio_b64 = {+ use base64::Engine;+ base64::engine::general_purpose::STANDARD.encode(&silent_wav)+ };++ return match provider+ .transcribe(&config, &audio_b64, Some("audio/wav"), None, Some("en"))+ .await+ {+ Ok(_outcome) => {+ let elapsed = start.elapsed().as_millis();+ Ok(serde_json::json!({+ "ok": true,+ "detail": format!("STT test passed ({elapsed}ms)"),+ "latency_ms": elapsed,+ }))}+ Err(e) => Ok(serde_json::json!({+ "ok": false,+ "detail": format!("STT test failed: {e}"),+ })),+ };+ }++ let provider = crate::openhuman::voice::create_tts_provider(trimmed, "", &config)+ .map_err(|e| e.to_string())?;+ match provider.synthesize(&config, "Hello", None).await {+ Ok(_outcome) => {+ let elapsed = start.elapsed().as_millis();+ Ok(serde_json::json!({+ "ok": true,+ "detail": format!("TTS test passed ({elapsed}ms)"),+ "latency_ms": elapsed,+ }))}- other => Err(format!("invalid workload '{other}' (valid: 'stt', 'tts')")),+ Err(e) => Ok(serde_json::json!({+ "ok": false,+ "detail": format!("TTS test failed: {e}"),+ })),}})}diff --git a/src/openhuman/voice/schemas/helpers.rs b/src/openhuman/voice/schemas/helpers.rsindex 79e9c3df01..9ed1713628 100644--- a/src/openhuman/voice/schemas/helpers.rs+++ b/src/openhuman/voice/schemas/helpers.rs@@ -104,32 +104,52 @@ pub(super) fn effective_tts_provider(config: &crate::openhuman::config::Config)crate::openhuman::voice::effective_tts_provider(config)}-/// Validate a TTS provider's API key by hitting a lightweight read-only endpoint-/// rather than synthesizing audio (which requires a valid voice ID).-pub(super) async fn validate_tts_provider_key(+/// Validate a voice provider's API key by hitting a lightweight read-only+/// endpoint rather than synthesizing audio or transcribing a clip (both of+/// which need a valid voice/model id, and both of which cost the user a real+/// inference call just to answer "is this key good?").+///+/// `candidate_key` makes this a **dry run**: when the caller supplies a key,+/// it is validated as-is and nothing is read from the keychain, so the settings+/// modal can check a key the user typed *before* deciding to store it (#5896).+/// Passing `None` falls back to the stored credential for the slug, which is+/// what the already-configured "Test" buttons in the routing section want.+///+/// Likewise the endpoint is resolved from `config.voice_providers` when the+/// provider is already registered, and from `builtin_voice_provider`+/// otherwise — a first-time key check happens before any config entry exists.+pub(super) async fn validate_provider_key(provider: &str,config: &crate::openhuman::config::Config,+ candidate_key: Option<&str>,) -> Result<String, String> {+ use crate::openhuman::config::schema::voice_providers::builtin_voice_provider;+let (slug, _model) = if let Some(pos) = provider.find(':') {(&provider[..pos], &provider[pos + 1..])} else {(provider, "")};- let entry = config+ let endpoint = config.voice_providers.iter().find(|p| p.slug == slug)+ .map(|p| p.endpoint.as_str())+ .or_else(|| builtin_voice_provider(slug).map(|b| b.endpoint)).ok_or_else(|| format!("no voice provider with slug '{slug}'"))?;- let api_key = crate::openhuman::inference::provider::factory::lookup_key_for_slug(slug, config)- .unwrap_or_default();+ let api_key = match candidate_key.map(str::trim) {+ Some(k) if !k.is_empty() => k.to_string(),+ _ => crate::openhuman::inference::provider::factory::lookup_key_for_slug(slug, config)+ .unwrap_or_default(),+ };if api_key.is_empty() {return Err("no API key configured for this provider".to_string());}- let endpoint = entry.endpoint.trim_end_matches('/');+ let endpoint = endpoint.trim_end_matches('/');let client = reqwest::Client::new();// ElevenLabs: GET /user/subscription requires only basic auth (no@@ -140,12 +160,19 @@ pub(super) async fn validate_tts_provider_key(format!("{endpoint}/models")};- let mut req = client.get(&url);- if slug == "elevenlabs" {- req = req.header("xi-api-key", &api_key);- } else {- req = req.header("Authorization", format!("Bearer {api_key}"));- }+ // Auth headers must match what the real providers send, or a valid key+ // reads as invalid. Deepgram in particular uses `Token`, not `Bearer`+ // (see `factory::stt_providers`) — validating it as Bearer would 401 on+ // a perfectly good key.+ let req = match slug {+ "elevenlabs" => client.get(&url).header("xi-api-key", &api_key),+ "deepgram" => client+ .get(&url)+ .header("Authorization", format!("Token {api_key}")),+ _ => client+ .get(&url)+ .header("Authorization", format!("Bearer {api_key}")),+ };let resp = req.send()@@ -153,7 +180,7 @@ pub(super) async fn validate_tts_provider_key(.map_err(|e| format!("request failed: {e}"))?;if resp.status().is_success() {- Ok("TTS provider key is valid".to_string())+ Ok("Provider key is valid".to_string())} else {let status = resp.status();let body = resp.text().await.unwrap_or_default();diff --git a/src/openhuman/voice/schemas/params.rs b/src/openhuman/voice/schemas/params.rsindex d5642b5f39..19156662e4 100644--- a/src/openhuman/voice/schemas/params.rs+++ b/src/openhuman/voice/schemas/params.rs@@ -148,7 +148,11 @@ pub(super) struct VoiceListModelsParams {}/// Test a voice provider endpoint.-#[derive(Debug, Deserialize)]+///+/// `Debug` is implemented by hand rather than derived: `api_key` carries a raw+/// user credential, and a derived `Debug` would print it in full the first time+/// anyone adds a `{:?}` of this struct to a log line.+#[derive(Deserialize)]pub(super) struct VoiceTestProviderParams {pub(super) workload: String,pub(super) provider: String,@@ -156,6 +160,23 @@ pub(super) struct VoiceTestProviderParams {/// synthesizing or transcribing. Used by the provider-enable modal.#[serde(default)]pub(super) validate_only: bool,+ /// Candidate API key to validate **without storing it**, so the+ /// provider-enable modal can check a key before the user commits to+ /// saving it (#5896). Omitted means "use the stored credential for this+ /// provider's slug". Only consulted when `validate_only` is set.+ #[serde(default)]+ pub(super) api_key: Option<String>,+}++impl std::fmt::Debug for VoiceTestProviderParams {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("VoiceTestProviderParams")+ .field("workload", &self.workload)+ .field("provider", &self.provider)+ .field("validate_only", &self.validate_only)+ .field("api_key", &self.api_key.as_ref().map(|_| "[REDACTED]"))+ .finish()+ }}#[derive(Debug, Deserialize)]diff --git a/src/openhuman/voice/schemas/registry.rs b/src/openhuman/voice/schemas/registry.rsindex a72a796124..0c41a79f89 100644--- a/src/openhuman/voice/schemas/registry.rs+++ b/src/openhuman/voice/schemas/registry.rs@@ -322,7 +322,9 @@ pub fn voice_schemas(function: &str) -> ControllerSchema {function: "test_provider",description:"Test a voice provider endpoint without saving. STT transcribes a \- silent audio clip; TTS synthesizes 'Hello' and discards.",+ silent audio clip; TTS synthesizes 'Hello' and discards. With \+ `validate_only` it is a dry run: a lightweight authenticated GET, \+ no inference call and nothing persisted.",inputs: vec![required_string("workload", "Workload to test: 'stt' or 'tts'."),required_string(@@ -331,7 +333,14 @@ pub fn voice_schemas(function: &str) -> ControllerSchema {),optional_bool("validate_only",- "When true, only validate the API key without synthesizing/transcribing.",+ "When true, only validate the API key without synthesizing/transcribing. \+ Honoured for both workloads.",+ ),+ optional_string(+ "api_key",+ "Candidate API key to validate without storing it, so a key can be \+ checked before the user commits to saving it. Omit to use the stored \+ credential. Only read when `validate_only` is true.",),],outputs: vec![json_output(diff --git a/src/openhuman/voice/schemas_tests.rs b/src/openhuman/voice/schemas_tests.rsindex 326dc05984..e6cbd7cbf8 100644--- a/src/openhuman/voice/schemas_tests.rs+++ b/src/openhuman/voice/schemas_tests.rs@@ -485,6 +485,58 @@ fn deserialize_voice_test_provider_params() {let parsed = deserialize_params::<VoiceTestProviderParams>(params).unwrap();assert_eq!(parsed.workload, "stt");assert_eq!(parsed.provider, "deepgram:nova-2");+ // Absent `api_key` means "use the stored credential", not "empty key".+ assert_eq!(parsed.api_key, None);+ assert!(!parsed.validate_only);+}++#[test]+fn deserialize_voice_test_provider_params_accepts_candidate_key() {+ let params = Map::from_iter([+ ("workload".to_string(), json!("stt")),+ ("provider".to_string(), json!("elevenlabs")),+ ("validate_only".to_string(), json!(true)),+ ("api_key".to_string(), json!("sk-candidate-not-yet-saved")),+ ]);+ let parsed = deserialize_params::<VoiceTestProviderParams>(params).unwrap();+ assert!(parsed.validate_only);+ assert_eq!(+ parsed.api_key.as_deref(),+ Some("sk-candidate-not-yet-saved")+ );+}++#[test]+fn voice_test_provider_params_debug_redacts_the_candidate_key() {+ let params = Map::from_iter([+ ("workload".to_string(), json!("stt")),+ ("provider".to_string(), json!("elevenlabs")),+ ("api_key".to_string(), json!("sk-super-secret-value")),+ ]);+ let parsed = deserialize_params::<VoiceTestProviderParams>(params).unwrap();+ let rendered = format!("{parsed:?}");+ assert!(+ !rendered.contains("sk-super-secret-value"),+ "Debug must never render the raw key: {rendered}"+ );+ assert!(rendered.contains("[REDACTED]"), "got: {rendered}");+ // The non-secret fields still have to be debuggable, or the manual impl+ // has traded a leak for an undiagnosable handler.+ assert!(rendered.contains("elevenlabs"), "got: {rendered}");+}++#[test]+fn test_provider_schema_exposes_the_dry_run_candidate_key() {+ let s = voice_schemas("voice_test_provider");+ let api_key = s+ .inputs+ .iter()+ .find(|i| i.name == "api_key")+ .expect("voice_test_provider must accept a candidate api_key for the dry run");+ assert!(+ !api_key.required,+ "api_key is optional — omitting it means 'use the stored credential'"+ );}#[test]