mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
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
This commit is contained in:
1 parent
04400c91cc
commit
f0c87ffa5d
11 files changed
+525
-270
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<PromptInputHandle, PromptInputProps>(
|
||||
const [localMode, setLocalMode] = useState<string | null>(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<number | null>(null)
|
||||
const voiceGestureStartYRef = useRef<number | null>(null)
|
||||
const voiceSwipeArmedRef = useRef(false)
|
||||
const voicePendingReleaseRef = useRef(false)
|
||||
const pendingVoiceAutoSubmitRef = useRef(false)
|
||||
const ignoreVoiceClickUntilRef = useRef(0)
|
||||
const voiceHoldTimerRef = useRef<ReturnType<typeof setTimeout> | 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<PromptInputHandle, PromptInputProps>(
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const voiceButtonContainerRef = useRef<HTMLDivElement | null>(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<PromptInputHandle, PromptInputProps>(
|
||||
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<PromptInputHandle, PromptInputProps>(
|
||||
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<HTMLButtonElement>) => {
|
||||
if ((event.pointerType === 'mouse' && event.button !== 0) || disabled || isProcessing) {
|
||||
return
|
||||
}
|
||||
|
||||
voiceHoldStartYRef.current = event.clientY
|
||||
voiceHoldActiveRef.current = true
|
||||
await startVoiceRecording()
|
||||
}
|
||||
|
||||
const handleVoicePointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
|
||||
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<HTMLButtonElement>) => {
|
||||
if (!voiceHoldActiveRef.current || voiceHoldStartYRef.current === null) {
|
||||
const handleVoicePointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
|
||||
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<PromptInputHandle, PromptInputProps>(
|
||||
}
|
||||
}
|
||||
|
||||
const handleVoicePointerEnd = (event: ReactPointerEvent<HTMLButtonElement>, canceled = false) => {
|
||||
const handleVoicePointerEnd = (event: ReactPointerEvent<HTMLDivElement>, 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<PromptInputHandle, PromptInputProps>(
|
||||
}, [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<PromptInputHandle, PromptInputProps>(
|
||||
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<PromptInputHandle, PromptInputProps>(
|
||||
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<PromptInputHandle, PromptInputProps>(
|
||||
|
||||
if (!pendingVoiceAutoSubmitRef.current) {
|
||||
textareaRef.current?.focus()
|
||||
} else {
|
||||
setIsVoiceAutoSendWaitingForTranscript(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -673,31 +644,21 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
}, [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 (
|
||||
<div
|
||||
aria-live="polite"
|
||||
className="pointer-events-none absolute inset-x-0 bottom-0 z-10"
|
||||
>
|
||||
<span className="sr-only">{voiceFeedbackLabel}</span>
|
||||
<div className="relative flex h-36 w-full flex-col items-center justify-between overflow-hidden rounded-xl border border-green-300/70 bg-gradient-to-t from-green-700 via-green-500 to-emerald-400 px-1 py-3 text-white shadow-lg shadow-green-500/40">
|
||||
<div className="absolute inset-x-1 top-1 h-10 rounded-full bg-white/20 blur-sm" />
|
||||
<div className="relative flex flex-1 flex-col items-center justify-center gap-2">
|
||||
<ArrowUp className="h-6 w-6 animate-bounce" />
|
||||
<span className="text-[9px] font-bold uppercase leading-none tracking-tight">Swipe</span>
|
||||
</div>
|
||||
<span className="relative text-[10px] font-bold uppercase leading-none tracking-wide">Send</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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<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
|
||||
@@ -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 (
|
||||
<div ref={voiceButtonContainerRef} className={isDesktop ? 'relative hidden md:block' : 'relative'}>
|
||||
{renderVoiceStatusOverlay()}
|
||||
<div
|
||||
ref={voiceButtonContainerRef}
|
||||
className={containerClassName}
|
||||
{...voiceGestureHandlers}
|
||||
>
|
||||
<VoiceStatusOverlay show={!isDesktop && showVoiceFeedback} label={voiceFeedbackLabel} state={voiceFeedbackState} />
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleVoiceClick}
|
||||
onPointerDown={handleVoicePointerDown}
|
||||
onPointerMove={handleVoicePointerMove}
|
||||
onPointerUp={(event) => handleVoicePointerEnd(event)}
|
||||
onPointerCancel={(event) => handleVoicePointerEnd(event, true)}
|
||||
disabled={disabled || isProcessing}
|
||||
className={buttonClassName}
|
||||
title={voiceButtonTitle}
|
||||
@@ -1143,12 +1108,6 @@ const { model, modelString, setModel: setStoredModel } = useModelSelection(opcod
|
||||
onPromptChange?.(prompt.trim().length > 0)
|
||||
}, [prompt, onPromptChange])
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
clearVoiceHoldTimer()
|
||||
}
|
||||
}, [clearVoiceHoldTimer])
|
||||
|
||||
useEffect(() => {
|
||||
if (isRecording) {
|
||||
abortRecording()
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { ArrowUp, LoaderCircle, X } from 'lucide-react'
|
||||
|
||||
export type VoiceStatusOverlayState = 'starting' | 'recording' | 'readyToSend' | 'processing' | 'sending'
|
||||
|
||||
interface VoiceStatusOverlayProps {
|
||||
show: boolean
|
||||
label: string | null
|
||||
state: VoiceStatusOverlayState | null
|
||||
}
|
||||
|
||||
export function VoiceStatusOverlay({ show, label, state }: VoiceStatusOverlayProps) {
|
||||
if (!show || !label || !state) {
|
||||
return null
|
||||
}
|
||||
|
||||
const isLoading = state === 'starting' || state === 'processing' || state === 'sending'
|
||||
const topLabel = state === 'readyToSend'
|
||||
? 'Release'
|
||||
: state === 'starting'
|
||||
? 'Starting'
|
||||
: state === 'processing'
|
||||
? 'Transcribe'
|
||||
: state === 'sending'
|
||||
? 'Sending'
|
||||
: 'Swipe'
|
||||
const bottomLabel = state === 'starting'
|
||||
? 'Mic'
|
||||
: state === 'processing'
|
||||
? 'Speech'
|
||||
: state === 'sending'
|
||||
? 'Prompt'
|
||||
: state === 'readyToSend'
|
||||
? 'Send'
|
||||
: 'Send'
|
||||
const actionWords = state === 'readyToSend'
|
||||
? ['Release', 'To', 'Send']
|
||||
: ['Swipe', 'To', 'Send']
|
||||
|
||||
return (
|
||||
<div
|
||||
aria-live="polite"
|
||||
className="pointer-events-none absolute inset-x-0 bottom-0 z-10"
|
||||
>
|
||||
<span className="sr-only">{label}</span>
|
||||
<div className="relative flex h-36 w-full flex-col items-center justify-between overflow-hidden rounded-xl border border-green-300/70 bg-gradient-to-t from-green-700 via-green-500 to-emerald-400 px-1 py-3 text-white shadow-lg shadow-green-500/40">
|
||||
<div className="absolute inset-x-1 top-1 h-10 rounded-full bg-white/20 blur-sm" />
|
||||
<div className="relative flex flex-1 flex-col items-center justify-center gap-1">
|
||||
{isLoading ? (
|
||||
<>
|
||||
<LoaderCircle className="h-6 w-6 animate-spin" />
|
||||
<span className="text-[10px] font-bold uppercase leading-none tracking-wide">{topLabel}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ArrowUp className="h-8 w-8 animate-bounce" />
|
||||
<div className="flex flex-col items-center text-[9px] font-bold uppercase leading-none tracking-tight">
|
||||
{actionWords.map((word) => (
|
||||
<span key={word}>{word}</span>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{isLoading ? (
|
||||
<span className="relative text-[10px] font-bold uppercase leading-none tracking-wide">{bottomLabel}</span>
|
||||
) : (
|
||||
<X className="relative h-4 w-4" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { RepoQuickSwitchSheet } from './RepoQuickSwitchSheet'
|
||||
import { listRepos } from '@/api/repos'
|
||||
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
|
||||
|
||||
vi.mock('@/api/repos')
|
||||
|
||||
@@ -29,6 +30,16 @@ function LocationSpy() {
|
||||
return <div data-testid="location">{`${pathname}${search}`}</div>
|
||||
}
|
||||
|
||||
function MobileSheetHarness() {
|
||||
const { close } = useMobileTabBar()
|
||||
return (
|
||||
<>
|
||||
<RepoQuickSwitchSheet isOpen onClose={close} />
|
||||
<LocationSpy />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
describe('RepoQuickSwitchSheet', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
@@ -162,7 +173,7 @@ describe('RepoQuickSwitchSheet', () => {
|
||||
fireEvent.click(screen.getByText('repo1'))
|
||||
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('/repos/1/assistant')
|
||||
expect(handleClose).toHaveBeenCalled()
|
||||
expect(handleClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('navigates from assistant to repo detail when clicking active repo', async () => {
|
||||
@@ -206,4 +217,47 @@ describe('RepoQuickSwitchSheet', () => {
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('/repos/1')
|
||||
expect(handleClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('switches repos from the mobile repos sheet without navigating back to the previous repo', async () => {
|
||||
vi.mocked(listRepos).mockResolvedValue([
|
||||
{
|
||||
id: 1,
|
||||
repoUrl: 'https://github.com/test/repo1.git',
|
||||
localPath: '/path/to/repo1',
|
||||
sourcePath: null,
|
||||
currentBranch: 'main',
|
||||
isLocal: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
repoUrl: 'https://github.com/test/repo2.git',
|
||||
localPath: '/path/to/repo2',
|
||||
sourcePath: null,
|
||||
currentBranch: 'main',
|
||||
isLocal: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
])
|
||||
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<MemoryRouter initialEntries={['/repos/1?mobileTab=repos']}>
|
||||
<Routes>
|
||||
<Route path="*" element={<MobileSheetHarness />} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('repo2')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByText('repo2'))
|
||||
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('/repos/2')
|
||||
})
|
||||
})
|
||||
@@ -38,18 +38,26 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
|
||||
)
|
||||
}, [repos, searchQuery])
|
||||
|
||||
const isUrlControlledSheet = new URLSearchParams(location.search).get('mobileTab') === 'repos'
|
||||
|
||||
const navigateAndClose = (path: string, options?: { replace?: boolean }) => {
|
||||
navigate(path, options)
|
||||
if (!isUrlControlledSheet) {
|
||||
onClose()
|
||||
}
|
||||
}
|
||||
|
||||
const handleClick = (id: number) => {
|
||||
const pendingAction = new URLSearchParams(location.search).get('mobileTabAction')
|
||||
if (pendingAction === 'assistant') {
|
||||
navigate(`/repos/${id}/assistant`)
|
||||
onClose()
|
||||
navigateAndClose(`/repos/${id}/assistant`)
|
||||
return
|
||||
}
|
||||
|
||||
const isAssistantRoute = location.pathname === `/repos/${id}/assistant`
|
||||
if (id === activeRepoId) {
|
||||
if (isAssistantRoute) {
|
||||
navigate(`/repos/${id}`, { replace: true })
|
||||
navigateAndClose(`/repos/${id}`, { replace: true })
|
||||
return
|
||||
}
|
||||
|
||||
@@ -57,8 +65,7 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
|
||||
return
|
||||
}
|
||||
|
||||
navigate(`/repos/${id}`, { replace: true })
|
||||
onClose()
|
||||
navigateAndClose(`/repos/${id}`, { replace: true })
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -3,6 +3,7 @@ import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { useSSE } from './useSSE'
|
||||
import { useSessionStatus } from '../stores/sessionStatusStore'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getSessionStatuses: vi.fn(),
|
||||
@@ -64,11 +65,13 @@ describe('useSSE', () => {
|
||||
vi.clearAllMocks()
|
||||
MockEventSource.instances = []
|
||||
mocks.getSessionStatuses.mockResolvedValue({})
|
||||
useSessionStatus.getState().replaceStatuses({})
|
||||
globalThis.EventSource = MockEventSource as unknown as typeof EventSource
|
||||
globalThis.fetch = vi.fn(() => Promise.resolve({ ok: true } as Response))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
useSessionStatus.getState().replaceStatuses({})
|
||||
globalThis.EventSource = originalEventSource
|
||||
globalThis.fetch = originalFetch
|
||||
})
|
||||
@@ -125,4 +128,87 @@ describe('useSSE', () => {
|
||||
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('clears stale active statuses from the initial status snapshot', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
|
||||
useSessionStatus.getState().setStatus('session-1', { type: 'busy' })
|
||||
|
||||
const { unmount } = renderHook(
|
||||
() => useSSE('http://localhost:5551', '/repo', 'session-1'),
|
||||
{ wrapper }
|
||||
)
|
||||
|
||||
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
|
||||
|
||||
act(() => {
|
||||
MockEventSource.instances[0].emit('connected', { clientId: 'client-1' })
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'idle' })
|
||||
})
|
||||
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('ignores stale status snapshots after the directory changes', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
|
||||
let resolveRepoA: (value: Record<string, { type: 'busy' }>) => void = () => {}
|
||||
let resolveRepoB: (value: Record<string, { type: 'busy' }>) => void = () => {}
|
||||
mocks.getSessionStatuses
|
||||
.mockImplementationOnce(() => new Promise((resolve) => { resolveRepoA = resolve }))
|
||||
.mockImplementationOnce(() => new Promise((resolve) => { resolveRepoB = resolve }))
|
||||
|
||||
const { rerender, unmount } = renderHook(
|
||||
({ directory }) => useSSE('http://localhost:5551', directory, 'session-1'),
|
||||
{ wrapper, initialProps: { directory: '/repo-a' } }
|
||||
)
|
||||
|
||||
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
|
||||
|
||||
act(() => {
|
||||
MockEventSource.instances[0].emit('connected', { clientId: 'client-1' })
|
||||
})
|
||||
|
||||
rerender({ directory: '/repo-b' })
|
||||
|
||||
await waitFor(() => expect(MockEventSource.instances).toHaveLength(2))
|
||||
|
||||
act(() => {
|
||||
MockEventSource.instances[1].emit('connected', { clientId: 'client-2' })
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
resolveRepoB({ 'session-b': { type: 'busy' } })
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(useSessionStatus.getState().getStatus('session-b')).toEqual({ type: 'busy' })
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
resolveRepoA({ 'session-a': { type: 'busy' } })
|
||||
})
|
||||
|
||||
expect(useSessionStatus.getState().getStatus('session-b')).toEqual({ type: 'busy' })
|
||||
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'idle' })
|
||||
|
||||
unmount()
|
||||
})
|
||||
})
|
||||
@@ -10,6 +10,11 @@ import { sseManager, subscribeToSSE, reconnectSSE, addSSEDirectory } from '@/lib
|
||||
import { parseOpenCodeError } from '@/lib/opencode-errors'
|
||||
import { createPartsBatcher } from '@/lib/partsBatcher'
|
||||
|
||||
const getEventDirectory = (event: SSEEvent): string | undefined => {
|
||||
const directory = (event as { directory?: unknown }).directory
|
||||
return typeof directory === 'string' ? directory : undefined
|
||||
}
|
||||
|
||||
const handleRestartServer = async () => {
|
||||
showToast.loading('Reloading OpenCode configuration...', {
|
||||
id: 'restart-server',
|
||||
@@ -45,16 +50,18 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
|
||||
const queryClient = useQueryClient()
|
||||
const mountedRef = useRef(true)
|
||||
const sessionIdRef = useRef(currentSessionId)
|
||||
const statusSyncVersionRef = useRef(0)
|
||||
sessionIdRef.current = currentSessionId
|
||||
const [isConnected, setIsConnected] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [isReconnecting, setIsReconnecting] = useState(false)
|
||||
const setSessionStatus = useSessionStatus((state) => state.setStatus)
|
||||
const replaceSessionStatuses = useSessionStatus((state) => state.replaceStatuses)
|
||||
const setSessionTodos = useSessionTodos((state) => state.setTodos)
|
||||
const batcherRef = useRef<ReturnType<typeof createPartsBatcher> | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!opcodeUrl) {
|
||||
if (!opcodeUrl || !directory) {
|
||||
batcherRef.current?.destroy()
|
||||
batcherRef.current = null
|
||||
return
|
||||
@@ -69,7 +76,11 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
|
||||
}, [queryClient, opcodeUrl, directory])
|
||||
|
||||
const handleSSEEvent = useCallback((event: SSEEvent) => {
|
||||
const eventDirectory = getEventDirectory(event)
|
||||
if (eventDirectory && directory && eventDirectory !== directory) return
|
||||
|
||||
switch (event.type) {
|
||||
case 'session.created':
|
||||
case 'session.updated':
|
||||
if ('info' in event.properties) {
|
||||
const session = event.properties.info
|
||||
@@ -118,6 +129,13 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
|
||||
break
|
||||
}
|
||||
|
||||
case 'message.part.delta': {
|
||||
if (!('sessionID' in event.properties && 'messageID' in event.properties && 'partID' in event.properties && 'field' in event.properties && 'delta' in event.properties)) break
|
||||
const { sessionID, messageID, partID, field, delta } = event.properties
|
||||
batcherRef.current?.queuePartDelta(sessionID, messageID, partID, field, delta)
|
||||
break
|
||||
}
|
||||
|
||||
case 'message.updated':
|
||||
case 'messagev2.updated': {
|
||||
if (!('info' in event.properties)) break
|
||||
@@ -125,11 +143,6 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
|
||||
const { info } = event.properties
|
||||
const sessionID = info.sessionID
|
||||
|
||||
if (info.role === 'assistant') {
|
||||
const isComplete = 'completed' in info.time && info.time.completed
|
||||
setSessionStatus(sessionID, isComplete ? { type: 'idle' } : { type: 'busy' })
|
||||
}
|
||||
|
||||
const messagesQueryKey = ['opencode', 'messages', opcodeUrl, sessionID, directory]
|
||||
const currentData = queryClient.getQueryData<MessageWithParts[]>(messagesQueryKey)
|
||||
if (!currentData) {
|
||||
@@ -313,25 +326,24 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
|
||||
}, [queryClient, opcodeUrl, directory, setSessionStatus, setSessionTodos, currentSessionId])
|
||||
|
||||
const fetchInitialData = useCallback(async () => {
|
||||
if (!client || !mountedRef.current) return
|
||||
if (!client || !directory || !mountedRef.current) return
|
||||
const syncVersion = ++statusSyncVersionRef.current
|
||||
|
||||
try {
|
||||
const statuses = await client.getSessionStatuses()
|
||||
if (mountedRef.current && statuses) {
|
||||
Object.entries(statuses).forEach(([sessionID, status]) => {
|
||||
setSessionStatus(sessionID, status)
|
||||
})
|
||||
if (mountedRef.current && statusSyncVersionRef.current === syncVersion && statuses) {
|
||||
replaceSessionStatuses(statuses)
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof Error && !err.message.includes('aborted')) {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
}, [client, setSessionStatus])
|
||||
}, [client, directory, replaceSessionStatuses])
|
||||
|
||||
const syncCurrentSession = useCallback(() => {
|
||||
const sessionId = sessionIdRef.current
|
||||
if (!sessionId || !opcodeUrl) return
|
||||
if (!sessionId || !opcodeUrl || !directory) return
|
||||
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['opencode', 'session', opcodeUrl, sessionId, directory],
|
||||
@@ -344,8 +356,10 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
|
||||
if (!opcodeUrl) {
|
||||
if (!opcodeUrl || !directory) {
|
||||
statusSyncVersionRef.current += 1
|
||||
setIsConnected(false)
|
||||
setIsReconnecting(false)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -370,7 +384,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
|
||||
}
|
||||
}
|
||||
|
||||
const directoryCleanup = directory ? addSSEDirectory(directory) : undefined
|
||||
const directoryCleanup = addSSEDirectory(directory)
|
||||
|
||||
const unsubscribe = subscribeToSSE(handleMessage, handleStatusChange)
|
||||
|
||||
@@ -388,11 +402,12 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
|
||||
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
statusSyncVersionRef.current += 1
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange)
|
||||
window.removeEventListener('focus', handleReconnect)
|
||||
window.removeEventListener('online', handleReconnect)
|
||||
unsubscribe()
|
||||
directoryCleanup?.()
|
||||
directoryCleanup()
|
||||
}
|
||||
}, [opcodeUrl, directory, handleSSEEvent, fetchInitialData, syncCurrentSession])
|
||||
|
||||
|
||||
@@ -3,18 +3,23 @@ import type { Part, MessageWithParts } from '@/api/types'
|
||||
|
||||
interface PartsBatcher {
|
||||
queuePartUpdate: (sessionID: string, part: Part) => void
|
||||
queuePartDelta: (sessionID: string, messageID: string, partID: string, field: string, delta: string) => void
|
||||
queuePartRemoval: (sessionID: string, messageID: string, partID: string) => void
|
||||
flush: () => void
|
||||
destroy: () => void
|
||||
}
|
||||
|
||||
type PartOperation =
|
||||
| { type: 'upsert'; part: Part }
|
||||
| { type: 'delta'; messageID: string; partID: string; field: string; delta: string }
|
||||
| { type: 'remove'; messageID: string; partID: string }
|
||||
|
||||
export function createPartsBatcher(
|
||||
queryClient: QueryClient,
|
||||
opcodeUrl: string,
|
||||
directory?: string
|
||||
): PartsBatcher {
|
||||
const pendingUpserts = new Map<string, Map<string, Part>>()
|
||||
const pendingRemovals = new Map<string, Map<string, Set<string>>>()
|
||||
const pendingOperations = new Map<string, PartOperation[]>()
|
||||
let pendingFrameId: number | null = null
|
||||
|
||||
const scheduleFlush = () => {
|
||||
@@ -26,14 +31,9 @@ export function createPartsBatcher(
|
||||
}
|
||||
|
||||
const flush = () => {
|
||||
if (pendingUpserts.size === 0 && pendingRemovals.size === 0) return
|
||||
if (pendingOperations.size === 0) return
|
||||
|
||||
const sessionsToUpdate = new Set([
|
||||
...pendingUpserts.keys(),
|
||||
...pendingRemovals.keys(),
|
||||
])
|
||||
|
||||
for (const sessionID of sessionsToUpdate) {
|
||||
for (const [sessionID, operations] of pendingOperations.entries()) {
|
||||
const queryKey = ['opencode', 'messages', opcodeUrl, sessionID, directory]
|
||||
const currentData = queryClient.getQueryData<MessageWithParts[]>(queryKey)
|
||||
|
||||
@@ -41,64 +41,67 @@ export function createPartsBatcher(
|
||||
|
||||
let updatedData = [...currentData]
|
||||
|
||||
const sessionUpserts = pendingUpserts.get(sessionID)
|
||||
const sessionRemovals = pendingRemovals.get(sessionID)
|
||||
for (const operation of operations) {
|
||||
updatedData = updatedData.map((msgWithParts) => {
|
||||
if (operation.type === 'upsert') {
|
||||
if (msgWithParts.info.id !== operation.part.messageID) return msgWithParts
|
||||
|
||||
updatedData = updatedData.map((msgWithParts) => {
|
||||
let msgParts = [...msgWithParts.parts]
|
||||
|
||||
if (sessionRemovals?.has(msgWithParts.info.id)) {
|
||||
const partIDsToRemove = sessionRemovals.get(msgWithParts.info.id)!
|
||||
msgParts = msgParts.filter((p) => !partIDsToRemove.has(p.id))
|
||||
}
|
||||
|
||||
if (sessionUpserts) {
|
||||
const partsForMessage = Array.from(sessionUpserts.values()).filter(
|
||||
(part) => part.messageID === msgWithParts.info.id
|
||||
)
|
||||
for (const part of partsForMessage) {
|
||||
const existingIdx = msgParts.findIndex((p) => p.id === part.id)
|
||||
const existingIdx = msgWithParts.parts.findIndex((part) => part.id === operation.part.id)
|
||||
const parts = [...msgWithParts.parts]
|
||||
if (existingIdx >= 0) {
|
||||
msgParts[existingIdx] = part
|
||||
parts[existingIdx] = operation.part
|
||||
} else {
|
||||
msgParts.push(part)
|
||||
parts.push(operation.part)
|
||||
}
|
||||
|
||||
return { ...msgWithParts, parts }
|
||||
}
|
||||
|
||||
if (msgWithParts.info.id !== operation.messageID) return msgWithParts
|
||||
|
||||
if (operation.type === 'remove') {
|
||||
return {
|
||||
...msgWithParts,
|
||||
parts: msgWithParts.parts.filter((part) => part.id !== operation.partID),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...msgWithParts,
|
||||
parts: msgParts,
|
||||
}
|
||||
})
|
||||
return {
|
||||
...msgWithParts,
|
||||
parts: msgWithParts.parts.map((part) => {
|
||||
if (part.id !== operation.partID) return part
|
||||
|
||||
const currentValue = (part as Record<string, unknown>)[operation.field]
|
||||
const nextValue = `${typeof currentValue === 'string' ? currentValue : ''}${operation.delta}`
|
||||
return { ...part, [operation.field]: nextValue } as Part
|
||||
}),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
queryClient.setQueryData(queryKey, updatedData)
|
||||
}
|
||||
|
||||
pendingUpserts.clear()
|
||||
pendingRemovals.clear()
|
||||
pendingOperations.clear()
|
||||
}
|
||||
|
||||
const queueOperation = (sessionID: string, operation: PartOperation) => {
|
||||
const operations = pendingOperations.get(sessionID) ?? []
|
||||
operations.push(operation)
|
||||
pendingOperations.set(sessionID, operations)
|
||||
scheduleFlush()
|
||||
}
|
||||
|
||||
const queuePartUpdate = (sessionID: string, part: Part) => {
|
||||
if (!pendingUpserts.has(sessionID)) {
|
||||
pendingUpserts.set(sessionID, new Map())
|
||||
}
|
||||
const sessionUpserts = pendingUpserts.get(sessionID)!
|
||||
sessionUpserts.set(part.id, part)
|
||||
scheduleFlush()
|
||||
queueOperation(sessionID, { type: 'upsert', part })
|
||||
}
|
||||
|
||||
const queuePartDelta = (sessionID: string, messageID: string, partID: string, field: string, delta: string) => {
|
||||
queueOperation(sessionID, { type: 'delta', messageID, partID, field, delta })
|
||||
}
|
||||
|
||||
const queuePartRemoval = (sessionID: string, messageID: string, partID: string) => {
|
||||
if (!pendingRemovals.has(sessionID)) {
|
||||
pendingRemovals.set(sessionID, new Map())
|
||||
}
|
||||
const sessionRemovals = pendingRemovals.get(sessionID)!
|
||||
if (!sessionRemovals.has(messageID)) {
|
||||
sessionRemovals.set(messageID, new Set())
|
||||
}
|
||||
const messageRemovals = sessionRemovals.get(messageID)!
|
||||
messageRemovals.add(partID)
|
||||
scheduleFlush()
|
||||
queueOperation(sessionID, { type: 'remove', messageID, partID })
|
||||
}
|
||||
|
||||
const destroy = () => {
|
||||
@@ -106,12 +109,12 @@ export function createPartsBatcher(
|
||||
cancelAnimationFrame(pendingFrameId)
|
||||
pendingFrameId = null
|
||||
}
|
||||
pendingUpserts.clear()
|
||||
pendingRemovals.clear()
|
||||
pendingOperations.clear()
|
||||
}
|
||||
|
||||
return {
|
||||
queuePartUpdate,
|
||||
queuePartDelta,
|
||||
queuePartRemoval,
|
||||
flush,
|
||||
destroy,
|
||||
|
||||
@@ -10,6 +10,7 @@ interface SessionStatusStore {
|
||||
statuses: Map<string, SessionStatusType>
|
||||
statusCache: Map<string, string>
|
||||
setStatus: (sessionID: string, status: SessionStatusType) => void
|
||||
replaceStatuses: (statuses: Record<string, SessionStatusType>) => void
|
||||
getStatus: (sessionID: string) => SessionStatusType
|
||||
clearStatus: (sessionID: string) => void
|
||||
}
|
||||
@@ -32,6 +33,19 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => ({
|
||||
const previousHash = get().statusCache.get(sessionID)
|
||||
|
||||
if (previousHash === hash) return
|
||||
|
||||
if (status.type === 'idle') {
|
||||
if (!previousHash) return
|
||||
|
||||
set((state) => {
|
||||
const newMap = new Map(state.statuses)
|
||||
const newCache = new Map(state.statusCache)
|
||||
newMap.delete(sessionID)
|
||||
newCache.delete(sessionID)
|
||||
return { statuses: newMap, statusCache: newCache }
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
set((state) => {
|
||||
const newMap = new Map(state.statuses)
|
||||
@@ -41,6 +55,31 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => ({
|
||||
return { statuses: newMap, statusCache: newCache }
|
||||
})
|
||||
},
|
||||
|
||||
replaceStatuses: (statuses: Record<string, SessionStatusType>) => {
|
||||
const newMap = new Map<string, SessionStatusType>()
|
||||
const newCache = new Map<string, string>()
|
||||
|
||||
for (const [sessionID, status] of Object.entries(statuses)) {
|
||||
if (status.type === 'idle') continue
|
||||
newMap.set(sessionID, status)
|
||||
newCache.set(sessionID, getStatusHash(status))
|
||||
}
|
||||
|
||||
const currentCache = get().statusCache
|
||||
if (currentCache.size === newCache.size) {
|
||||
let unchanged = true
|
||||
for (const [sessionID, hash] of newCache.entries()) {
|
||||
if (currentCache.get(sessionID) !== hash) {
|
||||
unchanged = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if (unchanged) return
|
||||
}
|
||||
|
||||
set({ statuses: newMap, statusCache: newCache })
|
||||
},
|
||||
|
||||
getStatus: (sessionID: string) => {
|
||||
return get().statuses.get(sessionID) || DEFAULT_STATUS
|
||||
|
||||
Reference in new issue
Block a user