From f0c87ffa5dd1f59fa8f80419e4542f64f3dfc689 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Wed, 29 Apr 2026 12:26:41 -0400 Subject: [PATCH] refactor(frontend): rework speech-to-text to tap-first interaction (#207) * refactor(frontend): extract VoiceStatusOverlay component and improve swipe tracking - Extract voice status overlay to dedicated VoiceStatusOverlay.tsx component - Move pointer event handlers from button to container for larger swipe surface area - Users can now initiate swipe gesture from anywhere in the container, not just the button * refactor(frontend): add SSE delta support and improve status synchronization - Add SSEMessagePartDeltaEvent type for streaming delta updates - Add SSESessionCreatedEvent type for session creation events - Implement directory filtering for SSE events to prevent cross-contamination - Add version tracking for status snapshots to ignore stale responses - Replace individual status updates with atomic replaceStatuses operation - Refactor parts batcher to use unified operation queue with delta support - Clear stale statuses on initial snapshot and directory changes - Add tests for status snapshot clearing and stale response handling * refactor: remove auto-restart from assistant mode and fix mobile sheet close behavior Stop restarting OpenCode after assistant mode initialization since the startup error logic is no longer needed. Also fix the repo quick switch sheet to stay open when launched from the mobile tab bar, preventing unwanted navigation away from the sheet. * refactor(frontend): improve speech-to-text UI --- backend/src/routes/repos.ts | 4 - backend/test/routes/repos.test.ts | 3 + frontend/src/api/types.ts | 21 ++ .../src/components/message/PromptInput.tsx | 341 ++++++++---------- .../components/message/VoiceStatusOverlay.tsx | 72 ++++ .../navigation/RepoQuickSwitchSheet.test.tsx | 56 ++- .../navigation/RepoQuickSwitchSheet.tsx | 17 +- frontend/src/hooks/useSSE.test.tsx | 86 +++++ frontend/src/hooks/useSSE.ts | 47 ++- frontend/src/lib/partsBatcher.ts | 109 +++--- frontend/src/stores/sessionStatusStore.ts | 39 ++ 11 files changed, 525 insertions(+), 270 deletions(-) create mode 100644 frontend/src/components/message/VoiceStatusOverlay.tsx diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index 9085ad55..b7c3bf7a 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -423,10 +423,6 @@ app.get('/', async (c) => { const options = AssistantModeInitRequestSchema.parse(body) const status = await ensureAssistantMode(repo, options) - if (status.files.opencodeJson.created) { - opencodeServerManager.clearStartupError() - await restartOpenCode(openCodeSupervisor) - } return c.json(status) } catch (error: unknown) { logger.error('Failed to initialize assistant mode:', error) diff --git a/backend/test/routes/repos.test.ts b/backend/test/routes/repos.test.ts index f19b9951..8de8f436 100644 --- a/backend/test/routes/repos.test.ts +++ b/backend/test/routes/repos.test.ts @@ -37,6 +37,7 @@ vi.mock('../../src/services/opencode-single-server', () => ({ import * as db from '../../src/db/queries' import { createRepoRoutes } from '../../src/routes/repos' +import { opencodeServerManager } from '../../src/services/opencode-single-server' import type { GitAuthService } from '../../src/services/git-auth' import type { ScheduleService } from '../../src/services/schedules' import type { AssistantModeStatus } from '@opencode-manager/shared/types' @@ -215,6 +216,8 @@ describe('Repo Routes', () => { }) expect(res.status).toBe(200) + expect(opencodeServerManager.clearStartupError).not.toHaveBeenCalled() + expect(opencodeServerManager.restart).not.toHaveBeenCalled() }) it('should handle errors from ensureAssistantMode', async () => { diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index aa33fafe..a0316d82 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -43,6 +43,17 @@ export interface SSEMessagePartUpdatedEvent { } } +export interface SSEMessagePartDeltaEvent { + type: 'message.part.delta' + properties: { + sessionID: string + messageID: string + partID: string + field: string + delta: string + } +} + export interface SSEMessageUpdatedEvent { type: 'message.updated' | 'messagev2.updated' properties: { @@ -74,6 +85,14 @@ export interface SSESessionUpdatedEvent { } } +export interface SSESessionCreatedEvent { + type: 'session.created' + properties: { + sessionID: string + info: Session + } +} + export interface SSESessionDeletedEvent { type: 'session.deleted' properties: { @@ -196,9 +215,11 @@ export interface SSESSHHostKeyRequestEvent { export type SSEEvent = | SSEMessagePartUpdatedEvent + | SSEMessagePartDeltaEvent | SSEMessageUpdatedEvent | SSEMessageRemovedEvent | SSEMessagePartRemovedEvent + | SSESessionCreatedEvent | SSESessionUpdatedEvent | SSESessionDeletedEvent | SSESessionCompactedEvent diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index c96bc417..c3b0776d 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -15,7 +15,7 @@ import { useUIState } from '@/stores/uiStateStore' import { useMobile } from '@/hooks/useMobile' import { usePermissions } from '@/contexts/EventContext' -import { ArrowDown, ArrowUp, Upload, X, Mic, MicOff } from 'lucide-react' +import { ArrowDown, Upload, X, Mic, MicOff } from 'lucide-react' import { SquareFill } from '@/components/ui/square-fill' @@ -24,6 +24,7 @@ import { MentionSuggestions, type MentionItem } from './MentionSuggestions' import { SessionStatusIndicator } from '@/components/ui/session-status-indicator' import { ModelQuickSelect } from '@/components/model/ModelQuickSelect' import { AgentQuickSelect } from '@/components/agent/AgentQuickSelect' +import { VoiceStatusOverlay, type VoiceStatusOverlayState } from './VoiceStatusOverlay' import { detectMentionTrigger, parsePromptToParts, getFilename, filterAgentsByQuery } from '@/lib/promptParser' import { formatModelName, getProviders } from '@/api/providers' import { useQuery } from '@tanstack/react-query' @@ -46,7 +47,6 @@ const revokeBlobUrls = (attachments: ImageAttachment[]) => { const ACCEPTED_FILE_TYPES = [...ACCEPTED_IMAGE_TYPES, "application/pdf"] const VOICE_SEND_SWIPE_THRESHOLD = 48 -const VOICE_HOLD_ACTIVATION_MS = 200 type VoiceButtonVariant = 'desktop' | 'mobile' @@ -109,18 +109,14 @@ export const PromptInput = memo(forwardRef( const [localMode, setLocalMode] = useState(null) const [isFocused, setIsFocused] = useState(false) const [isTogglingRecording, setIsTogglingRecording] = useState(false) - const [isVoiceHoldActive, setIsVoiceHoldActive] = useState(false) const [isVoiceSwipeArmed, setIsVoiceSwipeArmed] = useState(false) const [isVoiceAutoSendPending, setIsVoiceAutoSendPending] = useState(false) + const [isVoiceAutoSendWaitingForTranscript, setIsVoiceAutoSendWaitingForTranscript] = useState(false) const lastAddedTranscriptRef = useRef('') - const voiceHoldActiveRef = useRef(false) - const voiceHoldStartYRef = useRef(null) + const voiceGestureStartYRef = useRef(null) const voiceSwipeArmedRef = useRef(false) - const voicePendingReleaseRef = useRef(false) const pendingVoiceAutoSubmitRef = useRef(false) const ignoreVoiceClickUntilRef = useRef(0) - const voiceHoldTimerRef = useRef | null>(null) - const voiceHoldActivatedRef = useRef(false) const voiceStartRequestRef = useRef(0) const handleSubmitRef = useRef<() => void>(() => {}) const pendingPromptCommand = useUIState((state) => state.pendingPromptCommand) @@ -144,26 +140,16 @@ export const PromptInput = memo(forwardRef( const textareaRef = useRef(null) const fileInputRef = useRef(null) const voiceButtonContainerRef = useRef(null) - const clearVoiceHoldTimer = useCallback(() => { - if (voiceHoldTimerRef.current) { - clearTimeout(voiceHoldTimerRef.current) - voiceHoldTimerRef.current = null - } - }, []) const resetVoiceGestureState = useCallback(() => { - clearVoiceHoldTimer() - voiceHoldActiveRef.current = false - voiceHoldActivatedRef.current = false - voiceHoldStartYRef.current = null + voiceGestureStartYRef.current = null voiceSwipeArmedRef.current = false - voicePendingReleaseRef.current = false pendingVoiceAutoSubmitRef.current = false ignoreVoiceClickUntilRef.current = 0 - setIsVoiceHoldActive(false) setIsVoiceSwipeArmed(false) setIsVoiceAutoSendPending(false) - }, [clearVoiceHoldTimer]) + setIsVoiceAutoSendWaitingForTranscript(false) + }, []) useImperativeHandle(ref, () => ({ setPromptValue: (value: string) => { @@ -448,31 +434,38 @@ export const PromptInput = memo(forwardRef( setStoredAgent(sessionID, agent) } - const handleVoiceToggle = async () => { + const startVoiceRecording = async () => { + if (isRecording || isProcessing || isTogglingRecording) { + return + } + + const startRequestId = voiceStartRequestRef.current + 1 + voiceStartRequestRef.current = startRequestId pendingVoiceAutoSubmitRef.current = false setIsVoiceAutoSendPending(false) + setIsVoiceAutoSendWaitingForTranscript(false) setIsVoiceSwipeArmed(false) voiceSwipeArmedRef.current = false - if (isRecording) { - stopRecording() - } else { - const startRequestId = voiceStartRequestRef.current + 1 - voiceStartRequestRef.current = startRequestId - setIsTogglingRecording(true) - const started = await startRecording() - if (voiceStartRequestRef.current !== startRequestId) { - setIsTogglingRecording(false) - if (started) { - abortRecording() - } - return - } - if (!started) { - setIsTogglingRecording(false) - } else if (textareaRef.current) { - textareaRef.current.blur() + 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 () => { @@ -480,101 +473,41 @@ export const PromptInput = memo(forwardRef( return } - await handleVoiceToggle() - } - - const handleVoiceHoldStart = async () => { - if (!isRecording && !isProcessing) { - const startRequestId = voiceStartRequestRef.current + 1 - voiceStartRequestRef.current = startRequestId + if (isRecording) { pendingVoiceAutoSubmitRef.current = false setIsVoiceAutoSendPending(false) - voiceHoldActivatedRef.current = true - setIsTogglingRecording(true) - const started = await startRecording() - if (voiceStartRequestRef.current !== startRequestId) { - setIsTogglingRecording(false) - if (started) { - abortRecording() - } - return - } - if (!started) { - setIsTogglingRecording(false) - } else { - if (typeof navigator !== 'undefined' && navigator.vibrate) { - navigator.vibrate(10) - } - if (textareaRef.current) { - textareaRef.current.blur() - } - } - } - } - - const handleVoiceHoldEnd = (shouldAutoSend: boolean) => { - setIsVoiceHoldActive(false) - setIsVoiceSwipeArmed(false) - voiceHoldActivatedRef.current = false - voiceHoldStartYRef.current = null - voiceSwipeArmedRef.current = false - pendingVoiceAutoSubmitRef.current = shouldAutoSend - setIsVoiceAutoSendPending(shouldAutoSend) - - if (isRecording) { - if (typeof navigator !== 'undefined' && navigator.vibrate) { - navigator.vibrate([10, 20, 10]) - } + setIsVoiceAutoSendWaitingForTranscript(false) + setIsVoiceSwipeArmed(false) + voiceSwipeArmedRef.current = false stopRecording() - } else if (isTogglingRecording) { - voicePendingReleaseRef.current = true - } - } - - const handleVoicePointerDown = async (event: ReactPointerEvent) => { - if ((event.pointerType === 'mouse' && event.button !== 0) || disabled || isProcessing) { return } - voiceHoldStartYRef.current = event.clientY - voiceHoldActiveRef.current = true + await startVoiceRecording() + } + + const handleVoicePointerDown = (event: ReactPointerEvent) => { + if ((event.pointerType === 'mouse' && event.button !== 0) || disabled || isProcessing || !isRecording) { + return + } + + voiceGestureStartYRef.current = event.clientY voiceSwipeArmedRef.current = false - voicePendingReleaseRef.current = false - pendingVoiceAutoSubmitRef.current = false - setIsVoiceHoldActive(true) setIsVoiceSwipeArmed(false) - setIsVoiceAutoSendPending(false) if (event.currentTarget.setPointerCapture) { event.currentTarget.setPointerCapture(event.pointerId) } - - voiceHoldTimerRef.current = setTimeout(() => { - if (voiceHoldActiveRef.current && voiceHoldStartYRef.current !== null && !voiceHoldActivatedRef.current) { - handleVoiceHoldStart() - } - }, VOICE_HOLD_ACTIVATION_MS) } - const handleVoicePointerMove = (event: ReactPointerEvent) => { - if (!voiceHoldActiveRef.current || voiceHoldStartYRef.current === null) { + const handleVoicePointerMove = (event: ReactPointerEvent) => { + if (!isRecording || voiceGestureStartYRef.current === null) { return } - const deltaY = voiceHoldStartYRef.current - event.clientY + const deltaY = voiceGestureStartYRef.current - event.clientY const nextIsSwipeArmed = deltaY >= VOICE_SEND_SWIPE_THRESHOLD - if (nextIsSwipeArmed && !voiceSwipeArmedRef.current) { - clearVoiceHoldTimer() - voiceHoldActivatedRef.current = true - voiceSwipeArmedRef.current = true - setIsVoiceSwipeArmed(true) - setIsVoiceHoldActive(true) - ignoreVoiceClickUntilRef.current = Date.now() + 400 - handleVoiceHoldStart() - return - } - if (nextIsSwipeArmed !== voiceSwipeArmedRef.current) { voiceSwipeArmedRef.current = nextIsSwipeArmed setIsVoiceSwipeArmed(nextIsSwipeArmed) @@ -585,22 +518,40 @@ export const PromptInput = memo(forwardRef( } } - const handleVoicePointerEnd = (event: ReactPointerEvent, canceled = false) => { + const handleVoicePointerEnd = (event: ReactPointerEvent, canceled = false) => { if (event.currentTarget.releasePointerCapture && event.currentTarget.hasPointerCapture(event.pointerId)) { event.currentTarget.releasePointerCapture(event.pointerId) } - if (!voiceHoldActivatedRef.current) { - clearVoiceHoldTimer() - voiceHoldActiveRef.current = false - setIsVoiceHoldActive(false) - voiceHoldStartYRef.current = null + if (voiceGestureStartYRef.current === null) { + return + } + + voiceGestureStartYRef.current = null + + if (canceled || !voiceSwipeArmedRef.current) { + ignoreVoiceClickUntilRef.current = Date.now() + 400 + voiceSwipeArmedRef.current = false + setIsVoiceSwipeArmed(false) + pendingVoiceAutoSubmitRef.current = false + setIsVoiceAutoSendPending(false) + setIsVoiceAutoSendWaitingForTranscript(false) + stopRecording() return } ignoreVoiceClickUntilRef.current = Date.now() + 400 - voiceHoldActiveRef.current = false - handleVoiceHoldEnd(canceled ? false : voiceSwipeArmedRef.current) + voiceSwipeArmedRef.current = false + setIsVoiceSwipeArmed(false) + pendingVoiceAutoSubmitRef.current = true + setIsVoiceAutoSendPending(true) + setIsVoiceAutoSendWaitingForTranscript(true) + + if (typeof navigator !== 'undefined' && navigator.vibrate) { + navigator.vibrate([10, 20, 10]) + } + + stopRecording() } const cancelVoiceInput = useCallback(() => { @@ -614,7 +565,7 @@ export const PromptInput = memo(forwardRef( }, [abortRecording, isProcessing, isRecording, isTogglingRecording, resetVoiceGestureState]) useEffect(() => { - const isVoiceFeedbackVisible = isVoiceHoldActive || isRecording || isTogglingRecording || isProcessing || isVoiceAutoSendPending + const isVoiceFeedbackVisible = isRecording || isTogglingRecording || isProcessing || isVoiceAutoSendPending if (!isVoiceFeedbackVisible) { return @@ -631,6 +582,24 @@ export const PromptInput = memo(forwardRef( return } + if (isRecording) { + voiceGestureStartYRef.current = null + voiceSwipeArmedRef.current = false + pendingVoiceAutoSubmitRef.current = false + setIsVoiceSwipeArmed(false) + setIsVoiceAutoSendPending(false) + setIsVoiceAutoSendWaitingForTranscript(false) + stopRecording() + return + } + + if (isProcessing || isVoiceAutoSendPending) { + pendingVoiceAutoSubmitRef.current = false + setIsVoiceAutoSendPending(false) + setIsVoiceAutoSendWaitingForTranscript(false) + return + } + cancelVoiceInput() } @@ -639,7 +608,7 @@ export const PromptInput = memo(forwardRef( return () => { document.removeEventListener('pointerdown', handleOutsidePointerDown, true) } - }, [cancelVoiceInput, isProcessing, isRecording, isTogglingRecording, isVoiceAutoSendPending, isVoiceHoldActive]) + }, [cancelVoiceInput, isProcessing, isRecording, isTogglingRecording, isVoiceAutoSendPending, stopRecording]) useEffect(() => { const textToUse = transcript || interimTranscript @@ -655,6 +624,8 @@ export const PromptInput = memo(forwardRef( if (!pendingVoiceAutoSubmitRef.current) { textareaRef.current?.focus() + } else { + setIsVoiceAutoSendWaitingForTranscript(false) } } } @@ -673,31 +644,21 @@ export const PromptInput = memo(forwardRef( }, [isTogglingRecording]) useEffect(() => { - if (isRecording && voicePendingReleaseRef.current) { - voicePendingReleaseRef.current = false - - if (typeof navigator !== 'undefined' && navigator.vibrate) { - navigator.vibrate([10, 20, 10]) - } - - stopRecording() - } - }, [isRecording, stopRecording]) - - useEffect(() => { - if (!pendingVoiceAutoSubmitRef.current || isRecording || isProcessing || !prompt.trim()) { + if (!pendingVoiceAutoSubmitRef.current || isVoiceAutoSendWaitingForTranscript || isRecording || isProcessing || !prompt.trim()) { return } pendingVoiceAutoSubmitRef.current = false setIsVoiceAutoSendPending(false) + setIsVoiceAutoSendWaitingForTranscript(false) handleSubmitRef.current() - }, [prompt, isRecording, isProcessing]) + }, [prompt, isRecording, isProcessing, isVoiceAutoSendWaitingForTranscript]) useEffect(() => { if (pendingVoiceAutoSubmitRef.current && !isRecording && !isProcessing && !transcript.trim() && !interimTranscript.trim()) { pendingVoiceAutoSubmitRef.current = false setIsVoiceAutoSendPending(false) + setIsVoiceAutoSendWaitingForTranscript(false) } }, [isRecording, isProcessing, transcript, interimTranscript]) @@ -1046,53 +1007,55 @@ const { model, modelString, setModel: setStoredModel } = useModelSelection(opcod const { hasVariants, currentVariant, cycleVariant } = useVariants(opcodeUrl, directory) const showStopButton = isSessionActive const hideSecondaryButtons = isMobile && isSessionActive - const showVoiceFeedback = isVoiceHoldActive || isRecording || isTogglingRecording || isProcessing || isVoiceAutoSendPending - const voiceFeedbackLabel = isProcessing - ? isVoiceAutoSendPending + const voiceFeedbackState: VoiceStatusOverlayState | null = isTogglingRecording + ? 'starting' + : isProcessing + ? isVoiceAutoSendPending + ? 'sending' + : 'processing' + : isRecording + ? isVoiceSwipeArmed + ? 'readyToSend' + : 'recording' + : isVoiceAutoSendPending + ? 'sending' + : null + const showVoiceFeedback = voiceFeedbackState !== null + const voiceFeedbackLabel = voiceFeedbackState === 'starting' + ? 'Starting microphone...' + : voiceFeedbackState === 'sending' ? 'Transcribing and sending...' - : 'Transcribing...' - : isRecording - ? isVoiceSwipeArmed - ? 'Release to send' - : 'Recording... swipe up to send' - : isTogglingRecording || isVoiceHoldActive - ? 'Starting microphone...' - : null - const voiceButtonTitle = isProcessing - ? 'Transcribing speech' - : isRecording - ? isVoiceSwipeArmed - ? 'Release to send' - : 'Release to transcribe' - : 'Tap or hold to speak' + : voiceFeedbackState === 'processing' + ? 'Transcribing...' + : voiceFeedbackState === 'readyToSend' + ? 'Release to send' + : voiceFeedbackState === 'recording' + ? 'Recording... swipe up to send' + : null + const voiceButtonTitle = voiceFeedbackState === 'starting' + ? 'Starting microphone' + : voiceFeedbackState === 'sending' + ? 'Transcribing and sending speech' + : voiceFeedbackState === 'processing' + ? 'Transcribing speech' + : voiceFeedbackState === 'readyToSend' + ? 'Release to send' + : voiceFeedbackState === 'recording' + ? 'Tap to transcribe' + : 'Tap to speak' - const renderVoiceStatusOverlay = () => { - if (!showVoiceFeedback || !voiceFeedbackLabel) { - return null - } - return ( -
- {voiceFeedbackLabel} -
-
-
- - Swipe -
- Send -
-
- ) - } const renderVoiceButton = (variant: VoiceButtonVariant) => { const isDesktop = variant === 'desktop' const isBusy = isRecording || isTogglingRecording || (isProcessing && !isRecording) const spinnerClassName = `w-5 h-5 animate-spin rounded-full border-2 ${isDesktop ? 'border-muted-foreground' : 'border-white'} border-t-transparent` + const voiceGestureHandlers = isDesktop ? {} : { + onPointerDown: handleVoicePointerDown, + onPointerMove: handleVoicePointerMove, + onPointerUp: handleVoicePointerEnd, + onPointerCancel: (event: ReactPointerEvent) => 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 @@ -1105,16 +1068,18 @@ const { model, modelString, setModel: setStoredModel } = useModelSelection(opcod : '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 w-full' + return ( -