Skip to content

The agent that grows with you

fix(desktop): route GPT-Live sessions through the Bot owner's profile

Konstantin Khlopkovae1530745a45
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-live-conversation.owner.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-voice-live-conversation.owner.test.tsx
new file mode 100644
index 00000000000..0c037fdfeb0
--- /dev/null
+++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-live-conversation.owner.test.tsx
@@ -0,0 +1,87 @@
+// @vitest-environment jsdom
+import { act, cleanup, renderHook } from '@testing-library/react'
+import type { ReactNode } from 'react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import type { VoiceLiveHandlers } from '@/lib/voice-live'
+
+import { ComposerScopeProvider, MAIN_COMPOSER_SCOPE } from '../scope'
+
+import { useVoiceLiveConversation } from './use-voice-live-conversation'
+
+// A Bot chat's GPT-Live session must dial the Bot's own (connection, profile)
+// — the same owner route the TTS legs already trust (#117014) — so the voice
+// configured on the Bot's profile is the voice that answers (#117401).
+
+const constructed = vi.hoisted(() => ({ owners: [] as Array<null | { connectionId?: null | string; profile?: null | string }> }))
+
+vi.mock('@/lib/voice-live', async importOriginal => {
+ const actual = (await importOriginal()) as Record<string, unknown>
+
+ return {
+ ...actual,
+ VoiceLiveSession: class {
+ close = vi.fn()
+
+ constructor(_handlers: VoiceLiveHandlers, owner: null | { connectionId?: null | string; profile?: null | string } = null) {
+ constructed.owners.push(owner)
+ }
+
+ async start(): Promise<void> {}
+ }
+ }
+})
+
+vi.mock('@/store/notifications', () => ({ notify: vi.fn(), notifyError: vi.fn() }))
+
+afterEach(() => {
+ cleanup()
+ constructed.owners.length = 0
+})
+
+function mountLive(wrapper?: ({ children }: { children: ReactNode }) => ReactNode) {
+ return renderHook(
+ () =>
+ useVoiceLiveConversation({
+ busy: false,
+ consumePendingResponse: vi.fn(),
+ enabled: true,
+ onSubmit: vi.fn(),
+ pendingResponse: () => null,
+ seedHistory: () => []
+ }),
+ wrapper ? { wrapper } : undefined
+ )
+}
+
+describe('useVoiceLiveConversation — owner-routed session', () => {
+ it('constructs the session with the composer scope owner (connection, profile)', async () => {
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <ComposerScopeProvider
+ value={{ ...MAIN_COMPOSER_SCOPE, connectionId: 'gw-bots', profile: 'bot-adam', target: 'tile:bot' }}
+ >
+ {children}
+ </ComposerScopeProvider>
+ )
+
+ const hook = mountLive(wrapper)
+
+ await act(async () => {
+ await hook.result.current.start()
+ })
+
+ expect(constructed.owners).toEqual([{ connectionId: 'gw-bots', profile: 'bot-adam' }])
+ })
+
+ it('passes an empty owner for the main composer scope (ambient routing keeps the session)', async () => {
+ const hook = mountLive()
+
+ await act(async () => {
+ await hook.result.current.start()
+ })
+
+ // An ownerless scope still passes the ref object; ownerScoped treats the
+ // empty (connection, profile) exactly like the old bare profileScoped().
+ expect(constructed.owners).toEqual([{ connectionId: undefined, profile: undefined }])
+ })
+})
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-live-conversation.ts b/apps/desktop/src/app/chat/composer/hooks/use-voice-live-conversation.ts
index 3e45ead5774..2033e239def 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-voice-live-conversation.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-live-conversation.ts
@@ -6,6 +6,8 @@ import { type LiveHistoryMessage, type LiveTranscriptFragment, VoiceLiveSession
import { isVoiceStopCommand } from '@/lib/voice-stop-word'
import { notify, notifyError } from '@/store/notifications'
+import { useComposerScope } from '../scope'
+
import { micError } from './use-mic-recorder'
import type { ConversationStatus } from './use-voice-conversation'
@@ -121,6 +123,12 @@ export function useVoiceLiveConversation({
// restart the feed loop, and a ref write alone does not re-render.
const [activeDelegation, setActiveDelegation] = useState<null | string>(null)
const sessionRef = useRef<null | VoiceLiveSession>(null)
+ // The scope's session owner (a Bot's own connection + profile) picks the
+ // GPT-Live backend and voice; a ref keeps the long-lived start closures
+ // reading the current value.
+ const { connectionId: ownerConnectionId, profile: ownerProfile } = useComposerScope()
+ const ownerRef = useRef({ connectionId: ownerConnectionId, profile: ownerProfile })
+ ownerRef.current = { connectionId: ownerConnectionId, profile: ownerProfile }
// Bumped by every start/end so an in-flight start() that lost the race
// (StrictMode double-effect, quick toggle) closes its session instead of
// leaving a second billed one running.
@@ -326,7 +334,7 @@ export function useVoiceLiveConversation({
setLevel(speaking ? 0.6 : 0)
refreshStatus()
}
- })
+ }, ownerRef.current)
sessionRef.current = session
startingRef.current = false
diff --git a/apps/desktop/src/lib/voice-live.routing.test.ts b/apps/desktop/src/lib/voice-live.routing.test.ts
new file mode 100644
index 00000000000..86628e70475
--- /dev/null
+++ b/apps/desktop/src/lib/voice-live.routing.test.ts
@@ -0,0 +1,107 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { setApiRequestConnection, setApiRequestProfile } from '@/hermes'
+
+import { fetchVoiceLiveStatus, type VoiceLiveHandlers, VoiceLiveSession } from './voice-live'
+
+// A GPT-Live session is created on the chat OWNER's (connection, profile) —
+// the Bot that owns the chat — never on the window's active scope, mirroring
+// the TTS legs (#117014): two Bots with different voices configured must get
+// their own voices. The status probe follows the same rule so a Bot tile
+// mounts the engine the Bot's own profile selected.
+
+const handlers: VoiceLiveHandlers = {
+ onClosed: () => undefined,
+ onDelegation: () => undefined,
+ onError: () => undefined
+}
+
+function installApi() {
+ const api = vi.fn(async (_request: unknown) => ({ ok: true, session: { id: 's1' }, transport: { sdp: 'answer', type: 'answer' } }))
+
+ Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: { api } })
+
+ return api
+}
+
+/** Enough of RTCPeerConnection/getUserMedia for `start()` to reach the POST. */
+function installWebRTC() {
+ const channel = { addEventListener: () => undefined, readyState: 'open' as const, send: () => undefined }
+
+ const PeerConnection = class {
+ addEventListener = () => undefined
+ connectionState = 'new'
+ createDataChannel = () => channel
+ createOffer = async () => ({})
+ iceGatheringState = 'complete'
+ localDescription = { sdp: 'v=0\r\n' }
+ setLocalDescription = async () => undefined
+ setRemoteDescription = async () => undefined
+ }
+
+ Object.defineProperty(globalThis, 'RTCPeerConnection', { configurable: true, value: PeerConnection })
+ Object.defineProperty(window.navigator, 'mediaDevices', {
+ configurable: true,
+ value: { getUserMedia: async () => ({ getAudioTracks: () => [] }) }
+ })
+}
+
+afterEach(() => {
+ setApiRequestConnection(null)
+ setApiRequestProfile(null)
+ Reflect.deleteProperty(window, 'hermesDesktop')
+ Reflect.deleteProperty(globalThis, 'RTCPeerConnection')
+ Reflect.deleteProperty(window.navigator, 'mediaDevices')
+})
+
+describe('GPT-Live owner routing', () => {
+ it('creates the session on the chat owner (connection, profile) ahead of the active scope', async () => {
+ installWebRTC()
+ const api = installApi()
+ setApiRequestConnection('gw-active')
+ setApiRequestProfile('research')
+
+ const session = new VoiceLiveSession(handlers, { connectionId: 'gw-bots', profile: 'bot-adam' })
+ await session.start([])
+
+ expect(api).toHaveBeenCalledTimes(1)
+ const request = api.mock.calls[0][0] as { connectionId?: string; path: string; priority?: string; profile?: string }
+
+ expect(request.path).toBe('/api/audio/voice-live/session')
+ expect(request.profile).toBe('bot-adam')
+ expect(request.connectionId).toBe('gw-bots')
+ expect(request.priority).toBe('foreground')
+ })
+
+ it('keeps the active scope verbatim for an ownerless chat', async () => {
+ installWebRTC()
+ const api = installApi()
+ setApiRequestConnection('gw-active')
+ setApiRequestProfile('research')
+
+ const session = new VoiceLiveSession(handlers, null)
+ await session.start([])
+
+ const request = api.mock.calls[0][0] as { connectionId?: string; path: string; priority?: string; profile?: string }
+
+ expect(request.path).toBe('/api/audio/voice-live/session')
+ expect(request.profile).toBe('research')
+ expect(request.connectionId).toBe('gw-active')
+ expect(request.priority).toBeUndefined()
+ })
+
+ it('probes the mode status on the owner scope too', async () => {
+ const api = installApi()
+ setApiRequestConnection('gw-active')
+ setApiRequestProfile('research')
+
+ await fetchVoiceLiveStatus({ connectionId: 'gw-bots', profile: 'bot-adam' })
+
+ const request = api.mock.calls[0][0] as { connectionId?: string; path: string; priority?: string; profile?: string }
+
+ expect(request.path).toBe('/api/audio/voice-live/status')
+ expect(request.profile).toBe('bot-adam')
+ expect(request.connectionId).toBe('gw-bots')
+ expect(request.priority).toBe('foreground')
+ })
+})
diff --git a/apps/desktop/src/lib/voice-live.ts b/apps/desktop/src/lib/voice-live.ts
index 0ddd88581d9..14f57da21a8 100644
--- a/apps/desktop/src/lib/voice-live.ts
+++ b/apps/desktop/src/lib/voice-live.ts
@@ -1,4 +1,4 @@
-import { profileScoped } from '@/api/client'
+import { type OwnerScope, ownerScoped } from '@/api/client'
import { hermesApi } from '@/hermes'
/**
@@ -78,10 +78,10 @@ const APPEND_CHAR_LIMIT = 1_400
const CONTEXT_WINDOW_MS = 5 * 60_000
const CONTEXT_MAX_FRAGMENTS = 80
-export async function fetchVoiceLiveStatus(): Promise<null | VoiceLiveStatus> {
+export async function fetchVoiceLiveStatus(owner?: null | OwnerScope): Promise<null | VoiceLiveStatus> {
try {
const response = await hermesApi<{ ok: boolean } & VoiceLiveStatus>({
- ...profileScoped(),
+ ...ownerScoped(owner ?? undefined),
path: '/api/audio/voice-live/status'
})
@@ -213,6 +213,11 @@ async function waitForIceGathering(connection: RTCPeerConnection): Promise<void>
export class VoiceLiveSession {
readonly audio: HTMLAudioElement
+ /** Whose (connection, profile) this session dials; null → the active scope.
+ * A Bot chat runs its GPT-Live session on the Bot's own profile, so the
+ * voice configured there is the voice that answers. */
+ private readonly owner: null | OwnerScope
+ private readonly handlers: VoiceLiveHandlers
private peer: null | RTCPeerConnection = null
private events: null | RTCDataChannel = null
private microphone: null | MediaStream = null
@@ -230,7 +235,9 @@ export class VoiceLiveSession {
* older id are dropped by the conversation hook. */
activeDelegationId: null | string = null
- constructor(private readonly handlers: VoiceLiveHandlers) {
+ constructor(handlers: VoiceLiveHandlers, owner: null | OwnerScope = null) {
+ this.handlers = handlers
+ this.owner = owner
this.audio = new Audio()
this.audio.autoplay = true
}
@@ -321,7 +328,7 @@ export class VoiceLiveSession {
session?: { id: string }
transport?: { sdp: string; type: string }
}>({
- ...profileScoped(),
+ ...ownerScoped(this.owner ?? undefined),
body: { history, sdp },
method: 'POST',
path: '/api/audio/voice-live/session',