The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): pin each voice operation to one owner and fence stale STT continuations
Brooklyn Nicholson7ee2840c06f5
diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.tsindex cdb8973d931..c6a727599b8 100644--- a/apps/desktop/src/api/client.ts+++ b/apps/desktop/src/api/client.ts@@ -98,6 +98,38 @@ export function ownerScoped(owner?: OwnerScope): { connectionId?: string; priori}}+/** An owner resolved ONCE for one operation (a recording, a voice conversation).+ * `null` halves mean "untagged": the primary profile / the connection an+ * untagged request lands on. They are never re-read from the ambient scope+ * later, so a gateway/profile switch mid-operation cannot move its tail+ * (release, transcription) to another backend. */+export interface ResolvedOwner {+ connectionId: null | string+ profile: null | string+}++/** Fill an owner's missing halves from the ambient scope, now. */+export function resolveOwnerNow(owner?: OwnerScope): ResolvedOwner {+ const ambient = $apiRequestScope.get()++ return {+ connectionId: owner?.connectionId || ambient.connectionId || null,+ profile: owner?.profile || ambient.profile || null+ }+}++/** `hermesApi` for a resolved owner: its tags are sent verbatim, with no+ * ambient connection spread underneath. An untagged half stays untagged. A+ * named profile is always explicit here, so it carries the foreground+ * priority `profileScoped` gives explicit profiles (voice is user-driven). */+export function hermesApiAs<T>(owner: ResolvedOwner, request: HermesApiRequest): Promise<T> {+ return window.hermesDesktop.api<T>({+ ...(owner.connectionId ? { connectionId: owner.connectionId } : {}),+ ...(owner.profile ? { priority: 'foreground' as const, profile: owner.profile } : {}),+ ...request+ })+}+/** Profile that profile-scoped REST/WS calls should target (null → primary).* Read-only twin of setApiRequestProfile for modules (e.g. voice playback)* that build their own connection URLs and must stay on the same backend. */diff --git a/apps/desktop/src/api/system.ts b/apps/desktop/src/api/system.tsindex 021b0392dc5..6b729c57ba5 100644--- a/apps/desktop/src/api/system.ts+++ b/apps/desktop/src/api/system.ts@@ -14,7 +14,16 @@ import type {MemoryStatusResponse} from '@/types/hermes'-import { capabilityScoped, hermesApi, type OwnerScope, ownerScoped, type ProfileScope, profileScoped } from './client'+import {+ capabilityScoped,+ hermesApi,+ hermesApiAs,+ type OwnerScope,+ ownerScoped,+ type ProfileScope,+ profileScoped,+ type ResolvedOwner+} from './client'export const AUDIO_SPEAK_MIN_REQUEST_TIMEOUT_MS = 180_000export const AUDIO_SPEAK_MAX_REQUEST_TIMEOUT_MS = 600_000@@ -169,11 +178,16 @@ export function getActionStatus(name: string, lines = 200, profile?: ProfileScop})}-export function transcribeAudio(dataUrl: string, mimeType?: string): Promise<AudioTranscriptionResponse> {- return hermesApi<AudioTranscriptionResponse>({+/** `owner` = the recording's owner, resolved when the mic opened: the audio is+ * decoded on the backend its STT warm-up targeted. Omitted → the active scope. */+export function transcribeAudio(+ dataUrl: string,+ mimeType?: string,+ owner?: ResolvedOwner+): Promise<AudioTranscriptionResponse> {+ const request = {path: '/api/audio/transcribe',method: 'POST',- ...profileScoped(),body: {data_url: dataUrl,mime_type: mimeType@@ -182,7 +196,11 @@ export function transcribeAudio(dataUrl: string, mimeType?: string): Promise<Aud// encoding finish. Remote providers and long clips regularly exceed the// default 15s Electron backend timeout.timeoutMs: audioTranscribeRequestTimeoutMs(dataUrl)- })+ }++ return owner+ ? hermesApiAs<AudioTranscriptionResponse>(owner, request)+ : hermesApi<AudioTranscriptionResponse>({ ...profileScoped(), ...request })}// `owner` = the speaking session's (connection, profile) — a Bot's own TTS@@ -230,13 +248,11 @@ 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>`. `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`).+ * the voice operation's owner, resolved once when it started, so a queued call+ * is never re-routed by a later gateway/profile switch.*/-export function setSttLease(lease: string, active: boolean, owner?: OwnerScope): Promise<AudioSttLeaseResponse> {- return hermesApi<AudioSttLeaseResponse>({- ...ownerScoped(owner),+export function setSttLease(lease: string, active: boolean, owner: ResolvedOwner): Promise<AudioSttLeaseResponse> {+ return hermesApiAs<AudioSttLeaseResponse>(owner, {path: '/api/audio/stt-lease',method: 'POST',body: { active, lease },diff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation-meter.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation-meter.test.tsxindex e881e117a46..017e2fe4e46 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation-meter.test.tsx+++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation-meter.test.tsx@@ -95,7 +95,7 @@ describe('useVoiceConversation with a failed level meter', () => {lastStartOptions().onMeterFailure?.()})- await waitFor(() => expect(onTranscribeAudio).toHaveBeenCalledWith(take.audio))+ await waitFor(() => expect(onTranscribeAudio).toHaveBeenCalledWith(take.audio, expect.anything()))await waitFor(() => expect(onSubmit).toHaveBeenCalledWith('what time is it'))})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.tsxindex f4103e0ed19..fd95dbcd766 100644--- 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.tsx@@ -1,9 +1,7 @@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@@ -22,10 +20,10 @@ vi.mock('./use-mic-recorder', () => ({useMicRecorder: () => ({ handle: micHandle, level: 0, recording: false })}))-const syncSttLeaseSpy = vi.fn(async () => undefined)+const syncSttLeaseSpy = vi.fn(async (..._args: unknown[]): Promise<void> => undefined)vi.mock('@/lib/stt-lease', () => ({- syncSttLease: (...args: unknown[]) => syncSttLeaseSpy(...(args as [])),+ syncSttLease: (...args: unknown[]) => syncSttLeaseSpy(...args),VOICE_INPUT_LEASE: 'desktop:voice-input:test'}))@@ -99,9 +97,23 @@ vi.mock('../scope', () => ({useComposerScope: () => ({ $messages: { get: () => [] }, connectionId: undefined, profile: undefined })}))+// The ambient selection resolveOwnerNow reads; tests flip it mid-conversation.+const ambient = { connectionId: 'gateway-a' as null | string, profile: 'worker_alpha' as null | string }++vi.mock('@/hermes', () => ({+ resolveOwnerNow: (owner?: { connectionId?: string; profile?: string }) => ({+ connectionId: owner?.connectionId || ambient.connectionId,+ profile: owner?.profile || ambient.profile+ })+}))++const OWNER_A = { connectionId: 'gateway-a', profile: 'worker_alpha' }+describe('useVoiceConversation STT readiness barrier', () => {beforeEach(() => {cleanup()+ ambient.connectionId = 'gateway-a'+ ambient.profile = 'worker_alpha'micHandle.start.mockClear()micHandle.cancel.mockClear()micHandle.stop.mockReset()@@ -114,13 +126,16 @@ describe('useVoiceConversation STT readiness barrier', () => {cleanup()})- function renderConversation(onTranscribeAudio: (audio: Blob) => Promise<string>) {+ function renderConversation(+ onTranscribeAudio: (audio: Blob, owner?: unknown) => Promise<string>,+ onSubmit: (text: string) => void = () => undefined+ ) {const hook = renderHook(() =>useVoiceConversation({busy: false,consumePendingResponse: () => undefined,enabled: true,- onSubmit: () => undefined,+ onSubmit,onTranscribeAudio,pendingResponse: () => null})@@ -150,10 +165,7 @@ describe('useVoiceConversation STT readiness barrier', () => {await Promise.resolve()})expect(micHandle.start).toHaveBeenCalledTimes(1)- expect(syncSttLeaseSpy).toHaveBeenCalledWith('desktop:voice-input:test', true, {- connectionId: undefined,- profile: undefined- })+ expect(syncSttLeaseSpy).toHaveBeenCalledWith('desktop:voice-input:test', true, OWNER_A)// The VAD silence callback fires a turn while the cold load is in flight.let turnPromise: Promise<void> = Promise.resolve()@@ -175,4 +187,69 @@ describe('useVoiceConversation STT readiness barrier', () => {await waitFor(() => expect(transcribe).toHaveBeenCalledTimes(1))expect(await transcribe.mock.results[0].value).toBe('hello world')})++ // #128668 review (P1): end() while the warm-up is still settling fences the+ // turn — no transcription, no submit into a conversation that is over.+ it('drops the turn when the conversation ends while the warm-up is settling', async () => {+ let settleWarmup!: () => void+ syncSttLeaseSpy.mockImplementationOnce(+ () =>+ new Promise<void>(resolve => {+ settleWarmup = resolve+ })+ )++ const transcribe = vi.fn(async () => 'hello world')+ const onSubmit = vi.fn()+ const hook = renderConversation(transcribe, onSubmit)++ await act(async () => {+ await hook.result.current.start()+ })++ let turnPromise: Promise<void> = Promise.resolve()+ await act(async () => {+ turnPromise = Promise.resolve(hook.result.current.stopTurn())+ await Promise.resolve()+ await Promise.resolve()+ })++ await act(async () => {+ hook.result.current.end()+ })+ expect(syncSttLeaseSpy).toHaveBeenLastCalledWith('desktop:voice-input:test', false, OWNER_A)++ settleWarmup()+ await act(async () => {+ await turnPromise+ })++ expect(transcribe).not.toHaveBeenCalled()+ expect(onSubmit).not.toHaveBeenCalled()+ })++ // #128668 review: one owner per conversation, resolved at start().+ it('transcribes and releases on the start() owner across a mid-conversation switch', async () => {+ const transcribe = vi.fn(async (_audio: Blob, _owner?: unknown) => 'hello world')+ const hook = renderConversation(transcribe)++ await act(async () => {+ await hook.result.current.start()+ })++ ambient.connectionId = null+ ambient.profile = null++ await act(async () => {+ await hook.result.current.stopTurn()+ })+ await waitFor(() => expect(transcribe).toHaveBeenCalledTimes(1))+ expect(transcribe.mock.calls[0][1]).toEqual(OWNER_A)++ await act(async () => {+ hook.result.current.end()+ })+ expect(syncSttLeaseSpy.mock.calls.every(call => JSON.stringify(call[2]) === JSON.stringify(OWNER_A))).toBe(true)+ expect(syncSttLeaseSpy).toHaveBeenLastCalledWith('desktop:voice-input:test', false, OWNER_A)+ })})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 4e3d2409650..45000574bd9 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@@ -1,5 +1,6 @@import { useCallback, useEffect, useRef, useState } from 'react'+import { type ResolvedOwner, resolveOwnerNow } from '@/hermes'import { useI18n } from '@/i18n'import { IncrementalSpeechSentenceBuffer } from '@/lib/speech-text'import { syncSttLease, VOICE_INPUT_LEASE } from '@/lib/stt-lease'@@ -40,7 +41,7 @@ interface VoiceConversationOptions {onInterrupt?: () => Promise<void> | voidonStopWord?: () => voidonSubmit: (text: string) => Promise<void> | void- onTranscribeAudio?: (audio: Blob) => Promise<string>+ onTranscribeAudio?: (audio: Blob, owner?: ResolvedOwner) => Promise<string>pendingResponse: () => PendingVoiceResponse | nullconsumePendingResponse: () => void/** Awaited right before the mic is opened. Used to let the wake-word listener@@ -48,6 +49,18 @@ interface VoiceConversationOptions {beforeMicOpen?: () => Promise<void> | void}+/**+ * One voice conversation, from start() to end(). Its STT owner is resolved+ * once at start and used for every warm-up, transcription and the final+ * release. `warmup` is the latest listening start's warm-up: transcription+ * awaits it so a cold model load never runs inside the transcription+ * request's decode budget (#105955).+ */+interface Conversation {+ owner: ResolvedOwner+ warmup: Promise<void>+}+/** How long a barge-triggered interrupt may take to settle before we submit* the captured utterance anyway. */const INTERRUPT_SETTLE_TIMEOUT_MS = 5_000@@ -88,12 +101,11 @@ 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)+ // The live conversation. Every await in a turn is followed by a check that+ // it is still this one: end() and unmount clear it (and a new start()+ // replaces it), so a warm-up or transcript settling afterwards cannot+ // transcribe, submit, or move status.+ const conversationRef = useRef<Conversation | null>(null)const responseIdRef = useRef<string | null>(null)const spokenSourceLengthRef = useRef(0)const speechSessionRef = useRef<null | SpeechStreamSession>(null)@@ -156,6 +168,18 @@ export function useVoiceConversation({useEffect(() => () => cancelFallbackPollRef.current?.(), [])+ useEffect(+ () => () => {+ const conversation = conversationRef.current+ conversationRef.current = null++ if (conversation) {+ void syncSttLease(VOICE_INPUT_LEASE, false, conversation.owner)+ }+ },+ []+ )+const clearTurnTimeout = () => {if (turnTimeoutRef.current) {window.clearTimeout(turnTimeoutRef.current)@@ -184,9 +208,16 @@ export function useVoiceConversation({turnClosingRef.current = trueclearTurnTimeout()setStatus('transcribing')+ const conversation = conversationRef.current+ const live = () => conversation !== null && conversationRef.current === conversationtry {const result = await handle.stop()++ if (!conversation || !live()) {+ return // ended while the recorder stopped+ }+const meterFailed = Boolean(result?.meterFailed)meterFailuresRef.current = meterFailed ? meterFailuresRef.current + 1 : 0@@ -224,8 +255,17 @@ export function useVoiceConversation({// 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.current- const transcript = (await onTranscribeAudio(result.audio)).trim()+ await conversation.warmup++ if (!live()) {+ return+ }++ const transcript = (await onTranscribeAudio(result.audio, conversation.owner)).trim()++ if (!live()) {+ return+ }if (!transcript) {if (enabledRef.current) {@@ -259,8 +299,15 @@ export function useVoiceConversation({// one arrives and barges in.consumePendingResponse()await onSubmit(transcript)- setStatus('thinking')++ if (live()) {+ setStatus('thinking')+ }} catch (error) {+ if (!live()) {+ return+ }+notifyError(error, voiceCopy.transcriptionFailed)if (enabledRef.current && !mutedRef.current && !busyRef.current) {@@ -310,7 +357,9 @@ export function useVoiceConversation({}// enabled/muted/busy or an interleaved turn may have changed while we waited.- if (!enabledRef.current || mutedRef.current || busyRef.current || statusRef.current !== 'idle') {+ const conversation = conversationRef.current++ if (!conversation || !enabledRef.current || mutedRef.current || busyRef.current || statusRef.current !== 'idle') {return}@@ -334,12 +383,11 @@ 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 — 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)+ // Sent on every listening start: the idle watcher may have evicted the+ // model during a long reply or a mute, and the backend re-warm is a+ // cache hit otherwise. The promise is the readiness barrier the+ // transcription paths await before submitting audio.+ conversation.warmup = syncSttLease(VOICE_INPUT_LEASE, true, conversation.owner)// 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@@ -402,6 +450,8 @@ export function useVoiceConversation({const submitCapturedUtterance = useCallback(async (audio: Blob | null) => {const echoSource = bargeEchoTextRef.current+ const conversation = conversationRef.current+ const live = () => conversation !== null && conversationRef.current === conversationbargeEchoTextRef.current = ''@@ -413,6 +463,10 @@ export function useVoiceConversation({setStatus('idle')}+ if (!conversation || !live()) {+ return // ended while the barge monitor was capturing+ }+if (!audio || !onTranscribeAudio) {resumeListening()@@ -426,8 +480,17 @@ export function useVoiceConversation({// 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.current- const transcript = (await onTranscribeAudio(audio)).trim()+ await conversation.warmup++ if (!live()) {+ return+ }++ const transcript = (await onTranscribeAudio(audio, conversation.owner)).trim()++ if (!live()) {+ return+ }if (!transcript) {resumeListening()@@ -466,14 +529,23 @@ export function useVoiceConversation({await new Promise(resolve => window.setTimeout(resolve, 100))}+ if (!live()) {+ return+ }+awaitingSpokenResponseRef.current = truedropSpeechSession()consumePendingResponse()await onSubmit(transcript)- setStatus('thinking')++ if (live()) {+ setStatus('thinking')+ }} catch (error) {- notifyError(error, voiceCopy.transcriptionFailed)- resumeListening()+ if (live()) {+ notifyError(error, voiceCopy.transcriptionFailed)+ resumeListening()+ }}},[consumePendingResponse, onSubmit, onTranscribeAudio, voiceCopy.transcriptionFailed]@@ -818,6 +890,9 @@ export function useVoiceConversation({awaitingSpokenResponseRef.current = falsedropSpeechSession()consumePendingResponse()+ // A fresh conversation: its owner is resolved now and kept to the end.+ // Replacing the ref also fences any continuation of a previous one.+ conversationRef.current = { owner: resolveOwnerNow(ownerRef.current), warmup: Promise.resolve() }pendingStartRef.current = trueawait startListening()}, [@@ -838,11 +913,18 @@ 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. Released to- // the owner that acquired it, not whatever is selected now.- void syncSttLease(VOICE_INPUT_LEASE, false, ownerRef.current)+ // Conversation over: drop the STT lease to the owner that acquired it,+ // and fence every continuation still awaiting a warm-up or transcript.+ // 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.+ const conversation = conversationRef.current+ conversationRef.current = null++ if (conversation) {+ void syncSttLease(VOICE_INPUT_LEASE, false, conversation.owner)+ }+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.tsxindex f73c5f4503b..99dd2b9b81e 100644--- 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.tsx@@ -2,7 +2,6 @@ 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@@ -14,6 +13,7 @@ import { useVoiceRecorder } from './use-voice-recorder'// The real recorder flips `recording` in start/stop; dictate() routes on it.let recording = false+const micHandle = {cancel: vi.fn(),start: vi.fn(async () => {@@ -30,10 +30,10 @@ vi.mock('./use-mic-recorder', () => ({useMicRecorder: () => ({ handle: micHandle, level: 0, get recording() { return recording } })}))-const syncSttLeaseSpy = vi.fn(async () => undefined)+const syncSttLeaseSpy = vi.fn(async (..._args: unknown[]): Promise<void> => undefined)vi.mock('@/lib/stt-lease', () => ({- syncSttLease: (...args: unknown[]) => syncSttLeaseSpy(...(args as [])),+ syncSttLease: (...args: unknown[]) => syncSttLeaseSpy(...args),VOICE_INPUT_LEASE: 'desktop:voice-input:test'}))@@ -67,10 +67,24 @@ vi.mock('../scope', () => ({useComposerScope: () => ({ connectionId: undefined, profile: undefined })}))+// The ambient selection resolveOwnerNow reads; tests flip it mid-recording.+const ambient = { connectionId: 'gateway-a' as null | string, profile: 'worker_alpha' as null | string }++vi.mock('@/hermes', () => ({+ resolveOwnerNow: (owner?: { connectionId?: string; profile?: string }) => ({+ connectionId: owner?.connectionId || ambient.connectionId,+ profile: owner?.profile || ambient.profile+ })+}))++const OWNER_A = { connectionId: 'gateway-a', profile: 'worker_alpha' }+describe('useVoiceRecorder STT readiness barrier', () => {beforeEach(() => {cleanup()recording = false+ ambient.connectionId = 'gateway-a'+ ambient.profile = 'worker_alpha'micHandle.start.mockClear()micHandle.stop.mockReset()micHandle.stop.mockImplementation(async () => {@@ -86,12 +100,15 @@ describe('useVoiceRecorder STT readiness barrier', () => {cleanup()})- function renderRecorder(onTranscribeAudio: (audio: Blob) => Promise<string>) {+ function renderRecorder(+ onTranscribeAudio: (audio: Blob, owner?: unknown) => Promise<string>,+ onTranscript: (text: string) => void = () => undefined+ ) {return renderHook(() =>useVoiceRecorder({focusInput: () => undefined,maxRecordingSeconds: 30,- onTranscript: () => undefined,+ onTranscript,onTranscribeAudio}))@@ -118,10 +135,7 @@ describe('useVoiceRecorder STT readiness barrier', () => {await Promise.resolve()})expect(micHandle.start).toHaveBeenCalledTimes(1)- expect(syncSttLeaseSpy).toHaveBeenCalledWith('desktop:voice-input:test', true, {- connectionId: undefined,- profile: undefined- })+ expect(syncSttLeaseSpy).toHaveBeenCalledWith('desktop:voice-input:test', true, OWNER_A)// User stops after a short clip — but the cold load is still in flight.let stopping: Promise<void> = Promise.resolve()@@ -164,8 +178,10 @@ describe('useVoiceRecorder STT readiness barrier', () => {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')+ // #128668 review: one owner per recording — resolved at mic-open, used for+ // the warm-up, the transcription and the release.+ it('keeps warm-up, transcription and release on the mic-open owner across a mid-recording switch', async () => {+ const transcribe = vi.fn(async (_audio: Blob, _owner?: unknown) => 'hello world')const hook = renderRecorder(transcribe)await act(async () => {@@ -174,14 +190,91 @@ describe('useVoiceRecorder STT readiness barrier', () => {await act(async () => {await Promise.resolve()})++ ambient.connectionId = null+ ambient.profile = null+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(call => call[1] === false)- expect(releaseCall).toEqual(['desktop:voice-input:test', false, { connectionId: undefined, profile: undefined }])+ expect(transcribe.mock.calls[0][1]).toEqual(OWNER_A)+ expect(syncSttLeaseSpy.mock.calls).toEqual([+ ['desktop:voice-input:test', true, OWNER_A],+ ['desktop:voice-input:test', false, OWNER_A]+ ])+ })++ // #128668 review (P1): a warm-up settling after unmount must not transcribe+ // or insert text into a torn-down composer.+ it('drops the dictation when the composer unmounts while the warm-up is settling', async () => {+ let settleWarmup!: () => void+ syncSttLeaseSpy.mockImplementationOnce(+ () =>+ new Promise<void>(resolve => {+ settleWarmup = resolve+ })+ )++ const transcribe = vi.fn(async () => 'hello world')+ const onTranscript = vi.fn()+ const hook = renderRecorder(transcribe, onTranscript)++ await act(async () => {+ hook.result.current.dictate()+ })+ await act(async () => {+ await Promise.resolve()+ })++ let stopping: Promise<void> = Promise.resolve()+ await act(async () => {+ stopping = hook.result.current.dictate() ?? Promise.resolve()+ await Promise.resolve()+ })++ hook.unmount()+ // Unmount releases to the owner that acquired.+ expect(syncSttLeaseSpy).toHaveBeenLastCalledWith('desktop:voice-input:test', false, OWNER_A)++ settleWarmup()+ await stopping++ expect(transcribe).not.toHaveBeenCalled()+ expect(onTranscript).not.toHaveBeenCalled()+ })++ it('drops a transcript that settles after unmount', async () => {+ let finishTranscription!: (text: string) => void++ const transcribe = vi.fn(+ () =>+ new Promise<string>(resolve => {+ finishTranscription = resolve+ })+ )++ const onTranscript = vi.fn()+ const hook = renderRecorder(transcribe, onTranscript)++ await act(async () => {+ hook.result.current.dictate()+ })+ await act(async () => {+ await Promise.resolve()+ })++ let stopping: Promise<void> = Promise.resolve()+ await act(async () => {+ stopping = hook.result.current.dictate() ?? Promise.resolve()+ })+ await waitFor(() => expect(transcribe).toHaveBeenCalledTimes(1))++ hook.unmount()+ finishTranscription('late words')+ await stopping++ expect(onTranscript).not.toHaveBeenCalled()})})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 0cba8a9223a..d93643eb85c 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,24 +1,33 @@import { useEffect, useRef, useState } from 'react'+import { type ResolvedOwner, resolveOwnerNow } from '@/hermes'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 { useComposerScope } from '../scope'import type { VoiceActivityState, VoiceStatus } from '../types'import { useMicRecorder } from './use-mic-recorder'interface VoiceRecorderOptions {maxRecordingSeconds: number- onTranscribeAudio?: (audio: Blob) => Promise<string>+ onTranscribeAudio?: (audio: Blob, owner?: ResolvedOwner) => Promise<string>focusInput: () => voidonTranscript: (text: string) => void}-/** Settles when the STT warm-up issued at mic-open resolves (or never ran). */-type WarmupBarrier = null | Promise<void>+/**+ * One dictation, from mic-open to the settled transcript. Its owner is+ * resolved once at mic-open and used for the warm-up, the transcription and+ * the release, so a gateway/profile switch mid-recording cannot split them+ * across backends. `warmup` settles when that mic-open warm-up settled.+ */+interface Dictation {+ owner: ResolvedOwner+ warmup: Promise<void>+}export function useVoiceRecorder({maxRecordingSeconds,@@ -29,8 +38,8 @@ 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.+ // The scope's session owner (a Bot tile's own connection + profile); the+ // main composer leaves it unset and the ambient scope fills it at mic-open.const { connectionId: ownerConnectionId, profile: ownerProfile } = useComposerScope()const ownerRef = useRef({ connectionId: ownerConnectionId, profile: ownerProfile })ownerRef.current = { connectionId: ownerConnectionId, profile: ownerProfile }@@ -39,13 +48,12 @@ export function useVoiceRecorder({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)+ // The live dictation. stop() awaits its warm-up before transcribing (a cold+ // model load must not run inside the transcription request's decode+ // budget, #105955) and checks it is still the live one after every await:+ // unmount clears it, so a warm-up or transcript settling afterwards cannot+ // transcribe, insert text or move focus.+ const dictationRef = useRef<Dictation | null>(null)const clearTimers = () => {if (intervalRef.current) {@@ -59,19 +67,31 @@ export function useVoiceRecorder({}}- useEffect(() => () => clearTimers(), [])+ useEffect(+ () => () => {+ clearTimers()+ const dictation = dictationRef.current+ dictationRef.current = null++ if (dictation) {+ void syncSttLease(VOICE_INPUT_LEASE, false, dictation.owner)+ }+ },+ []+ )const stop = async () => {clearTimers()+ const dictation = dictationRef.currentconst result = await handle.stop()+ const live = () => dictation !== null && dictationRef.current === dictation- if (!result) {- setVoiceStatus('idle')-- return+ if (!dictation || !live()) {+ return // unmounted (or never started) while the recorder stopped}- if (!onTranscribeAudio) {+ if (!result || !onTranscribeAudio) {+ finish(dictation)setVoiceStatus('idle')return@@ -83,10 +103,18 @@ export function useVoiceRecorder({// 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.current- const transcript = (await onTranscribeAudio(result.audio)).trim()+ // and its budget is the lease request's own 180 s timeout.+ await dictation.warmup++ if (!live()) {+ return+ }++ const transcript = (await onTranscribeAudio(result.audio, dictation.owner)).trim()++ if (!live()) {+ return+ }if (!transcript) {notify({ kind: 'warning', title: voiceCopy.noSpeechDetected, message: voiceCopy.tryRecordingAgain })@@ -94,16 +122,26 @@ export function useVoiceRecorder({onTranscript(transcript)}} catch (error) {- notifyError(error, voiceCopy.transcriptionFailed)+ if (live()) {+ 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, ownerRef.current)- focusInput()+ if (live()) {+ finish(dictation)+ setVoiceStatus('idle')+ focusInput()+ }}}+ // The transcript settled (or failed): this dictation no longer needs the+ // engine held. Released to the owner that acquired it. The backend keeps the+ // shared model resident regardless.+ const finish = (dictation: Dictation) => {+ dictationRef.current = null+ void syncSttLease(VOICE_INPUT_LEASE, false, dictation.owner)+ }+const start = async () => {if (!onTranscribeAudio) {notify({ kind: 'warning', title: voiceCopy.unavailable, message: voiceCopy.transcriptionUnavailable })@@ -117,11 +155,9 @@ export function useVoiceRecorder({// engine now so a cold local model loads while the user is still// speaking instead of inside the transcription timeout (#105955).// 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)+ // it as the readiness barrier before transcription (see above).+ const owner = resolveOwnerNow(ownerRef.current)+ dictationRef.current = { owner, warmup: syncSttLease(VOICE_INPUT_LEASE, true, owner) }startedAtRef.current = Date.now()setElapsedSeconds(0)setVoiceStatus('recording')diff --git a/apps/desktop/src/app/chat/composer/types.ts b/apps/desktop/src/app/chat/composer/types.tsindex b97ccedc7ab..f6b75dad09a 100644--- a/apps/desktop/src/app/chat/composer/types.ts+++ b/apps/desktop/src/app/chat/composer/types.ts@@ -1,7 +1,7 @@import type { ReactNode } from 'react'import type { SubmitTextOptions } from '@/app/session/hooks/use-prompt-actions/utils'-import type { HermesGateway } from '@/hermes'+import type { HermesGateway, ResolvedOwner } from '@/hermes'import type { DroppedFile } from '../hooks/use-composer-actions'@@ -65,7 +65,7 @@ export interface ChatBarProps {/** Delivers a hidden note to the model mid-turn with no user turn (gateway session.steer). */onSteerHidden?: (text: string) => Promise<boolean> | booleanonSubmit: (value: string, options?: SubmitTextOptions) => Promise<boolean> | boolean- onTranscribeAudio?: (audio: Blob) => Promise<string>+ onTranscribeAudio?: (audio: Blob, owner?: ResolvedOwner) => Promise<string>}export type VoiceStatus = 'idle' | 'recording' | 'transcribing'diff --git a/apps/desktop/src/app/chat/index.tsx b/apps/desktop/src/app/chat/index.tsxindex f85c3ec1f98..ed43c27522a 100644--- a/apps/desktop/src/app/chat/index.tsx+++ b/apps/desktop/src/app/chat/index.tsx@@ -17,7 +17,7 @@ import { usePaneGroup, usePaneVisible } from '@/components/pane-shell/pane-visibimport { $hoveredTreeGroup, $sessionTileDragging, $sessionTileEdgeHover } from '@/components/pane-shell/tree/store'import { PromptOverlays } from '@/components/prompt-overlays'import { TitleMenuTrigger } from '@/components/ui/title-menu-trigger'-import { type HermesGateway } from '@/hermes'+import { type HermesGateway, type ResolvedOwner } from '@/hermes'import { useI18n } from '@/i18n'import type { ChatMessage } from '@/lib/chat-messages'import { NEW_SESSION_TITLE, quickModelOptions, sessionTitle } from '@/lib/chat-runtime'@@ -119,7 +119,7 @@ interface ChatViewProps extends Omit<React.ComponentProps<'div'>, 'onSubmit'> {onReload: (parentId: string | null) => Promise<void>onRestoreToMessage?: (messageId: string, target?: { text?: string; userOrdinal?: number | null }) => Promise<void>onRetryResume: (sessionId: string) => void- onTranscribeAudio?: (audio: Blob) => Promise<string>+ onTranscribeAudio?: (audio: Blob, owner?: ResolvedOwner) => Promise<string>onDismissError?: (messageId: string) => void}diff --git a/apps/desktop/src/app/chat/session-tile.tsx b/apps/desktop/src/app/chat/session-tile.tsxindex 8ab87e4aea3..e46140d936c 100644--- a/apps/desktop/src/app/chat/session-tile.tsx+++ b/apps/desktop/src/app/chat/session-tile.tsx@@ -36,7 +36,7 @@ import {} from '@/components/pane-shell/workspace-scope'import { Button } from '@/components/ui/button'import { ConfirmDialog } from '@/components/ui/confirm-dialog'-import { transcribeAudio } from '@/hermes'+import { type ResolvedOwner, transcribeAudio } from '@/hermes'import { useI18n } from '@/i18n'import type { ChatMessage } from '@/lib/chat-messages'import { NEW_SESSION_TITLE, sessionTitle } from '@/lib/chat-runtime'@@ -226,17 +226,18 @@ function buildTileView(storedSessionId: string): SessionView {// tiles have no pin/delete affordance, and transcription needs no per-tile state.const noop = () => undefined-const tileTranscribeAudio = async (audio: Blob) => {+const tileTranscribeAudio = async (audio: Blob, owner?: ResolvedOwner) => {// Client-direct first (profile's own STT provider, no gateway audio hop);// relay when the provider is not client-callable. Same ladder as the main- // composer's transcribeVoiceAudio.- const direct = await transcribeAudioClientDirect(audio)+ // composer's transcribeVoiceAudio. `owner` is the recording's owner — the+ // tile's (connection, profile), resolved when its mic opened.+ const direct = await transcribeAudioClientDirect(audio, owner)if (direct !== null) {return direct}- return (await transcribeAudio(await blobToDataUrl(audio), audio.type)).transcript+ return (await transcribeAudio(await blobToDataUrl(audio), audio.type, owner)).transcript}function TileChat({diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.tsindex 986083e1b83..5c1b4f069d7 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts@@ -5,7 +5,7 @@ import { stripAnsi } from '@hermes/shared/ansi'import { useStore } from '@nanostores/react'import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'-import { transcribeAudio } from '@/hermes'+import { type ResolvedOwner, transcribeAudio } from '@/hermes'import { useI18n } from '@/i18n'import { attachmentPathNeedsUpload } from '@/lib/attachment-upload-policy'import { type ChatMessage, textPart } from '@/lib/chat-messages'@@ -642,7 +642,7 @@ export function usePromptActions({)const transcribeVoiceAudio = useCallback(- async (audio: Blob) => {+ async (audio: Blob, owner?: ResolvedOwner) => {if (!sttEnabled) {throw new Error(copy.sttDisabled)}@@ -652,15 +652,17 @@ export function usePromptActions({// the desktop→gateway audio hop. `null` = provider not client-callable// (local whisper, command providers, older backend) → relay unchanged.// Provider REJECTIONS surface — re-running the same request through- // the relay would fail identically, just slower.- const direct = await transcribeAudioClientDirect(audio)+ // the relay would fail identically, just slower. `owner` is the+ // recording's owner, resolved when the mic opened: the config lookup and+ // the relay decode on the backend its STT warm-up targeted.+ const direct = await transcribeAudioClientDirect(audio, owner)if (direct !== null) {return direct}const dataUrl = await blobToDataUrl(audio)- const result = await transcribeAudio(dataUrl, audio.type)+ const result = await transcribeAudio(dataUrl, audio.type, owner)return result.transcript},diff --git a/apps/desktop/src/hermes.test.ts b/apps/desktop/src/hermes.test.tsindex d0166dc5e07..c48c8c50552 100644--- a/apps/desktop/src/hermes.test.ts+++ b/apps/desktop/src/hermes.test.ts@@ -677,8 +677,8 @@ describe('Hermes REST helpers', () => {api.mockResolvedValueOnce({ ok: true })api.mockResolvedValueOnce({ ok: true })- await setSttLease('desktop:voice-input:abc', true)- await setSttLease('desktop:voice-input:abc', false)+ await setSttLease('desktop:voice-input:abc', true, { connectionId: null, profile: null })+ await setSttLease('desktop:voice-input:abc', false, { connectionId: null, profile: null })expect(api).toHaveBeenNthCalledWith(1, {body: { active: true, lease: 'desktop:voice-input:abc' },@@ -694,16 +694,16 @@ 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.+ it('sends an STT lease to its resolved owner verbatim — never the ambient selection', async () => {+ // #128668 review: the owner is resolved once per voice operation. A later+ // gateway/profile switch must not re-route it, and its untagged halves+ // must stay untagged instead of re-reading the ambient scope.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' })+ await setSttLease('desktop:voice-input:abc', false, { connectionId: null, profile: null })expect(api).toHaveBeenNthCalledWith(1, {body: { active: true, lease: 'desktop:voice-input:abc' },@@ -716,21 +716,23 @@ describe('Hermes REST helpers', () => {})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})+ })++ it('transcribes on the recording owner when one is given', async () => {+ setApiRequestConnection('gateway-b')+ setApiRequestProfile('worker_beta')+ api.mockResolvedValue({ ok: true, transcript: 'hi' })++ await transcribeAudio('data:audio/webm;base64,AAAA', 'audio/webm', { connectionId: 'gateway-a', profile: null })- // 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' })+ expect.objectContaining({ connectionId: 'gateway-a', path: '/api/audio/transcribe' }))+ expect(api.mock.calls.at(-1)?.[0]).not.toHaveProperty('profile')})it('defaults model options to configured providers only', async () => {diff --git a/apps/desktop/src/hermes.ts b/apps/desktop/src/hermes.tsindex 09eabaaa06c..2eb0101ad24 100644--- a/apps/desktop/src/hermes.ts+++ b/apps/desktop/src/hermes.ts@@ -11,11 +11,12 @@ export {HermesGateway,profileScopeKey,PROMPT_SUBMIT_REQUEST_TIMEOUT_MS,+ resolveOwnerNow,setApiRequestConnection,setApiRequestProfile,STARTUP_REQUEST_TIMEOUT_MS} from './api/client'-export type { ProfileScope } from './api/client'+export type { ProfileScope, ResolvedOwner } from './api/client'export * from './api/config'export * from './api/cron'export * from './api/local-models'diff --git a/apps/desktop/src/lib/stt-lease.test.ts b/apps/desktop/src/lib/stt-lease.test.tsindex 8fe1e3538d6..5d2be6aee93 100644--- a/apps/desktop/src/lib/stt-lease.test.ts+++ b/apps/desktop/src/lib/stt-lease.test.ts@@ -1,283 +1,188 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-const setSttLease = vi.fn(- async (- _lease: string,- _active: boolean,- _owner?: { connectionId?: null | string; profile?: null | string }- ) => ({ ok: true }) as { ok: boolean; action?: string; warmed?: boolean }-)+import type { ResolvedOwner } from '@/hermes'++const setSttLease = vi.fn(async (_lease: string, _active: boolean, _owner: ResolvedOwner) => ({ ok: true }))vi.mock('@/hermes', () => ({- getApiRequestConnection: () => currentScope.connectionId,- getApiRequestProfile: () => currentScope.profile,- setSttLease: (- lease: string,- active: boolean,- owner?: { connectionId?: null | string; profile?: null | string }- ) => setSttLease(lease, active, owner)+ setSttLease: (lease: string, active: boolean, owner: ResolvedOwner) => setSttLease(lease, active, owner)}))-import {- resetSttLeasesForTests,- setSttWarmRevalidateMsForTests,- syncSttLease,- VOICE_INPUT_LEASE-} from './stt-lease'+import { resetSttLeasesForTests, syncSttLease, VOICE_INPUT_LEASE } from './stt-lease'++const PRIMARY: ResolvedOwner = { connectionId: null, profile: null }+const ALPHA: ResolvedOwner = { connectionId: 'gateway-a', profile: 'worker_alpha' }+const BETA: ResolvedOwner = { connectionId: 'gateway-b', profile: 'worker_beta' }-// 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 }+/** Make the next setSttLease call hang until the returned function is called. */+function holdNextCall(): () => void {+ let finish: () => void = () => undefined+ setSttLease.mockImplementationOnce(+ () =>+ new Promise(resolve => {+ finish = () => resolve({ ok: true })+ })+ )-const resetScope = () => {- currentScope.connectionId = null- currentScope.profile = null+ return () => finish()}describe('syncSttLease', () => {beforeEach(() => {resetSttLeasesForTests()- resetScope()setSttLease.mockReset()setSttLease.mockImplementation(async () => ({ ok: true }))})- afterEach(() => {- resetSttLeasesForTests()- resetScope()- })+ 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)+ await syncSttLease(VOICE_INPUT_LEASE, true, PRIMARY)+ await syncSttLease(VOICE_INPUT_LEASE, false, PRIMARY)expect(setSttLease.mock.calls).toEqual([- [VOICE_INPUT_LEASE, true, { connectionId: null, profile: null }],- [VOICE_INPUT_LEASE, false, { connectionId: null, profile: null }]+ [VOICE_INPUT_LEASE, true, PRIMARY],+ [VOICE_INPUT_LEASE, false, PRIMARY]])})it('skips an initial off — never releases a lease it did not hold', async () => {- await syncSttLease(VOICE_INPUT_LEASE, false)+ await syncSttLease(VOICE_INPUT_LEASE, false, PRIMARY)expect(setSttLease).not.toHaveBeenCalled()})- 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)+ it('sends every settled-apart acquire — the backend, not a client clock, knows residency', async () => {+ // The idle-unload watcher can evict the model between two listening+ // starts at any moment; each start re-warms (a cache hit when resident).+ await syncSttLease(VOICE_INPUT_LEASE, true, PRIMARY)+ await syncSttLease(VOICE_INPUT_LEASE, true, PRIMARY)++ expect(setSttLease).toHaveBeenCalledTimes(2)+ })++ it('coalesces concurrent identical acquires onto the one in flight', async () => {+ const finish = holdNextCall()+ const first = syncSttLease(VOICE_INPUT_LEASE, true, PRIMARY)+ await Promise.resolve()+ const second = syncSttLease(VOICE_INPUT_LEASE, true, PRIMARY)+ expect(second).toBe(first)+ finish()+ await Promise.all([first, second])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).+ const finish = holdNextCall()+ const on = syncSttLease(VOICE_INPUT_LEASE, true, PRIMARY)await Promise.resolve()- expect(setSttLease.mock.calls).toEqual([[VOICE_INPUT_LEASE, true, { connectionId: null, profile: null }]])-- const off = syncSttLease(VOICE_INPUT_LEASE, false)+ const off = syncSttLease(VOICE_INPUT_LEASE, false, PRIMARY)await Promise.resolve()- // Still only the acquire — the release waits for it to finish.expect(setSttLease).toHaveBeenCalledTimes(1)- finishAcquire()+ finish()await Promise.all([on, off])-expect(setSttLease.mock.calls).toEqual([- [VOICE_INPUT_LEASE, true, { connectionId: null, profile: null }],- [VOICE_INPUT_LEASE, false, { connectionId: null, profile: null }]+ [VOICE_INPUT_LEASE, true, PRIMARY],+ [VOICE_INPUT_LEASE, false, PRIMARY]])})- 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)+ it('drops a flip that reverses before its call went out — latest intent wins', async () => {+ const on = syncSttLease(VOICE_INPUT_LEASE, true, PRIMARY)+ const off = syncSttLease(VOICE_INPUT_LEASE, false, PRIMARY)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, { connectionId: null, profile: null }]])- })-- 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]+$/)- })-- // ── 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()- }+ expect(setSttLease.mock.calls).toEqual([[VOICE_INPUT_LEASE, false, PRIMARY]])})- 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 }))+ // #128668 review: an acquire queued behind a release must not coalesce onto+ // an earlier acquire — it would resolve before the latest acquire settled+ // and leave the backend released.+ it('on → off → on across turns ends acquired, and the last on waits for its own acquire', async () => {+ await syncSttLease(VOICE_INPUT_LEASE, true, PRIMARY)+ setSttLease.mockClear()- await syncSttLease(VOICE_INPUT_LEASE, true)- await syncSttLease(VOICE_INPUT_LEASE, true)-- expect(setSttLease).toHaveBeenCalledTimes(1)- })+ const pending: Array<() => void> = []+ setSttLease.mockImplementation(() => new Promise(resolve => pending.push(() => resolve({ ok: true }))))- 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.+ const on1 = syncSttLease(VOICE_INPUT_LEASE, true, PRIMARY)await Promise.resolve()- const second = syncSttLease(VOICE_INPUT_LEASE, true)+ const off = syncSttLease(VOICE_INPUT_LEASE, false, PRIMARY)+ const on2 = syncSttLease(VOICE_INPUT_LEASE, true, PRIMARY)+ expect(on2).not.toBe(on1)- expect(setSttLease).toHaveBeenCalledTimes(1)+ let on2Settled = false+ void on2.then(() => (on2Settled = true))- finishAcquire()- await Promise.all([first, second])+ pending[0]()+ await on1+ await new Promise(resolve => setTimeout(resolve, 0))+ // on2's own acquire is on the wire and unsettled — its caller still waits.+ expect(on2Settled).toBe(false)+ expect(pending).toHaveLength(2)- expect(setSttLease).toHaveBeenCalledTimes(1)- })+ pending[1]()+ await Promise.all([off, on2])- // ── A lease belongs to the connection/profile that acquired it ────────────+ const wire = setSttLease.mock.calls.map(([, active]) => active)+ expect(wire.at(-1)).toBe(true)+ expect(on2Settled).toBe(true)+ })- 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 })- })- )+ it('an acquire queued behind an on-the-wire release is sent after it', async () => {+ await syncSttLease(VOICE_INPUT_LEASE, true, PRIMARY)+ setSttLease.mockClear()- 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' })+ const finishRelease = holdNextCall()+ const off = syncSttLease(VOICE_INPUT_LEASE, false, PRIMARY)await Promise.resolve()+ const on = syncSttLease(VOICE_INPUT_LEASE, true, PRIMARY)- // 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.+ finishRelease()+ await Promise.all([off, on])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' }]+ [VOICE_INPUT_LEASE, false, PRIMARY],+ [VOICE_INPUT_LEASE, true, PRIMARY]])})- 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 })- })- )+ it('forgets the sent state on failure so the next flip retries', async () => {+ setSttLease.mockImplementationOnce(async () => {+ throw new Error('backend not ready')+ })- const on = syncSttLease(VOICE_INPUT_LEASE, true)- await Promise.resolve()- const off = syncSttLease(VOICE_INPUT_LEASE, false)- await Promise.resolve()+ await expect(syncSttLease(VOICE_INPUT_LEASE, true, PRIMARY)).resolves.toBeUndefined()+ await syncSttLease(VOICE_INPUT_LEASE, true, PRIMARY)- currentScope.connectionId = 'gateway-b'- currentScope.profile = 'worker_beta'+ expect(setSttLease).toHaveBeenCalledTimes(2)+ })- finishAcquire()- await Promise.all([on, off])+ it('never rejects — recording must not depend on warm-up', async () => {+ setSttLease.mockRejectedValue(new Error('backend gone'))- 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' }]- ])+ await expect(syncSttLease(VOICE_INPUT_LEASE, true, PRIMARY)).resolves.toBeUndefined()+ await expect(syncSttLease(VOICE_INPUT_LEASE, false, PRIMARY)).resolves.toBeUndefined()})- 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 }))+ it('voice-input lease is per renderer', () => {+ expect(VOICE_INPUT_LEASE).toMatch(/^desktop:voice-input:[a-z0-9]+$/)+ })- await syncSttLease(VOICE_INPUT_LEASE, true, { connectionId: 'gateway-a', profile: 'worker_alpha' })- await syncSttLease(VOICE_INPUT_LEASE, true, { connectionId: 'gateway-b', profile: 'worker_beta' })+ it('keeps each owner on its own queue — A never satisfies or delays B', async () => {+ const finishA = holdNextCall()+ const a = syncSttLease(VOICE_INPUT_LEASE, true, ALPHA)+ await Promise.resolve()+ await syncSttLease(VOICE_INPUT_LEASE, true, BETA)+ finishA()+ await a+ await syncSttLease(VOICE_INPUT_LEASE, false, ALPHA)- // 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' }]+ [VOICE_INPUT_LEASE, true, ALPHA],+ [VOICE_INPUT_LEASE, true, BETA],+ [VOICE_INPUT_LEASE, false, ALPHA]])})-- 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 c5385a93532..049e3e1a502 100644--- a/apps/desktop/src/lib/stt-lease.ts+++ b/apps/desktop/src/lib/stt-lease.ts@@ -1,6 +1,4 @@-import { getApiRequestConnection, getApiRequestProfile, setSttLease } from '@/hermes'--import type { AudioSttLeaseResponse } from '@/types/hermes'+import { type ResolvedOwner, 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@@ -10,36 +8,27 @@ import type { AudioSttLeaseResponse } from '@/types/hermes'// 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.+// This module is the renderer's single choke point for that signal. It+// serializes per lease so a fast on→off→on can't be reordered on the wire,+// coalesces concurrent identical acquires (recorder and conversation loop+// observe the same mic session), 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.+// 1. Registration ≠ readiness. The idle-unload watcher can evict the model+// between two listening starts (a long reply, a mute), so every acquire is+// sent: the backend re-warm is a cache hit when the model is resident and a+// reload when it is not. No client-side timestamp stands in for residency.+// 2. Readiness is carried into transcription. The promise returned for an+// acquire settles only when that acquire has settled on the wire — the+// hooks use it as the barrier before submitting audio, so the transcription+// request's deadline measures decoding, not the loader's cold start.+// 3. A lease belongs to the owner that acquired it. Callers resolve the owner+// once per voice operation and pass the same value to acquire, transcribe+// and release; the queue and coalescing identity include 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.@@ -47,175 +36,66 @@ const RENDERER_ID = Math.random().toString(36).slice(2, 10)export const VOICE_INPUT_LEASE = `desktop:voice-input:${RENDERER_ID}`-/**- * 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 {+function keyFor(lease: string, owner: ResolvedOwner): 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. */+/** Latest requested state 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>()++/** The last queued operation per (lease, owner), until it settles. */+const tails = new Map<string, { active: boolean; promise: Promise<void> }>()/**- * 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.+ * Bring the backend's view of `lease` in line with `active`, for `owner`.+ *+ * An acquire coalesces only onto a queued acquire that is still the latest+ * intent — that acquire's settle IS this caller's readiness. Anything queued+ * behind a release is a new acquire. Releasing a lease that was never acquired+ * (or is already released) sends nothing.*/-export function syncSttLease(lease: string, active: boolean, owner?: SttLeaseOwner): Promise<void> {- const scope = resolveOwner(owner)- const key = keyFor(lease, scope)+export function syncSttLease(lease: string, active: boolean, owner: ResolvedOwner): Promise<void> {+ const key = keyFor(lease, owner)+ const tail = tails.get(key)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()+ return tail?.promise ?? Promise.resolve()}- 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 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()- }+ if (active && tail?.active && intent.get(key) === true) {+ return tail.promise}intent.set(key, active)- if (!active) {- warm.delete(key)- }-- const previous = inFlight.get(key) ?? Promise.resolve()- const next = previous+ const promise: Promise<void> = (tail?.promise ?? Promise.resolve()).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 (intent.get(key) !== active) {- return- }-- const response = await setSttLease(lease, active, scope)- if (active) {- warm.set(key, { at: Date.now(), state: classifyAcquire(response) })+ // Latest intent wins: flipped again while queued → the newer call sends+ // its own state and this one has nothing to say.+ if (intent.get(key) === active) {+ await setSttLease(lease, active, owner)}}).catch(() => {- // Backend not up yet / older backend without the endpoint / warm-up- // failure: forget what we "sent" so the next flip retries honestly.- // (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.)+ // Backend not up yet / older backend without the endpoint: forget what+ // we "sent" so the next flip retries honestly.if (intent.get(key) === active) {intent.delete(key)}- warm.delete(key)}).finally(() => {- if (active) {- acquiring.delete(key)- }- if (inFlight.get(key) === next) {- inFlight.delete(key)+ if (tails.get(key)?.promise === promise) {+ tails.delete(key)}})- if (active) {- acquiring.add(key)- }- inFlight.set(key, next)+ tails.set(key, { active, promise })- return next+ return promise}-/** Test seams. */+/** Test seam. */export function resetSttLeasesForTests() {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- }+ tails.clear()}diff --git a/apps/desktop/src/lib/voice-client-direct.ts b/apps/desktop/src/lib/voice-client-direct.tsindex 0a2dea2c57e..a4a1269cc26 100644--- a/apps/desktop/src/lib/voice-client-direct.ts+++ b/apps/desktop/src/lib/voice-client-direct.ts@@ -1,4 +1,4 @@-import { type OwnerScope, ownerScoped } from '@/api/client'+import { hermesApiAs, type OwnerScope, ownerScoped, type ResolvedOwner } from '@/api/client'import { getApiRequestConnection, getApiRequestProfile, hermesApi } from '@/hermes'/**@@ -86,8 +86,28 @@ export function clearVoiceClientConfigCache(): void {}export async function fetchVoiceClientConfig(owner?: OwnerScope): Promise<null | VoiceClientConfig> {- const key = scopeKey(owner)+ // hermesApi carries connectionScoped(); profileScoped() adds the profile —+ // the same routing every relay audio call uses, so the config comes from+ // the backend the user is actually talking to.+ return loadVoiceClientConfig(scopeKey(owner), () =>+ hermesApi<VoiceConfigResponse>({ ...ownerScoped(owner), path: '/api/audio/voice-config' })+ )+}++/** The config for an owner resolved once for a whole voice operation: the+ * lookup cannot drift to whatever scope is ambient by the time it runs. */+export async function fetchVoiceClientConfigFor(owner: ResolvedOwner): Promise<null | VoiceClientConfig> {+ return loadVoiceClientConfig(`${owner.connectionId || 'local'}::${owner.profile || 'default'}`, () =>+ hermesApiAs<VoiceConfigResponse>(owner, { path: '/api/audio/voice-config' })+ )+}++type VoiceConfigResponse = { ok: boolean } & VoiceClientConfig+async function loadVoiceClientConfig(+ key: string,+ fetchConfig: () => Promise<VoiceConfigResponse>+): Promise<null | VoiceClientConfig> {if (cached && cached.key === key && Date.now() - cached.at < CONFIG_TTL_MS) {return cached.config}@@ -98,13 +118,7 @@ export async function fetchVoiceClientConfig(owner?: OwnerScope): Promise<null |const promise = (async () => {try {- // hermesApi carries connectionScoped(); profileScoped() adds the- // profile — the same routing every relay audio call uses, so the- // config comes from the backend the user is actually talking to.- const response = await hermesApi<{ ok: boolean } & VoiceClientConfig>({- ...ownerScoped(owner),- path: '/api/audio/voice-config'- })+ const response = await fetchConfig()if (!response?.ok || !response.stt || !response.tts) {return null@@ -254,10 +268,11 @@ async function sttFetch(stt: DirectSttConfig, url: string, init: RequestInit): P* when the profile's provider isn't client-callable — the caller relays.* Provider REJECTIONS throw: the configured provider said no, and silently* re-running the same request through the gateway would just fail again- * slower and hide the real error.+ * slower and hide the real error. `owner` pins the provider config to the+ * recording's owner (resolved when the mic opened); omitted → the active scope.*/-export async function transcribeAudioClientDirect(audio: Blob): Promise<null | string> {- const config = await fetchVoiceClientConfig()+export async function transcribeAudioClientDirect(audio: Blob, owner?: ResolvedOwner): Promise<null | string> {+ const config = await (owner ? fetchVoiceClientConfigFor(owner) : fetchVoiceClientConfig())const stt = config?.sttif (!stt || stt.mode !== 'direct') {diff --git a/tests/hermes_cli/test_web_server_stt_lease.py b/tests/hermes_cli/test_web_server_stt_lease.pyindex aa421b87919..a06637aa815 100644--- a/tests/hermes_cli/test_web_server_stt_lease.py+++ b/tests/hermes_cli/test_web_server_stt_lease.py@@ -309,3 +309,82 @@ def test_warm_reacquire_after_eviction_restarts_watcher(monkeypatch):transcription_tools._local_model = Nonetranscription_tools._local_model_name = Nonetranscription_tools._idle_unload_thread = None+++def _watch_under_profiles(monkeypatch, *owners):+ """Start/refresh the idle watcher from each (profile, idle_seconds) caller in order, each+ inside its own context — the same ContextVar mechanism a request's profile scope uses."""+ import contextvars+ import threading++ from tools import transcription_tools++ class _GatedStop:+ """The watcher's first tick waits until every owner has been registered."""++ def __init__(self):+ self.event = threading.Event()+ self.gate = threading.Event()++ def wait(self, timeout):+ self.gate.wait(2)+ return self.event.wait(timeout)++ def set(self):+ self.event.set()+ self.gate.set()++ def clear(self):+ self.event.clear()++ stop = _GatedStop()+ monkeypatch.setattr(transcription_tools, "_idle_unload_stop", stop)++ profile = contextvars.ContextVar("test_stt_profile", default="launch")+ idle_by_profile = {"launch": 3600, **dict(owners)}+ monkeypatch.setattr(+ transcription_tools,+ "_load_stt_config",+ lambda: {"local": {"model": "tiny", "unload_after_idle_seconds": idle_by_profile[profile.get()]}},+ )+ monkeypatch.setattr(transcription_tools, "_IDLE_UNLOAD_CHECK_INTERVAL", 0.01)+ monkeypatch.setattr(transcription_tools, "_idle_unload_thread", None)+ monkeypatch.setattr(transcription_tools, "_last_transcription_time", time.monotonic() - 2)+ transcription_tools._local_model = object()+ transcription_tools._local_model_name = "tiny"++ for name, idle in owners:+ def _call(name=name, idle=idle):+ profile.set(name)+ transcription_tools._start_idle_unload_watcher(idle)++ contextvars.copy_context().run(_call)++ stop.gate.set()+ for _ in range(50):+ if transcription_tools._local_model is None:+ break+ time.sleep(0.01)+ evicted = transcription_tools._local_model is None++ stop.set()+ if transcription_tools._idle_unload_thread is not None:+ transcription_tools._idle_unload_thread.join(timeout=2)+ transcription_tools._local_model = None+ transcription_tools._local_model_name = None+ transcription_tools._idle_unload_thread = None+ return evicted+++def test_idle_watcher_applies_the_profile_that_warmed_the_model(monkeypatch):+ """#128668 review: the watcher thread has no request scope of its own. It must read+ ``unload_after_idle_seconds`` in the scope of the caller that loaded the model, not the+ launch profile's (3600s here), or a 1s policy never fires."""+ assert _watch_under_profiles(monkeypatch, ("worker_beta", 1)) is True+++def test_idle_watcher_follows_the_latest_owner_of_the_shared_model(monkeypatch):+ """A → B → A: the live watcher adopts each new owner's policy instead of keeping the one+ it was started under."""+ assert _watch_under_profiles(monkeypatch, ("alpha", 3600), ("worker_beta", 1)) is True+ assert _watch_under_profiles(monkeypatch, ("worker_beta", 1), ("alpha", 3600)) is Falsediff --git a/tools/transcription_tools.py b/tools/transcription_tools.pyindex d41e11e835b..03da9561388 100644--- a/tools/transcription_tools.py+++ b/tools/transcription_tools.py@@ -9,6 +9,7 @@ the dispatcher and the cached local model + idle-unload state; backends live in``transcription_{common,audio,local,cloud,command}``."""+import contextvarsimport loggingimport osimport shutil@@ -74,6 +75,9 @@ _last_transcription_time: float = 0.0_idle_unload_thread: Optional[threading.Thread] = None_idle_unload_stop = threading.Event()_idle_unload_mgmt_lock = threading.Lock()+# (context, fallback timeout) of the last caller that loaded or used the model: whose profile's+# stt.local.unload_after_idle_seconds the watcher applies. Guarded by _idle_unload_mgmt_lock.+_idle_unload_policy: tuple[contextvars.Context, int] = (contextvars.copy_context(), 0)_IDLE_UNLOAD_CHECK_INTERVAL = 30 # seconds between idle checks@@ -282,22 +286,37 @@ def _unload_local_model() -> None:_local_model_name = None+def _configured_idle_unload_seconds() -> int:+ return _get_idle_unload_seconds(_load_stt_config().get("local") or {})++def _start_idle_unload_watcher(timeout_seconds: int) -> None:- """Ensure the single idle-unload watcher thread is running. The loop re-reads- ``stt.local.unload_after_idle_seconds`` every cycle so config edits apply within one interval;- ``timeout_seconds`` seeds the first cycle so a just-written config is honored even if a- concurrent read races. Exits after unloading, when the timeout becomes 0, or when the model is gone."""- global _idle_unload_thread+ """Ensure the single idle-unload watcher thread is running, governed by the caller's profile.++ One process can serve several profiles, each with its own+ ``stt.local.unload_after_idle_seconds``, and they share the one cached model. The policy that+ governs it is the one of whoever last loaded or used it: every call records the caller's+ context (profile scope included) and the loop re-reads the setting inside that context each+ cycle, so config edits still apply within one interval and a watcher started under profile A+ stops applying A's policy once profile B warms or transcribes. ``timeout_seconds`` is the+ fallback when that read fails. Exits after unloading, when the timeout becomes 0, or when the+ model is gone."""+ global _idle_unload_thread, _idle_unload_policywith _idle_unload_mgmt_lock:+ _idle_unload_policy = (contextvars.copy_context(), timeout_seconds)if _idle_unload_thread is not None and _idle_unload_thread.is_alive():return- def _watch(initial_timeout=timeout_seconds):+ def _watch():while not _idle_unload_stop.wait(_IDLE_UNLOAD_CHECK_INTERVAL) and _local_model is not None:+ with _idle_unload_mgmt_lock:+ owner_context, fallback = _idle_unload_policytry:- timeout = _get_idle_unload_seconds(_load_stt_config().get("local") or {})- except Exception: # noqa: BLE001 - keep the seed value- timeout = initial_timeout+ # A copy: a Context can't be entered twice at once, and the owner's own+ # request may still be running in the original.+ timeout = owner_context.copy().run(_configured_idle_unload_seconds)+ except Exception: # noqa: BLE001 - keep the owner's last known value+ timeout = fallbackif timeout <= 0:break # unload disabled mid-flight — stand downif time.monotonic() - _last_transcription_time >= timeout: