Fix Zod v4 schema errors, mobile permission dialog overflow, and TTS test mocking

This commit is contained in:
Chris Scott committed 2025-12-14 23:19:59 -05:00
1 parent 71cf496711
commit e993a83027
9 files changed
+557 -264

No files matched your search

+6
View File
@@ -20,4 +20,10 @@ export default defineConfig([
globals: globals.browser,
},
},
{
files: ['src/components/ui/**/*.{ts,tsx}'],
rules: {
'react-refresh/only-export-components': 'off',
},
},
])
@@ -140,7 +140,7 @@ export function PermissionRequestDialog({
return (
<Dialog open={true} onOpenChange={() => {}}>
<DialogContent hideCloseButton className="sm:max-w-md">
<DialogContent hideCloseButton className="max-w-[calc(100vw-2rem)] sm:max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
Permission Request
@@ -163,16 +163,16 @@ export function PermissionRequestDialog({
</div>
{details.primary && (
<div className="bg-muted/50 border rounded-md p-3 max-h-32 overflow-y-auto">
<pre className="text-sm font-mono whitespace-pre-wrap break-all">
<div className="bg-muted/50 border rounded-md p-3 max-h-32 overflow-x-auto overflow-y-auto">
<pre className="text-sm font-mono whitespace-pre-wrap break-words max-w-full">
{details.primary}
</pre>
</div>
)}
{details.secondary && (
<div className="bg-muted/30 border rounded-md p-3 max-h-24 overflow-y-auto">
<pre className="text-xs font-mono whitespace-pre-wrap break-all text-muted-foreground">
<div className="bg-muted/30 border rounded-md p-3 max-h-24 overflow-x-auto overflow-y-auto">
<pre className="text-xs font-mono whitespace-pre-wrap break-words max-w-full text-muted-foreground">
{details.secondary}
</pre>
</div>
@@ -189,13 +189,13 @@ export function PermissionRequestDialog({
)}
</div>
<DialogFooter className="flex-row gap-2 sm:justify-between">
<DialogFooter className="flex-col-reverse gap-2 sm:flex-row sm:justify-between">
<Button
variant="outline"
onClick={() => handleResponse('reject')}
disabled={isLoading}
className={cn(
"flex-1",
"w-full sm:flex-1",
loadingAction === 'reject' && "opacity-70"
)}
>
@@ -206,7 +206,7 @@ export function PermissionRequestDialog({
onClick={() => handleResponse('once')}
disabled={isLoading}
className={cn(
"flex-1",
"w-full sm:flex-1",
loadingAction === 'once' && "opacity-70"
)}
>
@@ -217,7 +217,7 @@ export function PermissionRequestDialog({
onClick={() => handleResponse('always')}
disabled={isLoading}
className={cn(
"flex-1",
"w-full sm:flex-1",
loadingAction === 'always' && "opacity-70"
)}
>
@@ -1,10 +1,10 @@
import { useEffect, useState } from 'react'
import { useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useSettings } from '@/hooks/useSettings'
import { useTTS } from '@/hooks/useTTS'
import { Loader2, Volume2, Square, CheckCircle, XCircle } from 'lucide-react'
import { Loader2, Volume2, Square, XCircle } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
@@ -37,7 +37,6 @@ type TTSFormValues = z.infer<typeof ttsFormSchema>
export function TTSSettings() {
const { preferences, isLoading, updateSettings, isUpdating } = useSettings()
const { speak, stop, isPlaying, isLoading: isTTSLoading, error: ttsError } = useTTS()
const [testStatus, setTestStatus] = useState<'idle' | 'success' | 'error'>('idle')
const form = useForm<TTSFormValues>({
resolver: zodResolver(ttsFormSchema),
@@ -67,20 +66,12 @@ export function TTSSettings() {
updateSettings({ tts: data })
}
const handleTest = async () => {
setTestStatus('idle')
try {
await speak(TEST_PHRASE)
setTestStatus('success')
setTimeout(() => setTestStatus('idle'), 3000)
} catch {
setTestStatus('error')
}
const handleTest = () => {
speak(TEST_PHRASE)
}
const handleStopTest = () => {
stop()
setTestStatus('idle')
}
if (isLoading) {
@@ -276,12 +267,6 @@ export function TTSSettings() {
{ttsError}
</p>
)}
{testStatus === 'success' && (
<p className="text-sm text-green-500 flex items-center gap-1">
<CheckCircle className="h-4 w-4" />
TTS is working
</p>
)}
</div>
<Button
type="button"
+6 -4
View File
@@ -58,8 +58,9 @@ export function usePermissionRequests(currentSessionID?: string) {
const filtered = sessionPermissions.filter(p => p.id !== permissionID)
if (filtered.length === 0) {
const { [sessionID]: _, ...rest } = prev
return rest
return Object.fromEntries(
Object.entries(prev).filter(([key]) => key !== sessionID)
)
}
return { ...prev, [sessionID]: filtered }
})
@@ -93,8 +94,9 @@ export function usePermissionRequests(currentSessionID?: string) {
const filtered = sessionPermissions.filter(p => p.id !== permissionID)
if (filtered.length === 0) {
const { [sessionID]: _, ...rest } = prev
return rest
return Object.fromEntries(
Object.entries(prev).filter(([key]) => key !== sessionID)
)
}
return { ...prev, [sessionID]: filtered }
}
+192 -227
View File
@@ -2,79 +2,37 @@ import { useState, useRef, useCallback, useEffect } from 'react'
import { useSettings } from './useSettings'
import { API_BASE_URL } from '@/config'
const TTS_CACHE_NAME = 'tts-audio-cache'
const CACHE_TTL_MS = 24 * 60 * 60 * 1000
const PUNCTUATION_REGEX = /(?<=[.!?;])\s+/
const SENTENCE_REGEX = /(?<=[.!?])\s+/
const SENTENCES_PER_CHUNK = 2
function generateCacheKey(text: string, voice: string, model: string, speed: number): string {
const data = `${text}|${voice}|${model}|${speed}`
let hash = 0
for (let i = 0; i < data.length; i++) {
const char = data.charCodeAt(i)
hash = ((hash << 5) - hash) + char
hash = hash & hash
function splitIntoChunks(text: string): string[] {
const sentences = text.split(SENTENCE_REGEX).filter(s => s.trim().length > 0)
if (sentences.length === 0) return [text]
const chunks: string[] = []
for (let i = 0; i < sentences.length; i += SENTENCES_PER_CHUNK) {
const chunk = sentences.slice(i, i + SENTENCES_PER_CHUNK).join(' ')
if (chunk.trim()) chunks.push(chunk.trim())
}
return Math.abs(hash).toString(16).padStart(8, '0')
}
function isCacheApiAvailable(): boolean {
return typeof caches !== 'undefined'
}
async function getCachedAudio(cacheKey: string): Promise<Blob | null> {
if (!isCacheApiAvailable()) return null
try {
const cache = await caches.open(TTS_CACHE_NAME)
const response = await cache.match(cacheKey)
if (!response) return null
const cachedAt = response.headers.get('x-cached-at')
if (cachedAt && Date.now() - parseInt(cachedAt) > CACHE_TTL_MS) {
await cache.delete(cacheKey)
return null
}
return await response.blob()
} catch {
return null
}
}
async function cacheAudio(cacheKey: string, blob: Blob): Promise<void> {
if (!isCacheApiAvailable()) return
try {
const cache = await caches.open(TTS_CACHE_NAME)
const headers = new Headers({
'Content-Type': 'audio/mpeg',
'x-cached-at': Date.now().toString(),
})
const response = new Response(blob, { headers })
await cache.put(cacheKey, response)
} catch {
// Cache API not available or storage full, continue without caching
}
}
export type TTSState = 'idle' | 'loading' | 'playing' | 'paused' | 'error'
function splitTextByPunctuation(text: string): string[] {
const chunks = text.split(PUNCTUATION_REGEX).filter(chunk => chunk.trim().length > 0)
return chunks.length > 0 ? chunks : [text]
}
export type TTSState = 'idle' | 'loading' | 'playing' | 'error'
export function useTTS() {
const { preferences } = useSettings()
const [state, setState] = useState<TTSState>('idle')
const [error, setError] = useState<string | null>(null)
const [currentText, setCurrentText] = useState<string | null>(null)
const audioRef = useRef<HTMLAudioElement | null>(null)
const abortControllerRef = useRef<AbortController | null>(null)
const chunkQueueRef = useRef<string[]>([])
const isPlayingChunksRef = useRef<boolean>(false)
const fullTextRef = useRef<string | null>(null)
const audioRef = useRef<HTMLAudioElement | null>(null)
const stoppedRef = useRef(false)
const chunksRef = useRef<string[]>([])
const chunkIndexRef = useRef(0)
const prefetchedBlobsRef = useRef<Map<number, Blob>>(new Map())
const fetchingIndexRef = useRef<number>(-1)
const ttsConfig = preferences?.tts
const isEnabled = ttsConfig?.enabled && ttsConfig?.apiKey
@@ -89,195 +47,202 @@ export function useTTS() {
abortControllerRef.current.abort()
abortControllerRef.current = null
}
chunkQueueRef.current = []
isPlayingChunksRef.current = false
prefetchedBlobsRef.current.forEach((_, key) => {
prefetchedBlobsRef.current.delete(key)
})
prefetchedBlobsRef.current.clear()
chunksRef.current = []
chunkIndexRef.current = 0
fetchingIndexRef.current = -1
}, [])
useEffect(() => {
return () => cleanup()
}, [cleanup])
const synthesizeChunk = useCallback(async (text: string): Promise<Blob | null> => {
if (!isPlayingChunksRef.current) return null
const { voice, model, speed } = ttsConfig!
const cacheKey = generateCacheKey(text, voice, model, speed ?? 1)
const cachedBlob = await getCachedAudio(cacheKey)
if (!isPlayingChunksRef.current) return null
if (cachedBlob) return cachedBlob
abortControllerRef.current = new AbortController()
const response = await fetch(`${API_BASE_URL}/api/tts/synthesize`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text }),
signal: abortControllerRef.current.signal,
})
if (!isPlayingChunksRef.current) return null
if (!response.ok) {
let errorMessage = 'TTS request failed'
try {
const errorData = await response.json()
errorMessage = errorData.error || errorData.details || errorMessage
} catch {
if (response.status === 401) errorMessage = 'Invalid TTS API key'
else if (response.status === 429) errorMessage = 'TTS rate limit exceeded'
else if (response.status >= 500) errorMessage = 'TTS service unavailable'
}
throw new Error(errorMessage)
}
const contentType = response.headers.get('content-type')
if (!contentType?.includes('audio')) throw new Error('Invalid response from TTS service')
const audioBlob = await response.blob()
if (!isPlayingChunksRef.current) return null
if (audioBlob.size === 0) throw new Error('Empty audio response from TTS service')
await cacheAudio(cacheKey, audioBlob)
return audioBlob
}, [ttsConfig])
const playNextChunk = useCallback(async () => {
if (!isPlayingChunksRef.current || chunkQueueRef.current.length === 0) {
isPlayingChunksRef.current = false
fullTextRef.current = null
setState('idle')
setCurrentText(null)
return
}
const chunk = chunkQueueRef.current.shift()!
try {
const audioBlob = await synthesizeChunk(chunk)
if (!audioBlob || !isPlayingChunksRef.current) return
const audioUrl = URL.createObjectURL(audioBlob)
const audio = new Audio(audioUrl)
audioRef.current = audio
audio.onplay = () => setState('playing')
audio.onpause = () => {
if (audio.currentTime < audio.duration) setState('paused')
}
audio.onended = () => {
URL.revokeObjectURL(audioUrl)
playNextChunk()
}
audio.onerror = () => {
const mediaError = audio.error
let errorMessage = 'Audio playback failed'
if (mediaError) {
switch (mediaError.code) {
case MediaError.MEDIA_ERR_ABORTED: errorMessage = 'Audio playback was aborted'; break
case MediaError.MEDIA_ERR_NETWORK: errorMessage = 'Network error during audio playback'; break
case MediaError.MEDIA_ERR_DECODE: errorMessage = 'Audio decoding failed'; break
case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED: errorMessage = 'Audio format not supported'; break
}
}
setError(errorMessage)
setState('error')
isPlayingChunksRef.current = false
URL.revokeObjectURL(audioUrl)
}
await audio.play()
} catch (err) {
if (err instanceof Error && err.name === 'AbortError') {
setState('idle')
return
}
setError(err instanceof Error ? err.message : 'TTS failed')
setState('error')
isPlayingChunksRef.current = false
}
}, [synthesizeChunk])
const speak = useCallback(async (text: string) => {
if (!ttsConfig?.enabled) {
setError('TTS is not enabled in settings')
setState('error')
return
}
if (!ttsConfig?.apiKey) {
setError('TTS API key is not configured')
setState('error')
return
}
if (!text?.trim()) {
setError('No text provided for speech')
setState('error')
return
}
if (!ttsConfig.voice || !ttsConfig.model) {
setError('TTS voice or model not configured')
setState('error')
return
}
cleanup()
setError(null)
setState('loading')
setCurrentText(text)
fullTextRef.current = text
const chunks = splitTextByPunctuation(text)
chunkQueueRef.current = chunks
isPlayingChunksRef.current = true
await playNextChunk()
}, [ttsConfig, cleanup, playNextChunk])
const stop = useCallback(() => {
stoppedRef.current = true
cleanup()
fullTextRef.current = null
setState('idle')
setCurrentText(null)
setError(null)
}, [cleanup])
const pause = useCallback(() => {
if (audioRef.current && state === 'playing') {
audioRef.current.pause()
useEffect(() => {
return () => {
stoppedRef.current = true
cleanup()
}
}, [state])
}, [cleanup])
const resume = useCallback(() => {
if (audioRef.current && state === 'paused') {
audioRef.current.play()
}
}, [state])
const synthesize = useCallback(async (text: string, signal?: AbortSignal): Promise<Blob | null> => {
if (stoppedRef.current) return null
const toggle = useCallback(() => {
if (state === 'playing') {
pause()
} else if (state === 'paused') {
resume()
try {
const response = await fetch(`${API_BASE_URL}/api/tts/synthesize`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text }),
signal,
})
if (stoppedRef.current) return null
if (!response.ok) {
let errorMessage = 'TTS request failed'
try {
const errorData = await response.json()
errorMessage = errorData.error || errorData.details || errorMessage
} catch {
if (response.status === 401) errorMessage = 'Invalid API key'
else if (response.status === 429) errorMessage = 'Rate limit exceeded'
else if (response.status >= 500) errorMessage = 'Service unavailable'
}
throw new Error(errorMessage)
}
const contentType = response.headers.get('content-type')
if (!contentType?.includes('audio')) {
throw new Error('Invalid response from TTS service')
}
const blob = await response.blob()
if (blob.size === 0) {
throw new Error('Empty audio response')
}
return blob
} catch (err) {
if (err instanceof Error && err.name === 'AbortError') {
return null
}
throw err
}
}, [state, pause, resume])
}, [])
const fetchNextChunk = useCallback(async (index: number) => {
if (stoppedRef.current) return
if (index >= chunksRef.current.length) return
if (prefetchedBlobsRef.current.has(index)) {
fetchNextChunk(index + 1)
return
}
fetchingIndexRef.current = index
try {
const blob = await synthesize(chunksRef.current[index], abortControllerRef.current?.signal)
if (blob && !stoppedRef.current) {
prefetchedBlobsRef.current.set(index, blob)
fetchNextChunk(index + 1)
}
} catch {
if (stoppedRef.current) return
}
fetchingIndexRef.current = -1
}, [synthesize])
const playChunk = useCallback(async (index: number) => {
if (stoppedRef.current || index >= chunksRef.current.length) {
if (!stoppedRef.current) {
setState('idle')
setCurrentText(null)
}
return
}
chunkIndexRef.current = index
try {
let blob: Blob | undefined = prefetchedBlobsRef.current.get(index)
if (!blob) {
setState('loading')
const fetched = await synthesize(chunksRef.current[index], abortControllerRef.current?.signal)
if (fetched && !stoppedRef.current) {
blob = fetched
}
fetchNextChunk(index + 1)
}
if (!blob || stoppedRef.current) return
prefetchedBlobsRef.current.delete(index)
const url = URL.createObjectURL(blob)
const audio = new Audio(url)
audioRef.current = audio
audio.onended = () => {
URL.revokeObjectURL(url)
audioRef.current = null
if (!stoppedRef.current) {
playChunk(index + 1)
}
}
audio.onerror = () => {
URL.revokeObjectURL(url)
audioRef.current = null
if (!stoppedRef.current) {
setError('Audio playback failed')
setState('error')
}
}
setState('playing')
await audio.play()
} catch (err) {
if (stoppedRef.current) return
setError(err instanceof Error ? err.message : 'TTS failed')
setState('error')
}
}, [synthesize, fetchNextChunk])
const speak = useCallback(async (text: string): Promise<boolean> => {
if (!ttsConfig?.enabled) {
setError('TTS is not enabled')
setState('error')
return false
}
if (!ttsConfig?.apiKey) {
setError('API key not configured')
setState('error')
return false
}
if (!text?.trim()) {
setError('No text provided')
setState('error')
return false
}
if (!ttsConfig.voice || !ttsConfig.model) {
setError('Voice or model not configured')
setState('error')
return false
}
stop()
stoppedRef.current = false
setError(null)
setCurrentText(text)
abortControllerRef.current = new AbortController()
chunksRef.current = splitIntoChunks(text)
playChunk(0)
return true
}, [ttsConfig, stop, playChunk])
return {
speak,
stop,
pause,
resume,
toggle,
state,
error,
currentText,
isEnabled,
isPlaying: state === 'playing',
isLoading: state === 'loading',
isPaused: state === 'paused',
isIdle: state === 'idle',
}
}
+3 -3
View File
@@ -128,7 +128,7 @@ export function RepoDetail() {
/>
) : branchToDisplay ? (
<Badge
className={`text-xs px-2.5 py-0.5 ${
className={`text-xs px-1.5 sm:px-2.5 py-0.5 ${
repo.isWorktree
? "bg-purple-600/20 text-purple-400 border-purple-600/40"
: isNotMainBranch
@@ -137,8 +137,8 @@ export function RepoDetail() {
}`}
title={repo.isWorktree ? "Worktree" : branchToDisplay}
>
{repo.isWorktree && <GitBranch className="h-3 w-3 mr-1" />}
{branchToDisplay}
{repo.isWorktree && <GitBranch className="h-3 w-3 sm:mr-1" />}
<span className="hidden sm:inline">{branchToDisplay}</span>
</Badge>
) : null}
</div>