Skip to content

The agent that grows with you

fix(desktop): speak each assistant turn once across id rewrite

brooklyn!8b88c6b6c8e5
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 d8548d1c4cf..97659a9bcf4 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
@@ -129,4 +129,208 @@ describe('useAutoSpeakReplies — Edge TTS fallback chain (#93515)', () => {
expect($voicePlayback.get().status).toBe('idle')
expect(playSpeechText).toHaveBeenCalledTimes(1)
})
+
+ it('speaks a tool-folded rewrite once when the assistant ordinal drifts', async () => {
+ $autoSpeakReplies.set(true)
+
+ const $messages = atom<ChatMessage[]>([])
+
+ 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
+ }
+
+ return { id: last.id, pending: Boolean(last.pending), text: chatMessageText(last), turnKey: `${SESSION_ID}:0` }
+ }
+
+ const markSpoken = () => {
+ const messages = $messages.get()
+ const last = messages.findLast(m => m.role === 'assistant' && !m.hidden)
+
+ if (last) {
+ markAssistantIdSpoken(SESSION_ID, messages, last.id)
+ }
+ }
+
+ let settlePlayback: (() => void) | null = null
+
+ vi.mocked(playSpeechText).mockImplementation(async () => {
+ setVoicePlaybackState({
+ audioElement: null,
+ messageId: 'assistant-stream-1',
+ sequence: 1,
+ source: 'read-aloud',
+ status: 'preparing'
+ })
+
+ await new Promise<void>(resolve => {
+ settlePlayback = resolve
+ })
+
+ // Tool rows fold into one durable bubble. The assistant ordinal moves.
+ $messages.set([
+ { id: 'u1', parts: [assistantTextPart('do the thing')], role: 'user' },
+ assistantMessage('durable-42', 'the folded answer')
+ ])
+ setVoicePlaybackState({ ...IDLE_STATE })
+
+ 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>
+ )
+ }
+ )
+
+ act(() => {
+ $messages.set([
+ { id: 'u1', parts: [assistantTextPart('do the thing')], role: 'user' },
+ assistantMessage('narration', 'checking'),
+ assistantMessage('tool-segment', 'ran the tool'),
+ assistantMessage('assistant-stream-1', 'the folded answer')
+ ])
+ })
+
+ await waitFor(() => expect(playSpeechText).toHaveBeenCalledTimes(1))
+
+ await act(async () => {
+ settlePlayback?.()
+ await Promise.resolve()
+ await Promise.resolve()
+ await Promise.resolve()
+ })
+
+ expect($voicePlayback.get().status).toBe('idle')
+ expect(playSpeechText).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not consume a reply when markSpoken runs before a play that never starts', async () => {
+ $autoSpeakReplies.set(true)
+
+ const $messages = atom<ChatMessage[]>([])
+
+ 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
+ }
+
+ return { id: last.id, pending: false, text: chatMessageText(last) }
+ }
+
+ 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).mockResolvedValue(false)
+
+ renderHook(
+ () =>
+ useAutoSpeakReplies({
+ conversationActive: false,
+ failureLabel: 'read-aloud failed',
+ markSpoken,
+ pendingReply,
+ sessionId: SESSION_ID
+ }),
+ {
+ wrapper: ({ children }) => (
+ <ComposerScopeProvider value={{ ...MAIN_COMPOSER_SCOPE, $messages }}>{children}</ComposerScopeProvider>
+ )
+ }
+ )
+
+ act(() => {
+ $messages.set([assistantMessage('assistant-stream-1', 'hello there')])
+ })
+
+ await waitFor(() => expect(playSpeechText).toHaveBeenCalledTimes(1))
+ await waitFor(() => expect(resolveSpokenReply(SESSION_ID, $messages.get())).toBeNull())
+ })
+
+ it('speaks a later turn that says the same thing', async () => {
+ $autoSpeakReplies.set(true)
+
+ const $messages = atom<ChatMessage[]>([])
+
+ 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
+ }
+
+ return { id: last.id, pending: false, text: chatMessageText(last) }
+ }
+
+ 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).mockResolvedValue(true)
+
+ renderHook(
+ () =>
+ useAutoSpeakReplies({
+ conversationActive: false,
+ failureLabel: 'read-aloud failed',
+ markSpoken,
+ pendingReply,
+ sessionId: SESSION_ID
+ }),
+ {
+ wrapper: ({ children }) => (
+ <ComposerScopeProvider value={{ ...MAIN_COMPOSER_SCOPE, $messages }}>{children}</ComposerScopeProvider>
+ )
+ }
+ )
+
+ act(() => {
+ $messages.set([
+ { id: 'u1', parts: [assistantTextPart('again')], role: 'user' },
+ assistantMessage('assistant-stream-1', 'Done.')
+ ])
+ })
+ await waitFor(() => expect(playSpeechText).toHaveBeenCalledTimes(1))
+
+ act(() => {
+ $messages.set([
+ { id: 'u1', parts: [assistantTextPart('again')], role: 'user' },
+ assistantMessage('durable-1', 'Done.'),
+ { id: 'u2', parts: [assistantTextPart('again')], role: 'user' },
+ assistantMessage('assistant-stream-2', 'Done.')
+ ])
+ })
+ await waitFor(() => expect(playSpeechText).toHaveBeenCalledTimes(2))
+ })
})
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 f2873a5f550..dee97506721 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,6 +1,7 @@
import { useStore } from '@nanostores/react'
import { useEffect, useRef } from 'react'
+import { releaseUnplayedSpokenReply, spokenReplyOf } from '@/lib/spoken-reply'
import { playSpeechText } from '@/lib/voice-playback'
import { ownsAmbientCue } from '@/store/ambient'
import { notifyError } from '@/store/notifications'
@@ -13,6 +14,8 @@ interface AutoSpeakReply {
id: string
pending: boolean
text: string
+ /** Survives the live-id rewrite. Absent callers still speak; they just cannot join an in-flight play. */
+ turnKey?: string
}
interface UseAutoSpeakReplies {
@@ -56,6 +59,8 @@ export function useAutoSpeakReplies({
// on (or a chat opens) — consume it so only later replies are spoken.
latest.current.markSpoken()
+ let attemptSeq = 0
+
const speakLatest = () => {
const { connectionId, conversationActive, failureLabel, markSpoken, pendingReply, profile } = latest.current
@@ -69,16 +74,37 @@ export function useAutoSpeakReplies({
return
}
+ const attempt = ++attemptSeq
+
markSpoken()
+ const marked = spokenReplyOf(sessionId)
// Only one window voices a given reply when the same chat is open in
- // several (reply.id is the shared backend message id). markSpoken already
- // ran in every window, so peers just stay quiet.
- void ownsAmbientCue(`speak:${reply.id}`).then(owns => {
- if (owns) {
- void playSpeechText(reply.text, { connectionId, messageId: reply.id, profile, source: 'read-aloud' }).catch(
- error => notifyError(error, failureLabel)
- )
+ // 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) {
+ return
}
+
+ void playSpeechText(reply.text, {
+ connectionId,
+ messageId: reply.id,
+ profile,
+ source: 'read-aloud',
+ ...(reply.turnKey ? { turnKey: reply.turnKey } : {})
+ }).then(
+ started => {
+ if (!started && attempt === attemptSeq) {
+ releaseUnplayedSpokenReply(sessionId, marked)
+ }
+ },
+ error => {
+ if (attempt === attemptSeq) {
+ releaseUnplayedSpokenReply(sessionId, marked)
+ notifyError(error, failureLabel)
+ }
+ }
+ )
})
}
@@ -86,6 +112,9 @@ export function useAutoSpeakReplies({
// ($voicePlayback → idle), which frees us to read the next held reply.
const stops = [$messages.subscribe(speakLatest), $voicePlayback.listen(speakLatest)]
- return () => stops.forEach(f => f())
+ return () => {
+ attemptSeq += 1
+ stops.forEach(f => f())
+ }
}, [$messages, enabled, sessionId])
}
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 4283577cc8d..6c085e87560 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
@@ -5,7 +5,12 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } fr
import { useI18n } from '@/i18n'
import { chatMessageText, collectUnspokenTurnSpeech } from '@/lib/chat-messages'
import { triggerHaptic } from '@/lib/haptics'
-import { adoptSpokenReplySession, markAssistantIdSpoken, resolveSpokenReply } from '@/lib/spoken-reply'
+import {
+ adoptSpokenReplySession,
+ assistantTurnKey,
+ markAssistantIdSpoken,
+ resolveSpokenReply
+} from '@/lib/spoken-reply'
import { CONVERSATION_LEASE, READ_ALOUD_LEASE, syncTtsLease } from '@/lib/tts-lease'
import { toLiveHistory } from '@/lib/voice-live'
import { clearWakeIndicator, syncWakeIndicatorWithVoice } from '@/lib/wake-indicator'
@@ -134,7 +139,8 @@ export function useComposerVoice({
return {
id: last.id,
pending: Boolean(last.pending),
- text
+ text,
+ turnKey: assistantTurnKey(sessionId, messages, last.id)
}
}
diff --git a/apps/desktop/src/lib/spoken-reply.test.ts b/apps/desktop/src/lib/spoken-reply.test.ts
index d48a1e879b4..91e7a65247b 100644
--- a/apps/desktop/src/lib/spoken-reply.test.ts
+++ b/apps/desktop/src/lib/spoken-reply.test.ts
@@ -60,6 +60,29 @@ describe('absorbSpokenReplyRewrite', () => {
expect(absorbSpokenReplyRewrite(spoken, after)).toEqual(spoken)
})
+ it('follows a live-tail rewrite when tool rows change the assistant ordinal', () => {
+ const before = [user('u1'), assistant('narration'), assistant('tool-segment'), assistant('assistant-stream-s')]
+
+ markAssistantIdSpoken('s', before, 'assistant-stream-s')
+
+ // Hydration folds the tool segments into one bubble. The assistant ordinal
+ // moves; the user turn does not.
+ const after = [user('u1'), assistant('42')]
+
+ expect(resolveSpokenReply('s', after)?.id).toBe('42')
+ expect(spokenReplyOf('s')?.id).toBe('42')
+ })
+
+ it('does not mark a later user turn spoken when the live tail vanished', () => {
+ markAssistantIdSpoken('s', [user('u1'), assistant('assistant-stream-s')], 'assistant-stream-s')
+
+ const after = [user('u1'), assistant('durable-1'), user('u2'), assistant('assistant-stream-next')]
+ const spoken = resolveSpokenReply('s', after)
+
+ expect(spoken?.id).not.toBe('assistant-stream-next')
+ expect(after.findLast(message => message.role === 'assistant')?.id).not.toBe(spoken?.id)
+ })
+
it('keeps the anchor when the spoken id is still in the list', () => {
const spoken = { id: 'assistant-stream-s', ordinal: 0 }
const messages = [assistant('assistant-stream-s')]
diff --git a/apps/desktop/src/lib/spoken-reply.ts b/apps/desktop/src/lib/spoken-reply.ts
index 82f614f0ecb..1d1f69a52e2 100644
--- a/apps/desktop/src/lib/spoken-reply.ts
+++ b/apps/desktop/src/lib/spoken-reply.ts
@@ -7,13 +7,18 @@
* edge. A content fingerprint would swallow a later distinct turn that happens
* to say the same thing ("Done.").
*
- * Anchor on the assistant-role ordinal (nth visible assistant bubble). The
- * rewrite keeps that slot; a new turn appends and the ordinal moves.
+ * Anchor on the user turn that owns the bubble, not the assistant-role
+ * ordinal. Hydration rewrites the live id and folds tool segments into one
+ * bubble, so the ordinal moves; the owning user turn does not. A later turn
+ * has a new user row and stays unspoken. Text is not identity — two turns
+ * that both say "Done." are different turns.
*/
export interface SpokenReplyAnchor {
id: string
ordinal: number
+ /** User-turn index at mark time. Absent on anchors built before turn identity. */
+ turnIndex?: number
}
export interface SpokenReplyMessage {
@@ -56,8 +61,39 @@ function lastVisibleAssistant(messages: readonly SpokenReplyMessage[]): SpokenRe
return messages.findLast(message => message.role === 'assistant' && !message.hidden)
}
-/** If a spoken live-tail row vanished and the same assistant slot now has a
- * durable id, migrate the anchor. Leave durable ids and later turns alone. */
+/** Index of the user turn that owns `id`, or -1 when no user row precedes it.
+ * Hidden user rows count: a widget intent is a real turn boundary. Tool and
+ * assistant rows do not, so a fold that changes the assistant ordinal keeps
+ * this index. */
+export function assistantTurnIndex(messages: readonly SpokenReplyMessage[], id: string): number {
+ let turnIndex = -1
+
+ for (const message of messages) {
+ if (message.role === 'user') {
+ turnIndex += 1
+ }
+
+ if (message.id === id) {
+ return message.role === 'assistant' ? turnIndex : -1
+ }
+ }
+
+ return -1
+}
+
+/** Stable across a live-id rewrite. Session-scoped so two chats' first turns
+ * do not share a speech claim. */
+export function assistantTurnKey(
+ sessionId: string | null | undefined,
+ messages: readonly SpokenReplyMessage[],
+ id: string
+): string {
+ return `${sessionId ?? ''}:${assistantTurnIndex(messages, id)}`
+}
+
+/** 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. */
export function absorbSpokenReplyRewrite(
spoken: SpokenReplyAnchor | null,
messages: readonly SpokenReplyMessage[]
@@ -81,6 +117,18 @@ export function absorbSpokenReplyRewrite(
}
const ordinal = assistantReplyOrdinal(messages, last.id)
+ const turnIndex = assistantTurnIndex(messages, last.id)
+ const sameTurn = spoken.turnIndex !== undefined && spoken.turnIndex >= 0 && turnIndex === spoken.turnIndex
+
+ // Turn identity wins over the assistant ordinal. A missing turnIndex is a
+ // legacy anchor: keep the old same-slot check so those still migrate.
+ if (spoken.turnIndex !== undefined && spoken.turnIndex >= 0) {
+ if (!sameTurn) {
+ return spoken
+ }
+
+ return { id: last.id, ordinal, turnIndex: spoken.turnIndex }
+ }
if (ordinal !== spoken.ordinal) {
return spoken
@@ -108,7 +156,7 @@ export function markAssistantIdSpoken(
return
}
- markSpokenReply(sessionId, { id, ordinal })
+ markSpokenReply(sessionId, { id, ordinal, turnIndex: assistantTurnIndex(messages, id) })
}
/**
@@ -161,3 +209,27 @@ export function resolveSpokenReply(
export function clearSpokenRepliesForTests(): void {
lastSpokenBySession.clear()
}
+
+/** A play that never started must not consume the turn. Only clears the anchor
+ * still pointing at the turn we marked — a newer turn's mark stays. */
+export function releaseUnplayedSpokenReply(
+ sessionId: string | null | undefined,
+ marked: SpokenReplyAnchor | null
+): void {
+ if (!marked) {
+ return
+ }
+
+ const current = spokenReplyOf(sessionId)
+
+ if (!current) {
+ return
+ }
+
+ const sameId = current.id === marked.id
+ const sameTurn = marked.turnIndex !== undefined && marked.turnIndex >= 0 && current.turnIndex === marked.turnIndex
+
+ if (sameId || sameTurn) {
+ lastSpokenBySession.delete(sessionKey(sessionId))
+ }
+}
diff --git a/apps/desktop/src/lib/voice-playback.same-turn.test.ts b/apps/desktop/src/lib/voice-playback.same-turn.test.ts
new file mode 100644
index 00000000000..ea30acca1ef
--- /dev/null
+++ b/apps/desktop/src/lib/voice-playback.same-turn.test.ts
@@ -0,0 +1,101 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { $voicePlayback } from '@/store/voice-playback'
+
+import { playSpeechText, stopVoicePlayback } from './voice-playback'
+
+vi.mock('@/lib/voice-client-direct', () => ({
+ cutSentences: (text: string) => [text],
+ directTtsConfig: vi.fn(async () => null),
+ synthesizeSpeechClientDirect: vi.fn()
+}))
+
+vi.mock('@/hermes', () => ({
+ getApiRequestConnection: () => null,
+ getApiRequestProfile: () => null,
+ speakText: vi.fn(async () => {
+ throw new Error('no audio in test')
+ })
+}))
+
+describe('playSpeechText same-turn start', () => {
+ afterEach(() => {
+ stopVoicePlayback()
+ })
+
+ it('does not stop an in-flight play when a second start is the same turn', async () => {
+ const first = playSpeechText('hello there', {
+ messageId: 'assistant-stream-1',
+ source: 'read-aloud',
+ turnKey: 'session:0'
+ })
+
+ const sequenceAfterFirst = $voicePlayback.get().sequence
+
+ const second = playSpeechText('hello there', {
+ messageId: 'durable-42',
+ source: 'read-aloud',
+ turnKey: 'session:0'
+ })
+
+ expect($voicePlayback.get().sequence).toBe(sequenceAfterFirst)
+ expect($voicePlayback.get().status).not.toBe('idle')
+
+ stopVoicePlayback()
+ await Promise.allSettled([first, second])
+ })
+
+ it('still replaces playback when the next start is a different turn', async () => {
+ const first = playSpeechText('first reply', {
+ messageId: 'a1',
+ source: 'read-aloud',
+ turnKey: 'session:0'
+ })
+
+ const sequenceAfterFirst = $voicePlayback.get().sequence
+
+ const second = playSpeechText('second reply', {
+ messageId: 'a2',
+ source: 'read-aloud',
+ turnKey: 'session:1'
+ })
+
+ expect($voicePlayback.get().sequence).toBeGreaterThan(sequenceAfterFirst)
+
+ stopVoicePlayback()
+ await Promise.allSettled([first, second])
+ })
+
+ it('does not let the idle notification from its own stop start a second clip of the same turn', async () => {
+ const stops: number[] = []
+
+ const unlisten = $voicePlayback.listen(state => {
+ if (state.status !== 'idle') {
+ return
+ }
+
+ stops.push(state.sequence)
+ void playSpeechText('hello there', {
+ messageId: 'durable-42',
+ source: 'read-aloud',
+ turnKey: 'session:0'
+ })
+ })
+
+ const before = $voicePlayback.get().sequence
+
+ const first = playSpeechText('hello there', {
+ messageId: 'assistant-stream-1',
+ source: 'read-aloud',
+ turnKey: 'session:0'
+ })
+
+ unlisten()
+ // One stop: the start itself. A second playSpeechText from the idle edge would bump sequence again.
+ expect($voicePlayback.get().sequence).toBe(before + 1)
+ expect(stops.length).toBeGreaterThan(0)
+
+ stopVoicePlayback()
+ await Promise.allSettled([first])
+ })
+})
diff --git a/apps/desktop/src/lib/voice-playback.ts b/apps/desktop/src/lib/voice-playback.ts
index 17cecc2f532..a31f9154da2 100644
--- a/apps/desktop/src/lib/voice-playback.ts
+++ b/apps/desktop/src/lib/voice-playback.ts
@@ -22,6 +22,8 @@ const PLAYBACK_STALL_MS = 15_000
let currentAudio: HTMLAudioElement | null = null
let currentStop: (() => void) | null = null
let sequence = 0
+let claimTurnKey: string | null = null
+let inFlight: { done: Promise<boolean>; turnKey: string } | null = null
// A shared, lazily-created AudioContext used only to nudge the browser's
// autoplay state out of "suspended". A wake-word-started voice turn has no
@@ -77,9 +79,12 @@ export interface VoicePlaybackOptions extends OwnerScope {
* answered `fallback` this reply; the relay may not have been probed. */
syncOnly?: boolean
source: VoicePlaybackSource
+ /** Stable across a live-id rewrite. A second start of this turn must not stop the first. */
+ turnKey?: string
}
export function stopVoicePlayback() {
+ inFlight = null
sequence += 1
currentStop?.()
currentStop = null
@@ -663,8 +668,36 @@ async function playSpeechDataUrl(
}
export async function playSpeechText(text: string, options: VoicePlaybackOptions): Promise<boolean> {
- stopVoicePlayback()
+ if (options.turnKey && (claimTurnKey === options.turnKey || inFlight?.turnKey === options.turnKey)) {
+ return inFlight?.turnKey === options.turnKey ? inFlight.done : Promise.resolve(true)
+ }
+
+ const previousClaim = claimTurnKey
+ claimTurnKey = options.turnKey ?? null
+
+ try {
+ stopVoicePlayback()
+
+ const done = startSpeechText(text, options)
+
+ if (options.turnKey) {
+ inFlight = { done, turnKey: options.turnKey }
+ void done.finally(() => {
+ if (inFlight?.done === done) {
+ inFlight = null
+ }
+ })
+ }
+
+ return done
+ } finally {
+ if (claimTurnKey === (options.turnKey ?? null)) {
+ claimTurnKey = previousClaim
+ }
+ }
+}
+async function startSpeechText(text: string, options: VoicePlaybackOptions): Promise<boolean> {
const speakableText = sanitizeTextForSpeech(text)
if (!speakableText) {