mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 21:04:23 +01:00
Merge pull request #426 from chriswritescode-dev/feat/tts-visible-messages-shortcut
feat(tts): play TTS for visible messages with a keyboard shortcut
This commit is contained in:
15 files changed
+957
-175
No files matched your search
@@ -35,12 +35,14 @@ interface MockTTSReturn {
|
||||
describe('FloatingTTSButton', () => {
|
||||
const mockSpeakMessage = vi.fn()
|
||||
const mockStop = vi.fn()
|
||||
const mockSpeakVisible = vi.fn()
|
||||
const mockUpdateSettings = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockSpeakMessage.mockClear()
|
||||
mockStop.mockClear()
|
||||
mockSpeakVisible.mockClear()
|
||||
mockUpdateSettings.mockClear()
|
||||
mocks.showToastInfo.mockClear()
|
||||
})
|
||||
@@ -84,19 +86,19 @@ describe('FloatingTTSButton', () => {
|
||||
|
||||
it('renders pill when content is empty but autoplay is enabled', () => {
|
||||
setup({ autoPlay: true })
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content="" />)
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content="" isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
|
||||
expect(screen.getByRole('button', { name: /hold to toggle auto-play/i })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders pill when content is whitespace but autoplay is enabled', () => {
|
||||
setup({ autoPlay: true })
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content=" " />)
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content=" " isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
|
||||
expect(screen.getByRole('button', { name: /hold to toggle auto-play/i })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls speakMessage on tap when idle', () => {
|
||||
setup()
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /play latest reply/i })
|
||||
fireEvent.pointerDown(button)
|
||||
@@ -110,7 +112,7 @@ describe('FloatingTTSButton', () => {
|
||||
|
||||
it('calls stop on tap when this message is active', () => {
|
||||
setup({ activeMessageId: TEST_MESSAGE_ID, isPlaying: true })
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /stop playback/i })
|
||||
fireEvent.pointerDown(button)
|
||||
@@ -124,7 +126,7 @@ describe('FloatingTTSButton', () => {
|
||||
|
||||
it('calls stop when any playback is active, even for a different messageId (stream conflict fix)', () => {
|
||||
setup({ activeMessageId: 'other-message-id', isPlaying: true })
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /stop playback/i })
|
||||
fireEvent.pointerDown(button)
|
||||
@@ -139,7 +141,7 @@ describe('FloatingTTSButton', () => {
|
||||
it('toggles autoplay on long press', async () => {
|
||||
vi.useFakeTimers()
|
||||
setup({ autoPlay: false })
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /play latest reply/i })
|
||||
await act(async () => {
|
||||
@@ -172,7 +174,7 @@ describe('FloatingTTSButton', () => {
|
||||
it('shows a toast when long press disables autoplay', async () => {
|
||||
vi.useFakeTimers()
|
||||
setup({ autoPlay: true })
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /auto-play enabled/i })
|
||||
await act(async () => {
|
||||
@@ -195,7 +197,7 @@ describe('FloatingTTSButton', () => {
|
||||
it('does not call speakMessage after long press (race guard)', async () => {
|
||||
vi.useFakeTimers()
|
||||
setup()
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /play latest reply/i })
|
||||
await act(async () => {
|
||||
@@ -212,7 +214,7 @@ describe('FloatingTTSButton', () => {
|
||||
it('does not call speakMessage if pointer leaves before release after long press fires', async () => {
|
||||
vi.useFakeTimers()
|
||||
setup()
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /play latest reply/i })
|
||||
await act(async () => {
|
||||
@@ -227,7 +229,7 @@ describe('FloatingTTSButton', () => {
|
||||
|
||||
it('exposes the gesture hint in the aria-label for accessibility', () => {
|
||||
setup()
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /hold to toggle auto-play/i })
|
||||
expect(button).toBeInTheDocument()
|
||||
@@ -235,7 +237,7 @@ describe('FloatingTTSButton', () => {
|
||||
|
||||
it('shows stop icon when this message is playing', () => {
|
||||
setup({ autoPlay: true, activeMessageId: TEST_MESSAGE_ID, isPlaying: true })
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /stop playback/i })
|
||||
|
||||
@@ -249,14 +251,14 @@ describe('FloatingTTSButton', () => {
|
||||
|
||||
it('shows the same stop icon while this message is loading', () => {
|
||||
setup({ activeMessageId: TEST_MESSAGE_ID, isLoading: true })
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
|
||||
|
||||
expect(screen.getByRole('button', { name: /stop playback/i })).toHaveClass('bg-destructive')
|
||||
})
|
||||
|
||||
it('shows autoplay state with button color when autoPlay is enabled', () => {
|
||||
setup({ autoPlay: true })
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /auto-play enabled/i })
|
||||
|
||||
@@ -269,7 +271,7 @@ describe('FloatingTTSButton', () => {
|
||||
|
||||
it('uses the default play color when autoPlay is disabled', () => {
|
||||
setup({ autoPlay: false })
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /play latest reply/i })
|
||||
|
||||
@@ -277,4 +279,68 @@ describe('FloatingTTSButton', () => {
|
||||
expect(button).not.toHaveClass('bg-primary')
|
||||
expect(screen.queryByText('Play')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reads visible replies on tap when scrolled up and idle', () => {
|
||||
setup()
|
||||
render(
|
||||
<FloatingTTSButton
|
||||
messageId={TEST_MESSAGE_ID}
|
||||
content={TEST_CONTENT}
|
||||
isScrolledUp
|
||||
onSpeakVisible={mockSpeakVisible}
|
||||
/>
|
||||
)
|
||||
|
||||
const button = screen.getByRole('button', { name: /read visible replies/i })
|
||||
fireEvent.pointerDown(button)
|
||||
act(() => {
|
||||
fireEvent.pointerUp(button)
|
||||
})
|
||||
|
||||
expect(mockSpeakVisible).toHaveBeenCalledTimes(1)
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('stops playback on tap when scrolled up and playing', () => {
|
||||
setup({ activeMessageId: TEST_MESSAGE_ID, isPlaying: true })
|
||||
render(
|
||||
<FloatingTTSButton
|
||||
messageId={TEST_MESSAGE_ID}
|
||||
content={TEST_CONTENT}
|
||||
isScrolledUp
|
||||
onSpeakVisible={mockSpeakVisible}
|
||||
/>
|
||||
)
|
||||
|
||||
const button = screen.getByRole('button', { name: /stop playback/i })
|
||||
fireEvent.pointerDown(button)
|
||||
act(() => {
|
||||
fireEvent.pointerUp(button)
|
||||
})
|
||||
|
||||
expect(mockStop).toHaveBeenCalledTimes(1)
|
||||
expect(mockSpeakVisible).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('speaks the latest reply on tap when not scrolled up and idle', () => {
|
||||
setup()
|
||||
render(
|
||||
<FloatingTTSButton
|
||||
messageId={TEST_MESSAGE_ID}
|
||||
content={TEST_CONTENT}
|
||||
isScrolledUp={false}
|
||||
onSpeakVisible={mockSpeakVisible}
|
||||
/>
|
||||
)
|
||||
|
||||
const button = screen.getByRole('button', { name: /play latest reply/i })
|
||||
fireEvent.pointerDown(button)
|
||||
act(() => {
|
||||
fireEvent.pointerUp(button)
|
||||
})
|
||||
|
||||
expect(mockSpeakMessage).toHaveBeenCalledTimes(1)
|
||||
expect(mockSpeakMessage).toHaveBeenCalledWith(TEST_MESSAGE_ID, TEST_CONTENT)
|
||||
expect(mockSpeakVisible).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -8,11 +8,13 @@ import { DEFAULT_TTS_CONFIG } from '@opencode-manager/shared'
|
||||
interface FloatingTTSButtonProps {
|
||||
messageId: string
|
||||
content: string
|
||||
isScrolledUp: boolean
|
||||
onSpeakVisible: () => void
|
||||
}
|
||||
|
||||
const LONG_PRESS_DURATION = 500
|
||||
|
||||
export function FloatingTTSButton({ messageId, content }: FloatingTTSButtonProps) {
|
||||
export function FloatingTTSButton({ messageId, content, isScrolledUp, onSpeakVisible }: FloatingTTSButtonProps) {
|
||||
const { speakMessage, stop, isPlaying, isLoading } = useTTS()
|
||||
const { preferences, updateSettings } = useSettings()
|
||||
|
||||
@@ -63,10 +65,15 @@ export function FloatingTTSButton({ messageId, content }: FloatingTTSButtonProps
|
||||
return
|
||||
}
|
||||
|
||||
if (isScrolledUp) {
|
||||
onSpeakVisible()
|
||||
return
|
||||
}
|
||||
|
||||
if (hasContent) {
|
||||
speakMessage(messageId, content)
|
||||
}
|
||||
}, [clearLongPressTimer, isAnyPlaybackActive, stop, speakMessage, messageId, content, hasContent])
|
||||
}, [clearLongPressTimer, isAnyPlaybackActive, stop, isScrolledUp, onSpeakVisible, speakMessage, messageId, content, hasContent])
|
||||
|
||||
const handlePointerLeave = useCallback(() => {
|
||||
clearLongPressTimer()
|
||||
@@ -77,9 +84,11 @@ export function FloatingTTSButton({ messageId, content }: FloatingTTSButtonProps
|
||||
const showStop = isAnyPlaybackActive
|
||||
const pillTitle = showStop
|
||||
? 'Stop playback'
|
||||
: hasContent
|
||||
? 'Play latest reply'
|
||||
: 'TTS controls'
|
||||
: isScrolledUp
|
||||
? 'Read visible replies'
|
||||
: hasContent
|
||||
? 'Play latest reply'
|
||||
: 'TTS controls'
|
||||
const pillAriaLabel = `${pillTitle}. ${autoPlay ? 'Auto-play enabled.' : 'Auto-play disabled.'} hold to toggle auto-play`
|
||||
const buttonToneClasses = showStop
|
||||
? 'justify-center px-3 py-1.5 rounded-lg bg-destructive border border-destructive/60 shadow-destructive/30 ring-destructive/20 hover:ring-destructive/40 text-destructive-foreground'
|
||||
|
||||
@@ -496,7 +496,7 @@ const MessageRow = memo(function MessageRow({
|
||||
: 0
|
||||
|
||||
return (
|
||||
<div className="flex flex-col group">
|
||||
<div className="flex flex-col group" data-message-id={message.id}>
|
||||
<div
|
||||
className={`w-full rounded-lg p-1.5 bg-card/50 border border-border ${streaming ? 'animate-pulse-subtle' : ''}`}
|
||||
>
|
||||
|
||||
@@ -7,7 +7,7 @@ import { formatEventModifiers, formatShortcutEvent, isModifierOnlyEvent, normali
|
||||
import { applyTuiKeybindImport, parseTuiKeybindConfig } from '@/lib/tuiKeybindImport'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
const CONVERSATION_ACTIONS = ['submit', 'abort', 'clearPrompt', 'toggleMode', 'undo', 'redo', 'compact', 'fork', 'timeline', 'exportSession', 'selectModel', 'variantCycle', 'favoriteCycle', 'halfPageUp', 'halfPageDown']
|
||||
const CONVERSATION_ACTIONS = ['submit', 'abort', 'clearPrompt', 'toggleMode', 'undo', 'redo', 'compact', 'fork', 'timeline', 'exportSession', 'selectModel', 'variantCycle', 'favoriteCycle', 'halfPageUp', 'halfPageDown', 'speakVisible']
|
||||
const NAVIGATION_ACTIONS = ['settings', 'sessions', 'newSession', 'closeSession', 'toggleSidebar', 'toggleTerminal', 'toggleSourceControl']
|
||||
|
||||
const formatShortcutLabel = (action: string): string => {
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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])
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type {
|
||||
SessionMessageAssistant,
|
||||
SessionMessageInfo,
|
||||
SessionMessageUser,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import { collectVisibleAssistantTexts } from './visibleMessageTexts'
|
||||
|
||||
const assistantMessage = (id: string, texts: string[]): SessionMessageAssistant => ({
|
||||
id,
|
||||
type: 'assistant',
|
||||
agent: 'test-agent',
|
||||
model: { providerID: 'test-provider', id: 'test-model' },
|
||||
content: texts.map((text) => ({ type: 'text', text })),
|
||||
time: { created: 1, completed: 2 },
|
||||
})
|
||||
|
||||
const userMessage = (id: string, text: string): SessionMessageUser => ({
|
||||
id,
|
||||
type: 'user',
|
||||
text,
|
||||
time: { created: 1 },
|
||||
})
|
||||
|
||||
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 stubRect = (element: HTMLElement, top: number, bottom: number) => {
|
||||
element.getBoundingClientRect = () => rect(top, bottom)
|
||||
}
|
||||
|
||||
const buildContainer = (): HTMLDivElement => {
|
||||
const container = document.createElement('div')
|
||||
stubRect(container, 0, 100)
|
||||
return container
|
||||
}
|
||||
|
||||
const appendMessageElement = (
|
||||
container: HTMLElement,
|
||||
messageId: string,
|
||||
top: number,
|
||||
bottom: number,
|
||||
): HTMLElement => {
|
||||
const element = document.createElement('div')
|
||||
element.dataset.messageId = messageId
|
||||
stubRect(element, top, bottom)
|
||||
container.appendChild(element)
|
||||
return element
|
||||
}
|
||||
|
||||
describe('collectVisibleAssistantTexts', () => {
|
||||
it('returns only intersecting assistant messages in DOM order', () => {
|
||||
const container = buildContainer()
|
||||
appendMessageElement(container, 'a1', 10, 30)
|
||||
appendMessageElement(container, 'u2', 40, 60)
|
||||
appendMessageElement(container, 'a3', 70, 90)
|
||||
appendMessageElement(container, 'a4', 200, 220)
|
||||
appendMessageElement(container, 'a5', 5, 8)
|
||||
|
||||
const messages: SessionMessageInfo[] = [
|
||||
assistantMessage('a1', ['one']),
|
||||
userMessage('u2', 'hello'),
|
||||
assistantMessage('a3', []),
|
||||
assistantMessage('a4', ['four']),
|
||||
assistantMessage('a5', ['five']),
|
||||
]
|
||||
|
||||
expect(collectVisibleAssistantTexts(container, messages, 0)).toEqual(['one', 'five'])
|
||||
})
|
||||
|
||||
it('ignores user and system messages and assistant messages with no text parts', () => {
|
||||
const container = buildContainer()
|
||||
appendMessageElement(container, 'u1', 10, 30)
|
||||
appendMessageElement(container, 's1', 20, 40)
|
||||
appendMessageElement(container, 'a-empty', 30, 50)
|
||||
appendMessageElement(container, 'a-valid', 40, 60)
|
||||
|
||||
const messages: SessionMessageInfo[] = [
|
||||
userMessage('u1', 'hello'),
|
||||
{ id: 's1', type: 'system', text: 'note', time: { created: 1 } },
|
||||
assistantMessage('a-empty', []),
|
||||
assistantMessage('a-valid', ['kept']),
|
||||
]
|
||||
|
||||
expect(collectVisibleAssistantTexts(container, messages, 0)).toEqual(['kept'])
|
||||
})
|
||||
|
||||
it('returns an empty list when nothing intersects', () => {
|
||||
const container = buildContainer()
|
||||
appendMessageElement(container, 'a1', 200, 220)
|
||||
|
||||
const messages: SessionMessageInfo[] = [assistantMessage('a1', ['hidden'])]
|
||||
|
||||
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'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
import { type SessionMessageInfo } from '@opencode-manager/shared/opencode'
|
||||
import { getAssistantText } from '@/hooks/useAutoPlayLastResponse'
|
||||
|
||||
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, 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 - bottomInset
|
||||
})
|
||||
.map((element) => textById.get(element.dataset.messageId ?? '') ?? '')
|
||||
.filter((text) => text.length > 0)
|
||||
}
|
||||
@@ -35,6 +35,7 @@ import { MessageSkeleton } from "@/components/message/MessageSkeleton";
|
||||
import { exportSession, downloadMarkdown } from "@/lib/exportSession";
|
||||
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||
import { getMessagesContentVersion } from "./sessionContentVersion";
|
||||
import { useSpeakVisibleMessages } from "@/hooks/useSpeakVisibleMessages";
|
||||
import { showToast } from "@/lib/toast";
|
||||
import { getWorkspaceFilePath } from "@/lib/markdownLinks";
|
||||
import { getRepoDisplayName } from "@/lib/utils";
|
||||
@@ -614,6 +615,12 @@ export function SessionDetail() {
|
||||
scrollByUser((direction * container.clientHeight) / 2);
|
||||
}, [scrollByUser]);
|
||||
|
||||
const handleSpeakVisibleMessages = useSpeakVisibleMessages(
|
||||
messageContainerRef,
|
||||
messages,
|
||||
promptOverlayHeight + inputBottomOffset,
|
||||
);
|
||||
|
||||
useShortcutActions({
|
||||
selectModel: handleOpenModelDialog,
|
||||
sessions: handleShowSessionsDialog,
|
||||
@@ -633,6 +640,7 @@ export function SessionDetail() {
|
||||
clearPrompt: handleClearPrompt,
|
||||
halfPageUp: () => scrollMessagesByHalfPage(-1),
|
||||
halfPageDown: () => scrollMessagesByHalfPage(1),
|
||||
speakVisible: handleSpeakVisibleMessages,
|
||||
});
|
||||
|
||||
const handleUndoMessage = useCallback((restoredPrompt: string) => {
|
||||
@@ -768,6 +776,8 @@ export function SessionDetail() {
|
||||
<FloatingTTSButton
|
||||
messageId={latestPlayableAssistant.messageId}
|
||||
content={latestPlayableAssistant.text}
|
||||
isScrolledUp={showScrollButton}
|
||||
onSpeakVisible={handleSpeakVisibleMessages}
|
||||
/>
|
||||
)}
|
||||
{hasPromptContent && !isSessionActive && (
|
||||
|
||||
Reference in new issue
Block a user