mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
feat(frontend): improve mobile voice controls and TTS playback
This commit is contained in:
1 parent
dad1a608a1
commit
29b9d028c7
14 files changed
+1434
-142
No files matched your search
@@ -116,17 +116,6 @@ export function findGitHubCredential(credentials: GitCredential[]): GitCredentia
|
||||
}) || null
|
||||
}
|
||||
|
||||
export function getCredentialForHost(credentials: GitCredential[], host: string): GitCredential | undefined {
|
||||
return credentials.find(cred => {
|
||||
try {
|
||||
const parsed = new URL(cred.host)
|
||||
return parsed.hostname.toLowerCase() === host.toLowerCase()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function getSSHCredentialsForHost(credentials: GitCredential[], host: string): GitCredential[] {
|
||||
return credentials.filter(cred => {
|
||||
if (cred.type !== 'ssh') return false
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, act } from '@testing-library/react'
|
||||
import { FloatingTTSButton } from './FloatingTTSButton'
|
||||
import type { TTSConfig } from '@opencode-manager/shared'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useTTS: vi.fn(),
|
||||
useSettings: vi.fn(),
|
||||
showToastInfo: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useTTS', () => ({
|
||||
useTTS: mocks.useTTS,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSettings', () => ({
|
||||
useSettings: mocks.useSettings,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: {
|
||||
info: mocks.showToastInfo,
|
||||
},
|
||||
}))
|
||||
|
||||
interface MockTTSReturn {
|
||||
speakMessage: ReturnType<typeof vi.fn>
|
||||
stop: ReturnType<typeof vi.fn>
|
||||
activeMessageId: string | null
|
||||
isPlaying: boolean
|
||||
isLoading: boolean
|
||||
isEnabled: boolean
|
||||
}
|
||||
|
||||
describe('FloatingTTSButton', () => {
|
||||
const mockSpeakMessage = vi.fn()
|
||||
const mockStop = vi.fn()
|
||||
const mockUpdateSettings = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockSpeakMessage.mockClear()
|
||||
mockStop.mockClear()
|
||||
mockUpdateSettings.mockClear()
|
||||
mocks.showToastInfo.mockClear()
|
||||
})
|
||||
|
||||
const setup = (options: {
|
||||
ttsEnabled?: boolean
|
||||
autoPlay?: boolean
|
||||
activeMessageId?: string | null
|
||||
isPlaying?: boolean
|
||||
isLoading?: boolean
|
||||
} = {}) => {
|
||||
const mockTTS: MockTTSReturn = {
|
||||
speakMessage: mockSpeakMessage,
|
||||
stop: mockStop,
|
||||
activeMessageId: options.activeMessageId ?? null,
|
||||
isPlaying: options.isPlaying ?? false,
|
||||
isLoading: options.isLoading ?? false,
|
||||
isEnabled: options.ttsEnabled ?? true,
|
||||
}
|
||||
mocks.useTTS.mockReturnValue(mockTTS)
|
||||
|
||||
mocks.useSettings.mockReturnValue({
|
||||
preferences: {
|
||||
tts: {
|
||||
enabled: options.ttsEnabled ?? true,
|
||||
autoPlay: options.autoPlay ?? false,
|
||||
provider: 'external',
|
||||
endpoint: 'https://api.openai.com',
|
||||
apiKey: 'test-key',
|
||||
voice: 'alloy',
|
||||
model: 'tts-1',
|
||||
speed: 1.0,
|
||||
} as TTSConfig,
|
||||
},
|
||||
updateSettings: mockUpdateSettings,
|
||||
})
|
||||
}
|
||||
|
||||
const TEST_MESSAGE_ID = 'test-message-1'
|
||||
const TEST_CONTENT = 'Test content'
|
||||
|
||||
it('renders pill when content is empty but autoplay is enabled', () => {
|
||||
setup({ autoPlay: true })
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content="" />)
|
||||
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=" " />)
|
||||
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} />)
|
||||
|
||||
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)
|
||||
})
|
||||
|
||||
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} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /stop playback/i })
|
||||
fireEvent.pointerDown(button)
|
||||
act(() => {
|
||||
fireEvent.pointerUp(button)
|
||||
})
|
||||
|
||||
expect(mockStop).toHaveBeenCalledTimes(1)
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
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} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /stop playback/i })
|
||||
fireEvent.pointerDown(button)
|
||||
act(() => {
|
||||
fireEvent.pointerUp(button)
|
||||
})
|
||||
|
||||
expect(mockStop).toHaveBeenCalledTimes(1)
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('toggles autoplay on long press', async () => {
|
||||
vi.useFakeTimers()
|
||||
setup({ autoPlay: false })
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /play latest reply/i })
|
||||
await act(async () => {
|
||||
fireEvent.pointerDown(button)
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
fireEvent.pointerUp(button)
|
||||
})
|
||||
|
||||
expect(mockUpdateSettings).toHaveBeenCalledTimes(1)
|
||||
expect(mockUpdateSettings).toHaveBeenCalledWith({
|
||||
tts: {
|
||||
autoPlay: true,
|
||||
enabled: true,
|
||||
provider: 'external',
|
||||
endpoint: 'https://api.openai.com',
|
||||
apiKey: 'test-key',
|
||||
voice: 'alloy',
|
||||
model: 'tts-1',
|
||||
speed: 1.0,
|
||||
},
|
||||
})
|
||||
expect(mocks.showToastInfo).toHaveBeenCalledWith('Auto-play enabled', {
|
||||
id: 'tts-autoplay-toggle',
|
||||
duration: 1800,
|
||||
})
|
||||
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('shows a toast when long press disables autoplay', async () => {
|
||||
vi.useFakeTimers()
|
||||
setup({ autoPlay: true })
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /auto-play enabled/i })
|
||||
await act(async () => {
|
||||
fireEvent.pointerDown(button)
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
fireEvent.pointerUp(button)
|
||||
})
|
||||
|
||||
expect(mockUpdateSettings).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ tts: expect.objectContaining({ autoPlay: false }) })
|
||||
)
|
||||
expect(mocks.showToastInfo).toHaveBeenCalledWith('Auto-play disabled', {
|
||||
id: 'tts-autoplay-toggle',
|
||||
duration: 1800,
|
||||
})
|
||||
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('does not call speakMessage after long press (race guard)', async () => {
|
||||
vi.useFakeTimers()
|
||||
setup()
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /play latest reply/i })
|
||||
await act(async () => {
|
||||
fireEvent.pointerDown(button)
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
fireEvent.pointerUp(button)
|
||||
})
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
expect(mockStop).not.toHaveBeenCalled()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
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} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /play latest reply/i })
|
||||
await act(async () => {
|
||||
fireEvent.pointerDown(button)
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
fireEvent.pointerLeave(button)
|
||||
})
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('exposes the gesture hint in the aria-label for accessibility', () => {
|
||||
setup()
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /hold to toggle auto-play/i })
|
||||
expect(button).toBeInTheDocument()
|
||||
})
|
||||
|
||||
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} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /stop playback/i })
|
||||
|
||||
expect(button).toHaveClass('from-red-600')
|
||||
expect(button).toHaveClass('rounded-lg')
|
||||
expect(button).not.toHaveClass('rounded-full')
|
||||
expect(button).not.toHaveClass('hidden')
|
||||
expect(screen.queryByText('Stop')).not.toBeInTheDocument()
|
||||
expect(screen.queryByLabelText('Autoplay enabled')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
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} />)
|
||||
|
||||
expect(screen.getByRole('button', { name: /stop playback/i })).toHaveClass('from-red-600')
|
||||
})
|
||||
|
||||
it('shows autoplay state with button color when autoPlay is enabled', () => {
|
||||
setup({ autoPlay: true })
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /auto-play enabled/i })
|
||||
|
||||
expect(button).toHaveClass('from-blue-500')
|
||||
expect(button).toHaveClass('rounded-lg')
|
||||
expect(screen.queryByText('Play')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Auto')).not.toBeInTheDocument()
|
||||
expect(screen.queryByLabelText('Autoplay enabled')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('uses the default play color when autoPlay is disabled', () => {
|
||||
setup({ autoPlay: false })
|
||||
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
|
||||
|
||||
const button = screen.getByRole('button', { name: /play latest reply/i })
|
||||
|
||||
expect(button).toHaveClass('from-amber-500')
|
||||
expect(button).not.toHaveClass('from-blue-500')
|
||||
expect(screen.queryByText('Play')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,49 +1,109 @@
|
||||
import { Volume2, VolumeX, Loader2 } from 'lucide-react'
|
||||
import { useState, useCallback, useRef } from 'react'
|
||||
import { Volume2, VolumeX } from 'lucide-react'
|
||||
import { useTTS } from '@/hooks/useTTS'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { DEFAULT_TTS_CONFIG } from '@opencode-manager/shared'
|
||||
|
||||
interface FloatingTTSButtonProps {
|
||||
messageId: string
|
||||
content: string
|
||||
}
|
||||
|
||||
export function FloatingTTSButton({ content }: FloatingTTSButtonProps) {
|
||||
const { speak, stop, isEnabled, isPlaying, isLoading, originalText } = useTTS()
|
||||
|
||||
if (!isEnabled || !content.trim()) {
|
||||
return null
|
||||
}
|
||||
|
||||
const isThisPlaying = (isPlaying || isLoading) && originalText === content
|
||||
|
||||
const handleClick = () => {
|
||||
if (isThisPlaying) {
|
||||
stop()
|
||||
} else {
|
||||
speak(content)
|
||||
const LONG_PRESS_DURATION = 500
|
||||
|
||||
export function FloatingTTSButton({ messageId, content }: FloatingTTSButtonProps) {
|
||||
const { speakMessage, stop, isPlaying, isLoading } = useTTS()
|
||||
const { preferences, updateSettings } = useSettings()
|
||||
|
||||
const autoPlay = preferences?.tts?.autoPlay ?? false
|
||||
const [isLongPressVisual, setIsLongPressVisual] = useState(false)
|
||||
const longPressTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const didLongPressFireRef = useRef(false)
|
||||
|
||||
const isAnyPlaybackActive = isPlaying || isLoading
|
||||
const hasContent = content.trim().length > 0
|
||||
|
||||
const clearLongPressTimer = useCallback(() => {
|
||||
if (longPressTimerRef.current) {
|
||||
clearTimeout(longPressTimerRef.current)
|
||||
longPressTimerRef.current = null
|
||||
}
|
||||
}
|
||||
|
||||
}, [])
|
||||
|
||||
const handlePointerDown = useCallback(() => {
|
||||
clearLongPressTimer()
|
||||
didLongPressFireRef.current = false
|
||||
longPressTimerRef.current = setTimeout(() => {
|
||||
const nextAutoPlay = !autoPlay
|
||||
|
||||
didLongPressFireRef.current = true
|
||||
setIsLongPressVisual(true)
|
||||
updateSettings({ tts: { ...(preferences?.tts ?? DEFAULT_TTS_CONFIG), autoPlay: nextAutoPlay } })
|
||||
showToast.info(nextAutoPlay ? 'Auto-play enabled' : 'Auto-play disabled', {
|
||||
id: 'tts-autoplay-toggle',
|
||||
duration: 1800,
|
||||
})
|
||||
}, LONG_PRESS_DURATION)
|
||||
}, [autoPlay, updateSettings, preferences?.tts, clearLongPressTimer])
|
||||
|
||||
const handlePointerUp = useCallback(() => {
|
||||
clearLongPressTimer()
|
||||
|
||||
if (didLongPressFireRef.current) {
|
||||
didLongPressFireRef.current = false
|
||||
setIsLongPressVisual(false)
|
||||
return
|
||||
}
|
||||
|
||||
if (isAnyPlaybackActive) {
|
||||
stop()
|
||||
return
|
||||
}
|
||||
|
||||
if (hasContent) {
|
||||
speakMessage(messageId, content)
|
||||
}
|
||||
}, [clearLongPressTimer, isAnyPlaybackActive, stop, speakMessage, messageId, content, hasContent])
|
||||
|
||||
const handlePointerLeave = useCallback(() => {
|
||||
clearLongPressTimer()
|
||||
didLongPressFireRef.current = false
|
||||
setIsLongPressVisual(false)
|
||||
}, [clearLongPressTimer])
|
||||
|
||||
const showStop = isAnyPlaybackActive
|
||||
const pillTitle = showStop
|
||||
? 'Stop playback (hold to toggle auto-play)'
|
||||
: hasContent
|
||||
? autoPlay
|
||||
? 'Play latest reply (auto-play enabled; hold to toggle auto-play)'
|
||||
: 'Play latest reply (hold to toggle auto-play)'
|
||||
: autoPlay
|
||||
? 'Auto-play enabled (hold to toggle auto-play)'
|
||||
: 'Hold to toggle auto-play'
|
||||
const pillAriaLabel = pillTitle
|
||||
const buttonToneClasses = showStop
|
||||
? 'justify-center px-3 py-1.5 rounded-lg bg-gradient-to-br from-red-600 to-red-700 border border-red-500/60 shadow-red-500/30 ring-red-500/20 hover:ring-red-500/40 text-white'
|
||||
: autoPlay
|
||||
? 'justify-center px-3 py-1.5 rounded-lg bg-gradient-to-br from-blue-500 to-blue-600 border border-blue-400/60 shadow-blue-500/30 ring-blue-500/20 hover:ring-blue-500/40 text-white'
|
||||
: 'justify-center px-3 py-1.5 rounded-lg bg-gradient-to-br from-amber-500 to-orange-600 border border-amber-400/60 shadow-amber-500/30 ring-amber-500/20 hover:ring-amber-500/40 text-white'
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={handleClick}
|
||||
className={`absolute -top-5 right-0 md:right-4 z-50 flex items-center gap-1.5 px-3 py-1.5 rounded-lg transition-all duration-200 active:scale-95 hover:scale-105 shadow-md backdrop-blur-md ring-1 ${
|
||||
isThisPlaying
|
||||
? 'bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-destructive-foreground border border-red-500/60 shadow-red-500/30 ring-red-500/20 hover:ring-red-500/40'
|
||||
: 'bg-gradient-to-br from-amber-500 to-orange-600 hover:from-amber-400 hover:to-orange-500 text-white border border-amber-400/60 shadow-amber-500/30 ring-amber-500/20 hover:ring-amber-500/40'
|
||||
}`}
|
||||
title={isThisPlaying ? 'Stop playback' : 'Play last response'}
|
||||
aria-label={isThisPlaying ? 'Stop playback' : 'Play last response'}
|
||||
disabled={isLoading && originalText !== content}
|
||||
>
|
||||
{isLoading && isThisPlaying ? (
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
) : isThisPlaying ? (
|
||||
<VolumeX className="w-5 h-5" />
|
||||
) : (
|
||||
<Volume2 className="w-5 h-5" />
|
||||
)}
|
||||
<span className="text-sm font-medium hidden sm:inline">
|
||||
{isThisPlaying ? 'Stop' : 'Play Last'}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerUp={handlePointerUp}
|
||||
onPointerLeave={handlePointerLeave}
|
||||
className={`absolute -top-5 right-0 md:right-4 z-50 flex items-center transition-all duration-200 shadow-md backdrop-blur-md ring-1 ${buttonToneClasses} ${isLongPressVisual ? 'scale-95 opacity-80' : 'active:scale-95 hover:scale-105'} ${!hasContent && !autoPlay ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
title={pillTitle}
|
||||
aria-label={pillAriaLabel}
|
||||
disabled={!hasContent && !autoPlay}
|
||||
>
|
||||
{showStop ? (
|
||||
<VolumeX className="w-5 h-5" />
|
||||
) : hasContent || autoPlay ? (
|
||||
<Volume2 className="w-5 h-5" />
|
||||
) : null}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { MessagePart } from './MessagePart'
|
||||
import type { MessagePart as MessagePartType } from '@/api/types'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useTTS: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useTTS', () => ({
|
||||
useTTS: mocks.useTTS,
|
||||
}))
|
||||
|
||||
interface MockTTSReturn {
|
||||
speakMessage: ReturnType<typeof vi.fn>
|
||||
stop: ReturnType<typeof vi.fn>
|
||||
activeMessageId: string | null
|
||||
isPlaying: boolean
|
||||
isLoading: boolean
|
||||
isEnabled: boolean
|
||||
}
|
||||
|
||||
describe('MessagePart', () => {
|
||||
const mockSpeakMessage = vi.fn()
|
||||
const mockStop = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
mockSpeakMessage.mockClear()
|
||||
mockStop.mockClear()
|
||||
})
|
||||
|
||||
const setup = (options: {
|
||||
ttsEnabled?: boolean
|
||||
autoPlay?: boolean
|
||||
activeMessageId?: string | null
|
||||
isPlaying?: boolean
|
||||
isLoading?: boolean
|
||||
} = {}) => {
|
||||
const mockTTS: MockTTSReturn = {
|
||||
speakMessage: mockSpeakMessage,
|
||||
stop: mockStop,
|
||||
activeMessageId: options.activeMessageId ?? null,
|
||||
isPlaying: options.isPlaying ?? false,
|
||||
isLoading: options.isLoading ?? false,
|
||||
isEnabled: options.ttsEnabled ?? true,
|
||||
}
|
||||
mocks.useTTS.mockReturnValue(mockTTS)
|
||||
}
|
||||
|
||||
const createStepFinishPart = (messageID: string): MessagePartType => ({
|
||||
type: 'step-finish',
|
||||
messageID,
|
||||
sessionID: 'test-session',
|
||||
cost: 0.01,
|
||||
tokens: {
|
||||
input: 100,
|
||||
output: 50,
|
||||
cache: { read: 0, write: 0 },
|
||||
},
|
||||
time: {
|
||||
start: Date.now(),
|
||||
end: Date.now() + 100,
|
||||
},
|
||||
})
|
||||
|
||||
const TEST_MESSAGE_ID = 'message-1'
|
||||
const TEST_CONTENT = 'Test message content'
|
||||
|
||||
it('renders TTS button for step-finish part with message text', () => {
|
||||
setup()
|
||||
const part = createStepFinishPart(TEST_MESSAGE_ID)
|
||||
|
||||
render(
|
||||
<MessagePart
|
||||
part={part}
|
||||
messageTextContent={TEST_CONTENT}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByRole('button')).toBeInTheDocument()
|
||||
expect(screen.getByTitle('Read aloud')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not render TTS button when message text is empty', () => {
|
||||
setup()
|
||||
const part = createStepFinishPart(TEST_MESSAGE_ID)
|
||||
|
||||
render(
|
||||
<MessagePart
|
||||
part={part}
|
||||
messageTextContent=""
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not render TTS button when TTS is disabled', () => {
|
||||
setup({ ttsEnabled: false })
|
||||
const part = createStepFinishPart(TEST_MESSAGE_ID)
|
||||
|
||||
render(
|
||||
<MessagePart
|
||||
part={part}
|
||||
messageTextContent={TEST_CONTENT}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls speakMessage with message id on tap when idle', () => {
|
||||
setup()
|
||||
const part = createStepFinishPart(TEST_MESSAGE_ID)
|
||||
|
||||
render(
|
||||
<MessagePart
|
||||
part={part}
|
||||
messageTextContent={TEST_CONTENT}
|
||||
/>
|
||||
)
|
||||
|
||||
const button = screen.getByRole('button')
|
||||
fireEvent.click(button)
|
||||
|
||||
expect(mockSpeakMessage).toHaveBeenCalledTimes(1)
|
||||
expect(mockSpeakMessage).toHaveBeenCalledWith(TEST_MESSAGE_ID, TEST_CONTENT)
|
||||
})
|
||||
|
||||
it('calls stop on tap when this message is active', () => {
|
||||
const mockTTSForTest: MockTTSReturn = {
|
||||
speakMessage: mockSpeakMessage,
|
||||
stop: mockStop,
|
||||
activeMessageId: TEST_MESSAGE_ID,
|
||||
isPlaying: true,
|
||||
isLoading: false,
|
||||
isEnabled: true,
|
||||
}
|
||||
mocks.useTTS.mockReturnValue(mockTTSForTest)
|
||||
|
||||
const part = createStepFinishPart(TEST_MESSAGE_ID)
|
||||
|
||||
render(
|
||||
<MessagePart
|
||||
part={part}
|
||||
messageTextContent={TEST_CONTENT}
|
||||
/>
|
||||
)
|
||||
|
||||
const button = screen.getByRole('button')
|
||||
fireEvent.click(button)
|
||||
|
||||
expect(mockStop).toHaveBeenCalledTimes(1)
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows active state when this message is playing', () => {
|
||||
setup({ activeMessageId: TEST_MESSAGE_ID, isPlaying: true })
|
||||
const part = createStepFinishPart(TEST_MESSAGE_ID)
|
||||
|
||||
render(
|
||||
<MessagePart
|
||||
part={part}
|
||||
messageTextContent={TEST_CONTENT}
|
||||
/>
|
||||
)
|
||||
|
||||
const button = screen.getByRole('button')
|
||||
expect(button).toHaveClass('bg-red-500/20')
|
||||
expect(button).toHaveClass('text-red-500')
|
||||
})
|
||||
|
||||
it('shows active state when this message is loading', () => {
|
||||
setup({ activeMessageId: TEST_MESSAGE_ID, isLoading: true })
|
||||
const part = createStepFinishPart(TEST_MESSAGE_ID)
|
||||
|
||||
render(
|
||||
<MessagePart
|
||||
part={part}
|
||||
messageTextContent={TEST_CONTENT}
|
||||
/>
|
||||
)
|
||||
|
||||
const button = screen.getByRole('button')
|
||||
expect(button).toHaveClass('bg-red-500/20')
|
||||
})
|
||||
|
||||
it('does not show active state when different message is playing', () => {
|
||||
setup({ activeMessageId: 'other-message', isPlaying: true })
|
||||
const part = createStepFinishPart(TEST_MESSAGE_ID)
|
||||
|
||||
render(
|
||||
<MessagePart
|
||||
part={part}
|
||||
messageTextContent={TEST_CONTENT}
|
||||
/>
|
||||
)
|
||||
|
||||
const button = screen.getByRole('button')
|
||||
expect(button).not.toHaveClass('bg-red-500/20')
|
||||
})
|
||||
|
||||
it('tracks playback by message id not text', () => {
|
||||
setup({ activeMessageId: TEST_MESSAGE_ID, isPlaying: true })
|
||||
const part1 = createStepFinishPart(TEST_MESSAGE_ID)
|
||||
const part2 = createStepFinishPart('message-2')
|
||||
|
||||
const { rerender } = render(
|
||||
<MessagePart
|
||||
part={part1}
|
||||
messageTextContent={TEST_CONTENT}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByRole('button')).toHaveClass('bg-red-500/20')
|
||||
|
||||
rerender(
|
||||
<MessagePart
|
||||
part={part2}
|
||||
messageTextContent={TEST_CONTENT}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByRole('button')).not.toHaveClass('bg-red-500/20')
|
||||
})
|
||||
})
|
||||
@@ -59,24 +59,25 @@ function getCopyableContent(part: Part, allParts?: Part[]): string {
|
||||
}
|
||||
|
||||
interface TTSButtonProps {
|
||||
messageId: string
|
||||
content: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
function TTSButton({ content, className = "" }: TTSButtonProps) {
|
||||
const { speak, stop, isEnabled, isPlaying, isLoading, originalText } = useTTS()
|
||||
function TTSButton({ messageId, content, className = "" }: TTSButtonProps) {
|
||||
const { speakMessage, stop, isEnabled, isPlaying, isLoading, activeMessageId } = useTTS()
|
||||
|
||||
if (!isEnabled || !content.trim()) {
|
||||
return null
|
||||
}
|
||||
|
||||
const isThisPlaying = (isPlaying || isLoading) && originalText === content
|
||||
const isThisPlaying = (isPlaying || isLoading) && activeMessageId === messageId
|
||||
|
||||
const handleClick = () => {
|
||||
if (isThisPlaying) {
|
||||
stop()
|
||||
} else {
|
||||
speak(content)
|
||||
speakMessage(messageId, content)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,7 +86,7 @@ function TTSButton({ content, className = "" }: TTSButtonProps) {
|
||||
onClick={handleClick}
|
||||
className={`p-1.5 rounded ${isThisPlaying ? 'bg-red-500/20 text-red-500 hover:bg-red-500/30' : 'bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground'} ${className}`}
|
||||
title={isThisPlaying ? "Stop playback" : "Read aloud"}
|
||||
disabled={isLoading && originalText !== content}
|
||||
disabled={isLoading && !isThisPlaying}
|
||||
>
|
||||
{isLoading && isThisPlaying ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
@@ -146,7 +147,7 @@ export const MessagePart = memo(function MessagePart({ part, role, allParts, par
|
||||
<div className="text-xs text-muted-foreground my-1 flex items-center gap-2">
|
||||
{costText}
|
||||
<CopyButton content={copyableContent} title="Copy step complete" />
|
||||
{messageTextContent && <TTSButton content={messageTextContent} />}
|
||||
{messageTextContent && part.messageID && <TTSButton messageId={part.messageID} content={messageTextContent} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, memo, type KeyboardEvent } from 'react'
|
||||
import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, memo, useCallback, type KeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react'
|
||||
import { useSendPrompt, useAbortSession, useSendShell, useAgents } from '@/hooks/useOpenCode'
|
||||
import { useCommands } from '@/hooks/useCommands'
|
||||
import { useCommandHandler } from '@/hooks/useCommandHandler'
|
||||
@@ -44,6 +44,8 @@ const revokeBlobUrls = (attachments: ImageAttachment[]) => {
|
||||
|
||||
const ACCEPTED_FILE_TYPES = [...ACCEPTED_IMAGE_TYPES, "application/pdf"]
|
||||
|
||||
const VOICE_SEND_SWIPE_THRESHOLD = 48
|
||||
|
||||
|
||||
type CommandType = components['schemas']['Command']
|
||||
|
||||
@@ -102,7 +104,16 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
const [localMode, setLocalMode] = useState<string | null>(null)
|
||||
const [isFocused, setIsFocused] = useState(false)
|
||||
const [isTogglingRecording, setIsTogglingRecording] = useState(false)
|
||||
const [isVoiceHoldActive, setIsVoiceHoldActive] = useState(false)
|
||||
const [isVoiceSwipeArmed, setIsVoiceSwipeArmed] = useState(false)
|
||||
const [isVoiceAutoSendPending, setIsVoiceAutoSendPending] = useState(false)
|
||||
const lastAddedTranscriptRef = useRef('')
|
||||
const voiceHoldStartYRef = useRef<number | null>(null)
|
||||
const voiceSwipeArmedRef = useRef(false)
|
||||
const voicePendingReleaseRef = useRef(false)
|
||||
const pendingVoiceAutoSubmitRef = useRef(false)
|
||||
const ignoreVoiceClickUntilRef = useRef(0)
|
||||
const handleSubmitRef = useRef<() => void>(() => {})
|
||||
|
||||
const {
|
||||
isRecording,
|
||||
@@ -119,6 +130,16 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const resetVoiceGestureState = useCallback(() => {
|
||||
voiceHoldStartYRef.current = null
|
||||
voiceSwipeArmedRef.current = false
|
||||
voicePendingReleaseRef.current = false
|
||||
pendingVoiceAutoSubmitRef.current = false
|
||||
ignoreVoiceClickUntilRef.current = 0
|
||||
setIsVoiceHoldActive(false)
|
||||
setIsVoiceSwipeArmed(false)
|
||||
setIsVoiceAutoSendPending(false)
|
||||
}, [])
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
setPromptValue: (value: string) => {
|
||||
@@ -131,6 +152,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
revokeBlobUrls(imageAttachments)
|
||||
setImageAttachments([])
|
||||
setSelectedAgent(null)
|
||||
resetVoiceGestureState()
|
||||
if (isRecording) {
|
||||
abortRecording()
|
||||
} else {
|
||||
@@ -141,7 +163,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
triggerFileUpload: () => {
|
||||
fileInputRef.current?.click()
|
||||
}
|
||||
}), [imageAttachments, clearSTT, isRecording, abortRecording])
|
||||
}), [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState])
|
||||
const sendPrompt = useSendPrompt(opcodeUrl, directory)
|
||||
const sendShell = useSendShell(opcodeUrl, directory)
|
||||
const abortSession = useAbortSession(opcodeUrl, directory, sessionID, repoId)
|
||||
@@ -197,6 +219,9 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
if (disabled) return
|
||||
if (!prompt.trim() && imageAttachments.length === 0) return
|
||||
|
||||
pendingVoiceAutoSubmitRef.current = false
|
||||
setIsVoiceAutoSendPending(false)
|
||||
|
||||
if (hasActiveStream) {
|
||||
const parts = parsePromptToParts(prompt, attachedFiles, imageAttachments)
|
||||
const agentUsed = selectedAgent || currentMode
|
||||
@@ -273,6 +298,8 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
clearSTT()
|
||||
}
|
||||
|
||||
handleSubmitRef.current = handleSubmit
|
||||
|
||||
const handleStop = () => {
|
||||
abortSession.mutate(sessionID)
|
||||
}
|
||||
@@ -381,6 +408,10 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
}
|
||||
|
||||
const handleVoiceToggle = async () => {
|
||||
pendingVoiceAutoSubmitRef.current = false
|
||||
setIsVoiceAutoSendPending(false)
|
||||
setIsVoiceSwipeArmed(false)
|
||||
voiceSwipeArmedRef.current = false
|
||||
if (isRecording) {
|
||||
stopRecording()
|
||||
} else {
|
||||
@@ -388,7 +419,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
try {
|
||||
await startRecording()
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.blur()
|
||||
textareaRef.current?.blur()
|
||||
}
|
||||
} catch {
|
||||
setIsTogglingRecording(false)
|
||||
@@ -396,6 +427,101 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
}
|
||||
}
|
||||
|
||||
const handleVoiceClick = async () => {
|
||||
if (Date.now() < ignoreVoiceClickUntilRef.current) {
|
||||
return
|
||||
}
|
||||
|
||||
await handleVoiceToggle()
|
||||
}
|
||||
|
||||
const handleVoiceHoldStart = async () => {
|
||||
if (!isRecording && !isProcessing) {
|
||||
pendingVoiceAutoSubmitRef.current = false
|
||||
setIsVoiceAutoSendPending(false)
|
||||
setIsTogglingRecording(true)
|
||||
try {
|
||||
if (typeof navigator !== 'undefined' && navigator.vibrate) {
|
||||
navigator.vibrate(10)
|
||||
}
|
||||
await startRecording()
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current?.blur()
|
||||
}
|
||||
} catch {
|
||||
setIsTogglingRecording(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleVoiceHoldEnd = (shouldAutoSend: boolean) => {
|
||||
setIsVoiceHoldActive(false)
|
||||
setIsVoiceSwipeArmed(false)
|
||||
voiceHoldStartYRef.current = null
|
||||
voiceSwipeArmedRef.current = false
|
||||
pendingVoiceAutoSubmitRef.current = shouldAutoSend
|
||||
setIsVoiceAutoSendPending(shouldAutoSend)
|
||||
|
||||
if (isRecording) {
|
||||
if (typeof navigator !== 'undefined' && navigator.vibrate) {
|
||||
navigator.vibrate([10, 20, 10])
|
||||
}
|
||||
stopRecording()
|
||||
} else if (isTogglingRecording) {
|
||||
voicePendingReleaseRef.current = true
|
||||
}
|
||||
}
|
||||
|
||||
const handleVoicePointerDown = async (event: ReactPointerEvent<HTMLButtonElement>) => {
|
||||
if ((event.pointerType === 'mouse' && event.button !== 0) || disabled || isProcessing) {
|
||||
return
|
||||
}
|
||||
|
||||
ignoreVoiceClickUntilRef.current = Date.now() + 400
|
||||
voiceHoldStartYRef.current = event.clientY
|
||||
voiceSwipeArmedRef.current = false
|
||||
voicePendingReleaseRef.current = false
|
||||
pendingVoiceAutoSubmitRef.current = false
|
||||
setIsVoiceHoldActive(true)
|
||||
setIsVoiceSwipeArmed(false)
|
||||
setIsVoiceAutoSendPending(false)
|
||||
|
||||
if (event.currentTarget.setPointerCapture) {
|
||||
event.currentTarget.setPointerCapture(event.pointerId)
|
||||
}
|
||||
|
||||
await handleVoiceHoldStart()
|
||||
}
|
||||
|
||||
const handleVoicePointerMove = (event: ReactPointerEvent<HTMLButtonElement>) => {
|
||||
if (!isVoiceHoldActive || voiceHoldStartYRef.current === null) {
|
||||
return
|
||||
}
|
||||
|
||||
const nextIsSwipeArmed = voiceHoldStartYRef.current - event.clientY >= VOICE_SEND_SWIPE_THRESHOLD
|
||||
|
||||
if (nextIsSwipeArmed !== voiceSwipeArmedRef.current) {
|
||||
voiceSwipeArmedRef.current = nextIsSwipeArmed
|
||||
setIsVoiceSwipeArmed(nextIsSwipeArmed)
|
||||
|
||||
if (nextIsSwipeArmed && typeof navigator !== 'undefined' && navigator.vibrate) {
|
||||
navigator.vibrate(10)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleVoicePointerEnd = (event: ReactPointerEvent<HTMLButtonElement>, canceled = false) => {
|
||||
if (event.currentTarget.releasePointerCapture && event.currentTarget.hasPointerCapture(event.pointerId)) {
|
||||
event.currentTarget.releasePointerCapture(event.pointerId)
|
||||
}
|
||||
|
||||
if (!isVoiceHoldActive && !isTogglingRecording && !isRecording) {
|
||||
return
|
||||
}
|
||||
|
||||
handleVoiceHoldEnd(canceled ? false : voiceSwipeArmedRef.current)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const textToUse = transcript || interimTranscript
|
||||
if (!isRecording && textToUse && textToUse !== 'Processing...' && textToUse !== 'Recording...') {
|
||||
@@ -407,7 +533,10 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
setPrompt(prev => `${prev} ${trimmedTranscript}`)
|
||||
}
|
||||
lastAddedTranscriptRef.current = trimmedTranscript
|
||||
textareaRef.current?.focus()
|
||||
|
||||
if (!pendingVoiceAutoSubmitRef.current) {
|
||||
textareaRef.current?.focus()
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [isRecording, interimTranscript, transcript, prompt])
|
||||
@@ -424,6 +553,35 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
}
|
||||
}, [isTogglingRecording])
|
||||
|
||||
useEffect(() => {
|
||||
if (isRecording && voicePendingReleaseRef.current) {
|
||||
voicePendingReleaseRef.current = false
|
||||
|
||||
if (typeof navigator !== 'undefined' && navigator.vibrate) {
|
||||
navigator.vibrate([10, 20, 10])
|
||||
}
|
||||
|
||||
stopRecording()
|
||||
}
|
||||
}, [isRecording, stopRecording])
|
||||
|
||||
useEffect(() => {
|
||||
if (!pendingVoiceAutoSubmitRef.current || isRecording || isProcessing || !prompt.trim()) {
|
||||
return
|
||||
}
|
||||
|
||||
pendingVoiceAutoSubmitRef.current = false
|
||||
setIsVoiceAutoSendPending(false)
|
||||
handleSubmitRef.current()
|
||||
}, [prompt, isRecording, isProcessing])
|
||||
|
||||
useEffect(() => {
|
||||
if (pendingVoiceAutoSubmitRef.current && !isRecording && !isProcessing && !transcript.trim() && !interimTranscript.trim()) {
|
||||
pendingVoiceAutoSubmitRef.current = false
|
||||
setIsVoiceAutoSendPending(false)
|
||||
}
|
||||
}, [isRecording, isProcessing, transcript, interimTranscript])
|
||||
|
||||
const addImageAttachment = (file: File) => {
|
||||
const generateId = () => {
|
||||
if (typeof crypto !== 'undefined' && crypto.randomUUID) {
|
||||
@@ -680,6 +838,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
setPrompt('')
|
||||
revokeBlobUrls(imageAttachments)
|
||||
setImageAttachments([])
|
||||
resetVoiceGestureState()
|
||||
clearSTT()
|
||||
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 't') {
|
||||
e.preventDefault()
|
||||
@@ -768,6 +927,47 @@ const { model, modelString, setModel: setStoredModel } = useModelSelection(opcod
|
||||
const { hasVariants, currentVariant, cycleVariant } = useVariants(opcodeUrl, directory)
|
||||
const showStopButton = hasActiveStream
|
||||
const hideSecondaryButtons = isMobile && hasActiveStream
|
||||
const showVoiceFeedback = isVoiceHoldActive || isRecording || isTogglingRecording || isProcessing || isVoiceAutoSendPending
|
||||
const voiceFeedbackLabel = isProcessing
|
||||
? isVoiceAutoSendPending
|
||||
? 'Transcribing and sending...'
|
||||
: 'Transcribing...'
|
||||
: isRecording
|
||||
? isVoiceSwipeArmed
|
||||
? 'Release to send'
|
||||
: 'Recording... swipe up to send'
|
||||
: isTogglingRecording || isVoiceHoldActive
|
||||
? 'Starting microphone...'
|
||||
: null
|
||||
const voiceFeedbackToneClasses = isVoiceSwipeArmed || isVoiceAutoSendPending
|
||||
? 'border-blue-400/60 bg-blue-500/90 text-white shadow-blue-500/30'
|
||||
: 'border-red-500/60 bg-red-600/90 text-white shadow-red-500/30'
|
||||
const voiceFeedbackGlowClasses = isVoiceSwipeArmed || isVoiceAutoSendPending ? 'bg-blue-500/30' : 'bg-red-500/25'
|
||||
const voiceButtonTitle = isProcessing
|
||||
? 'Transcribing speech'
|
||||
: isRecording
|
||||
? isVoiceSwipeArmed
|
||||
? 'Release to send'
|
||||
: 'Release to transcribe'
|
||||
: 'Hold to speak'
|
||||
|
||||
const renderVoiceStatusOverlay = () => {
|
||||
if (!showVoiceFeedback || !voiceFeedbackLabel) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={`pointer-events-none absolute -inset-4 rounded-2xl blur-xl ${voiceFeedbackGlowClasses}`} />
|
||||
<div
|
||||
aria-live="polite"
|
||||
className={`pointer-events-none absolute bottom-full right-0 z-10 mb-3 w-[200px] rounded-xl border px-3 py-2 text-center text-xs font-medium leading-tight shadow-lg backdrop-blur-md ${voiceFeedbackToneClasses}`}
|
||||
>
|
||||
{voiceFeedbackLabel}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -784,6 +984,7 @@ const { model, modelString, setModel: setStoredModel } = useModelSelection(opcod
|
||||
abortRecording()
|
||||
}
|
||||
clearSTT()
|
||||
resetVoiceGestureState()
|
||||
lastAddedTranscriptRef.current = ''
|
||||
setIsTogglingRecording(false)
|
||||
setLocalMode(null)
|
||||
@@ -930,49 +1131,63 @@ return (
|
||||
<Upload className="w-5 h-5" />
|
||||
</button>
|
||||
{sttEnabled && sttSupported && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleVoiceToggle}
|
||||
disabled={disabled || isProcessing}
|
||||
className={`hidden md:flex p-2 rounded-lg transition-all duration-200 active:scale-95 hover:scale-105 shadow-md border items-center justify-center ${
|
||||
isRecording
|
||||
? 'bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-destructive-foreground border-red-500/60 animate-pulse'
|
||||
: 'bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border'
|
||||
}`}
|
||||
title={isRecording ? 'Stop recording' : 'Voice input'}
|
||||
>
|
||||
{isTogglingRecording && !isRecording ? (
|
||||
<div className="w-5 h-5 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
|
||||
) : isProcessing && !isRecording ? (
|
||||
<div className="w-5 h-5 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
|
||||
) : isRecording ? (
|
||||
<MicOff className="w-5 h-5" />
|
||||
) : (
|
||||
<Mic className="w-5 h-5" />
|
||||
)}
|
||||
</button>
|
||||
<div className="relative hidden md:block">
|
||||
{renderVoiceStatusOverlay()}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleVoiceClick}
|
||||
onPointerDown={handleVoicePointerDown}
|
||||
onPointerMove={handleVoicePointerMove}
|
||||
onPointerUp={(event) => handleVoicePointerEnd(event)}
|
||||
onPointerCancel={(event) => handleVoicePointerEnd(event, true)}
|
||||
disabled={disabled || isProcessing}
|
||||
className={`hidden md:flex p-2 rounded-lg transition-all duration-200 active:scale-95 hover:scale-105 shadow-md border items-center justify-center touch-none select-none ${
|
||||
isRecording || isTogglingRecording || (isProcessing && !isRecording)
|
||||
? 'bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-destructive-foreground border-red-500/60 animate-pulse'
|
||||
: 'bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border'
|
||||
}`}
|
||||
title={voiceButtonTitle}
|
||||
>
|
||||
{isTogglingRecording && !isRecording ? (
|
||||
<div className="w-5 h-5 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
|
||||
) : isProcessing && !isRecording ? (
|
||||
<div className="w-5 h-5 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
|
||||
) : isRecording ? (
|
||||
<MicOff className="w-5 h-5" />
|
||||
) : (
|
||||
<Mic className="w-5 h-5" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{isMobile && !showScrollButton && sttEnabled && sttSupported && !hasPendingPermissionForSession && (
|
||||
<button
|
||||
onClick={handleVoiceToggle}
|
||||
disabled={disabled || isProcessing}
|
||||
className={`px-4 py-2 rounded-lg transition-all duration-200 active:scale-95 flex items-center justify-center min-w-[52px] border ${
|
||||
isRecording || isTogglingRecording || (isProcessing && !isRecording)
|
||||
? 'bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-destructive-foreground border-red-500/60 shadow-lg shadow-red-500/30 animate-pulse'
|
||||
: 'bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border'
|
||||
}`}
|
||||
title={isRecording ? 'Stop recording' : 'Voice input'}
|
||||
>
|
||||
{isTogglingRecording && !isRecording ? (
|
||||
<div className="w-5 h-5 animate-spin rounded-full border-2 border-white border-t-transparent" />
|
||||
) : isProcessing && !isRecording ? (
|
||||
<div className="w-5 h-5 animate-spin rounded-full border-2 border-white border-t-transparent" />
|
||||
) : isRecording ? (
|
||||
<MicOff className="w-5 h-5" />
|
||||
) : (
|
||||
<Mic className="w-5 h-5" />
|
||||
)}
|
||||
</button>
|
||||
<div className="relative">
|
||||
{renderVoiceStatusOverlay()}
|
||||
<button
|
||||
onClick={handleVoiceClick}
|
||||
onPointerDown={handleVoicePointerDown}
|
||||
onPointerMove={handleVoicePointerMove}
|
||||
onPointerUp={(event) => handleVoicePointerEnd(event)}
|
||||
onPointerCancel={(event) => handleVoicePointerEnd(event, true)}
|
||||
disabled={disabled || isProcessing}
|
||||
className={`px-4 py-2 rounded-lg transition-all duration-150 flex items-center justify-center min-w-[52px] border touch-none select-none ${
|
||||
isRecording || isTogglingRecording || (isProcessing && !isRecording)
|
||||
? 'bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-destructive-foreground border-red-500/60 shadow-lg shadow-red-500/30 animate-pulse'
|
||||
: 'bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border active:bg-muted-foreground/30 active:scale-95'
|
||||
}`}
|
||||
title={voiceButtonTitle}
|
||||
>
|
||||
{isTogglingRecording && !isRecording ? (
|
||||
<div className="w-5 h-5 animate-spin rounded-full border-2 border-white border-t-transparent" />
|
||||
) : isProcessing && !isRecording ? (
|
||||
<div className="w-5 h-5 animate-spin rounded-full border-2 border-white border-t-transparent" />
|
||||
) : isRecording ? (
|
||||
<MicOff className="w-5 h-5" />
|
||||
) : (
|
||||
<Mic className="w-5 h-5" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
data-submit-prompt
|
||||
|
||||
@@ -31,6 +31,7 @@ function isKokoroStyleVoice(voice: string): boolean {
|
||||
const ttsFormSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
provider: z.enum(['external', 'builtin']),
|
||||
autoPlay: z.boolean(),
|
||||
endpoint: z.string(),
|
||||
apiKey: z.string(),
|
||||
voice: z.string(),
|
||||
@@ -175,6 +176,7 @@ export function TTSSettings() {
|
||||
reset({
|
||||
enabled: preferences.tts.enabled ?? DEFAULT_TTS_CONFIG.enabled,
|
||||
provider: preferences.tts.provider ?? DEFAULT_TTS_CONFIG.provider,
|
||||
autoPlay: preferences.tts.autoPlay ?? DEFAULT_TTS_CONFIG.autoPlay,
|
||||
endpoint: preferences.tts.endpoint ?? DEFAULT_TTS_CONFIG.endpoint,
|
||||
apiKey: preferences.tts.apiKey ?? DEFAULT_TTS_CONFIG.apiKey,
|
||||
voice: preferences.tts.voice ?? DEFAULT_TTS_CONFIG.voice,
|
||||
@@ -288,6 +290,29 @@ export function TTSSettings() {
|
||||
)}
|
||||
/>
|
||||
|
||||
{watchEnabled && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="autoPlay"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<FormLabel className="text-base">Auto-play replies</FormLabel>
|
||||
<FormDescription>
|
||||
Automatically speak new assistant replies when they complete.
|
||||
</FormDescription>
|
||||
</div>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{watchEnabled && (
|
||||
<>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
|
||||
@@ -33,6 +33,7 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [currentText, setCurrentText] = useState<string | null>(null)
|
||||
const [originalText, setOriginalText] = useState<string | null>(null)
|
||||
const [activeMessageId, setActiveMessageId] = useState<string | null>(null)
|
||||
|
||||
const abortControllerRef = useRef<AbortController | null>(null)
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null)
|
||||
@@ -97,6 +98,7 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
setState('idle')
|
||||
setCurrentText(null)
|
||||
setOriginalText(null)
|
||||
setActiveMessageId(null)
|
||||
setError(null)
|
||||
}, [cleanup])
|
||||
|
||||
@@ -181,6 +183,7 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
if (!stoppedRef.current) {
|
||||
setState('idle')
|
||||
setCurrentText(null)
|
||||
setActiveMessageId(null)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -233,8 +236,8 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
}
|
||||
}, [synthesizeExternal, fetchNextChunk])
|
||||
|
||||
// Builtin Web Speech synthesis - takes explicit config
|
||||
const speakBuiltinWithConfig = useCallback(async (text: string, config: TTSConfig): Promise<boolean> => {
|
||||
// Builtin Web Speech synthesis - takes explicit config and optional messageId
|
||||
const speakBuiltinWithConfig = useCallback(async (text: string, config: TTSConfig, messageId: string | null = null): Promise<boolean> => {
|
||||
if (!isWebSpeechSupported()) {
|
||||
setError('Web Speech API not supported in this browser')
|
||||
setState('error')
|
||||
@@ -261,6 +264,11 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
|
||||
setOriginalText(text)
|
||||
setCurrentText(sanitizedText)
|
||||
if (messageId) {
|
||||
setActiveMessageId(messageId)
|
||||
} else {
|
||||
setActiveMessageId(null)
|
||||
}
|
||||
setState('loading')
|
||||
|
||||
const synth = getSynthesizer()
|
||||
@@ -274,6 +282,7 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
if (!stoppedRef.current) {
|
||||
setState('idle')
|
||||
setCurrentText(null)
|
||||
setActiveMessageId(null)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -303,8 +312,30 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
}
|
||||
}, [stop, getSynthesizer])
|
||||
|
||||
// Config-aware speak function - takes explicit config
|
||||
const speakWithConfig = useCallback(async (text: string, config: TTSConfig): Promise<boolean> => {
|
||||
// Internal helper to start external TTS playback
|
||||
const startExternalPlayback = useCallback((sanitizedText: string, original: string, messageId: string | null): boolean => {
|
||||
stop()
|
||||
stoppedRef.current = false
|
||||
setError(null)
|
||||
|
||||
setOriginalText(original)
|
||||
setCurrentText(sanitizedText)
|
||||
if (messageId) {
|
||||
setActiveMessageId(messageId)
|
||||
} else {
|
||||
setActiveMessageId(null)
|
||||
}
|
||||
|
||||
abortControllerRef.current = new AbortController()
|
||||
chunksRef.current = splitIntoChunks(sanitizedText)
|
||||
|
||||
playChunk(0)
|
||||
|
||||
return true
|
||||
}, [stop, playChunk])
|
||||
|
||||
// Config-aware speak function - takes explicit config and optional messageId
|
||||
const speakWithConfig = useCallback(async (text: string, config: TTSConfig, messageId: string | null = null): Promise<boolean> => {
|
||||
if (!config.enabled) {
|
||||
setError('TTS is not enabled')
|
||||
setState('error')
|
||||
@@ -319,7 +350,7 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
setState('error')
|
||||
return false
|
||||
}
|
||||
return speakBuiltinWithConfig(text, config)
|
||||
return speakBuiltinWithConfig(text, config, messageId)
|
||||
} else {
|
||||
if (!config.apiKey) {
|
||||
setError('API key not configured')
|
||||
@@ -341,21 +372,30 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
return false
|
||||
}
|
||||
|
||||
stop()
|
||||
stoppedRef.current = false
|
||||
setError(null)
|
||||
|
||||
setOriginalText(text)
|
||||
setCurrentText(sanitizedText)
|
||||
|
||||
abortControllerRef.current = new AbortController()
|
||||
chunksRef.current = splitIntoChunks(sanitizedText)
|
||||
|
||||
playChunk(0)
|
||||
|
||||
return true
|
||||
return startExternalPlayback(sanitizedText, text, messageId)
|
||||
}
|
||||
}, [speakBuiltinWithConfig, stop, playChunk])
|
||||
}, [speakBuiltinWithConfig, startExternalPlayback])
|
||||
|
||||
// Message-aware speak function - tracks active message id
|
||||
const speakMessage = useCallback(async (messageId: string, text: string): Promise<boolean> => {
|
||||
if (!ttsConfig) {
|
||||
setError('TTS is not configured')
|
||||
setState('error')
|
||||
return false
|
||||
}
|
||||
|
||||
const config: TTSConfig = {
|
||||
enabled: ttsConfig.enabled ?? false,
|
||||
provider: ttsConfig.provider ?? 'external',
|
||||
endpoint: ttsConfig.endpoint ?? '',
|
||||
apiKey: ttsConfig.apiKey ?? '',
|
||||
voice: ttsConfig.voice ?? '',
|
||||
model: ttsConfig.model ?? '',
|
||||
speed: ttsConfig.speed ?? 1.0,
|
||||
}
|
||||
|
||||
return speakWithConfig(text, config, messageId)
|
||||
}, [ttsConfig, speakWithConfig])
|
||||
|
||||
// Main speak function - uses stored preferences
|
||||
const speak = useCallback(async (text: string): Promise<boolean> => {
|
||||
@@ -381,11 +421,13 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
const value = {
|
||||
speak,
|
||||
speakWithConfig,
|
||||
speakMessage,
|
||||
stop,
|
||||
state,
|
||||
error,
|
||||
currentText,
|
||||
originalText,
|
||||
activeMessageId,
|
||||
isEnabled,
|
||||
isPlaying: state === 'playing',
|
||||
isLoading: state === 'loading',
|
||||
|
||||
@@ -15,11 +15,13 @@ export interface TTSConfig {
|
||||
export interface TTSContextValue {
|
||||
speak: (text: string) => Promise<boolean>
|
||||
speakWithConfig: (text: string, config: TTSConfig) => Promise<boolean>
|
||||
speakMessage: (messageId: string, text: string) => Promise<boolean>
|
||||
stop: () => void
|
||||
state: TTSState
|
||||
error: string | null
|
||||
currentText: string | null
|
||||
originalText: string | null
|
||||
activeMessageId: string | null
|
||||
isEnabled: boolean
|
||||
isPlaying: boolean
|
||||
isLoading: boolean
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import type { MessageWithParts } from '../../api/types'
|
||||
import type { TTSConfig } from '@opencode-manager/shared'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useTTS: vi.fn(),
|
||||
useSettings: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../useTTS', () => ({
|
||||
useTTS: mocks.useTTS,
|
||||
}))
|
||||
|
||||
vi.mock('../useSettings', () => ({
|
||||
useSettings: mocks.useSettings,
|
||||
}))
|
||||
|
||||
interface MockTTSReturn {
|
||||
speak: ReturnType<typeof vi.fn>
|
||||
speakMessage: ReturnType<typeof vi.fn>
|
||||
stop: ReturnType<typeof vi.fn>
|
||||
isEnabled: boolean
|
||||
isPlaying: boolean
|
||||
isLoading: boolean
|
||||
originalText: string | null
|
||||
activeMessageId: string | null
|
||||
}
|
||||
|
||||
import { useAutoPlayLastResponse } from '../useAutoPlayLastResponse'
|
||||
|
||||
const createMessage = (id: string, completed?: number): MessageWithParts => ({
|
||||
info: {
|
||||
id,
|
||||
sessionID: 'test-session',
|
||||
role: 'assistant',
|
||||
time: {
|
||||
created: Date.now(),
|
||||
...(completed ? { completed } : {}),
|
||||
},
|
||||
parentID: 'parent-1',
|
||||
modelID: 'gpt-4',
|
||||
providerID: 'openai',
|
||||
mode: 'build',
|
||||
agent: 'default',
|
||||
path: {
|
||||
cwd: '/test',
|
||||
root: '/test',
|
||||
},
|
||||
cost: 0.01,
|
||||
tokens: {
|
||||
input: 100,
|
||||
output: 50,
|
||||
reasoning: 0,
|
||||
cache: { read: 0, write: 0 },
|
||||
},
|
||||
},
|
||||
parts: [
|
||||
{
|
||||
id: 'part-1',
|
||||
sessionID: 'test-session',
|
||||
messageID: id,
|
||||
type: 'text',
|
||||
text: 'Test message text',
|
||||
time: {
|
||||
start: Date.now(),
|
||||
end: Date.now() + 100,
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
describe('useAutoPlayLastResponse', () => {
|
||||
const mockSpeak = vi.fn()
|
||||
const mockSpeakMessage = vi.fn()
|
||||
const mockStop = vi.fn()
|
||||
const mockUpdateSettings = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockSpeak.mockClear()
|
||||
mockSpeakMessage.mockClear()
|
||||
mockStop.mockClear()
|
||||
mockUpdateSettings.mockClear()
|
||||
})
|
||||
|
||||
const setup = (options: {
|
||||
ttsEnabled?: boolean
|
||||
autoPlay?: boolean
|
||||
} = {}) => {
|
||||
const mockTTS: MockTTSReturn = {
|
||||
speak: mockSpeak,
|
||||
speakMessage: mockSpeakMessage,
|
||||
stop: mockStop,
|
||||
isEnabled: options.ttsEnabled ?? true,
|
||||
isPlaying: false,
|
||||
isLoading: false,
|
||||
originalText: null,
|
||||
activeMessageId: null,
|
||||
}
|
||||
mocks.useTTS.mockReturnValue(mockTTS)
|
||||
|
||||
mocks.useSettings.mockReturnValue({
|
||||
preferences: {
|
||||
tts: {
|
||||
enabled: options.ttsEnabled ?? true,
|
||||
autoPlay: options.autoPlay ?? true,
|
||||
provider: 'external',
|
||||
endpoint: 'https://api.openai.com',
|
||||
apiKey: 'test-key',
|
||||
voice: 'alloy',
|
||||
model: 'tts-1',
|
||||
speed: 1.0,
|
||||
} as TTSConfig,
|
||||
},
|
||||
updateSettings: mockUpdateSettings,
|
||||
})
|
||||
}
|
||||
|
||||
it('does NOT call speakMessage when tts.enabled is false', () => {
|
||||
setup({ ttsEnabled: false, autoPlay: true })
|
||||
|
||||
const message = createMessage('1', Date.now())
|
||||
renderHook(() =>
|
||||
useAutoPlayLastResponse({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: message,
|
||||
lastAssistantText: 'Test text',
|
||||
hasActiveStream: false,
|
||||
})
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does NOT call speakMessage when tts.autoPlay is false', () => {
|
||||
setup({ ttsEnabled: true, autoPlay: false })
|
||||
|
||||
const message = createMessage('1', Date.now())
|
||||
renderHook(() =>
|
||||
useAutoPlayLastResponse({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: message,
|
||||
lastAssistantText: 'Test text',
|
||||
hasActiveStream: false,
|
||||
})
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does NOT call speakMessage on mount when last message was already time.completed', () => {
|
||||
setup()
|
||||
|
||||
const message = createMessage('1', Date.now() - 1000)
|
||||
renderHook(() =>
|
||||
useAutoPlayLastResponse({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: message,
|
||||
lastAssistantText: 'Test text',
|
||||
hasActiveStream: false,
|
||||
})
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('CALLS speakMessage exactly once when lastAssistantMessage transitions from incomplete to completed', () => {
|
||||
setup()
|
||||
|
||||
const incompleteMessage = createMessage('1')
|
||||
const { rerender } = renderHook(
|
||||
(props) => useAutoPlayLastResponse(props),
|
||||
{
|
||||
initialProps: {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: incompleteMessage,
|
||||
lastAssistantText: 'Test text',
|
||||
hasActiveStream: false,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
|
||||
const completedMessage = createMessage('1', Date.now())
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: completedMessage,
|
||||
lastAssistantText: 'Test text',
|
||||
hasActiveStream: 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()
|
||||
|
||||
const message = createMessage('1', Date.now())
|
||||
const { rerender } = renderHook(
|
||||
(props) => useAutoPlayLastResponse(props),
|
||||
{
|
||||
initialProps: {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: message,
|
||||
lastAssistantText: 'Test text',
|
||||
hasActiveStream: false,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: message,
|
||||
lastAssistantText: 'Test text',
|
||||
hasActiveStream: false,
|
||||
})
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('CALLS speakMessage for a subsequent new message id after the baseline', () => {
|
||||
setup()
|
||||
|
||||
const firstMessage = createMessage('1', Date.now() - 2000)
|
||||
|
||||
const { rerender } = renderHook(
|
||||
(props) => useAutoPlayLastResponse(props),
|
||||
{
|
||||
initialProps: {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: firstMessage,
|
||||
lastAssistantText: 'First text',
|
||||
hasActiveStream: false,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
|
||||
const secondMessage = createMessage('2', Date.now())
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: secondMessage,
|
||||
lastAssistantText: 'Second text',
|
||||
hasActiveStream: false,
|
||||
})
|
||||
|
||||
expect(mockSpeakMessage).toHaveBeenCalledTimes(1)
|
||||
expect(mockSpeakMessage).toHaveBeenCalledWith('2', 'Second text')
|
||||
})
|
||||
|
||||
it('resets baseline when sessionId changes', () => {
|
||||
setup()
|
||||
|
||||
const message1 = createMessage('1', Date.now() - 2000)
|
||||
|
||||
const { rerender } = renderHook(
|
||||
(props) => useAutoPlayLastResponse(props),
|
||||
{
|
||||
initialProps: {
|
||||
sessionId: 'session-1',
|
||||
lastAssistantMessage: message1,
|
||||
lastAssistantText: 'Session 1 text',
|
||||
hasActiveStream: false,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
|
||||
const message2 = createMessage('1', Date.now())
|
||||
rerender({
|
||||
sessionId: 'session-2',
|
||||
lastAssistantMessage: message2,
|
||||
lastAssistantText: 'Session 2 text',
|
||||
hasActiveStream: false,
|
||||
})
|
||||
|
||||
expect(mockSpeakMessage).toHaveBeenCalledTimes(1)
|
||||
expect(mockSpeakMessage).toHaveBeenCalledWith('1', 'Session 2 text')
|
||||
})
|
||||
|
||||
it('does NOT call speakMessage when hasActiveStream is true', () => {
|
||||
setup()
|
||||
|
||||
const message = createMessage('1', Date.now())
|
||||
renderHook(() =>
|
||||
useAutoPlayLastResponse({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: message,
|
||||
lastAssistantText: 'Test text',
|
||||
hasActiveStream: true,
|
||||
})
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does NOT call speakMessage when lastAssistantText is empty', () => {
|
||||
setup()
|
||||
|
||||
const message = createMessage('1', Date.now())
|
||||
renderHook(() =>
|
||||
useAutoPlayLastResponse({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: message,
|
||||
lastAssistantText: '',
|
||||
hasActiveStream: false,
|
||||
})
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does NOT call speakMessage when lastAssistantText is whitespace only', () => {
|
||||
setup()
|
||||
|
||||
const message = createMessage('1', Date.now())
|
||||
renderHook(() =>
|
||||
useAutoPlayLastResponse({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: message,
|
||||
lastAssistantText: ' ',
|
||||
hasActiveStream: false,
|
||||
})
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,102 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useTTS } from './useTTS'
|
||||
import { useSettings } from './useSettings'
|
||||
import type { MessageWithParts } from '@/api/types'
|
||||
|
||||
interface UseAutoPlayLastResponseParams {
|
||||
sessionId: string
|
||||
lastAssistantMessage: MessageWithParts | undefined
|
||||
lastAssistantText: string
|
||||
hasActiveStream: boolean
|
||||
}
|
||||
|
||||
function isMessageCompleted(message: MessageWithParts['info']): boolean {
|
||||
return message.role === 'assistant' && message.time.completed !== undefined
|
||||
}
|
||||
|
||||
export function useAutoPlayLastResponse({
|
||||
sessionId,
|
||||
lastAssistantMessage,
|
||||
lastAssistantText,
|
||||
hasActiveStream,
|
||||
}: UseAutoPlayLastResponseParams): void {
|
||||
const { speakMessage, isEnabled: ttsEnabled } = useTTS()
|
||||
const { preferences } = useSettings()
|
||||
|
||||
const autoPlayEnabled = preferences?.tts?.autoPlay ?? false
|
||||
|
||||
const lastSpokenIdRef = useRef<string | null>(null)
|
||||
const hasInitializedRef = useRef<boolean>(false)
|
||||
const lastKnownCompletedRef = useRef<Record<string, boolean>>({})
|
||||
const hasSeenIncompleteRef = useRef<boolean>(false)
|
||||
const previousSessionIdRef = useRef<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const isSessionChange = previousSessionIdRef.current !== null && previousSessionIdRef.current !== sessionId
|
||||
const isFirstMount = previousSessionIdRef.current === null
|
||||
previousSessionIdRef.current = sessionId
|
||||
|
||||
lastSpokenIdRef.current = null
|
||||
hasInitializedRef.current = false
|
||||
lastKnownCompletedRef.current = {}
|
||||
|
||||
if (isSessionChange) {
|
||||
hasSeenIncompleteRef.current = true
|
||||
} else if (isFirstMount) {
|
||||
hasSeenIncompleteRef.current = false
|
||||
}
|
||||
}, [sessionId])
|
||||
|
||||
useEffect(() => {
|
||||
if (!ttsEnabled || !autoPlayEnabled) {
|
||||
return
|
||||
}
|
||||
|
||||
if (hasActiveStream || !lastAssistantMessage) {
|
||||
return
|
||||
}
|
||||
|
||||
const messageId = lastAssistantMessage.info.id
|
||||
const isCompleted = isMessageCompleted(lastAssistantMessage.info)
|
||||
const wasCompleted = lastKnownCompletedRef.current[messageId] ?? false
|
||||
|
||||
if (!isCompleted) {
|
||||
lastKnownCompletedRef.current[messageId] = false
|
||||
hasSeenIncompleteRef.current = true
|
||||
return
|
||||
}
|
||||
|
||||
if (!lastAssistantText.trim()) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!hasInitializedRef.current) {
|
||||
hasInitializedRef.current = true
|
||||
lastSpokenIdRef.current = messageId
|
||||
lastKnownCompletedRef.current[messageId] = true
|
||||
if (hasSeenIncompleteRef.current) {
|
||||
speakMessage(messageId, lastAssistantText)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (!wasCompleted && messageId === lastSpokenIdRef.current) {
|
||||
lastKnownCompletedRef.current[messageId] = true
|
||||
speakMessage(messageId, lastAssistantText)
|
||||
return
|
||||
}
|
||||
|
||||
if (messageId !== lastSpokenIdRef.current) {
|
||||
lastSpokenIdRef.current = messageId
|
||||
lastKnownCompletedRef.current[messageId] = true
|
||||
speakMessage(messageId, lastAssistantText)
|
||||
}
|
||||
}, [
|
||||
ttsEnabled,
|
||||
autoPlayEnabled,
|
||||
hasActiveStream,
|
||||
lastAssistantMessage,
|
||||
lastAssistantText,
|
||||
speakMessage,
|
||||
])
|
||||
}
|
||||
@@ -278,11 +278,11 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
};
|
||||
|
||||
if (model) {
|
||||
const [providerID, ...rest] = model.split("/");
|
||||
if (providerID && rest.length > 0) {
|
||||
const [providerID, modelID] = model.split("/");
|
||||
if (providerID && modelID) {
|
||||
requestData.model = {
|
||||
providerID,
|
||||
modelID: rest.join("/"),
|
||||
modelID,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ import { useAutoScroll } from "@/hooks/useAutoScroll";
|
||||
import { useMobile } from "@/hooks/useMobile";
|
||||
import { useVisualViewport } from "@/hooks/useVisualViewport";
|
||||
import { useTTS } from "@/hooks/useTTS";
|
||||
import { useAutoPlayLastResponse } from "@/hooks/useAutoPlayLastResponse";
|
||||
import { useEffect, useRef, useCallback, useMemo } from "react";
|
||||
import { MessageSkeleton } from "@/components/message/MessageSkeleton";
|
||||
import { exportSession, downloadMarkdown } from "@/lib/exportSession";
|
||||
@@ -155,6 +156,13 @@ export function SessionDetail() {
|
||||
const hasIncompleteMessages = lastAssistantMessage ? !('completed' in lastAssistantMessage.info.time && lastAssistantMessage.info.time.completed) : false;
|
||||
const hasActiveStream = hasIncompleteMessages && isSessionActive;
|
||||
|
||||
useAutoPlayLastResponse({
|
||||
sessionId: sessionId ?? '',
|
||||
lastAssistantMessage,
|
||||
lastAssistantText,
|
||||
hasActiveStream,
|
||||
});
|
||||
|
||||
const handleShowModelsDialog = useCallback(() => setModelDialogOpen(true), []);
|
||||
const handleShowSessionsDialog = useCallback(() => setSessionsDialogOpen(true), []);
|
||||
const handleShowHelpDialog = useCallback(() => openSettings(), [openSettings]);
|
||||
@@ -516,30 +524,34 @@ export function SessionDetail() {
|
||||
style={{ bottom: inputBottomOffset }}
|
||||
>
|
||||
<div className="relative w-[94%] md:max-w-4xl">
|
||||
{hasPromptContent && (
|
||||
<button
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onTouchEnd={(e) => {
|
||||
e.preventDefault()
|
||||
handleClearPrompt()
|
||||
}}
|
||||
onClick={handleClearPrompt}
|
||||
className="absolute -top-5 right-0 md:right-4 z-50 flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-destructive-foreground border border-red-500/60 hover:border-red-400 shadow-md shadow-red-500/30 hover:shadow-red-500/50 backdrop-blur-md transition-all duration-200 active:scale-95 hover:scale-105 ring-1 ring-red-500/20 hover:ring-red-500/40"
|
||||
aria-label="Clear"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
<span className="text-sm font-medium hidden sm:inline">Clear</span>
|
||||
</button>
|
||||
)}
|
||||
<div className="absolute -top-5 right-0 md:right-4 z-50 flex flex-col items-end gap-2">
|
||||
{ttsEnabled && !hasPromptContent && !hasActiveStream && ((lastAssistantMessage && lastAssistantText) || preferences?.tts?.autoPlay) && (
|
||||
<FloatingTTSButton
|
||||
messageId={lastAssistantMessage?.info.id ?? ''}
|
||||
content={lastAssistantText}
|
||||
/>
|
||||
)}
|
||||
{hasPromptContent && (
|
||||
<button
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onTouchEnd={(e) => {
|
||||
e.preventDefault()
|
||||
handleClearPrompt()
|
||||
}}
|
||||
onClick={handleClearPrompt}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-destructive-foreground border border-red-500/60 hover:border-red-400 shadow-md shadow-red-500/30 hover:shadow-red-500/50 backdrop-blur-md transition-all duration-200 active:scale-95 hover:scale-105 ring-1 ring-red-500/20 hover:ring-red-500/40"
|
||||
aria-label="Clear"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
<span className="text-sm font-medium hidden sm:inline">Clear</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{leaderActive && (
|
||||
<div className="absolute -top-12 left-1/2 -translate-x-1/2 z-50 px-4 py-2 rounded-xl bg-primary/90 text-primary-foreground border border-primary shadow-lg backdrop-blur-md animate-pulse">
|
||||
<span className="text-sm font-medium">Waiting for shortcut key...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{ttsEnabled && lastAssistantText && !hasPromptContent && !hasActiveStream && (
|
||||
<FloatingTTSButton content={lastAssistantText} />
|
||||
)}
|
||||
{minimizedQuestion && minimizedQuestion.sessionID === sessionId && (
|
||||
<MinimizedQuestionIndicator
|
||||
question={minimizedQuestion}
|
||||
|
||||
@@ -10,6 +10,7 @@ export const CustomCommandSchema = z.object({
|
||||
export const TTSConfigSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
provider: z.enum(['external', 'builtin']).default('external'),
|
||||
autoPlay: z.boolean().default(false),
|
||||
endpoint: z.string(),
|
||||
apiKey: z.string(),
|
||||
voice: z.string(),
|
||||
@@ -35,6 +36,7 @@ export const STTConfigSchema = z.object({
|
||||
export type TTSConfig = {
|
||||
enabled: boolean;
|
||||
provider: 'external' | 'builtin';
|
||||
autoPlay: boolean;
|
||||
endpoint: string;
|
||||
apiKey: string;
|
||||
voice: string;
|
||||
@@ -132,6 +134,7 @@ export const UserPreferencesSchema = z.object({
|
||||
export const DEFAULT_TTS_CONFIG: TTSConfig = {
|
||||
enabled: false,
|
||||
provider: 'external',
|
||||
autoPlay: false,
|
||||
endpoint: "https://api.openai.com",
|
||||
apiKey: "",
|
||||
voice: "alloy",
|
||||
|
||||
Reference in new issue
Block a user