All files / src/components/chat VoiceRecorder.tsx

0% Statements 0/232
0% Branches 0/1
0% Functions 0/1
0% Lines 0/232

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import { cn } from "@heroui/react"
import { TranscribeAudioRequest } from "@shared/proto/cline/dictation"
import { EmptyRequest } from "@shared/proto/index.cline"
import React, { useCallback, useEffect, useRef, useState } from "react"
import { DictationServiceClient } from "@/services/grpc-client"
import { formatSeconds } from "@/utils/format"
import HeroTooltip from "../common/HeroTooltip"
 
interface VoiceRecorderProps {
	onTranscription: (text: string) => void
	onProcessingStateChange?: (isProcessing: boolean, message?: string) => void
	onRecordingStateChange?: (isRecording: boolean) => void
	disabled?: boolean
	language?: string
	isAuthenticated?: boolean
}
 
const MAX_DURATION = 5 * 60 // 5 minutes in seconds
 
const VoiceRecorder: React.FC<VoiceRecorderProps> = ({
	onTranscription,
	onProcessingStateChange,
	onRecordingStateChange,
	disabled = false,
	language = "en",
	isAuthenticated = false,
}) => {
	const [isRecording, setIsRecording] = useState(false)
	const [isProcessing, setIsProcessing] = useState(false)
	const [isStarting, setIsStarting] = useState(false) // New state for loading
	const [recordingDuration, setRecordingDuration] = useState(0)
	const [error, setError] = useState<string | null>(null)
	const pollingIntervalRef = useRef<NodeJS.Timeout | null>(null)
 
	// Notify parent when recording state changes
	useEffect(() => {
		onRecordingStateChange?.(isRecording)
	}, [isRecording, onRecordingStateChange])
 
	// Auto-clear authentication errors when user signs in
	useEffect(() => {
		if (isAuthenticated && error) {
			// Clear error if it's related to authentication
			if (error.toLowerCase().includes("sign in") || error.toLowerCase().includes("aihydro account")) {
				setError(null)
			}
		}
	}, [isAuthenticated, error])
 
	const startRecording = useCallback(async () => {
		try {
			// Show loading state instead of immediately setting recording
			setIsStarting(true)
			setError(null) // Clear any previous errors
			onProcessingStateChange?.(false) // Clear any previous processing state
			setRecordingDuration(0) // Reset recording duration
 
			// Call Extension Host to start recording
			const response = await DictationServiceClient.startRecording(EmptyRequest.create({}))
 
			if (!response.success) {
				console.error("Failed to start recording:", response.error)
				setError(response.error || "Failed to start recording")
				return
			}
 
			// Only set recording state after backend confirms success
			setIsRecording(true)
			console.log("Recording started successfully")
		} catch (error) {
			console.error("Error starting recording:", error)
			const errorMessage = error instanceof Error ? error.message : "Failed to start recording"
			setError(errorMessage)
		} finally {
			// Always clear the starting state
			setIsStarting(false)
		}
	}, [onProcessingStateChange])
 
	const stopRecording = useCallback(async () => {
		try {
			setIsRecording(false)
			setIsProcessing(true)
			onProcessingStateChange?.(true, "Processing...")
 
			// Call Extension Host to stop recording and get audio
			const response = await DictationServiceClient.stopRecording(EmptyRequest.create({}))
 
			if (!response.success) {
				console.error("Failed to stop recording:", response.error)
				setIsProcessing(false)
				const errorMessage = response.error || "Failed to stop recording"
				setError(errorMessage)
				onTranscription("")
				return
			}
 
			if (!response.audioBase64) {
				setIsProcessing(false)
				const errorMessage = "No audio data received"
				setError(errorMessage)
				onTranscription("")
				return
			}
 
			// Update processing state for transcription
			onProcessingStateChange?.(true, "Transcribing...")
 
			// Transcribe the audio using OpenAI Whisper
			const transcriptionResponse = await DictationServiceClient.transcribeAudio(
				TranscribeAudioRequest.create({
					audioBase64: response.audioBase64,
					language: language,
				}),
			)
 
			if (transcriptionResponse.error) {
				setError(transcriptionResponse.error)
				onTranscription("")
				// Clear the error after a delay
				setTimeout(() => {
					setError(null)
					onProcessingStateChange?.(false)
				}, 5000)
			} else if (transcriptionResponse.text) {
				setError(null)
				onTranscription(transcriptionResponse.text)
				onProcessingStateChange?.(false)
			}
		} catch (error) {
			console.error("Error stopping recording:", error)
			const errorMessage = error instanceof Error ? error.message : "An error occurred"
			setError(errorMessage)
			onTranscription("")
		} finally {
			setIsProcessing(false)
		}
	}, [onTranscription, onProcessingStateChange])
 
	// Poll recording status while recording to update duration
	useEffect(() => {
		const pollRecordingStatus = async () => {
			try {
				const statusResponse = await DictationServiceClient.getRecordingStatus(EmptyRequest.create({}))
				if (statusResponse.isRecording) {
					setRecordingDuration(Math.floor(statusResponse.durationSeconds))
 
					// Auto-stop if max duration reached
					if (statusResponse.durationSeconds >= MAX_DURATION) {
						stopRecording()
					}
				}
			} catch (error) {
				console.error("Error polling recording status:", error)
			}
		}
 
		if (isRecording && !isProcessing) {
			pollingIntervalRef.current = setInterval(pollRecordingStatus, 1000)
		} else {
			// Clear polling when not recording
			if (pollingIntervalRef.current) {
				clearInterval(pollingIntervalRef.current)
				pollingIntervalRef.current = null
			}
		}
 
		// Cleanup on unmount
		return () => {
			if (pollingIntervalRef.current) {
				clearInterval(pollingIntervalRef.current)
				pollingIntervalRef.current = null
			}
		}
	}, [isRecording, isProcessing, stopRecording])
 
	const cancelRecording = useCallback(async () => {
		try {
			setIsRecording(false)
			setError(null)
			onProcessingStateChange?.(false)
			onTranscription("")
 
			// Call Extension Host to cancel recording
			const response = await DictationServiceClient.cancelRecording(EmptyRequest.create({}))
 
			if (!response.success) {
				console.error("Failed to cancel recording:", response.error)
				setError(response.error || "Failed to cancel recording")
				return
			}
 
			console.log("Recording canceled successfully")
		} catch (error) {
			console.error("Error canceling recording:", error)
			const errorMessage = error instanceof Error ? error.message : "Failed to cancel recording"
			setError(errorMessage)
		}
	}, [onProcessingStateChange, onTranscription])
 
	const handleStartClick = useCallback(() => {
		if (disabled || isProcessing || isStarting) {
			return
		}
		if (error) {
			return setError(null)
		}
		startRecording()
	}, [startRecording, disabled, isProcessing, isStarting, error])
 
	const handleCancelClick = useCallback(() => {
		if (disabled || isProcessing) {
			return
		}
		cancelRecording()
	}, [cancelRecording, disabled, isProcessing])
 
	const handleStopClick = useCallback(() => {
		if (disabled || isProcessing) {
			return
		}
		stopRecording()
	}, [stopRecording, disabled, isProcessing])
 
	const iconAnimation = isProcessing || isStarting ? "animate-spin" : ""
	const iconAdjustment = isProcessing || isStarting ? "mt-0" : error ? "mt-1" : "mt-0.5"
	// When not recording, show single mic button
	if (!isRecording) {
		const iconClass = isProcessing
			? "codicon-loading"
			: isStarting
				? "codicon-loading"
				: error
					? "codicon-error"
					: "codicon-mic"
		const iconColor = error ? "text-error" : ""
		const tooltipContent = isProcessing
			? "Transcribing..."
			: isStarting
				? "Starting recording..."
				: error
					? `Error: ${error}`
					: null
 
		return (
			<HeroTooltip content={tooltipContent} placement="top">
				<div
					className={`input-icon-button mr-1.5 text-base ${iconAdjustment} ${iconAnimation} ${disabled || isProcessing || isStarting ? "disabled" : ""}`}
					onClick={handleStartClick}
					style={{ color: iconColor }}>
					<span className={`codicon ${iconClass}`} />
				</div>
			</HeroTooltip>
		)
	}
 
	return (
		<div className={`flex items-center ${isRecording ? "mr-0.5" : "mr-1.5"}`}>
			<HeroTooltip
				content={`Stop Recording (${formatSeconds(recordingDuration)}/${formatSeconds(MAX_DURATION)})`}
				placement="top">
				<div
					className={cn("input-icon-button mr-1.5 text-error", iconAdjustment, iconAnimation, {
						disabled: disabled || isProcessing,
					})}
					onClick={handleStopClick}>
					<span className="codicon codicon-stop-circle" />
				</div>
			</HeroTooltip>
			<HeroTooltip content="Cancel Recording" placement="top">
				<div
					className={`input-icon-button text-base ${isRecording ? "mt-0.5" : "mt-1"} text-foreground ${disabled || isProcessing ? "disabled" : ""}`}
					onClick={handleCancelClick}>
					<span className="codicon codicon-close" />
				</div>
			</HeroTooltip>
		</div>
	)
}
 
export default VoiceRecorder