feat(frontend): give the composer its own strip and let voice mode skip reading replies

This commit is contained in:
Chris Scott committed 2026-11-27 22:26:32 -05:00
1 parent 5f4cf63f8b
commit 6904cfbc58
15 files changed
+341 -55

No files matched your search

@@ -91,17 +91,17 @@ export function FloatingTTSButton({ messageId, content, isScrolledUp, onSpeakVis
: 'TTS controls'
const pillAriaLabel = `${pillTitle}. ${autoPlay ? 'Auto-play enabled.' : 'Auto-play disabled.'} hold to toggle auto-play`
const buttonToneClasses = showStop
? 'justify-center px-3 py-1.5 rounded-lg bg-destructive border border-destructive/60 shadow-destructive/30 ring-destructive/20 hover:ring-destructive/40 text-destructive-foreground'
? 'bg-destructive border border-destructive/60 shadow-destructive/30 ring-destructive/20 hover:ring-destructive/40 text-destructive-foreground'
: autoPlay
? 'justify-center px-3 py-1.5 rounded-lg bg-primary border border-primary/60 shadow-primary/30 ring-primary/20 hover:ring-primary/40 text-primary-foreground'
: 'justify-center px-3 py-1.5 rounded-lg bg-gradient-to-br from-warning to-highlight border border-warning/60 shadow-warning/30 ring-warning/20 hover:ring-warning/40 text-warning-foreground'
? 'bg-primary border border-primary/60 shadow-primary/30 ring-primary/20 hover:ring-primary/40 text-primary-foreground'
: 'bg-gradient-to-br from-warning to-highlight border border-warning/60 shadow-warning/30 ring-warning/20 hover:ring-warning/40 text-warning-foreground'
return (
<button
onPointerDown={handlePointerDown}
onPointerUp={handlePointerUp}
onPointerLeave={handlePointerLeave}
className={`flex items-center transition-all duration-200 shadow-md backdrop-blur-md ring-1 ${buttonToneClasses} ${isLongPressVisual ? 'scale-95 opacity-80' : 'active:scale-95 hover:scale-105'} ${!hasContent && !autoPlay ? 'opacity-50 cursor-not-allowed' : ''}`}
className={`flex h-full w-full items-center justify-center rounded-lg transition-all duration-200 shadow-md ring-1 ${buttonToneClasses} ${isLongPressVisual ? 'scale-95 opacity-80' : 'active:scale-95'} ${!hasContent && !autoPlay ? 'opacity-50 cursor-not-allowed' : ''}`}
title={pillTitle}
aria-label={pillAriaLabel}
disabled={!hasContent && !autoPlay}
@@ -318,9 +318,9 @@ describe('PromptInput command submission', () => {
const tokens = frame.className.split(/\s+/)
expect(tokens).not.toContain('transition-all')
expect(tokens.some((token) => token.startsWith('backdrop-blur'))).toBe(false)
expect(tokens.some((token) => token.includes('backdrop-blur'))).toBe(false)
expect(tokens.some((token) => token.startsWith('opacity-'))).toBe(false)
expect(tokens).toContain('before:backdrop-blur-md')
expect(tokens.some((token) => token.startsWith('before:bg-'))).toBe(false)
})
describe('mobile keybar', () => {
@@ -234,7 +234,7 @@ describe('PromptInput composer layout', () => {
expect(await screen.findByRole('button', { name: /^Session config/ })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Scroll to bottom' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Jump to latest' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Back to latest' })).not.toBeInTheDocument()
})
it('keeps the voice button and the session config in the input row', async () => {
@@ -308,6 +308,41 @@ describe('PromptInput composer layout', () => {
})
})
describe('trailing action slot', () => {
it('renders the trailing action as the last child of the input row', async () => {
await renderPromptInput({
trailingAction: <button type="button" aria-label="Read aloud">Read</button>,
})
await screen.findByPlaceholderText('Send a message...')
const slot = screen.getByTestId('composer-trailing-slot')
const action = screen.getByRole('button', { name: 'Read aloud' })
expect(inputRow().lastElementChild).toBe(slot)
expect(slot).toContainElement(action)
expect(action.parentElement).toBe(slot)
})
it('reserves the mic-sized slot when the action is null', async () => {
await renderPromptInput({ trailingAction: null })
await screen.findByPlaceholderText('Send a message...')
const slot = screen.getByTestId('composer-trailing-slot')
expect(inputRow()).toContainElement(slot)
expect(inputRow().lastElementChild).toBe(slot)
expect(slot).toBeEmptyDOMElement()
expect(slot).toHaveClass('h-11', 'w-11', 'shrink-0', 'md:h-10', 'md:w-10')
})
it('omits the slot when no trailing action is provided', async () => {
await renderPromptInput()
await screen.findByPlaceholderText('Send a message...')
expect(screen.queryByTestId('composer-trailing-slot')).toBeNull()
})
})
describe('control sizing', () => {
it('keeps the mic at 44px before and after the prompt gains focus on mobile', async () => {
await renderPromptInput({ mobile: true })
@@ -103,7 +103,7 @@ describe.each([
expect(trigger).not.toHaveClass('bg-highlight')
expect(trigger).toHaveClass('size-11')
} else {
expect(trigger).toHaveClass('size-9')
expect(trigger).toHaveClass('size-10')
}
await openConfig(user)
@@ -1,4 +1,4 @@
import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, memo, useCallback, type KeyboardEvent } from 'react'
import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, memo, useCallback, type KeyboardEvent, type ReactNode } from 'react'
import { z } from 'zod'
import { useSendPrompt, useInterruptSession, useSendShell, useAgents, useSkills } from '@/hooks/useOpenCode'
import { useCommands } from '@/hooks/useCommands'
@@ -88,19 +88,19 @@ const KEYBAR_KEYS: Array<{ id: KeybarKey, symbol: string, label: string }> = [
const COMPOSER_MODE_STYLES = {
command: {
label: 'COMMAND',
frame: 'border-primary/70 ring-1 ring-primary/40 shadow-lg shadow-primary/20',
frame: 'ring-1 ring-primary/40 shadow-lg shadow-primary/20',
badge: 'bg-primary text-primary-foreground',
key: 'bg-primary text-primary-foreground border-primary',
},
mention: {
label: 'MENTION',
frame: 'border-success/70 ring-1 ring-success/40 shadow-lg shadow-success/20',
frame: 'ring-1 ring-success/40 shadow-lg shadow-success/20',
badge: 'bg-success text-success-foreground',
key: 'bg-success text-success-foreground border-success',
},
bash: {
label: 'BASH',
frame: 'border-warning/70 ring-1 ring-warning/40 shadow-lg shadow-warning/20',
frame: 'ring-1 ring-warning/40 shadow-lg shadow-warning/20',
badge: 'bg-warning text-warning-foreground',
key: 'bg-warning text-warning-foreground border-warning',
},
@@ -132,6 +132,7 @@ interface PromptInputProps {
commandActions: PageCommandActions
onPromptChange?: (hasContent: boolean) => void
voiceConversation?: VoiceConversationFactory
trailingAction?: ReactNode
}
export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(function PromptInput({
@@ -145,7 +146,8 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
onScrollToBottom,
commandActions,
onPromptChange,
voiceConversation
voiceConversation,
trailingAction
}, ref) {
const [restoredDraft] = useState(() => useComposerDraftStore.getState().getDraft(sessionID))
const [prompt, setPrompt] = useState(restoredDraft.prompt)
@@ -1175,7 +1177,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
}}
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'
: 'p-2 rounded-lg transition-all duration-200 active:scale-95 hover:scale-105 shadow-md border flex items-center justify-center bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border'}
: 'size-10 shrink-0 rounded-lg transition-all duration-200 active:scale-95 hover:scale-105 shadow-md border flex items-center justify-center bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border'}
>
<Mic className={isMobile ? 'w-6 h-6' : 'w-5 h-5'} />
</button>
@@ -1240,7 +1242,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
: ''
return (
<div className={`relative isolate border-t md:border border-border dark:border-border/30 rounded-t-xl md:rounded-xl p-2 pb-7 md:p-3 md:mb-3 w-full before:pointer-events-none before:absolute before:-inset-px before:-z-10 before:rounded-t-xl md:before:rounded-xl before:bg-background md:before:bg-background/95 before:backdrop-blur-md before:content-[''] ${hasPendingPermissionForSession ? 'border-highlight/50 ring-1 ring-highlight/30' : composerModeStyle?.frame ?? ''} ${isTakeoverOpen ? 'z-[60]' : ''}`}>
<div className={`relative isolate rounded-t-xl md:rounded-xl p-2 pb-7 md:p-3 md:mb-3 w-full ${hasPendingPermissionForSession ? 'ring-1 ring-highlight/30' : composerModeStyle?.frame ?? ''} ${isTakeoverOpen ? 'z-[60]' : ''}`}>
<div role="status" aria-live="polite" className="sr-only">
{sessionActivityAnnouncement}
</div>
@@ -1308,7 +1310,7 @@ return (
? "Enter bash command..."
: "Send a message..."
}
className={`flex-1 min-w-0 bg-muted/50 pl-2 md:pl-3 pr-3 py-2 text-[16px] text-foreground placeholder-muted-foreground focus:outline-none focus:bg-muted/70 resize-none min-h-[40px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed md:text-sm rounded-lg [field-sizing:content] ${
className={`flex-1 min-w-0 bg-muted/50 pl-2 md:pl-3 pr-3 py-2.5 md:py-2 text-[16px] text-foreground placeholder-muted-foreground focus:outline-none focus:bg-muted/70 resize-none min-h-11 md:min-h-[40px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed md:text-sm rounded-lg [field-sizing:content] ${
isBashMode
? 'border-warning/50 bg-warning/5 focus:bg-warning/10'
: isDragging ? 'border-info/50 border-dashed bg-info/5' : ''
@@ -1347,6 +1349,14 @@ return (
onChange={handleFileInputChange}
/>
{showVoiceMic && !hasPromptContent && !showStopButton && renderVoiceMic()}
{trailingAction !== undefined && (
<div
data-testid="composer-trailing-slot"
className="flex h-11 w-11 shrink-0 items-center justify-center md:h-10 md:w-10 @min-[86rem]/composer:absolute @min-[86rem]/composer:bottom-0 @min-[86rem]/composer:left-full @min-[86rem]/composer:ml-4 @min-[86rem]/composer:h-10 @min-[86rem]/composer:w-10"
>
{trailingAction}
</div>
)}
</div>
{imageAttachments.length > 0 && (
@@ -585,7 +585,7 @@ export const SessionConfigMenu = memo(function SessionConfigMenu({
className={cn(
getIconToggleButtonClassName(isAnySessionToggleActive),
'relative flex shrink-0 items-center justify-center overflow-hidden p-0',
isMobile ? 'size-11' : 'size-9',
isMobile ? 'size-11' : 'size-10',
gutterCardClassName,
)}
>
@@ -17,6 +17,8 @@ const buildController = (
canStopAgent: false,
hasHeldReading: false,
isEndpointing: false,
readRepliesAloud: true,
canReadRepliesAloud: true,
notice: null,
start: vi.fn(),
exit: vi.fn(),
@@ -25,6 +27,7 @@ const buildController = (
pause: vi.fn(),
resume: vi.fn(),
stopAgent: vi.fn(),
toggleReadRepliesAloud: vi.fn(),
...overrides,
})
@@ -111,6 +114,34 @@ describe('VoiceConversationBar', () => {
expect(controller.stopAgent).toHaveBeenCalledTimes(1)
})
it('toggles reading replies aloud from the bar', async () => {
const user = userEvent.setup()
const controller = buildController({ readRepliesAloud: true })
renderBar(controller)
const toggle = screen.getByRole('button', { name: 'Read replies aloud' })
expect(toggle).toHaveAttribute('aria-pressed', 'true')
await user.click(toggle)
expect(controller.toggleReadRepliesAloud).toHaveBeenCalledTimes(1)
})
it('presents the read-aloud toggle as unpressed when reading is off', () => {
renderBar(buildController({ readRepliesAloud: false }))
expect(screen.getByRole('button', { name: 'Read replies aloud' })).toHaveAttribute(
'aria-pressed',
'false',
)
})
it('hides the read-aloud toggle when text-to-speech is not configured', () => {
renderBar(buildController({ canReadRepliesAloud: false }))
expect(screen.queryByRole('button', { name: 'Read replies aloud' })).toBeNull()
})
it('shows the approval control instead of pause while the session waits for approval', async () => {
const user = userEvent.setup()
const onViewApproval = vi.fn()
@@ -1,4 +1,4 @@
import { Pause, Pencil, Play, X } from 'lucide-react'
import { Pause, Pencil, Play, Volume2, VolumeX, X } from 'lucide-react'
import type { ReactNode } from 'react'
import { VoiceConversationOrb } from '@/components/message/VoiceConversationOrb'
import { Button } from '@/components/ui/button'
@@ -7,9 +7,16 @@ import { SquareFill } from '@/components/ui/square-fill'
import type { VoiceConversationController } from '@/hooks/useVoiceConversation'
import { cn } from '@/lib/utils'
const BAR_ICON_BUTTON_SIZE_CLASS = 'flex size-11 shrink-0 items-center justify-center p-0'
const BAR_ICON_BUTTON_CLASS = cn(
getIconToggleButtonClassName(false),
'flex size-11 shrink-0 items-center justify-center p-0',
BAR_ICON_BUTTON_SIZE_CLASS,
)
const BAR_ICON_BUTTON_ACTIVE_CLASS = cn(
getIconToggleButtonClassName(true),
BAR_ICON_BUTTON_SIZE_CLASS,
)
const RESERVED_LINE_CLASS = 'h-4 w-full truncate text-center leading-4'
@@ -17,18 +24,20 @@ const RESERVED_LINE_CLASS = 'h-4 w-full truncate text-center leading-4'
interface BarIconButtonProps {
label: string
onClick: () => void
pressed?: boolean
children: ReactNode
}
function BarIconButton({ label, onClick, children }: BarIconButtonProps) {
function BarIconButton({ label, onClick, pressed, children }: BarIconButtonProps) {
return (
<button
type="button"
aria-label={label}
aria-pressed={pressed}
title={label}
onMouseDown={(event) => event.preventDefault()}
onClick={onClick}
className={BAR_ICON_BUTTON_CLASS}
className={pressed ? BAR_ICON_BUTTON_ACTIVE_CLASS : BAR_ICON_BUTTON_CLASS}
>
{children}
</button>
@@ -55,6 +64,8 @@ export function VoiceConversationBar({
canEditInTextBox,
canStopAgent,
hasHeldReading,
readRepliesAloud,
canReadRepliesAloud,
notice,
} = controller
@@ -90,6 +101,15 @@ export function VoiceConversationBar({
<X className="size-5" />
</BarIconButton>
)}
{canReadRepliesAloud ? (
<BarIconButton
label="Read replies aloud"
onClick={controller.toggleReadRepliesAloud}
pressed={readRepliesAloud}
>
{readRepliesAloud ? <Volume2 className="size-5" /> : <VolumeX className="size-5" />}
</BarIconButton>
) : null}
{canStopAgent ? (
<BarIconButton label="Stop the agent" onClick={controller.stopAgent}>
<SquareFill className="size-4" />
@@ -6,6 +6,7 @@ import type { SessionMessageAssistant } from '@opencode-manager/shared/opencode'
import type { SpeakMessageOptions, TTSContextValue } from '@/contexts/tts-context'
import type { SttEndOfSpeechReason } from '@/lib/webSpeechRecognizer'
import type { StartRecordingOptions } from '@/hooks/useSTT'
import { useVoiceConversationStore } from '@/stores/voiceConversationStore'
import { useVoiceConversation } from './useVoiceConversation'
import type { UseVoiceConversationInput, VoiceConversationCollaborators } from './useVoiceConversation'
@@ -183,6 +184,7 @@ describe('useVoiceConversation', () => {
isPaused: false,
error: null,
})
useVoiceConversationStore.setState({ readRepliesAloud: true })
sttListeners.clear()
harness.putSessionInstruction.mockResolvedValue(undefined)
harness.removeSessionInstruction.mockResolvedValue(undefined)
@@ -581,6 +583,72 @@ describe('useVoiceConversation', () => {
expect(result.current.label).toBe('Reading the reply failed')
})
it('marks replies as heard without speaking when read-back is turned off', async () => {
useVoiceConversationStore.setState({ readRepliesAloud: false })
const { result, rerender } = renderHook(
(props: UseVoiceConversationInput) => useVoiceConversation(props, collaborators),
{ initialProps: createProps() },
)
act(() => result.current.start())
await waitFor(() => expect(result.current.phase).toBe('listening'))
await endOfSpeech('pause', 'hello there')
await waitFor(() => expect(result.current.phase).toBe('working'))
rerender(createProps({ messages: [assistantMessage('msg_1', 'Done')] }))
await waitFor(() => expect(result.current.phase).toBe('listening'))
expect(harness.speakMessage).not.toHaveBeenCalled()
expect(result.current.readRepliesAloud).toBe(false)
expect(harness.startRecording).toHaveBeenCalledTimes(2)
})
it('stops reading and listens again when read-back is turned off mid-reply', async () => {
const { result, rerender } = renderHook(
(props: UseVoiceConversationInput) => useVoiceConversation(props, collaborators),
{ initialProps: createProps() },
)
act(() => result.current.start())
await waitFor(() => expect(result.current.phase).toBe('listening'))
await endOfSpeech('pause', 'hello there')
await waitFor(() => expect(result.current.phase).toBe('working'))
rerender(createProps({ messages: [assistantMessage('msg_1', 'Done')] }))
await waitFor(() => expect(result.current.phase).toBe('speaking'))
act(() => result.current.toggleReadRepliesAloud())
expect(harness.ttsStop).toHaveBeenCalledTimes(1)
await waitFor(() => expect(result.current.phase).toBe('listening'))
expect(result.current.readRepliesAloud).toBe(false)
expect(harness.startRecording).toHaveBeenCalledTimes(2)
})
it('keeps waiting for a busy agent when read-back is turned off mid-reply', async () => {
const { result, rerender } = renderHook(
(props: UseVoiceConversationInput) => useVoiceConversation(props, collaborators),
{ initialProps: createProps() },
)
act(() => result.current.start())
await waitFor(() => expect(result.current.phase).toBe('listening'))
await endOfSpeech('pause', 'hello there')
await waitFor(() => expect(result.current.phase).toBe('working'))
rerender(createProps({ status: 'busy', messages: [assistantMessage('msg_1', 'Working on it')] }))
await waitFor(() => expect(result.current.phase).toBe('speaking'))
act(() => result.current.toggleReadRepliesAloud())
expect(harness.ttsStop).toHaveBeenCalledTimes(1)
await waitFor(() => expect(result.current.phase).toBe('working'))
rerender(createProps({ status: 'idle', messages: [assistantMessage('msg_1', 'Working on it'), assistantMessage('msg_2', 'Done')] }))
await waitFor(() => expect(result.current.phase).toBe('listening'))
expect(harness.speakMessage).toHaveBeenCalledTimes(1)
})
it('marks a reply with nothing to read as heard and listens again', async () => {
const { result, rerender } = renderHook(
(props: UseVoiceConversationInput) => useVoiceConversation(props, collaborators),
+51 -15
View File
@@ -31,6 +31,7 @@ import { useSTT } from '@/hooks/useSTT'
import { useTTS } from '@/hooks/useTTS'
import { sanitizeForTTS } from '@/lib/utils'
import type { SttEndOfSpeechReason } from '@/lib/webSpeechRecognizer'
import { useVoiceConversationStore } from '@/stores/voiceConversationStore'
export interface UseVoiceConversationInput {
sessionID: string
@@ -56,6 +57,8 @@ export interface VoiceConversationController {
canStopAgent: boolean
hasHeldReading: boolean
isEndpointing: boolean
readRepliesAloud: boolean
canReadRepliesAloud: boolean
notice: string | null
start: () => void
exit: () => void
@@ -64,6 +67,7 @@ export interface VoiceConversationController {
pause: () => void
resume: () => void
stopAgent: () => void
toggleReadRepliesAloud: () => void
}
interface VoiceConversationLatest {
@@ -74,6 +78,7 @@ interface VoiceConversationLatest {
sendTurn: (text: string, options: { busy: boolean }) => Promise<void>
interrupt: () => Promise<void>
onEditInTextBox: (text: string) => void
readRepliesAloud: boolean
tts: ReturnType<typeof useTTS>
}
@@ -217,6 +222,8 @@ export function useVoiceConversation(
const listInstructionKeys = collaborators.listSessionInstructionKeys ?? DEFAULT_COLLABORATORS.listSessionInstructionKeys
const tts = ttsHook()
const stt = sttHook()
const readRepliesAloud = useVoiceConversationStore((state) => state.readRepliesAloud)
const setReadRepliesAloud = useVoiceConversationStore((state) => state.setReadRepliesAloud)
const [state, dispatch] = useReducer(
reduceVoiceConversation,
@@ -258,6 +265,7 @@ export function useVoiceConversation(
sendTurn,
interrupt,
onEditInTextBox,
readRepliesAloud,
tts,
})
@@ -289,6 +297,7 @@ export function useVoiceConversation(
sendTurn,
interrupt,
onEditInTextBox,
readRepliesAloud,
tts,
}
sttRef.current = stt
@@ -553,9 +562,10 @@ export function useVoiceConversation(
}
const spokenIds = spokenIdsRef.current
const unspoken = listUnspokenMessages(messages, state.baselineId, spokenIds)
const readable = latestRef.current.tts.isEnabled
? unspoken.find((message) => sanitizeForTTS(message.text).trim() !== '')
: undefined
const readable =
latestRef.current.tts.isEnabled && latestRef.current.readRepliesAloud
? unspoken.find((message) => sanitizeForTTS(message.text).trim() !== '')
: undefined
if (readable) {
clearWorkingTimers()
dispatch({ type: 'speak-start' })
@@ -606,6 +616,7 @@ export function useVoiceConversation(
hasPendingApproval,
clearWorkingTimers,
speakMessage,
readRepliesAloud,
])
useEffect(() => {
@@ -777,6 +788,38 @@ export function useVoiceConversation(
})
}, [setHeldPlayback])
const skipReading = useCallback(() => {
const latest = latestRef.current
for (const message of listUnspokenMessages(
latest.messages,
baselineIdRef.current,
spokenIdsRef.current,
)) {
spokenIdsRef.current.add(message.id)
}
speakTokenRef.current += 1
speakingIdRef.current = null
latest.tts.stop()
dispatch({ type: 'skip' })
}, [])
const toggleReadRepliesAloud = useCallback(() => {
const next = !latestRef.current.readRepliesAloud
latestRef.current = { ...latestRef.current, readRepliesAloud: next }
setReadRepliesAloud(next)
if (next) return
if (phaseRef.current === 'speaking') {
speakTokenRef.current += 1
speakingIdRef.current = null
latestRef.current.tts.stop()
dispatch({ type: 'speech-ended' })
return
}
if (!playbackHeldRef.current) return
setHeldPlayback(false)
latestRef.current.tts.stop()
}, [setReadRepliesAloud, setHeldPlayback])
const tapOrb = useCallback(() => {
const phase = phaseRef.current
const latest = latestRef.current
@@ -793,17 +836,7 @@ export function useVoiceConversation(
return
case 'speaking':
if (latest.status === 'idle') {
for (const message of listUnspokenMessages(
latest.messages,
baselineIdRef.current,
spokenIdsRef.current,
)) {
spokenIdsRef.current.add(message.id)
}
speakTokenRef.current += 1
speakingIdRef.current = null
latest.tts.stop()
dispatch({ type: 'skip' })
skipReading()
return
}
speakTokenRef.current += 1
@@ -820,7 +853,7 @@ export function useVoiceConversation(
default:
return
}
}, [resumeConversation])
}, [resumeConversation, skipReading])
const stopAgent = useCallback(() => {
void latestRef.current.interrupt()
@@ -926,6 +959,8 @@ export function useVoiceConversation(
canStopAgent,
hasHeldReading,
isEndpointing: stt.isEndpointing,
readRepliesAloud,
canReadRepliesAloud: tts.isEnabled,
notice,
start,
exit,
@@ -934,5 +969,6 @@ export function useVoiceConversation(
pause,
resume: resumeConversation,
stopAgent,
toggleReadRepliesAloud,
}
}
+18 -13
View File
@@ -726,6 +726,19 @@ export function SessionDetail() {
promptInputRef.current?.setPromptValue(restoredPrompt)
}, []);
const composerTrailingAction = ttsEnabled && !isMobile && !isVoiceConversationActive
? !isFormSheetOpen && !hasPromptContent && !isSessionActive && latestPlayableAssistant
? (
<FloatingTTSButton
messageId={latestPlayableAssistant.messageId}
content={latestPlayableAssistant.text}
isScrolledUp={showScrollButton}
onSpeakVisible={handleSpeakVisibleMessages}
/>
)
: null
: undefined;
@@ -895,7 +908,7 @@ export function SessionDetail() {
data-testid="prompt-overlay"
className={cn(
"@container/composer absolute left-0 right-0 flex justify-center",
isFormOpen && "top-0 flex-col items-center justify-end pointer-events-none md:pt-3",
isFormOpen ? "top-0 flex-col items-center justify-end pointer-events-none md:pt-3" : "border-t border-border/50 bg-background",
)}
style={{ bottom: inputBottomOffset }}
>
@@ -911,14 +924,6 @@ export function SessionDetail() {
>
{!isFormSheetOpen && (
<div className="absolute bottom-full right-[3%] md:right-0 mb-2 z-50 flex flex-col items-end gap-2">
{ttsEnabled && !isVoiceConversationActive && !hasPromptContent && !isSessionActive && latestPlayableAssistant && (
<FloatingTTSButton
messageId={latestPlayableAssistant.messageId}
content={latestPlayableAssistant.text}
isScrolledUp={showScrollButton}
onSpeakVisible={handleSpeakVisibleMessages}
/>
)}
{hasPromptContent && !isSessionActive && !hasComposerSuggestions && (
<button
onMouseDown={(e) => e.preventDefault()}
@@ -939,13 +944,12 @@ export function SessionDetail() {
{showScrollButton && !isFormSheetOpen && (
<button
type="button"
aria-label="Jump to latest"
title="Jump to latest"
onMouseDown={(e) => e.preventDefault()}
onClick={scrollToBottom}
className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 z-50 size-11 rounded-full bg-card text-foreground border border-border shadow-md flex items-center justify-center transition-all duration-200 active:scale-95 hover:bg-accent"
className="absolute bottom-full left-1/2 -translate-x-1/2 z-50 h-8 flex items-center gap-1.5 rounded-t-lg border border-b-0 border-border/50 bg-background px-3 text-xs font-medium text-foreground transition-colors hover:bg-accent"
>
<ArrowDown className="w-5 h-5" />
<ArrowDown className="w-3.5 h-3.5" />
Back to latest
</button>
)}
{minimizedForm && (
@@ -991,6 +995,7 @@ export function SessionDetail() {
onScrollToBottom={scrollToBottom}
commandActions={commandActions}
onPromptChange={setHasPromptContent}
trailingAction={composerTrailingAction}
/>
</SessionTranscriptContext.Provider>
</div>
@@ -5,11 +5,14 @@ import {
installElementScrollMetrics,
installMatchMedia,
installResizeObserver,
installSpeechSynthesis,
installWindowSize,
} from '@/test/browserFakes'
import { makeUserMessage } from '@/test/fixtures/api'
import { makeSettingsResponse, makeUserMessage, makeUserPreferences } from '@/test/fixtures/api'
import { promptTextarea } from '@/test/promptInput'
import { renderSessionPage } from '@/test/sessionPage'
import { DEFAULT_TTS_CONFIG } from '@opencode-manager/shared/schemas'
import type { SessionMessageAssistant } from '@opencode-manager/shared/opencode'
import type { ElementScrollMetricsFake, ResizeObserverFake } from '@/test/browserFakes'
import type { FetchRouteResult } from '@/test/fetchFake'
@@ -79,7 +82,7 @@ describe('SessionDetail scroll and composer affordances', () => {
scrollUpInTranscript()
expect(screen.getByRole('button', { name: 'Jump to latest' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Back to latest' })).toBeInTheDocument()
})
it('keeps jump to latest visible while the composer has content', async () => {
@@ -90,7 +93,7 @@ describe('SessionDetail scroll and composer affordances', () => {
scrollUpInTranscript()
expect(await screen.findByRole('button', { name: 'Clear' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Jump to latest' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Back to latest' })).toBeInTheDocument()
})
it('hides jump to latest while the transcript is at the bottom', async () => {
@@ -98,7 +101,7 @@ describe('SessionDetail scroll and composer affordances', () => {
await waitForComposer()
scrollMetrics.setScrollTop(transcriptContainer(), TRANSCRIPT_SCROLL_HEIGHT)
expect(screen.queryByRole('button', { name: 'Jump to latest' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Back to latest' })).not.toBeInTheDocument()
})
it('scrolls the transcript back to the bottom when jump to latest is clicked', async () => {
@@ -106,10 +109,10 @@ describe('SessionDetail scroll and composer affordances', () => {
await waitForComposer()
scrollUpInTranscript()
fireEvent.click(screen.getByRole('button', { name: 'Jump to latest' }))
fireEvent.click(screen.getByRole('button', { name: 'Back to latest' }))
await waitFor(() => {
expect(screen.queryByRole('button', { name: 'Jump to latest' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Back to latest' })).not.toBeInTheDocument()
})
expect(transcriptScrollTop()).toBe(TRANSCRIPT_SCROLL_HEIGHT)
})
@@ -128,6 +131,59 @@ describe('SessionDetail scroll and composer affordances', () => {
})
})
it('places the speaker button inside the composer input row', async () => {
installSpeechSynthesis()
const assistantReply: SessionMessageAssistant = {
id: 'msg_reply',
type: 'assistant',
agent: 'build',
model: { providerID: 'anthropic', id: 'claude-sonnet-4-5' },
content: [{ type: 'text', text: 'A reply' }],
time: { created: 1, completed: 2 },
}
const preferences = makeUserPreferences({ tts: { ...DEFAULT_TTS_CONFIG, enabled: true, provider: 'builtin' } })
renderSessionPage({
messages: [assistantReply],
extraRoutes: [
{ method: 'GET', path: '/api/settings', respond: () => ({ json: makeSettingsResponse({ preferences }) }) },
],
})
await waitForComposer()
const speaker = await screen.findByRole('button', { name: /play latest reply/i })
const slot = screen.getByTestId('composer-trailing-slot')
expect(slot).toContainElement(speaker)
expect(screen.getByTestId('composer-input-row')).toContainElement(slot)
})
it('leaves the speaker button out of the composer on mobile', async () => {
installWindowSize(480)
installSpeechSynthesis()
const assistantReply: SessionMessageAssistant = {
id: 'msg_reply',
type: 'assistant',
agent: 'build',
model: { providerID: 'anthropic', id: 'claude-sonnet-4-5' },
content: [{ type: 'text', text: 'A reply' }],
time: { created: 1, completed: 2 },
}
const preferences = makeUserPreferences({ tts: { ...DEFAULT_TTS_CONFIG, enabled: true, provider: 'builtin' } })
renderSessionPage({
messages: [assistantReply],
extraRoutes: [
{ method: 'GET', path: '/api/settings', respond: () => ({ json: makeSettingsResponse({ preferences }) }) },
],
})
await waitForComposer()
await screen.findByText('A reply')
expect(screen.queryByTestId('composer-trailing-slot')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /play latest reply/i })).not.toBeInTheDocument()
})
it.each(VIEWPORTS)('interrupts the active session from the composer stop button on $name', async ({ width }) => {
installWindowSize(width)
const { fetchFake } = renderSessionPage({ activeSessions: ['session-1'] })
@@ -0,0 +1,20 @@
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
interface VoiceConversationStore {
readRepliesAloud: boolean
setReadRepliesAloud: (readRepliesAloud: boolean) => void
}
export const useVoiceConversationStore = create<VoiceConversationStore>()(
persist(
(set) => ({
readRepliesAloud: true,
setReadRepliesAloud: (readRepliesAloud: boolean) => set({ readRepliesAloud }),
}),
{
name: 'opencode-voice-conversation',
partialize: (state) => ({ readRepliesAloud: state.readRepliesAloud }),
},
),
)
+2
View File
@@ -52,6 +52,7 @@ export interface PromptInputFixture {
onPromptChange?: (hasContent: boolean) => void
onSuggestionsOpenChange?: (open: boolean) => void
onVoiceConversationActiveChange?: (active: boolean) => void
trailingAction?: ReactNode
}
export function makeAgent(overrides: Partial<AgentInfo> & { id: string }): AgentInfo {
@@ -153,6 +154,7 @@ export async function renderPromptInput(fixture: PromptInputFixture = {}) {
onSuggestionsOpenChange={active.onSuggestionsOpenChange}
onVoiceConversationActiveChange={active.onVoiceConversationActiveChange}
voiceConversation={active.voiceConversation}
trailingAction={active.trailingAction}
ref={active.promptRef}
/>
</SessionTranscriptContext.Provider>
+3
View File
@@ -22,6 +22,8 @@ export function createVoiceConversationControllerMock(
canStopAgent: false,
hasHeldReading: false,
isEndpointing: false,
readRepliesAloud: true,
canReadRepliesAloud: true,
notice: null,
start: vi.fn(),
exit: vi.fn(),
@@ -30,6 +32,7 @@ export function createVoiceConversationControllerMock(
pause: vi.fn(),
resume: vi.fn(),
stopAgent: vi.fn(),
toggleReadRepliesAloud: vi.fn(),
...overrides,
}
}