mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
Merge pull request #459 from chriswritescode-dev/feat/voice-conversation-mode
feat(frontend): hands-free voice conversation mode in the composer
This commit is contained in:
36 files changed
+5760
-1314
No files matched your search
@@ -273,6 +273,63 @@ export async function backgroundSession(sessionID: string, serverId?: string): P
|
||||
await callOpenCode((api) => api.session.background({ sessionID }), serverId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores one instruction entry on a session, which the model is told about at
|
||||
* the next step boundary.
|
||||
*
|
||||
* @param sessionID The session that receives the instruction.
|
||||
* @param key Stable key of the instruction entry.
|
||||
* @param text Instruction text stored under the key.
|
||||
* @param serverId Server that owns the session, when it is not the local one.
|
||||
*/
|
||||
export async function putSessionInstruction(
|
||||
sessionID: string,
|
||||
key: string,
|
||||
text: string,
|
||||
serverId?: string,
|
||||
): Promise<void> {
|
||||
await callOpenCode(
|
||||
(api) => api.session.instructions.entry.put({ sessionID, key, value: text }),
|
||||
serverId,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes one instruction entry from a session.
|
||||
*
|
||||
* @param sessionID The session that holds the instruction.
|
||||
* @param key Stable key of the instruction entry.
|
||||
* @param serverId Server that owns the session, when it is not the local one.
|
||||
*/
|
||||
export async function removeSessionInstruction(
|
||||
sessionID: string,
|
||||
key: string,
|
||||
serverId?: string,
|
||||
): Promise<void> {
|
||||
await callOpenCode(
|
||||
(api) => api.session.instructions.entry.remove({ sessionID, key }),
|
||||
serverId,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the keys of the instruction entries a session holds.
|
||||
*
|
||||
* @param sessionID The session whose instruction keys are read.
|
||||
* @param serverId Server that owns the session, when it is not the local one.
|
||||
* @returns The stored instruction keys, in the order the server reports them.
|
||||
*/
|
||||
export async function listSessionInstructionKeys(
|
||||
sessionID: string,
|
||||
serverId?: string,
|
||||
): Promise<string[]> {
|
||||
const entries = await callOpenCode(
|
||||
(api) => api.session.instructions.entry.list({ sessionID }),
|
||||
serverId,
|
||||
)
|
||||
return entries.map((entry) => entry.key)
|
||||
}
|
||||
|
||||
export async function listShells(directory: string, serverId?: string): Promise<ShellInfo[]> {
|
||||
const { data } = await callOpenCode((api) => api.shell.list(openCodeLocation(directory)), serverId)
|
||||
return data
|
||||
|
||||
@@ -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 }))
|
||||
@@ -169,6 +174,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,7 @@ const createTestQueryClient = () => new QueryClient({
|
||||
const defaultProps = {
|
||||
directory: '/test',
|
||||
sessionID: 'test-session',
|
||||
showScrollButton: false,
|
||||
showScrollButton: false,
|
||||
isSessionActive: false,
|
||||
isStreamingResponse: false,
|
||||
onScrollToBottom: vi.fn(),
|
||||
@@ -106,11 +111,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 +334,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 +368,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 +386,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 }))
|
||||
@@ -159,6 +164,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 }))
|
||||
@@ -148,6 +153,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
@@ -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,7 @@ 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 { useUserBash } from '@/stores/userBashStore'
|
||||
import { useSessionAgentStore } from '@/stores/sessionAgentStore'
|
||||
@@ -19,7 +19,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 +28,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 { VoiceConversation, type VoiceConversationHandle } from './VoiceConversation'
|
||||
import { PermissionModeToggle } from '@/components/session/PermissionModeToggle'
|
||||
import { SessionSandboxMenu } from '@/components/session/SessionSandboxMenu'
|
||||
import { ComposerToolsMenu } from './ComposerToolsMenu'
|
||||
@@ -104,13 +104,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 +118,7 @@ export interface PromptInputHandle {
|
||||
interface PromptInputProps {
|
||||
directory?: string
|
||||
sessionID: string
|
||||
onVoiceConversationActiveChange?: (active: boolean) => void
|
||||
showScrollButton?: boolean
|
||||
isSessionActive?: boolean
|
||||
isStreamingResponse?: boolean
|
||||
@@ -136,6 +130,7 @@ interface PromptInputProps {
|
||||
export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(function PromptInput({
|
||||
directory,
|
||||
sessionID,
|
||||
onVoiceConversationActiveChange,
|
||||
showScrollButton,
|
||||
isSessionActive = false,
|
||||
isStreamingResponse = false,
|
||||
@@ -158,44 +153,20 @@ 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 [isVoiceActive, setIsVoiceActive] = useState(false)
|
||||
const voiceRef = useRef<VoiceConversationHandle>(null)
|
||||
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 +177,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 +198,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
revokeBlobUrls(submittedImageAttachments)
|
||||
setImageAttachments([])
|
||||
}
|
||||
clearSTT()
|
||||
}, [clearSTT])
|
||||
}, [])
|
||||
|
||||
const pendingConfirmClearRef = useRef<{
|
||||
prompt: string
|
||||
@@ -262,7 +220,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 +354,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 +399,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
if (promptRef.current !== submittedPrompt) return
|
||||
setPrompt('')
|
||||
setIsBashMode(false)
|
||||
clearSTT()
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -527,8 +482,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 +580,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 +857,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 +1087,60 @@ 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 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
|
||||
const current = promptRef.current
|
||||
const next = current.trim() ? `${current} ${dictated}` : dictated
|
||||
setPrompt(next)
|
||||
focusPromptAt(next.length)
|
||||
}, [focusPromptAt])
|
||||
|
||||
const handleVoiceActiveChange = useCallback((active: boolean) => {
|
||||
setIsVoiceActive(active)
|
||||
onVoiceConversationActiveChange?.(active)
|
||||
}, [onVoiceConversationActiveChange])
|
||||
|
||||
const handleViewApproval = useCallback(() => {
|
||||
setShowDialog(true)
|
||||
}, [setShowDialog])
|
||||
|
||||
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()
|
||||
voiceRef.current?.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 +1186,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 +1213,20 @@ return (
|
||||
{composerModeStyle.label}
|
||||
</span>
|
||||
)}
|
||||
<VoiceConversation
|
||||
ref={voiceRef}
|
||||
sessionID={sessionID}
|
||||
serverId={serverId}
|
||||
hasPendingApproval={hasPendingPermissionForSession}
|
||||
sendTurn={sendVoiceTurn}
|
||||
interrupt={interruptTurn}
|
||||
onEditInTextBox={handleVoiceEditInTextBox}
|
||||
onViewApproval={handleViewApproval}
|
||||
onActiveChange={handleVoiceActiveChange}
|
||||
/>
|
||||
|
||||
{!isVoiceActive && (
|
||||
<>
|
||||
<div className="flex items-end gap-1.5 md:gap-2 mb-1.5 md:mb-2">
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
@@ -1662,28 +1289,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 +1366,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 +1389,13 @@ return (
|
||||
onAttachFile={openFilePicker}
|
||||
/>
|
||||
)}
|
||||
{!isMobile && sttEnabled && sttSupported && (
|
||||
renderVoiceButton('desktop')
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{!isVoiceActive && (
|
||||
<>
|
||||
<PromptSuggestions
|
||||
isOpen={showSuggestions}
|
||||
items={commandSuggestions}
|
||||
@@ -1833,6 +1421,8 @@ return (
|
||||
setMentionRange(null)
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}))
|
||||
@@ -0,0 +1,80 @@
|
||||
import { forwardRef, useEffect, useImperativeHandle } from 'react'
|
||||
import { useSessionTranscriptSnapshot } from '@/contexts/session-transcript-context'
|
||||
import { useVoiceConversation, type UseVoiceConversationInput } from '@/hooks/useVoiceConversation'
|
||||
import { useVoicePauseSetting } from '@/hooks/useVoicePauseSetting'
|
||||
import { VoiceConversationBar } from './VoiceConversationBar'
|
||||
|
||||
/** Controls the voice conversation that lives inside the session composer. */
|
||||
export interface VoiceConversationHandle {
|
||||
/** Starts the conversation loop. */
|
||||
start: () => void
|
||||
}
|
||||
|
||||
export interface VoiceConversationProps {
|
||||
/** Id of the session the conversation belongs to. */
|
||||
sessionID: string
|
||||
/** Server that owns the session, when it is not the local one. */
|
||||
serverId?: string
|
||||
/** Whether the session is waiting for the user to approve a tool or a form. */
|
||||
hasPendingApproval: boolean
|
||||
/** Sends one transcribed turn to the session. */
|
||||
sendTurn: UseVoiceConversationInput['sendTurn']
|
||||
/** Aborts the reply that the session is currently producing. */
|
||||
interrupt: UseVoiceConversationInput['interrupt']
|
||||
/** Hands a captured transcript to the composer for editing. */
|
||||
onEditInTextBox: UseVoiceConversationInput['onEditInTextBox']
|
||||
/** Opens the pending approval dialog. */
|
||||
onViewApproval: () => void
|
||||
/** Reports whether voice mode is running, including while paused. */
|
||||
onActiveChange: (active: boolean) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns the hands-free voice conversation for a session and renders its bar in
|
||||
* place of the composer while the conversation runs. It reads the transcript
|
||||
* from {@link useSessionTranscriptSnapshot}, so the composer that hosts it does
|
||||
* not re-render when the transcript changes, and it stays mounted for the whole
|
||||
* session because the conversation keeps its sweep, visibility listener and
|
||||
* cleanup effects alive between turns.
|
||||
*/
|
||||
export const VoiceConversation = forwardRef<VoiceConversationHandle, VoiceConversationProps>(
|
||||
function VoiceConversation({
|
||||
sessionID,
|
||||
serverId,
|
||||
hasPendingApproval,
|
||||
sendTurn,
|
||||
interrupt,
|
||||
onEditInTextBox,
|
||||
onViewApproval,
|
||||
onActiveChange,
|
||||
}, ref) {
|
||||
const { messages, pending, status } = useSessionTranscriptSnapshot()
|
||||
const { pauseMs } = useVoicePauseSetting()
|
||||
const controller = useVoiceConversation({
|
||||
sessionID,
|
||||
serverId,
|
||||
messages,
|
||||
pending,
|
||||
status,
|
||||
hasPendingApproval,
|
||||
pauseMs,
|
||||
sendTurn,
|
||||
interrupt,
|
||||
onEditInTextBox,
|
||||
})
|
||||
|
||||
useImperativeHandle(ref, () => ({ start: controller.start }), [controller.start])
|
||||
|
||||
useEffect(() => {
|
||||
onActiveChange(controller.isActive)
|
||||
}, [onActiveChange, controller.isActive])
|
||||
|
||||
return controller.isActive ? (
|
||||
<VoiceConversationBar
|
||||
controller={controller}
|
||||
hasPendingApproval={hasPendingApproval}
|
||||
onViewApproval={onViewApproval}
|
||||
/>
|
||||
) : null
|
||||
},
|
||||
)
|
||||
@@ -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 & 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(),
|
||||
|
||||
@@ -11,6 +11,8 @@ const mocks = vi.hoisted(() => ({
|
||||
|
||||
const webSpeech = vi.hoisted(() => ({
|
||||
stop: vi.fn(),
|
||||
pause: vi.fn(),
|
||||
resume: vi.fn(),
|
||||
clearCallbacks: vi.fn(),
|
||||
waitForVoices: vi.fn(() => Promise.resolve()),
|
||||
onEnd: vi.fn(),
|
||||
@@ -303,6 +305,234 @@ describe('TTSProvider playback isolation', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('TTSProvider message completion', () => {
|
||||
it('reports completion once after the last chunk finishes', async () => {
|
||||
setPreferences()
|
||||
renderProvider()
|
||||
const onEnd = vi.fn()
|
||||
|
||||
await act(async () => {
|
||||
await ttsRef.current!.speakMessage('A', textA, { onEnd })
|
||||
})
|
||||
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThan(index))
|
||||
const audio = FakeAudio.instances[index]
|
||||
await waitFor(() => expect(audio.paused).toBe(false))
|
||||
expect(onEnd).not.toHaveBeenCalled()
|
||||
await act(async () => {
|
||||
audio.onended!()
|
||||
})
|
||||
}
|
||||
|
||||
await waitFor(() => expect(onEnd).toHaveBeenCalledTimes(1))
|
||||
expect(onEnd).toHaveBeenCalledWith('completed')
|
||||
expect(ttsRef.current!.state).toBe('idle')
|
||||
})
|
||||
|
||||
it('reports a stop once and ignores the stale chunk end', async () => {
|
||||
setPreferences()
|
||||
renderProvider()
|
||||
const onEnd = vi.fn()
|
||||
|
||||
await act(async () => {
|
||||
await ttsRef.current!.speakMessage('A', textA, { onEnd })
|
||||
})
|
||||
|
||||
await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThanOrEqual(1))
|
||||
const firstAudio = FakeAudio.instances[0]
|
||||
await waitFor(() => expect(firstAudio.paused).toBe(false))
|
||||
const staleOnended = firstAudio.onended
|
||||
|
||||
await act(async () => {
|
||||
ttsRef.current!.stop()
|
||||
})
|
||||
|
||||
expect(onEnd).toHaveBeenCalledTimes(1)
|
||||
expect(onEnd).toHaveBeenCalledWith('stopped')
|
||||
|
||||
await act(async () => {
|
||||
staleOnended!()
|
||||
})
|
||||
|
||||
expect(onEnd).toHaveBeenCalledTimes(1)
|
||||
expect(ttsRef.current!.state).toBe('idle')
|
||||
})
|
||||
|
||||
it('reports the replaced message as stopped without settling the new one', async () => {
|
||||
setPreferences()
|
||||
renderProvider()
|
||||
const onEndA = vi.fn()
|
||||
const onEndB = vi.fn()
|
||||
|
||||
await act(async () => {
|
||||
await ttsRef.current!.speakMessage('A', textA, { onEnd: onEndA })
|
||||
})
|
||||
|
||||
await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThanOrEqual(1))
|
||||
const firstAudio = FakeAudio.instances[0]
|
||||
await waitFor(() => expect(firstAudio.paused).toBe(false))
|
||||
const staleOnended = firstAudio.onended
|
||||
|
||||
await act(async () => {
|
||||
await ttsRef.current!.speakMessage('B', textB, { onEnd: onEndB })
|
||||
})
|
||||
|
||||
expect(onEndA).toHaveBeenCalledTimes(1)
|
||||
expect(onEndA).toHaveBeenCalledWith('stopped')
|
||||
expect(onEndB).not.toHaveBeenCalled()
|
||||
|
||||
await act(async () => {
|
||||
staleOnended!()
|
||||
})
|
||||
|
||||
expect(onEndA).toHaveBeenCalledTimes(1)
|
||||
expect(onEndB).not.toHaveBeenCalled()
|
||||
expect(ttsRef.current!.activeMessageId).toBe('B')
|
||||
})
|
||||
|
||||
it('clears the paused state and reports a stop when stopped while paused', async () => {
|
||||
setPreferences()
|
||||
renderProvider()
|
||||
const onEnd = vi.fn()
|
||||
|
||||
await act(async () => {
|
||||
await ttsRef.current!.speakMessage('A', textA, { onEnd })
|
||||
})
|
||||
|
||||
await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThanOrEqual(1))
|
||||
const firstAudio = FakeAudio.instances[0]
|
||||
await waitFor(() => expect(firstAudio.paused).toBe(false))
|
||||
|
||||
await act(async () => {
|
||||
ttsRef.current!.pause()
|
||||
})
|
||||
|
||||
expect(ttsRef.current!.isPaused).toBe(true)
|
||||
|
||||
await act(async () => {
|
||||
ttsRef.current!.stop()
|
||||
})
|
||||
|
||||
expect(ttsRef.current!.isPaused).toBe(false)
|
||||
expect(onEnd).toHaveBeenCalledTimes(1)
|
||||
expect(onEnd).toHaveBeenCalledWith('stopped')
|
||||
})
|
||||
})
|
||||
|
||||
describe('TTSProvider pause and resume', () => {
|
||||
it('pauses the current chunk and resumes it without restarting the message', async () => {
|
||||
setPreferences()
|
||||
renderProvider()
|
||||
|
||||
await act(async () => {
|
||||
await ttsRef.current!.speakMessage('A', textA)
|
||||
})
|
||||
|
||||
await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThanOrEqual(1))
|
||||
const firstAudio = FakeAudio.instances[0]
|
||||
await waitFor(() => expect(firstAudio.paused).toBe(false))
|
||||
const instanceCount = FakeAudio.instances.length
|
||||
|
||||
await act(async () => {
|
||||
ttsRef.current!.pause()
|
||||
})
|
||||
|
||||
expect(ttsRef.current!.isPaused).toBe(true)
|
||||
expect(ttsRef.current!.isPlaying).toBe(true)
|
||||
expect(firstAudio.pause).toHaveBeenCalled()
|
||||
expect(firstAudio.paused).toBe(true)
|
||||
|
||||
const playCallsWhilePaused = firstAudio.play.mock.calls.length
|
||||
|
||||
await act(async () => {
|
||||
ttsRef.current!.resume()
|
||||
})
|
||||
|
||||
expect(ttsRef.current!.isPaused).toBe(false)
|
||||
expect(firstAudio.play.mock.calls.length).toBe(playCallsWhilePaused + 1)
|
||||
expect(firstAudio.paused).toBe(false)
|
||||
expect(FakeAudio.instances).toHaveLength(instanceCount)
|
||||
expect(fetchBodies.filter((text) => text === 'Alpha one. Alpha two.')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('holds the next chunk until resumed when paused between chunks', async () => {
|
||||
setPreferences()
|
||||
renderProvider()
|
||||
|
||||
await act(async () => {
|
||||
await ttsRef.current!.speakMessage('A', textA)
|
||||
})
|
||||
|
||||
await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThanOrEqual(1))
|
||||
const firstAudio = FakeAudio.instances[0]
|
||||
await waitFor(() => expect(firstAudio.paused).toBe(false))
|
||||
|
||||
await act(async () => {
|
||||
ttsRef.current!.pause()
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
firstAudio.onended!()
|
||||
})
|
||||
|
||||
await waitFor(() => expect(FakeAudio.instances.length).toBeGreaterThanOrEqual(2))
|
||||
const secondAudio = FakeAudio.instances[1]
|
||||
|
||||
expect(secondAudio.play).not.toHaveBeenCalled()
|
||||
expect(secondAudio.paused).toBe(true)
|
||||
expect(ttsRef.current!.isPaused).toBe(true)
|
||||
expect(ttsRef.current!.activeMessageId).toBe('A')
|
||||
|
||||
await act(async () => {
|
||||
ttsRef.current!.resume()
|
||||
})
|
||||
|
||||
expect(secondAudio.play).toHaveBeenCalledTimes(1)
|
||||
expect(secondAudio.paused).toBe(false)
|
||||
expect(ttsRef.current!.isPaused).toBe(false)
|
||||
})
|
||||
|
||||
it('delegates pause and resume to the synthesizer for builtin playback', async () => {
|
||||
setPreferences({ provider: 'builtin' })
|
||||
renderProvider()
|
||||
|
||||
let releaseSpeech: () => void = () => {}
|
||||
webSpeech.speakChunked.mockImplementationOnce(
|
||||
() => new Promise<void>((resolve) => {
|
||||
releaseSpeech = resolve
|
||||
}),
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
void ttsRef.current!.speakWithConfig('Hello from builtin speech.', builtinConfig)
|
||||
})
|
||||
|
||||
await waitFor(() => expect(ttsRef.current!.isPlaying).toBe(true))
|
||||
|
||||
await act(async () => {
|
||||
ttsRef.current!.pause()
|
||||
})
|
||||
|
||||
expect(webSpeech.pause).toHaveBeenCalledTimes(1)
|
||||
expect(ttsRef.current!.isPaused).toBe(true)
|
||||
|
||||
await act(async () => {
|
||||
ttsRef.current!.resume()
|
||||
})
|
||||
|
||||
expect(webSpeech.resume).toHaveBeenCalledTimes(1)
|
||||
expect(ttsRef.current!.isPaused).toBe(false)
|
||||
|
||||
await act(async () => {
|
||||
releaseSpeech()
|
||||
await Promise.resolve()
|
||||
})
|
||||
|
||||
await waitFor(() => expect(ttsRef.current!.isIdle).toBe(true))
|
||||
})
|
||||
})
|
||||
|
||||
describe('TTSProvider message queue', () => {
|
||||
const QUEUE_PAUSE_MS = 600
|
||||
const firstText = 'Alpha plays first.'
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
import { useState, useRef, useCallback, useEffect, type ReactNode } from 'react'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { TTSContext, type TTSState, type TTSConfig } from './tts-context'
|
||||
import { TTSContext, type TTSState, type TTSConfig, type TTSEndReason, type SpeakMessageOptions } from './tts-context'
|
||||
import { sanitizeForTTS } from '@/lib/utils'
|
||||
import { getWebSpeechSynthesizer, isWebSpeechSupported } from '@/lib/webSpeechSynthesizer'
|
||||
|
||||
export { TTSContext, type TTSContextValue, type TTSState, type TTSConfig } from './tts-context'
|
||||
export {
|
||||
TTSContext,
|
||||
type TTSContextValue,
|
||||
type TTSState,
|
||||
type TTSConfig,
|
||||
type TTSEndReason,
|
||||
type SpeakMessageOptions,
|
||||
} from './tts-context'
|
||||
|
||||
const SENTENCE_REGEX = /(?<=[.!?])\s+/
|
||||
const SENTENCES_PER_CHUNK = 2
|
||||
@@ -16,6 +23,10 @@ interface QueuedMessage {
|
||||
text: string
|
||||
}
|
||||
|
||||
interface SpeechRequest {
|
||||
onEnd?: (reason: TTSEndReason) => void
|
||||
}
|
||||
|
||||
function splitIntoChunks(text: string): string[] {
|
||||
const sentences = text.split(SENTENCE_REGEX).filter(s => s.trim().length > 0)
|
||||
if (sentences.length === 0) return [text]
|
||||
@@ -40,6 +51,7 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
const [currentText, setCurrentText] = useState<string | null>(null)
|
||||
const [originalText, setOriginalText] = useState<string | null>(null)
|
||||
const [activeMessageId, setActiveMessageId] = useState<string | null>(null)
|
||||
const [isPaused, setIsPaused] = useState(false)
|
||||
|
||||
const abortControllerRef = useRef<AbortController | null>(null)
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null)
|
||||
@@ -52,6 +64,9 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
const busyRef = useRef(false)
|
||||
const advanceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const playMessageRef = useRef<((messageId: string, text: string) => Promise<boolean>) | null>(null)
|
||||
const speechRequestRef = useRef<SpeechRequest | null>(null)
|
||||
const activeProviderRef = useRef<TTSConfig['provider'] | null>(null)
|
||||
const pausedRef = useRef(false)
|
||||
|
||||
// Web Speech API reference
|
||||
const webSpeechSynthRef = useRef<ReturnType<typeof getWebSpeechSynthesizer> | null>(null)
|
||||
@@ -104,6 +119,18 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
chunkIndexRef.current = 0
|
||||
}, [])
|
||||
|
||||
const settleSpeechRequest = useCallback((reason: TTSEndReason) => {
|
||||
const request = speechRequestRef.current
|
||||
speechRequestRef.current = null
|
||||
request?.onEnd?.(reason)
|
||||
}, [])
|
||||
|
||||
const beginSpeechRequest = useCallback((onEnd?: (reason: TTSEndReason) => void) => {
|
||||
const previous = speechRequestRef.current
|
||||
speechRequestRef.current = { onEnd }
|
||||
previous?.onEnd?.('stopped')
|
||||
}, [])
|
||||
|
||||
const clearAdvanceTimer = useCallback(() => {
|
||||
if (advanceTimerRef.current !== null) {
|
||||
clearTimeout(advanceTimerRef.current)
|
||||
@@ -120,6 +147,9 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
clearAdvanceTimer()
|
||||
playbackIdRef.current += 1
|
||||
cleanup()
|
||||
activeProviderRef.current = null
|
||||
pausedRef.current = false
|
||||
setIsPaused(false)
|
||||
setState('idle')
|
||||
setCurrentText(null)
|
||||
setOriginalText(null)
|
||||
@@ -128,16 +158,21 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
}, [cleanup, clearAdvanceTimer])
|
||||
|
||||
const stop = useCallback(() => {
|
||||
settleSpeechRequest('stopped')
|
||||
clearQueue()
|
||||
busyRef.current = false
|
||||
resetPlayback()
|
||||
}, [clearQueue, resetPlayback])
|
||||
}, [clearQueue, resetPlayback, settleSpeechRequest])
|
||||
|
||||
const failPlayback = useCallback(() => {
|
||||
clearQueue()
|
||||
busyRef.current = false
|
||||
activeProviderRef.current = null
|
||||
pausedRef.current = false
|
||||
setIsPaused(false)
|
||||
setActiveMessageId(null)
|
||||
}, [clearQueue])
|
||||
settleSpeechRequest('error')
|
||||
}, [clearQueue, settleSpeechRequest])
|
||||
|
||||
const advanceQueue = useCallback((playbackId: number) => {
|
||||
if (playbackIdRef.current !== playbackId) return
|
||||
@@ -145,6 +180,9 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
clearAdvanceTimer()
|
||||
const next = queueRef.current.shift()
|
||||
|
||||
activeProviderRef.current = null
|
||||
pausedRef.current = false
|
||||
setIsPaused(false)
|
||||
setState('idle')
|
||||
setCurrentText(null)
|
||||
setActiveMessageId(null)
|
||||
@@ -163,13 +201,14 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
settleSpeechRequest('stopped')
|
||||
clearAdvanceTimer()
|
||||
queueRef.current = []
|
||||
busyRef.current = false
|
||||
playbackIdRef.current += 1
|
||||
cleanup()
|
||||
}
|
||||
}, [cleanup, clearAdvanceTimer])
|
||||
}, [cleanup, clearAdvanceTimer, settleSpeechRequest])
|
||||
|
||||
// External API synthesis
|
||||
const synthesizeExternal = useCallback(async (text: string, signal: AbortSignal | undefined, playbackId: number): Promise<Blob | null> => {
|
||||
@@ -244,6 +283,7 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
|
||||
if (index >= chunksRef.current.length) {
|
||||
advanceQueue(playbackId)
|
||||
settleSpeechRequest('completed')
|
||||
return
|
||||
}
|
||||
|
||||
@@ -292,14 +332,16 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
}
|
||||
|
||||
setState('playing')
|
||||
await audio.play()
|
||||
if (!pausedRef.current) {
|
||||
await audio.play()
|
||||
}
|
||||
} catch (err) {
|
||||
if (playbackIdRef.current !== playbackId) return
|
||||
failPlayback()
|
||||
setError(err instanceof Error ? err.message : 'TTS failed')
|
||||
setState('error')
|
||||
}
|
||||
}, [getChunkAudio, prefetchChunk, advanceQueue, failPlayback])
|
||||
}, [getChunkAudio, prefetchChunk, advanceQueue, failPlayback, settleSpeechRequest])
|
||||
|
||||
// Builtin Web Speech synthesis - takes explicit config and optional messageId
|
||||
const speakBuiltinWithConfig = useCallback(async (text: string, config: TTSConfig, messageId: string | null = null): Promise<boolean> => {
|
||||
@@ -328,6 +370,7 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
|
||||
resetPlayback()
|
||||
busyRef.current = true
|
||||
activeProviderRef.current = 'builtin'
|
||||
const playbackId = playbackIdRef.current
|
||||
setError(null)
|
||||
|
||||
@@ -349,11 +392,6 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
|
||||
synth.clearCallbacks()
|
||||
|
||||
synth.onEnd(() => {
|
||||
if (playbackIdRef.current !== playbackId) return
|
||||
advanceQueue(playbackId)
|
||||
})
|
||||
|
||||
synth.onError((err) => {
|
||||
if (playbackIdRef.current !== playbackId) return
|
||||
failPlayback()
|
||||
@@ -371,6 +409,10 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
rate: rate,
|
||||
})
|
||||
|
||||
if (playbackIdRef.current !== playbackId) return false
|
||||
|
||||
advanceQueue(playbackId)
|
||||
settleSpeechRequest('completed')
|
||||
return true
|
||||
} catch (err) {
|
||||
if (playbackIdRef.current !== playbackId) return false
|
||||
@@ -379,12 +421,13 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
setState('error')
|
||||
return false
|
||||
}
|
||||
}, [resetPlayback, advanceQueue, failPlayback, getSynthesizer])
|
||||
}, [resetPlayback, advanceQueue, failPlayback, getSynthesizer, settleSpeechRequest])
|
||||
|
||||
// Internal helper to start external TTS playback
|
||||
const startExternalPlayback = useCallback((sanitizedText: string, original: string, messageId: string | null): boolean => {
|
||||
resetPlayback()
|
||||
busyRef.current = true
|
||||
activeProviderRef.current = 'external'
|
||||
const playbackId = playbackIdRef.current
|
||||
setError(null)
|
||||
|
||||
@@ -483,27 +526,72 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
|
||||
const speakWithConfig = useCallback(async (text: string, config: TTSConfig): Promise<boolean> => {
|
||||
clearQueue()
|
||||
beginSpeechRequest()
|
||||
return playWithConfig(text, config)
|
||||
}, [clearQueue, playWithConfig])
|
||||
}, [clearQueue, beginSpeechRequest, playWithConfig])
|
||||
|
||||
const speakMessage = useCallback(async (messageId: string, text: string): Promise<boolean> => {
|
||||
const speakMessage = useCallback(async (
|
||||
messageId: string,
|
||||
text: string,
|
||||
options?: SpeakMessageOptions,
|
||||
): Promise<boolean> => {
|
||||
clearQueue()
|
||||
beginSpeechRequest(options?.onEnd)
|
||||
return playMessage(messageId, text)
|
||||
}, [clearQueue, playMessage])
|
||||
}, [clearQueue, beginSpeechRequest, playMessage])
|
||||
|
||||
const speak = useCallback(async (text: string): Promise<boolean> => {
|
||||
clearQueue()
|
||||
beginSpeechRequest()
|
||||
|
||||
const config = buildStoredConfig()
|
||||
|
||||
if (!config) {
|
||||
failPlayback()
|
||||
setError('TTS is not configured')
|
||||
setState('error')
|
||||
return false
|
||||
}
|
||||
|
||||
return playWithConfig(text, config)
|
||||
}, [clearQueue, buildStoredConfig, playWithConfig])
|
||||
}, [clearQueue, beginSpeechRequest, buildStoredConfig, playWithConfig, failPlayback])
|
||||
|
||||
const pause = useCallback(() => {
|
||||
if (pausedRef.current) return
|
||||
|
||||
const provider = activeProviderRef.current
|
||||
if (!provider) return
|
||||
|
||||
if (provider === 'builtin') {
|
||||
getSynthesizer().pause()
|
||||
} else {
|
||||
audioRef.current?.pause()
|
||||
}
|
||||
|
||||
pausedRef.current = true
|
||||
setIsPaused(true)
|
||||
}, [getSynthesizer])
|
||||
|
||||
const resume = useCallback(() => {
|
||||
if (!pausedRef.current) return
|
||||
|
||||
pausedRef.current = false
|
||||
setIsPaused(false)
|
||||
|
||||
if (activeProviderRef.current === 'builtin') {
|
||||
getSynthesizer().resume()
|
||||
return
|
||||
}
|
||||
|
||||
const audio = audioRef.current
|
||||
if (!audio) return
|
||||
|
||||
void audio.play().catch((err: unknown) => {
|
||||
failPlayback()
|
||||
setError(err instanceof Error ? err.message : 'TTS failed')
|
||||
setState('error')
|
||||
})
|
||||
}, [getSynthesizer, failPlayback])
|
||||
|
||||
const queueMessage = useCallback((messageId: string, text: string) => {
|
||||
if (messageId === activeMessageId || queueRef.current.some((item) => item.messageId === messageId)) {
|
||||
@@ -524,6 +612,8 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
speakMessage,
|
||||
queueMessage,
|
||||
stop,
|
||||
pause,
|
||||
resume,
|
||||
state,
|
||||
error,
|
||||
currentText,
|
||||
@@ -533,6 +623,7 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
isPlaying: state === 'playing',
|
||||
isLoading: state === 'loading',
|
||||
isIdle: state === 'idle',
|
||||
isPaused,
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { createContext, useContext } from 'react'
|
||||
import type { SessionInboxInfo, SessionMessageInfo, VoiceSessionStatus } from '@opencode-manager/shared/opencode'
|
||||
|
||||
/** The live session transcript a voice conversation reads while it runs. */
|
||||
export interface SessionTranscriptSnapshot {
|
||||
/** The session transcript, oldest first. */
|
||||
messages: SessionMessageInfo[]
|
||||
/** Prompts the user queued on the session that have not started yet. */
|
||||
pending: SessionInboxInfo[]
|
||||
/** Reported status of the conversation's session. */
|
||||
status: VoiceSessionStatus
|
||||
}
|
||||
|
||||
const EMPTY_TRANSCRIPT_SNAPSHOT: SessionTranscriptSnapshot = { messages: [], pending: [], status: 'idle' }
|
||||
|
||||
/** Transcript snapshot published to the composer's voice conversation. */
|
||||
export const SessionTranscriptContext = createContext<SessionTranscriptSnapshot>(EMPTY_TRANSCRIPT_SNAPSHOT)
|
||||
|
||||
/**
|
||||
* Reads the session transcript published by the surrounding provider, falling
|
||||
* back to an empty idle transcript when there is none.
|
||||
*/
|
||||
export function useSessionTranscriptSnapshot(): SessionTranscriptSnapshot {
|
||||
return useContext(SessionTranscriptContext)
|
||||
}
|
||||
@@ -2,6 +2,12 @@ import { createContext } from 'react'
|
||||
|
||||
export type TTSState = 'idle' | 'loading' | 'playing' | 'error'
|
||||
|
||||
export type TTSEndReason = 'completed' | 'stopped' | 'error'
|
||||
|
||||
export interface SpeakMessageOptions {
|
||||
onEnd?: (reason: TTSEndReason) => void
|
||||
}
|
||||
|
||||
export interface TTSConfig {
|
||||
enabled: boolean
|
||||
provider: 'external' | 'builtin'
|
||||
@@ -15,9 +21,11 @@ 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>
|
||||
speakMessage: (messageId: string, text: string, options?: SpeakMessageOptions) => Promise<boolean>
|
||||
queueMessage: (messageId: string, text: string) => void
|
||||
stop: () => void
|
||||
pause: () => void
|
||||
resume: () => void
|
||||
state: TTSState
|
||||
error: string | null
|
||||
currentText: string | null
|
||||
@@ -27,6 +35,7 @@ export interface TTSContextValue {
|
||||
isPlaying: boolean
|
||||
isLoading: boolean
|
||||
isIdle: boolean
|
||||
isPaused: boolean
|
||||
}
|
||||
|
||||
export const TTSContext = createContext<TTSContextValue | null>(null)
|
||||
@@ -27,7 +27,7 @@ interface MockTTSReturn {
|
||||
activeMessageId: string | null
|
||||
}
|
||||
|
||||
import { getLatestPlayableAssistantMessage, useAutoPlayLastResponse } from '../useAutoPlayLastResponse'
|
||||
import { getAssistantText, getLatestPlayableAssistantMessage, useAutoPlayLastResponse } from '../useAutoPlayLastResponse'
|
||||
|
||||
const createMessage = (
|
||||
id: string,
|
||||
@@ -147,6 +147,139 @@ describe('useAutoPlayLastResponse', () => {
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does NOT call queueMessage while auto-play is disabled', () => {
|
||||
setup()
|
||||
|
||||
const { rerender } = renderHook(
|
||||
(props) => useAutoPlayLastResponse(props),
|
||||
{
|
||||
initialProps: {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: createMessage('1'),
|
||||
lastAssistantText: 'Test text',
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: createMessage('1', Date.now()),
|
||||
lastAssistantText: 'Test text',
|
||||
enabled: false,
|
||||
})
|
||||
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does NOT queue a reply that completed while voice mode owned playback when enabled turns back on', () => {
|
||||
setup()
|
||||
|
||||
const baselineMessage = createMessage('0', Date.now())
|
||||
const streamingMessage = createMessage('1')
|
||||
const completedMessage = createMessage('1', Date.now())
|
||||
const { rerender } = renderHook(
|
||||
(props) => useAutoPlayLastResponse(props),
|
||||
{
|
||||
initialProps: {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: baselineMessage,
|
||||
lastAssistantText: 'Earlier reply',
|
||||
enabled: true,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: streamingMessage,
|
||||
lastAssistantText: 'Read by voice mode',
|
||||
enabled: false,
|
||||
})
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: completedMessage,
|
||||
lastAssistantText: 'Read by voice mode',
|
||||
enabled: false,
|
||||
})
|
||||
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: completedMessage,
|
||||
lastAssistantText: 'Read by voice mode',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('queues a reply that was still streaming when voice mode handed playback back, once it completes', () => {
|
||||
setup()
|
||||
|
||||
const streamingMessage = createMessage('1')
|
||||
const { rerender } = renderHook(
|
||||
(props) => useAutoPlayLastResponse(props),
|
||||
{
|
||||
initialProps: {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: streamingMessage,
|
||||
lastAssistantText: 'Test text',
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: streamingMessage,
|
||||
lastAssistantText: 'Test text',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: createMessage('1', Date.now()),
|
||||
lastAssistantText: 'Test text',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
expect(mockQueueMessage).toHaveBeenCalledTimes(1)
|
||||
expect(mockQueueMessage).toHaveBeenCalledWith('1', 'Test text')
|
||||
})
|
||||
|
||||
it('queues a reply with its inline think block stripped', () => {
|
||||
setup()
|
||||
|
||||
const streamingMessage = createMessage('1', undefined, 'The answer is ready <think>hidden reasoning</think> and verified')
|
||||
const { rerender } = renderHook(
|
||||
(props) => useAutoPlayLastResponse(props),
|
||||
{
|
||||
initialProps: {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: streamingMessage,
|
||||
lastAssistantText: getAssistantText(streamingMessage),
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
const completedMessage = createMessage('1', Date.now(), 'The answer is ready <think>hidden reasoning</think> and verified')
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: completedMessage,
|
||||
lastAssistantText: getAssistantText(completedMessage),
|
||||
})
|
||||
|
||||
expect(mockQueueMessage).toHaveBeenCalledTimes(1)
|
||||
expect(mockQueueMessage).toHaveBeenCalledWith('1', 'The answer is ready and verified')
|
||||
})
|
||||
|
||||
it('does NOT call queueMessage on mount when last message was already time.completed', () => {
|
||||
setup()
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ interface UseAutoPlayLastResponseParams {
|
||||
sessionId: string
|
||||
lastAssistantMessage: SessionMessageInfo | undefined
|
||||
lastAssistantText: string
|
||||
/** Whether a finished reply may start playing; false while hands-free voice owns playback. */
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
interface PlayableAssistantMessage {
|
||||
@@ -15,7 +17,7 @@ interface PlayableAssistantMessage {
|
||||
}
|
||||
|
||||
export function getAssistantText(message: SessionMessageInfo | undefined): string {
|
||||
return message?.type === 'assistant' ? assistantText(message.content) : ''
|
||||
return message?.type === 'assistant' ? assistantText(message.content, { stripThink: true }) : ''
|
||||
}
|
||||
|
||||
export function getLatestPlayableAssistantMessage(messages: SessionMessageInfo[] | undefined): PlayableAssistantMessage | undefined {
|
||||
@@ -34,6 +36,7 @@ export function useAutoPlayLastResponse({
|
||||
sessionId,
|
||||
lastAssistantMessage,
|
||||
lastAssistantText,
|
||||
enabled = true,
|
||||
}: UseAutoPlayLastResponseParams): void {
|
||||
const { queueMessage, isEnabled: ttsEnabled, isPlaying, isLoading, activeMessageId } = useTTS()
|
||||
const { preferences } = useSettings()
|
||||
@@ -70,10 +73,19 @@ export function useAutoPlayLastResponse({
|
||||
}, [sessionId])
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
if (lastAssistantMessage && isMessageCompleted(lastAssistantMessage)) {
|
||||
hasInitializedRef.current = true
|
||||
lastSpokenIdRef.current = lastAssistantMessage.id
|
||||
lastKnownCompletedRef.current[lastAssistantMessage.id] = true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (!ttsEnabled || !autoPlayEnabled) {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
if (!lastAssistantMessage) {
|
||||
return
|
||||
}
|
||||
@@ -119,6 +131,7 @@ export function useAutoPlayLastResponse({
|
||||
}
|
||||
}
|
||||
}, [
|
||||
enabled,
|
||||
ttsEnabled,
|
||||
autoPlayEnabled,
|
||||
lastAssistantMessage,
|
||||
|
||||
@@ -119,6 +119,27 @@ describe('useSTT external provider lifecycle', () => {
|
||||
expect(mockRecorder.start).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('stays tap-to-send with the external provider even when endpointing is requested', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
const onEndOfSpeech = vi.fn()
|
||||
|
||||
let started: boolean | undefined
|
||||
await act(async () => {
|
||||
started = await result.current.startRecording({
|
||||
endpointing: { pauseMs: 800, noSpeechTimeoutMs: 5000 },
|
||||
onEndOfSpeech,
|
||||
})
|
||||
})
|
||||
|
||||
const recognizerInstance = mocks.getWebSpeechRecognizer.mock.results[0].value as { start: ReturnType<typeof vi.fn> }
|
||||
|
||||
expect(started).toBe(true)
|
||||
expect(result.current.isEndpointing).toBe(false)
|
||||
expect(mockRecorder.start).toHaveBeenCalledTimes(1)
|
||||
expect(recognizerInstance.start).not.toHaveBeenCalled()
|
||||
expect(onEndOfSpeech).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('clears processing without an error when no speech is detected', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
|
||||
@@ -451,4 +472,136 @@ describe('useSTT builtin provider lifecycle', () => {
|
||||
expect(result.current.isProcessing).toBe(false)
|
||||
expect(result.current.state).toBe('idle')
|
||||
})
|
||||
|
||||
it('keeps the default start options when endpointing is not requested', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
|
||||
await act(async () => {
|
||||
await result.current.startRecording()
|
||||
})
|
||||
|
||||
expect(result.current.isEndpointing).toBe(false)
|
||||
expect(mockRecognizer.start).toHaveBeenCalledWith({
|
||||
language: 'en-US',
|
||||
interimResults: true,
|
||||
maxAlternatives: 1,
|
||||
})
|
||||
})
|
||||
|
||||
it('applies endpointing to the browser provider and clears it when capture ends', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
const endpointing = { pauseMs: 800, noSpeechTimeoutMs: 5000 }
|
||||
|
||||
let started: boolean | undefined
|
||||
await act(async () => {
|
||||
started = await result.current.startRecording({ endpointing, onEndOfSpeech: vi.fn() })
|
||||
})
|
||||
|
||||
expect(started).toBe(true)
|
||||
expect(result.current.isEndpointing).toBe(true)
|
||||
expect(mockRecognizer.start).toHaveBeenCalledWith({
|
||||
language: 'en-US',
|
||||
interimResults: true,
|
||||
maxAlternatives: 1,
|
||||
inactivityTimeoutMs: 800,
|
||||
endpointing,
|
||||
onEndOfSpeech: expect.any(Function),
|
||||
})
|
||||
|
||||
act(() => {
|
||||
registeredCallbacks.onStart[0]()
|
||||
})
|
||||
|
||||
expect(result.current.isRecording).toBe(true)
|
||||
expect(result.current.isEndpointing).toBe(true)
|
||||
|
||||
act(() => {
|
||||
registeredCallbacks.onEnd[0]()
|
||||
})
|
||||
|
||||
expect(result.current.isEndpointing).toBe(false)
|
||||
})
|
||||
|
||||
it('delivers the final transcript when the recognizer reports a pause endpoint', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
const onEndOfSpeech = vi.fn()
|
||||
|
||||
await act(async () => {
|
||||
await result.current.startRecording({
|
||||
endpointing: { pauseMs: 800, noSpeechTimeoutMs: 5000 },
|
||||
onEndOfSpeech,
|
||||
})
|
||||
})
|
||||
|
||||
const startOptions = mockRecognizer.start.mock.calls[0][0] as {
|
||||
onEndOfSpeech: (reason: string, finalText: string) => void
|
||||
}
|
||||
|
||||
act(() => {
|
||||
registeredCallbacks.onStart[0]()
|
||||
registeredCallbacks.onResult[0]({ transcript: 'hello world', isFinal: true, confidence: 1 })
|
||||
})
|
||||
|
||||
act(() => {
|
||||
startOptions.onEndOfSpeech('pause', 'hello world')
|
||||
registeredCallbacks.onEnd[0]()
|
||||
})
|
||||
|
||||
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
|
||||
expect(onEndOfSpeech).toHaveBeenCalledWith('pause', 'hello world')
|
||||
expect(result.current.transcript).toBe('hello world')
|
||||
expect(result.current.isEndpointing).toBe(false)
|
||||
expect(result.current.isError).toBe(false)
|
||||
})
|
||||
|
||||
it('reports a no-speech endpoint without surfacing an error', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
const onEndOfSpeech = vi.fn()
|
||||
|
||||
await act(async () => {
|
||||
await result.current.startRecording({
|
||||
endpointing: { pauseMs: 800, noSpeechTimeoutMs: 1500 },
|
||||
onEndOfSpeech,
|
||||
})
|
||||
})
|
||||
|
||||
const startOptions = mockRecognizer.start.mock.calls[0][0] as {
|
||||
onEndOfSpeech: (reason: string, finalText: string) => void
|
||||
}
|
||||
|
||||
act(() => {
|
||||
registeredCallbacks.onStart[0]()
|
||||
startOptions.onEndOfSpeech('no-speech', '')
|
||||
registeredCallbacks.onEnd[0]()
|
||||
})
|
||||
|
||||
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
|
||||
expect(onEndOfSpeech).toHaveBeenCalledWith('no-speech', '')
|
||||
expect(result.current.isError).toBe(false)
|
||||
expect(result.current.error).toBeNull()
|
||||
expect(result.current.transcript).toBe('')
|
||||
expect(result.current.isEndpointing).toBe(false)
|
||||
})
|
||||
|
||||
it('does not report end of speech for a manual stop or abort', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
const onEndOfSpeech = vi.fn()
|
||||
|
||||
await act(async () => {
|
||||
await result.current.startRecording({
|
||||
endpointing: { pauseMs: 800, noSpeechTimeoutMs: 5000 },
|
||||
onEndOfSpeech,
|
||||
})
|
||||
})
|
||||
|
||||
act(() => {
|
||||
registeredCallbacks.onStart[0]()
|
||||
result.current.stopRecording()
|
||||
registeredCallbacks.onEnd[0]()
|
||||
result.current.abortRecording()
|
||||
})
|
||||
|
||||
expect(onEndOfSpeech).not.toHaveBeenCalled()
|
||||
expect(result.current.isEndpointing).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,13 +1,49 @@
|
||||
import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { getWebSpeechRecognizer, isWebRecognitionSupported, appendTranscriptSegment, type SpeechRecognitionOptions, type SpeechRecognitionResult, type RecognitionState } from '@/lib/webSpeechRecognizer'
|
||||
import { getWebSpeechRecognizer, isWebRecognitionSupported, appendTranscriptSegment, type SpeechRecognitionOptions, type SpeechRecognitionResult, type RecognitionState, type SttEndpointingOptions, type SttEndOfSpeechReason } from '@/lib/webSpeechRecognizer'
|
||||
import { AudioRecorder } from '@/lib/audioRecorder'
|
||||
import { sttApi } from '@/api/stt'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import { DEFAULT_STT_CONFIG } from '@/api/types/settings'
|
||||
import { DEFAULT_STT_CONFIG, type STTConfig } from '@/api/types/settings'
|
||||
|
||||
const STT_START_TIMEOUT_MS = 10_000
|
||||
|
||||
/** Whether the user's speech-to-text configuration can capture in this browser. */
|
||||
export interface SttAvailability {
|
||||
/** Whether speech-to-text is enabled in the user's voice settings. */
|
||||
isEnabled: boolean
|
||||
/** Whether the configured speech-to-text provider can capture in this browser. */
|
||||
isSupported: boolean
|
||||
}
|
||||
|
||||
function resolveSttAvailability(config: STTConfig): SttAvailability {
|
||||
const isExternalProvider = config.provider === 'external'
|
||||
return {
|
||||
isEnabled: config.enabled,
|
||||
isSupported: isExternalProvider ? AudioRecorder.isSupported() : isWebRecognitionSupported(),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads whether speech-to-text can capture, without creating a recorder.
|
||||
*
|
||||
* @returns The enabled flag from the user's voice settings and the browser support of its provider.
|
||||
*/
|
||||
export function useSttAvailability(): SttAvailability {
|
||||
const { preferences } = useSettings()
|
||||
return resolveSttAvailability(preferences?.stt ?? DEFAULT_STT_CONFIG)
|
||||
}
|
||||
|
||||
export interface StartRecordingOptions {
|
||||
/** Enables automatic end-of-speech for the browser provider. Ignored by the external provider. */
|
||||
endpointing?: SttEndpointingOptions
|
||||
/**
|
||||
* Called when the browser provider ends the capture by itself. Receives the
|
||||
* final transcript so a caller can send it without waiting for a render.
|
||||
*/
|
||||
onEndOfSpeech?: (reason: SttEndOfSpeechReason, finalText: string) => void
|
||||
}
|
||||
|
||||
export function useSTT(userId = 'default') {
|
||||
const { preferences } = useSettings(userId)
|
||||
const [isRecording, setIsRecording] = useState(false)
|
||||
@@ -17,6 +53,7 @@ export function useSTT(userId = 'default') {
|
||||
const [transcript, setTranscript] = useState('')
|
||||
const [interimTranscript, setInterimTranscript] = useState('')
|
||||
const [state, setState] = useState<RecognitionState>('idle')
|
||||
const [isEndpointing, setIsEndpointing] = useState(false)
|
||||
|
||||
const recognizer = useRef(getWebSpeechRecognizer())
|
||||
const audioRecorder = useRef<AudioRecorder | null>(null)
|
||||
@@ -34,13 +71,9 @@ export function useSTT(userId = 'default') {
|
||||
userIdRef.current = userId
|
||||
}, [userId])
|
||||
|
||||
const isEnabled = preferences?.stt?.enabled ?? false
|
||||
const config = preferences?.stt ?? DEFAULT_STT_CONFIG
|
||||
const isExternalProvider = config.provider === 'external'
|
||||
|
||||
const isSupported = isExternalProvider
|
||||
? AudioRecorder.isSupported()
|
||||
: isWebRecognitionSupported()
|
||||
const { isEnabled, isSupported } = resolveSttAvailability(config)
|
||||
|
||||
const flashError = useCallback((message: string) => {
|
||||
setIsError(true)
|
||||
@@ -56,6 +89,7 @@ export function useSTT(userId = 'default') {
|
||||
const resetToIdle = useCallback((clearInterim = false) => {
|
||||
setIsRecording(false)
|
||||
setIsProcessing(false)
|
||||
setIsEndpointing(false)
|
||||
setState('idle')
|
||||
if (clearInterim) setInterimTranscript('')
|
||||
}, [])
|
||||
@@ -247,7 +281,7 @@ export function useSTT(userId = 'default') {
|
||||
[clearStartupTimeout, abortAndResetOnTimeout],
|
||||
)
|
||||
|
||||
const startRecording = useCallback(async (): Promise<boolean> => {
|
||||
const startRecording = useCallback(async (options?: StartRecordingOptions): Promise<boolean> => {
|
||||
if (!isSupported) {
|
||||
setError('Speech recognition is not supported in this browser')
|
||||
setIsError(true)
|
||||
@@ -260,10 +294,14 @@ export function useSTT(userId = 'default') {
|
||||
return false
|
||||
}
|
||||
|
||||
const endpointing = isExternalProvider ? undefined : options?.endpointing
|
||||
const onEndOfSpeech = endpointing ? options?.onEndOfSpeech : undefined
|
||||
|
||||
setTranscript('')
|
||||
setInterimTranscript('')
|
||||
setIsError(false)
|
||||
setError(null)
|
||||
setIsEndpointing(Boolean(endpointing))
|
||||
lastProcessedBlobRef.current = null
|
||||
|
||||
const startOpId = ++startOpIdRef.current
|
||||
@@ -279,14 +317,30 @@ export function useSTT(userId = 'default') {
|
||||
}
|
||||
return started
|
||||
} else {
|
||||
const options: SpeechRecognitionOptions = {
|
||||
const recognitionOptions: SpeechRecognitionOptions = {
|
||||
language: config.language,
|
||||
interimResults: true,
|
||||
maxAlternatives: 1,
|
||||
}
|
||||
|
||||
if (endpointing) {
|
||||
recognitionOptions.inactivityTimeoutMs = endpointing.pauseMs
|
||||
recognitionOptions.endpointing = endpointing
|
||||
}
|
||||
|
||||
if (onEndOfSpeech) {
|
||||
recognitionOptions.onEndOfSpeech = (reason, finalText) => {
|
||||
if (finalText) setTranscript(finalText)
|
||||
onEndOfSpeech(reason, finalText)
|
||||
}
|
||||
}
|
||||
|
||||
setIsProcessing(true)
|
||||
return runStartupWithTimeout(() => recognizer.current.start(options), startOpId)
|
||||
const started = await runStartupWithTimeout(() => recognizer.current.start(recognitionOptions), startOpId)
|
||||
if (!started && startOpIdRef.current === startOpId) {
|
||||
setIsEndpointing(false)
|
||||
}
|
||||
return started
|
||||
}
|
||||
}, [isSupported, isEnabled, isExternalProvider, config.language, clearStartupTimeout, ensureAudioRecorder, runStartupWithTimeout])
|
||||
|
||||
@@ -346,6 +400,7 @@ export function useSTT(userId = 'default') {
|
||||
transcript,
|
||||
interimTranscript,
|
||||
state,
|
||||
isEndpointing,
|
||||
isSupported,
|
||||
isEnabled,
|
||||
isExternalProvider,
|
||||
|
||||
@@ -0,0 +1,516 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { useReducer, useEffect } from 'react'
|
||||
import { VOICE_MODE_INSTRUCTION_KEY, VOICE_NO_SPEECH_TIMEOUT_MS } from '@opencode-manager/shared/opencode'
|
||||
import type { SessionMessageAssistant } from '@opencode-manager/shared/opencode'
|
||||
import type { TTSEndReason } from '@/contexts/tts-context'
|
||||
import type { SttEndOfSpeechReason } from '@/lib/webSpeechRecognizer'
|
||||
import { useVoiceConversation } from './useVoiceConversation'
|
||||
import type { UseVoiceConversationInput } from './useVoiceConversation'
|
||||
|
||||
interface MockStartOptions {
|
||||
endpointing?: { pauseMs: number; noSpeechTimeoutMs: number }
|
||||
onEndOfSpeech?: (reason: SttEndOfSpeechReason, finalText: string) => void
|
||||
}
|
||||
|
||||
interface MockSttValues {
|
||||
isRecording: boolean
|
||||
isProcessing: boolean
|
||||
isEndpointing: boolean
|
||||
isExternalProvider: boolean
|
||||
isEnabled: boolean
|
||||
isSupported: boolean
|
||||
isError: boolean
|
||||
error: string | null
|
||||
transcript: string
|
||||
interimTranscript: string
|
||||
state: 'idle' | 'listening' | 'processing' | 'error'
|
||||
}
|
||||
|
||||
const harness = vi.hoisted(() => ({
|
||||
useStt: vi.fn(),
|
||||
useTts: vi.fn(),
|
||||
putSessionInstruction: vi.fn(),
|
||||
removeSessionInstruction: vi.fn(),
|
||||
listSessionInstructionKeys: vi.fn(),
|
||||
startRecording: vi.fn(),
|
||||
stopRecording: vi.fn(),
|
||||
abortRecording: vi.fn(),
|
||||
speakMessage: vi.fn(),
|
||||
ttsStop: vi.fn(),
|
||||
ttsPause: vi.fn(),
|
||||
ttsResume: vi.fn(),
|
||||
sendTurn: vi.fn(),
|
||||
interrupt: vi.fn(),
|
||||
onEditInTextBox: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSTT', () => ({ useSTT: harness.useStt }))
|
||||
|
||||
vi.mock('@/hooks/useTTS', () => ({ useTTS: harness.useTts }))
|
||||
|
||||
vi.mock('@/api/opencode', () => ({
|
||||
putSessionInstruction: harness.putSessionInstruction,
|
||||
removeSessionInstruction: harness.removeSessionInstruction,
|
||||
listSessionInstructionKeys: harness.listSessionInstructionKeys,
|
||||
}))
|
||||
|
||||
const sttListeners = new Set<() => void>()
|
||||
|
||||
const sttValue: MockSttValues = {
|
||||
isRecording: false,
|
||||
isProcessing: false,
|
||||
isEndpointing: false,
|
||||
isExternalProvider: false,
|
||||
isEnabled: true,
|
||||
isSupported: true,
|
||||
isError: false,
|
||||
error: null,
|
||||
transcript: '',
|
||||
interimTranscript: '',
|
||||
state: 'idle',
|
||||
}
|
||||
|
||||
const ttsValue = {
|
||||
isEnabled: true,
|
||||
isPlaying: false,
|
||||
isPaused: false,
|
||||
error: null as string | null,
|
||||
speakMessage: harness.speakMessage,
|
||||
stop: harness.ttsStop,
|
||||
pause: harness.ttsPause,
|
||||
resume: harness.ttsResume,
|
||||
}
|
||||
function useMockStt() {
|
||||
const [, forceRender] = useReducer((value: number) => value + 1, 0)
|
||||
useEffect(() => {
|
||||
sttListeners.add(forceRender)
|
||||
return () => {
|
||||
sttListeners.delete(forceRender)
|
||||
}
|
||||
}, [])
|
||||
return {
|
||||
...sttValue,
|
||||
startRecording: harness.startRecording,
|
||||
stopRecording: harness.stopRecording,
|
||||
abortRecording: harness.abortRecording,
|
||||
}
|
||||
}
|
||||
|
||||
function updateStt(patch: Partial<MockSttValues>) {
|
||||
Object.assign(sttValue, patch)
|
||||
act(() => {
|
||||
for (const listener of sttListeners) listener()
|
||||
})
|
||||
}
|
||||
|
||||
function lastStartOptions(): MockStartOptions {
|
||||
const calls = harness.startRecording.mock.calls
|
||||
return (calls[calls.length - 1]?.[0] ?? {}) as MockStartOptions
|
||||
}
|
||||
|
||||
async function endOfSpeech(reason: SttEndOfSpeechReason, finalText: string) {
|
||||
const options = lastStartOptions()
|
||||
await act(async () => {
|
||||
options.onEndOfSpeech?.(reason, finalText)
|
||||
})
|
||||
}
|
||||
|
||||
function speechEndHandler(callIndex = 0): (reason: TTSEndReason) => void {
|
||||
const options = harness.speakMessage.mock.calls[callIndex]?.[2] as
|
||||
| { onEnd?: (reason: TTSEndReason) => void }
|
||||
| undefined
|
||||
if (!options?.onEnd) throw new Error('speakMessage was not called with an onEnd handler')
|
||||
return options.onEnd
|
||||
}
|
||||
|
||||
function assistantMessage(id: string, text: string): SessionMessageAssistant {
|
||||
return {
|
||||
id,
|
||||
type: 'assistant',
|
||||
agent: 'build',
|
||||
model: { id: 'claude', providerID: 'anthropic' },
|
||||
content: [{ type: 'text', text }],
|
||||
time: { created: 1, completed: 2 },
|
||||
}
|
||||
}
|
||||
|
||||
function createProps(
|
||||
overrides: Partial<UseVoiceConversationInput> = {},
|
||||
): UseVoiceConversationInput {
|
||||
return {
|
||||
sessionID: 'ses_1',
|
||||
serverId: 'local',
|
||||
messages: [],
|
||||
pending: [],
|
||||
status: 'idle',
|
||||
hasPendingApproval: false,
|
||||
pauseMs: 1200,
|
||||
sendTurn: harness.sendTurn,
|
||||
interrupt: harness.interrupt,
|
||||
onEditInTextBox: harness.onEditInTextBox,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('useVoiceConversation', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
Object.assign(sttValue, {
|
||||
isRecording: false,
|
||||
isProcessing: false,
|
||||
isEndpointing: false,
|
||||
isExternalProvider: false,
|
||||
isEnabled: true,
|
||||
isSupported: true,
|
||||
isError: false,
|
||||
error: null,
|
||||
transcript: '',
|
||||
interimTranscript: '',
|
||||
state: 'idle',
|
||||
} satisfies MockSttValues)
|
||||
Object.assign(ttsValue, {
|
||||
isEnabled: true,
|
||||
isPlaying: false,
|
||||
isPaused: false,
|
||||
error: null,
|
||||
})
|
||||
sttListeners.clear()
|
||||
harness.useStt.mockImplementation(useMockStt)
|
||||
harness.useTts.mockImplementation(() => ttsValue)
|
||||
harness.putSessionInstruction.mockResolvedValue(undefined)
|
||||
harness.removeSessionInstruction.mockResolvedValue(undefined)
|
||||
harness.listSessionInstructionKeys.mockResolvedValue([])
|
||||
harness.sendTurn.mockResolvedValue(undefined)
|
||||
harness.interrupt.mockResolvedValue(undefined)
|
||||
harness.startRecording.mockResolvedValue(true)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('starts listening and opens capture with the pause budget when idle', async () => {
|
||||
const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props), {
|
||||
initialProps: createProps(),
|
||||
})
|
||||
|
||||
act(() => result.current.start())
|
||||
|
||||
await waitFor(() => expect(result.current.phase).toBe('listening'))
|
||||
expect(result.current.isActive).toBe(true)
|
||||
expect(result.current.label).toBe('Listening')
|
||||
expect(harness.startRecording).toHaveBeenCalledTimes(1)
|
||||
expect(lastStartOptions().endpointing).toEqual({ pauseMs: 1200, noSpeechTimeoutMs: 10_000 })
|
||||
expect(harness.putSessionInstruction).toHaveBeenCalledWith(
|
||||
'ses_1',
|
||||
VOICE_MODE_INSTRUCTION_KEY,
|
||||
expect.any(String),
|
||||
'local',
|
||||
)
|
||||
})
|
||||
|
||||
it('sends a finished utterance and works on the reply', async () => {
|
||||
const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props), {
|
||||
initialProps: createProps(),
|
||||
})
|
||||
|
||||
act(() => result.current.start())
|
||||
await waitFor(() => expect(result.current.phase).toBe('listening'))
|
||||
|
||||
await endOfSpeech('pause', 'hello there')
|
||||
|
||||
await waitFor(() => expect(result.current.phase).toBe('working'))
|
||||
expect(harness.sendTurn).toHaveBeenCalledWith('hello there', { busy: false })
|
||||
expect(result.current.label).toBe('Working')
|
||||
})
|
||||
|
||||
it('reads a completed reply and listens again once it ends', async () => {
|
||||
const { result, rerender } = renderHook(
|
||||
(props: UseVoiceConversationInput) => useVoiceConversation(props),
|
||||
{ initialProps: createProps() },
|
||||
)
|
||||
|
||||
act(() => result.current.start())
|
||||
await waitFor(() => expect(result.current.phase).toBe('listening'))
|
||||
await endOfSpeech('pause', 'hello there')
|
||||
await waitFor(() => expect(result.current.phase).toBe('working'))
|
||||
|
||||
rerender(createProps({ messages: [assistantMessage('msg_1', 'Done')] }))
|
||||
|
||||
await waitFor(() => expect(result.current.phase).toBe('speaking'))
|
||||
expect(harness.speakMessage).toHaveBeenCalledWith('msg_1', 'Done', expect.any(Object))
|
||||
expect(result.current.label).toBe('Speaking')
|
||||
expect(result.current.canStopAgent).toBe(false)
|
||||
|
||||
act(() => speechEndHandler(0)('completed'))
|
||||
|
||||
await waitFor(() => expect(result.current.phase).toBe('listening'))
|
||||
expect(harness.startRecording).toHaveBeenCalledTimes(2)
|
||||
expect(result.current.label).toBe('Listening')
|
||||
})
|
||||
|
||||
it('marks replies as heard without speaking when text-to-speech is disabled', async () => {
|
||||
ttsValue.isEnabled = false
|
||||
const { result, rerender } = renderHook(
|
||||
(props: UseVoiceConversationInput) => useVoiceConversation(props),
|
||||
{ initialProps: createProps() },
|
||||
)
|
||||
|
||||
act(() => result.current.start())
|
||||
await waitFor(() => expect(result.current.phase).toBe('listening'))
|
||||
await endOfSpeech('pause', 'hello there')
|
||||
await waitFor(() => expect(result.current.phase).toBe('working'))
|
||||
|
||||
rerender(createProps({ messages: [assistantMessage('msg_1', 'Done')] }))
|
||||
|
||||
await waitFor(() => expect(result.current.phase).toBe('listening'))
|
||||
expect(harness.speakMessage).not.toHaveBeenCalled()
|
||||
expect(harness.startRecording).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('records a message while the agent works and sends it as busy', async () => {
|
||||
const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props), {
|
||||
initialProps: createProps({ status: 'busy' }),
|
||||
})
|
||||
|
||||
act(() => result.current.start())
|
||||
await waitFor(() => expect(result.current.phase).toBe('working'))
|
||||
expect(result.current.orbLabel).toBe('Add a message')
|
||||
|
||||
act(() => result.current.tapOrb())
|
||||
await waitFor(() => expect(result.current.phase).toBe('recording'))
|
||||
expect(harness.startRecording).toHaveBeenCalledTimes(1)
|
||||
expect(result.current.label).toBe('Adding to queue')
|
||||
|
||||
await endOfSpeech('pause', 'also check the tests')
|
||||
|
||||
await waitFor(() => expect(result.current.phase).toBe('working'))
|
||||
expect(harness.sendTurn).toHaveBeenCalledWith('also check the tests', { busy: true })
|
||||
})
|
||||
|
||||
it('pauses and resumes a reading that is held mid-reply', async () => {
|
||||
ttsValue.isPlaying = true
|
||||
const { result, rerender } = renderHook(
|
||||
(props: UseVoiceConversationInput) => useVoiceConversation(props),
|
||||
{ initialProps: createProps() },
|
||||
)
|
||||
|
||||
act(() => result.current.start())
|
||||
await waitFor(() => expect(result.current.phase).toBe('listening'))
|
||||
await endOfSpeech('pause', 'hello there')
|
||||
await waitFor(() => expect(result.current.phase).toBe('working'))
|
||||
rerender(createProps({ messages: [assistantMessage('msg_1', 'Done')] }))
|
||||
await waitFor(() => expect(result.current.phase).toBe('speaking'))
|
||||
|
||||
act(() => result.current.pause())
|
||||
|
||||
expect(harness.ttsPause).toHaveBeenCalledTimes(1)
|
||||
expect(result.current.phase).toBe('paused')
|
||||
expect(result.current.hasHeldReading).toBe(true)
|
||||
expect(result.current.orbLabel).toBe('Continue reading')
|
||||
expect(result.current.hint).toBe('Tap to continue')
|
||||
|
||||
ttsValue.isPaused = true
|
||||
act(() => result.current.resume())
|
||||
|
||||
expect(harness.ttsResume).toHaveBeenCalledTimes(1)
|
||||
expect(result.current.phase).toBe('speaking')
|
||||
expect(result.current.hasHeldReading).toBe(false)
|
||||
})
|
||||
|
||||
it('removes the session instruction on exit', async () => {
|
||||
const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props), {
|
||||
initialProps: createProps(),
|
||||
})
|
||||
|
||||
act(() => result.current.start())
|
||||
await waitFor(() => expect(result.current.phase).toBe('listening'))
|
||||
|
||||
act(() => result.current.exit())
|
||||
|
||||
expect(result.current.phase).toBe('off')
|
||||
expect(result.current.isActive).toBe(false)
|
||||
await waitFor(() =>
|
||||
expect(harness.removeSessionInstruction).toHaveBeenCalledWith(
|
||||
'ses_1',
|
||||
VOICE_MODE_INSTRUCTION_KEY,
|
||||
'local',
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
it('hands the live transcript to the composer when editing in the text box', async () => {
|
||||
const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props), {
|
||||
initialProps: createProps(),
|
||||
})
|
||||
|
||||
act(() => result.current.start())
|
||||
await waitFor(() => expect(result.current.phase).toBe('listening'))
|
||||
|
||||
updateStt({ transcript: 'edit this turn' })
|
||||
|
||||
expect(result.current.liveTranscript).toBe('edit this turn')
|
||||
expect(result.current.canEditInTextBox).toBe(true)
|
||||
|
||||
act(() => result.current.editInTextBox())
|
||||
|
||||
await waitFor(() => expect(harness.onEditInTextBox).toHaveBeenCalledWith('edit this turn'))
|
||||
expect(result.current.phase).toBe('off')
|
||||
})
|
||||
|
||||
it('ignores speech-to-text placeholders in the live transcript', async () => {
|
||||
const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props), {
|
||||
initialProps: createProps(),
|
||||
})
|
||||
|
||||
act(() => result.current.start())
|
||||
await waitFor(() => expect(result.current.phase).toBe('listening'))
|
||||
|
||||
updateStt({ isRecording: true, interimTranscript: 'Recording...' })
|
||||
|
||||
expect(result.current.liveTranscript).toBe('')
|
||||
expect(result.current.canEditInTextBox).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps an external-provider dictation open past the no-speech timeout', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props), {
|
||||
initialProps: createProps(),
|
||||
})
|
||||
|
||||
act(() => result.current.start())
|
||||
await waitFor(() => expect(result.current.phase).toBe('listening'))
|
||||
|
||||
updateStt({ isExternalProvider: true, isRecording: true, interimTranscript: 'Recording...' })
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(VOICE_NO_SPEECH_TIMEOUT_MS + 2_000)
|
||||
})
|
||||
|
||||
expect(harness.abortRecording).not.toHaveBeenCalled()
|
||||
expect(result.current.phase).toBe('listening')
|
||||
expect(result.current.label).toBe('Listening')
|
||||
})
|
||||
|
||||
it('keeps an external-provider capture running when the session starts a turn', async () => {
|
||||
const { result, rerender } = renderHook(
|
||||
(props: UseVoiceConversationInput) => useVoiceConversation(props),
|
||||
{ initialProps: createProps() },
|
||||
)
|
||||
|
||||
act(() => result.current.start())
|
||||
await waitFor(() => expect(result.current.phase).toBe('listening'))
|
||||
|
||||
updateStt({ isExternalProvider: true, isRecording: true, interimTranscript: 'Recording...' })
|
||||
rerender(createProps({ status: 'busy' }))
|
||||
|
||||
expect(harness.abortRecording).not.toHaveBeenCalled()
|
||||
expect(result.current.phase).toBe('listening')
|
||||
expect(result.current.label).toBe('Listening')
|
||||
})
|
||||
|
||||
it('pauses when the browser provider captures no speech for the timeout', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props), {
|
||||
initialProps: createProps(),
|
||||
})
|
||||
|
||||
act(() => result.current.start())
|
||||
await waitFor(() => expect(result.current.phase).toBe('listening'))
|
||||
|
||||
updateStt({ isRecording: true })
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(VOICE_NO_SPEECH_TIMEOUT_MS)
|
||||
})
|
||||
|
||||
expect(harness.abortRecording).toHaveBeenCalled()
|
||||
expect(result.current.phase).toBe('paused')
|
||||
expect(result.current.label).toBe("Didn't catch that")
|
||||
})
|
||||
|
||||
it('pauses without a message when the turn produces no speech', async () => {
|
||||
const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props), {
|
||||
initialProps: createProps(),
|
||||
})
|
||||
|
||||
act(() => result.current.start())
|
||||
await waitFor(() => expect(result.current.phase).toBe('listening'))
|
||||
|
||||
await endOfSpeech('no-speech', '')
|
||||
|
||||
expect(harness.abortRecording).toHaveBeenCalled()
|
||||
expect(harness.sendTurn).not.toHaveBeenCalled()
|
||||
expect(result.current.phase).toBe('paused')
|
||||
expect(result.current.label).toBe("Didn't catch that")
|
||||
expect(result.current.hint).toBe('Tap to talk')
|
||||
expect(result.current.orbLabel).toBe('Resume voice conversation')
|
||||
})
|
||||
|
||||
it('pauses with an error when capture cannot start', async () => {
|
||||
harness.startRecording.mockResolvedValue(false)
|
||||
const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props), {
|
||||
initialProps: createProps(),
|
||||
})
|
||||
|
||||
act(() => result.current.start())
|
||||
|
||||
await waitFor(() => expect(result.current.phase).toBe('paused'))
|
||||
expect(result.current.label).toBe('Something went wrong')
|
||||
expect(result.current.hint).toBe('Tap to retry')
|
||||
})
|
||||
|
||||
it('pauses when speech recognition reports an error while listening', async () => {
|
||||
const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props), {
|
||||
initialProps: createProps(),
|
||||
})
|
||||
|
||||
act(() => result.current.start())
|
||||
await waitFor(() => expect(result.current.phase).toBe('listening'))
|
||||
|
||||
updateStt({ isError: true, error: 'Microphone access denied' })
|
||||
|
||||
await waitFor(() => expect(result.current.phase).toBe('paused'))
|
||||
expect(result.current.label).toBe('Something went wrong')
|
||||
})
|
||||
|
||||
it('pauses instead of finishing the turn when reading the reply fails', async () => {
|
||||
const { result, rerender } = renderHook(
|
||||
(props: UseVoiceConversationInput) => useVoiceConversation(props),
|
||||
{ initialProps: createProps() },
|
||||
)
|
||||
|
||||
act(() => result.current.start())
|
||||
await waitFor(() => expect(result.current.phase).toBe('listening'))
|
||||
await endOfSpeech('pause', 'hello there')
|
||||
await waitFor(() => expect(result.current.phase).toBe('working'))
|
||||
|
||||
rerender(createProps({ messages: [assistantMessage('msg_1', 'Done')] }))
|
||||
await waitFor(() => expect(result.current.phase).toBe('speaking'))
|
||||
|
||||
act(() => speechEndHandler(0)('error'))
|
||||
|
||||
expect(result.current.phase).toBe('paused')
|
||||
expect(result.current.label).toBe('Something went wrong')
|
||||
expect(harness.startRecording).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('marks a reply with nothing to read as heard and listens again', async () => {
|
||||
const { result, rerender } = renderHook(
|
||||
(props: UseVoiceConversationInput) => useVoiceConversation(props),
|
||||
{ initialProps: createProps() },
|
||||
)
|
||||
|
||||
act(() => result.current.start())
|
||||
await waitFor(() => expect(result.current.phase).toBe('listening'))
|
||||
await endOfSpeech('pause', 'hello there')
|
||||
await waitFor(() => expect(result.current.phase).toBe('working'))
|
||||
|
||||
rerender(createProps({ messages: [assistantMessage('msg_1', '```ts\nconst answer = 42\n```')] }))
|
||||
|
||||
await waitFor(() => expect(result.current.phase).toBe('listening'))
|
||||
expect(harness.speakMessage).not.toHaveBeenCalled()
|
||||
expect(harness.startRecording).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,96 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import {
|
||||
DEFAULT_VOICE_PAUSE_MS,
|
||||
VOICE_PAUSE_STORAGE_KEY,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import { useVoicePauseSetting } from './useVoicePauseSetting'
|
||||
|
||||
function readStoredPause(): string | null {
|
||||
return window.localStorage.getItem(VOICE_PAUSE_STORAGE_KEY)
|
||||
}
|
||||
|
||||
function dispatchStorageEvent(key: string): void {
|
||||
window.dispatchEvent(new StorageEvent('storage', { key }))
|
||||
}
|
||||
|
||||
describe('useVoicePauseSetting', () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear()
|
||||
})
|
||||
|
||||
it('falls back to the default pause when storage holds nothing', () => {
|
||||
const { result } = renderHook(() => useVoicePauseSetting())
|
||||
|
||||
expect(result.current.pauseMs).toBe(DEFAULT_VOICE_PAUSE_MS)
|
||||
})
|
||||
|
||||
it('reads a valid stored pause', () => {
|
||||
window.localStorage.setItem(VOICE_PAUSE_STORAGE_KEY, '2000')
|
||||
|
||||
const { result } = renderHook(() => useVoicePauseSetting())
|
||||
|
||||
expect(result.current.pauseMs).toBe(2000)
|
||||
})
|
||||
|
||||
it('falls back to the default pause when the stored value is not an option', () => {
|
||||
window.localStorage.setItem(VOICE_PAUSE_STORAGE_KEY, '1234')
|
||||
|
||||
const { result } = renderHook(() => useVoicePauseSetting())
|
||||
|
||||
expect(result.current.pauseMs).toBe(DEFAULT_VOICE_PAUSE_MS)
|
||||
})
|
||||
|
||||
it('persists a selected pause and ignores values outside the options', () => {
|
||||
const { result } = renderHook(() => useVoicePauseSetting())
|
||||
|
||||
act(() => {
|
||||
result.current.setPauseMs(3000)
|
||||
})
|
||||
|
||||
expect(result.current.pauseMs).toBe(3000)
|
||||
expect(readStoredPause()).toBe('3000')
|
||||
|
||||
act(() => {
|
||||
result.current.setPauseMs(1234)
|
||||
})
|
||||
|
||||
expect(result.current.pauseMs).toBe(3000)
|
||||
expect(readStoredPause()).toBe('3000')
|
||||
})
|
||||
|
||||
it('propagates changes to every consumer mounted in the same tab', () => {
|
||||
const first = renderHook(() => useVoicePauseSetting())
|
||||
const second = renderHook(() => useVoicePauseSetting())
|
||||
|
||||
act(() => {
|
||||
first.result.current.setPauseMs(1600)
|
||||
})
|
||||
|
||||
expect(first.result.current.pauseMs).toBe(1600)
|
||||
expect(second.result.current.pauseMs).toBe(1600)
|
||||
})
|
||||
|
||||
it('follows changes written by another tab', () => {
|
||||
const { result } = renderHook(() => useVoicePauseSetting())
|
||||
|
||||
act(() => {
|
||||
window.localStorage.setItem(VOICE_PAUSE_STORAGE_KEY, '800')
|
||||
dispatchStorageEvent(VOICE_PAUSE_STORAGE_KEY)
|
||||
})
|
||||
|
||||
expect(result.current.pauseMs).toBe(800)
|
||||
})
|
||||
|
||||
it('ignores storage events for unrelated keys', () => {
|
||||
window.localStorage.setItem(VOICE_PAUSE_STORAGE_KEY, '800')
|
||||
const { result } = renderHook(() => useVoicePauseSetting())
|
||||
|
||||
window.localStorage.setItem(VOICE_PAUSE_STORAGE_KEY, '3000')
|
||||
act(() => {
|
||||
dispatchStorageEvent('some-other-key')
|
||||
})
|
||||
|
||||
expect(result.current.pauseMs).toBe(800)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useSyncExternalStore } from 'react'
|
||||
import {
|
||||
DEFAULT_VOICE_PAUSE_MS,
|
||||
VOICE_PAUSE_STORAGE_KEY,
|
||||
normalizeVoicePauseMs,
|
||||
parseVoicePauseMs,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import { readStoredValue, writeStoredValue } from '@/lib/persistentStorage'
|
||||
|
||||
const subscribers = new Set<() => void>()
|
||||
|
||||
function readPauseMs(): number {
|
||||
const raw = readStoredValue(VOICE_PAUSE_STORAGE_KEY)
|
||||
if (raw === null) {
|
||||
return DEFAULT_VOICE_PAUSE_MS
|
||||
}
|
||||
return parseVoicePauseMs(raw) ?? DEFAULT_VOICE_PAUSE_MS
|
||||
}
|
||||
|
||||
function notifySubscribers(): void {
|
||||
subscribers.forEach((subscriber) => subscriber())
|
||||
}
|
||||
|
||||
function handleStorageChange(event: StorageEvent): void {
|
||||
if (event.key === VOICE_PAUSE_STORAGE_KEY) {
|
||||
notifySubscribers()
|
||||
}
|
||||
}
|
||||
|
||||
function subscribe(subscriber: () => void): () => void {
|
||||
subscribers.add(subscriber)
|
||||
if (subscribers.size === 1) {
|
||||
window.addEventListener('storage', handleStorageChange)
|
||||
}
|
||||
return () => {
|
||||
subscribers.delete(subscriber)
|
||||
if (subscribers.size === 0) {
|
||||
window.removeEventListener('storage', handleStorageChange)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function setPauseMs(ms: number): void {
|
||||
const normalized = normalizeVoicePauseMs(ms)
|
||||
if (normalized === undefined) {
|
||||
return
|
||||
}
|
||||
writeStoredValue(VOICE_PAUSE_STORAGE_KEY, normalized)
|
||||
notifySubscribers()
|
||||
}
|
||||
|
||||
function getServerPauseMs(): number {
|
||||
return DEFAULT_VOICE_PAUSE_MS
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads and writes the device-local pause-before-sending duration, keeping every
|
||||
* mounted consumer in the tab and other tabs in sync. Missing or unusable stored
|
||||
* values fall back to {@link DEFAULT_VOICE_PAUSE_MS}.
|
||||
*/
|
||||
export function useVoicePauseSetting(): { pauseMs: number; setPauseMs: (ms: number) => void } {
|
||||
const pauseMs = useSyncExternalStore(subscribe, readPauseMs, getServerPauseMs)
|
||||
return { pauseMs, setPauseMs }
|
||||
}
|
||||
+16
-4
@@ -176,11 +176,23 @@ body {
|
||||
}
|
||||
|
||||
@theme {
|
||||
--animate-voice-wave-bar: voice-wave-bar 0.9s ease-in-out infinite;
|
||||
--animate-voice-orb-breathe: voice-orb-breathe 2.6s ease-in-out infinite;
|
||||
--animate-voice-orb-work: voice-orb-work 1.8s ease-in-out infinite;
|
||||
--animate-voice-orb-speak: voice-orb-speak 0.7s ease-in-out infinite;
|
||||
|
||||
@keyframes voice-wave-bar {
|
||||
0%, 100% { transform: scaleY(0.25); }
|
||||
50% { transform: scaleY(1); }
|
||||
@keyframes voice-orb-breathe {
|
||||
0%, 100% { transform: scale(0.96); }
|
||||
50% { transform: scale(1.04); }
|
||||
}
|
||||
|
||||
@keyframes voice-orb-work {
|
||||
0%, 100% { transform: scale(0.94); }
|
||||
50% { transform: scale(1); }
|
||||
}
|
||||
|
||||
@keyframes voice-orb-speak {
|
||||
0%, 100% { transform: scale(0.9); }
|
||||
50% { transform: scale(1); }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,807 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type {
|
||||
SessionMessageAssistant,
|
||||
SessionMessageInfo,
|
||||
VoiceConversationEvent,
|
||||
VoiceConversationLabelInput,
|
||||
VoiceConversationState,
|
||||
VoicePhase,
|
||||
VoiceSessionStatus,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import {
|
||||
DEFAULT_VOICE_PAUSE_MS,
|
||||
INITIAL_VOICE_CONVERSATION_STATE,
|
||||
VOICE_NO_SPEECH_TIMEOUT_MS,
|
||||
VOICE_PAUSE_OPTIONS_MS,
|
||||
findNextUnspokenMessage,
|
||||
formatVoicePauseMs,
|
||||
hasIncompleteAssistant,
|
||||
hasSpokenMessage,
|
||||
isVoicePauseOption,
|
||||
isVoiceTurnComplete,
|
||||
listUnspokenMessages,
|
||||
normalizeVoicePauseMs,
|
||||
parseVoicePauseMs,
|
||||
reduceVoiceConversation,
|
||||
voiceConversationHint,
|
||||
voiceConversationLabel,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
|
||||
function assistant(
|
||||
id: string,
|
||||
created: number,
|
||||
completed?: number,
|
||||
texts: readonly string[] = ['Done'],
|
||||
): SessionMessageAssistant {
|
||||
return {
|
||||
id,
|
||||
type: 'assistant',
|
||||
agent: 'build',
|
||||
model: { id: 'claude', providerID: 'anthropic' },
|
||||
content: texts.map((text) => ({ type: 'text' as const, text })),
|
||||
time: { created, ...(completed === undefined ? {} : { completed }) },
|
||||
}
|
||||
}
|
||||
|
||||
function narration(
|
||||
id: string,
|
||||
created: number,
|
||||
completed: number,
|
||||
text: string,
|
||||
): SessionMessageAssistant {
|
||||
return {
|
||||
...assistant(id, created, completed, [text]),
|
||||
content: [
|
||||
{ type: 'text', text },
|
||||
{
|
||||
type: 'tool',
|
||||
id: 'tool-1',
|
||||
name: 'read',
|
||||
state: { status: 'streaming', input: '' },
|
||||
time: { created },
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function user(id: string, text: string, created = 0): SessionMessageInfo {
|
||||
return { id, type: 'user', text, time: { created } }
|
||||
}
|
||||
|
||||
function conversation(overrides: Partial<VoiceConversationState> = {}): VoiceConversationState {
|
||||
return { ...INITIAL_VOICE_CONVERSATION_STATE, ...overrides }
|
||||
}
|
||||
|
||||
function labelInput(
|
||||
overrides: Partial<VoiceConversationLabelInput> = {},
|
||||
): VoiceConversationLabelInput {
|
||||
return {
|
||||
phase: 'off',
|
||||
pauseReason: null,
|
||||
pendingApproval: false,
|
||||
isEndpointing: false,
|
||||
isPlaybackPaused: false,
|
||||
sessionBusy: false,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('reduceVoiceConversation', () => {
|
||||
describe('start', () => {
|
||||
it('enters working and records busy when the session is already working', () => {
|
||||
expect(
|
||||
reduceVoiceConversation(conversation(), { type: 'start', busy: true, baselineId: 'b1' }),
|
||||
).toEqual({
|
||||
phase: 'working',
|
||||
pauseReason: null,
|
||||
error: null,
|
||||
sawBusy: true,
|
||||
baselineId: 'b1',
|
||||
})
|
||||
})
|
||||
|
||||
it('enters listening and clears stale turn data when the session is idle', () => {
|
||||
expect(
|
||||
reduceVoiceConversation(conversation({ error: 'old', baselineId: 'old' }), {
|
||||
type: 'start',
|
||||
busy: false,
|
||||
baselineId: 'b1',
|
||||
}),
|
||||
).toEqual({
|
||||
phase: 'listening',
|
||||
pauseReason: null,
|
||||
error: null,
|
||||
sawBusy: false,
|
||||
baselineId: null,
|
||||
})
|
||||
})
|
||||
|
||||
it.each<VoicePhase>(['listening', 'sending', 'working', 'speaking', 'recording', 'paused'])(
|
||||
'is ignored from %s',
|
||||
(phase) => {
|
||||
const state = conversation({ phase })
|
||||
expect(
|
||||
reduceVoiceConversation(state, { type: 'start', busy: false, baselineId: 'b1' }),
|
||||
).toBe(state)
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
describe('transcript', () => {
|
||||
it('moves to sending when the transcript has content', () => {
|
||||
const state = conversation({ phase: 'listening' })
|
||||
expect(reduceVoiceConversation(state, { type: 'transcript', text: 'hello there' })).toEqual({
|
||||
...state,
|
||||
phase: 'sending',
|
||||
})
|
||||
})
|
||||
|
||||
it('pauses as no-speech when the transcript is only whitespace', () => {
|
||||
const state = conversation({ phase: 'listening' })
|
||||
expect(reduceVoiceConversation(state, { type: 'transcript', text: ' ' })).toEqual({
|
||||
...state,
|
||||
phase: 'paused',
|
||||
pauseReason: 'no-speech',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('turn-sent', () => {
|
||||
it('enters working with the new baseline and clears the busy marker', () => {
|
||||
const state = conversation({ phase: 'sending', sawBusy: true, baselineId: 'old' })
|
||||
expect(reduceVoiceConversation(state, { type: 'turn-sent', baselineId: 'b2' })).toEqual({
|
||||
...state,
|
||||
phase: 'working',
|
||||
sawBusy: false,
|
||||
baselineId: 'b2',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('turn-started', () => {
|
||||
it('enters working with the new baseline when a queued prompt starts a turn', () => {
|
||||
const state = conversation({ phase: 'listening' })
|
||||
expect(reduceVoiceConversation(state, { type: 'turn-started', baselineId: 'b3' })).toEqual({
|
||||
...state,
|
||||
phase: 'working',
|
||||
sawBusy: true,
|
||||
baselineId: 'b3',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('send-failed', () => {
|
||||
it('pauses with the failure message', () => {
|
||||
const state = conversation({ phase: 'sending' })
|
||||
expect(
|
||||
reduceVoiceConversation(state, { type: 'send-failed', message: 'network down' }),
|
||||
).toEqual({
|
||||
...state,
|
||||
phase: 'paused',
|
||||
pauseReason: 'error',
|
||||
error: 'network down',
|
||||
})
|
||||
})
|
||||
|
||||
it('pauses with the failure message when the sent turn never arrives', () => {
|
||||
const state = conversation({ phase: 'working', baselineId: 'b2' })
|
||||
expect(
|
||||
reduceVoiceConversation(state, { type: 'send-failed', message: 'not delivered' }),
|
||||
).toEqual({
|
||||
...state,
|
||||
phase: 'paused',
|
||||
pauseReason: 'error',
|
||||
error: 'not delivered',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('status', () => {
|
||||
it('records the first busy report after a turn is sent', () => {
|
||||
const state = conversation({ phase: 'working', baselineId: 'b2' })
|
||||
expect(reduceVoiceConversation(state, { type: 'status', busy: true })).toEqual({
|
||||
...state,
|
||||
sawBusy: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('ignores a repeated busy report', () => {
|
||||
const state = conversation({ phase: 'working', sawBusy: true })
|
||||
expect(reduceVoiceConversation(state, { type: 'status', busy: true })).toBe(state)
|
||||
})
|
||||
|
||||
it('ignores an idle report', () => {
|
||||
const state = conversation({ phase: 'working' })
|
||||
expect(reduceVoiceConversation(state, { type: 'status', busy: false })).toBe(state)
|
||||
})
|
||||
})
|
||||
|
||||
describe('speak-start', () => {
|
||||
it('enters speaking from working', () => {
|
||||
const state = conversation({ phase: 'working', baselineId: 'b2', sawBusy: true })
|
||||
expect(reduceVoiceConversation(state, { type: 'speak-start' })).toEqual({
|
||||
...state,
|
||||
phase: 'speaking',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('speech-ended', () => {
|
||||
it('returns to working so the next message can be scheduled', () => {
|
||||
const state = conversation({ phase: 'speaking', baselineId: 'b2' })
|
||||
expect(reduceVoiceConversation(state, { type: 'speech-ended' })).toEqual({
|
||||
...state,
|
||||
phase: 'working',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('skip', () => {
|
||||
it('returns to listening when the reply is skipped', () => {
|
||||
const state = conversation({ phase: 'speaking' })
|
||||
expect(reduceVoiceConversation(state, { type: 'skip' })).toEqual({
|
||||
...state,
|
||||
phase: 'listening',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('record', () => {
|
||||
it('enters recording from working without moving the baseline', () => {
|
||||
const state = conversation({ phase: 'working', baselineId: 'b2', sawBusy: true })
|
||||
expect(reduceVoiceConversation(state, { type: 'record' })).toEqual({
|
||||
...state,
|
||||
phase: 'recording',
|
||||
baselineId: 'b2',
|
||||
})
|
||||
})
|
||||
|
||||
it('enters recording from speaking', () => {
|
||||
const state = conversation({ phase: 'speaking', baselineId: 'b2' })
|
||||
expect(reduceVoiceConversation(state, { type: 'record' })).toEqual({
|
||||
...state,
|
||||
phase: 'recording',
|
||||
baselineId: 'b2',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('record-ended', () => {
|
||||
it('returns to working so the queued turn and pending replies continue', () => {
|
||||
const state = conversation({ phase: 'recording', baselineId: 'b2', sawBusy: true })
|
||||
expect(reduceVoiceConversation(state, { type: 'record-ended' })).toEqual({
|
||||
...state,
|
||||
phase: 'working',
|
||||
baselineId: 'b2',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('turn-complete', () => {
|
||||
it('returns to listening when the turn finished', () => {
|
||||
const state = conversation({ phase: 'working', baselineId: 'b2', sawBusy: true })
|
||||
expect(reduceVoiceConversation(state, { type: 'turn-complete' })).toEqual({
|
||||
...state,
|
||||
phase: 'listening',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('no-speech', () => {
|
||||
it('pauses as no-speech from listening', () => {
|
||||
const state = conversation({ phase: 'listening' })
|
||||
expect(reduceVoiceConversation(state, { type: 'no-speech' })).toEqual({
|
||||
...state,
|
||||
phase: 'paused',
|
||||
pauseReason: 'no-speech',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('pause', () => {
|
||||
it.each<VoicePhase>(['listening', 'sending', 'working', 'speaking', 'recording'])(
|
||||
'pauses from %s with the given reason',
|
||||
(phase) => {
|
||||
const state = conversation({ phase })
|
||||
expect(reduceVoiceConversation(state, { type: 'pause', reason: 'background' })).toEqual({
|
||||
...state,
|
||||
phase: 'paused',
|
||||
pauseReason: 'background',
|
||||
})
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
describe('resume', () => {
|
||||
it('enters working and clears the pause when the session is busy', () => {
|
||||
const state = conversation({ phase: 'paused', pauseReason: 'user', error: 'boom' })
|
||||
expect(
|
||||
reduceVoiceConversation(state, { type: 'resume', busy: true, baselineId: 'b3' }),
|
||||
).toEqual({
|
||||
...state,
|
||||
phase: 'working',
|
||||
sawBusy: true,
|
||||
baselineId: 'b3',
|
||||
pauseReason: null,
|
||||
error: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('enters listening and clears the pause when the session is idle', () => {
|
||||
const state = conversation({
|
||||
phase: 'paused',
|
||||
pauseReason: 'error',
|
||||
error: 'boom',
|
||||
baselineId: 'b3',
|
||||
})
|
||||
expect(
|
||||
reduceVoiceConversation(state, { type: 'resume', busy: false, baselineId: 'b4' }),
|
||||
).toEqual({
|
||||
...state,
|
||||
phase: 'listening',
|
||||
sawBusy: false,
|
||||
baselineId: null,
|
||||
pauseReason: null,
|
||||
error: null,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('resume-speech', () => {
|
||||
it('returns to speaking and clears the pause when a held reading continues', () => {
|
||||
const state = conversation({
|
||||
phase: 'paused',
|
||||
pauseReason: 'background',
|
||||
error: 'boom',
|
||||
baselineId: 'b3',
|
||||
})
|
||||
expect(reduceVoiceConversation(state, { type: 'resume-speech' })).toEqual({
|
||||
...state,
|
||||
phase: 'speaking',
|
||||
pauseReason: null,
|
||||
error: null,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('error', () => {
|
||||
it.each<VoicePhase>(['listening', 'sending', 'working', 'speaking', 'recording', 'paused'])(
|
||||
'pauses with the failure message from %s',
|
||||
(phase) => {
|
||||
const state = conversation({ phase })
|
||||
expect(
|
||||
reduceVoiceConversation(state, { type: 'error', message: 'mic unavailable' }),
|
||||
).toEqual({
|
||||
...state,
|
||||
phase: 'paused',
|
||||
pauseReason: 'error',
|
||||
error: 'mic unavailable',
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
it('is ignored while voice mode is off', () => {
|
||||
const state = conversation()
|
||||
expect(reduceVoiceConversation(state, { type: 'error', message: 'mic unavailable' })).toBe(
|
||||
state,
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('exit', () => {
|
||||
it.each<VoicePhase>([
|
||||
'off',
|
||||
'listening',
|
||||
'sending',
|
||||
'working',
|
||||
'speaking',
|
||||
'recording',
|
||||
'paused',
|
||||
])('resets to the initial state from %s', (phase) => {
|
||||
const state = conversation({ phase, pauseReason: 'error', error: 'boom', sawBusy: true })
|
||||
const next = reduceVoiceConversation(state, { type: 'exit' })
|
||||
expect(next).toBe(INITIAL_VOICE_CONVERSATION_STATE)
|
||||
expect(next.phase).toBe('off')
|
||||
})
|
||||
})
|
||||
|
||||
it.each<[string, VoiceConversationState, VoiceConversationEvent]>([
|
||||
['transcript while off', conversation(), { type: 'transcript', text: 'hi' }],
|
||||
[
|
||||
'transcript while working',
|
||||
conversation({ phase: 'working' }),
|
||||
{ type: 'transcript', text: 'hi' },
|
||||
],
|
||||
[
|
||||
'turn-sent while listening',
|
||||
conversation({ phase: 'listening' }),
|
||||
{ type: 'turn-sent', baselineId: null },
|
||||
],
|
||||
[
|
||||
'turn-started while working',
|
||||
conversation({ phase: 'working' }),
|
||||
{ type: 'turn-started', baselineId: 'b2' },
|
||||
],
|
||||
['status while listening', conversation({ phase: 'listening' }), { type: 'status', busy: true }],
|
||||
['speak-start while listening', conversation({ phase: 'listening' }), { type: 'speak-start' }],
|
||||
['speak-start while speaking', conversation({ phase: 'speaking' }), { type: 'speak-start' }],
|
||||
['speech-ended while working', conversation({ phase: 'working' }), { type: 'speech-ended' }],
|
||||
['skip while working', conversation({ phase: 'working' }), { type: 'skip' }],
|
||||
['record while listening', conversation({ phase: 'listening' }), { type: 'record' }],
|
||||
['record-ended while working', conversation({ phase: 'working' }), { type: 'record-ended' }],
|
||||
['turn-complete while speaking', conversation({ phase: 'speaking' }), { type: 'turn-complete' }],
|
||||
['no-speech while sending', conversation({ phase: 'sending' }), { type: 'no-speech' }],
|
||||
['no-speech while recording', conversation({ phase: 'recording' }), { type: 'no-speech' }],
|
||||
['pause while off', conversation(), { type: 'pause', reason: 'user' }],
|
||||
[
|
||||
'pause while paused',
|
||||
conversation({ phase: 'paused', pauseReason: 'user' }),
|
||||
{ type: 'pause', reason: 'background' },
|
||||
],
|
||||
[
|
||||
'resume while listening',
|
||||
conversation({ phase: 'listening' }),
|
||||
{ type: 'resume', busy: false, baselineId: null },
|
||||
],
|
||||
['resume-speech while listening', conversation({ phase: 'listening' }), { type: 'resume-speech' }],
|
||||
['resume-speech while speaking', conversation({ phase: 'speaking' }), { type: 'resume-speech' }],
|
||||
])('ignores %s and returns the same state object', (_description, state, event) => {
|
||||
expect(reduceVoiceConversation(state, event)).toBe(state)
|
||||
})
|
||||
})
|
||||
|
||||
describe('listUnspokenMessages', () => {
|
||||
it('lists every completed text message after the baseline, oldest first', () => {
|
||||
const messages = [
|
||||
user('u1', 'first', 1),
|
||||
assistant('a1', 2, 3, ['First answer']),
|
||||
user('u2', 'second', 4),
|
||||
assistant('a2', 5, 6, ['Second answer']),
|
||||
assistant('a3', 7, 8, ['Third answer']),
|
||||
]
|
||||
|
||||
expect(listUnspokenMessages(messages, 'a1', new Set())).toEqual([
|
||||
{ id: 'a2', text: 'Second answer' },
|
||||
{ id: 'a3', text: 'Third answer' },
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps reading past a user message so replies to queued prompts are spoken', () => {
|
||||
const messages = [
|
||||
user('u1', 'first', 1),
|
||||
assistant('a1', 2, 3, ['First answer']),
|
||||
user('u2', 'queued prompt', 4),
|
||||
assistant('a2', 5, 6, ['Reply to the queued prompt']),
|
||||
]
|
||||
|
||||
expect(listUnspokenMessages(messages, 'a1', new Set())).toEqual([
|
||||
{ id: 'a2', text: 'Reply to the queued prompt' },
|
||||
])
|
||||
})
|
||||
|
||||
it('reads narration that a tool step ended', () => {
|
||||
const messages = [
|
||||
user('u1', 'fix it', 1),
|
||||
narration('a1', 2, 3, 'Looking at the file'),
|
||||
assistant('a2', 4, 5, ['All fixed']),
|
||||
]
|
||||
|
||||
expect(listUnspokenMessages(messages, null, new Set())).toEqual([
|
||||
{ id: 'a1', text: 'Looking at the file' },
|
||||
{ id: 'a2', text: 'All fixed' },
|
||||
])
|
||||
})
|
||||
|
||||
it('skips messages that were already spoken', () => {
|
||||
const messages = [
|
||||
user('u1', 'first', 1),
|
||||
assistant('a1', 2, 3, ['First answer']),
|
||||
assistant('a2', 4, 5, ['Second answer']),
|
||||
]
|
||||
|
||||
expect(listUnspokenMessages(messages, 'u1', new Set(['a1']))).toEqual([
|
||||
{ id: 'a2', text: 'Second answer' },
|
||||
])
|
||||
})
|
||||
|
||||
it('skips messages that have not completed', () => {
|
||||
const messages = [user('u1', 'hi', 1), assistant('a1', 2, undefined, ['Still streaming'])]
|
||||
|
||||
expect(listUnspokenMessages(messages, null, new Set())).toEqual([])
|
||||
})
|
||||
|
||||
it('skips completed messages without text', () => {
|
||||
const reasoningOnly: SessionMessageAssistant = {
|
||||
...assistant('a1', 2, 3),
|
||||
content: [{ type: 'reasoning', text: 'thinking it through' }],
|
||||
}
|
||||
const messages = [user('u1', 'hi', 1), reasoningOnly, assistant('a2', 4, 5, ['Spoken'])]
|
||||
|
||||
expect(listUnspokenMessages(messages, null, new Set())).toEqual([{ id: 'a2', text: 'Spoken' }])
|
||||
})
|
||||
|
||||
it('excludes an inline think block from the spoken text', () => {
|
||||
const messages = [
|
||||
user('u1', 'hi', 1),
|
||||
assistant('a1', 2, 3, ['The answer is ready <think>hidden reasoning</think> and verified']),
|
||||
]
|
||||
|
||||
expect(listUnspokenMessages(messages, null, new Set())).toEqual([
|
||||
{ id: 'a1', text: 'The answer is ready and verified' },
|
||||
])
|
||||
})
|
||||
|
||||
it('skips a completed reply that only contains a think block', () => {
|
||||
const messages = [
|
||||
user('u1', 'hi', 1),
|
||||
assistant('a1', 2, 3, ['<think>hidden reasoning</think>']),
|
||||
assistant('a2', 4, 5, ['Spoken']),
|
||||
]
|
||||
|
||||
expect(listUnspokenMessages(messages, null, new Set())).toEqual([{ id: 'a2', text: 'Spoken' }])
|
||||
})
|
||||
|
||||
it('considers the whole transcript when the baseline is null', () => {
|
||||
const messages = [user('u1', 'only turn', 1), assistant('a1', 2, 3, ['The answer'])]
|
||||
|
||||
expect(listUnspokenMessages(messages, null, new Set())).toEqual([
|
||||
{ id: 'a1', text: 'The answer' },
|
||||
])
|
||||
})
|
||||
|
||||
it('considers the whole transcript when the baseline is unknown', () => {
|
||||
const messages = [user('u1', 'only turn', 1), assistant('a1', 2, 3, ['The answer'])]
|
||||
|
||||
expect(listUnspokenMessages(messages, 'missing', new Set())).toEqual([
|
||||
{ id: 'a1', text: 'The answer' },
|
||||
])
|
||||
})
|
||||
|
||||
it('returns nothing when the baseline is the newest message', () => {
|
||||
const messages = [user('u1', 'first', 1), assistant('a1', 2, 3, ['First answer'])]
|
||||
|
||||
expect(listUnspokenMessages(messages, 'a1', new Set())).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('findNextUnspokenMessage', () => {
|
||||
it('returns the oldest unspoken message', () => {
|
||||
const messages = [
|
||||
user('u1', 'first', 1),
|
||||
assistant('a1', 2, 3, ['First answer']),
|
||||
assistant('a2', 4, 5, ['Second answer']),
|
||||
]
|
||||
|
||||
expect(findNextUnspokenMessage(messages, 'u1', new Set())).toEqual({
|
||||
id: 'a1',
|
||||
text: 'First answer',
|
||||
})
|
||||
expect(findNextUnspokenMessage(messages, 'u1', new Set(['a1']))).toEqual({
|
||||
id: 'a2',
|
||||
text: 'Second answer',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns null when nothing is left to read', () => {
|
||||
const messages = [user('u1', 'first', 1), assistant('a1', 2, 3, ['First answer'])]
|
||||
|
||||
expect(findNextUnspokenMessage(messages, 'u1', new Set(['a1']))).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasSpokenMessage', () => {
|
||||
it('reports a spoken message after the baseline', () => {
|
||||
const messages = [
|
||||
user('u1', 'first', 1),
|
||||
assistant('a1', 2, 3, ['First answer']),
|
||||
assistant('a2', 4, 5, ['Second answer']),
|
||||
]
|
||||
|
||||
expect(hasSpokenMessage(messages, 'a1', new Set(['a2']))).toBe(true)
|
||||
})
|
||||
|
||||
it('ignores messages spoken in an earlier turn', () => {
|
||||
const messages = [
|
||||
user('u1', 'first', 1),
|
||||
assistant('a1', 2, 3, ['First answer']),
|
||||
user('u2', 'second', 4),
|
||||
]
|
||||
|
||||
expect(hasSpokenMessage(messages, 'a1', new Set(['a1']))).toBe(false)
|
||||
})
|
||||
|
||||
it('reports nothing spoken when no id was recorded', () => {
|
||||
const messages = [user('u1', 'first', 1), assistant('a1', 2, 3, ['First answer'])]
|
||||
|
||||
expect(hasSpokenMessage(messages, 'u1', new Set())).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasIncompleteAssistant', () => {
|
||||
it('reports a message that is still streaming after the baseline', () => {
|
||||
const messages = [
|
||||
user('u1', 'fix it', 1),
|
||||
assistant('a1', 2, 3, ['Earlier answer']),
|
||||
assistant('a2', 4, undefined, ['Still streaming']),
|
||||
]
|
||||
|
||||
expect(hasIncompleteAssistant(messages, null)).toBe(true)
|
||||
})
|
||||
|
||||
it('reports no incomplete message once every reply settled', () => {
|
||||
const messages = [
|
||||
user('u1', 'fix it', 1),
|
||||
assistant('a1', 2, 3, ['Earlier answer']),
|
||||
assistant('a2', 4, 5, ['All fixed']),
|
||||
]
|
||||
|
||||
expect(hasIncompleteAssistant(messages, null)).toBe(false)
|
||||
})
|
||||
|
||||
it('ignores incomplete messages at or before the baseline', () => {
|
||||
const messages = [
|
||||
user('u1', 'first', 1),
|
||||
assistant('a1', 2, undefined, ['Still streaming']),
|
||||
user('u2', 'second', 3),
|
||||
]
|
||||
|
||||
expect(hasIncompleteAssistant(messages, 'a1')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isVoiceTurnComplete', () => {
|
||||
it.each<[string, VoiceSessionStatus, boolean, boolean, boolean, boolean, boolean]>([
|
||||
['idle after being seen busy', 'idle', true, false, false, false, true],
|
||||
['idle after reading a reply', 'idle', false, true, false, false, true],
|
||||
['idle without activity', 'idle', false, false, false, false, false],
|
||||
['retry with a busy report', 'retry', true, false, false, false, false],
|
||||
['idle with a queued prompt pending', 'idle', true, true, true, false, false],
|
||||
['idle with a message still streaming', 'idle', true, true, false, true, false],
|
||||
])('%s', (_description, status, sawBusy, spoke, hasPendingPrompts, hasIncomplete, expected) => {
|
||||
expect(isVoiceTurnComplete({ status, sawBusy, spoke, hasPendingPrompts, hasIncomplete })).toBe(
|
||||
expected,
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('voiceConversationLabel', () => {
|
||||
it.each<[string, Partial<VoiceConversationLabelInput>, string]>([
|
||||
['listening while recording', { phase: 'listening' }, 'Listening'],
|
||||
['listening while finalizing', { phase: 'listening', isEndpointing: true }, 'Listening'],
|
||||
['sending', { phase: 'sending' }, 'Sending…'],
|
||||
['working', { phase: 'working' }, 'Working'],
|
||||
[
|
||||
'working with a pending approval',
|
||||
{ phase: 'working', pendingApproval: true },
|
||||
'Needs your approval',
|
||||
],
|
||||
['speaking while the session is idle', { phase: 'speaking' }, 'Speaking'],
|
||||
['speaking while the session is busy', { phase: 'speaking', sessionBusy: true }, 'Speaking'],
|
||||
['recording a queued message', { phase: 'recording' }, 'Adding to queue'],
|
||||
['paused after silence', { phase: 'paused', pauseReason: 'no-speech' }, "Didn't catch that"],
|
||||
['paused after a failure', { phase: 'paused', pauseReason: 'error' }, 'Something went wrong'],
|
||||
['paused by the user', { phase: 'paused', pauseReason: 'user' }, 'Paused'],
|
||||
[
|
||||
'paused by the user while a reply is held',
|
||||
{ phase: 'paused', pauseReason: 'user', isPlaybackPaused: true },
|
||||
'Paused',
|
||||
],
|
||||
[
|
||||
'paused by the background while a reply is held',
|
||||
{ phase: 'paused', pauseReason: 'background', isPlaybackPaused: true },
|
||||
'Paused',
|
||||
],
|
||||
[
|
||||
'paused after silence while a reply is held',
|
||||
{ phase: 'paused', pauseReason: 'no-speech', isPlaybackPaused: true },
|
||||
"Didn't catch that",
|
||||
],
|
||||
[
|
||||
'paused after a failure while a reply is held',
|
||||
{ phase: 'paused', pauseReason: 'error', isPlaybackPaused: true },
|
||||
'Something went wrong',
|
||||
],
|
||||
['paused without a reason', { phase: 'paused' }, 'Paused'],
|
||||
['off', { phase: 'off' }, ''],
|
||||
])('labels %s', (_description, overrides, expected) => {
|
||||
expect(voiceConversationLabel(labelInput(overrides))).toBe(expected)
|
||||
})
|
||||
})
|
||||
|
||||
describe('voiceConversationHint', () => {
|
||||
it.each<[string, Partial<VoiceConversationLabelInput>, string]>([
|
||||
['listening while recording', { phase: 'listening' }, 'Tap to send'],
|
||||
['listening while finalizing', { phase: 'listening', isEndpointing: true }, ''],
|
||||
['sending', { phase: 'sending' }, ''],
|
||||
['working', { phase: 'working' }, 'Tap to add a message'],
|
||||
['working with a pending approval', { phase: 'working', pendingApproval: true }, ''],
|
||||
['speaking while the session is idle', { phase: 'speaking' }, 'Tap to skip'],
|
||||
[
|
||||
'speaking while the session is busy',
|
||||
{ phase: 'speaking', sessionBusy: true },
|
||||
'Tap to add a message',
|
||||
],
|
||||
['recording a queued message', { phase: 'recording' }, 'Tap to queue'],
|
||||
['paused after silence', { phase: 'paused', pauseReason: 'no-speech' }, 'Tap to talk'],
|
||||
['paused after a failure', { phase: 'paused', pauseReason: 'error' }, 'Tap to retry'],
|
||||
['paused by the user', { phase: 'paused', pauseReason: 'user' }, 'Tap to talk'],
|
||||
[
|
||||
'paused by the user while a reply is held',
|
||||
{ phase: 'paused', pauseReason: 'user', isPlaybackPaused: true },
|
||||
'Tap to continue',
|
||||
],
|
||||
[
|
||||
'paused by the background while a reply is held',
|
||||
{ phase: 'paused', pauseReason: 'background', isPlaybackPaused: true },
|
||||
'Tap to continue',
|
||||
],
|
||||
[
|
||||
'paused after silence while a reply is held',
|
||||
{ phase: 'paused', pauseReason: 'no-speech', isPlaybackPaused: true },
|
||||
'Tap to talk',
|
||||
],
|
||||
[
|
||||
'paused after a failure while a reply is held',
|
||||
{ phase: 'paused', pauseReason: 'error', isPlaybackPaused: true },
|
||||
'Tap to retry',
|
||||
],
|
||||
['paused without a reason', { phase: 'paused' }, 'Tap to talk'],
|
||||
['off', { phase: 'off' }, ''],
|
||||
])('suggests %s', (_description, overrides, expected) => {
|
||||
expect(voiceConversationHint(labelInput(overrides))).toBe(expected)
|
||||
})
|
||||
})
|
||||
|
||||
describe('voice pause options', () => {
|
||||
it('offers the default as a pickable option', () => {
|
||||
expect(VOICE_PAUSE_OPTIONS_MS).toContain(DEFAULT_VOICE_PAUSE_MS)
|
||||
})
|
||||
|
||||
it('defaults to 1200', () => {
|
||||
expect(DEFAULT_VOICE_PAUSE_MS).toBe(1200)
|
||||
})
|
||||
|
||||
it('keeps the no-speech timeout fixed at 10000', () => {
|
||||
expect(VOICE_NO_SPEECH_TIMEOUT_MS).toBe(10000)
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseVoicePauseMs', () => {
|
||||
it('reads a valid stored value', () => {
|
||||
expect(parseVoicePauseMs('2000')).toBe(2000)
|
||||
})
|
||||
|
||||
it('treats a value outside the options as absent', () => {
|
||||
expect(parseVoicePauseMs('999')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('treats a non-numeric value as absent', () => {
|
||||
expect(parseVoicePauseMs('abc')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('normalizeVoicePauseMs', () => {
|
||||
it('accepts a selectable duration', () => {
|
||||
expect(normalizeVoicePauseMs(800)).toBe(800)
|
||||
})
|
||||
|
||||
it('rejects a value outside the options instead of clamping it', () => {
|
||||
expect(normalizeVoicePauseMs(999)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('isVoicePauseOption', () => {
|
||||
it('reports the selectable durations', () => {
|
||||
expect(isVoicePauseOption(1200)).toBe(true)
|
||||
expect(isVoicePauseOption(1000)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatVoicePauseMs', () => {
|
||||
it('formats one-decimal seconds with a space before the unit', () => {
|
||||
expect(formatVoicePauseMs(800)).toBe('0.8 s')
|
||||
expect(formatVoicePauseMs(1200)).toBe('1.2 s')
|
||||
expect(formatVoicePauseMs(2000)).toBe('2.0 s')
|
||||
expect(formatVoicePauseMs(3000)).toBe('3.0 s')
|
||||
})
|
||||
})
|
||||
@@ -66,6 +66,7 @@ describe('WebSpeechRecognizer', () => {
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
delete (window as any).SpeechRecognition
|
||||
})
|
||||
|
||||
@@ -223,4 +224,463 @@ describe('WebSpeechRecognizer', () => {
|
||||
expect(fakeRec.stop).not.toHaveBeenCalled()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('uses the provided inactivity timeout instead of the default', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
await rec.start({ inactivityTimeoutMs: 500 })
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'test', confidence: 1.0 },
|
||||
]))
|
||||
|
||||
vi.advanceTimersByTime(499)
|
||||
expect(fakeRec.stop).not.toHaveBeenCalled()
|
||||
|
||||
vi.advanceTimersByTime(1)
|
||||
expect(fakeRec.stop).toHaveBeenCalledTimes(1)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('reports a pause endpoint with the final transcript after pauseMs', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEndOfSpeech = vi.fn()
|
||||
const onEnd = vi.fn()
|
||||
rec.onEnd(onEnd)
|
||||
await rec.start({ endpointing: { pauseMs: 800, noSpeechTimeoutMs: 5000 }, onEndOfSpeech })
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'hello', confidence: 1.0 },
|
||||
]))
|
||||
|
||||
vi.advanceTimersByTime(799)
|
||||
expect(fakeRec.stop).not.toHaveBeenCalled()
|
||||
|
||||
vi.advanceTimersByTime(1)
|
||||
expect(fakeRec.stop).toHaveBeenCalledTimes(1)
|
||||
expect(onEndOfSpeech).not.toHaveBeenCalled()
|
||||
|
||||
fakeRec.onend!(new Event('end'))
|
||||
fakeRec.onend!(new Event('end'))
|
||||
|
||||
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
|
||||
expect(onEndOfSpeech).toHaveBeenCalledWith('pause', 'hello')
|
||||
expect(onEnd).toHaveBeenCalledTimes(2)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('reports a no-speech endpoint when no result arrives within noSpeechTimeoutMs', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEndOfSpeech = vi.fn()
|
||||
const onError = vi.fn()
|
||||
rec.onError(onError)
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
const startPromise = rec.start({ endpointing: { pauseMs: 800, noSpeechTimeoutMs: 1500 }, onEndOfSpeech })
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
await startPromise
|
||||
|
||||
vi.advanceTimersByTime(1499)
|
||||
expect(onEndOfSpeech).not.toHaveBeenCalled()
|
||||
|
||||
vi.advanceTimersByTime(1)
|
||||
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
|
||||
expect(onEndOfSpeech).toHaveBeenCalledWith('no-speech', '')
|
||||
expect(fakeRec.stop).toHaveBeenCalledTimes(1)
|
||||
expect(onError).not.toHaveBeenCalled()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('cancels the no-speech timeout once a result arrives', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEndOfSpeech = vi.fn()
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
const startPromise = rec.start({ endpointing: { pauseMs: 1000, noSpeechTimeoutMs: 1500 }, onEndOfSpeech })
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
await startPromise
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'hi', confidence: 1.0 },
|
||||
]))
|
||||
|
||||
vi.advanceTimersByTime(1000)
|
||||
expect(onEndOfSpeech).not.toHaveBeenCalled()
|
||||
|
||||
fakeRec.onend!(new Event('end'))
|
||||
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
|
||||
expect(onEndOfSpeech).toHaveBeenCalledWith('pause', 'hi')
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('reports no-speech instead of an error when Chrome raises no-speech after the deadline', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEndOfSpeech = vi.fn()
|
||||
const onError = vi.fn()
|
||||
const onEnd = vi.fn()
|
||||
rec.onError(onError)
|
||||
rec.onEnd(onEnd)
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
const startPromise = rec.start({ endpointing: { pauseMs: 800, noSpeechTimeoutMs: 5000 }, onEndOfSpeech })
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
await startPromise
|
||||
|
||||
vi.setSystemTime(Date.now() + 5000)
|
||||
fakeRec.onerror!({ error: 'no-speech' })
|
||||
|
||||
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
|
||||
expect(onEndOfSpeech).toHaveBeenCalledWith('no-speech', '')
|
||||
expect(onError).not.toHaveBeenCalled()
|
||||
expect(fakeRec.start).toHaveBeenCalledTimes(1)
|
||||
|
||||
fakeRec.onend!(new Event('end'))
|
||||
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
|
||||
expect(onEnd).toHaveBeenCalledTimes(1)
|
||||
expect(rec.getState()).toBe('idle')
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('restarts transparently when Chrome raises no-speech before the deadline', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEndOfSpeech = vi.fn()
|
||||
const onError = vi.fn()
|
||||
const onEnd = vi.fn()
|
||||
const onStart = vi.fn()
|
||||
rec.onError(onError)
|
||||
rec.onEnd(onEnd)
|
||||
rec.onStart(onStart)
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
const startPromise = rec.start({
|
||||
endpointing: { pauseMs: 2000, noSpeechTimeoutMs: 10000 },
|
||||
onEndOfSpeech,
|
||||
})
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
await startPromise
|
||||
|
||||
expect(onStart).toHaveBeenCalledTimes(1)
|
||||
|
||||
vi.advanceTimersByTime(6000)
|
||||
fakeRec.onerror!({ error: 'no-speech' })
|
||||
|
||||
expect(onEndOfSpeech).not.toHaveBeenCalled()
|
||||
expect(onError).not.toHaveBeenCalled()
|
||||
|
||||
fakeRec.onend!(new Event('end'))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(fakeRec.start).toHaveBeenCalledTimes(2)
|
||||
expect(onStart).toHaveBeenCalledTimes(1)
|
||||
expect(onEnd).not.toHaveBeenCalled()
|
||||
expect(rec.isCurrentlyListening()).toBe(true)
|
||||
|
||||
vi.advanceTimersByTime(3999)
|
||||
expect(onEndOfSpeech).not.toHaveBeenCalled()
|
||||
|
||||
vi.advanceTimersByTime(1)
|
||||
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
|
||||
expect(onEndOfSpeech).toHaveBeenCalledWith('no-speech', '')
|
||||
|
||||
fakeRec.onend!(new Event('end'))
|
||||
expect(onEnd).toHaveBeenCalledTimes(1)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('restarts when recognition ends unexpectedly before the deadline without speech', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEndOfSpeech = vi.fn()
|
||||
const onError = vi.fn()
|
||||
const onEnd = vi.fn()
|
||||
const onStart = vi.fn()
|
||||
rec.onError(onError)
|
||||
rec.onEnd(onEnd)
|
||||
rec.onStart(onStart)
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
const startPromise = rec.start({
|
||||
endpointing: { pauseMs: 2000, noSpeechTimeoutMs: 10000 },
|
||||
onEndOfSpeech,
|
||||
})
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
await startPromise
|
||||
|
||||
vi.advanceTimersByTime(3000)
|
||||
fakeRec.onend!(new Event('end'))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(fakeRec.start).toHaveBeenCalledTimes(2)
|
||||
expect(onStart).toHaveBeenCalledTimes(1)
|
||||
expect(onEnd).not.toHaveBeenCalled()
|
||||
expect(onError).not.toHaveBeenCalled()
|
||||
expect(onEndOfSpeech).not.toHaveBeenCalled()
|
||||
expect(rec.isCurrentlyListening()).toBe(true)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('reports a pause with the final transcript when recognition ends unexpectedly', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEndOfSpeech = vi.fn()
|
||||
const onEnd = vi.fn()
|
||||
rec.onEnd(onEnd)
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
const startPromise = rec.start({
|
||||
endpointing: { pauseMs: 2000, noSpeechTimeoutMs: 10000 },
|
||||
onEndOfSpeech,
|
||||
})
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
await startPromise
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'hello world', confidence: 1.0 },
|
||||
]))
|
||||
|
||||
fakeRec.onend!(new Event('end'))
|
||||
|
||||
expect(fakeRec.start).toHaveBeenCalledTimes(1)
|
||||
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
|
||||
expect(onEndOfSpeech).toHaveBeenCalledWith('pause', 'hello world')
|
||||
expect(onEnd).toHaveBeenCalledTimes(1)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('keeps the accumulated transcript across transparent restarts', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEndOfSpeech = vi.fn()
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
const startPromise = rec.start({
|
||||
endpointing: { pauseMs: 5000, noSpeechTimeoutMs: 10000 },
|
||||
onEndOfSpeech,
|
||||
})
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
await startPromise
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'hello', confidence: 1.0 },
|
||||
]))
|
||||
|
||||
vi.advanceTimersByTime(1000)
|
||||
fakeRec.onerror!({ error: 'no-speech' })
|
||||
fakeRec.onend!(new Event('end'))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(rec.getFinalTranscript()).toBe('hello')
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'world', confidence: 1.0 },
|
||||
]))
|
||||
fakeRec.onend!(new Event('end'))
|
||||
|
||||
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
|
||||
expect(onEndOfSpeech).toHaveBeenCalledWith('pause', 'hello world')
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('reports a pause with the interim transcript when recognition ends unexpectedly before a final result', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEndOfSpeech = vi.fn()
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
const startPromise = rec.start({
|
||||
endpointing: { pauseMs: 2000, noSpeechTimeoutMs: 10000 },
|
||||
onEndOfSpeech,
|
||||
})
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
await startPromise
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: false, transcript: 'hello there', confidence: 0.0 },
|
||||
]))
|
||||
|
||||
fakeRec.onend!(new Event('end'))
|
||||
|
||||
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
|
||||
expect(onEndOfSpeech).toHaveBeenCalledWith('pause', 'hello there')
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('cancels a pending restart when stop() is called', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEndOfSpeech = vi.fn()
|
||||
const onEnd = vi.fn()
|
||||
rec.onEnd(onEnd)
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
const startPromise = rec.start({
|
||||
endpointing: { pauseMs: 2000, noSpeechTimeoutMs: 10000 },
|
||||
onEndOfSpeech,
|
||||
})
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
await startPromise
|
||||
|
||||
vi.advanceTimersByTime(3000)
|
||||
fakeRec.onerror!({ error: 'no-speech' })
|
||||
rec.stop()
|
||||
fakeRec.onend!(new Event('end'))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(fakeRec.start).toHaveBeenCalledTimes(1)
|
||||
expect(onEndOfSpeech).not.toHaveBeenCalled()
|
||||
expect(onEnd).toHaveBeenCalledTimes(1)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('surfaces an error when a transparent restart throws', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEndOfSpeech = vi.fn()
|
||||
const onError = vi.fn()
|
||||
const onEnd = vi.fn()
|
||||
rec.onError(onError)
|
||||
rec.onEnd(onEnd)
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
const startPromise = rec.start({
|
||||
endpointing: { pauseMs: 2000, noSpeechTimeoutMs: 10000 },
|
||||
onEndOfSpeech,
|
||||
})
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
await startPromise
|
||||
|
||||
fakeRec.start.mockImplementationOnce(() => {
|
||||
throw new Error('InvalidStateError')
|
||||
})
|
||||
|
||||
vi.advanceTimersByTime(3000)
|
||||
fakeRec.onend!(new Event('end'))
|
||||
|
||||
expect(fakeRec.start).toHaveBeenCalledTimes(2)
|
||||
expect(onError).toHaveBeenCalledTimes(1)
|
||||
expect(onError).toHaveBeenCalledWith('Speech recognition stopped unexpectedly. Please try again.')
|
||||
expect(onEndOfSpeech).not.toHaveBeenCalled()
|
||||
expect(onEnd).toHaveBeenCalledTimes(1)
|
||||
expect(rec.getState()).toBe('idle')
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('stops restarting after the transparent restart cap', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEndOfSpeech = vi.fn()
|
||||
const onEnd = vi.fn()
|
||||
rec.onEnd(onEnd)
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
const startPromise = rec.start({
|
||||
endpointing: { pauseMs: 2000, noSpeechTimeoutMs: 20000 },
|
||||
onEndOfSpeech,
|
||||
})
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
await startPromise
|
||||
|
||||
for (let i = 0; i < 6; i++) {
|
||||
vi.advanceTimersByTime(500)
|
||||
fakeRec.onerror!({ error: 'no-speech' })
|
||||
fakeRec.onend!(new Event('end'))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
}
|
||||
|
||||
expect(fakeRec.start).toHaveBeenCalledTimes(6)
|
||||
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
|
||||
expect(onEndOfSpeech).toHaveBeenCalledWith('no-speech', '')
|
||||
expect(onEnd).toHaveBeenCalledTimes(1)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('stops restarting when a restarted session ends immediately without audio', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEndOfSpeech = vi.fn()
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
const startPromise = rec.start({
|
||||
endpointing: { pauseMs: 2000, noSpeechTimeoutMs: 10000 },
|
||||
onEndOfSpeech,
|
||||
})
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
await startPromise
|
||||
|
||||
vi.advanceTimersByTime(3000)
|
||||
fakeRec.onend!(new Event('end'))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
vi.advanceTimersByTime(100)
|
||||
fakeRec.onend!(new Event('end'))
|
||||
|
||||
expect(fakeRec.start).toHaveBeenCalledTimes(2)
|
||||
expect(onEndOfSpeech).toHaveBeenCalledTimes(1)
|
||||
expect(onEndOfSpeech).toHaveBeenCalledWith('no-speech', '')
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('surfaces Chrome no-speech as an error when endpointing is off', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onError = vi.fn()
|
||||
const onEnd = vi.fn()
|
||||
rec.onError(onError)
|
||||
rec.onEnd(onEnd)
|
||||
|
||||
await rec.start()
|
||||
|
||||
fakeRec.onerror!({ error: 'no-speech' })
|
||||
|
||||
expect(onError).toHaveBeenCalledTimes(1)
|
||||
expect(onError).toHaveBeenCalledWith('No speech detected. Please try again.')
|
||||
expect(fakeRec.start).toHaveBeenCalledTimes(1)
|
||||
|
||||
fakeRec.onend!(new Event('end'))
|
||||
expect(onEnd).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('does not report end of speech for a manual stop', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEndOfSpeech = vi.fn()
|
||||
await rec.start({ endpointing: { pauseMs: 800, noSpeechTimeoutMs: 5000 }, onEndOfSpeech })
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'hello', confidence: 1.0 },
|
||||
]))
|
||||
|
||||
rec.stop()
|
||||
fakeRec.onend!(new Event('end'))
|
||||
vi.advanceTimersByTime(5000)
|
||||
|
||||
expect(onEndOfSpeech).not.toHaveBeenCalled()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('does not report end of speech for an abort during endpointing', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEndOfSpeech = vi.fn()
|
||||
await rec.start({ endpointing: { pauseMs: 800, noSpeechTimeoutMs: 5000 }, onEndOfSpeech })
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'hello', confidence: 1.0 },
|
||||
]))
|
||||
|
||||
rec.abort()
|
||||
fakeRec.onend!(new Event('end'))
|
||||
vi.advanceTimersByTime(5000)
|
||||
|
||||
expect(onEndOfSpeech).not.toHaveBeenCalled()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
})
|
||||
@@ -4,10 +4,35 @@ export interface SpeechRecognitionResult {
|
||||
confidence: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a capture session ended without the caller stopping it.
|
||||
*/
|
||||
export type SttEndOfSpeechReason = 'pause' | 'no-speech';
|
||||
|
||||
/**
|
||||
* Client-side endpointing budget for one capture session.
|
||||
*/
|
||||
export interface SttEndpointingOptions {
|
||||
/** Silence after speech, in milliseconds, that ends the session. */
|
||||
pauseMs: number;
|
||||
/** Silence from capture start, in milliseconds, before any speech is heard. */
|
||||
noSpeechTimeoutMs: number;
|
||||
}
|
||||
|
||||
export interface SpeechRecognitionOptions {
|
||||
language?: string;
|
||||
interimResults?: boolean;
|
||||
maxAlternatives?: number;
|
||||
/** Silences after a result that stop capture. Defaults to 2000. */
|
||||
inactivityTimeoutMs?: number;
|
||||
/** Enables automatic end-of-speech reporting. Omit for tap-to-stop behavior. */
|
||||
endpointing?: SttEndpointingOptions;
|
||||
/**
|
||||
* Called at most once per session when the capture stops itself. The final
|
||||
* transcript accumulated so far is passed with it so callers do not have to
|
||||
* wait for a state update. Never called for a manual stop or abort.
|
||||
*/
|
||||
onEndOfSpeech?: (reason: SttEndOfSpeechReason, finalText: string) => void;
|
||||
}
|
||||
|
||||
export type RecognitionState = 'idle' | 'listening' | 'processing' | 'error';
|
||||
@@ -66,6 +91,9 @@ declare global {
|
||||
}
|
||||
|
||||
const WEB_SPEECH_INACTIVITY_TIMEOUT_MS = 2000;
|
||||
const MAX_TRANSPARENT_RESTARTS = 5;
|
||||
const MIN_RESTART_SESSION_MS = 250;
|
||||
const RESTART_FAILED_MESSAGE = 'Speech recognition stopped unexpectedly. Please try again.';
|
||||
|
||||
export function appendTranscriptSegment(current: string, segment: string): string {
|
||||
const trimmedCurrent = current.trim();
|
||||
@@ -83,7 +111,22 @@ export class WebSpeechRecognizer {
|
||||
private onEndCallbacks: (() => void)[] = [];
|
||||
private onStartCallbacks: (() => void)[] = [];
|
||||
private finalTranscript = '';
|
||||
private interimTranscript = '';
|
||||
private inactivityTimeoutRef: ReturnType<typeof setTimeout> | null = null;
|
||||
private noSpeechTimeoutRef: ReturnType<typeof setTimeout> | null = null;
|
||||
private noSpeechDeadlineAt: number | null = null;
|
||||
private inactivityTimeoutMs = WEB_SPEECH_INACTIVITY_TIMEOUT_MS;
|
||||
private endpointing: SttEndpointingOptions | null = null;
|
||||
private endOfSpeechHandler: ((reason: SttEndOfSpeechReason, finalText: string) => void) | null = null;
|
||||
private pendingEndOfSpeechReason: SttEndOfSpeechReason | null = null;
|
||||
private endOfSpeechEmitted = false;
|
||||
private restartCount = 0;
|
||||
private restartStartedAt = 0;
|
||||
private sessionHadSpeech = false;
|
||||
private awaitingRestart = false;
|
||||
private stopRequested = false;
|
||||
private fatalErrorRaised = false;
|
||||
private suppressStartCallbacks = false;
|
||||
|
||||
private clearInactivityTimeout(): void {
|
||||
if (this.inactivityTimeoutRef !== null) {
|
||||
@@ -92,14 +135,94 @@ export class WebSpeechRecognizer {
|
||||
}
|
||||
}
|
||||
|
||||
private clearNoSpeechTimeout(): void {
|
||||
if (this.noSpeechTimeoutRef !== null) {
|
||||
clearTimeout(this.noSpeechTimeoutRef);
|
||||
this.noSpeechTimeoutRef = null;
|
||||
}
|
||||
}
|
||||
|
||||
private accumulatedTranscript(): string {
|
||||
const interim = this.interimTranscript.trim();
|
||||
return interim ? appendTranscriptSegment(this.finalTranscript, interim) : this.finalTranscript;
|
||||
}
|
||||
|
||||
private emitEndOfSpeech(reason: SttEndOfSpeechReason): void {
|
||||
if (this.endOfSpeechEmitted) return;
|
||||
this.endOfSpeechEmitted = true;
|
||||
this.endOfSpeechHandler?.(reason, this.accumulatedTranscript());
|
||||
}
|
||||
|
||||
private hasNoSpeechBudgetRemaining(): boolean {
|
||||
return this.noSpeechDeadlineAt !== null && Date.now() < this.noSpeechDeadlineAt;
|
||||
}
|
||||
|
||||
private scheduleNoSpeechTimeout(): void {
|
||||
this.clearNoSpeechTimeout();
|
||||
|
||||
if (this.noSpeechDeadlineAt === null) return;
|
||||
|
||||
const remainingMs = Math.max(0, this.noSpeechDeadlineAt - Date.now());
|
||||
|
||||
this.noSpeechTimeoutRef = setTimeout(() => {
|
||||
this.noSpeechTimeoutRef = null;
|
||||
if (this.endOfSpeechEmitted || this.finalTranscript) return;
|
||||
if (!this.isListening && !this.awaitingRestart) return;
|
||||
this.emitEndOfSpeech('no-speech');
|
||||
this.stop();
|
||||
}, remainingMs);
|
||||
}
|
||||
|
||||
private canRestartCapture(): boolean {
|
||||
if (this.endOfSpeechEmitted) return false;
|
||||
if (this.restartCount >= MAX_TRANSPARENT_RESTARTS) return false;
|
||||
|
||||
const endedTooSoon =
|
||||
this.restartCount > 0 &&
|
||||
!this.sessionHadSpeech &&
|
||||
Date.now() - this.restartStartedAt < MIN_RESTART_SESSION_MS;
|
||||
|
||||
return !endedTooSoon;
|
||||
}
|
||||
|
||||
private restartCapture(): 'restarted' | 'blocked' | 'failed' {
|
||||
if (!this.recognition || !this.canRestartCapture()) return 'blocked';
|
||||
|
||||
this.restartCount += 1;
|
||||
this.restartStartedAt = Date.now();
|
||||
this.isListening = true;
|
||||
this.state = 'listening';
|
||||
this.awaitingRestart = false;
|
||||
this.stopRequested = false;
|
||||
this.fatalErrorRaised = false;
|
||||
this.sessionHadSpeech = false;
|
||||
this.suppressStartCallbacks = true;
|
||||
|
||||
try {
|
||||
this.recognition.start();
|
||||
return 'restarted';
|
||||
} catch {
|
||||
this.suppressStartCallbacks = false;
|
||||
this.isListening = false;
|
||||
this.endpointing = null;
|
||||
this.endOfSpeechHandler = null;
|
||||
this.endOfSpeechEmitted = true;
|
||||
this.onErrorCallbacks.forEach((cb) => cb(RESTART_FAILED_MESSAGE));
|
||||
return 'failed';
|
||||
}
|
||||
}
|
||||
|
||||
private resetInactivityTimeout(): void {
|
||||
this.clearInactivityTimeout();
|
||||
if (this.isListening) {
|
||||
this.inactivityTimeoutRef = setTimeout(() => {
|
||||
if (this.isListening) {
|
||||
this.stop();
|
||||
this.inactivityTimeoutRef = null;
|
||||
if (!this.isListening) return;
|
||||
if (this.endpointing) {
|
||||
this.pendingEndOfSpeechReason = 'pause';
|
||||
}
|
||||
}, WEB_SPEECH_INACTIVITY_TIMEOUT_MS);
|
||||
this.stop();
|
||||
}, this.inactivityTimeoutMs);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,10 +240,20 @@ export class WebSpeechRecognizer {
|
||||
this.recognition.onstart = () => {
|
||||
this.isListening = true;
|
||||
this.state = 'listening';
|
||||
this.sessionHadSpeech = false;
|
||||
this.scheduleNoSpeechTimeout();
|
||||
|
||||
if (this.suppressStartCallbacks) {
|
||||
this.suppressStartCallbacks = false;
|
||||
return;
|
||||
}
|
||||
|
||||
this.onStartCallbacks.forEach((cb) => cb());
|
||||
};
|
||||
|
||||
this.recognition.onresult = (event: SpeechRecognitionEvent) => {
|
||||
this.clearNoSpeechTimeout();
|
||||
this.sessionHadSpeech = true;
|
||||
let interimTranscript = '';
|
||||
|
||||
for (let i = event.resultIndex; i < event.results.length; i++) {
|
||||
@@ -142,6 +275,8 @@ export class WebSpeechRecognizer {
|
||||
}
|
||||
}
|
||||
|
||||
this.interimTranscript = interimTranscript;
|
||||
|
||||
if (interimTranscript) {
|
||||
this.onInterimResultCallbacks.forEach((cb) => cb(this.finalTranscript + ' ' + interimTranscript));
|
||||
}
|
||||
@@ -151,8 +286,30 @@ export class WebSpeechRecognizer {
|
||||
|
||||
this.recognition.onerror = (event: SpeechRecognitionErrorEvent) => {
|
||||
this.clearInactivityTimeout();
|
||||
|
||||
if (this.endpointing && event.error === 'no-speech') {
|
||||
if (this.hasNoSpeechBudgetRemaining() && !this.endOfSpeechEmitted) {
|
||||
this.awaitingRestart = true;
|
||||
this.isListening = false;
|
||||
return;
|
||||
}
|
||||
|
||||
this.fatalErrorRaised = true;
|
||||
this.clearNoSpeechTimeout();
|
||||
this.state = 'error';
|
||||
this.isListening = false;
|
||||
this.pendingEndOfSpeechReason = null;
|
||||
this.emitEndOfSpeech('no-speech');
|
||||
this.endpointing = null;
|
||||
this.endOfSpeechHandler = null;
|
||||
return;
|
||||
}
|
||||
|
||||
this.clearNoSpeechTimeout();
|
||||
this.state = 'error';
|
||||
this.isListening = false;
|
||||
this.pendingEndOfSpeechReason = null;
|
||||
this.fatalErrorRaised = true;
|
||||
|
||||
let errorMsg = event.error || 'Unknown error';
|
||||
|
||||
@@ -179,8 +336,34 @@ export class WebSpeechRecognizer {
|
||||
|
||||
this.recognition.onend = () => {
|
||||
this.clearInactivityTimeout();
|
||||
|
||||
const reason = this.pendingEndOfSpeechReason;
|
||||
this.pendingEndOfSpeechReason = null;
|
||||
|
||||
if (reason) {
|
||||
this.emitEndOfSpeech(reason);
|
||||
} else if (this.endpointing && !this.stopRequested && !this.fatalErrorRaised) {
|
||||
if (this.awaitingRestart) {
|
||||
const outcome = this.hasNoSpeechBudgetRemaining() ? this.restartCapture() : 'blocked';
|
||||
if (outcome === 'restarted') return;
|
||||
if (outcome === 'blocked') this.emitEndOfSpeech('no-speech');
|
||||
} else if (this.accumulatedTranscript()) {
|
||||
this.emitEndOfSpeech('pause');
|
||||
} else if (this.hasNoSpeechBudgetRemaining()) {
|
||||
const outcome = this.restartCapture();
|
||||
if (outcome === 'restarted') return;
|
||||
if (outcome === 'blocked') this.emitEndOfSpeech('no-speech');
|
||||
} else {
|
||||
this.emitEndOfSpeech('no-speech');
|
||||
}
|
||||
}
|
||||
|
||||
this.clearNoSpeechTimeout();
|
||||
this.isListening = false;
|
||||
this.state = 'idle';
|
||||
this.endpointing = null;
|
||||
this.endOfSpeechHandler = null;
|
||||
this.awaitingRestart = false;
|
||||
this.onEndCallbacks.forEach((cb) => cb());
|
||||
};
|
||||
}
|
||||
@@ -209,7 +392,26 @@ export class WebSpeechRecognizer {
|
||||
}
|
||||
|
||||
this.finalTranscript = '';
|
||||
this.interimTranscript = '';
|
||||
this.state = 'listening';
|
||||
this.clearInactivityTimeout();
|
||||
this.clearNoSpeechTimeout();
|
||||
this.inactivityTimeoutMs =
|
||||
options.inactivityTimeoutMs ?? options.endpointing?.pauseMs ?? WEB_SPEECH_INACTIVITY_TIMEOUT_MS;
|
||||
this.endpointing = options.endpointing ?? null;
|
||||
this.endOfSpeechHandler = options.onEndOfSpeech ?? null;
|
||||
this.pendingEndOfSpeechReason = null;
|
||||
this.endOfSpeechEmitted = false;
|
||||
this.restartCount = 0;
|
||||
this.restartStartedAt = 0;
|
||||
this.sessionHadSpeech = false;
|
||||
this.awaitingRestart = false;
|
||||
this.stopRequested = false;
|
||||
this.fatalErrorRaised = false;
|
||||
this.suppressStartCallbacks = false;
|
||||
|
||||
const noSpeechTimeoutMs = this.endpointing?.noSpeechTimeoutMs ?? 0;
|
||||
this.noSpeechDeadlineAt = noSpeechTimeoutMs > 0 ? Date.now() + noSpeechTimeoutMs : null;
|
||||
|
||||
if (options.language) {
|
||||
this.recognition.lang = options.language;
|
||||
@@ -258,7 +460,10 @@ export class WebSpeechRecognizer {
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopRequested = true;
|
||||
this.awaitingRestart = false;
|
||||
this.clearInactivityTimeout();
|
||||
this.clearNoSpeechTimeout();
|
||||
if (this.recognition) {
|
||||
try {
|
||||
this.recognition.stop();
|
||||
@@ -270,7 +475,10 @@ export class WebSpeechRecognizer {
|
||||
}
|
||||
|
||||
abort(): void {
|
||||
this.stopRequested = true;
|
||||
this.awaitingRestart = false;
|
||||
this.clearInactivityTimeout();
|
||||
this.clearNoSpeechTimeout();
|
||||
if (this.recognition) {
|
||||
try {
|
||||
this.recognition.abort();
|
||||
@@ -282,6 +490,11 @@ export class WebSpeechRecognizer {
|
||||
this.state = 'idle';
|
||||
this.isListening = false;
|
||||
this.finalTranscript = '';
|
||||
this.interimTranscript = '';
|
||||
this.endpointing = null;
|
||||
this.endOfSpeechHandler = null;
|
||||
this.pendingEndOfSpeechReason = null;
|
||||
this.endOfSpeechEmitted = true;
|
||||
}
|
||||
|
||||
isCurrentlyListening(): boolean {
|
||||
@@ -314,6 +527,14 @@ export class WebSpeechRecognizer {
|
||||
|
||||
clearCallbacks(): void {
|
||||
this.clearInactivityTimeout();
|
||||
this.clearNoSpeechTimeout();
|
||||
this.endpointing = null;
|
||||
this.endOfSpeechHandler = null;
|
||||
this.pendingEndOfSpeechReason = null;
|
||||
this.endOfSpeechEmitted = true;
|
||||
this.noSpeechDeadlineAt = null;
|
||||
this.awaitingRestart = false;
|
||||
this.suppressStartCallbacks = false;
|
||||
this.onResultCallbacks = [];
|
||||
this.onInterimResultCallbacks = [];
|
||||
this.onErrorCallbacks = [];
|
||||
|
||||
@@ -56,6 +56,7 @@ import { useSessionStatus } from "@/stores/sessionStatusStore";
|
||||
import type { PageCommandActions } from "@/lib/builtinCommands";
|
||||
import { useRedoMessage, useUndoMessage } from "@/hooks/useUndoMessage";
|
||||
import { usePermissions, useForms } from "@/contexts/EventContext";
|
||||
import { SessionTranscriptContext, type SessionTranscriptSnapshot } from "@/contexts/session-transcript-context";
|
||||
import type { FormInfo, SessionMessageInfo } from "@opencode-manager/shared/opencode";
|
||||
import type { SkillFileInfo } from "@opencode-manager/shared";
|
||||
import { formatOpenCodeModelRef } from "@opencode-manager/shared/opencode";
|
||||
@@ -152,6 +153,7 @@ export function SessionDetail() {
|
||||
const [selectedFilePath, setSelectedFilePath] = useState<string | undefined>();
|
||||
const [showScrollButton, setShowScrollButton] = useState(false);
|
||||
const [hasPromptContent, setHasPromptContent] = useState(false);
|
||||
const [isVoiceConversationActive, setIsVoiceConversationActive] = useState(false);
|
||||
const [minimizedFormId, setMinimizedFormId] = useState<string | null>(null);
|
||||
const [sideQuestion, setSideQuestion] = useState<{ id: number; question: string } | null>(null);
|
||||
const [messagePickerMode, setMessagePickerMode] = useState<'fork' | 'timeline' | null>(null);
|
||||
@@ -273,6 +275,11 @@ export function SessionDetail() {
|
||||
[transcriptMessages, session?.revert?.messageID],
|
||||
);
|
||||
|
||||
const transcriptSnapshot = useMemo<SessionTranscriptSnapshot>(
|
||||
() => ({ messages, pending: pendingPrompts, status: transcriptStatus }),
|
||||
[messages, pendingPrompts, transcriptStatus],
|
||||
);
|
||||
|
||||
const messagesRef = useRef(messages);
|
||||
messagesRef.current = messages;
|
||||
|
||||
@@ -365,6 +372,7 @@ export function SessionDetail() {
|
||||
sessionId: sessionId ?? '',
|
||||
lastAssistantMessage,
|
||||
lastAssistantText,
|
||||
enabled: !isVoiceConversationActive,
|
||||
});
|
||||
|
||||
const handleShowSessionsDialog = useCallback(() => setSessionsDialogOpen(true), []);
|
||||
@@ -908,7 +916,7 @@ export function SessionDetail() {
|
||||
>
|
||||
{!isFormSheetOpen && (
|
||||
<div className="absolute bottom-full right-[3%] md:right-0 mb-2 z-50 flex flex-col items-end gap-2">
|
||||
{ttsEnabled && !hasPromptContent && !isSessionActive && latestPlayableAssistant && (
|
||||
{ttsEnabled && !isVoiceConversationActive && !hasPromptContent && !isSessionActive && latestPlayableAssistant && (
|
||||
<FloatingTTSButton
|
||||
messageId={latestPlayableAssistant.messageId}
|
||||
content={latestPlayableAssistant.text}
|
||||
@@ -973,17 +981,20 @@ export function SessionDetail() {
|
||||
onChildSessionClick={handleChildSessionClick}
|
||||
/>
|
||||
</div>
|
||||
<PromptInput
|
||||
ref={promptInputRef}
|
||||
directory={sessionDirectory}
|
||||
sessionID={sessionId}
|
||||
showScrollButton={showScrollButton}
|
||||
isSessionActive={isSessionActive}
|
||||
isStreamingResponse={isStreamingResponse}
|
||||
onScrollToBottom={scrollToBottom}
|
||||
commandActions={commandActions}
|
||||
onPromptChange={setHasPromptContent}
|
||||
/>
|
||||
<SessionTranscriptContext.Provider value={transcriptSnapshot}>
|
||||
<PromptInput
|
||||
ref={promptInputRef}
|
||||
directory={sessionDirectory}
|
||||
sessionID={sessionId}
|
||||
onVoiceConversationActiveChange={setIsVoiceConversationActive}
|
||||
showScrollButton={showScrollButton}
|
||||
isSessionActive={isSessionActive}
|
||||
isStreamingResponse={isStreamingResponse}
|
||||
onScrollToBottom={scrollToBottom}
|
||||
commandActions={commandActions}
|
||||
onPromptChange={setHasPromptContent}
|
||||
/>
|
||||
</SessionTranscriptContext.Provider>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -5,8 +5,35 @@ import { renderHook } from '@testing-library/react'
|
||||
import { MemoryRouter, useLocation } from 'react-router-dom'
|
||||
import { vi } from 'vitest'
|
||||
import type { useSettings } from '@/hooks/useSettings'
|
||||
import type { VoiceConversationController } from '@/hooks/useVoiceConversation'
|
||||
import { BUILTIN_COMMAND_ACTIONS, type CommandActions } from '@/lib/builtinCommands'
|
||||
|
||||
export function createVoiceConversationControllerMock(
|
||||
overrides: Partial<VoiceConversationController> = {},
|
||||
): VoiceConversationController {
|
||||
return {
|
||||
isActive: false,
|
||||
phase: 'off',
|
||||
label: 'Voice conversation',
|
||||
hint: '',
|
||||
orbLabel: 'Voice conversation',
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
export function createCommandActionsMock(): CommandActions {
|
||||
return Object.fromEntries(
|
||||
BUILTIN_COMMAND_ACTIONS.map((action) => [action, vi.fn()]),
|
||||
|
||||
@@ -125,6 +125,42 @@ export {
|
||||
parseOpenCodeVersionOutput,
|
||||
} from './release'
|
||||
|
||||
export {
|
||||
DEFAULT_VOICE_PAUSE_MS,
|
||||
VOICE_NO_SPEECH_TIMEOUT_MS,
|
||||
VOICE_PAUSE_OPTIONS_MS,
|
||||
VOICE_PAUSE_STORAGE_KEY,
|
||||
formatVoicePauseMs,
|
||||
isVoicePauseOption,
|
||||
normalizeVoicePauseMs,
|
||||
parseVoicePauseMs,
|
||||
} from './voicePauseSetting'
|
||||
|
||||
export {
|
||||
INITIAL_VOICE_CONVERSATION_STATE,
|
||||
VOICE_MODE_INSTRUCTIONS,
|
||||
VOICE_MODE_INSTRUCTION_KEY,
|
||||
findNextUnspokenMessage,
|
||||
hasIncompleteAssistant,
|
||||
hasSpokenMessage,
|
||||
isVoiceTurnComplete,
|
||||
listUnspokenMessages,
|
||||
reduceVoiceConversation,
|
||||
voiceConversationHint,
|
||||
voiceConversationLabel,
|
||||
} from './voiceConversation'
|
||||
|
||||
export type {
|
||||
VoiceConversationEvent,
|
||||
VoiceConversationLabelInput,
|
||||
VoiceConversationState,
|
||||
VoicePauseReason,
|
||||
VoicePhase,
|
||||
VoiceSessionStatus,
|
||||
VoiceSpokenMessage,
|
||||
VoiceTurnCompletionInput,
|
||||
} from './voiceConversation'
|
||||
|
||||
export { OPENCODE_LIFECYCLE_STATES, OPENCODE_RECOVERY_ACTIONS } from './lifecycle'
|
||||
|
||||
export type { OpenCodeLifecycleState, OpenCodeLifecycleStatus, OpenCodeRecoveryAction } from './lifecycle'
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
import type { SessionMessageInfo, SessionStatus } from '@opencode/client'
|
||||
|
||||
import { assistantText } from './content'
|
||||
|
||||
/** Key under which the voice conversation instructions are stored on a session. */
|
||||
export const VOICE_MODE_INSTRUCTION_KEY = 'voice-mode'
|
||||
|
||||
/** Session instructions that make every assistant reply suitable for reading aloud. */
|
||||
export const VOICE_MODE_INSTRUCTIONS =
|
||||
'Every reply will be read aloud in full by text-to-speech. Write plain, conversational spoken sentences. Never include file paths, filenames, line numbers, URLs, code, commands, markdown, lists, tables or symbols; describe code by what it does instead. Say numbers naturally. Lead with the outcome and keep it to a few sentences unless asked for detail. End with a direct question when you need input. This changes only how replies are written, not how thoroughly you work or use tools, and it takes precedence over other formatting guidance while active.'
|
||||
|
||||
/**
|
||||
* The stage a hands-free voice conversation is currently in. `recording`
|
||||
* captures a message that is added to the session queue while the agent keeps
|
||||
* working, so it is separate from the `listening` stage that opens a new turn.
|
||||
*/
|
||||
export type VoicePhase =
|
||||
| 'off'
|
||||
| 'listening'
|
||||
| 'sending'
|
||||
| 'working'
|
||||
| 'speaking'
|
||||
| 'recording'
|
||||
| 'paused'
|
||||
|
||||
/** Why a paused voice conversation stopped listening. */
|
||||
export type VoicePauseReason = 'user' | 'background' | 'no-speech' | 'error'
|
||||
|
||||
/** The reported status of a session, as a session transcript carries it. */
|
||||
export type VoiceSessionStatus = SessionStatus['type']
|
||||
|
||||
/** Everything needed to resume or label a hands-free voice conversation. */
|
||||
export interface VoiceConversationState {
|
||||
/** Current stage of the conversation loop. */
|
||||
phase: VoicePhase
|
||||
/** Why the conversation is paused, or null when it is not paused. */
|
||||
pauseReason: VoicePauseReason | null
|
||||
/** Message shown to the user after a failure, or null when there is none. */
|
||||
error: string | null
|
||||
/**
|
||||
* Id of the transcript message whose successors the conversation reads
|
||||
* aloud, or null when the whole transcript is in scope. Replies after it are
|
||||
* read one by one, including replies to messages queued during the turn.
|
||||
*/
|
||||
baselineId: string | null
|
||||
/** Whether the session has reported being busy since the current turn was sent. */
|
||||
sawBusy: boolean
|
||||
}
|
||||
|
||||
/** State of a voice conversation that is not running. */
|
||||
export const INITIAL_VOICE_CONVERSATION_STATE: VoiceConversationState = {
|
||||
phase: 'off',
|
||||
pauseReason: null,
|
||||
error: null,
|
||||
baselineId: null,
|
||||
sawBusy: false,
|
||||
}
|
||||
|
||||
/** A signal from the voice conversation controller or the session. */
|
||||
export type VoiceConversationEvent =
|
||||
| { type: 'start'; busy: boolean; baselineId: string | null }
|
||||
| { type: 'transcript'; text: string }
|
||||
| { type: 'turn-sent'; baselineId: string | null }
|
||||
| { type: 'turn-started'; baselineId: string | null }
|
||||
| { type: 'send-failed'; message: string }
|
||||
| { type: 'status'; busy: boolean }
|
||||
| { type: 'speak-start' }
|
||||
| { type: 'speech-ended' }
|
||||
| { type: 'skip' }
|
||||
| { type: 'record' }
|
||||
| { type: 'record-ended' }
|
||||
| { type: 'turn-complete' }
|
||||
| { type: 'no-speech' }
|
||||
| { type: 'pause'; reason: VoicePauseReason }
|
||||
| { type: 'resume'; busy: boolean; baselineId: string | null }
|
||||
| { type: 'resume-speech' }
|
||||
| { type: 'error'; message: string }
|
||||
| { type: 'exit' }
|
||||
|
||||
/** An assistant message the conversation reads aloud. */
|
||||
export interface VoiceSpokenMessage {
|
||||
/** Id of the assistant message. */
|
||||
id: string
|
||||
/** Trimmed spoken text of the message, which is never empty. */
|
||||
text: string
|
||||
}
|
||||
|
||||
/** Session data used to decide whether the current turn is finished. */
|
||||
export interface VoiceTurnCompletionInput {
|
||||
/** Reported session status for the active session. */
|
||||
status: VoiceSessionStatus
|
||||
/** Whether the session has reported being busy since the current turn started. */
|
||||
sawBusy: boolean
|
||||
/** Whether a message of the current turn was read aloud. */
|
||||
spoke: boolean
|
||||
/** Whether the session still holds prompts queued by the user. */
|
||||
hasPendingPrompts: boolean
|
||||
/** Whether an assistant message after the baseline is still streaming. */
|
||||
hasIncomplete: boolean
|
||||
}
|
||||
|
||||
/** Inputs that determine the text shown for the voice conversation. */
|
||||
export interface VoiceConversationLabelInput {
|
||||
/** Current stage of the conversation loop. */
|
||||
phase: VoicePhase
|
||||
/** Why the conversation is paused, or null when it is not paused. */
|
||||
pauseReason: VoicePauseReason | null
|
||||
/** Whether the session is waiting for the user to approve a tool. */
|
||||
pendingApproval: boolean
|
||||
/** Whether the current recording has stopped and is being finalized. */
|
||||
isEndpointing: boolean
|
||||
/** Whether a reading is held mid-reply after a pause. */
|
||||
isPlaybackPaused: boolean
|
||||
/** Whether the session is still working on the current turn. */
|
||||
sessionBusy: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies one voice conversation event to the loop state. Events that do not
|
||||
* apply to the current phase are ignored, and the previous state object is
|
||||
* returned unchanged so callers can skip re-rendering on no-ops.
|
||||
*
|
||||
* @param state The current conversation state.
|
||||
* @param event The event to apply.
|
||||
* @returns The next state, or the same state object when the event does not apply.
|
||||
*/
|
||||
export function reduceVoiceConversation(
|
||||
state: VoiceConversationState,
|
||||
event: VoiceConversationEvent,
|
||||
): VoiceConversationState {
|
||||
switch (event.type) {
|
||||
case 'start':
|
||||
if (state.phase !== 'off') return state
|
||||
return event.busy
|
||||
? {
|
||||
phase: 'working',
|
||||
pauseReason: null,
|
||||
error: null,
|
||||
sawBusy: true,
|
||||
baselineId: event.baselineId,
|
||||
}
|
||||
: {
|
||||
phase: 'listening',
|
||||
pauseReason: null,
|
||||
error: null,
|
||||
sawBusy: false,
|
||||
baselineId: null,
|
||||
}
|
||||
case 'transcript':
|
||||
if (state.phase !== 'listening') return state
|
||||
return event.text.trim()
|
||||
? { ...state, phase: 'sending' }
|
||||
: { ...state, phase: 'paused', pauseReason: 'no-speech' }
|
||||
case 'turn-sent':
|
||||
if (state.phase !== 'sending') return state
|
||||
return { ...state, phase: 'working', sawBusy: false, baselineId: event.baselineId }
|
||||
case 'turn-started':
|
||||
if (state.phase !== 'listening') return state
|
||||
return { ...state, phase: 'working', sawBusy: true, baselineId: event.baselineId }
|
||||
case 'send-failed':
|
||||
if (state.phase !== 'sending' && state.phase !== 'working') return state
|
||||
return { ...state, phase: 'paused', pauseReason: 'error', error: event.message }
|
||||
case 'status':
|
||||
if (state.phase !== 'working') return state
|
||||
if (!event.busy || state.sawBusy) return state
|
||||
return { ...state, sawBusy: true }
|
||||
case 'speak-start':
|
||||
if (state.phase !== 'working') return state
|
||||
return { ...state, phase: 'speaking' }
|
||||
case 'speech-ended':
|
||||
if (state.phase !== 'speaking') return state
|
||||
return { ...state, phase: 'working' }
|
||||
case 'skip':
|
||||
if (state.phase !== 'speaking') return state
|
||||
return { ...state, phase: 'listening' }
|
||||
case 'record':
|
||||
if (state.phase !== 'working' && state.phase !== 'speaking') return state
|
||||
return { ...state, phase: 'recording' }
|
||||
case 'record-ended':
|
||||
if (state.phase !== 'recording') return state
|
||||
return { ...state, phase: 'working' }
|
||||
case 'turn-complete':
|
||||
if (state.phase !== 'working') return state
|
||||
return { ...state, phase: 'listening' }
|
||||
case 'no-speech':
|
||||
if (state.phase !== 'listening') return state
|
||||
return { ...state, phase: 'paused', pauseReason: 'no-speech' }
|
||||
case 'pause':
|
||||
if (state.phase === 'off' || state.phase === 'paused') return state
|
||||
return { ...state, phase: 'paused', pauseReason: event.reason }
|
||||
case 'resume':
|
||||
if (state.phase !== 'paused') return state
|
||||
return event.busy
|
||||
? {
|
||||
...state,
|
||||
phase: 'working',
|
||||
sawBusy: true,
|
||||
baselineId: event.baselineId,
|
||||
pauseReason: null,
|
||||
error: null,
|
||||
}
|
||||
: {
|
||||
...state,
|
||||
phase: 'listening',
|
||||
sawBusy: false,
|
||||
baselineId: null,
|
||||
pauseReason: null,
|
||||
error: null,
|
||||
}
|
||||
case 'resume-speech':
|
||||
if (state.phase !== 'paused') return state
|
||||
return { ...state, phase: 'speaking', pauseReason: null, error: null }
|
||||
case 'error':
|
||||
if (state.phase === 'off') return state
|
||||
return { ...state, phase: 'paused', pauseReason: 'error', error: event.message }
|
||||
case 'exit':
|
||||
return INITIAL_VOICE_CONVERSATION_STATE
|
||||
default:
|
||||
return state
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the index of the first message the conversation may read. Messages at
|
||||
* or before the baseline are excluded; a null or unknown baseline leaves the
|
||||
* whole transcript in scope.
|
||||
*
|
||||
* @param messages The session transcript, oldest first.
|
||||
* @param baselineId Id of the message the turn starts after.
|
||||
* @returns The index of the first message in scope.
|
||||
*/
|
||||
function spokenWindowStart(
|
||||
messages: readonly SessionMessageInfo[],
|
||||
baselineId: string | null,
|
||||
): number {
|
||||
if (baselineId === null) return 0
|
||||
const baselineIndex = messages.findIndex((message) => message.id === baselineId)
|
||||
return baselineIndex === -1 ? 0 : baselineIndex + 1
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists every completed assistant message with text that the conversation has
|
||||
* not read yet, oldest first. Messages are read in the order they arrive, so a
|
||||
* user message inside the window does not end the scan: replies to prompts
|
||||
* queued during the turn are read as well.
|
||||
*
|
||||
* @param messages The session transcript, oldest first.
|
||||
* @param baselineId Id of the message the turn starts after.
|
||||
* @param spokenIds Ids of the messages already read aloud.
|
||||
* @returns The unread messages, oldest first.
|
||||
*/
|
||||
export function listUnspokenMessages(
|
||||
messages: readonly SessionMessageInfo[],
|
||||
baselineId: string | null,
|
||||
spokenIds: ReadonlySet<string>,
|
||||
): VoiceSpokenMessage[] {
|
||||
const unspoken: VoiceSpokenMessage[] = []
|
||||
for (let index = spokenWindowStart(messages, baselineId); index < messages.length; index += 1) {
|
||||
const message = messages[index]
|
||||
if (message === undefined || message.type !== 'assistant') continue
|
||||
if (message.time.completed === undefined) continue
|
||||
if (spokenIds.has(message.id)) continue
|
||||
const text = assistantText(message.content, { stripThink: true }).trim()
|
||||
if (!text) continue
|
||||
unspoken.push({ id: message.id, text })
|
||||
}
|
||||
return unspoken
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the message the conversation reads next: the oldest unread message that
|
||||
* has already completed.
|
||||
*
|
||||
* @param messages The session transcript, oldest first.
|
||||
* @param baselineId Id of the message the turn starts after.
|
||||
* @param spokenIds Ids of the messages already read aloud.
|
||||
* @returns The next message to read, or null when there is nothing to read.
|
||||
*/
|
||||
export function findNextUnspokenMessage(
|
||||
messages: readonly SessionMessageInfo[],
|
||||
baselineId: string | null,
|
||||
spokenIds: ReadonlySet<string>,
|
||||
): VoiceSpokenMessage | null {
|
||||
return listUnspokenMessages(messages, baselineId, spokenIds)[0] ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides whether any message of the current turn has been read aloud, which
|
||||
* lets a turn that produced a reply finish without ever reporting itself busy.
|
||||
*
|
||||
* @param messages The session transcript, oldest first.
|
||||
* @param baselineId Id of the message the turn starts after.
|
||||
* @param spokenIds Ids of the messages already read aloud.
|
||||
* @returns Whether a message after the baseline has been read.
|
||||
*/
|
||||
export function hasSpokenMessage(
|
||||
messages: readonly SessionMessageInfo[],
|
||||
baselineId: string | null,
|
||||
spokenIds: ReadonlySet<string>,
|
||||
): boolean {
|
||||
return messages
|
||||
.slice(spokenWindowStart(messages, baselineId))
|
||||
.some((message) => spokenIds.has(message.id))
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether the turn still produces an assistant message, which keeps the
|
||||
* turn open so the rest of a just-finished reply can still be read.
|
||||
*
|
||||
* @param messages The session transcript, oldest first.
|
||||
* @param baselineId Id of the message the turn starts after.
|
||||
* @returns Whether an assistant message after the baseline is still streaming.
|
||||
*/
|
||||
export function hasIncompleteAssistant(
|
||||
messages: readonly SessionMessageInfo[],
|
||||
baselineId: string | null,
|
||||
): boolean {
|
||||
return messages
|
||||
.slice(spokenWindowStart(messages, baselineId))
|
||||
.some((message) => message.type === 'assistant' && message.time.completed === undefined)
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides whether the session has finished the current turn. The turn is over
|
||||
* only when the session is idle, holds no prompt the user queued during it, and
|
||||
* has no reply still streaming, and when the turn showed activity — a busy
|
||||
* report or a message that was read aloud. Callers only ask once every eligible
|
||||
* message has been read, so an unread message keeps the turn open by
|
||||
* construction.
|
||||
*
|
||||
* @param input The session status and the turn's queued, streaming and spoken state.
|
||||
* @returns Whether the turn is over.
|
||||
*/
|
||||
export function isVoiceTurnComplete(input: VoiceTurnCompletionInput): boolean {
|
||||
return (
|
||||
input.status === 'idle' &&
|
||||
!input.hasPendingPrompts &&
|
||||
!input.hasIncomplete &&
|
||||
(input.sawBusy || input.spoke)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Produces the short status text shown on the status line while a voice
|
||||
* conversation is active. The text never names the next action, so a single
|
||||
* line describes the phase without growing or shifting the bar.
|
||||
*
|
||||
* @param input The current phase, pause reason and session signals.
|
||||
* @returns The status to display, or an empty string when voice mode is off.
|
||||
*/
|
||||
export function voiceConversationLabel(input: VoiceConversationLabelInput): string {
|
||||
const { phase, pauseReason, pendingApproval } = input
|
||||
|
||||
switch (phase) {
|
||||
case 'listening':
|
||||
return 'Listening'
|
||||
case 'sending':
|
||||
return 'Sending…'
|
||||
case 'working':
|
||||
return pendingApproval ? 'Needs your approval' : 'Working'
|
||||
case 'speaking':
|
||||
return 'Speaking'
|
||||
case 'recording':
|
||||
return 'Adding to queue'
|
||||
case 'paused':
|
||||
if (pauseReason === 'no-speech') return "Didn't catch that"
|
||||
if (pauseReason === 'error') return 'Something went wrong'
|
||||
return 'Paused'
|
||||
case 'off':
|
||||
return ''
|
||||
default:
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Produces the action hint shown directly under the conversation orb, which
|
||||
* names what a tap does in the current phase and state.
|
||||
*
|
||||
* @param input The current phase, pause reason and session signals.
|
||||
* @returns The hint to display, or an empty string when the orb has no action.
|
||||
*/
|
||||
export function voiceConversationHint(input: VoiceConversationLabelInput): string {
|
||||
const { phase, pauseReason, pendingApproval, isEndpointing, isPlaybackPaused, sessionBusy } =
|
||||
input
|
||||
|
||||
switch (phase) {
|
||||
case 'listening':
|
||||
return isEndpointing ? '' : 'Tap to send'
|
||||
case 'sending':
|
||||
return ''
|
||||
case 'working':
|
||||
return pendingApproval ? '' : 'Tap to add a message'
|
||||
case 'speaking':
|
||||
return sessionBusy ? 'Tap to add a message' : 'Tap to skip'
|
||||
case 'recording':
|
||||
return 'Tap to queue'
|
||||
case 'paused':
|
||||
if (pauseReason === 'no-speech') return 'Tap to talk'
|
||||
if (pauseReason === 'error') return 'Tap to retry'
|
||||
return isPlaybackPaused ? 'Tap to continue' : 'Tap to talk'
|
||||
case 'off':
|
||||
return ''
|
||||
default:
|
||||
return ''
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/** Storage key under which a device persists the pause-before-sending duration. */
|
||||
export const VOICE_PAUSE_STORAGE_KEY = 'voice.pauseBeforeSendingMs'
|
||||
|
||||
/**
|
||||
* Pause durations, in milliseconds, offered by the pause-before-sending picker.
|
||||
* A stored or requested value outside this list is treated as absent.
|
||||
*/
|
||||
export const VOICE_PAUSE_OPTIONS_MS = [800, 1200, 1600, 2000, 3000] as const
|
||||
|
||||
/**
|
||||
* Pause duration applied before the first stored value is hydrated, and the
|
||||
* value persisted when storage holds nothing usable.
|
||||
*/
|
||||
export const DEFAULT_VOICE_PAUSE_MS = 1200
|
||||
|
||||
/**
|
||||
* Fixed silence timeout, in milliseconds, that ends a hands-free voice turn.
|
||||
* Not user-adjustable and therefore independent of the pause preference.
|
||||
*/
|
||||
export const VOICE_NO_SPEECH_TIMEOUT_MS = 10_000
|
||||
|
||||
/**
|
||||
* Reports whether `value` is one of the selectable pause durations.
|
||||
*
|
||||
* @param value Candidate pause duration in milliseconds.
|
||||
* @returns Whether the value is offered by the pause-before-sending picker.
|
||||
*/
|
||||
export function isVoicePauseOption(value: number): boolean {
|
||||
return (VOICE_PAUSE_OPTIONS_MS as readonly number[]).includes(value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a stored pause duration. A value that is not one of
|
||||
* {@link VOICE_PAUSE_OPTIONS_MS} is treated as absent, so the caller keeps
|
||||
* {@link DEFAULT_VOICE_PAUSE_MS}.
|
||||
*
|
||||
* @param raw The stored string.
|
||||
* @returns The pause duration in milliseconds, or undefined when it is unusable.
|
||||
*/
|
||||
export function parseVoicePauseMs(raw: string): number | undefined {
|
||||
const ms = Number(raw)
|
||||
return isVoicePauseOption(ms) ? ms : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a requested pause duration. A value that is not one of
|
||||
* {@link VOICE_PAUSE_OPTIONS_MS} is rejected instead of being clamped.
|
||||
*
|
||||
* @param ms Requested pause duration in milliseconds.
|
||||
* @returns The pause duration in milliseconds, or undefined when it is unusable.
|
||||
*/
|
||||
export function normalizeVoicePauseMs(ms: number): number | undefined {
|
||||
return isVoicePauseOption(ms) ? ms : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a pause duration as the one-decimal seconds label used by the
|
||||
* pause-before-sending picker and the settings row.
|
||||
*
|
||||
* @param ms Pause duration in milliseconds.
|
||||
* @returns The label, for example `"1.2 s"` for 1200 milliseconds.
|
||||
*/
|
||||
export function formatVoicePauseMs(ms: number): string {
|
||||
return `${(ms / 1000).toFixed(1)} s`
|
||||
}
|
||||
Reference in new issue
Block a user