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:
Chris Scott authored and GitHub committed 2026-04-29 12:26:41 -04:00
1 parent 04400c91cc
commit f0c87ffa5d
11 files changed
+525 -270

No files matched your search

+86
View File
@@ -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()
})
})
+31 -16
View File
@@ -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])