Skip to content

The agent that grows with you

fix(desktop): read the final reply aloud after tool calls (#140623)

Austin Pickett9cb34e9e285d
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.cross-window.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.cross-window.test.tsx
new file mode 100644
index 00000000000..33350c748d0
--- /dev/null
+++ b/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.cross-window.test.tsx
@@ -0,0 +1,130 @@
+import { act, cleanup, renderHook } from '@testing-library/react'
+import { atom } from 'nanostores'
+import { afterEach, expect, it, vi } from 'vitest'
+
+import type { ChatMessage } from '@/lib/chat-messages'
+
+import { createAmbientClaimArbiter } from '../../../../../electron/event-dedupe'
+
+// Two windows with the same chat open: each renderer has its own playback
+// store, and the only thing they share is the main-process claim arbiter.
+// Adapted from @unsupportedpastels' review probe on #140623.
+
+const IDLE = { audioElement: null, messageId: null, sequence: 0, source: null, status: 'idle' as const }
+
+const message = (id: string, text: string, role: 'assistant' | 'user' = 'assistant'): ChatMessage => ({
+ id,
+ parts: [{ text, type: 'text' }],
+ role
+})
+
+afterEach(() => {
+ cleanup()
+ delete (window as { hermesDesktop?: unknown }).hermesDesktop
+ vi.doUnmock('@/lib/voice-playback')
+ vi.resetModules()
+})
+
+async function openWindow(name: string, plays: string[]) {
+ vi.resetModules()
+ const playback = await import('@/store/voice-playback')
+ const prefs = await import('@/store/voice-prefs')
+ const spoken = await import('@/lib/spoken-reply')
+ const chat = await import('@/lib/chat-messages')
+ const scope = await import('../scope')
+
+ vi.doMock('@/lib/voice-playback', () => ({
+ playSpeechText: vi.fn(async (text: string) => {
+ plays.push(`${name}:${text}`)
+ playback.setVoicePlaybackState({ ...IDLE, source: 'read-aloud', status: 'speaking' })
+
+ return true
+ })
+ }))
+
+ const { useAutoSpeakReplies } = await import('./use-auto-speak-replies')
+ const user = message('u1', 'fix it', 'user')
+ const $messages = atom<ChatMessage[]>([user])
+ prefs.$autoSpeakReplies.set(true)
+
+ const markSpoken = () => {
+ const rows = $messages.get()
+ const last = rows.findLast(m => m.role === 'assistant')
+
+ if (last) {
+ spoken.markAssistantIdSpoken('s1', rows, last.id)
+ }
+ }
+
+ const pendingReply = () => {
+ const rows = $messages.get()
+ const last = rows.findLast(m => m.role === 'assistant')
+
+ if (!last || last.id === spoken.resolveSpokenReply('s1', rows)?.id) {
+ return null
+ }
+
+ return {
+ id: last.id,
+ pending: false,
+ segmentText: chat.lastTextPartText(last),
+ text: chat.chatMessageText(last),
+ turnKey: spoken.assistantTurnKey('s1', rows, last.id)
+ }
+ }
+
+ renderHook(
+ () =>
+ useAutoSpeakReplies({
+ conversationActive: false,
+ failureLabel: 'failed',
+ markSpoken,
+ pendingReply,
+ sessionId: 's1'
+ }),
+ {
+ wrapper: ({ children }) => (
+ <scope.ComposerScopeProvider value={{ ...scope.MAIN_COMPOSER_SCOPE, $messages }}>
+ {children}
+ </scope.ComposerScopeProvider>
+ )
+ }
+ )
+
+ return { $messages, playback, user }
+}
+
+it('reads the final reply once, in the window that read the progress update, after that clip ends', async () => {
+ const owns = createAmbientClaimArbiter()
+
+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = { claimAmbientCue: async (key: string) => owns(key) }
+
+ const plays: string[] = []
+ const a = await openWindow('A', plays)
+ const b = await openWindow('B', plays)
+ expect(a.playback.$voicePlayback).not.toBe(b.playback.$voicePlayback)
+
+ const progress = message('assistant-interim-1', 'Looking into it.')
+ const final = message('assistant-stream-2', 'Here is the final report.')
+
+ await act(async () => {
+ a.$messages.set([a.user, progress])
+ })
+ await act(async () => {
+ b.$messages.set([b.user, progress])
+ })
+ expect(plays).toEqual(['A:Looking into it.'])
+
+ // The final reply lands in both windows while A is still speaking.
+ await act(async () => {
+ a.$messages.set([a.user, progress, final])
+ b.$messages.set([b.user, progress, final])
+ })
+ expect(plays).toEqual(['A:Looking into it.'])
+
+ // A's progress clip ends.
+ await act(async () => {
+ a.playback.setVoicePlaybackState({ ...IDLE })
+ })
+ expect(plays).toEqual(['A:Looking into it.', 'A:Here is the final report.'])
+})
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.test.tsx
index 97659a9bcf4..f9cac8b8657 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.test.tsx
@@ -3,14 +3,19 @@ import { atom } from 'nanostores'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { assistantTextPart, type ChatMessage, chatMessageText } from '@/lib/chat-messages'
-import { clearSpokenRepliesForTests, markAssistantIdSpoken, resolveSpokenReply } from '@/lib/spoken-reply'
+import {
+ assistantTurnKey,
+ clearSpokenRepliesForTests,
+ markAssistantIdSpoken,
+ resolveSpokenReply
+} from '@/lib/spoken-reply'
import { playSpeechText } from '@/lib/voice-playback'
import { $voicePlayback, setVoicePlaybackState } from '@/store/voice-playback'
import { $autoSpeakReplies } from '@/store/voice-prefs'
import { ComposerScopeProvider, MAIN_COMPOSER_SCOPE } from '../scope'
-import { useAutoSpeakReplies } from './use-auto-speak-replies'
+import { clearOwnedSpeechTurnsForTests, useAutoSpeakReplies } from './use-auto-speak-replies'
vi.mock('@/lib/voice-playback', () => ({
playSpeechText: vi.fn()
@@ -34,6 +39,7 @@ describe('useAutoSpeakReplies — Edge TTS fallback chain (#93515)', () => {
afterEach(() => {
cleanup()
clearSpokenRepliesForTests()
+ clearOwnedSpeechTurnsForTests()
$autoSpeakReplies.set(false)
setVoicePlaybackState({ ...IDLE_STATE })
vi.clearAllMocks()
@@ -334,3 +340,112 @@ describe('useAutoSpeakReplies — Edge TTS fallback chain (#93515)', () => {
await waitFor(() => expect(playSpeechText).toHaveBeenCalledTimes(2))
})
})
+
+// A turn with tool calls speaks several bubbles under ONE user turn: progress
+// updates, then the final reply. Keyed on the turn alone, the progress update's
+// cross-window speech claim (held for minutes) refused the final reply, and
+// the reply (already marked spoken) never reached TTS.
+describe('useAutoSpeakReplies — final reply after tool calls', () => {
+ afterEach(() => {
+ cleanup()
+ clearSpokenRepliesForTests()
+ clearOwnedSpeechTurnsForTests()
+ $autoSpeakReplies.set(false)
+ setVoicePlaybackState({ ...IDLE_STATE })
+ delete (window as { hermesDesktop?: unknown }).hermesDesktop
+ vi.clearAllMocks()
+ })
+
+ it('reads the final reply held behind a progress update of the same turn', async () => {
+ // The main-process arbiter within its speech TTL: first claim of a key wins.
+ const claimed = new Set<string>()
+
+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = {
+ claimAmbientCue: async (key: string) => !claimed.has(key) && Boolean(claimed.add(key))
+ }
+
+ $autoSpeakReplies.set(true)
+
+ const user = { id: 'u1', parts: [assistantTextPart('fix it')], role: 'user' } as ChatMessage
+ const interim = { ...assistantMessage('assistant-interim-1', 'Looking into it.'), interim: true }
+ const $messages = atom<ChatMessage[]>([user])
+
+ // The pendingResponse / consumePendingResponse pair use-composer-voice.ts wires up.
+ const pendingReply = () => {
+ const messages = $messages.get()
+ const last = messages.findLast(m => m.role === 'assistant' && !m.hidden)
+ const spoken = resolveSpokenReply(SESSION_ID, messages)
+
+ if (!last || last.id === spoken?.id) {
+ return null
+ }
+
+ const text = chatMessageText(last).trim()
+
+ return {
+ id: last.id,
+ pending: Boolean(last.pending),
+ text,
+ turnKey: assistantTurnKey(SESSION_ID, messages, last.id)
+ }
+ }
+
+ const markSpoken = () => {
+ const messages = $messages.get()
+ const last = messages.findLast(m => m.role === 'assistant' && !m.hidden)
+
+ if (last) {
+ markAssistantIdSpoken(SESSION_ID, messages, last.id)
+ }
+ }
+
+ vi.mocked(playSpeechText).mockImplementation(async (_text, options) => {
+ setVoicePlaybackState({
+ ...IDLE_STATE,
+ messageId: options.messageId ?? null,
+ source: 'read-aloud',
+ status: 'speaking'
+ })
+
+ return true
+ })
+
+ renderHook(
+ () =>
+ useAutoSpeakReplies({
+ conversationActive: false,
+ failureLabel: 'read-aloud failed',
+ markSpoken,
+ pendingReply,
+ sessionId: SESSION_ID
+ }),
+ {
+ wrapper: ({ children }) => (
+ <ComposerScopeProvider value={{ ...MAIN_COMPOSER_SCOPE, $messages }}>{children}</ComposerScopeProvider>
+ )
+ }
+ )
+
+ await act(async () => {
+ $messages.set([user, interim])
+ })
+ expect(playSpeechText).toHaveBeenCalledTimes(1)
+
+ // The final reply lands while the progress update is still playing: held.
+ await act(async () => {
+ $messages.set([user, interim, assistantMessage('assistant-stream-2', 'Here is the final report.')])
+ })
+ expect(playSpeechText).toHaveBeenCalledTimes(1)
+
+ // The progress update's clip ends.
+ await act(async () => {
+ setVoicePlaybackState({ ...IDLE_STATE })
+ })
+
+ expect(playSpeechText).toHaveBeenCalledTimes(2)
+ expect(playSpeechText).toHaveBeenLastCalledWith(
+ 'Here is the final report.',
+ expect.objectContaining({ messageId: 'assistant-stream-2', source: 'read-aloud' })
+ )
+ })
+})
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.ts b/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.ts
index dee97506721..0104f6ec1e1 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.ts
@@ -1,7 +1,7 @@
import { useStore } from '@nanostores/react'
import { useEffect, useRef } from 'react'
-import { releaseUnplayedSpokenReply, spokenReplyOf } from '@/lib/spoken-reply'
+import { releaseUnplayedSpokenReply, spokenReplyOf, spokenSegmentKey } from '@/lib/spoken-reply'
import { playSpeechText } from '@/lib/voice-playback'
import { ownsAmbientCue } from '@/store/ambient'
import { notifyError } from '@/store/notifications'
@@ -14,10 +14,40 @@ interface AutoSpeakReply {
id: string
pending: boolean
text: string
+ /** Text that identifies this message within its turn: the bubble's last text
+ * part. Hydration folds a tool-call turn into one bubble whose full text
+ * changes, but whose last text part is still this message. Defaults to `text`. */
+ segmentText?: string
/** Survives the live-id rewrite. Absent callers still speak; they just cannot join an in-flight play. */
turnKey?: string
}
+// Turns this window speaks for. The window that wins a turn's first message
+// voices every later message of that turn, so a second, idle window cannot
+// start the final reply over the first window's progress update.
+const OWNED_TURNS_MAX = 64
+const ownedTurns = new Set<string>()
+
+async function claimSpeech(turnKey: string | undefined, claimKey: string): Promise<boolean> {
+ if (turnKey && !ownedTurns.has(turnKey)) {
+ if (!(await ownsAmbientCue(`speak:turn:${turnKey}`))) {
+ return false
+ }
+
+ ownedTurns.add(turnKey)
+
+ if (ownedTurns.size > OWNED_TURNS_MAX) {
+ ownedTurns.delete(ownedTurns.values().next().value!)
+ }
+ }
+
+ return ownsAmbientCue(claimKey)
+}
+
+export function clearOwnedSpeechTurnsForTests(): void {
+ ownedTurns.clear()
+}
+
interface UseAutoSpeakReplies {
conversationActive: boolean
failureLabel: string
@@ -78,11 +108,24 @@ export function useAutoSpeakReplies({
markSpoken()
const marked = spokenReplyOf(sessionId)
- // Only one window voices a given reply when the same chat is open in
- // several. The claim key is the turn, not the row id: hydration rewrites
- // the row id, and a second claim would start a second clip.
- void ownsAmbientCue(`speak:${reply.turnKey ?? reply.id}`).then(owns => {
- if (!owns || attempt !== attemptSeq) {
+ // Only one window voices a turn when the same chat is open in several:
+ // the turn's owner (see claimSpeech), then once per message. Keys are the
+ // turn and its message text, not the row id: hydration rewrites the row
+ // id, and a second claim would start a second clip. A turn with tool
+ // calls speaks several messages, so the turn alone would let the first
+ // message's claim refuse the final reply.
+ const segmentKey = reply.turnKey ? spokenSegmentKey(reply.turnKey, reply.segmentText ?? reply.text) : null
+ const claimKey = `speak:${segmentKey ?? reply.id}`
+
+ void claimSpeech(reply.turnKey, claimKey).then(owns => {
+ if (attempt !== attemptSeq) {
+ return
+ }
+
+ if (!owns) {
+ // Another window owns this turn, or this message was already voiced.
+ console.debug('[auto-speak] claim already taken', claimKey)
+
return
}
@@ -91,7 +134,7 @@ export function useAutoSpeakReplies({
messageId: reply.id,
profile,
source: 'read-aloud',
- ...(reply.turnKey ? { turnKey: reply.turnKey } : {})
+ ...(segmentKey ? { turnKey: segmentKey } : {})
}).then(
started => {
if (!started && attempt === attemptSeq) {
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts
index ce44bd63e2c..728a2fe8a80 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts
@@ -3,7 +3,7 @@ import { computed } from 'nanostores'
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { useI18n } from '@/i18n'
-import { chatMessageText, collectUnspokenTurnSpeech } from '@/lib/chat-messages'
+import { chatMessageText, collectUnspokenTurnSpeech, lastTextPartText } from '@/lib/chat-messages'
import { triggerHaptic } from '@/lib/haptics'
import {
adoptSpokenReplySession,
@@ -145,6 +145,7 @@ export function useComposerVoice({
return {
id: last.id,
pending: Boolean(last.pending),
+ segmentText: lastTextPartText(last),
text,
turnKey: assistantTurnKey(sessionId, messages, last.id)
}
diff --git a/apps/desktop/src/lib/chat-messages/index.ts b/apps/desktop/src/lib/chat-messages/index.ts
index ab9bc3b4983..efde87bcd2a 100644
--- a/apps/desktop/src/lib/chat-messages/index.ts
+++ b/apps/desktop/src/lib/chat-messages/index.ts
@@ -9,6 +9,7 @@ export {
completeOpenTimelineParts,
dedupeRepeatedTextInParts,
finalizeInterruptedMessages,
+ lastTextPartText,
mergeFinalAssistantText,
normalizeWs,
partsText,
diff --git a/apps/desktop/src/lib/chat-messages/parts.ts b/apps/desktop/src/lib/chat-messages/parts.ts
index a983c0d84a9..488a4eee4a8 100644
--- a/apps/desktop/src/lib/chat-messages/parts.ts
+++ b/apps/desktop/src/lib/chat-messages/parts.ts
@@ -313,6 +313,20 @@ export function partsText(parts: ChatMessagePart[]): string {
.join('')
}
+/** The bubble's last non-empty text part, trimmed. A hydrated tool-call turn
+ * folds several messages into one bubble; this is the newest of them. */
+export function lastTextPartText(message: ChatMessage): string {
+ for (let index = message.parts.length - 1; index >= 0; index -= 1) {
+ const part = message.parts[index]
+
+ if (part.type === 'text' && part.text.trim()) {
+ return part.text.trim()
+ }
+ }
+
+ return ''
+}
+
export function chatMessageText(message: ChatMessage): string {
return partsText(message.parts)
}
diff --git a/apps/desktop/src/lib/spoken-reply.test.ts b/apps/desktop/src/lib/spoken-reply.test.ts
index 91e7a65247b..60d850db618 100644
--- a/apps/desktop/src/lib/spoken-reply.test.ts
+++ b/apps/desktop/src/lib/spoken-reply.test.ts
@@ -1,5 +1,8 @@
import { afterEach, describe, expect, it } from 'vitest'
+import type { SessionMessage } from '@/types/hermes'
+
+import { assistantTextPart, type ChatMessage, lastTextPartText, toChatMessages } from './chat-messages'
import {
absorbSpokenReplyRewrite,
adoptSpokenReplySession,
@@ -8,7 +11,8 @@ import {
isLiveTailReplyId,
markAssistantIdSpoken,
resolveSpokenReply,
- spokenReplyOf
+ spokenReplyOf,
+ spokenSegmentKey
} from './spoken-reply'
const assistant = (id: string) => ({ id, role: 'assistant' as const })
@@ -141,3 +145,51 @@ describe('adoptSpokenReplySession', () => {
expect(spokenReplyOf('session-a')?.id).toBe('a1')
})
})
+
+describe('spokenSegmentKey', () => {
+ it('survives a live-id rewrite: same turn, same text, same key', () => {
+ expect(spokenSegmentKey('s1:0', 'the folded answer')).toBe(spokenSegmentKey('s1:0', 'the folded answer'))
+ })
+
+ it('separates the segments of one tool-run turn', () => {
+ expect(spokenSegmentKey('s1:0', 'Looking into it.')).not.toBe(spokenSegmentKey('s1:0', 'Here is the final report.'))
+ })
+
+ it('separates two turns that say the same thing', () => {
+ expect(spokenSegmentKey('s1:0', 'Done.')).not.toBe(spokenSegmentKey('s1:1', 'Done.'))
+ })
+})
+
+// Hydration folds a tool-call turn's assistant rows into one bubble, so its full
+// text is progress + final. A window that only sees that history must derive
+// the same key as the window that spoke the live final bubble, or both read it.
+describe('spokenSegmentKey across a hydration fold', () => {
+ it("gives the hydrated bubble the live final bubble's key", () => {
+ const stored: SessionMessage[] = [
+ { role: 'user', content: 'fix it', timestamp: 1 },
+ {
+ role: 'assistant',
+ content: 'Looking into it.',
+ timestamp: 2,
+ tool_calls: [{ id: 'tc', function: { name: 'terminal', arguments: '{}' } }]
+ },
+ { role: 'tool', tool_call_id: 'tc', content: 'ok', timestamp: 3 },
+ { role: 'assistant', content: 'Here is the final report.', timestamp: 4 }
+ ]
+
+ const hydrated = toChatMessages(stored)
+ const folded = hydrated.findLast(m => m.role === 'assistant')!
+
+ // The fold really did merge both messages into one bubble.
+ expect(hydrated.filter(m => m.role === 'assistant')).toHaveLength(1)
+
+ const live: ChatMessage = {
+ id: 'assistant-stream-2',
+ parts: [assistantTextPart('Here is the final report.')],
+ role: 'assistant'
+ }
+
+ expect(spokenSegmentKey('s1:0', lastTextPartText(folded))).toBe(spokenSegmentKey('s1:0', lastTextPartText(live)))
+ expect(spokenSegmentKey('s1:0', lastTextPartText(folded))).not.toBe(spokenSegmentKey('s1:0', 'Looking into it.'))
+ })
+})
diff --git a/apps/desktop/src/lib/spoken-reply.ts b/apps/desktop/src/lib/spoken-reply.ts
index 1d1f69a52e2..984dc573825 100644
--- a/apps/desktop/src/lib/spoken-reply.ts
+++ b/apps/desktop/src/lib/spoken-reply.ts
@@ -91,6 +91,27 @@ export function assistantTurnKey(
return `${sessionId ?? ''}:${assistantTurnIndex(messages, id)}`
}
+// FNV-1a: a short, deterministic text fingerprint every window computes alike.
+function textHash(text: string): string {
+ let hash = 0x811c9dc5
+
+ for (let index = 0; index < text.length; index += 1) {
+ hash ^= text.charCodeAt(index)
+ hash = Math.imul(hash, 16777619)
+ }
+
+ return (hash >>> 0).toString(36)
+}
+
+/** One spoken message of a turn. A turn with tool calls speaks several bubbles
+ * under one user turn (progress updates, then the final reply), so the turn
+ * key alone would let the first bubble's claim swallow the rest. Pass the
+ * bubble's last text part: a live-id rewrite and a hydration fold both keep
+ * it, so the key survives either. */
+export function spokenSegmentKey(turnKey: string, text: string): string {
+ return `${turnKey}:${textHash(text)}`
+}
+
/** If a spoken live-tail row vanished and the same user turn now has a durable
* id, migrate the anchor — even when tool rows moved the assistant ordinal.
* Leave durable ids and later turns alone. */