fix(tts): exclude covered messages and skip auto-play during shortcut playback

This commit is contained in:
Chris Scott committed 2026-10-13 20:49:32 -04:00
1 parent 7cb6c07494
commit eafa8941cb
7 files changed
+364 -25

No files matched your search

@@ -111,6 +111,8 @@ describe('useAutoPlayLastResponse', () => {
},
updateSettings: mockUpdateSettings,
})
return mockTTS
}
it('does NOT call speakMessage when tts.enabled is false', () => {
@@ -191,6 +193,77 @@ describe('useAutoPlayLastResponse', () => {
expect(mockSpeakMessage).toHaveBeenCalledWith('1', 'Test text')
})
it('does NOT call speakMessage when unattributed playback is active, and does not speak it after playback ends', () => {
const mockTTS = setup()
const incompleteMessage = createMessage('1')
const { rerender } = renderHook(
(props) => useAutoPlayLastResponse(props),
{
initialProps: {
sessionId: 'test-session',
lastAssistantMessage: incompleteMessage,
lastAssistantText: 'Test text',
isStreamingResponse: false,
},
}
)
mockTTS.isPlaying = true
mockTTS.activeMessageId = null
const completedMessage = createMessage('1', Date.now())
rerender({
sessionId: 'test-session',
lastAssistantMessage: completedMessage,
lastAssistantText: 'Test text',
isStreamingResponse: false,
})
expect(mockSpeakMessage).not.toHaveBeenCalled()
mockTTS.isPlaying = false
rerender({
sessionId: 'test-session',
lastAssistantMessage: completedMessage,
lastAssistantText: 'Test text',
isStreamingResponse: false,
})
expect(mockSpeakMessage).not.toHaveBeenCalled()
})
it('CALLS speakMessage when a message-attributed playback is active', () => {
const mockTTS = setup()
const incompleteMessage = createMessage('1')
const { rerender } = renderHook(
(props) => useAutoPlayLastResponse(props),
{
initialProps: {
sessionId: 'test-session',
lastAssistantMessage: incompleteMessage,
lastAssistantText: 'Test text',
isStreamingResponse: false,
},
}
)
mockTTS.isPlaying = true
mockTTS.activeMessageId = 'other-message'
const completedMessage = createMessage('1', Date.now())
rerender({
sessionId: 'test-session',
lastAssistantMessage: completedMessage,
lastAssistantText: 'Test text',
isStreamingResponse: false,
})
expect(mockSpeakMessage).toHaveBeenCalledTimes(1)
expect(mockSpeakMessage).toHaveBeenCalledWith('1', 'Test text')
})
it('does NOT call speakMessage twice for the same message id across multiple rerenders', () => {
setup()
@@ -0,0 +1,202 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook } from '@testing-library/react'
import type { RefObject } from 'react'
import type { SessionMessageAssistant, SessionMessageInfo } from '@opencode-manager/shared/opencode'
import type { TTSState } from '@/hooks/useTTS'
const mocks = vi.hoisted(() => ({
useTTS: vi.fn(),
showToastError: vi.fn(),
}))
vi.mock('@/hooks/useTTS', () => ({
useTTS: mocks.useTTS,
}))
vi.mock('@/lib/toast', () => ({
showToast: { error: mocks.showToastError },
}))
import { useSpeakVisibleMessages } from '../useSpeakVisibleMessages'
interface MockTTSReturn {
speak: ReturnType<typeof vi.fn>
stop: ReturnType<typeof vi.fn>
isEnabled: boolean
isPlaying: boolean
isLoading: boolean
state: TTSState
error: string | null
activeMessageId: string | null
}
const rect = (top: number, bottom: number): DOMRect => ({
top,
bottom,
left: 0,
right: 100,
width: 100,
height: bottom - top,
x: 0,
y: top,
toJSON: () => ({}),
} as DOMRect)
const buildContainer = (messageId: string): HTMLDivElement => {
const container = document.createElement('div')
container.getBoundingClientRect = () => rect(0, 100)
const element = document.createElement('div')
element.dataset.messageId = messageId
element.getBoundingClientRect = () => rect(10, 30)
container.appendChild(element)
return container
}
const assistantMessage = (id: string, text: string): SessionMessageAssistant => ({
id,
type: 'assistant',
agent: 'test-agent',
model: { providerID: 'test-provider', id: 'test-model' },
content: [{ type: 'text', text }],
time: { created: 1, completed: 2 },
})
describe('useSpeakVisibleMessages', () => {
const mockSpeak = vi.fn()
const mockStop = vi.fn()
const setupTTS = (overrides: Partial<MockTTSReturn> = {}) => {
const value: MockTTSReturn = {
speak: mockSpeak,
stop: mockStop,
isEnabled: true,
isPlaying: false,
isLoading: false,
state: 'idle',
error: null,
activeMessageId: null,
...overrides,
}
mocks.useTTS.mockReturnValue(value)
}
beforeEach(() => {
vi.clearAllMocks()
mockSpeak.mockResolvedValue(true)
})
it('stops playback while playing', () => {
setupTTS({ isPlaying: true })
const containerRef: RefObject<HTMLElement | null> = { current: null }
const { result } = renderHook(() =>
useSpeakVisibleMessages(containerRef, [], 0)
)
result.current()
expect(mockStop).toHaveBeenCalledTimes(1)
expect(mockSpeak).not.toHaveBeenCalled()
})
it('speaks the visible assistant texts joined by a blank line', () => {
setupTTS()
const container = buildContainer('a1')
const containerRef: RefObject<HTMLElement | null> = { current: container }
const messages: SessionMessageInfo[] = [assistantMessage('a1', 'hello world')]
const { result } = renderHook(() =>
useSpeakVisibleMessages(containerRef, messages, 0)
)
result.current()
expect(mockSpeak).toHaveBeenCalledTimes(1)
expect(mockSpeak).toHaveBeenCalledWith('hello world')
})
it('does nothing when TTS is disabled', () => {
setupTTS({ isEnabled: false })
const container = buildContainer('a1')
const containerRef: RefObject<HTMLElement | null> = { current: container }
const messages: SessionMessageInfo[] = [assistantMessage('a1', 'hello world')]
const { result } = renderHook(() =>
useSpeakVisibleMessages(containerRef, messages, 0)
)
result.current()
expect(mockSpeak).not.toHaveBeenCalled()
})
it('shows an error toast once after shortcut-started playback fails', () => {
setupTTS()
const container = buildContainer('a1')
const containerRef: RefObject<HTMLElement | null> = { current: container }
const messages: SessionMessageInfo[] = [assistantMessage('a1', 'hello world')]
const { result, rerender } = renderHook(() =>
useSpeakVisibleMessages(containerRef, messages, 0)
)
result.current()
expect(mockSpeak).toHaveBeenCalledTimes(1)
setupTTS({ state: 'error', error: 'network failure' })
rerender()
expect(mocks.showToastError).toHaveBeenCalledTimes(1)
expect(mocks.showToastError).toHaveBeenCalledWith('network failure')
setupTTS({ state: 'error', error: 'another failure' })
rerender()
expect(mocks.showToastError).toHaveBeenCalledTimes(1)
})
it('does not toast when shortcut-started playback returns to idle', () => {
setupTTS()
const container = buildContainer('a1')
const containerRef: RefObject<HTMLElement | null> = { current: container }
const messages: SessionMessageInfo[] = [assistantMessage('a1', 'hello world')]
const { result, rerender } = renderHook(() =>
useSpeakVisibleMessages(containerRef, messages, 0)
)
result.current()
setupTTS({ state: 'playing' })
rerender()
setupTTS({ state: 'idle' })
rerender()
setupTTS({ state: 'error', error: 'late failure' })
rerender()
expect(mocks.showToastError).not.toHaveBeenCalled()
})
it('does not toast when playback becomes message-attributed', () => {
setupTTS()
const container = buildContainer('a1')
const containerRef: RefObject<HTMLElement | null> = { current: container }
const messages: SessionMessageInfo[] = [assistantMessage('a1', 'hello world')]
const { result, rerender } = renderHook(() =>
useSpeakVisibleMessages(containerRef, messages, 0)
)
result.current()
setupTTS({ state: 'playing', activeMessageId: 'a1' })
rerender()
setupTTS({ state: 'error', error: 'late failure', activeMessageId: 'a1' })
rerender()
expect(mocks.showToastError).not.toHaveBeenCalled()
})
})
+16 -4
View File
@@ -37,7 +37,7 @@ export function useAutoPlayLastResponse({
lastAssistantText,
isStreamingResponse,
}: UseAutoPlayLastResponseParams): void {
const { speakMessage, isEnabled: ttsEnabled } = useTTS()
const { speakMessage, isEnabled: ttsEnabled, isPlaying, isLoading, activeMessageId } = useTTS()
const { preferences } = useSettings()
const autoPlayEnabled = preferences?.tts?.autoPlay ?? false
@@ -47,6 +47,13 @@ export function useAutoPlayLastResponse({
const lastKnownCompletedRef = useRef<Record<string, boolean>>({})
const hasSeenIncompleteRef = useRef<boolean>(false)
const previousSessionIdRef = useRef<string | null>(null)
const isUnattributedPlaybackActiveRef = useRef<boolean>(false)
const isUnattributedPlaybackActive = (isPlaying || isLoading) && activeMessageId === null
useEffect(() => {
isUnattributedPlaybackActiveRef.current = isUnattributedPlaybackActive
}, [isUnattributedPlaybackActive])
useEffect(() => {
const isSessionChange = previousSessionIdRef.current !== null && previousSessionIdRef.current !== sessionId
@@ -76,6 +83,7 @@ export function useAutoPlayLastResponse({
const messageId = lastAssistantMessage.id
const isCompleted = isMessageCompleted(lastAssistantMessage)
const wasCompleted = lastKnownCompletedRef.current[messageId] ?? false
const shouldAutoSpeak = !isUnattributedPlaybackActiveRef.current
if (!isCompleted) {
lastKnownCompletedRef.current[messageId] = false
@@ -91,7 +99,7 @@ export function useAutoPlayLastResponse({
hasInitializedRef.current = true
lastSpokenIdRef.current = messageId
lastKnownCompletedRef.current[messageId] = true
if (hasSeenIncompleteRef.current) {
if (hasSeenIncompleteRef.current && shouldAutoSpeak) {
speakMessage(messageId, lastAssistantText)
}
return
@@ -99,14 +107,18 @@ export function useAutoPlayLastResponse({
if (!wasCompleted && messageId === lastSpokenIdRef.current) {
lastKnownCompletedRef.current[messageId] = true
speakMessage(messageId, lastAssistantText)
if (shouldAutoSpeak) {
speakMessage(messageId, lastAssistantText)
}
return
}
if (messageId !== lastSpokenIdRef.current) {
lastSpokenIdRef.current = messageId
lastKnownCompletedRef.current[messageId] = true
speakMessage(messageId, lastAssistantText)
if (shouldAutoSpeak) {
speakMessage(messageId, lastAssistantText)
}
}
}, [
ttsEnabled,
@@ -0,0 +1,41 @@
import { useCallback, useEffect, useRef, type RefObject } from 'react'
import type { SessionMessageInfo } from '@opencode-manager/shared/opencode'
import { useTTS } from './useTTS'
import { collectVisibleAssistantTexts } from '@/lib/visibleMessageTexts'
import { showToast } from '@/lib/toast'
export function useSpeakVisibleMessages(
containerRef: RefObject<HTMLElement | null>,
messages: SessionMessageInfo[],
bottomInset: number,
): () => void {
const { speak, stop, isPlaying, isLoading, isEnabled, state, error, activeMessageId } = useTTS()
const pendingRef = useRef(false)
useEffect(() => {
if (!pendingRef.current) return
if (activeMessageId !== null || state === 'idle') {
pendingRef.current = false
return
}
if (state === 'error') {
showToast.error(error ?? 'Text-to-speech failed')
pendingRef.current = false
}
}, [state, error, activeMessageId])
return useCallback(() => {
if (!isEnabled) return
if (isPlaying || isLoading) {
pendingRef.current = false
stop()
return
}
const container = containerRef.current
if (!container) return
const texts = collectVisibleAssistantTexts(container, messages, bottomInset)
if (texts.length === 0) return
pendingRef.current = true
void speak(texts.join('\n\n'))
}, [isEnabled, isPlaying, isLoading, stop, speak, messages, containerRef, bottomInset])
}
+16 -3
View File
@@ -74,7 +74,7 @@ describe('collectVisibleAssistantTexts', () => {
assistantMessage('a5', ['five']),
]
expect(collectVisibleAssistantTexts(container, messages)).toEqual(['one', 'five'])
expect(collectVisibleAssistantTexts(container, messages, 0)).toEqual(['one', 'five'])
})
it('ignores user and system messages and assistant messages with no text parts', () => {
@@ -91,7 +91,7 @@ describe('collectVisibleAssistantTexts', () => {
assistantMessage('a-valid', ['kept']),
]
expect(collectVisibleAssistantTexts(container, messages)).toEqual(['kept'])
expect(collectVisibleAssistantTexts(container, messages, 0)).toEqual(['kept'])
})
it('returns an empty list when nothing intersects', () => {
@@ -100,6 +100,19 @@ describe('collectVisibleAssistantTexts', () => {
const messages: SessionMessageInfo[] = [assistantMessage('a1', ['hidden'])]
expect(collectVisibleAssistantTexts(container, messages)).toEqual([])
expect(collectVisibleAssistantTexts(container, messages, 0)).toEqual([])
})
it('excludes messages hidden within the bottom inset and includes messages straddling it', () => {
const container = buildContainer()
appendMessageElement(container, 'hidden', 85, 95)
appendMessageElement(container, 'straddling', 75, 95)
const messages: SessionMessageInfo[] = [
assistantMessage('hidden', ['hidden']),
assistantMessage('straddling', ['straddling']),
]
expect(collectVisibleAssistantTexts(container, messages, 20)).toEqual(['straddling'])
})
})
+9 -4
View File
@@ -1,16 +1,21 @@
import { assistantText, type SessionMessageInfo } from '@opencode-manager/shared/opencode'
import { type SessionMessageInfo } from '@opencode-manager/shared/opencode'
import { getAssistantText } from '@/hooks/useAutoPlayLastResponse'
export function collectVisibleAssistantTexts(container: HTMLElement, messages: SessionMessageInfo[]): string[] {
export function collectVisibleAssistantTexts(
container: HTMLElement,
messages: SessionMessageInfo[],
bottomInset: number,
): string[] {
const containerRect = container.getBoundingClientRect()
const textById = new Map(
messages
.filter((message) => message.type === 'assistant')
.map((message) => [message.id, assistantText(message.content).trim()]),
.map((message) => [message.id, getAssistantText(message).trim()]),
)
return Array.from(container.querySelectorAll<HTMLElement>('[data-message-id]'))
.filter((element) => {
const rect = element.getBoundingClientRect()
return rect.bottom > containerRect.top && rect.top < containerRect.bottom
return rect.bottom > containerRect.top && rect.top < containerRect.bottom - bottomInset
})
.map((element) => textById.get(element.dataset.messageId ?? '') ?? '')
.filter((text) => text.length > 0)
+7 -14
View File
@@ -35,7 +35,7 @@ import { MessageSkeleton } from "@/components/message/MessageSkeleton";
import { exportSession, downloadMarkdown } from "@/lib/exportSession";
import { copyTextToClipboard } from "@/lib/clipboard";
import { getMessagesContentVersion } from "./sessionContentVersion";
import { collectVisibleAssistantTexts } from '@/lib/visibleMessageTexts';
import { useSpeakVisibleMessages } from "@/hooks/useSpeakVisibleMessages";
import { showToast } from "@/lib/toast";
import { getWorkspaceFilePath } from "@/lib/markdownLinks";
import { getRepoDisplayName } from "@/lib/utils";
@@ -275,7 +275,7 @@ export function SessionDetail() {
const { modelRef } = useModelSelection(sessionDirectory, modelSelectionSession);
const setSessionStatus = useSessionStatus((state) => state.setStatus);
const isEditingMessage = useUIState((state) => state.isEditingMessage);
const { isEnabled: ttsEnabled, speak, stop, isPlaying: isTTSPlaying, isLoading: isTTSLoading } = useTTS();
const { isEnabled: ttsEnabled } = useTTS();
const { syncForSession: syncPermissionsForSession } = usePermissions();
const { getForSession: getFormForSession, reply: replyToForm, cancel: cancelForm, syncForSession: syncFormsForSession } = useForms();
const currentForm = sessionId ? getFormForSession(sessionId) : null;
@@ -615,18 +615,11 @@ export function SessionDetail() {
scrollByUser((direction * container.clientHeight) / 2);
}, [scrollByUser]);
const handleSpeakVisibleMessages = useCallback(() => {
if (!ttsEnabled) return;
if (isTTSPlaying || isTTSLoading) {
stop();
return;
}
const container = messageContainerRef.current;
if (!container) return;
const texts = collectVisibleAssistantTexts(container, messages);
if (texts.length === 0) return;
speak(texts.join('\n\n'));
}, [ttsEnabled, isTTSPlaying, isTTSLoading, stop, speak, messages]);
const handleSpeakVisibleMessages = useSpeakVisibleMessages(
messageContainerRef,
messages,
promptOverlayHeight + inputBottomOffset,
);
useShortcutActions({
selectModel: handleOpenModelDialog,