diff --git a/backend/src/utils/git-auth.ts b/backend/src/utils/git-auth.ts index 3a7f338b..7f470fb9 100644 --- a/backend/src/utils/git-auth.ts +++ b/backend/src/utils/git-auth.ts @@ -116,17 +116,6 @@ export function findGitHubCredential(credentials: GitCredential[]): GitCredentia }) || null } -export function getCredentialForHost(credentials: GitCredential[], host: string): GitCredential | undefined { - return credentials.find(cred => { - try { - const parsed = new URL(cred.host) - return parsed.hostname.toLowerCase() === host.toLowerCase() - } catch { - return false - } - }) -} - export function getSSHCredentialsForHost(credentials: GitCredential[], host: string): GitCredential[] { return credentials.filter(cred => { if (cred.type !== 'ssh') return false diff --git a/frontend/src/components/message/FloatingTTSButton.test.tsx b/frontend/src/components/message/FloatingTTSButton.test.tsx new file mode 100644 index 00000000..b2d60d0f --- /dev/null +++ b/frontend/src/components/message/FloatingTTSButton.test.tsx @@ -0,0 +1,280 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { render, screen, fireEvent, act } from '@testing-library/react' +import { FloatingTTSButton } from './FloatingTTSButton' +import type { TTSConfig } from '@opencode-manager/shared' + +const mocks = vi.hoisted(() => ({ + useTTS: vi.fn(), + useSettings: vi.fn(), + showToastInfo: vi.fn(), +})) + +vi.mock('@/hooks/useTTS', () => ({ + useTTS: mocks.useTTS, +})) + +vi.mock('@/hooks/useSettings', () => ({ + useSettings: mocks.useSettings, +})) + +vi.mock('@/lib/toast', () => ({ + showToast: { + info: mocks.showToastInfo, + }, +})) + +interface MockTTSReturn { + speakMessage: ReturnType + stop: ReturnType + activeMessageId: string | null + isPlaying: boolean + isLoading: boolean + isEnabled: boolean +} + +describe('FloatingTTSButton', () => { + const mockSpeakMessage = vi.fn() + const mockStop = vi.fn() + const mockUpdateSettings = vi.fn() + + beforeEach(() => { + vi.clearAllMocks() + mockSpeakMessage.mockClear() + mockStop.mockClear() + mockUpdateSettings.mockClear() + mocks.showToastInfo.mockClear() + }) + + const setup = (options: { + ttsEnabled?: boolean + autoPlay?: boolean + activeMessageId?: string | null + isPlaying?: boolean + isLoading?: boolean + } = {}) => { + const mockTTS: MockTTSReturn = { + speakMessage: mockSpeakMessage, + stop: mockStop, + activeMessageId: options.activeMessageId ?? null, + isPlaying: options.isPlaying ?? false, + isLoading: options.isLoading ?? false, + isEnabled: options.ttsEnabled ?? true, + } + mocks.useTTS.mockReturnValue(mockTTS) + + mocks.useSettings.mockReturnValue({ + preferences: { + tts: { + enabled: options.ttsEnabled ?? true, + autoPlay: options.autoPlay ?? false, + provider: 'external', + endpoint: 'https://api.openai.com', + apiKey: 'test-key', + voice: 'alloy', + model: 'tts-1', + speed: 1.0, + } as TTSConfig, + }, + updateSettings: mockUpdateSettings, + }) + } + + const TEST_MESSAGE_ID = 'test-message-1' + const TEST_CONTENT = 'Test content' + + it('renders pill when content is empty but autoplay is enabled', () => { + setup({ autoPlay: true }) + render() + expect(screen.getByRole('button', { name: /hold to toggle auto-play/i })).toBeInTheDocument() + }) + + it('renders pill when content is whitespace but autoplay is enabled', () => { + setup({ autoPlay: true }) + render() + expect(screen.getByRole('button', { name: /hold to toggle auto-play/i })).toBeInTheDocument() + }) + + it('calls speakMessage on tap when idle', () => { + setup() + render() + + const button = screen.getByRole('button', { name: /play latest reply/i }) + fireEvent.pointerDown(button) + act(() => { + fireEvent.pointerUp(button) + }) + + expect(mockSpeakMessage).toHaveBeenCalledTimes(1) + expect(mockSpeakMessage).toHaveBeenCalledWith(TEST_MESSAGE_ID, TEST_CONTENT) + }) + + it('calls stop on tap when this message is active', () => { + setup({ activeMessageId: TEST_MESSAGE_ID, isPlaying: true }) + render() + + const button = screen.getByRole('button', { name: /stop playback/i }) + fireEvent.pointerDown(button) + act(() => { + fireEvent.pointerUp(button) + }) + + expect(mockStop).toHaveBeenCalledTimes(1) + expect(mockSpeakMessage).not.toHaveBeenCalled() + }) + + it('calls stop when any playback is active, even for a different messageId (stream conflict fix)', () => { + setup({ activeMessageId: 'other-message-id', isPlaying: true }) + render() + + const button = screen.getByRole('button', { name: /stop playback/i }) + fireEvent.pointerDown(button) + act(() => { + fireEvent.pointerUp(button) + }) + + expect(mockStop).toHaveBeenCalledTimes(1) + expect(mockSpeakMessage).not.toHaveBeenCalled() + }) + + it('toggles autoplay on long press', async () => { + vi.useFakeTimers() + setup({ autoPlay: false }) + render() + + const button = screen.getByRole('button', { name: /play latest reply/i }) + await act(async () => { + fireEvent.pointerDown(button) + await vi.advanceTimersByTimeAsync(500) + fireEvent.pointerUp(button) + }) + + expect(mockUpdateSettings).toHaveBeenCalledTimes(1) + expect(mockUpdateSettings).toHaveBeenCalledWith({ + tts: { + autoPlay: true, + enabled: true, + provider: 'external', + endpoint: 'https://api.openai.com', + apiKey: 'test-key', + voice: 'alloy', + model: 'tts-1', + speed: 1.0, + }, + }) + expect(mocks.showToastInfo).toHaveBeenCalledWith('Auto-play enabled', { + id: 'tts-autoplay-toggle', + duration: 1800, + }) + + vi.useRealTimers() + }) + + it('shows a toast when long press disables autoplay', async () => { + vi.useFakeTimers() + setup({ autoPlay: true }) + render() + + const button = screen.getByRole('button', { name: /auto-play enabled/i }) + await act(async () => { + fireEvent.pointerDown(button) + await vi.advanceTimersByTimeAsync(500) + fireEvent.pointerUp(button) + }) + + expect(mockUpdateSettings).toHaveBeenCalledWith( + expect.objectContaining({ tts: expect.objectContaining({ autoPlay: false }) }) + ) + expect(mocks.showToastInfo).toHaveBeenCalledWith('Auto-play disabled', { + id: 'tts-autoplay-toggle', + duration: 1800, + }) + + vi.useRealTimers() + }) + + it('does not call speakMessage after long press (race guard)', async () => { + vi.useFakeTimers() + setup() + render() + + const button = screen.getByRole('button', { name: /play latest reply/i }) + await act(async () => { + fireEvent.pointerDown(button) + await vi.advanceTimersByTimeAsync(500) + fireEvent.pointerUp(button) + }) + + expect(mockSpeakMessage).not.toHaveBeenCalled() + expect(mockStop).not.toHaveBeenCalled() + vi.useRealTimers() + }) + + it('does not call speakMessage if pointer leaves before release after long press fires', async () => { + vi.useFakeTimers() + setup() + render() + + const button = screen.getByRole('button', { name: /play latest reply/i }) + await act(async () => { + fireEvent.pointerDown(button) + await vi.advanceTimersByTimeAsync(500) + fireEvent.pointerLeave(button) + }) + + expect(mockSpeakMessage).not.toHaveBeenCalled() + vi.useRealTimers() + }) + + it('exposes the gesture hint in the aria-label for accessibility', () => { + setup() + render() + + const button = screen.getByRole('button', { name: /hold to toggle auto-play/i }) + expect(button).toBeInTheDocument() + }) + + it('shows stop icon when this message is playing', () => { + setup({ autoPlay: true, activeMessageId: TEST_MESSAGE_ID, isPlaying: true }) + render() + + const button = screen.getByRole('button', { name: /stop playback/i }) + + expect(button).toHaveClass('from-red-600') + expect(button).toHaveClass('rounded-lg') + expect(button).not.toHaveClass('rounded-full') + expect(button).not.toHaveClass('hidden') + expect(screen.queryByText('Stop')).not.toBeInTheDocument() + expect(screen.queryByLabelText('Autoplay enabled')).not.toBeInTheDocument() + }) + + it('shows the same stop icon while this message is loading', () => { + setup({ activeMessageId: TEST_MESSAGE_ID, isLoading: true }) + render() + + expect(screen.getByRole('button', { name: /stop playback/i })).toHaveClass('from-red-600') + }) + + it('shows autoplay state with button color when autoPlay is enabled', () => { + setup({ autoPlay: true }) + render() + + const button = screen.getByRole('button', { name: /auto-play enabled/i }) + + expect(button).toHaveClass('from-blue-500') + expect(button).toHaveClass('rounded-lg') + expect(screen.queryByText('Play')).not.toBeInTheDocument() + expect(screen.queryByText('Auto')).not.toBeInTheDocument() + expect(screen.queryByLabelText('Autoplay enabled')).not.toBeInTheDocument() + }) + + it('uses the default play color when autoPlay is disabled', () => { + setup({ autoPlay: false }) + render() + + const button = screen.getByRole('button', { name: /play latest reply/i }) + + expect(button).toHaveClass('from-amber-500') + expect(button).not.toHaveClass('from-blue-500') + expect(screen.queryByText('Play')).not.toBeInTheDocument() + }) +}) diff --git a/frontend/src/components/message/FloatingTTSButton.tsx b/frontend/src/components/message/FloatingTTSButton.tsx index bba58661..b129234a 100644 --- a/frontend/src/components/message/FloatingTTSButton.tsx +++ b/frontend/src/components/message/FloatingTTSButton.tsx @@ -1,49 +1,109 @@ -import { Volume2, VolumeX, Loader2 } from 'lucide-react' +import { useState, useCallback, useRef } from 'react' +import { Volume2, VolumeX } from 'lucide-react' import { useTTS } from '@/hooks/useTTS' +import { useSettings } from '@/hooks/useSettings' +import { showToast } from '@/lib/toast' +import { DEFAULT_TTS_CONFIG } from '@opencode-manager/shared' interface FloatingTTSButtonProps { + messageId: string content: string } -export function FloatingTTSButton({ content }: FloatingTTSButtonProps) { - const { speak, stop, isEnabled, isPlaying, isLoading, originalText } = useTTS() - - if (!isEnabled || !content.trim()) { - return null - } - - const isThisPlaying = (isPlaying || isLoading) && originalText === content - - const handleClick = () => { - if (isThisPlaying) { - stop() - } else { - speak(content) +const LONG_PRESS_DURATION = 500 + +export function FloatingTTSButton({ messageId, content }: FloatingTTSButtonProps) { + const { speakMessage, stop, isPlaying, isLoading } = useTTS() + const { preferences, updateSettings } = useSettings() + + const autoPlay = preferences?.tts?.autoPlay ?? false + const [isLongPressVisual, setIsLongPressVisual] = useState(false) + const longPressTimerRef = useRef | null>(null) + const didLongPressFireRef = useRef(false) + + const isAnyPlaybackActive = isPlaying || isLoading + const hasContent = content.trim().length > 0 + + const clearLongPressTimer = useCallback(() => { + if (longPressTimerRef.current) { + clearTimeout(longPressTimerRef.current) + longPressTimerRef.current = null } - } - + }, []) + + const handlePointerDown = useCallback(() => { + clearLongPressTimer() + didLongPressFireRef.current = false + longPressTimerRef.current = setTimeout(() => { + const nextAutoPlay = !autoPlay + + didLongPressFireRef.current = true + setIsLongPressVisual(true) + updateSettings({ tts: { ...(preferences?.tts ?? DEFAULT_TTS_CONFIG), autoPlay: nextAutoPlay } }) + showToast.info(nextAutoPlay ? 'Auto-play enabled' : 'Auto-play disabled', { + id: 'tts-autoplay-toggle', + duration: 1800, + }) + }, LONG_PRESS_DURATION) + }, [autoPlay, updateSettings, preferences?.tts, clearLongPressTimer]) + + const handlePointerUp = useCallback(() => { + clearLongPressTimer() + + if (didLongPressFireRef.current) { + didLongPressFireRef.current = false + setIsLongPressVisual(false) + return + } + + if (isAnyPlaybackActive) { + stop() + return + } + + if (hasContent) { + speakMessage(messageId, content) + } + }, [clearLongPressTimer, isAnyPlaybackActive, stop, speakMessage, messageId, content, hasContent]) + + const handlePointerLeave = useCallback(() => { + clearLongPressTimer() + didLongPressFireRef.current = false + setIsLongPressVisual(false) + }, [clearLongPressTimer]) + + const showStop = isAnyPlaybackActive + const pillTitle = showStop + ? 'Stop playback (hold to toggle auto-play)' + : hasContent + ? autoPlay + ? 'Play latest reply (auto-play enabled; hold to toggle auto-play)' + : 'Play latest reply (hold to toggle auto-play)' + : autoPlay + ? 'Auto-play enabled (hold to toggle auto-play)' + : 'Hold to toggle auto-play' + const pillAriaLabel = pillTitle + const buttonToneClasses = showStop + ? 'justify-center px-3 py-1.5 rounded-lg bg-gradient-to-br from-red-600 to-red-700 border border-red-500/60 shadow-red-500/30 ring-red-500/20 hover:ring-red-500/40 text-white' + : autoPlay + ? 'justify-center px-3 py-1.5 rounded-lg bg-gradient-to-br from-blue-500 to-blue-600 border border-blue-400/60 shadow-blue-500/30 ring-blue-500/20 hover:ring-blue-500/40 text-white' + : 'justify-center px-3 py-1.5 rounded-lg bg-gradient-to-br from-amber-500 to-orange-600 border border-amber-400/60 shadow-amber-500/30 ring-amber-500/20 hover:ring-amber-500/40 text-white' + return ( - + ) } diff --git a/frontend/src/components/message/MessagePart.test.tsx b/frontend/src/components/message/MessagePart.test.tsx new file mode 100644 index 00000000..99f5b5d5 --- /dev/null +++ b/frontend/src/components/message/MessagePart.test.tsx @@ -0,0 +1,226 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { render, screen, fireEvent } from '@testing-library/react' +import { MessagePart } from './MessagePart' +import type { MessagePart as MessagePartType } from '@/api/types' + +const mocks = vi.hoisted(() => ({ + useTTS: vi.fn(), +})) + +vi.mock('@/hooks/useTTS', () => ({ + useTTS: mocks.useTTS, +})) + +interface MockTTSReturn { + speakMessage: ReturnType + stop: ReturnType + activeMessageId: string | null + isPlaying: boolean + isLoading: boolean + isEnabled: boolean +} + +describe('MessagePart', () => { + const mockSpeakMessage = vi.fn() + const mockStop = vi.fn() + + beforeEach(() => { + mockSpeakMessage.mockClear() + mockStop.mockClear() + }) + + const setup = (options: { + ttsEnabled?: boolean + autoPlay?: boolean + activeMessageId?: string | null + isPlaying?: boolean + isLoading?: boolean + } = {}) => { + const mockTTS: MockTTSReturn = { + speakMessage: mockSpeakMessage, + stop: mockStop, + activeMessageId: options.activeMessageId ?? null, + isPlaying: options.isPlaying ?? false, + isLoading: options.isLoading ?? false, + isEnabled: options.ttsEnabled ?? true, + } + mocks.useTTS.mockReturnValue(mockTTS) + } + + const createStepFinishPart = (messageID: string): MessagePartType => ({ + type: 'step-finish', + messageID, + sessionID: 'test-session', + cost: 0.01, + tokens: { + input: 100, + output: 50, + cache: { read: 0, write: 0 }, + }, + time: { + start: Date.now(), + end: Date.now() + 100, + }, + }) + + const TEST_MESSAGE_ID = 'message-1' + const TEST_CONTENT = 'Test message content' + + it('renders TTS button for step-finish part with message text', () => { + setup() + const part = createStepFinishPart(TEST_MESSAGE_ID) + + render( + + ) + + expect(screen.getByRole('button')).toBeInTheDocument() + expect(screen.getByTitle('Read aloud')).toBeInTheDocument() + }) + + it('does not render TTS button when message text is empty', () => { + setup() + const part = createStepFinishPart(TEST_MESSAGE_ID) + + render( + + ) + + expect(screen.queryByRole('button')).not.toBeInTheDocument() + }) + + it('does not render TTS button when TTS is disabled', () => { + setup({ ttsEnabled: false }) + const part = createStepFinishPart(TEST_MESSAGE_ID) + + render( + + ) + + expect(screen.queryByRole('button')).not.toBeInTheDocument() + }) + + it('calls speakMessage with message id on tap when idle', () => { + setup() + const part = createStepFinishPart(TEST_MESSAGE_ID) + + render( + + ) + + const button = screen.getByRole('button') + fireEvent.click(button) + + expect(mockSpeakMessage).toHaveBeenCalledTimes(1) + expect(mockSpeakMessage).toHaveBeenCalledWith(TEST_MESSAGE_ID, TEST_CONTENT) + }) + + it('calls stop on tap when this message is active', () => { + const mockTTSForTest: MockTTSReturn = { + speakMessage: mockSpeakMessage, + stop: mockStop, + activeMessageId: TEST_MESSAGE_ID, + isPlaying: true, + isLoading: false, + isEnabled: true, + } + mocks.useTTS.mockReturnValue(mockTTSForTest) + + const part = createStepFinishPart(TEST_MESSAGE_ID) + + render( + + ) + + const button = screen.getByRole('button') + fireEvent.click(button) + + expect(mockStop).toHaveBeenCalledTimes(1) + expect(mockSpeakMessage).not.toHaveBeenCalled() + }) + + it('shows active state when this message is playing', () => { + setup({ activeMessageId: TEST_MESSAGE_ID, isPlaying: true }) + const part = createStepFinishPart(TEST_MESSAGE_ID) + + render( + + ) + + const button = screen.getByRole('button') + expect(button).toHaveClass('bg-red-500/20') + expect(button).toHaveClass('text-red-500') + }) + + it('shows active state when this message is loading', () => { + setup({ activeMessageId: TEST_MESSAGE_ID, isLoading: true }) + const part = createStepFinishPart(TEST_MESSAGE_ID) + + render( + + ) + + const button = screen.getByRole('button') + expect(button).toHaveClass('bg-red-500/20') + }) + + it('does not show active state when different message is playing', () => { + setup({ activeMessageId: 'other-message', isPlaying: true }) + const part = createStepFinishPart(TEST_MESSAGE_ID) + + render( + + ) + + const button = screen.getByRole('button') + expect(button).not.toHaveClass('bg-red-500/20') + }) + + it('tracks playback by message id not text', () => { + setup({ activeMessageId: TEST_MESSAGE_ID, isPlaying: true }) + const part1 = createStepFinishPart(TEST_MESSAGE_ID) + const part2 = createStepFinishPart('message-2') + + const { rerender } = render( + + ) + + expect(screen.getByRole('button')).toHaveClass('bg-red-500/20') + + rerender( + + ) + + expect(screen.getByRole('button')).not.toHaveClass('bg-red-500/20') + }) +}) diff --git a/frontend/src/components/message/MessagePart.tsx b/frontend/src/components/message/MessagePart.tsx index 15931ea2..25be72b6 100644 --- a/frontend/src/components/message/MessagePart.tsx +++ b/frontend/src/components/message/MessagePart.tsx @@ -59,24 +59,25 @@ function getCopyableContent(part: Part, allParts?: Part[]): string { } interface TTSButtonProps { + messageId: string content: string className?: string } -function TTSButton({ content, className = "" }: TTSButtonProps) { - const { speak, stop, isEnabled, isPlaying, isLoading, originalText } = useTTS() +function TTSButton({ messageId, content, className = "" }: TTSButtonProps) { + const { speakMessage, stop, isEnabled, isPlaying, isLoading, activeMessageId } = useTTS() if (!isEnabled || !content.trim()) { return null } - const isThisPlaying = (isPlaying || isLoading) && originalText === content + const isThisPlaying = (isPlaying || isLoading) && activeMessageId === messageId const handleClick = () => { if (isThisPlaying) { stop() } else { - speak(content) + speakMessage(messageId, content) } } @@ -85,7 +86,7 @@ function TTSButton({ content, className = "" }: TTSButtonProps) { onClick={handleClick} className={`p-1.5 rounded ${isThisPlaying ? 'bg-red-500/20 text-red-500 hover:bg-red-500/30' : 'bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground'} ${className}`} title={isThisPlaying ? "Stop playback" : "Read aloud"} - disabled={isLoading && originalText !== content} + disabled={isLoading && !isThisPlaying} > {isLoading && isThisPlaying ? ( @@ -146,7 +147,7 @@ export const MessagePart = memo(function MessagePart({ part, role, allParts, par
{costText} - {messageTextContent && } + {messageTextContent && part.messageID && }
) } diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index 6c32c83d..32181a19 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -1,4 +1,4 @@ -import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, memo, type KeyboardEvent } from 'react' +import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, memo, useCallback, type KeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react' import { useSendPrompt, useAbortSession, useSendShell, useAgents } from '@/hooks/useOpenCode' import { useCommands } from '@/hooks/useCommands' import { useCommandHandler } from '@/hooks/useCommandHandler' @@ -44,6 +44,8 @@ const revokeBlobUrls = (attachments: ImageAttachment[]) => { const ACCEPTED_FILE_TYPES = [...ACCEPTED_IMAGE_TYPES, "application/pdf"] +const VOICE_SEND_SWIPE_THRESHOLD = 48 + type CommandType = components['schemas']['Command'] @@ -102,7 +104,16 @@ export const PromptInput = memo(forwardRef( 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 lastAddedTranscriptRef = useRef('') + const voiceHoldStartYRef = useRef(null) + const voiceSwipeArmedRef = useRef(false) + const voicePendingReleaseRef = useRef(false) + const pendingVoiceAutoSubmitRef = useRef(false) + const ignoreVoiceClickUntilRef = useRef(0) + const handleSubmitRef = useRef<() => void>(() => {}) const { isRecording, @@ -119,6 +130,16 @@ export const PromptInput = memo(forwardRef( const textareaRef = useRef(null) const fileInputRef = useRef(null) + const resetVoiceGestureState = useCallback(() => { + voiceHoldStartYRef.current = null + voiceSwipeArmedRef.current = false + voicePendingReleaseRef.current = false + pendingVoiceAutoSubmitRef.current = false + ignoreVoiceClickUntilRef.current = 0 + setIsVoiceHoldActive(false) + setIsVoiceSwipeArmed(false) + setIsVoiceAutoSendPending(false) + }, []) useImperativeHandle(ref, () => ({ setPromptValue: (value: string) => { @@ -131,6 +152,7 @@ export const PromptInput = memo(forwardRef( revokeBlobUrls(imageAttachments) setImageAttachments([]) setSelectedAgent(null) + resetVoiceGestureState() if (isRecording) { abortRecording() } else { @@ -141,7 +163,7 @@ export const PromptInput = memo(forwardRef( triggerFileUpload: () => { fileInputRef.current?.click() } - }), [imageAttachments, clearSTT, isRecording, abortRecording]) + }), [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState]) const sendPrompt = useSendPrompt(opcodeUrl, directory) const sendShell = useSendShell(opcodeUrl, directory) const abortSession = useAbortSession(opcodeUrl, directory, sessionID, repoId) @@ -197,6 +219,9 @@ export const PromptInput = memo(forwardRef( if (disabled) return if (!prompt.trim() && imageAttachments.length === 0) return + pendingVoiceAutoSubmitRef.current = false + setIsVoiceAutoSendPending(false) + if (hasActiveStream) { const parts = parsePromptToParts(prompt, attachedFiles, imageAttachments) const agentUsed = selectedAgent || currentMode @@ -273,6 +298,8 @@ export const PromptInput = memo(forwardRef( clearSTT() } + handleSubmitRef.current = handleSubmit + const handleStop = () => { abortSession.mutate(sessionID) } @@ -381,6 +408,10 @@ export const PromptInput = memo(forwardRef( } const handleVoiceToggle = async () => { + pendingVoiceAutoSubmitRef.current = false + setIsVoiceAutoSendPending(false) + setIsVoiceSwipeArmed(false) + voiceSwipeArmedRef.current = false if (isRecording) { stopRecording() } else { @@ -388,7 +419,7 @@ export const PromptInput = memo(forwardRef( try { await startRecording() if (textareaRef.current) { - textareaRef.current.blur() + textareaRef.current?.blur() } } catch { setIsTogglingRecording(false) @@ -396,6 +427,101 @@ export const PromptInput = memo(forwardRef( } } + const handleVoiceClick = async () => { + if (Date.now() < ignoreVoiceClickUntilRef.current) { + return + } + + await handleVoiceToggle() + } + + const handleVoiceHoldStart = async () => { + if (!isRecording && !isProcessing) { + pendingVoiceAutoSubmitRef.current = false + setIsVoiceAutoSendPending(false) + setIsTogglingRecording(true) + try { + if (typeof navigator !== 'undefined' && navigator.vibrate) { + navigator.vibrate(10) + } + await startRecording() + if (textareaRef.current) { + textareaRef.current?.blur() + } + } catch { + setIsTogglingRecording(false) + } + } + } + + const handleVoiceHoldEnd = (shouldAutoSend: boolean) => { + setIsVoiceHoldActive(false) + setIsVoiceSwipeArmed(false) + voiceHoldStartYRef.current = null + voiceSwipeArmedRef.current = false + pendingVoiceAutoSubmitRef.current = shouldAutoSend + setIsVoiceAutoSendPending(shouldAutoSend) + + if (isRecording) { + if (typeof navigator !== 'undefined' && navigator.vibrate) { + navigator.vibrate([10, 20, 10]) + } + stopRecording() + } else if (isTogglingRecording) { + voicePendingReleaseRef.current = true + } + } + + const handleVoicePointerDown = async (event: ReactPointerEvent) => { + if ((event.pointerType === 'mouse' && event.button !== 0) || disabled || isProcessing) { + return + } + + ignoreVoiceClickUntilRef.current = Date.now() + 400 + voiceHoldStartYRef.current = event.clientY + voiceSwipeArmedRef.current = false + voicePendingReleaseRef.current = false + pendingVoiceAutoSubmitRef.current = false + setIsVoiceHoldActive(true) + setIsVoiceSwipeArmed(false) + setIsVoiceAutoSendPending(false) + + if (event.currentTarget.setPointerCapture) { + event.currentTarget.setPointerCapture(event.pointerId) + } + + await handleVoiceHoldStart() + } + + const handleVoicePointerMove = (event: ReactPointerEvent) => { + if (!isVoiceHoldActive || voiceHoldStartYRef.current === null) { + return + } + + const nextIsSwipeArmed = voiceHoldStartYRef.current - event.clientY >= VOICE_SEND_SWIPE_THRESHOLD + + if (nextIsSwipeArmed !== voiceSwipeArmedRef.current) { + voiceSwipeArmedRef.current = nextIsSwipeArmed + setIsVoiceSwipeArmed(nextIsSwipeArmed) + + if (nextIsSwipeArmed && typeof navigator !== 'undefined' && navigator.vibrate) { + navigator.vibrate(10) + } + } + } + + const handleVoicePointerEnd = (event: ReactPointerEvent, canceled = false) => { + if (event.currentTarget.releasePointerCapture && event.currentTarget.hasPointerCapture(event.pointerId)) { + event.currentTarget.releasePointerCapture(event.pointerId) + } + + if (!isVoiceHoldActive && !isTogglingRecording && !isRecording) { + return + } + + handleVoiceHoldEnd(canceled ? false : voiceSwipeArmedRef.current) + } + useEffect(() => { const textToUse = transcript || interimTranscript if (!isRecording && textToUse && textToUse !== 'Processing...' && textToUse !== 'Recording...') { @@ -407,7 +533,10 @@ export const PromptInput = memo(forwardRef( setPrompt(prev => `${prev} ${trimmedTranscript}`) } lastAddedTranscriptRef.current = trimmedTranscript - textareaRef.current?.focus() + + if (!pendingVoiceAutoSubmitRef.current) { + textareaRef.current?.focus() + } } } }, [isRecording, interimTranscript, transcript, prompt]) @@ -424,6 +553,35 @@ export const PromptInput = memo(forwardRef( } }, [isTogglingRecording]) + useEffect(() => { + if (isRecording && voicePendingReleaseRef.current) { + voicePendingReleaseRef.current = false + + if (typeof navigator !== 'undefined' && navigator.vibrate) { + navigator.vibrate([10, 20, 10]) + } + + stopRecording() + } + }, [isRecording, stopRecording]) + + useEffect(() => { + if (!pendingVoiceAutoSubmitRef.current || isRecording || isProcessing || !prompt.trim()) { + return + } + + pendingVoiceAutoSubmitRef.current = false + setIsVoiceAutoSendPending(false) + handleSubmitRef.current() + }, [prompt, isRecording, isProcessing]) + + useEffect(() => { + if (pendingVoiceAutoSubmitRef.current && !isRecording && !isProcessing && !transcript.trim() && !interimTranscript.trim()) { + pendingVoiceAutoSubmitRef.current = false + setIsVoiceAutoSendPending(false) + } + }, [isRecording, isProcessing, transcript, interimTranscript]) + const addImageAttachment = (file: File) => { const generateId = () => { if (typeof crypto !== 'undefined' && crypto.randomUUID) { @@ -680,6 +838,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read) setPrompt('') revokeBlobUrls(imageAttachments) setImageAttachments([]) + resetVoiceGestureState() clearSTT() } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 't') { e.preventDefault() @@ -768,6 +927,47 @@ const { model, modelString, setModel: setStoredModel } = useModelSelection(opcod const { hasVariants, currentVariant, cycleVariant } = useVariants(opcodeUrl, directory) const showStopButton = hasActiveStream const hideSecondaryButtons = isMobile && hasActiveStream + const showVoiceFeedback = isVoiceHoldActive || isRecording || isTogglingRecording || isProcessing || isVoiceAutoSendPending + const voiceFeedbackLabel = isProcessing + ? isVoiceAutoSendPending + ? 'Transcribing and sending...' + : 'Transcribing...' + : isRecording + ? isVoiceSwipeArmed + ? 'Release to send' + : 'Recording... swipe up to send' + : isTogglingRecording || isVoiceHoldActive + ? 'Starting microphone...' + : null + const voiceFeedbackToneClasses = isVoiceSwipeArmed || isVoiceAutoSendPending + ? 'border-blue-400/60 bg-blue-500/90 text-white shadow-blue-500/30' + : 'border-red-500/60 bg-red-600/90 text-white shadow-red-500/30' + const voiceFeedbackGlowClasses = isVoiceSwipeArmed || isVoiceAutoSendPending ? 'bg-blue-500/30' : 'bg-red-500/25' + const voiceButtonTitle = isProcessing + ? 'Transcribing speech' + : isRecording + ? isVoiceSwipeArmed + ? 'Release to send' + : 'Release to transcribe' + : 'Hold to speak' + + const renderVoiceStatusOverlay = () => { + if (!showVoiceFeedback || !voiceFeedbackLabel) { + return null + } + + return ( + <> +
+
+ {voiceFeedbackLabel} +
+ + ) + } @@ -784,6 +984,7 @@ const { model, modelString, setModel: setStoredModel } = useModelSelection(opcod abortRecording() } clearSTT() + resetVoiceGestureState() lastAddedTranscriptRef.current = '' setIsTogglingRecording(false) setLocalMode(null) @@ -930,49 +1131,63 @@ return ( {sttEnabled && sttSupported && ( - +
+ {renderVoiceStatusOverlay()} + +
)} {isMobile && !showScrollButton && sttEnabled && sttSupported && !hasPendingPermissionForSession && ( - +
+ {renderVoiceStatusOverlay()} + +
)} - )} +
+ {ttsEnabled && !hasPromptContent && !hasActiveStream && ((lastAssistantMessage && lastAssistantText) || preferences?.tts?.autoPlay) && ( + + )} + {hasPromptContent && ( + + )} +
{leaderActive && (
Waiting for shortcut key...
)} - - {ttsEnabled && lastAssistantText && !hasPromptContent && !hasActiveStream && ( - - )} {minimizedQuestion && minimizedQuestion.sessionID === sessionId && (