The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): warm local STT on mic-open so cold model load stops timing out transcription (#105955)
BrunoBza5f23cac56833
diff --git a/apps/desktop/src/api/system.ts b/apps/desktop/src/api/system.tsindex 47d2636f2bc..78de73ebd47 100644--- a/apps/desktop/src/api/system.ts+++ b/apps/desktop/src/api/system.ts@@ -2,6 +2,7 @@ import type {ActionResponse,ActionStatusResponse,AudioSpeakResponse,+ AudioSttLeaseResponse,AudioTranscriptionResponse,AudioTtsLeaseResponse,BackendUpdateCheckResponse,@@ -219,6 +220,27 @@ export function setTtsLease(lease: string, active: boolean): Promise<AudioTtsLea})}+// Same cold-start class as TTS: acquiring a lease pre-loads the local STT+// model (first-use download + load), which on CPU-bound hosts can exceed the+// transcription floor on its own (issue #105955). The desktop acquires when+// the mic opens so the load happens while the user is still speaking.+export const AUDIO_STT_LEASE_REQUEST_TIMEOUT_MS = 180_000++/**+ * Tell the backend a voice-input session started (`active: true`) so it can+ * warm the STT engine, or ended (`active: false`) to drop the lease.+ * `lease` names the session — `desktop:voice-input:<renderer>`.+ */+export function setSttLease(lease: string, active: boolean): Promise<AudioSttLeaseResponse> {+ return hermesApi<AudioSttLeaseResponse>({+ ...profileScoped(),+ path: '/api/audio/stt-lease',+ method: 'POST',+ body: { active, lease },+ timeoutMs: AUDIO_STT_LEASE_REQUEST_TIMEOUT_MS+ })+}+export function getElevenLabsVoices(profile?: null | string): Promise<ElevenLabsVoicesResponse> {return hermesApi<ElevenLabsVoicesResponse>({path: '/api/audio/elevenlabs/voices',diff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.ts b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.tsindex 4b1aeab50b2..ae61ea6f93e 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.ts@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'import { useI18n } from '@/i18n'import { IncrementalSpeechSentenceBuffer } from '@/lib/speech-text'+import { syncSttLease, VOICE_INPUT_LEASE } from '@/lib/stt-lease'import { startThinkingSound, stopThinkingSound } from '@/lib/thinking-sound'import { monitorSpeechDuringPlayback } from '@/lib/voice-barge-in'import {@@ -312,6 +313,10 @@ export function useVoiceConversation({onSilence: () => void handleTurn()})setStatus('listening')+ // Same warm-up as push-to-talk dictation: a cold local model loads while+ // the user speaks instead of inside the transcription timeout (#105955).+ // Deduped with the recorder's lease — one warm-up per renderer.+ void syncSttLease(VOICE_INPUT_LEASE, true)// Clear any prior turn-timeout before arming a fresh one. Each listen// cycle reassigns turnTimeoutRef; without clearing first, a stale 60s// timer from an earlier cycle survives and later fires handleTurn() in@@ -799,6 +804,10 @@ export function useVoiceConversation({awaitingSpokenResponseRef.current = falsedropSpeechSession()consumePendingResponse()+ // Conversation over: drop the STT lease. One lease is shared per renderer,+ // so a concurrent dictation session re-acquires on its next start; the+ // backend keeps the model resident regardless of the count.+ void syncSttLease(VOICE_INPUT_LEASE, false)setMuted(false)setStatus('idle')}, [consumePendingResponse, handle])diff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-recorder.ts b/apps/desktop/src/app/chat/composer/hooks/use-voice-recorder.tsindex ce18316e322..02218fe323a 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-voice-recorder.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-recorder.ts@@ -1,6 +1,7 @@import { useEffect, useRef, useState } from 'react'import { useI18n } from '@/i18n'+import { syncSttLease, VOICE_INPUT_LEASE } from '@/lib/stt-lease'import { recordFeatureUse } from '@/store/desktop-metrics'import { notify, notifyError } from '@/store/notifications'@@ -74,6 +75,9 @@ export function useVoiceRecorder({notifyError(error, voiceCopy.transcriptionFailed)} finally {setVoiceStatus('idle')+ // The transcript settled (or failed): this session no longer needs the+ // engine held. The backend keeps the shared model resident regardless.+ void syncSttLease(VOICE_INPUT_LEASE, false)focusInput()}}@@ -87,6 +91,11 @@ export function useVoiceRecorder({try {await handle.start({ onError: error => notifyError(error, voiceCopy.recordingFailed) })+ // The mic is open, so a transcript is coming: warm the backend's STT+ // engine now so a cold local model loads while the user is still+ // speaking instead of inside the transcription timeout (#105955).+ // Fire-and-forget — recording must not wait on (or fail with) warm-up.+ void syncSttLease(VOICE_INPUT_LEASE, true)startedAtRef.current = Date.now()setElapsedSeconds(0)setVoiceStatus('recording')diff --git a/apps/desktop/src/hermes.test.ts b/apps/desktop/src/hermes.test.tsindex 6a052b509cf..8b8d3fcfecd 100644--- a/apps/desktop/src/hermes.test.ts+++ b/apps/desktop/src/hermes.test.ts@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import {AUDIO_SPEAK_MAX_REQUEST_TIMEOUT_MS,AUDIO_SPEAK_MIN_REQUEST_TIMEOUT_MS,+ AUDIO_STT_LEASE_REQUEST_TIMEOUT_MS,AUDIO_TRANSCRIBE_MAX_REQUEST_TIMEOUT_MS,AUDIO_TRANSCRIBE_MIN_REQUEST_TIMEOUT_MS,audioSpeakRequestTimeoutMs,@@ -27,7 +28,9 @@ import {resetSidebarBatchCapability,setApiRequestConnection,setApiRequestProfile,+ setSttLease,speakText,+ transcribeAudio,triggerCronJob} from './hermes'import { $transcriptTailBySessionId, transcriptTailState } from './store/transcript-tail'@@ -649,6 +652,48 @@ describe('Hermes REST helpers', () => {expect(audioTranscribeRequestTimeoutMs('x'.repeat(9_000_000))).toBe(AUDIO_TRANSCRIBE_MAX_REQUEST_TIMEOUT_MS)})+ it('uses an extended timeout for blocking transcription', async () => {+ api.mockResolvedValueOnce({+ ok: true,+ provider: 'openai',+ text: 'transcribed text'+ })++ await expect(transcribeAudio('data:audio/webm;base64,AA==', 'audio/webm')).resolves.toEqual({+ ok: true,+ provider: 'openai',+ text: 'transcribed text'+ })++ expect(api).toHaveBeenCalledWith({+ body: { data_url: 'data:audio/webm;base64,AA==', mime_type: 'audio/webm' },+ method: 'POST',+ path: '/api/audio/transcribe',+ timeoutMs: AUDIO_TRANSCRIBE_MIN_REQUEST_TIMEOUT_MS+ })+ })++ it('routes STT lease acquire/release to the stt-lease endpoint with a warm-up budget', async () => {+ api.mockResolvedValueOnce({ ok: true })+ api.mockResolvedValueOnce({ ok: true })++ await setSttLease('desktop:voice-input:abc', true)+ await setSttLease('desktop:voice-input:abc', false)++ expect(api).toHaveBeenNthCalledWith(1, {+ body: { active: true, lease: 'desktop:voice-input:abc' },+ method: 'POST',+ path: '/api/audio/stt-lease',+ timeoutMs: AUDIO_STT_LEASE_REQUEST_TIMEOUT_MS+ })+ expect(api).toHaveBeenNthCalledWith(2, {+ body: { active: false, lease: 'desktop:voice-input:abc' },+ method: 'POST',+ path: '/api/audio/stt-lease',+ timeoutMs: AUDIO_STT_LEASE_REQUEST_TIMEOUT_MS+ })+ })+it('defaults model options to configured providers only', async () => {await getGlobalModelOptions()diff --git a/apps/desktop/src/lib/stt-lease.test.ts b/apps/desktop/src/lib/stt-lease.test.tsnew file mode 100644index 00000000000..460c886643c--- /dev/null+++ b/apps/desktop/src/lib/stt-lease.test.ts@@ -0,0 +1,105 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const setSttLease = vi.fn(async (_lease: string, _active: boolean) => ({ ok: true }))++vi.mock('@/hermes', () => ({+ setSttLease: (lease: string, active: boolean) => setSttLease(lease, active)+}))++import { resetSttLeasesForTests, syncSttLease, VOICE_INPUT_LEASE } from './stt-lease'++describe('syncSttLease', () => {+ beforeEach(() => {+ resetSttLeasesForTests()+ setSttLease.mockReset()+ setSttLease.mockImplementation(async () => ({ ok: true }))+ })++ afterEach(() => {+ resetSttLeasesForTests()+ })++ it('acquires on the first on and releases on off', async () => {+ await syncSttLease(VOICE_INPUT_LEASE, true)+ await syncSttLease(VOICE_INPUT_LEASE, false)++ expect(setSttLease.mock.calls).toEqual([+ [VOICE_INPUT_LEASE, true],+ [VOICE_INPUT_LEASE, false]+ ])+ })++ it('skips an initial off — never releases a lease it did not hold', async () => {+ await syncSttLease(VOICE_INPUT_LEASE, false)++ expect(setSttLease).not.toHaveBeenCalled()+ })++ it('dedupes a repeat of the last sent state', async () => {+ await syncSttLease(VOICE_INPUT_LEASE, true)+ await syncSttLease(VOICE_INPUT_LEASE, true)+ await syncSttLease(VOICE_INPUT_LEASE, true)++ expect(setSttLease).toHaveBeenCalledTimes(1)+ })++ it('queues an off behind an in-flight on so the wire never sees them reordered', async () => {+ let finishAcquire: () => void = () => undefined+ setSttLease.mockImplementationOnce(+ () =>+ new Promise(resolve => {+ finishAcquire = () => resolve({ ok: true })+ })+ )++ const on = syncSttLease(VOICE_INPUT_LEASE, true)+ // Let the acquire actually go out (it runs on a microtask).+ await Promise.resolve()+ expect(setSttLease.mock.calls).toEqual([[VOICE_INPUT_LEASE, true]])++ const off = syncSttLease(VOICE_INPUT_LEASE, false)+ await Promise.resolve()+ // Still only the acquire — the release waits for it to finish.+ expect(setSttLease).toHaveBeenCalledTimes(1)++ finishAcquire()+ await Promise.all([on, off])++ expect(setSttLease.mock.calls).toEqual([+ [VOICE_INPUT_LEASE, true],+ [VOICE_INPUT_LEASE, false]+ ])+ })++ it('coalesces a flip that reverses before its call went out — latest intent wins', async () => {+ const on = syncSttLease(VOICE_INPUT_LEASE, true)+ const off = syncSttLease(VOICE_INPUT_LEASE, false)+ await Promise.all([on, off])++ // The acquire never had a chance to go out; only the terminal state is sent+ // (a release of a never-held lease is a backend no-op).+ expect(setSttLease.mock.calls).toEqual([[VOICE_INPUT_LEASE, false]])+ })++ it('forgets the sent state on failure so the next flip retries', async () => {+ setSttLease.mockImplementationOnce(async () => {+ throw new Error('backend not ready')+ })++ await expect(syncSttLease(VOICE_INPUT_LEASE, true)).resolves.toBeUndefined()+ await syncSttLease(VOICE_INPUT_LEASE, true)++ expect(setSttLease).toHaveBeenCalledTimes(2)+ })++ it('never rejects — recording must not depend on warm-up', async () => {+ setSttLease.mockRejectedValue(new Error('backend gone'))++ await expect(syncSttLease(VOICE_INPUT_LEASE, true)).resolves.toBeUndefined()+ await expect(syncSttLease(VOICE_INPUT_LEASE, false)).resolves.toBeUndefined()+ })++ it('voice-input lease is per renderer', () => {+ expect(VOICE_INPUT_LEASE).toMatch(/^desktop:voice-input:[a-z0-9]+$/)+ })+})diff --git a/apps/desktop/src/lib/stt-lease.ts b/apps/desktop/src/lib/stt-lease.tsnew file mode 100644index 00000000000..88fcdf0b88f--- /dev/null+++ b/apps/desktop/src/lib/stt-lease.ts@@ -0,0 +1,75 @@+import { setSttLease } from '@/hermes'++// The desktop's voice-input sessions — push-to-talk dictation and the voice+// conversation loop — are the user telling us STT is about to be needed (or no+// longer is). The backend turns that into engine lifecycle: acquiring a lease+// pre-loads the local faster-whisper model (first-use download + load) so the+// transcription request starts hot instead of paying the cold cost inside its+// timeout (issue #105955); releasing drops the refcount but keeps the shared+// model resident for the gateway/CLI surfaces.+//+// This module is the renderer's single choke point for that signal. It dedupes+// (recorder and conversation loop observe the same mic session), serializes+// per lease so a fast on→off→on can't be reordered on the wire, and never+// surfaces failures — warm-up is an optimization; recording must not depend+// on it.++// Per-renderer id so two windows recording at once hold DISTINCT leases —+// window A finishing must not release the engine window B is still using.+const RENDERER_ID = Math.random().toString(36).slice(2, 10)++export const VOICE_INPUT_LEASE = `desktop:voice-input:${RENDERER_ID}`++const sent = new Map<string, boolean>()+const inFlight = new Map<string, Promise<void>>()++/**+ * Bring the backend's view of `lease` in line with `active`. Idempotent: a+ * repeat of the last sent state is a no-op. The initial `false` (nothing was+ * ever acquired) is also skipped — releasing a lease we never held would only+ * churn the backend on app start.+ */+export function syncSttLease(lease: string, active: boolean): Promise<void> {+ const last = sent.get(lease)++ if (last === active || (last === undefined && !active)) {+ return inFlight.get(lease) ?? Promise.resolve()+ }++ sent.set(lease, active)++ const previous = inFlight.get(lease) ?? Promise.resolve()++ const next = previous+ .then(async () => {+ // Latest intent wins: if the lease flipped again while we were queued,+ // the newer call sends its own state and this one has nothing to say.+ if (sent.get(lease) !== active) {+ return+ }++ await setSttLease(lease, active)+ })+ .catch(() => {+ // Backend not up yet / older backend without the endpoint / warm-up+ // failure: forget what we "sent" so the next flip retries honestly.+ if (sent.get(lease) === active) {+ sent.delete(lease)+ }+ })+ .finally(() => {+ if (inFlight.get(lease) === next) {+ inFlight.delete(lease)+ }+ })++ inFlight.set(lease, next)++ return next+}++/** Test seam — forget every sent state. */+export function resetSttLeasesForTests() {+ sent.clear()+ inFlight.clear()+}diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.tsindex bab1d31360f..a2f6e1f7c03 100644--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@ -50,6 +50,19 @@ export interface AudioTtsLeaseResponse {error?: string}+/** `POST /api/audio/stt-lease` — local STT pre-load driven by voice-input sessions. */+export interface AudioSttLeaseResponse {+ ok: boolean+ lease: string+ active: boolean+ /** Live lease holders after this call (null when the backend call itself failed). */+ leases: null | number+ /** Warm-up outcome: `loaded` | `cached` | `noop` | `error`. Release carries no action. */+ action?: string+ provider?: string+ error?: string+}+export interface ElevenLabsVoice {label: stringname: stringdiff --git a/hermes_cli/web_models.py b/hermes_cli/web_models.pyindex 29f1fd3572b..202a629694f 100644--- a/hermes_cli/web_models.py+++ b/hermes_cli/web_models.py@@ -246,6 +246,13 @@ class TTSLeaseRequest(BaseModel):lease: stractive: bool = True+class STTLeaseRequest(BaseModel):+ """POST /api/audio/stt-lease: ``lease`` names the voice-input session holding the lease+ (``desktop:voice-input:<renderer>``); ``active`` True acquires + pre-loads the local+ STT model, False releases. Unlike TTS, release never unloads (shared engine)."""+ lease: str+ active: bool = True+class OAuthSubmitBody(BaseModel):session_id: strcode: strdiff --git a/hermes_cli/web_routers/audio.py b/hermes_cli/web_routers/audio.pyindex 49ecb88cd3c..b8c6edefef0 100644--- a/hermes_cli/web_routers/audio.py+++ b/hermes_cli/web_routers/audio.py@@ -22,7 +22,13 @@ from hermes_cli.web_deps import latefrom hermes_cli.web_server_chat import _ws_auth_ok, _ws_request_is_allowedfrom hermes_cli.web_server_gateway import _split_text_for_speak_streamfrom fastapi import HTTPException, WebSocket, WebSocketDisconnect-from hermes_cli.web_models import AudioTranscriptionRequest, TTSSpeakRequest, TTSLeaseRequest, VoiceLiveSessionRequest+from hermes_cli.web_models import (+ AudioTranscriptionRequest,+ STTLeaseRequest,+ TTSSpeakRequest,+ TTSLeaseRequest,+ VoiceLiveSessionRequest,+)from typing import Any, Dict, Optional_log = logging.getLogger("hermes_cli.web_server")@@ -472,6 +478,40 @@ def _ffmpeg_s16le_mono(path: str) -> tuple:return result.stdout, 24000[email protected]("/api/audio/stt-lease")+async def stt_lease(payload: STTLeaseRequest, profile: Optional[str] = None):+ """Desktop voice-input sessions as STT warm-up / release signals.++ ``active: true`` registers a lease and pre-loads the configured local STT+ model (first-use download + load) so the transcription request doesn't pay+ the cold cost inside its timeout; ``active: false`` drops the lease. The+ model stays resident after the last release — it is shared with the+ gateway/CLI surfaces in this process, and ``stt.local.unload_after_idle_seconds``+ still governs eviction. Blocking work runs off the event loop. Warm-up+ failures are reported in the body, never as an HTTP error — recording must+ start even when preload fails.+ """+ lease = (payload.lease or "").strip()+ if not lease:+ raise HTTPException(status_code=400, detail="lease is required")++ def _apply():+ from tools.stt_lease import acquire_stt_lease, release_stt_lease+ if payload.active:+ with _config_profile_scope(profile):+ return acquire_stt_lease(lease)+ return release_stt_lease(lease)++ try:+ result = await asyncio.get_running_loop().run_in_executor(None, _apply)+ except HTTPException:+ raise+ except Exception as exc:+ _log.warning("STT lease %s (%s) failed: %s", lease, payload.active, exc)+ result = {"leases": None, "action": "error", "error": str(exc)}+ return {"ok": True, "lease": lease, "active": payload.active, **result}++@router.websocket("/api/audio/speak-stream")async def speak_stream_ws(ws: "WebSocket") -> None:"""Streaming TTS for the desktop: text in, raw int16 PCM frames out.diff --git a/tests/hermes_cli/test_web_server_stt_lease.py b/tests/hermes_cli/test_web_server_stt_lease.pynew file mode 100644index 00000000000..fc6d27daae9--- /dev/null+++ b/tests/hermes_cli/test_web_server_stt_lease.py@@ -0,0 +1,215 @@+"""``POST /api/audio/stt-lease`` — desktop voice input as STT warm-up/release.++The desktop acquires a lease when the mic opens so the backend pre-loads the+configured local faster-whisper model while the user is still speaking; the+transcription request then starts hot instead of paying the cold load inside+its timeout (issue #105955). Releasing the last lease drops the refcount but+— unlike TTS — never unloads the model: the engine is shared with the+gateway/CLI surfaces in the same backend process.+"""++from __future__ import annotations++import pytest+++def isolated_profiles(tmp_path, monkeypatch, _isolate_hermes_home):+ from hermes_constants import get_hermes_home+ from hermes_cli import profiles++ default_home = get_hermes_home()+ profiles_root = default_home / "profiles"+ worker_home = profiles_root / "worker_beta"+ for home in (default_home, worker_home):+ home.mkdir(parents=True, exist_ok=True)+ (home / "config.yaml").write_text("{}\n", encoding="utf-8")+ (worker_home / ".env").write_text("", encoding="utf-8")++ monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: default_home)+ monkeypatch.setattr(profiles, "_get_profiles_root", lambda: profiles_root)+ return {"default": default_home, "worker_beta": worker_home}+++def client(monkeypatch, isolated_profiles):+ try:+ from starlette.testclient import TestClient+ except ImportError:+ pytest.skip("fastapi/starlette not installed")++ import hermes_state+ from hermes_constants import get_hermes_home+ from hermes_cli.web_server import app, _SESSION_HEADER_NAME, _SESSION_TOKEN++ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", get_hermes_home() / "state.db")+ c = TestClient(app)+ c.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN+ return c++[email protected](autouse=True)+def _clean_stt_state():+ from tools import stt_lease, transcription_tools++ stt_lease._reset_stt_leases_for_tests()+ saved_model, saved_name = transcription_tools._local_model, transcription_tools._local_model_name+ transcription_tools._local_model, transcription_tools._local_model_name = None, None+ yield+ stt_lease._reset_stt_leases_for_tests()+ transcription_tools._local_model, transcription_tools._local_model_name = saved_model, saved_name+++def _local_cfg(monkeypatch, model="tiny"):+ from tools import transcription_tools++ monkeypatch.setattr(transcription_tools, "_HAS_FASTER_WHISPER", True)+ monkeypatch.setattr(+ transcription_tools, "_load_stt_config", lambda: {"local": {"model": model}}+ )+ # Explicit local provider without going through the selection-file probe.+ monkeypatch.setattr(transcription_tools, "_get_provider", lambda cfg: "local")+++def test_active_acquires_and_warms(client, monkeypatch):+ from tools import stt_lease++ warmed = []+ monkeypatch.setattr(+ stt_lease,+ "warm_stt_provider",+ lambda cfg=None, provider=None: warmed.append(1)+ or {"provider": "local", "warmed": True, "action": "loaded"},+ )++ resp = client.post("/api/audio/stt-lease", json={"lease": "desktop:voice-input:abc", "active": True})+ assert resp.status_code == 200+ body = resp.json()+ assert body["ok"] is True+ assert body["lease"] == "desktop:voice-input:abc"+ assert body["active"] is True+ assert body["leases"] == 1+ assert body["action"] == "loaded"+ assert warmed == [1]+ assert stt_lease.stt_lease_holders() == ["desktop:voice-input:abc"]+++def test_inactive_releases_without_unloading(client, monkeypatch):+ from tools import stt_lease, transcription_tools++ monkeypatch.setattr(+ stt_lease, "warm_stt_provider", lambda cfg=None, provider=None: {"action": "noop", "warmed": False, "provider": "openai"}+ )+ client.post("/api/audio/stt-lease", json={"lease": "desktop:voice-input:a", "active": True})+ client.post("/api/audio/stt-lease", json={"lease": "desktop:voice-input:b", "active": True})++ # A resident model shared with other surfaces must survive the releases.+ sentinel = object()+ transcription_tools._local_model, transcription_tools._local_model_name = sentinel, "tiny"++ first = client.post("/api/audio/stt-lease", json={"lease": "desktop:voice-input:a", "active": False}).json()+ assert first["leases"] == 1+ assert transcription_tools._local_model is sentinel++ last = client.post("/api/audio/stt-lease", json={"lease": "desktop:voice-input:b", "active": False}).json()+ assert last["leases"] == 0+ assert transcription_tools._local_model is sentinel+++def test_warm_failure_is_reported_not_an_http_error(client, monkeypatch):+ from tools import stt_lease++ def _boom(cfg=None, provider=None):+ raise RuntimeError("engine exploded")++ monkeypatch.setattr(stt_lease, "warm_stt_provider", _boom)+ resp = client.post("/api/audio/stt-lease", json={"lease": "desktop:voice-input:abc", "active": True})+ assert resp.status_code == 200+ body = resp.json()+ assert body["ok"] is True+ assert body["action"] == "error"+ assert "engine exploded" in body["error"]+++def test_blank_lease_rejected(client):+ resp = client.post("/api/audio/stt-lease", json={"lease": " ", "active": True})+ assert resp.status_code == 400+++def test_warm_loads_configured_local_model_into_transcription_slot(monkeypatch):+ from tools import stt_lease, transcription_tools++ _local_cfg(monkeypatch, model="small")+ loaded = []+ monkeypatch.setattr(+ transcription_tools,+ "_get_or_load_local_model",+ lambda name, cfg: loaded.append((name, cfg)) or object(),+ )++ result = stt_lease.warm_stt_provider()++ assert result["warmed"] is True+ assert result["provider"] == "local"+ assert result["action"] == "loaded"+ # Same name transcription resolves (config model, normalized) and the+ # same loader transcription reads — not a shadow cache.+ assert loaded and loaded[0][0] == "small"+ assert "elapsed_ms" in result+++def test_warm_reports_cached_when_model_already_resident(monkeypatch):+ from tools import stt_lease, transcription_tools++ _local_cfg(monkeypatch, model="tiny")+ sentinel = object()+ transcription_tools._local_model, transcription_tools._local_model_name = sentinel, "tiny"+ calls = []+ monkeypatch.setattr(+ transcription_tools,+ "_get_or_load_local_model",+ lambda name, cfg: calls.append(name) or sentinel,+ )++ result = stt_lease.warm_stt_provider()++ assert result == {+ "provider": "local",+ "warmed": True,+ "action": "cached",+ "elapsed_ms": result["elapsed_ms"],+ }+++def test_warm_is_noop_for_cloud_providers(monkeypatch):+ from tools import stt_lease, transcription_tools++ monkeypatch.setattr(transcription_tools, "_load_stt_config", lambda: {"provider": "openai"})+ monkeypatch.setattr(transcription_tools, "_get_provider", lambda cfg: "openai")+ calls = []+ monkeypatch.setattr(+ transcription_tools, "_get_or_load_local_model", lambda name, cfg: calls.append(name)+ )++ result = stt_lease.warm_stt_provider()++ assert result["warmed"] is False+ assert result["action"] == "noop"+ assert calls == []+++def test_warm_never_raises_on_engine_failure(monkeypatch):+ from tools import stt_lease, transcription_tools++ _local_cfg(monkeypatch)++ def _boom(name, cfg):+ raise RuntimeError("CUDA exploded")++ monkeypatch.setattr(transcription_tools, "_get_or_load_local_model", _boom)++ result = stt_lease.warm_stt_provider()++ assert result["warmed"] is False+ assert result["action"] == "error"+ assert "CUDA exploded" in result["error"]diff --git a/tools/stt_lease.py b/tools/stt_lease.pynew file mode 100644index 00000000000..f7bd255a0e6--- /dev/null+++ b/tools/stt_lease.py@@ -0,0 +1,123 @@+"""Local-STT lifecycle for the desktop voice-input path: warm-up leases.++Desktop voice transcription (``POST /api/audio/transcribe``) blocks until the+configured STT engine answers inside the renderer's timeout floor (180s for a+short clip). With the ``local`` provider that floor also covers the cold cost:+first-use faster-whisper download + model load, or a reload after+``stt.local.unload_after_idle_seconds`` evicted the cache — on CPU-bound hosts+that alone can exceed the floor, so every attempt times out while the engine+itself is healthy (issue #105955).++Every surface that is about to need speech-to-text holds a *lease* here while+it does (the desktop acquires when the mic opens, releases after the+transcript settles). Acquiring pre-loads the configured local model into the+exact singleton slot transcription reads, so the bill is paid while the user+is still speaking instead of inside the transcription request's timeout.++Mirrors :mod:`tools.tts_tool_lifecycle` with one deliberate divergence:+releasing the last lease does NOT unload the model. The cached local model is+shared with the gateway/CLI/Telegram surfaces in the same backend process —+one surface's "mic closed" must not evict an engine another surface is about+to use. Eviction stays governed by ``stt.local.unload_after_idle_seconds``,+and warming touches the idle timer so a just-warmed model is never+instantly eligible for unload.+"""++from __future__ import annotations++import logging+import threading+import time+from typing import Any, Dict, List, Optional++logger = logging.getLogger("tools.stt_lease")++_stt_lease_lock = threading.Lock()+_stt_leases: set = set()+++def warm_stt_provider(+ stt_config: Optional[Dict[str, Any]] = None, provider: Optional[str] = None+) -> Dict[str, Any]:+ """Pre-load the configured STT engine so the next transcription starts hot.++ Blocking; never raises. Only the ``local`` (faster-whisper) provider has+ anything resident: it fills the same cache slot ``_transcribe_local``+ reads (including first-use download and lazy install). ``local_command``+ shells out to an external binary and cloud providers are remote, so both+ are ``action: "noop"``. The result carries ``provider`` / ``warmed`` /+ ``action`` / ``error``.+ """+ from tools import transcription_tools+ from tools.transcription_local import _normalize_local_model++ if stt_config is None:+ stt_config = transcription_tools._load_stt_config()+ name = (provider or transcription_tools._get_provider(stt_config) or "").lower().strip()+ result: Dict[str, Any] = {"provider": name, "warmed": False, "action": "noop"}+ if name not in {"local", "local_command"}:+ return result+ if name == "local_command":+ result.update(warmed=True)+ return result+ if not transcription_tools._HAS_FASTER_WHISPER and not transcription_tools._try_lazy_install_stt():+ result.update(action="error", error="faster-whisper not installed")+ return result+ local_cfg = stt_config.get("local") or {}+ # Same name transcription itself resolves (config > default, cloud-only+ # names normalized) so warm-up fills the slot the next request reads.+ model_name = _normalize_local_model(local_cfg.get("model"))+ hot_before = (+ transcription_tools._local_model is not None+ and transcription_tools._local_model_name == model_name+ )+ started = time.monotonic()+ try:+ model = transcription_tools._get_or_load_local_model(model_name, local_cfg)+ if model is None: # defensive: load failed without raising+ result.update(action="error", error="Local whisper model failed to load")+ return result+ # A just-warmed model counts as activity: the idle-unload watcher must+ # not treat the load itself as idle time and evict it immediately.+ transcription_tools._touch_transcription_time()+ except Exception as exc: # engine missing, download failed, bad device…+ logger.warning("[STT] warm-up for local model '%s' failed: %s", model_name, exc)+ result.update(action="error", error=str(exc))+ return result+ elapsed_ms = int((time.monotonic() - started) * 1000)+ result.update(warmed=True, action="cached" if hot_before else "loaded", elapsed_ms=elapsed_ms)+ logger.info("[STT] warm-up local model '%s': %s in %dms", model_name, result["action"], elapsed_ms)+ return result+++def acquire_stt_lease(lease: str, stt_config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:+ """Register ``lease`` (e.g. ``"desktop:voice-input:abcd1234"``) and warm the engine.++ Re-acquiring is idempotent but still re-warms (cheap on a cache hit; heals+ a cache the idle-unload watcher cleared meanwhile).+ """+ with _stt_lease_lock:+ _stt_leases.add(lease)+ holders = len(_stt_leases)+ return {**warm_stt_provider(stt_config), "leases": holders}+++def release_stt_lease(lease: str) -> Dict[str, Any]:+ """Drop ``lease``. A never-acquired lease is a no-op (still reports the+ holder count) so surfaces can call this unconditionally. Never unloads the+ model — see the module docstring for why this diverges from TTS leases."""+ with _stt_lease_lock:+ _stt_leases.discard(lease)+ holders = len(_stt_leases)+ return {"leases": holders}+++def stt_lease_holders() -> List[str]:+ """Snapshot of live lease names (diagnostics / tests)."""+ with _stt_lease_lock:+ return sorted(_stt_leases)+++def _reset_stt_leases_for_tests() -> None:+ with _stt_lease_lock:+ _stt_leases.clear()