feat(tts): play TTS for visible messages with a keyboard shortcut

This commit is contained in:
Chris Scott committed 2026-10-13 19:26:31 -04:00
1 parent 59ffe6c586
commit 7cb6c07494
6 files changed
+141 -3

No files matched your search

@@ -496,7 +496,7 @@ const MessageRow = memo(function MessageRow({
: 0
return (
<div className="flex flex-col group">
<div className="flex flex-col group" data-message-id={message.id}>
<div
className={`w-full rounded-lg p-1.5 bg-card/50 border border-border ${streaming ? 'animate-pulse-subtle' : ''}`}
>
@@ -7,7 +7,7 @@ import { formatEventModifiers, formatShortcutEvent, isModifierOnlyEvent, normali
import { applyTuiKeybindImport, parseTuiKeybindConfig } from '@/lib/tuiKeybindImport'
import { showToast } from '@/lib/toast'
const CONVERSATION_ACTIONS = ['submit', 'abort', 'clearPrompt', 'toggleMode', 'undo', 'redo', 'compact', 'fork', 'timeline', 'exportSession', 'selectModel', 'variantCycle', 'favoriteCycle', 'halfPageUp', 'halfPageDown']
const CONVERSATION_ACTIONS = ['submit', 'abort', 'clearPrompt', 'toggleMode', 'undo', 'redo', 'compact', 'fork', 'timeline', 'exportSession', 'selectModel', 'variantCycle', 'favoriteCycle', 'halfPageUp', 'halfPageDown', 'speakVisible']
const NAVIGATION_ACTIONS = ['settings', 'sessions', 'newSession', 'closeSession', 'toggleSidebar', 'toggleTerminal', 'toggleSourceControl']
const formatShortcutLabel = (action: string): string => {
@@ -0,0 +1,105 @@
import { describe, expect, it } from 'vitest'
import type {
SessionMessageAssistant,
SessionMessageInfo,
SessionMessageUser,
} from '@opencode-manager/shared/opencode'
import { collectVisibleAssistantTexts } from './visibleMessageTexts'
const assistantMessage = (id: string, texts: string[]): SessionMessageAssistant => ({
id,
type: 'assistant',
agent: 'test-agent',
model: { providerID: 'test-provider', id: 'test-model' },
content: texts.map((text) => ({ type: 'text', text })),
time: { created: 1, completed: 2 },
})
const userMessage = (id: string, text: string): SessionMessageUser => ({
id,
type: 'user',
text,
time: { created: 1 },
})
const rect = (top: number, bottom: number): DOMRect => ({
top,
bottom,
left: 0,
right: 100,
width: 100,
height: bottom - top,
x: 0,
y: top,
toJSON: () => ({}),
} as DOMRect)
const stubRect = (element: HTMLElement, top: number, bottom: number) => {
element.getBoundingClientRect = () => rect(top, bottom)
}
const buildContainer = (): HTMLDivElement => {
const container = document.createElement('div')
stubRect(container, 0, 100)
return container
}
const appendMessageElement = (
container: HTMLElement,
messageId: string,
top: number,
bottom: number,
): HTMLElement => {
const element = document.createElement('div')
element.dataset.messageId = messageId
stubRect(element, top, bottom)
container.appendChild(element)
return element
}
describe('collectVisibleAssistantTexts', () => {
it('returns only intersecting assistant messages in DOM order', () => {
const container = buildContainer()
appendMessageElement(container, 'a1', 10, 30)
appendMessageElement(container, 'u2', 40, 60)
appendMessageElement(container, 'a3', 70, 90)
appendMessageElement(container, 'a4', 200, 220)
appendMessageElement(container, 'a5', 5, 8)
const messages: SessionMessageInfo[] = [
assistantMessage('a1', ['one']),
userMessage('u2', 'hello'),
assistantMessage('a3', []),
assistantMessage('a4', ['four']),
assistantMessage('a5', ['five']),
]
expect(collectVisibleAssistantTexts(container, messages)).toEqual(['one', 'five'])
})
it('ignores user and system messages and assistant messages with no text parts', () => {
const container = buildContainer()
appendMessageElement(container, 'u1', 10, 30)
appendMessageElement(container, 's1', 20, 40)
appendMessageElement(container, 'a-empty', 30, 50)
appendMessageElement(container, 'a-valid', 40, 60)
const messages: SessionMessageInfo[] = [
userMessage('u1', 'hello'),
{ id: 's1', type: 'system', text: 'note', time: { created: 1 } },
assistantMessage('a-empty', []),
assistantMessage('a-valid', ['kept']),
]
expect(collectVisibleAssistantTexts(container, messages)).toEqual(['kept'])
})
it('returns an empty list when nothing intersects', () => {
const container = buildContainer()
appendMessageElement(container, 'a1', 200, 220)
const messages: SessionMessageInfo[] = [assistantMessage('a1', ['hidden'])]
expect(collectVisibleAssistantTexts(container, messages)).toEqual([])
})
})
+17
View File
@@ -0,0 +1,17 @@
import { assistantText, type SessionMessageInfo } from '@opencode-manager/shared/opencode'
export function collectVisibleAssistantTexts(container: HTMLElement, messages: SessionMessageInfo[]): string[] {
const containerRect = container.getBoundingClientRect()
const textById = new Map(
messages
.filter((message) => message.type === 'assistant')
.map((message) => [message.id, assistantText(message.content).trim()]),
)
return Array.from(container.querySelectorAll<HTMLElement>('[data-message-id]'))
.filter((element) => {
const rect = element.getBoundingClientRect()
return rect.bottom > containerRect.top && rect.top < containerRect.bottom
})
.map((element) => textById.get(element.dataset.messageId ?? '') ?? '')
.filter((text) => text.length > 0)
}
+16 -1
View File
@@ -35,6 +35,7 @@ import { MessageSkeleton } from "@/components/message/MessageSkeleton";
import { exportSession, downloadMarkdown } from "@/lib/exportSession";
import { copyTextToClipboard } from "@/lib/clipboard";
import { getMessagesContentVersion } from "./sessionContentVersion";
import { collectVisibleAssistantTexts } from '@/lib/visibleMessageTexts';
import { showToast } from "@/lib/toast";
import { getWorkspaceFilePath } from "@/lib/markdownLinks";
import { getRepoDisplayName } from "@/lib/utils";
@@ -274,7 +275,7 @@ export function SessionDetail() {
const { modelRef } = useModelSelection(sessionDirectory, modelSelectionSession);
const setSessionStatus = useSessionStatus((state) => state.setStatus);
const isEditingMessage = useUIState((state) => state.isEditingMessage);
const { isEnabled: ttsEnabled } = useTTS();
const { isEnabled: ttsEnabled, speak, stop, isPlaying: isTTSPlaying, isLoading: isTTSLoading } = useTTS();
const { syncForSession: syncPermissionsForSession } = usePermissions();
const { getForSession: getFormForSession, reply: replyToForm, cancel: cancelForm, syncForSession: syncFormsForSession } = useForms();
const currentForm = sessionId ? getFormForSession(sessionId) : null;
@@ -614,6 +615,19 @@ export function SessionDetail() {
scrollByUser((direction * container.clientHeight) / 2);
}, [scrollByUser]);
const handleSpeakVisibleMessages = useCallback(() => {
if (!ttsEnabled) return;
if (isTTSPlaying || isTTSLoading) {
stop();
return;
}
const container = messageContainerRef.current;
if (!container) return;
const texts = collectVisibleAssistantTexts(container, messages);
if (texts.length === 0) return;
speak(texts.join('\n\n'));
}, [ttsEnabled, isTTSPlaying, isTTSLoading, stop, speak, messages]);
useShortcutActions({
selectModel: handleOpenModelDialog,
sessions: handleShowSessionsDialog,
@@ -633,6 +647,7 @@ export function SessionDetail() {
clearPrompt: handleClearPrompt,
halfPageUp: () => scrollMessagesByHalfPage(-1),
halfPageDown: () => scrollMessagesByHalfPage(1),
speakVisible: handleSpeakVisibleMessages,
});
const handleUndoMessage = useCallback((restoredPrompt: string) => {
+1
View File
@@ -88,6 +88,7 @@ export const DEFAULT_KEYBOARD_SHORTCUTS = {
exportSession: 'X',
halfPageUp: 'Ctrl+U',
halfPageDown: 'Ctrl+D',
speakVisible: 'S',
} satisfies Record<string, string>;
export type KeyboardShortcutAction = keyof typeof DEFAULT_KEYBOARD_SHORTCUTS;