feat(frontend): hands-free voice conversation mode in the composer

The mic opens a voice loop that listens, sends on end of speech, reads each completed reply and reopens the mic when the agent is idle. The phase reducer, pause options and voice-mode instruction move to the shared package. TTS gains per-message completion and pause/resume. The old tap-and-drag recorder, its strip and its CSS are removed.
This commit is contained in:
Chris Scott committed 2026-10-22 20:18:16 -04:00
1 parent 80ef211a94
commit 5d8b2c9445
34 files changed
+4876 -1302

No files matched your search

@@ -4,7 +4,7 @@ import { render, screen, fireEvent, act, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput, type PromptInputHandle } from './PromptInput'
import { BUILTIN_COMMANDS } from '@/lib/builtinCommands'
import { createCommandActionsMock, stubMatchMedia } from '@/test/test-utils'
import { createCommandActionsMock, stubMatchMedia, createVoiceConversationControllerMock } from '@/test/test-utils'
const mocks = vi.hoisted(() => ({
runCommand: vi.fn(),
@@ -24,6 +24,7 @@ const mocks = vi.hoisted(() => ({
dismiss: vi.fn(),
},
useSTT: vi.fn(),
useVoiceConversation: vi.fn(),
useMobile: vi.fn(),
useCommands: vi.fn(),
useFileSearch: vi.fn(),
@@ -57,7 +58,11 @@ vi.mock('@/hooks/useOpenCode', async () => {
}
})
vi.mock('@/hooks/useSTT', () => ({ useSTT: mocks.useSTT }))
vi.mock('@/hooks/useSTT', () => ({
useSTT: mocks.useSTT,
useSttAvailability: () => ({ isEnabled: true, isSupported: true }),
}))
vi.mock('@/hooks/useVoiceConversation', () => ({ useVoiceConversation: mocks.useVoiceConversation }))
vi.mock('@/hooks/useMobile', () => ({ useMobile: mocks.useMobile }))
vi.mock('@/hooks/useCommands', () => ({ useCommands: mocks.useCommands }))
vi.mock('@/hooks/useFileSearch', () => ({ useFileSearch: mocks.useFileSearch }))
@@ -142,6 +147,9 @@ describe('PromptInput command submission', () => {
const defaultProps = {
directory: '/test',
sessionID: 'test-session',
messages: [],
pending: [],
transcriptStatus: 'idle' as const,
showScrollButton: false,
isSessionActive: false,
isStreamingResponse: false,
@@ -169,6 +177,7 @@ describe('PromptInput command submission', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useVoiceConversation.mockReturnValue(createVoiceConversationControllerMock())
mocks.runCommand.mockResolvedValue(undefined)
mocks.switchSessionModel.mockResolvedValue(undefined)
mocks.switchSessionAgent.mockResolvedValue(undefined)
@@ -3,10 +3,11 @@ import { render, screen, fireEvent, waitFor, within, act } from '@testing-librar
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput } from './PromptInput'
import { useSessionStatus } from '@/stores/sessionStatusStore'
import { createCommandActionsMock } from '@/test/test-utils'
import { createCommandActionsMock, createVoiceConversationControllerMock } from '@/test/test-utils'
const mocks = vi.hoisted(() => ({
useSTT: vi.fn(),
useVoiceConversation: vi.fn(),
useMobile: vi.fn(),
useCommands: vi.fn(),
useCommandHandler: vi.fn(),
@@ -23,7 +24,11 @@ const mocks = vi.hoisted(() => ({
setShowDialog: vi.fn(),
}))
vi.mock('@/hooks/useSTT', () => ({ useSTT: mocks.useSTT }))
vi.mock('@/hooks/useSTT', () => ({
useSTT: mocks.useSTT,
useSttAvailability: () => ({ isEnabled: true, isSupported: true }),
}))
vi.mock('@/hooks/useVoiceConversation', () => ({ useVoiceConversation: mocks.useVoiceConversation }))
vi.mock('@/hooks/useMobile', () => ({ useMobile: mocks.useMobile }))
vi.mock('@/hooks/useCommands', () => ({ useCommands: mocks.useCommands }))
vi.mock('@/hooks/useCommandHandler', () => ({ useCommandHandler: mocks.useCommandHandler }))
@@ -88,7 +93,10 @@ const createTestQueryClient = () => new QueryClient({
const defaultProps = {
directory: '/test',
sessionID: 'test-session',
showScrollButton: false,
messages: [],
pending: [],
transcriptStatus: 'idle' as const,
showScrollButton: false,
isSessionActive: false,
isStreamingResponse: false,
onScrollToBottom: vi.fn(),
@@ -106,11 +114,12 @@ describe('PromptInput composer layout', () => {
const promptInput = () => screen.getByPlaceholderText('Send a message...')
const submitButton = () => document.querySelector('[data-submit-prompt]')
const controlsRow = () => screen.getByTestId('composer-controls-row')
const mobileVoiceButton = () => document.querySelector('[data-voice-variant="mobile"]')
const voiceMicButton = () => screen.queryByRole('button', { name: 'Start voice conversation' })
const keyButtons = () => screen.queryAllByRole('toolbar', { name: 'Insert' })
beforeEach(() => {
vi.clearAllMocks()
mocks.useVoiceConversation.mockReturnValue(createVoiceConversationControllerMock())
mocks.hasPendingPermission.mockReturnValue(false)
mocks.useMobile.mockReturnValue(false)
mocks.useSTT.mockReturnValue({
@@ -328,7 +337,7 @@ describe('PromptInput composer layout', () => {
fireEvent.focus(promptInput())
const actions = controlsRow().lastElementChild as HTMLElement
expect(actions).toContainElement(mobileVoiceButton() as HTMLElement)
expect(actions).toContainElement(voiceMicButton() as HTMLElement)
expect(actions).toContainElement(screen.getByTestId('composer-tools-menu'))
})
})
@@ -362,15 +371,15 @@ describe('PromptInput composer layout', () => {
fireEvent.change(promptInput(), { target: { value: 'hello' } })
expect(submitButton()).not.toBeNull()
expect(mobileVoiceButton()).not.toBeNull()
expect(controlsRow().lastElementChild).toContainElement(mobileVoiceButton() as HTMLElement)
expect(voiceMicButton()).not.toBeNull()
expect(controlsRow().lastElementChild).toContainElement(voiceMicButton() as HTMLElement)
})
it('hides the mic while a permission is pending', () => {
mocks.hasPendingPermission.mockReturnValue(true)
renderComponent()
expect(mobileVoiceButton()).toBeNull()
expect(voiceMicButton()).toBeNull()
expect(screen.getByTitle('View pending permission')).toBeInTheDocument()
})
})
@@ -380,13 +389,13 @@ describe('PromptInput composer layout', () => {
mocks.useMobile.mockReturnValue(true)
renderComponent()
const micBeforeFocus = mobileVoiceButton() as HTMLElement
const micBeforeFocus = voiceMicButton() as HTMLElement
expect(micBeforeFocus).toHaveClass('min-h-11', 'min-w-11')
expect(micBeforeFocus).not.toHaveClass('min-h-[44px]')
fireEvent.focus(promptInput())
const micAfterFocus = mobileVoiceButton() as HTMLElement
const micAfterFocus = voiceMicButton() as HTMLElement
expect(micAfterFocus).toHaveClass('min-h-11', 'min-w-11')
expect(micAfterFocus).not.toHaveClass('min-h-[44px]')
})
@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput } from './PromptInput'
import { createCommandActionsMock, stubMatchMedia } from '@/test/test-utils'
import { createCommandActionsMock, stubMatchMedia, createVoiceConversationControllerMock } from '@/test/test-utils'
const mocks = vi.hoisted(() => ({
sendPrompt: vi.fn(),
@@ -25,6 +25,7 @@ const mocks = vi.hoisted(() => ({
dismiss: vi.fn(),
},
useSTT: vi.fn(),
useVoiceConversation: vi.fn(),
useMobile: vi.fn(),
useCommands: vi.fn(),
useFileSearch: vi.fn(),
@@ -73,7 +74,11 @@ vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: mocks.useSessionPermissionMode,
}))
vi.mock('@/hooks/useSTT', () => ({ useSTT: mocks.useSTT }))
vi.mock('@/hooks/useSTT', () => ({
useSTT: mocks.useSTT,
useSttAvailability: () => ({ isEnabled: true, isSupported: true }),
}))
vi.mock('@/hooks/useVoiceConversation', () => ({ useVoiceConversation: mocks.useVoiceConversation }))
vi.mock('@/hooks/useMobile', () => ({ useMobile: mocks.useMobile }))
vi.mock('@/hooks/useCommands', () => ({ useCommands: mocks.useCommands }))
vi.mock('@/hooks/useFileSearch', () => ({ useFileSearch: mocks.useFileSearch }))
@@ -140,6 +145,9 @@ describe('PromptInput goal mode', () => {
const defaultProps = {
directory: '/test',
sessionID: 'test-session',
messages: [],
pending: [],
transcriptStatus: 'idle' as const,
showScrollButton: false,
isSessionActive: false,
isStreamingResponse: false,
@@ -159,6 +167,7 @@ describe('PromptInput goal mode', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useVoiceConversation.mockReturnValue(createVoiceConversationControllerMock())
mocks.useSessionGoal.mockReturnValue({ data: null })
mocks.useSessionPermissionMode.mockReturnValue({ data: undefined })
mocks.startGoal.mockResolvedValue({ id: 1 })
@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput } from './PromptInput'
import { createCommandActionsMock } from '@/test/test-utils'
import { createCommandActionsMock, createVoiceConversationControllerMock } from '@/test/test-utils'
const mocks = vi.hoisted(() => ({
sendPrompt: vi.fn(),
@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({
agents: [] as Array<{ name: string; description?: string }>,
skills: [] as Array<{ id: string; name: string; description?: string }>,
useSTT: vi.fn(),
useVoiceConversation: vi.fn(),
useMobile: vi.fn(),
useCommands: vi.fn(),
useFileSearch: vi.fn(),
@@ -45,7 +46,11 @@ vi.mock('@/hooks/useOpenCode', async () => {
}
})
vi.mock('@/hooks/useSTT', () => ({ useSTT: mocks.useSTT }))
vi.mock('@/hooks/useSTT', () => ({
useSTT: mocks.useSTT,
useSttAvailability: () => ({ isEnabled: true, isSupported: true }),
}))
vi.mock('@/hooks/useVoiceConversation', () => ({ useVoiceConversation: mocks.useVoiceConversation }))
vi.mock('@/hooks/useMobile', () => ({ useMobile: mocks.useMobile }))
vi.mock('@/hooks/useCommands', () => ({ useCommands: mocks.useCommands }))
vi.mock('@/hooks/useFileSearch', () => ({ useFileSearch: mocks.useFileSearch }))
@@ -128,6 +133,9 @@ describe('PromptInput agent mention submission', () => {
const defaultProps = {
directory: '/test',
sessionID: 'test-session',
messages: [],
pending: [],
transcriptStatus: 'idle' as const,
showScrollButton: false,
isSessionActive: false,
isStreamingResponse: false,
@@ -148,6 +156,7 @@ describe('PromptInput agent mention submission', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useVoiceConversation.mockReturnValue(createVoiceConversationControllerMock())
mocks.sendPrompt.mockResolvedValue({
id: 'inbox_1',
sessionID: 'test-session',
File diff suppressed because it is too large. Load diff
+106 -509
View File
@@ -1,4 +1,4 @@
import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, memo, useCallback, type KeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react'
import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, memo, useCallback, type KeyboardEvent } from 'react'
import { useSendPrompt, useInterruptSession, useSendShell, useAgents, useSkills } from '@/hooks/useOpenCode'
import { useCommands } from '@/hooks/useCommands'
import { useCommandHandler } from '@/hooks/useCommandHandler'
@@ -6,7 +6,9 @@ import { useFileSearch } from '@/hooks/useFileSearch'
import { useModelSelection } from '@/hooks/useModelSelection'
import { useVariants } from '@/hooks/useVariants'
import { useSessionAgent } from '@/hooks/useSessionAgent'
import { useSTT } from '@/hooks/useSTT'
import { useSttAvailability } from '@/hooks/useSTT'
import { useVoiceConversation } from '@/hooks/useVoiceConversation'
import { useVoicePauseSetting } from '@/hooks/useVoicePauseSetting'
import { useUserBash } from '@/stores/userBashStore'
import { useSessionAgentStore } from '@/stores/sessionAgentStore'
@@ -19,7 +21,7 @@ import { FINE_POINTER_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery'
import { usePermissions } from '@/contexts/EventContext'
import { isLocalOpenCodeServer, useOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
import { ArrowDown, ArrowUp, Upload, X, Mic, MicOff, Target } from 'lucide-react'
import { ArrowDown, Upload, X, Mic, Target } from 'lucide-react'
import { SquareFill } from '@/components/ui/square-fill'
import { IconToggleButton, getIconToggleButtonClassName } from '@/components/ui/icon-toggle-button'
@@ -28,7 +30,7 @@ import { PromptSuggestions, type PromptSuggestion } from './PromptSuggestions'
import { ComposerActivityBar } from './ComposerActivityBar'
import { ModelQuickSelect } from '@/components/model/ModelQuickSelect'
import { AgentQuickSelect } from '@/components/agent/AgentQuickSelect'
import { VoiceRecorderStrip, type VoiceRecorderStripState } from './VoiceRecorderStrip'
import { VoiceConversationBar } from './VoiceConversationBar'
import { PermissionModeToggle } from '@/components/session/PermissionModeToggle'
import { SessionSandboxMenu } from '@/components/session/SessionSandboxMenu'
import { ComposerToolsMenu } from './ComposerToolsMenu'
@@ -45,7 +47,7 @@ import { isOpenSessionGoal } from '@opencode-manager/shared/schemas'
import { useProviders } from '@/hooks/useProviders'
import type { CommandInfo } from '@opencode-manager/shared/opencode'
import type { CommandInfo, SessionInboxInfo, SessionMessageInfo, VoiceSessionStatus } from '@opencode-manager/shared/opencode'
import type { FileAttachmentInfo, ImageAttachment } from '@/api/types'
import { isBuiltinCommand, type CommandActions, type PageCommandActions } from '@/lib/builtinCommands'
@@ -104,13 +106,6 @@ const COMPOSER_MODE_STYLES: Record<ComposerMode, { label: string, frame: string,
const shiftRanges = (ranges: MatchRange[], offset: number): MatchRange[] =>
ranges.map(([start, end]) => [start + offset, end + offset])
const VOICE_SEND_DRAG_ARM_THRESHOLD = 24
const VOICE_SEND_DRAG_DISARM_THRESHOLD = 8
const VOICE_CANCEL_DRAG_ARM_THRESHOLD = 96
const VOICE_CANCEL_DRAG_DISARM_THRESHOLD = VOICE_CANCEL_DRAG_ARM_THRESHOLD - 8
const VOICE_CLICK_SUPPRESSION_MS = 400
type VoiceButtonVariant = 'desktop' | 'mobile'
export interface PromptInputHandle {
setPromptValue: (value: string) => void
@@ -125,6 +120,10 @@ export interface PromptInputHandle {
interface PromptInputProps {
directory?: string
sessionID: string
messages: SessionMessageInfo[]
pending: SessionInboxInfo[]
transcriptStatus: VoiceSessionStatus
onVoiceConversationActiveChange?: (active: boolean) => void
showScrollButton?: boolean
isSessionActive?: boolean
isStreamingResponse?: boolean
@@ -136,6 +135,10 @@ interface PromptInputProps {
export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(function PromptInput({
directory,
sessionID,
messages,
pending,
transcriptStatus,
onVoiceConversationActiveChange,
showScrollButton,
isSessionActive = false,
isStreamingResponse = false,
@@ -158,44 +161,18 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const [selectedMentionIndex, setSelectedMentionIndex] = useState(0)
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0)
const [localMode, setLocalMode] = useState<string | null>(null)
const [isTogglingRecording, setIsTogglingRecording] = useState(false)
const [isVoiceSendArmed, setIsVoiceSendArmed] = useState(false)
const [isVoiceCancelArmed, setIsVoiceCancelArmed] = useState(false)
const [isVoiceAutoSendPending, setIsVoiceAutoSendPending] = useState(false)
const [isVoiceAutoSendWaitingForTranscript, setIsVoiceAutoSendWaitingForTranscript] = useState(false)
const [voiceRecordingStartedAt, setVoiceRecordingStartedAt] = useState<number | null>(null)
const [isPromptFocused, setIsPromptFocused] = useState(false)
const promptBlurTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const pendingCommandSubmitRef = useRef(false)
const lastAddedTranscriptRef = useRef('')
const voiceGestureStartXRef = useRef<number | null>(null)
const voiceSendArmedRef = useRef(false)
const voiceCancelArmedRef = useRef(false)
const pendingVoiceAutoSubmitRef = useRef(false)
const ignoreVoiceClickUntilRef = useRef(0)
const voiceStartRequestRef = useRef(0)
const handleSubmitRef = useRef<() => void>(() => {})
const promptRef = useRef(prompt)
const attachedFilesRef = useRef(attachedFiles)
const imageAttachmentsRef = useRef(imageAttachments)
const {
isRecording,
isProcessing,
startRecording,
stopRecording,
abortRecording,
isSupported: sttSupported,
isEnabled: sttEnabled,
interimTranscript,
transcript,
clear: clearSTT,
} = useSTT()
const sttAvailability = useSttAvailability()
const textareaRef = useRef<HTMLTextAreaElement>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
const voiceButtonContainerRef = useRef<HTMLDivElement | null>(null)
const composerControlsRowRef = useRef<HTMLDivElement | null>(null)
const hasFinePointer = useMediaQuery(FINE_POINTER_MEDIA_QUERY)
const isMobile = useMobile()
@@ -206,18 +183,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
textareaRef.current?.focus()
}, [hasFinePointer, sessionID])
const resetVoiceGestureState = useCallback(() => {
voiceGestureStartXRef.current = null
voiceSendArmedRef.current = false
voiceCancelArmedRef.current = false
pendingVoiceAutoSubmitRef.current = false
ignoreVoiceClickUntilRef.current = 0
setIsVoiceSendArmed(false)
setIsVoiceCancelArmed(false)
setIsVoiceAutoSendPending(false)
setIsVoiceAutoSendWaitingForTranscript(false)
}, [])
useEffect(() => {
promptRef.current = prompt
attachedFilesRef.current = attachedFiles
@@ -239,8 +204,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
revokeBlobUrls(submittedImageAttachments)
setImageAttachments([])
}
clearSTT()
}, [clearSTT])
}, [])
const pendingConfirmClearRef = useRef<{
prompt: string
@@ -262,7 +226,8 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const sessionAgent = useSessionAgent(sessionID, directory)
const hasBackgroundActivity = useHasBackgroundActivity(sessionID)
const isLocalServer = isLocalOpenCodeServer(useOpenCodeServerId())
const serverId = useOpenCodeServerId()
const isLocalServer = isLocalOpenCodeServer(serverId)
const currentMode = localMode ?? sessionAgent.agent
const setStoredAgent = useSessionAgentStore((s) => s.setAgent)
const sendPrompt = useSendPrompt(directory)
@@ -395,9 +360,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
if (!prompt.trim() && imageAttachments.length === 0) return
if (startGoal.isPending) return
pendingVoiceAutoSubmitRef.current = false
setIsVoiceAutoSendPending(false)
if (isStreamingResponse) {
onScrollToBottom()
const parsed = parsePromptToInput(prompt, attachedFiles, agentNames, skillIds, imageAttachments)
@@ -443,7 +405,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
if (promptRef.current !== submittedPrompt) return
setPrompt('')
setIsBashMode(false)
clearSTT()
}
}
)
@@ -527,8 +488,16 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
handleSubmitRef.current = handleSubmit
const interruptTurn = useCallback(
(): Promise<void> =>
new Promise((resolve) => {
interruptSession.mutate(sessionID, { onSettled: () => resolve() })
}),
[interruptSession, sessionID],
)
const handleStop = () => {
interruptSession.mutate(sessionID)
void interruptTurn()
}
const focusPromptAt = useCallback((cursorPosition: number) => {
@@ -617,298 +586,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
setMentionRange(null)
}
const startVoiceRecording = async () => {
if (isRecording || isProcessing || isTogglingRecording) {
return
}
const startRequestId = voiceStartRequestRef.current + 1
voiceStartRequestRef.current = startRequestId
pendingVoiceAutoSubmitRef.current = false
setIsVoiceAutoSendPending(false)
setIsVoiceAutoSendWaitingForTranscript(false)
setIsVoiceSendArmed(false)
voiceSendArmedRef.current = false
setIsVoiceCancelArmed(false)
voiceCancelArmedRef.current = false
setIsTogglingRecording(true)
const started = await startRecording()
if (voiceStartRequestRef.current !== startRequestId) {
setIsTogglingRecording(false)
if (started) {
abortRecording()
}
return
}
if (!started) {
setIsTogglingRecording(false)
return
}
if (typeof navigator !== 'undefined' && navigator.vibrate) {
navigator.vibrate(10)
}
textareaRef.current?.blur()
}
const handleVoiceClick = async () => {
if (Date.now() < ignoreVoiceClickUntilRef.current) {
return
}
if (isRecording) {
pendingVoiceAutoSubmitRef.current = false
setIsVoiceAutoSendPending(false)
setIsVoiceAutoSendWaitingForTranscript(false)
setIsVoiceSendArmed(false)
voiceSendArmedRef.current = false
setIsVoiceCancelArmed(false)
voiceCancelArmedRef.current = false
stopRecording()
return
}
await startVoiceRecording()
}
const cancelVoiceInput = useCallback(() => {
voiceStartRequestRef.current += 1
resetVoiceGestureState()
setIsTogglingRecording(false)
if (isRecording || isTogglingRecording || isProcessing) {
abortRecording()
}
}, [abortRecording, isProcessing, isRecording, isTogglingRecording, resetVoiceGestureState])
const clearVoiceGestureArmedState = useCallback(() => {
ignoreVoiceClickUntilRef.current = Date.now() + VOICE_CLICK_SUPPRESSION_MS
voiceSendArmedRef.current = false
voiceCancelArmedRef.current = false
setIsVoiceSendArmed(false)
setIsVoiceCancelArmed(false)
}, [])
const armVoiceAutoSend = useCallback(() => {
pendingVoiceAutoSubmitRef.current = true
setIsVoiceAutoSendPending(true)
setIsVoiceAutoSendWaitingForTranscript(true)
if (typeof navigator !== 'undefined' && navigator.vibrate) {
navigator.vibrate([10, 20, 10])
}
}, [])
const handleVoiceSendRequest = useCallback(() => {
clearVoiceGestureArmedState()
armVoiceAutoSend()
if (isRecording) {
stopRecording()
}
}, [armVoiceAutoSend, clearVoiceGestureArmedState, isRecording, stopRecording])
const handleVoicePointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
if ((event.pointerType === 'mouse' && event.button !== 0) || isProcessing || !isRecording) {
return
}
event.preventDefault()
voiceGestureStartXRef.current = event.clientX
voiceSendArmedRef.current = false
voiceCancelArmedRef.current = false
setIsVoiceSendArmed(false)
setIsVoiceCancelArmed(false)
if (event.currentTarget.setPointerCapture) {
event.currentTarget.setPointerCapture(event.pointerId)
}
}
const handleVoicePointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
if (!isRecording || voiceGestureStartXRef.current === null) {
return
}
event.preventDefault()
const deltaX = event.clientX - voiceGestureStartXRef.current
const nextIsSendArmed = voiceSendArmedRef.current
? deltaX >= VOICE_SEND_DRAG_DISARM_THRESHOLD
: deltaX >= VOICE_SEND_DRAG_ARM_THRESHOLD
const nextIsCancelArmed = !nextIsSendArmed && (voiceCancelArmedRef.current
? deltaX <= -VOICE_CANCEL_DRAG_DISARM_THRESHOLD
: deltaX <= -VOICE_CANCEL_DRAG_ARM_THRESHOLD)
if (nextIsSendArmed !== voiceSendArmedRef.current) {
voiceSendArmedRef.current = nextIsSendArmed
setIsVoiceSendArmed(nextIsSendArmed)
if (nextIsSendArmed && typeof navigator !== 'undefined' && navigator.vibrate) {
navigator.vibrate(10)
}
}
if (nextIsCancelArmed !== voiceCancelArmedRef.current) {
voiceCancelArmedRef.current = nextIsCancelArmed
setIsVoiceCancelArmed(nextIsCancelArmed)
if (nextIsCancelArmed && typeof navigator !== 'undefined' && navigator.vibrate) {
navigator.vibrate(10)
}
}
}
const handleVoicePointerEnd = (event: ReactPointerEvent<HTMLDivElement>, canceled = false) => {
if (event.currentTarget.releasePointerCapture && event.currentTarget.hasPointerCapture(event.pointerId)) {
event.currentTarget.releasePointerCapture(event.pointerId)
}
if (voiceGestureStartXRef.current === null) {
return
}
event.preventDefault()
voiceGestureStartXRef.current = null
const wasSendArmed = voiceSendArmedRef.current
const wasCancelArmed = voiceCancelArmedRef.current
clearVoiceGestureArmedState()
if (canceled || (!wasSendArmed && !wasCancelArmed)) {
pendingVoiceAutoSubmitRef.current = false
setIsVoiceAutoSendPending(false)
setIsVoiceAutoSendWaitingForTranscript(false)
stopRecording()
return
}
if (wasCancelArmed) {
cancelVoiceInput()
ignoreVoiceClickUntilRef.current = Date.now() + VOICE_CLICK_SUPPRESSION_MS
return
}
handleVoiceSendRequest()
}
useEffect(() => {
const isVoiceFeedbackVisible = isRecording || isTogglingRecording || isProcessing || isVoiceAutoSendPending
if (!isVoiceFeedbackVisible) {
return
}
const handleOutsidePointerDown = (event: PointerEvent) => {
const target = event.target
if (!(target instanceof Node)) {
return
}
if (voiceButtonContainerRef.current?.contains(target)) {
return
}
if (isMobile && composerControlsRowRef.current?.contains(target)) {
return
}
if (isRecording) {
voiceGestureStartXRef.current = null
voiceSendArmedRef.current = false
voiceCancelArmedRef.current = false
pendingVoiceAutoSubmitRef.current = false
setIsVoiceSendArmed(false)
setIsVoiceCancelArmed(false)
setIsVoiceAutoSendPending(false)
setIsVoiceAutoSendWaitingForTranscript(false)
stopRecording()
return
}
if (isProcessing || isVoiceAutoSendPending) {
pendingVoiceAutoSubmitRef.current = false
setIsVoiceAutoSendPending(false)
setIsVoiceAutoSendWaitingForTranscript(false)
return
}
cancelVoiceInput()
}
document.addEventListener('pointerdown', handleOutsidePointerDown, true)
return () => {
document.removeEventListener('pointerdown', handleOutsidePointerDown, true)
}
}, [cancelVoiceInput, isMobile, isProcessing, isRecording, isTogglingRecording, isVoiceAutoSendPending, stopRecording])
useEffect(() => {
const textToUse = transcript || interimTranscript
if (!isRecording && textToUse && textToUse !== 'Processing...' && textToUse !== 'Recording...') {
const trimmedTranscript = textToUse.trim()
if (trimmedTranscript && trimmedTranscript !== lastAddedTranscriptRef.current) {
if (prompt === '' || prompt === 'Processing...' || prompt === 'Recording...') {
setPrompt(trimmedTranscript)
} else {
setPrompt(prev => `${prev} ${trimmedTranscript}`)
}
lastAddedTranscriptRef.current = trimmedTranscript
if (!pendingVoiceAutoSubmitRef.current) {
textareaRef.current?.focus()
} else {
setIsVoiceAutoSendWaitingForTranscript(false)
}
}
}
}, [isRecording, interimTranscript, transcript, prompt])
useEffect(() => {
if (isRecording && isTogglingRecording) {
setIsTogglingRecording(false)
}
}, [isRecording, isTogglingRecording])
useEffect(() => {
if (isTogglingRecording) {
lastAddedTranscriptRef.current = ''
}
}, [isTogglingRecording])
useEffect(() => {
setVoiceRecordingStartedAt(isRecording ? Date.now() : null)
}, [isRecording])
useEffect(() => {
if (!pendingVoiceAutoSubmitRef.current || isVoiceAutoSendWaitingForTranscript || isRecording || isProcessing || !prompt.trim()) {
return
}
pendingVoiceAutoSubmitRef.current = false
setIsVoiceAutoSendPending(false)
setIsVoiceAutoSendWaitingForTranscript(false)
handleSubmitRef.current()
}, [prompt, isRecording, isProcessing, isVoiceAutoSendWaitingForTranscript])
useEffect(() => {
if (!isVoiceAutoSendWaitingForTranscript || isRecording || isProcessing || !transcript.trim()) {
return
}
setIsVoiceAutoSendWaitingForTranscript(false)
}, [isRecording, isProcessing, transcript, isVoiceAutoSendWaitingForTranscript])
useEffect(() => {
if (pendingVoiceAutoSubmitRef.current && !isRecording && !isProcessing && !transcript.trim() && !interimTranscript.trim()) {
pendingVoiceAutoSubmitRef.current = false
setIsVoiceAutoSendPending(false)
setIsVoiceAutoSendWaitingForTranscript(false)
}
}, [isRecording, isProcessing, transcript, interimTranscript])
const addImageAttachment = (file: File) => {
try {
const reader = new FileReader()
@@ -1186,13 +863,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
setImageAttachments([])
closeSuggestions()
setIsBashMode(false)
resetVoiceGestureState()
if (isRecording) {
abortRecording()
} else {
clearSTT()
}
}, [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState, closeSuggestions])
}, [imageAttachments, closeSuggestions])
const updateSuggestionTriggers = (value: string, cursorPosition: number) => {
const mentionTrigger = detectMentionTrigger(value, cursorPosition)
@@ -1422,104 +1093,67 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
: 'Goal mode: the next message becomes the objective'
const isGoalModeDisabled = lockedReason !== null || hasOpenGoal || isBashMode || startGoal.isPending
const toggleGoalArmed = () => setIsGoalArmed((value) => !value)
const voiceFeedbackState: VoiceRecorderStripState | null = isTogglingRecording
? 'starting'
: isProcessing
? isVoiceAutoSendPending
? 'sending'
: 'processing'
: isRecording
? isVoiceCancelArmed
? 'cancelArmed'
: isVoiceSendArmed
? 'readyToSend'
: 'recording'
: isVoiceAutoSendPending
? 'sending'
: null
const mobileVoiceRecorderState = isMobile ? voiceFeedbackState : null
const { pauseMs } = useVoicePauseSetting()
const sendVoiceTurn = useCallback(
async (text: string, options: { busy: boolean }): Promise<void> => {
await sendPrompt.mutateAsync({
sessionID,
text,
model: modelRef ?? undefined,
agent: currentMode,
...(options.busy ? { delivery: 'queue' as const } : {}),
})
setStoredAgent(sessionID, currentMode)
},
[currentMode, modelRef, sendPrompt, sessionID, setStoredAgent],
)
const handleVoiceEditInTextBox = useCallback((text: string) => {
const dictated = text.trim()
if (!dictated) return
setPrompt((current) => (current.trim() ? `${current} ${dictated}` : dictated))
textareaRef.current?.focus()
}, [])
const voiceConversation = useVoiceConversation({
sessionID,
serverId,
messages,
pending,
status: transcriptStatus,
hasPendingApproval: hasPendingPermissionForSession,
pauseMs,
sendTurn: sendVoiceTurn,
interrupt: interruptTurn,
onEditInTextBox: handleVoiceEditInTextBox,
})
useEffect(() => {
onVoiceConversationActiveChange?.(voiceConversation.isActive)
}, [onVoiceConversationActiveChange, voiceConversation.isActive])
const hasPromptContent = prompt.trim().length > 0 || imageAttachments.length > 0
const canUseMobileVoice = isMobile && sttEnabled && sttSupported && !hasPendingPermissionForSession
const showMobileKeys = isMobile && isPromptFocused && !hasPendingPermissionForSession && mobileVoiceRecorderState === null
const voiceButtonTitle = voiceFeedbackState === 'starting'
? 'Starting microphone'
: voiceFeedbackState === 'sending'
? 'Transcribing and sending speech'
: voiceFeedbackState === 'processing'
? 'Transcribing speech'
: voiceFeedbackState === 'readyToSend'
? 'Release to send'
: voiceFeedbackState === 'cancelArmed'
? 'Release to discard'
: voiceFeedbackState === 'recording'
? 'Tap to transcribe'
: 'Tap to speak'
const showVoiceMic = sttAvailability.isEnabled && sttAvailability.isSupported && !hasPendingPermissionForSession
const showMobileKeys = isMobile && isPromptFocused && !hasPendingPermissionForSession
const handleSendVoiceRecording = () => {
if (isRecording) {
handleVoiceSendRequest()
return
}
if (isProcessing && !isVoiceAutoSendPending) {
armVoiceAutoSend()
}
}
const renderVoiceButton = (variant: VoiceButtonVariant) => {
const isDesktop = variant === 'desktop'
const isBusy = isRecording || isTogglingRecording || (isProcessing && !isRecording)
const iconSizeClassName = isDesktop ? 'w-5 h-5' : 'w-6 h-6'
const spinnerClassName = `${iconSizeClassName} animate-spin rounded-full border-2 ${isDesktop ? 'border-muted-foreground' : 'border-foreground'} border-t-transparent`
const voiceGestureHandlers = isDesktop ? {} : {
onPointerDown: handleVoicePointerDown,
onPointerMove: handleVoicePointerMove,
onPointerUp: handleVoicePointerEnd,
onPointerCancel: (event: ReactPointerEvent<HTMLDivElement>) => handleVoicePointerEnd(event, true),
}
const buttonClassName = isDesktop
? `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 ${
isBusy
? 'bg-destructive hover:bg-destructive/90 text-destructive-foreground border-destructive/60 animate-pulse'
: 'bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border'
}`
: `min-h-11 min-w-11 px-0 rounded-lg transition-all duration-150 flex items-center justify-center border touch-none select-none ${
isBusy
? 'bg-success text-success-foreground border-success/70 shadow-lg shadow-success/40'
: 'bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border active:bg-muted-foreground/30 active:scale-95'
}`
const containerClassName = isDesktop ? 'relative hidden md:block' : 'relative flex touch-none select-none'
return (
<div
ref={voiceButtonContainerRef}
className={containerClassName}
{...voiceGestureHandlers}
>
<button
type="button"
data-voice-variant={variant}
onClick={handleVoiceClick}
disabled={isProcessing}
className={buttonClassName}
title={voiceButtonTitle}
>
{isTogglingRecording && !isRecording ? (
<div className={spinnerClassName} />
) : isProcessing && !isRecording ? (
<div className={spinnerClassName} />
) : isRecording ? (
<MicOff className={iconSizeClassName} />
) : (
<Mic className={iconSizeClassName} />
)}
</button>
</div>
)
}
const renderVoiceMic = () => (
<button
type="button"
aria-label="Start voice conversation"
title="Start voice conversation"
onMouseDown={(event) => event.preventDefault()}
onClick={() => {
textareaRef.current?.blur()
voiceConversation.start()
}}
className={isMobile
? 'min-h-11 min-w-11 px-0 rounded-lg transition-all duration-150 flex items-center justify-center border bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border active:bg-muted-foreground/30 active:scale-95'
: 'p-2 rounded-lg transition-all duration-200 active:scale-95 hover:scale-105 shadow-md border flex items-center justify-center bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border'}
>
<Mic className={isMobile ? 'w-6 h-6' : 'w-5 h-5'} />
</button>
)
const renderMobileKeys = () => (
<div role="toolbar" aria-label="Insert" className="flex flex-nowrap items-center gap-1.5 min-w-0">
@@ -1565,16 +1199,8 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
}, [prompt, onPromptChange])
useEffect(() => {
if (isRecording) {
abortRecording()
}
clearSTT()
resetVoiceGestureState()
lastAddedTranscriptRef.current = ''
setIsTogglingRecording(false)
setLocalMode(null)
setIsGoalArmed(false)
// eslint-disable-next-line react-hooks/exhaustive-deps -- Intentionally only run on sessionID change to avoid clearing transcript when recording state changes
}, [sessionID])
@@ -1600,6 +1226,14 @@ return (
{composerModeStyle.label}
</span>
)}
{voiceConversation.isActive ? (
<VoiceConversationBar
controller={voiceConversation}
hasPendingApproval={hasPendingPermissionForSession}
onViewApproval={() => setShowDialog(true)}
/>
) : (
<>
<div className="flex items-end gap-1.5 md:gap-2 mb-1.5 md:mb-2">
<textarea
ref={textareaRef}
@@ -1662,28 +1296,10 @@ return (
</div>
)}
<div ref={composerControlsRowRef} data-testid="composer-controls-row" className="relative flex gap-1.5 md:gap-2 items-center justify-between">
<div data-testid="composer-controls-row" className="relative flex gap-1.5 md:gap-2 items-center justify-between">
<ComposerActivityBar sessionID={sessionID} />
<div className="flex flex-1 md:flex-initial gap-1.5 md:gap-2 items-center min-w-0">
{mobileVoiceRecorderState ? (
<>
<button
type="button"
aria-label="Discard recording"
title="Discard recording"
onMouseDown={(e) => e.preventDefault()}
onClick={cancelVoiceInput}
className={cn(
getIconToggleButtonClassName(false),
'flex items-center justify-center size-11 p-0 flex-shrink-0',
isVoiceCancelArmed && 'bg-destructive hover:bg-destructive/90 text-destructive-foreground border-destructive',
)}
>
<X className="w-5 h-5" />
</button>
<VoiceRecorderStrip state={mobileVoiceRecorderState} startedAt={voiceRecordingStartedAt} />
</>
) : showMobileKeys ? renderMobileKeys() : (
{showMobileKeys ? renderMobileKeys() : (
<>
<AgentQuickSelect
directory={directory}
@@ -1757,30 +1373,8 @@ return (
>
<Upload className="w-5 h-5" />
</button>
{canUseMobileVoice && (
renderVoiceButton('mobile')
)}
{mobileVoiceRecorderState ? (
<button
type="button"
aria-label="Send recording"
title="Send recording"
disabled={mobileVoiceRecorderState === 'starting'}
onMouseDown={(e) => e.preventDefault()}
onClick={handleSendVoiceRecording}
className={cn(
getIconToggleButtonClassName(false),
'flex items-center justify-center size-11 p-0 flex-shrink-0',
isVoiceSendArmed && 'bg-success hover:bg-success/90 text-success-foreground border-success',
)}
>
{mobileVoiceRecorderState === 'sending' ? (
<div className="w-5 h-5 animate-spin rounded-full border-2 border-foreground border-t-transparent" />
) : (
<ArrowUp className="w-5 h-5" />
)}
</button>
) : showMobileScrollButton ? (
{showVoiceMic && renderVoiceMic()}
{showMobileScrollButton ? (
<button
type="button"
aria-label="Scroll to bottom"
@@ -1802,12 +1396,13 @@ return (
onAttachFile={openFilePicker}
/>
)}
{!isMobile && sttEnabled && sttSupported && (
renderVoiceButton('desktop')
)}
</div>
</div>
</>
)}
{!voiceConversation.isActive && (
<>
<PromptSuggestions
isOpen={showSuggestions}
items={commandSuggestions}
@@ -1833,6 +1428,8 @@ return (
setMentionRange(null)
}}
/>
</>
)}
</div>
)
}))
@@ -0,0 +1,201 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it, vi } from 'vitest'
import { VoiceConversationBar } from './VoiceConversationBar'
import type { VoiceConversationController } from '@/hooks/useVoiceConversation'
const buildController = (
overrides: Partial<VoiceConversationController> = {},
): VoiceConversationController => ({
isActive: true,
phase: 'listening',
label: 'Listening',
hint: 'Speak what you want the agent to do',
orbLabel: 'Send now',
liveTranscript: '',
canEditInTextBox: false,
canStopAgent: false,
hasHeldReading: false,
isEndpointing: false,
notice: null,
start: vi.fn(),
exit: vi.fn(),
editInTextBox: vi.fn(),
tapOrb: vi.fn(),
pause: vi.fn(),
resume: vi.fn(),
stopAgent: vi.fn(),
...overrides,
})
const renderBar = (
controller: VoiceConversationController,
props: { hasPendingApproval?: boolean; onViewApproval?: () => void } = {},
) =>
render(
<VoiceConversationBar
controller={controller}
hasPendingApproval={props.hasPendingApproval ?? false}
onViewApproval={props.onViewApproval ?? vi.fn()}
/>,
)
describe('VoiceConversationBar', () => {
it('shows the status, the hint and the live transcript', () => {
renderBar(
buildController({
label: 'Listening',
hint: 'Speak what you want the agent to do',
liveTranscript: 'add a retry to the upload call',
}),
)
expect(screen.getByText('Listening')).toBeInTheDocument()
expect(screen.getByText('Speak what you want the agent to do')).toBeInTheDocument()
expect(screen.getByText('add a retry to the upload call')).toBeInTheDocument()
})
it('hides the transcript when it is empty', () => {
const { container } = renderBar(buildController({ liveTranscript: '' }))
const status = screen.getByRole('status')
expect(status).toHaveTextContent('Listening')
expect(container.querySelector('[dir="rtl"]')).toBeNull()
})
it('announces status changes through a polite live region', () => {
renderBar(buildController({ label: 'Working' }))
const status = screen.getByRole('status')
expect(status).toHaveAttribute('aria-live', 'polite')
expect(status).toHaveTextContent('Working')
})
it('exits the conversation from the close control', async () => {
const user = userEvent.setup()
const controller = buildController()
renderBar(controller)
await user.click(screen.getByRole('button', { name: 'Exit voice conversation' }))
expect(controller.exit).toHaveBeenCalledTimes(1)
expect(controller.editInTextBox).not.toHaveBeenCalled()
})
it('swaps the close control for the edit control when the transcript can be kept', async () => {
const user = userEvent.setup()
const controller = buildController({
canEditInTextBox: true,
liveTranscript: 'half a sentence',
})
renderBar(controller)
expect(screen.queryByRole('button', { name: 'Exit voice conversation' })).toBeNull()
await user.click(screen.getByRole('button', { name: 'Edit in text box' }))
expect(controller.editInTextBox).toHaveBeenCalledTimes(1)
expect(controller.exit).not.toHaveBeenCalled()
})
it('shows the stop control only while the agent can be stopped', async () => {
const user = userEvent.setup()
const { unmount } = renderBar(buildController({ canStopAgent: false }))
expect(screen.queryByRole('button', { name: 'Stop the agent' })).toBeNull()
unmount()
const controller = buildController({ canStopAgent: true })
renderBar(controller)
await user.click(screen.getByRole('button', { name: 'Stop the agent' }))
expect(controller.stopAgent).toHaveBeenCalledTimes(1)
})
it('shows the approval control instead of pause while the session waits for approval', async () => {
const user = userEvent.setup()
const onViewApproval = vi.fn()
const controller = buildController({ phase: 'working', canStopAgent: true })
renderBar(controller, { hasPendingApproval: true, onViewApproval })
expect(screen.queryByRole('button', { name: 'Pause voice conversation' })).toBeNull()
await user.click(screen.getByRole('button', { name: 'View pending permission' }))
expect(onViewApproval).toHaveBeenCalledTimes(1)
expect(controller.pause).not.toHaveBeenCalled()
})
it('pauses the conversation outside the paused phase', async () => {
const user = userEvent.setup()
const controller = buildController({ phase: 'listening' })
renderBar(controller)
await user.click(screen.getByRole('button', { name: 'Pause voice conversation' }))
expect(controller.pause).toHaveBeenCalledTimes(1)
expect(controller.resume).not.toHaveBeenCalled()
})
it('resumes the conversation while paused', async () => {
const user = userEvent.setup()
const controller = buildController({ phase: 'paused', orbLabel: 'Resume voice conversation' })
renderBar(controller)
expect(screen.queryByRole('button', { name: 'Pause voice conversation' })).toBeNull()
await user.click(screen.getByRole('button', { name: 'Resume' }))
expect(controller.resume).toHaveBeenCalledTimes(1)
})
it('continues a held reading while paused mid-reply', () => {
renderBar(buildController({ phase: 'paused', hasHeldReading: true }))
expect(screen.getByRole('button', { name: 'Continue reading' })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Resume' })).toBeNull()
})
it('sends the orb action for the current phase when the orb is pressed', async () => {
const user = userEvent.setup()
const controller = buildController({ phase: 'working', orbLabel: 'Add a message' })
renderBar(controller)
await user.click(screen.getByRole('button', { name: 'Add a message' }))
expect(controller.tapOrb).toHaveBeenCalledTimes(1)
})
it('names the orb action for every phase', () => {
const phases = [
{ phase: 'listening', orbLabel: 'Send now' },
{ phase: 'sending', orbLabel: 'Sending' },
{ phase: 'working', orbLabel: 'Add a message' },
{ phase: 'speaking', orbLabel: 'Skip reply' },
{ phase: 'recording', orbLabel: 'Send to queue' },
{ phase: 'paused', orbLabel: 'Resume voice conversation' },
{ phase: 'off', orbLabel: 'Voice conversation' },
] as const
for (const { phase, orbLabel } of phases) {
const { unmount } = renderBar(buildController({ phase, orbLabel }))
expect(screen.getByRole('button', { name: orbLabel })).toBeInTheDocument()
unmount()
}
})
it('marks the orb busy while a turn is sent', () => {
renderBar(buildController({ phase: 'sending', orbLabel: 'Sending' }))
expect(screen.getByRole('button', { name: 'Sending' })).toHaveAttribute('aria-busy', 'true')
})
it('shows the notice when there is one and keeps the reserved hint line empty', () => {
renderBar(
buildController({
hint: '',
notice: 'Turn on speech-to-text in Voice settings',
}),
)
expect(screen.getByText('Turn on speech-to-text in Voice settings')).toBeInTheDocument()
})
})
@@ -0,0 +1,138 @@
import { Pause, Pencil, Play, X } from 'lucide-react'
import type { ReactNode } from 'react'
import { VoiceConversationOrb } from '@/components/message/VoiceConversationOrb'
import { Button } from '@/components/ui/button'
import { getIconToggleButtonClassName } from '@/components/ui/icon-toggle-button'
import { SquareFill } from '@/components/ui/square-fill'
import type { VoiceConversationController } from '@/hooks/useVoiceConversation'
import { cn } from '@/lib/utils'
const BAR_ICON_BUTTON_CLASS = cn(
getIconToggleButtonClassName(false),
'flex size-11 shrink-0 items-center justify-center p-0',
)
const RESERVED_LINE_CLASS = 'h-4 w-full truncate text-center leading-4'
interface BarIconButtonProps {
label: string
onClick: () => void
children: ReactNode
}
function BarIconButton({ label, onClick, children }: BarIconButtonProps) {
return (
<button
type="button"
aria-label={label}
title={label}
onMouseDown={(event) => event.preventDefault()}
onClick={onClick}
className={BAR_ICON_BUTTON_CLASS}
>
{children}
</button>
)
}
export interface VoiceConversationBarProps {
/** Conversation state and its controls. */
controller: VoiceConversationController
/** Whether the session waits for the user to approve a tool or a form. */
hasPendingApproval: boolean
/** Opens the pending permission dialog. */
onViewApproval: () => void
}
/**
* Shows a hands-free voice conversation under the session composer on a fixed
* block: the short status sits on the left of the first line with the latest
* dictated words on the right, the orb keeps the centre of the control row, and
* the exit or edit control, the stop control and the pause, resume or approval
* control fill the two slots beside it. The hint and the notice each keep a
* reserved line under the orb, so the bar never changes height while the
* conversation talks, works, waits or reports a problem. Status changes are
* announced to assistive technology.
*/
export function VoiceConversationBar({
controller,
hasPendingApproval,
onViewApproval,
}: VoiceConversationBarProps) {
const {
phase,
label,
hint,
orbLabel,
liveTranscript,
canEditInTextBox,
canStopAgent,
hasHeldReading,
notice,
} = controller
return (
<div className="flex flex-col gap-1 border-t border-border bg-card px-3 pt-2 pb-2">
<div role="status" aria-live="polite" className="flex h-5 items-center gap-2">
<span className="max-w-[50%] shrink-0 truncate text-xs font-semibold">{label}</span>
{liveTranscript ? (
<span
dir="rtl"
aria-hidden="true"
className="min-w-0 flex-1 truncate text-right text-xs text-muted-foreground"
>
<span dir="ltr">{liveTranscript}</span>
</span>
) : null}
</div>
<div className="grid grid-cols-3 items-center">
<div className="flex items-center gap-1">
{canEditInTextBox ? (
<BarIconButton label="Edit in text box" onClick={controller.editInTextBox}>
<Pencil className="size-5" />
</BarIconButton>
) : (
<BarIconButton label="Exit voice conversation" onClick={controller.exit}>
<X className="size-5" />
</BarIconButton>
)}
{canStopAgent ? (
<BarIconButton label="Stop the agent" onClick={controller.stopAgent}>
<SquareFill className="size-4" />
</BarIconButton>
) : null}
</div>
<div className="flex justify-center">
<VoiceConversationOrb phase={phase} label={orbLabel} onPress={controller.tapOrb} />
</div>
<div className="flex justify-end">
{hasPendingApproval ? (
<Button
type="button"
aria-label="View pending permission"
onClick={onViewApproval}
className="h-11 px-4 text-xs font-semibold shadow-md"
>
View
</Button>
) : phase === 'paused' ? (
<BarIconButton
label={hasHeldReading ? 'Continue reading' : 'Resume'}
onClick={controller.resume}
>
<Play className="size-5" />
</BarIconButton>
) : (
<BarIconButton label="Pause voice conversation" onClick={controller.pause}>
<Pause className="size-5" />
</BarIconButton>
)}
</div>
</div>
<div className="flex flex-col items-center">
<p className={cn(RESERVED_LINE_CLASS, 'text-[11px] text-muted-foreground')}>{notice ?? ''}</p>
<p className={cn(RESERVED_LINE_CLASS, 'text-xs text-muted-foreground')}>{hint}</p>
</div>
</div>
)
}
@@ -0,0 +1,119 @@
import { Hourglass, LoaderCircle, MessageSquarePlus, Mic, MicOff, Volume2 } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import type { VoicePhase } from '@opencode-manager/shared/opencode'
import { cn } from '@/lib/utils'
interface PhasePresentation {
core: string
halo: string
animation: string
}
const PHASE_PRESENTATION: Record<VoicePhase, PhasePresentation> = {
off: {
core: 'bg-muted-foreground text-background',
halo: 'bg-muted-foreground/15',
animation: '',
},
listening: {
core: 'bg-primary text-primary-foreground',
halo: 'bg-primary/15',
animation: 'animate-voice-orb-breathe',
},
sending: {
core: 'bg-primary text-primary-foreground',
halo: 'bg-primary/15',
animation: '',
},
working: {
core: 'bg-highlight text-highlight-foreground',
halo: 'bg-highlight/15',
animation: 'animate-voice-orb-work',
},
speaking: {
core: 'bg-success text-success-foreground',
halo: 'bg-success/15',
animation: 'animate-voice-orb-speak',
},
recording: {
core: 'bg-warning text-warning-foreground',
halo: 'bg-warning/15',
animation: 'animate-voice-orb-breathe',
},
paused: {
core: 'bg-muted-foreground text-background',
halo: 'bg-muted-foreground/5',
animation: '',
},
}
const PHASE_ICONS: Record<VoicePhase, LucideIcon> = {
off: MicOff,
listening: Mic,
sending: LoaderCircle,
working: Hourglass,
speaking: Volume2,
recording: MessageSquarePlus,
paused: MicOff,
}
const GLYPH_CLASS = 'size-[26px]'
export interface VoiceConversationOrbProps {
/** Current stage of the conversation loop. */
phase: VoicePhase
/** Action label read by assistive technology. */
label: string
/** Called when the orb is pressed. */
onPress: () => void
/** Whether the orb cannot be pressed. */
disabled?: boolean
}
/**
* The single control of the voice conversation bar. It carries the phase color
* and glyph, breathes gently while the microphone captures a turn, pulses slowly
* while the agent works and faster while a reply is read, and holds still in
* every other phase. Paused reads fainter through a dimmed orb and a weaker
* halo. All motion stops when the system asks for reduced motion.
*/
export function VoiceConversationOrb({
phase,
label,
onPress,
disabled = false,
}: VoiceConversationOrbProps) {
const presentation = PHASE_PRESENTATION[phase]
const Glyph = PHASE_ICONS[phase]
const motion = cn(presentation.animation, 'motion-reduce:animate-none')
return (
<button
type="button"
aria-label={label}
aria-busy={phase === 'sending'}
disabled={disabled}
onClick={onPress}
className={cn(
'relative flex size-[72px] shrink-0 items-center justify-center rounded-full transition-opacity disabled:cursor-not-allowed disabled:opacity-50',
phase === 'paused' && 'opacity-50',
)}
>
<span aria-hidden="true" className={cn('absolute inset-0 rounded-full', presentation.halo, motion)} />
<span
aria-hidden="true"
className={cn(
'relative flex size-16 items-center justify-center rounded-full shadow-md',
presentation.core,
motion,
)}
>
{phase === 'sending' ? (
<LoaderCircle className={cn(GLYPH_CLASS, 'animate-spin motion-reduce:animate-none')} />
) : (
<Glyph className={GLYPH_CLASS} />
)}
</span>
</button>
)
}
@@ -1,104 +0,0 @@
import { useEffect, useState } from 'react'
import { LoaderCircle } from 'lucide-react'
import { cn } from '@/lib/utils'
export type VoiceRecorderStripState =
| 'starting'
| 'recording'
| 'readyToSend'
| 'cancelArmed'
| 'processing'
| 'sending'
interface VoiceRecorderStripProps {
state: VoiceRecorderStripState
startedAt: number | null
}
const WAVEFORM_BAR_COUNT = 5
const WAVEFORM_BAR_DELAY_MS = 120
const STRIP_TONES: Record<VoiceRecorderStripState, string> = {
starting: 'border-border bg-muted/50 text-muted-foreground',
recording: 'border-border bg-muted/50 text-foreground',
readyToSend: 'border-success/60 bg-success/10 text-success',
cancelArmed: 'border-destructive/60 bg-destructive/10 text-destructive',
processing: 'border-border bg-muted/50 text-muted-foreground',
sending: 'border-border bg-muted/50 text-muted-foreground',
}
function WaveformBars() {
return (
<div aria-hidden="true" className="flex h-4 items-end gap-[2px] text-destructive">
{Array.from({ length: WAVEFORM_BAR_COUNT }, (_, index) => (
<span
key={index}
className="animate-voice-wave-bar h-full w-[3px] rounded-full bg-current motion-reduce:animate-none"
style={{ animationDelay: `${index * WAVEFORM_BAR_DELAY_MS}ms` }}
/>
))}
</div>
)
}
function useElapsedLabel(startedAt: number | null): string | null {
const [elapsedSeconds, setElapsedSeconds] = useState(0)
useEffect(() => {
if (startedAt === null) return
const tick = () => setElapsedSeconds(Math.max(0, Math.floor((Date.now() - startedAt) / 1000)))
tick()
const interval = setInterval(tick, 1000)
return () => clearInterval(interval)
}, [startedAt])
if (startedAt === null) return null
return `${Math.floor(elapsedSeconds / 60)}:${String(elapsedSeconds % 60).padStart(2, '0')}`
}
export function VoiceRecorderStrip({ state, startedAt }: VoiceRecorderStripProps) {
const elapsedLabel = useElapsedLabel(state === 'recording' ? startedAt : null)
return (
<div
role="status"
aria-live="polite"
className={cn(
'flex min-h-11 min-w-0 flex-1 items-center gap-2 rounded-lg border px-2.5 text-xs font-medium',
STRIP_TONES[state],
)}
>
{state === 'starting' && (
<>
<LoaderCircle className="size-4 shrink-0 animate-spin" />
<span className="truncate">Starting mic…</span>
</>
)}
{state === 'recording' && (
<>
<span aria-hidden="true" className="size-2 shrink-0 animate-pulse rounded-full bg-destructive" />
<span aria-hidden="true" className="shrink-0 font-mono tabular-nums">{elapsedLabel}</span>
<WaveformBars />
<span className="ml-auto shrink-0 truncate text-[10px] uppercase tracking-wide opacity-60">‹ discard · send ›</span>
</>
)}
{state === 'readyToSend' && <span className="truncate">Release to send</span>}
{state === 'cancelArmed' && <span className="truncate">Release to discard</span>}
{state === 'processing' && (
<>
<LoaderCircle className="size-4 shrink-0 animate-spin" />
<span className="truncate">Transcribing…</span>
</>
)}
{state === 'sending' && (
<>
<LoaderCircle className="size-4 shrink-0 animate-spin" />
<span className="truncate">Transcribing &amp; sending…</span>
</>
)}
</div>
)
}
@@ -0,0 +1,97 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { act, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { VOICE_PAUSE_STORAGE_KEY } from '@opencode-manager/shared/opencode'
import { STTSettings } from './STTSettings'
import { useSettings } from '@/hooks/useSettings'
import { useSTT } from '@/hooks/useSTT'
import { isWebRecognitionSupported, getAvailableLanguages } from '@/lib/webSpeechRecognizer'
import { createUseSettingsMock } from '@/test/test-utils'
import { DEFAULT_STT_CONFIG, DEFAULT_USER_PREFERENCES, type STTConfig, type UserPreferences } from '@/api/types/settings'
vi.mock('@/hooks/useSettings')
vi.mock('@/hooks/useSTT')
vi.mock('@/lib/webSpeechRecognizer')
vi.mock('@/api/stt', () => ({
sttApi: {
getModels: vi.fn().mockResolvedValue({ models: [] }),
transcribe: vi.fn(),
},
}))
function buildPreferences(stt: Partial<STTConfig> = {}): UserPreferences {
return {
...DEFAULT_USER_PREFERENCES,
stt: { ...DEFAULT_STT_CONFIG, ...stt },
}
}
function mockHooks(preferences: UserPreferences = buildPreferences({ enabled: true, provider: 'builtin' })) {
vi.mocked(useSettings).mockReturnValue(createUseSettingsMock({ preferences }))
vi.mocked(useSTT).mockReturnValue({
startRecording: vi.fn(),
stopRecording: vi.fn(),
abortRecording: vi.fn(),
isRecording: false,
isProcessing: false,
transcript: '',
interimTranscript: '',
error: null,
isExternalProvider: preferences.stt?.provider === 'external',
} as ReturnType<typeof useSTT>)
vi.mocked(isWebRecognitionSupported).mockReturnValue(true)
vi.mocked(getAvailableLanguages).mockReturnValue(['en-US'])
}
function getPauseSelect() {
return screen.queryByRole('combobox', { name: 'Pause before sending' })
}
async function renderSettings(preferences?: UserPreferences) {
if (preferences) {
mockHooks(preferences)
}
const rendered = render(<STTSettings />)
await act(async () => {})
return rendered
}
describe('STTSettings pause before sending', () => {
beforeEach(() => {
vi.clearAllMocks()
window.localStorage.clear()
mockHooks()
})
it('shows the pause select for the enabled built-in provider', async () => {
await renderSettings()
expect(getPauseSelect()).toHaveValue('1.2 s')
})
it('hides the pause select for the external provider', async () => {
await renderSettings(buildPreferences({ enabled: true, provider: 'external' }))
expect(getPauseSelect()).not.toBeInTheDocument()
})
it('hides the pause select when STT is disabled', async () => {
await renderSettings(buildPreferences({ enabled: false, provider: 'builtin' }))
expect(getPauseSelect()).not.toBeInTheDocument()
})
it('writes the selected pause to device-local storage', async () => {
const user = userEvent.setup()
await renderSettings()
const select = getPauseSelect()
expect(select).toHaveValue('1.2 s')
await user.click(select as HTMLElement)
await user.click(screen.getByRole('option', { name: '3.0 s' }))
expect(window.localStorage.getItem(VOICE_PAUSE_STORAGE_KEY)).toBe('3000')
expect(getPauseSelect()).toHaveValue('3.0 s')
})
})
@@ -4,13 +4,16 @@ import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useSettings } from '@/hooks/useSettings'
import { useSTT } from '@/hooks/useSTT'
import { useVoicePauseSetting } from '@/hooks/useVoicePauseSetting'
import { isWebRecognitionSupported, getAvailableLanguages } from '@/lib/webSpeechRecognizer'
import { sttApi } from '@/api/stt'
import { Mic, Loader2, XCircle, CheckCircle2, RefreshCw, Eye, EyeOff, MicOff } from 'lucide-react'
import { Switch } from '@/components/ui/switch'
import { Label } from '@/components/ui/label'
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'
import { Combobox } from '@/components/ui/combobox'
import { DEFAULT_STT_CONFIG } from '@/api/types/settings'
import { VOICE_PAUSE_OPTIONS_MS, formatVoicePauseMs } from '@opencode-manager/shared/opencode'
const sttFormSchema = z.object({
enabled: z.boolean(),
@@ -35,9 +38,15 @@ const sttFormSchema = z.object({
type STTFormValues = z.infer<typeof sttFormSchema>
const voicePauseOptions = VOICE_PAUSE_OPTIONS_MS.map((ms) => ({
value: String(ms),
label: formatVoicePauseMs(ms),
}))
export function STTSettings() {
const { preferences, updateSettings } = useSettings()
const { startRecording, stopRecording, abortRecording, isRecording, isProcessing, transcript, interimTranscript, error: sttError, isExternalProvider } = useSTT()
const { pauseMs, setPauseMs } = useVoicePauseSetting()
const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle')
const [isTesting, setIsTesting] = useState(false)
@@ -375,6 +384,21 @@ export function STTSettings() {
</FormItem>
)}
/>
<FormItem>
<Label>Pause before sending</Label>
<Combobox
value={String(pauseMs)}
onChange={(value) => setPauseMs(Number(value))}
options={voicePauseOptions}
placeholder="Select pause..."
allowCustomValue={false}
ariaLabel="Pause before sending"
/>
<p className="text-sm text-muted-foreground">
Voice conversation sends after this much silence. Uses your browser's speech recognition; other providers send when you tap.
</p>
</FormItem>
</>
)}
@@ -74,6 +74,8 @@ function mockHooks(preferences: UserPreferences = buildPreferences()) {
speakMessage: vi.fn(),
queueMessage: vi.fn(),
stop: vi.fn(),
pause: vi.fn(),
resume: vi.fn(),
state: 'idle',
error: null,
currentText: null,
@@ -83,6 +85,7 @@ function mockHooks(preferences: UserPreferences = buildPreferences()) {
isPlaying: false,
isLoading: false,
isIdle: true,
isPaused: false,
})
vi.mocked(useTTSDiscovery).mockReturnValue({
refreshModels: vi.fn(),