refactor(frontend): isolate voice conversation from the memoized composer re-renders

This commit is contained in:
Chris Scott committed 2026-10-22 21:58:13 -04:00
1 parent 95cd276e37
commit a5694d874f
9 files changed
+201 -79

No files matched your search

@@ -147,9 +147,6 @@ describe('PromptInput command submission', () => {
const defaultProps = {
directory: '/test',
sessionID: 'test-session',
messages: [],
pending: [],
transcriptStatus: 'idle' as const,
showScrollButton: false,
isSessionActive: false,
isStreamingResponse: false,
@@ -93,9 +93,6 @@ const createTestQueryClient = () => new QueryClient({
const defaultProps = {
directory: '/test',
sessionID: 'test-session',
messages: [],
pending: [],
transcriptStatus: 'idle' as const,
showScrollButton: false,
isSessionActive: false,
isStreamingResponse: false,
@@ -145,9 +145,6 @@ describe('PromptInput goal mode', () => {
const defaultProps = {
directory: '/test',
sessionID: 'test-session',
messages: [],
pending: [],
transcriptStatus: 'idle' as const,
showScrollButton: false,
isSessionActive: false,
isStreamingResponse: false,
@@ -133,9 +133,6 @@ describe('PromptInput agent mention submission', () => {
const defaultProps = {
directory: '/test',
sessionID: 'test-session',
messages: [],
pending: [],
transcriptStatus: 'idle' as const,
showScrollButton: false,
isSessionActive: false,
isStreamingResponse: false,
@@ -2,6 +2,10 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput } from './PromptInput'
import {
SessionTranscriptContext,
type SessionTranscriptSnapshot,
} from '@/contexts/session-transcript-context'
import {
createCommandActionsMock,
createVoiceConversationControllerMock,
@@ -10,6 +14,7 @@ import type {
UseVoiceConversationInput,
VoiceConversationController,
} from '@/hooks/useVoiceConversation'
import type { SessionMessageInfo } from '@opencode-manager/shared/opencode'
const createTestQueryClient = () => new QueryClient({
defaultOptions: {
@@ -146,9 +151,6 @@ describe('PromptInput voice conversation', () => {
const defaultProps = {
directory: '/test',
sessionID: 'test-session',
messages: [],
pending: [],
transcriptStatus: 'idle' as const,
showScrollButton: false,
isSessionActive: false,
isStreamingResponse: false,
@@ -157,17 +159,41 @@ describe('PromptInput voice conversation', () => {
onPromptChange: vi.fn(),
}
const renderComponent = (overrides: Partial<typeof defaultProps> = {}) => {
const createUserMessage = (id: string, text: string): SessionMessageInfo => ({
id,
type: 'user',
text,
time: { created: 1000 },
} as SessionMessageInfo)
const buildSnapshot = (overrides: Partial<SessionTranscriptSnapshot> = {}): SessionTranscriptSnapshot => ({
messages: [],
pending: [],
status: 'idle',
...overrides,
})
const renderComponent = (
overrides: Partial<typeof defaultProps> = {},
snapshotOverrides: Partial<SessionTranscriptSnapshot> = {},
) => {
const queryClient = createTestQueryClient()
const tree = (nextOverrides: Partial<typeof defaultProps>) => (
const tree = (
nextOverrides: Partial<typeof defaultProps>,
snapshot = buildSnapshot(snapshotOverrides),
) => (
<QueryClientProvider client={queryClient}>
<PromptInput {...defaultProps} {...overrides} {...nextOverrides} />
<SessionTranscriptContext.Provider value={snapshot}>
<PromptInput {...defaultProps} {...overrides} {...nextOverrides} />
</SessionTranscriptContext.Provider>
</QueryClientProvider>
)
const view = render(tree({}))
return {
...view,
rerenderWith: (nextOverrides: Partial<typeof defaultProps>) => view.rerender(tree(nextOverrides)),
rerenderWith: (nextOverrides: Partial<typeof defaultProps>) => {
view.rerender(tree(nextOverrides, buildSnapshot(snapshotOverrides)))
},
}
}
@@ -251,6 +277,16 @@ describe('PromptInput voice conversation', () => {
})
})
it('passes the published transcript to the voice conversation', () => {
const messages = [createUserMessage('msg_voice_1', 'hello there')]
renderComponent({}, { messages, status: 'busy' })
expect(mocks.useVoiceConversation).toHaveBeenCalledWith(
expect.objectContaining({ messages, status: 'busy' }),
)
})
describe('while a conversation is active', () => {
it('replaces the composer with the conversation bar and keeps the draft after exit', () => {
const onVoiceConversationActiveChange = vi.fn()
@@ -259,14 +295,14 @@ describe('PromptInput voice conversation', () => {
fireEvent.change(promptInput(), { target: { value: 'keep this draft' } })
setVoiceController({ isActive: true, phase: 'listening', label: 'Listening' })
view.rerenderWith({ messages: [] })
view.rerenderWith({})
expect(screen.queryByPlaceholderText('Send a message...')).toBeNull()
expect(screen.getByText('Listening')).toBeInTheDocument()
expect(onVoiceConversationActiveChange).toHaveBeenLastCalledWith(true)
setVoiceController()
view.rerenderWith({ messages: [] })
view.rerenderWith({})
expect(promptInput()).toHaveValue('keep this draft')
expect(onVoiceConversationActiveChange).toHaveBeenLastCalledWith(false)
@@ -279,7 +315,7 @@ describe('PromptInput voice conversation', () => {
fireEvent.click(screen.getByRole('button', { name: 'Edit in text box' }))
setVoiceController()
view.rerenderWith({ messages: [] })
view.rerenderWith({})
expect(promptInput()).toHaveValue('dictated words')
})
@@ -290,11 +326,11 @@ describe('PromptInput voice conversation', () => {
fireEvent.change(promptInput(), { target: { value: 'draft' } })
setVoiceController({ isActive: true, phase: 'listening', canEditInTextBox: true }, 'dictated words')
view.rerenderWith({ messages: [] })
view.rerenderWith({})
fireEvent.click(screen.getByRole('button', { name: 'Edit in text box' }))
setVoiceController()
view.rerenderWith({ messages: [] })
view.rerenderWith({})
expect(promptInput()).toHaveValue('draft dictated words')
})
@@ -305,11 +341,11 @@ describe('PromptInput voice conversation', () => {
fireEvent.change(promptInput(), { target: { value: 'draft' } })
setVoiceController({ isActive: true, phase: 'listening', canEditInTextBox: true }, 'dictated words')
view.rerenderWith({ messages: [] })
view.rerenderWith({})
fireEvent.click(screen.getByRole('button', { name: 'Edit in text box' }))
setVoiceController()
view.rerenderWith({ messages: [] })
view.rerenderWith({})
await waitFor(() => {
const input = promptInput() as HTMLTextAreaElement
@@ -366,9 +402,6 @@ describe('PromptInput submission', () => {
const defaultProps = {
directory: '/test',
sessionID: 'test-session',
messages: [],
pending: [],
transcriptStatus: 'idle' as const,
showScrollButton: false,
isSessionActive: false,
isStreamingResponse: false,
+26 -35
View File
@@ -7,8 +7,6 @@ import { useModelSelection } from '@/hooks/useModelSelection'
import { useVariants } from '@/hooks/useVariants'
import { useSessionAgent } from '@/hooks/useSessionAgent'
import { useSttAvailability } from '@/hooks/useSTT'
import { useVoiceConversation } from '@/hooks/useVoiceConversation'
import { useVoicePauseSetting } from '@/hooks/useVoicePauseSetting'
import { useUserBash } from '@/stores/userBashStore'
import { useSessionAgentStore } from '@/stores/sessionAgentStore'
@@ -30,7 +28,7 @@ import { PromptSuggestions, type PromptSuggestion } from './PromptSuggestions'
import { ComposerActivityBar } from './ComposerActivityBar'
import { ModelQuickSelect } from '@/components/model/ModelQuickSelect'
import { AgentQuickSelect } from '@/components/agent/AgentQuickSelect'
import { VoiceConversationBar } from './VoiceConversationBar'
import { VoiceConversation, type VoiceConversationHandle } from './VoiceConversation'
import { PermissionModeToggle } from '@/components/session/PermissionModeToggle'
import { SessionSandboxMenu } from '@/components/session/SessionSandboxMenu'
import { ComposerToolsMenu } from './ComposerToolsMenu'
@@ -47,7 +45,7 @@ import { isOpenSessionGoal } from '@opencode-manager/shared/schemas'
import { useProviders } from '@/hooks/useProviders'
import type { CommandInfo, SessionInboxInfo, SessionMessageInfo, VoiceSessionStatus } from '@opencode-manager/shared/opencode'
import type { CommandInfo } from '@opencode-manager/shared/opencode'
import type { FileAttachmentInfo, ImageAttachment } from '@/api/types'
import { isBuiltinCommand, type CommandActions, type PageCommandActions } from '@/lib/builtinCommands'
@@ -120,9 +118,6 @@ export interface PromptInputHandle {
interface PromptInputProps {
directory?: string
sessionID: string
messages: SessionMessageInfo[]
pending: SessionInboxInfo[]
transcriptStatus: VoiceSessionStatus
onVoiceConversationActiveChange?: (active: boolean) => void
showScrollButton?: boolean
isSessionActive?: boolean
@@ -135,9 +130,6 @@ interface PromptInputProps {
export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(function PromptInput({
directory,
sessionID,
messages,
pending,
transcriptStatus,
onVoiceConversationActiveChange,
showScrollButton,
isSessionActive = false,
@@ -162,6 +154,8 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0)
const [localMode, setLocalMode] = useState<string | null>(null)
const [isPromptFocused, setIsPromptFocused] = useState(false)
const [isVoiceActive, setIsVoiceActive] = useState(false)
const voiceRef = useRef<VoiceConversationHandle>(null)
const promptBlurTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const pendingCommandSubmitRef = useRef(false)
const handleSubmitRef = useRef<() => void>(() => {})
@@ -1093,7 +1087,6 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
: 'Goal mode: the next message becomes the objective'
const isGoalModeDisabled = lockedReason !== null || hasOpenGoal || isBashMode || startGoal.isPending
const toggleGoalArmed = () => setIsGoalArmed((value) => !value)
const { pauseMs } = useVoicePauseSetting()
const sendVoiceTurn = useCallback(
async (text: string, options: { busy: boolean }): Promise<void> => {
@@ -1118,22 +1111,14 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
focusPromptAt(next.length)
}, [focusPromptAt])
const voiceConversation = useVoiceConversation({
sessionID,
serverId,
messages,
pending,
status: transcriptStatus,
hasPendingApproval: hasPendingPermissionForSession,
pauseMs,
sendTurn: sendVoiceTurn,
interrupt: interruptTurn,
onEditInTextBox: handleVoiceEditInTextBox,
})
const handleVoiceActiveChange = useCallback((active: boolean) => {
setIsVoiceActive(active)
onVoiceConversationActiveChange?.(active)
}, [onVoiceConversationActiveChange])
useEffect(() => {
onVoiceConversationActiveChange?.(voiceConversation.isActive)
}, [onVoiceConversationActiveChange, voiceConversation.isActive])
const handleViewApproval = useCallback(() => {
setShowDialog(true)
}, [setShowDialog])
const hasPromptContent = prompt.trim().length > 0 || imageAttachments.length > 0
const showVoiceMic = sttAvailability.isEnabled && sttAvailability.isSupported && !hasPendingPermissionForSession
@@ -1147,7 +1132,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
onMouseDown={(event) => event.preventDefault()}
onClick={() => {
textareaRef.current?.blur()
voiceConversation.start()
voiceRef.current?.start()
}}
className={isMobile
? 'min-h-11 min-w-11 px-0 rounded-lg transition-all duration-150 flex items-center justify-center border bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border active:bg-muted-foreground/30 active:scale-95'
@@ -1228,13 +1213,19 @@ return (
{composerModeStyle.label}
</span>
)}
{voiceConversation.isActive ? (
<VoiceConversationBar
controller={voiceConversation}
hasPendingApproval={hasPendingPermissionForSession}
onViewApproval={() => setShowDialog(true)}
/>
) : (
<VoiceConversation
ref={voiceRef}
sessionID={sessionID}
serverId={serverId}
hasPendingApproval={hasPendingPermissionForSession}
sendTurn={sendVoiceTurn}
interrupt={interruptTurn}
onEditInTextBox={handleVoiceEditInTextBox}
onViewApproval={handleViewApproval}
onActiveChange={handleVoiceActiveChange}
/>
{!isVoiceActive && (
<>
<div className="flex items-end gap-1.5 md:gap-2 mb-1.5 md:mb-2">
<textarea
@@ -1403,7 +1394,7 @@ return (
</>
)}
{!voiceConversation.isActive && (
{!isVoiceActive && (
<>
<PromptSuggestions
isOpen={showSuggestions}
@@ -0,0 +1,80 @@
import { forwardRef, useEffect, useImperativeHandle } from 'react'
import { useSessionTranscriptSnapshot } from '@/contexts/session-transcript-context'
import { useVoiceConversation, type UseVoiceConversationInput } from '@/hooks/useVoiceConversation'
import { useVoicePauseSetting } from '@/hooks/useVoicePauseSetting'
import { VoiceConversationBar } from './VoiceConversationBar'
/** Controls the voice conversation that lives inside the session composer. */
export interface VoiceConversationHandle {
/** Starts the conversation loop. */
start: () => void
}
export interface VoiceConversationProps {
/** Id of the session the conversation belongs to. */
sessionID: string
/** Server that owns the session, when it is not the local one. */
serverId?: string
/** Whether the session is waiting for the user to approve a tool or a form. */
hasPendingApproval: boolean
/** Sends one transcribed turn to the session. */
sendTurn: UseVoiceConversationInput['sendTurn']
/** Aborts the reply that the session is currently producing. */
interrupt: UseVoiceConversationInput['interrupt']
/** Hands a captured transcript to the composer for editing. */
onEditInTextBox: UseVoiceConversationInput['onEditInTextBox']
/** Opens the pending approval dialog. */
onViewApproval: () => void
/** Reports whether voice mode is running, including while paused. */
onActiveChange: (active: boolean) => void
}
/**
* Owns the hands-free voice conversation for a session and renders its bar in
* place of the composer while the conversation runs. It reads the transcript
* from {@link useSessionTranscriptSnapshot}, so the composer that hosts it does
* not re-render when the transcript changes, and it stays mounted for the whole
* session because the conversation keeps its sweep, visibility listener and
* cleanup effects alive between turns.
*/
export const VoiceConversation = forwardRef<VoiceConversationHandle, VoiceConversationProps>(
function VoiceConversation({
sessionID,
serverId,
hasPendingApproval,
sendTurn,
interrupt,
onEditInTextBox,
onViewApproval,
onActiveChange,
}, ref) {
const { messages, pending, status } = useSessionTranscriptSnapshot()
const { pauseMs } = useVoicePauseSetting()
const controller = useVoiceConversation({
sessionID,
serverId,
messages,
pending,
status,
hasPendingApproval,
pauseMs,
sendTurn,
interrupt,
onEditInTextBox,
})
useImperativeHandle(ref, () => ({ start: controller.start }), [controller.start])
useEffect(() => {
onActiveChange(controller.isActive)
}, [onActiveChange, controller.isActive])
return controller.isActive ? (
<VoiceConversationBar
controller={controller}
hasPendingApproval={hasPendingApproval}
onViewApproval={onViewApproval}
/>
) : null
},
)
@@ -0,0 +1,25 @@
import { createContext, useContext } from 'react'
import type { SessionInboxInfo, SessionMessageInfo, VoiceSessionStatus } from '@opencode-manager/shared/opencode'
/** The live session transcript a voice conversation reads while it runs. */
export interface SessionTranscriptSnapshot {
/** The session transcript, oldest first. */
messages: SessionMessageInfo[]
/** Prompts the user queued on the session that have not started yet. */
pending: SessionInboxInfo[]
/** Reported status of the conversation's session. */
status: VoiceSessionStatus
}
const EMPTY_TRANSCRIPT_SNAPSHOT: SessionTranscriptSnapshot = { messages: [], pending: [], status: 'idle' }
/** Transcript snapshot published to the composer's voice conversation. */
export const SessionTranscriptContext = createContext<SessionTranscriptSnapshot>(EMPTY_TRANSCRIPT_SNAPSHOT)
/**
* Reads the session transcript published by the surrounding provider, falling
* back to an empty idle transcript when there is none.
*/
export function useSessionTranscriptSnapshot(): SessionTranscriptSnapshot {
return useContext(SessionTranscriptContext)
}
+20 -15
View File
@@ -56,6 +56,7 @@ import { useSessionStatus } from "@/stores/sessionStatusStore";
import type { PageCommandActions } from "@/lib/builtinCommands";
import { useRedoMessage, useUndoMessage } from "@/hooks/useUndoMessage";
import { usePermissions, useForms } from "@/contexts/EventContext";
import { SessionTranscriptContext, type SessionTranscriptSnapshot } from "@/contexts/session-transcript-context";
import type { FormInfo, SessionMessageInfo } from "@opencode-manager/shared/opencode";
import type { SkillFileInfo } from "@opencode-manager/shared";
import { formatOpenCodeModelRef } from "@opencode-manager/shared/opencode";
@@ -274,6 +275,11 @@ export function SessionDetail() {
[transcriptMessages, session?.revert?.messageID],
);
const transcriptSnapshot = useMemo<SessionTranscriptSnapshot>(
() => ({ messages, pending: pendingPrompts, status: transcriptStatus }),
[messages, pendingPrompts, transcriptStatus],
);
const messagesRef = useRef(messages);
messagesRef.current = messages;
@@ -975,21 +981,20 @@ export function SessionDetail() {
onChildSessionClick={handleChildSessionClick}
/>
</div>
<PromptInput
ref={promptInputRef}
directory={sessionDirectory}
sessionID={sessionId}
messages={messages}
pending={pendingPrompts}
transcriptStatus={transcriptStatus}
onVoiceConversationActiveChange={setIsVoiceConversationActive}
showScrollButton={showScrollButton}
isSessionActive={isSessionActive}
isStreamingResponse={isStreamingResponse}
onScrollToBottom={scrollToBottom}
commandActions={commandActions}
onPromptChange={setHasPromptContent}
/>
<SessionTranscriptContext.Provider value={transcriptSnapshot}>
<PromptInput
ref={promptInputRef}
directory={sessionDirectory}
sessionID={sessionId}
onVoiceConversationActiveChange={setIsVoiceConversationActive}
showScrollButton={showScrollButton}
isSessionActive={isSessionActive}
isStreamingResponse={isStreamingResponse}
onScrollToBottom={scrollToBottom}
commandActions={commandActions}
onPromptChange={setHasPromptContent}
/>
</SessionTranscriptContext.Provider>
</div>
</div>
</div>