The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): carry STT warm-up readiness into transcription and enforce lease ownership
Brooklyn Nicholsone40f2937962e
diff --git a/apps/desktop/src/api/system.ts b/apps/desktop/src/api/system.tsindex 78de73ebd47..021b0392dc5 100644--- a/apps/desktop/src/api/system.ts+++ b/apps/desktop/src/api/system.ts@@ -229,11 +229,14 @@ 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>`.+ * `lease` names the session — `desktop:voice-input:<renderer>`. `owner` is+ * the owning connection/profile captured when the intent was registered, so+ * a queued call is not re-routed by a later gateway/profile switch (omitted+ * halves → the active scope, like `speakText`).*/-export function setSttLease(lease: string, active: boolean): Promise<AudioSttLeaseResponse> {+export function setSttLease(lease: string, active: boolean, owner?: OwnerScope): Promise<AudioSttLeaseResponse> {return hermesApi<AudioSttLeaseResponse>({- ...profileScoped(),+ ...ownerScoped(owner),path: '/api/audio/stt-lease',method: 'POST',body: { active, lease },diff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation-warmup.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation-warmup.test.tsxnew file mode 100644index 00000000000..4f34887b843--- /dev/null+++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation-warmup.test.tsx@@ -0,0 +1,178 @@+import { act, cleanup, renderHook, waitFor } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import type { BargeMonitorCallbacks } from '@/lib/voice-barge-in'+import type { MicRecording } from './use-mic-recorder'++import { useVoiceConversation } from './use-voice-conversation'++// #105955 review: the warm-up fired when the conversation starts listening+// is a READINESS BARRIER before transcription — handleTurn() awaits it before+// handing the clip to `onTranscribeAudio`, so a cold local model load settles+// inside the lease request's own budget instead of eating the transcription+// request's decode deadline (190 s cold load + 3 s clip vs a 180 s floor).++const micHandle = {+ cancel: vi.fn(),+ start: vi.fn(async () => undefined),+ stop: vi.fn<() => Promise<MicRecording | null>>(async () => null)+}++vi.mock('./use-mic-recorder', () => ({+ useMicRecorder: () => ({ handle: micHandle, level: 0, recording: false })+}))++const syncSttLeaseSpy = vi.fn(async () => undefined)++vi.mock('@/lib/stt-lease', () => ({+ syncSttLease: (...args: unknown[]) => syncSttLeaseSpy(...(args as [])),+ VOICE_INPUT_LEASE: 'desktop:voice-input:test'+}))++vi.mock('@/lib/voice-barge-in', () => ({+ monitorSpeechDuringPlayback: () => () => undefined+}))++vi.mock('@/lib/voice-playback', () => ({+ markVoicePlaybackInterrupted: vi.fn(),+ playSpeechText: vi.fn(async () => true),+ startSpeechStream: vi.fn(async () => null),+ stopVoicePlayback: vi.fn(),+ takeVoicePlaybackInterrupted: vi.fn(() => true)+}))++vi.mock('@/lib/thinking-sound', () => ({+ startThinkingSound: vi.fn(),+ stopThinkingSound: vi.fn()+}))++vi.mock('@/lib/speech-text', () => ({+ IncrementalSpeechSentenceBuffer: class {+ append() { return [] }+ flush() { return [] }+ }+}))++vi.mock('@/lib/voice-stop-word', () => ({ isVoiceStopCommand: () => false }))+vi.mock('@/lib/voice-tts-echo', () => ({ isTtsEcho: () => false }))++vi.mock('@/store/notifications', () => ({+ notify: vi.fn(),+ notifyError: vi.fn()+}))++vi.mock('@/store/voice-playback', () => {+ const { atom } = require('nanostores') as never as { atom: (v: unknown) => unknown }++ return { $voicePlayback: atom({ sequence: 0, status: 'idle' }) }+})++vi.mock('@/store/voice-prefs', async () => {+ const { atom } = await import('nanostores')++ return {+ $autoSpeakReplies: atom(false),+ $bargeInThresholdMultiplier: atom(1),+ $voiceSilenceMs: atom(1250)+ }+})++vi.mock('@/i18n', () => ({+ useI18n: () => ({+ t: {+ notifications: {+ voice: {+ configureSpeechToText: 'configure STT',+ couldNotStartSession: 'could not start',+ microphoneFailed: 'mic failed',+ playbackFailed: 'playback failed',+ recordingFailed: 'recording failed',+ transcriptionFailed: 'transcription failed',+ unavailable: 'unavailable'+ }+ }+ }+ })+}))++vi.mock('../scope', () => ({+ useComposerScope: () => ({ $messages: { get: () => [] }, connectionId: undefined, profile: undefined })+}))++describe('useVoiceConversation STT readiness barrier', () => {+ beforeEach(() => {+ cleanup()+ micHandle.start.mockClear()+ micHandle.cancel.mockClear()+ micHandle.stop.mockReset()+ micHandle.stop.mockImplementation(async () => ({ audio: new Blob(), durationMs: 900, heardSpeech: true }))+ syncSttLeaseSpy.mockReset()+ syncSttLeaseSpy.mockImplementation(async () => undefined)+ })++ afterEach(() => {+ cleanup()+ })++ function renderConversation(onTranscribeAudio: (audio: Blob) => Promise<string>) {+ const hook = renderHook(() =>+ useVoiceConversation({+ busy: false,+ consumePendingResponse: () => undefined,+ enabled: true,+ onSubmit: () => undefined,+ onTranscribeAudio,+ pendingResponse: () => null+ })+ )++ return hook+ }++ it('waits for the listening warm-up before transcribing the captured utterance', async () => {+ // Cold load in flight: the acquire stays open past the silence stop.+ let settleWarmup!: () => void+ syncSttLeaseSpy.mockImplementation(+ () =>+ new Promise<void>(resolve => {+ settleWarmup = resolve+ })+ )++ const transcribe = vi.fn(async () => 'hello world')+ const hook = renderConversation(transcribe)++ // Listening starts: the mic opens without waiting on the warm-up.+ await act(async () => {+ await hook.result.current.start()+ })+ await act(async () => {+ await Promise.resolve()+ })+ expect(micHandle.start).toHaveBeenCalledTimes(1)+ expect(syncSttLeaseSpy).toHaveBeenCalledWith('desktop:voice-input:test', true, {+ connectionId: undefined,+ profile: undefined+ })++ // The VAD silence callback fires a turn while the cold load is in flight.+ let turnPromise: Promise<void> | undefined+ await act(async () => {+ micHandle.stop.mockImplementation(async () => ({ audio: new Blob(), durationMs: 900, heardSpeech: true }))+ turnPromise = Promise.resolve(hook.result.current.stopTurn())+ await Promise.resolve()+ await Promise.resolve()+ })++ // The barrier holds: transcription has not started inside the load wait.+ expect(transcribe).not.toHaveBeenCalled()++ settleWarmup()+ await act(async () => {+ await turnPromise+ })++ await waitFor(() => expect(transcribe).toHaveBeenCalledTimes(1))+ expect(await transcribe.mock.results[0].value).toBe('hello world')+ })+})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 2a49f497f32..4e3d2409650 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@@ -88,6 +88,12 @@ export function useVoiceConversation({const turnClosingRef = useRef(false)const meterFailuresRef = useRef(0)const awaitingSpokenResponseRef = useRef(false)+ // Readiness barrier for the warm-up fired when listening starts (#105955+ // review): transcription must not begin while a cold model load is still on+ // the wire — the load would eat the transcription request's own decode+ // budget. Each listen cycle captures its acquire promise; transcription+ // awaits it (bounded by the lease request's own timeout) before submitting.+ const warmupBarrierRef = useRef<null | Promise<void>>(null)const responseIdRef = useRef<string | null>(null)const spokenSourceLengthRef = useRef(0)const speechSessionRef = useRef<null | SpeechStreamSession>(null)@@ -214,6 +220,11 @@ export function useVoiceConversation({}try {+ // Readiness first: let the listening-start warm-up settle before+ // handing the clip to transcription (#105955) — a cold model load+ // must not run inside the transcription request's decode budget.+ // syncSttLease never rejects.+ await warmupBarrierRef.currentconst transcript = (await onTranscribeAudio(result.audio)).trim()if (!transcript) {@@ -323,8 +334,12 @@ export function useVoiceConversation({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)+ // Deduped with the recorder's lease — one warm-up per renderer — but+ // re-warms whenever readiness may have expired (idle eviction during a+ // long reply/mute, or a failed preload), pinned to this scope's owner.+ // The promise is kept as the readiness barrier the transcription paths+ // await before submitting audio.+ warmupBarrierRef.current = syncSttLease(VOICE_INPUT_LEASE, true, ownerRef.current)// 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@@ -407,6 +422,11 @@ export function useVoiceConversation({setStatus('transcribing')try {+ // Same readiness barrier as handleTurn: the barge capture transcribes+ // with the warm-up issued when this conversation last started+ // listening (the monitor is armed through the whole turn, so the+ // barrier is normally already settled by speech time).+ await warmupBarrierRef.currentconst transcript = (await onTranscribeAudio(audio)).trim()if (!transcript) {@@ -820,8 +840,9 @@ export function useVoiceConversation({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)+ // backend keeps the model resident regardless of the count. Released to+ // the owner that acquired it, not whatever is selected now.+ void syncSttLease(VOICE_INPUT_LEASE, false, ownerRef.current)setMuted(false)setStatus('idle')}, [consumePendingResponse, handle])diff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-recorder-warmup.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-voice-recorder-warmup.test.tsxnew file mode 100644index 00000000000..646758ae45a--- /dev/null+++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-recorder-warmup.test.tsx@@ -0,0 +1,187 @@+import { act, cleanup, renderHook, waitFor } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import type { MicRecording } from './use-mic-recorder'++import { useVoiceRecorder } from './use-voice-recorder'++// #105955 review: the mic-open warm-up must act as a READINESS BARRIER before+// transcription — `stop()` awaits the warm-up fired at start, so a cold local+// model load settles inside the lease request's own budget instead of eating+// the transcription request's decode deadline. Without the barrier, a 190 s+// cold load behind a 3 s recording exhausted the 180 s transcription floor+// before decoding began.++// The real recorder flips `recording` in start/stop; dictate() routes on it.+let recording = false+const micHandle = {+ cancel: vi.fn(),+ start: vi.fn(async () => {+ recording = true+ }),+ stop: vi.fn<() => Promise<MicRecording | null>>(async () => {+ recording = false++ return { audio: new Blob(), durationMs: 500, heardSpeech: true }+ })+}++vi.mock('./use-mic-recorder', () => ({+ useMicRecorder: () => ({ handle: micHandle, level: 0, get recording() { return recording } })+}))++const syncSttLeaseSpy = vi.fn(async () => undefined)++vi.mock('@/lib/stt-lease', () => ({+ syncSttLease: (...args: unknown[]) => syncSttLeaseSpy(...(args as [])),+ VOICE_INPUT_LEASE: 'desktop:voice-input:test'+}))++vi.mock('@/store/notifications', () => ({+ notify: vi.fn(),+ notifyError: vi.fn()+}))++vi.mock('@/store/desktop-metrics', () => ({+ recordFeatureUse: vi.fn()+}))++vi.mock('@/i18n', () => ({+ useI18n: () => ({+ t: {+ notifications: {+ voice: {+ noSpeechDetected: 'no speech',+ recordingFailed: 'recording failed',+ transcriptionFailed: 'transcription failed',+ transcriptionUnavailable: 'unavailable',+ tryRecordingAgain: 'try again',+ unavailable: 'unavailable'+ }+ }+ }+ })+}))++vi.mock('../scope', () => ({+ useComposerScope: () => ({ connectionId: undefined, profile: undefined })+}))++describe('useVoiceRecorder STT readiness barrier', () => {+ beforeEach(() => {+ cleanup()+ recording = false+ micHandle.start.mockClear()+ micHandle.stop.mockReset()+ micHandle.stop.mockImplementation(async () => {+ recording = false++ return { audio: new Blob(), durationMs: 500, heardSpeech: true }+ })+ syncSttLeaseSpy.mockReset()+ syncSttLeaseSpy.mockImplementation(async () => undefined)+ })++ afterEach(() => {+ cleanup()+ })++ function renderRecorder(onTranscribeAudio: (audio: Blob) => Promise<string>) {+ return renderHook(() =>+ useVoiceRecorder({+ focusInput: () => undefined,+ maxRecordingSeconds: 30,+ onTranscript: () => undefined,+ onTranscribeAudio+ })+ )+ }++ it('does not submit the clip to transcription while the mic-open warm-up is still settling', async () => {+ // Model the cold load: the acquire stays on the wire after the mic opens.+ let settleWarmup!: () => void+ syncSttLeaseSpy.mockImplementation(+ () =>+ new Promise<void>(resolve => {+ settleWarmup = resolve+ })+ )++ const transcribe = vi.fn(async () => 'hello world')+ const hook = renderRecorder(transcribe)++ // Mic opens: recording starts without waiting on the warm-up.+ await act(async () => {+ hook.result.current.dictate()+ })+ await act(async () => {+ await Promise.resolve()+ })+ expect(micHandle.start).toHaveBeenCalledTimes(1)+ expect(syncSttLeaseSpy).toHaveBeenCalledWith('desktop:voice-input:test', true, {+ connectionId: undefined,+ profile: undefined+ })++ // User stops after a short clip — but the cold load is still in flight.+ let stopping: Promise<void> | undefined+ await act(async () => {+ stopping = hook.result.current.dictate() ?? undefined+ await Promise.resolve()+ await Promise.resolve()+ })++ // The barrier holds: the transcription request has not gone out yet,+ // so the load wait is not inside the transcribe request's budget.+ expect(transcribe).not.toHaveBeenCalled()++ settleWarmup()+ await act(async () => {+ await stopping+ })++ // Readiness established → the clip is submitted and transcribes.+ await waitFor(() => expect(transcribe).toHaveBeenCalledTimes(1))+ expect(await transcribe.mock.results[0].value).toBe('hello world')+ })++ it('transcribes without extra delay once the warm-up has already settled', async () => {+ syncSttLeaseSpy.mockImplementation(async () => undefined)++ const transcribe = vi.fn(async () => 'hello world')+ const hook = renderRecorder(transcribe)++ await act(async () => {+ hook.result.current.dictate()+ })+ await act(async () => {+ await Promise.resolve()+ })+ await act(async () => {+ hook.result.current.dictate() // stop+ })++ await waitFor(() => expect(transcribe).toHaveBeenCalledTimes(1))+ })++ it('releases the lease to the composer scope owner after the transcript settles', async () => {+ const transcribe = vi.fn(async () => 'hello world')+ const hook = renderRecorder(transcribe)++ await act(async () => {+ hook.result.current.dictate()+ })+ await act(async () => {+ await Promise.resolve()+ })+ await act(async () => {+ hook.result.current.dictate() // stop+ })+ await waitFor(() => expect(transcribe).toHaveBeenCalledTimes(1))++ // The release also carries the captured owner, not a re-read of ambient+ // selection at settle time.+ const releaseCall = syncSttLeaseSpy.mock.calls.find(([, active]) => active === false)+ expect(releaseCall).toEqual(['desktop:voice-input:test', false, { connectionId: undefined, profile: undefined }])+ })+})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 02218fe323a..0cba8a9223a 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@@ -4,6 +4,7 @@ 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'+import { useComposerScope } from '../scope'import type { VoiceActivityState, VoiceStatus } from '../types'@@ -16,6 +17,9 @@ interface VoiceRecorderOptions {onTranscript: (text: string) => void}+/** Settles when the STT warm-up issued at mic-open resolves (or never ran). */+type WarmupBarrier = null | Promise<void>+export function useVoiceRecorder({maxRecordingSeconds,onTranscribeAudio,@@ -25,11 +29,23 @@ export function useVoiceRecorder({const { t } = useI18n()const voiceCopy = t.notifications.voiceconst { handle, level, recording } = useMicRecorder(voiceCopy)+ // The scope's session owner (a Bot tile's own connection + profile) pins+ // the STT lease to the backend that will transcribe this composer's audio.+ const { connectionId: ownerConnectionId, profile: ownerProfile } = useComposerScope()+ const ownerRef = useRef({ connectionId: ownerConnectionId, profile: ownerProfile })+ ownerRef.current = { connectionId: ownerConnectionId, profile: ownerProfile }const [voiceStatus, setVoiceStatus] = useState<VoiceStatus>('idle')const [elapsedSeconds, setElapsedSeconds] = useState(0)const startedAtRef = useRef(0)const intervalRef = useRef<number | null>(null)const timeoutRef = useRef<number | null>(null)+ // Readiness barrier for the warm-up fired at mic-open (#105955 review):+ // transcription must not start while the cold model load is still on the+ // wire — the load would eat the transcription request's own decode budget.+ // stop() awaits it (bounded by the lease request's 180 s timeout) so the+ // transcribe POST starts only once warm-up settled (warm, noop, or failed —+ // a failed warm-up proceeds to transcription, which re-loads server-side).+ const warmupBarrierRef = useRef<WarmupBarrier>(null)const clearTimers = () => {if (intervalRef.current) {@@ -64,6 +80,12 @@ export function useVoiceRecorder({setVoiceStatus('transcribing')try {+ // Readiness first: let the mic-open warm-up settle before handing the+ // clip to transcription, so a cold model load no longer runs inside the+ // transcription request's timeout (#105955). syncSttLease never rejects,+ // and its budget is the lease request's own 180 s timeout — recording+ // and stop() were never bounded tighter than that for local STT.+ await warmupBarrierRef.currentconst transcript = (await onTranscribeAudio(result.audio)).trim()if (!transcript) {@@ -77,7 +99,7 @@ export function useVoiceRecorder({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)+ void syncSttLease(VOICE_INPUT_LEASE, false, ownerRef.current)focusInput()}}@@ -94,8 +116,12 @@ export function useVoiceRecorder({// 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)+ // Fire-and-forget for the MIC UX — but keep the promise: stop() awaits+ // it as the readiness barrier before transcription (see above). Pinned+ // to this composer's owner so a mid-flight gateway/profile switch+ // cannot misroute the eventual release; re-warms if a prior warm-up+ // failed or the idle watcher evicted the model.+ warmupBarrierRef.current = syncSttLease(VOICE_INPUT_LEASE, true, ownerRef.current)startedAtRef.current = Date.now()setElapsedSeconds(0)setVoiceStatus('recording')diff --git a/apps/desktop/src/hermes.test.ts b/apps/desktop/src/hermes.test.tsindex 8b8d3fcfecd..d0166dc5e07 100644--- a/apps/desktop/src/hermes.test.ts+++ b/apps/desktop/src/hermes.test.ts@@ -694,6 +694,45 @@ describe('Hermes REST helpers', () => {})})+ it('pins an STT lease to an explicit owner scope instead of the ambient selection', async () => {+ // #105955 review: the lease belongs to the connection/profile that+ // acquired it — a queued call must carry the captured owner, not whatever+ // gateway/profile is selected when it finally runs.+ setApiRequestConnection('gateway-b')+ setApiRequestProfile('worker_beta')+ api.mockResolvedValue({ ok: true })++ await setSttLease('desktop:voice-input:abc', true, { connectionId: 'gateway-a', profile: 'worker_alpha' })+ await setSttLease('desktop:voice-input:abc', false, { connectionId: 'gateway-a', profile: 'worker_alpha' })++ expect(api).toHaveBeenNthCalledWith(1, {+ body: { active: true, lease: 'desktop:voice-input:abc' },+ connectionId: 'gateway-a',+ method: 'POST',+ path: '/api/audio/stt-lease',+ priority: 'foreground',+ profile: 'worker_alpha',+ timeoutMs: AUDIO_STT_LEASE_REQUEST_TIMEOUT_MS+ })+ expect(api).toHaveBeenNthCalledWith(2, {+ body: { active: false, lease: 'desktop:voice-input:abc' },+ connectionId: 'gateway-a',+ method: 'POST',+ path: '/api/audio/stt-lease',+ priority: 'foreground',+ profile: 'worker_alpha',+ timeoutMs: AUDIO_STT_LEASE_REQUEST_TIMEOUT_MS+ })++ // An explicit 'local' pin stays explicit — a later remote primary must+ // not reinterpret it.+ api.mockClear()+ await setSttLease('desktop:voice-input:abc', true, { connectionId: 'local' })+ expect(api).toHaveBeenCalledWith(+ expect.objectContaining({ connectionId: 'local', path: '/api/audio/stt-lease' })+ )+ })+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.tsindex 460c886643c..bfa38bce9a0 100644--- a/apps/desktop/src/lib/stt-lease.test.ts+++ b/apps/desktop/src/lib/stt-lease.test.ts@@ -1,22 +1,48 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-const setSttLease = vi.fn(async (_lease: string, _active: boolean) => ({ ok: true }))+const setSttLease = vi.fn(+ async (_lease: string, _active: boolean, _owner?: { connectionId?: null | string; profile?: null | string }) => ({+ ok: true+ })+)vi.mock('@/hermes', () => ({- setSttLease: (lease: string, active: boolean) => setSttLease(lease, active)+ getApiRequestConnection: () => currentScope.connectionId,+ getApiRequestProfile: () => currentScope.profile,+ setSttLease: (+ lease: string,+ active: boolean,+ owner?: { connectionId?: null | string; profile?: null | string }+ ) => setSttLease(lease, active, owner)}))-import { resetSttLeasesForTests, syncSttLease, VOICE_INPUT_LEASE } from './stt-lease'+import {+ resetSttLeasesForTests,+ setSttWarmRevalidateMsForTests,+ syncSttLease,+ VOICE_INPUT_LEASE+} from './stt-lease'++// Ambient scope the (mocked) api helpers would read; tests flip it to model a+// gateway/profile switch between enqueue and settle.+const currentScope = { connectionId: null as null | string, profile: null as null | string }++const resetScope = () => {+ currentScope.connectionId = null+ currentScope.profile = null+}describe('syncSttLease', () => {beforeEach(() => {resetSttLeasesForTests()+ resetScope()setSttLease.mockReset()setSttLease.mockImplementation(async () => ({ ok: true }))})afterEach(() => {resetSttLeasesForTests()+ resetScope()})it('acquires on the first on and releases on off', async () => {@@ -24,8 +50,8 @@ describe('syncSttLease', () => {await syncSttLease(VOICE_INPUT_LEASE, false)expect(setSttLease.mock.calls).toEqual([- [VOICE_INPUT_LEASE, true],- [VOICE_INPUT_LEASE, false]+ [VOICE_INPUT_LEASE, true, { connectionId: null, profile: null }],+ [VOICE_INPUT_LEASE, false, { connectionId: null, profile: null }]])})@@ -35,7 +61,7 @@ describe('syncSttLease', () => {expect(setSttLease).not.toHaveBeenCalled()})- it('dedupes a repeat of the last sent state', async () => {+ it('dedupes a repeat of the last sent state while the warm-up is fresh', async () => {await syncSttLease(VOICE_INPUT_LEASE, true)await syncSttLease(VOICE_INPUT_LEASE, true)await syncSttLease(VOICE_INPUT_LEASE, true)@@ -55,7 +81,7 @@ describe('syncSttLease', () => {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]])+ expect(setSttLease.mock.calls).toEqual([[VOICE_INPUT_LEASE, true, { connectionId: null, profile: null }]])const off = syncSttLease(VOICE_INPUT_LEASE, false)await Promise.resolve()@@ -66,8 +92,8 @@ describe('syncSttLease', () => {await Promise.all([on, off])expect(setSttLease.mock.calls).toEqual([- [VOICE_INPUT_LEASE, true],- [VOICE_INPUT_LEASE, false]+ [VOICE_INPUT_LEASE, true, { connectionId: null, profile: null }],+ [VOICE_INPUT_LEASE, false, { connectionId: null, profile: null }]])})@@ -78,7 +104,7 @@ describe('syncSttLease', () => {// 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]])+ expect(setSttLease.mock.calls).toEqual([[VOICE_INPUT_LEASE, false, { connectionId: null, profile: null }]])})it('forgets the sent state on failure so the next flip retries', async () => {@@ -102,4 +128,154 @@ describe('syncSttLease', () => {it('voice-input lease is per renderer', () => {expect(VOICE_INPUT_LEASE).toMatch(/^desktop:voice-input:[a-z0-9]+$/)})++ // ── Readiness is validated, never remembered (#105955 review) ────────────++ it('treats an application-level error outcome as not-warm and retries the next acquire', async () => {+ // /api/audio/stt-lease deliberately resolves HTTP 200 with+ // {ok: true, action: 'error', warmed: false} — a failed preload must not+ // suppress subsequent listening-cycle retries.+ setSttLease.mockImplementationOnce(async () => ({+ ok: true,+ action: 'error',+ warmed: false+ }))++ await syncSttLease(VOICE_INPUT_LEASE, true)+ await syncSttLease(VOICE_INPUT_LEASE, true)++ expect(setSttLease).toHaveBeenCalledTimes(2)+ })++ it('re-warms after the validation window lapses — idle eviction is invisible to the client', async () => {+ const restore = setSttWarmRevalidateMsForTests(0)+ try {+ setSttLease.mockImplementation(async () => ({ ok: true, action: 'cached', warmed: true }))++ await syncSttLease(VOICE_INPUT_LEASE, true)+ await syncSttLease(VOICE_INPUT_LEASE, true)++ // The backend's idle-unload watcher can evict the model at any time;+ // registration alone must not be treated as permanent readiness.+ expect(setSttLease).toHaveBeenCalledTimes(2)+ } finally {+ restore()+ }+ })++ it('accepts a settled cloud noop as warm — no retry churn for non-local providers', async () => {+ setSttLease.mockImplementation(async () => ({ ok: true, action: 'noop', warmed: false }))++ await syncSttLease(VOICE_INPUT_LEASE, true)+ await syncSttLease(VOICE_INPUT_LEASE, true)++ expect(setSttLease).toHaveBeenCalledTimes(1)+ })++ it('dedupes concurrent identical acquires into one wire call', async () => {+ let finishAcquire: () => void = () => undefined+ setSttLease.mockImplementation(+ () =>+ new Promise(resolve => {+ finishAcquire = () => resolve({ ok: true, action: 'loaded', warmed: true })+ })+ )++ const first = syncSttLease(VOICE_INPUT_LEASE, true)+ // The queued acquire runs on a microtask — let it reach the wire before+ // the second identical acquire is registered.+ await Promise.resolve()+ const second = syncSttLease(VOICE_INPUT_LEASE, true)++ expect(setSttLease).toHaveBeenCalledTimes(1)++ finishAcquire()+ await Promise.all([first, second])++ expect(setSttLease).toHaveBeenCalledTimes(1)+ })++ // ── A lease belongs to the connection/profile that acquired it ────────────++ it('binds queued operations to the owner captured at enqueue time', async () => {+ // gateway-A / worker_alpha acquires; the response is held so a release can+ // queue behind it; the source switches to gateway-B before either settles.+ let finishAcquire: () => void = () => undefined+ setSttLease.mockImplementationOnce(+ () =>+ new Promise(resolve => {+ finishAcquire = () => resolve({ ok: true, action: 'loaded', warmed: true })+ })+ )++ const on = syncSttLease(VOICE_INPUT_LEASE, true, { connectionId: 'gateway-a', profile: 'worker_alpha' })+ await Promise.resolve()+ const off = syncSttLease(VOICE_INPUT_LEASE, false, { connectionId: 'gateway-a', profile: 'worker_alpha' })+ await Promise.resolve()++ // Switch the ambient selection mid-flight.+ currentScope.connectionId = 'gateway-b'+ currentScope.profile = 'worker_beta'++ finishAcquire()+ await Promise.all([on, off])++ // Both wire calls carry the acquiring owner; the release lands on the+ // backend that holds the lease, not the newly selected one.+ expect(setSttLease.mock.calls).toEqual([+ [VOICE_INPUT_LEASE, true, { connectionId: 'gateway-a', profile: 'worker_alpha' }],+ [VOICE_INPUT_LEASE, false, { connectionId: 'gateway-a', profile: 'worker_alpha' }]+ ])+ })++ it('captures the ambient owner at call time when none is passed', async () => {+ currentScope.connectionId = 'gateway-a'+ currentScope.profile = 'worker_alpha'++ let finishAcquire: () => void = () => undefined+ setSttLease.mockImplementationOnce(+ () =>+ new Promise(resolve => {+ finishAcquire = () => resolve({ ok: true, action: 'loaded', warmed: true })+ })+ )++ const on = syncSttLease(VOICE_INPUT_LEASE, true)+ await Promise.resolve()+ const off = syncSttLease(VOICE_INPUT_LEASE, false)+ await Promise.resolve()++ currentScope.connectionId = 'gateway-b'+ currentScope.profile = 'worker_beta'++ finishAcquire()+ await Promise.all([on, off])++ expect(setSttLease.mock.calls).toEqual([+ [VOICE_INPUT_LEASE, true, { connectionId: 'gateway-a', profile: 'worker_alpha' }],+ [VOICE_INPUT_LEASE, false, { connectionId: 'gateway-a', profile: 'worker_alpha' }]+ ])+ })++ it('sends its own acquire to a new owner after a source switch — same lease, different backend', async () => {+ setSttLease.mockImplementation(async () => ({ ok: true, action: 'loaded', warmed: true }))++ await syncSttLease(VOICE_INPUT_LEASE, true, { connectionId: 'gateway-a', profile: 'worker_alpha' })+ await syncSttLease(VOICE_INPUT_LEASE, true, { connectionId: 'gateway-b', profile: 'worker_beta' })++ // A's remembered state must not satisfy B's acquire: warm-up must not+ // disappear after a source change in the same renderer.+ expect(setSttLease.mock.calls).toEqual([+ [VOICE_INPUT_LEASE, true, { connectionId: 'gateway-a', profile: 'worker_alpha' }],+ [VOICE_INPUT_LEASE, true, { connectionId: 'gateway-b', profile: 'worker_beta' }]+ ])+ })++ it('keeps an explicit local owner explicit so a later remote primary cannot reinterpret it', async () => {+ setSttLease.mockImplementation(async () => ({ ok: true, action: 'loaded', warmed: true }))++ await syncSttLease(VOICE_INPUT_LEASE, true, { connectionId: 'local', profile: 'default' })++ expect(setSttLease.mock.calls[0][2]).toEqual({ connectionId: 'local', profile: 'default' })+ })})diff --git a/apps/desktop/src/lib/stt-lease.ts b/apps/desktop/src/lib/stt-lease.tsindex 88fcdf0b88f..c5385a93532 100644--- a/apps/desktop/src/lib/stt-lease.ts+++ b/apps/desktop/src/lib/stt-lease.ts@@ -1,4 +1,6 @@-import { setSttLease } from '@/hermes'+import { getApiRequestConnection, getApiRequestProfile, setSttLease } from '@/hermes'++import type { AudioSttLeaseResponse } from '@/types/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@@ -13,6 +15,31 @@ import { setSttLease } from '@/hermes'// 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.+//+// Three invariants the backend's lease semantics force (they diverge from the+// TTS mirror this was drawn from — the STT engine does NOT pin the model while+// a lease is held):+//+// 1. Registration ≠ readiness. Knowing the backend holds the lease says+// nothing about the model being warm: the idle-unload watcher can evict it+// mid-conversation (during a long reply or a mute), and a failed warm-up+// comes back as HTTP 200 with `action: 'error'`. Warm-up is therefore+// VALIDATED on every acquire outcome and revalidated on later listening+// starts (a fresh validation is trusted for a short window only) — never+// remembered as permanent.+// 2. Readiness is bounded and carried into transcription. Awaiting+// `syncSttLease(lease, true, owner)` resolves only when the current+// warm-up has settled within its own request budget — the hooks use that+// as a readiness barrier before submitting audio, so the transcription+// request's deadline measures decoding, not the loader's cold start+// (#105955 review: a 190 s cold load + a 3 s recording used to exhaust+// the 180 s transcription floor before decoding began).+// 3. A lease belongs to the connection/profile that acquired it. The owner+// is captured when the intent is registered and carried on the queued wire+// call, so switching gateway/profile mid-flight sends the release to the+// scope that holds the lease — and a new owner's acquire warms its own+// backend instead of being swallowed by the old owner's remembered state.+// Queue and dedupe identity both include the owner.// 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.@@ -20,56 +47,175 @@ 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>()+/**+ * How long a validated warm-up is trusted before the next listening start+ * revalidates it with the backend. The STT idle-unload watcher can evict the+ * model at any configured moment, so readiness is only ever fresh for a short+ * window — a cache-hit revalidate is cheap; a suppressed re-warm after an+ * eviction makes the next transcription pay the cold load again.+ */+const STT_WARM_REVALIDATE_MS_DEFAULT = 60_000+let sttWarmRevalidateMs = STT_WARM_REVALIDATE_MS_DEFAULT++/**+ * The backend connection/profile that owns a lease operation. `undefined` →+ * the ambient scope captured when the intent is registered (single-profile+ * windows). An explicit `{ connectionId: 'local', profile }` stays explicit+ * through the queue so a later primary/remote selection cannot reinterpret it.+ */+export type SttLeaseOwner = undefined | { connectionId?: null | string; profile?: null | string }++interface Owner {+ connectionId: null | string+ profile: null | string+}++function resolveOwner(owner: SttLeaseOwner): Owner {+ if (owner === undefined) {+ return { connectionId: getApiRequestConnection(), profile: getApiRequestProfile() }+ }++ return {+ connectionId: owner.connectionId === undefined ? getApiRequestConnection() : owner.connectionId,+ profile: owner.profile === undefined ? getApiRequestProfile() : owner.profile+ }+}++/** Queue/dedupe identity: the same lease on a different owner is a different lease. */+function keyFor(lease: string, owner: Owner): string {+ return `${lease}::${owner.connectionId ?? ''}::${owner.profile ?? ''}`+}++/** Validated outcome of an acquire: warm, settled-nothing-to-warm (cloud), or cold (must retry). */+type WarmState = 'cold' | 'noop' | 'warm'++/**+ * A settled acquire is an honest warm-up only when the backend warmed (or had)+ * the model. `noop` is the legitimate cloud/local_command-with-no-model+ * outcome — settled, nothing to warm, not an error. `error` (and `ok: false`)+ * means the model is NOT hot regardless of the HTTP 200, so the next listen+ * must retry instead of trusting the registration.+ */+function classifyAcquire(response: AudioSttLeaseResponse): WarmState {+ if (!response?.ok || response.action === 'error') {+ return 'cold'+ }++ if (response.warmed === true || response.action === 'cached' || response.action === 'loaded') {+ return 'warm'+ }++ return 'noop'+}++/** Latest registered intent per (lease, owner): true = acquire, false = release. */+const intent = new Map<string, boolean>()+/** Last acquire's validated warm-up per (lease, owner), with when it was validated. */+const warm = new Map<string, { at: number; state: WarmState }>()const inFlight = new Map<string, Promise<void>>()+/** Keys with an acquire queued or on the wire — later identical acquires ride that promise. */+const acquiring = new Set<string>()/**- * 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+ * Bring the backend's view of `lease` in line with `active`, owned by `owner`.+ * Idempotent within the freshness window: a repeat acquire while a validated+ * warm-up is fresh (or an identical acquire is already in flight) is a no-op —+ * but a stale/failed validation re-warms, because unlike TTS the backend does+ * not pin the model while a lease is held. 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)+export function syncSttLease(lease: string, active: boolean, owner?: SttLeaseOwner): Promise<void> {+ const scope = resolveOwner(owner)+ const key = keyFor(lease, scope)- if (last === active || (last === undefined && !active)) {- return inFlight.get(lease) ?? Promise.resolve()+ if (!active && intent.get(key) !== true) {+ // Never held (or already released): nothing to send. A release queued+ // behind an in-flight acquire has intent true and rides the chain below.+ return inFlight.get(key) ?? Promise.resolve()}- sent.set(lease, active)+ if (active) {+ // An identical acquire is already going out — dedupe at the source so the+ // wire sees one acquire, and callers (the readiness barrier) can await it.+ if (acquiring.has(key)) {+ return inFlight.get(key) ?? Promise.resolve()+ }- const previous = inFlight.get(lease) ?? Promise.resolve()+ const warmState = warm.get(key)+ if (+ intent.get(key) === true &&+ warmState &&+ warmState.state !== 'cold' &&+ Date.now() - warmState.at < sttWarmRevalidateMs+ ) {+ // Registered AND readiness freshly validated — nothing to say.+ return inFlight.get(key) ?? Promise.resolve()+ }+ }++ intent.set(key, active)+ if (!active) {+ warm.delete(key)+ }++ const previous = inFlight.get(key) ?? 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) {+ if (intent.get(key) !== active) {return}- await setSttLease(lease, active)+ const response = await setSttLease(lease, active, scope)+ if (active) {+ warm.set(key, { at: Date.now(), state: classifyAcquire(response) })+ }}).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)+ // (A warm-up failure can also arrive as a RESOLVED `action: 'error'`+ // body — classifyAcquire records that as 'cold' so the next listening+ // start re-warms instead of trusting the registration.)+ if (intent.get(key) === active) {+ intent.delete(key)}+ warm.delete(key)}).finally(() => {- if (inFlight.get(lease) === next) {- inFlight.delete(lease)+ if (active) {+ acquiring.delete(key)+ }+ if (inFlight.get(key) === next) {+ inFlight.delete(key)}})- inFlight.set(lease, next)+ if (active) {+ acquiring.add(key)+ }+ inFlight.set(key, next)return next}-/** Test seam — forget every sent state. */+/** Test seams. */export function resetSttLeasesForTests() {- sent.clear()+ intent.clear()+ warm.clear()inFlight.clear()+ acquiring.clear()+ sttWarmRevalidateMs = STT_WARM_REVALIDATE_MS_DEFAULT+}++export function setSttWarmRevalidateMsForTests(ms: number) {+ const saved = sttWarmRevalidateMs+ sttWarmRevalidateMs = ms++ return () => {+ sttWarmRevalidateMs = saved+ }}diff --git a/tests/hermes_cli/test_web_server_stt_lease.py b/tests/hermes_cli/test_web_server_stt_lease.pyindex fc6d27daae9..aa421b87919 100644--- a/tests/hermes_cli/test_web_server_stt_lease.py+++ b/tests/hermes_cli/test_web_server_stt_lease.py@@ -10,6 +10,8 @@ gateway/CLI surfaces in the same backend process.from __future__ import annotations+import time+import pytest@@ -213,3 +215,97 @@ def test_warm_never_raises_on_engine_failure(monkeypatch):assert result["warmed"] is Falseassert result["action"] == "error"assert "CUDA exploded" in result["error"]+++def test_warm_only_load_starts_idle_unload_watcher(monkeypatch):+ """A model loaded ONLY by warm-up (mic open → cancel, no transcription)+ must still be governed by ``stt.local.unload_after_idle_seconds``.++ Pre-fix, ``_start_idle_unload_watcher`` only ran after a successful+ ``_transcribe_local``, so the warm-only path left the model resident with+ no watcher until some later transcription happened. The regression+ executes the real acquire/load path with a fresh process-like state and+ asserts the watcher started and eventually evicts the model.+ """+ from tools import stt_lease, transcription_tools++ _local_cfg(monkeypatch)+ monkeypatch.setattr(+ transcription_tools,+ "_load_stt_config",+ lambda: {"local": {"model": "tiny", "unload_after_idle_seconds": 1}},+ )++ loaded = []+ monkeypatch.setattr(transcription_tools, "_IDLE_UNLOAD_CHECK_INTERVAL", 0.01)+ monkeypatch.setattr(transcription_tools, "_local_model", None)+ monkeypatch.setattr(transcription_tools, "_local_model_name", None)+ monkeypatch.setattr(transcription_tools, "_idle_unload_thread", None)+ # Backdate the activity so the first watcher cycle (0.01s) already sees+ # the configured idle window as elapsed.+ monkeypatch.setattr(transcription_tools, "_last_transcription_time", 0.0)+ real_model = object()+ monkeypatch.setattr(+ transcription_tools,+ "_get_or_load_local_model",+ lambda name, cfg: loaded.append(name) or real_model,+ )+ # The idle watcher reads the module global, not the warm-up's local ref,+ # so mirror the singleton the real loader would have written.+ transcription_tools._local_model = real_model+ transcription_tools._local_model_name = "tiny"++ result = stt_lease.warm_stt_provider()++ assert result["warmed"] is True+ assert loaded == ["tiny"]+ # The watcher is running (fresh process: no prior watcher thread).+ assert transcription_tools._idle_unload_thread is not None+ assert transcription_tools._idle_unload_thread.is_alive()+ # ...and eventually enforces the configured idle lifetime.+ for _ in range(200):+ if transcription_tools._local_model is None:+ break+ time.sleep(0.02)+ assert transcription_tools._local_model is None+++def test_warm_reacquire_after_eviction_restarts_watcher(monkeypatch):+ """After a prior watcher evicted its model and exited, a warm-up that+ reloads it must start a NEW watcher — the old thread is gone."""+ from tools import stt_lease, transcription_tools++ _local_cfg(monkeypatch)+ monkeypatch.setattr(+ transcription_tools,+ "_load_stt_config",+ lambda: {"local": {"model": "tiny", "unload_after_idle_seconds": 60}},+ )+ monkeypatch.setattr(transcription_tools, "_IDLE_UNLOAD_CHECK_INTERVAL", 0.5)+ # Simulate the post-eviction world: model gone, previous watcher exited.+ monkeypatch.setattr(transcription_tools, "_local_model", None)+ monkeypatch.setattr(transcription_tools, "_local_model_name", None)+ monkeypatch.setattr(+ transcription_tools, "_idle_unload_thread", type("Dead", (), {"is_alive": lambda self: False})()+ )++ real_model = object()+ monkeypatch.setattr(+ transcription_tools, "_get_or_load_local_model", lambda name, cfg: real_model+ )+ transcription_tools._local_model = real_model+ transcription_tools._local_model_name = "tiny"++ result = stt_lease.warm_stt_provider()++ assert result["warmed"] is True+ # A NEW watcher is running for the reloaded model.+ assert transcription_tools._idle_unload_thread is not None+ assert transcription_tools._idle_unload_thread.is_alive()+ # Clean up the daemon so it does not leak into other tests.+ transcription_tools._idle_unload_stop.set()+ transcription_tools._idle_unload_thread.join(timeout=2)+ transcription_tools._idle_unload_stop.clear()+ transcription_tools._local_model = None+ transcription_tools._local_model_name = None+ transcription_tools._idle_unload_thread = Nonediff --git a/tools/stt_lease.py b/tools/stt_lease.pyindex f7bd255a0e6..4864001d404 100644--- a/tools/stt_lease.py+++ b/tools/stt_lease.py@@ -80,6 +80,15 @@ def warm_stt_provider(# 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()+ # Register with the idle-lifetime mechanism: a model loaded ONLY by+ # warm-up (mic open → cancel, no transcription) would otherwise sit+ # resident with no watcher, silently ignoring+ # stt.local.unload_after_idle_seconds until some later successful+ # transcription starts one. Also covers the reload-after-prior-eviction+ # case (the previous watcher exited after unloading).+ idle_timeout = transcription_tools._get_idle_unload_seconds(local_cfg)+ if idle_timeout > 0:+ transcription_tools._start_idle_unload_watcher(idle_timeout)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))