refactor(tts): read visible replies when floating button is tapped while scrolled up

This commit is contained in:
Chris Scott committed 2026-10-13 21:31:03 -04:00
1 parent eafa8941cb
commit 8a893d0d2a
6 files changed
+459 -169

No files matched your search

+14 -150
View File
@@ -1,10 +1,8 @@
import { execFileSync } from 'node:child_process'
import fs from 'node:fs'
import http from 'node:http'
import path from 'node:path'
import { request as playwrightRequest, type APIRequestContext, type Locator } from '@playwright/test'
import { type Locator } from '@playwright/test'
import { test, expect } from './fixtures'
import { BASE_URL, E2E_TMP, STORAGE_STATE } from './env'
import { createMockRepo, createSession, startMockProvider, type MockProvider, type MockRepo } from './mockProvider'
const PNG_BASE64 =
'iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAFElEQVQI12P8z8Dwn4GBgYGJAQoAHxcCAmep4oIAAAAASUVORK5CYII='
@@ -14,17 +12,8 @@ const PNG_BUFFER = Buffer.from(PNG_BASE64, 'base64')
const WEBP_BUFFER = Buffer.from(WEBP_BASE64, 'base64')
const MOCK_PROVIDER_PORT = 5565
const MOCK_MODEL_ID = 'mock-model'
let mockReply = ''
let mockServer: http.Server | undefined
interface MockRepo {
id: number
fullPath: string
sessionId: string
}
let mockProvider: MockProvider
let mockRepo: MockRepo
function rawFileUrl(filePath: string): string {
@@ -39,144 +28,19 @@ async function expectImageLoaded(image: Locator): Promise<void> {
.toBeGreaterThan(0)
}
function handleMockRequest(request: http.IncomingMessage, response: http.ServerResponse): void {
const chunks: Buffer[] = []
request.on('data', (chunk: Buffer) => chunks.push(chunk))
request.on('end', () => {
const url = request.url ?? ''
if (request.method === 'GET' && url.startsWith('/v1/models')) {
response.writeHead(200, { 'Content-Type': 'application/json' })
response.end(
JSON.stringify({
object: 'list',
data: [{ id: MOCK_MODEL_ID, object: 'model', created: 0, owned_by: 'mock' }],
}),
)
return
}
if (request.method === 'POST' && url.startsWith('/v1/chat/completions')) {
let body: { stream?: boolean } = {}
try {
body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')
} catch {
body = {}
}
const id = 'chatcmpl-mock'
const created = Math.floor(Date.now() / 1000)
const usage = { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }
if (body.stream) {
response.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
})
const base = { id, object: 'chat.completion.chunk', created, model: MOCK_MODEL_ID }
response.write(
`data: ${JSON.stringify({ ...base, choices: [{ index: 0, delta: { role: 'assistant', content: '' }, finish_reason: null }] })}\n\n`,
)
response.write(
`data: ${JSON.stringify({ ...base, choices: [{ index: 0, delta: { content: mockReply }, finish_reason: null }] })}\n\n`,
)
response.write(
`data: ${JSON.stringify({ ...base, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage })}\n\n`,
)
response.write('data: [DONE]\n\n')
response.end()
return
}
response.writeHead(200, { 'Content-Type': 'application/json' })
response.end(
JSON.stringify({
id,
object: 'chat.completion',
created,
model: MOCK_MODEL_ID,
choices: [{ index: 0, message: { role: 'assistant', content: mockReply }, finish_reason: 'stop' }],
usage,
}),
)
return
}
response.writeHead(404, { 'Content-Type': 'application/json' })
response.end(JSON.stringify({ error: { message: `unhandled ${request.method} ${url}` } }))
})
}
function git(directory: string, ...args: string[]): void {
execFileSync('git', args, { cwd: directory, stdio: 'pipe' })
}
async function createSession(api: APIRequestContext, directory: string): Promise<string> {
const response = await api.post('/api/opencode/api/session', { data: { location: { directory } } })
if (!response.ok()) {
throw new Error(`create session failed: ${response.status()} ${await response.text()}`)
}
const body = (await response.json()) as { data: { id: string } }
return body.data.id
}
test.beforeAll(async () => {
const server = http.createServer(handleMockRequest)
await new Promise<void>((resolve, reject) => {
server.once('error', reject)
server.listen(MOCK_PROVIDER_PORT, '127.0.0.1', () => resolve())
mockProvider = await startMockProvider(MOCK_PROVIDER_PORT)
mockRepo = await createMockRepo('e2e-inline-mock-repo', MOCK_PROVIDER_PORT, {
beforeCommit: (directory) => {
fs.mkdirSync(path.join(directory, 'docs', 'img'), { recursive: true })
fs.writeFileSync(path.join(directory, 'docs', 'img', 'logo.png'), PNG_BUFFER)
fs.writeFileSync(path.join(directory, 'docs', 'notes.txt'), 'attachment notes\n')
},
})
mockServer = server
const directory = path.join(E2E_TMP, 'workspace', 'repos', 'e2e-inline-mock-repo')
fs.rmSync(directory, { recursive: true, force: true })
fs.mkdirSync(path.join(directory, 'docs', 'img'), { recursive: true })
fs.writeFileSync(path.join(directory, 'docs', 'img', 'logo.png'), PNG_BUFFER)
fs.writeFileSync(path.join(directory, 'docs', 'notes.txt'), 'attachment notes\n')
fs.writeFileSync(
path.join(directory, 'opencode.json'),
JSON.stringify(
{
$schema: 'https://opencode.ai/config.json',
provider: {
mock: {
npm: '@ai-sdk/openai-compatible',
name: 'Mock',
options: { baseURL: `http://127.0.0.1:${MOCK_PROVIDER_PORT}/v1`, apiKey: 'mock' },
models: { [MOCK_MODEL_ID]: { name: 'Mock Model' } },
},
},
model: `mock/${MOCK_MODEL_ID}`,
small_model: `mock/${MOCK_MODEL_ID}`,
},
null,
2,
),
)
fs.writeFileSync(path.join(directory, 'README.md'), '# mock repository\n')
git(directory, '-c', 'init.defaultBranch=main', 'init', '-q')
git(directory, '-c', 'user.name=e2e', '-c', 'user.email=e2e@example.com', 'add', '-A')
git(directory, '-c', 'user.name=e2e', '-c', 'user.email=e2e@example.com', 'commit', '-q', '-m', 'initial commit')
const api = await playwrightRequest.newContext({ baseURL: BASE_URL, storageState: STORAGE_STATE })
try {
const repoResponse = await api.post('/api/repos', { data: { localPath: directory } })
if (!repoResponse.ok()) {
throw new Error(`register mock repo failed: ${repoResponse.status()} ${await repoResponse.text()}`)
}
const repo = (await repoResponse.json()) as { id: number; fullPath: string }
const sessionId = await createSession(api, repo.fullPath)
mockRepo = { id: repo.id, fullPath: repo.fullPath, sessionId }
} finally {
await api.dispose()
}
})
test.afterAll(async () => {
const server = mockServer
if (!server) return
await new Promise<void>((resolve) => server.close(() => resolve()))
mockServer = undefined
await mockProvider.close()
})
test.describe('inline markdown images', () => {
@@ -221,7 +85,7 @@ test.describe('inline markdown images', () => {
})
test('assistant markdown images resolve relative, absolute and inline data sources', async ({ page }) => {
mockReply = [
mockProvider.setReply([
'Here are the images:',
'',
'![rel](docs/img/logo.png)',
@@ -231,7 +95,7 @@ test.describe('inline markdown images', () => {
`![dataimg](data:image/png;base64,${PNG_BASE64})`,
'',
'![bad](data:text/html,hello)',
].join('\n')
].join('\n'))
await page.goto(`/repos/${mockRepo.id}/sessions/${mockRepo.sessionId}`)
const composer = page.getByPlaceholder('Send a message...')
@@ -257,7 +121,7 @@ test.describe('inline markdown images', () => {
})
test('user attachments render images as thumbnails and other files as chips', async ({ page, request }) => {
mockReply = 'Received your files.'
mockProvider.setReply('Received your files.')
const sessionId = await createSession(request, mockRepo.fullPath)
await page.goto(`/repos/${mockRepo.id}/sessions/${sessionId}`)
+178
View File
@@ -0,0 +1,178 @@
import { execFileSync } from 'node:child_process'
import fs from 'node:fs'
import http from 'node:http'
import path from 'node:path'
import { request as playwrightRequest, type APIRequestContext } from '@playwright/test'
import { BASE_URL, E2E_TMP, STORAGE_STATE } from './env'
const MOCK_MODEL_ID = 'mock-model'
export interface MockProvider {
setReply(text: string): void
close(): Promise<void>
}
export interface MockRepo {
id: number
fullPath: string
sessionId: string
}
export interface CreateMockRepoOptions {
beforeCommit?: (directory: string) => void
}
function handleMockRequest(
request: http.IncomingMessage,
response: http.ServerResponse,
getReply: () => string,
): void {
const chunks: Buffer[] = []
request.on('data', (chunk: Buffer) => chunks.push(chunk))
request.on('end', () => {
const url = request.url ?? ''
if (request.method === 'GET' && url.startsWith('/v1/models')) {
response.writeHead(200, { 'Content-Type': 'application/json' })
response.end(
JSON.stringify({
object: 'list',
data: [{ id: MOCK_MODEL_ID, object: 'model', created: 0, owned_by: 'mock' }],
}),
)
return
}
if (request.method === 'POST' && url.startsWith('/v1/chat/completions')) {
let body: { stream?: boolean } = {}
try {
body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')
} catch {
body = {}
}
const mockReply = getReply()
const id = 'chatcmpl-mock'
const created = Math.floor(Date.now() / 1000)
const usage = { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }
if (body.stream) {
response.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
})
const base = { id, object: 'chat.completion.chunk', created, model: MOCK_MODEL_ID }
response.write(
`data: ${JSON.stringify({ ...base, choices: [{ index: 0, delta: { role: 'assistant', content: '' }, finish_reason: null }] })}\n\n`,
)
response.write(
`data: ${JSON.stringify({ ...base, choices: [{ index: 0, delta: { content: mockReply }, finish_reason: null }] })}\n\n`,
)
response.write(
`data: ${JSON.stringify({ ...base, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage })}\n\n`,
)
response.write('data: [DONE]\n\n')
response.end()
return
}
response.writeHead(200, { 'Content-Type': 'application/json' })
response.end(
JSON.stringify({
id,
object: 'chat.completion',
created,
model: MOCK_MODEL_ID,
choices: [{ index: 0, message: { role: 'assistant', content: mockReply }, finish_reason: 'stop' }],
usage,
}),
)
return
}
response.writeHead(404, { 'Content-Type': 'application/json' })
response.end(JSON.stringify({ error: { message: `unhandled ${request.method} ${url}` } }))
})
}
export async function startMockProvider(port: number): Promise<MockProvider> {
let mockReply = ''
const server = http.createServer((request, response) => {
handleMockRequest(request, response, () => mockReply)
})
await new Promise<void>((resolve, reject) => {
server.once('error', reject)
server.listen(port, '127.0.0.1', () => resolve())
})
return {
setReply: (text) => {
mockReply = text
},
close: () =>
new Promise<void>((resolve) => {
server.close(() => resolve())
server.closeAllConnections()
}),
}
}
function git(directory: string, ...args: string[]): void {
execFileSync('git', args, { cwd: directory, stdio: 'pipe' })
}
export async function createSession(api: APIRequestContext, directory: string): Promise<string> {
const response = await api.post('/api/opencode/api/session', { data: { location: { directory } } })
if (!response.ok()) {
throw new Error(`create session failed: ${response.status()} ${await response.text()}`)
}
const body = (await response.json()) as { data: { id: string } }
return body.data.id
}
export async function createMockRepo(
name: string,
port: number,
options: CreateMockRepoOptions = {},
): Promise<MockRepo> {
const directory = path.join(E2E_TMP, 'workspace', 'repos', name)
fs.rmSync(directory, { recursive: true, force: true })
fs.mkdirSync(directory, { recursive: true })
fs.writeFileSync(
path.join(directory, 'opencode.json'),
JSON.stringify(
{
$schema: 'https://opencode.ai/config.json',
provider: {
mock: {
npm: '@ai-sdk/openai-compatible',
name: 'Mock',
options: { baseURL: `http://127.0.0.1:${port}/v1`, apiKey: 'mock' },
models: { [MOCK_MODEL_ID]: { name: 'Mock Model' } },
},
},
model: `mock/${MOCK_MODEL_ID}`,
small_model: `mock/${MOCK_MODEL_ID}`,
},
null,
2,
),
)
fs.writeFileSync(path.join(directory, 'README.md'), '# mock repository\n')
options.beforeCommit?.(directory)
git(directory, '-c', 'init.defaultBranch=main', 'init', '-q')
git(directory, '-c', 'user.name=e2e', '-c', 'user.email=e2e@example.com', 'add', '-A')
git(directory, '-c', 'user.name=e2e', '-c', 'user.email=e2e@example.com', 'commit', '-q', '-m', 'initial commit')
const api = await playwrightRequest.newContext({ baseURL: BASE_URL, storageState: STORAGE_STATE })
try {
const repoResponse = await api.post('/api/repos', { data: { localPath: directory } })
if (!repoResponse.ok()) {
throw new Error(`register mock repo failed: ${repoResponse.status()} ${await repoResponse.text()}`)
}
const repo = (await repoResponse.json()) as { id: number; fullPath: string }
const sessionId = await createSession(api, repo.fullPath)
return { id: repo.id, fullPath: repo.fullPath, sessionId }
} finally {
await api.dispose()
}
}
+171
View File
@@ -0,0 +1,171 @@
import { request as playwrightRequest, type APIRequestContext, type Page } from '@playwright/test'
import { test, expect } from './fixtures'
import { createMockRepo, startMockProvider, type MockProvider, type MockRepo } from './mockProvider'
import { BASE_URL, STORAGE_STATE } from './env'
const MOCK_PROVIDER_PORT = 5566
const MARKERS = ['ALPHAMARKER', 'BRAVOMARKER', 'CHARLIEMARKER'] as const
const ENABLED_TTS = {
enabled: true,
provider: 'external' as const,
autoPlay: false,
endpoint: 'https://api.openai.com',
apiKey: 'e2e-test-key',
voice: 'alloy',
model: 'tts-1',
speed: 1,
}
const DEFAULT_TTS = {
enabled: false,
provider: 'external' as const,
autoPlay: false,
endpoint: 'https://api.openai.com',
apiKey: '',
voice: 'alloy',
model: 'tts-1',
speed: 1,
}
function buildSilentWav(durationSeconds: number): Buffer {
const sampleRate = 8000
const channels = 1
const bitsPerSample = 16
const bytesPerSample = bitsPerSample / 8
const dataSize = sampleRate * channels * bytesPerSample * durationSeconds
const buffer = Buffer.alloc(44 + dataSize)
buffer.write('RIFF', 0, 'ascii')
buffer.writeUInt32LE(36 + dataSize, 4)
buffer.write('WAVE', 8, 'ascii')
buffer.write('fmt ', 12, 'ascii')
buffer.writeUInt32LE(16, 16)
buffer.writeUInt16LE(1, 20)
buffer.writeUInt16LE(channels, 22)
buffer.writeUInt32LE(sampleRate, 24)
buffer.writeUInt32LE(sampleRate * channels * bytesPerSample, 28)
buffer.writeUInt16LE(channels * bytesPerSample, 32)
buffer.writeUInt16LE(bitsPerSample, 34)
buffer.write('data', 36, 'ascii')
buffer.writeUInt32LE(dataSize, 40)
return buffer
}
const SILENT_WAV = buildSilentWav(3)
function buildReply(marker: string): string {
return Array.from(
{ length: 30 },
(_, index) =>
`${marker} paragraph ${index + 1}: this deliberately long filler sentence wraps across several lines on a narrow mobile viewport so the reply spans more than one screen.`,
).join('\n\n')
}
let api: APIRequestContext
let mockProvider: MockProvider
let mockRepo: MockRepo
async function seedReplies(sessionId: string): Promise<void> {
for (const marker of MARKERS) {
mockProvider.setReply(buildReply(marker))
const response = await api.post(`/api/opencode/api/session/${sessionId}/prompt`, {
data: { text: 'Reply with the next prepared paragraph set.' },
})
if (!response.ok()) {
throw new Error(`seed prompt failed: ${response.status()} ${await response.text()}`)
}
await expect
.poll(
async () => {
const messagesResponse = await api.get(`/api/opencode/api/session/${sessionId}/message?order=desc`)
if (!messagesResponse.ok()) return false
const body = (await messagesResponse.json()) as {
data: Array<{ type?: string; time?: { completed?: number } }>
}
return body.data.some(
(message) =>
message.type === 'assistant' &&
message.time?.completed !== undefined &&
JSON.stringify(message).includes(marker),
)
},
{ timeout: 60_000 },
)
.toBe(true)
}
}
test.use({ viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true })
test.beforeAll(async () => {
mockProvider = await startMockProvider(MOCK_PROVIDER_PORT)
mockRepo = await createMockRepo('e2e-tts-mock-repo', MOCK_PROVIDER_PORT)
api = await playwrightRequest.newContext({ baseURL: BASE_URL, storageState: STORAGE_STATE })
const settingsResponse = await api.patch('/api/settings', { data: { preferences: { tts: ENABLED_TTS } } })
if (!settingsResponse.ok()) {
throw new Error(`enable tts failed: ${settingsResponse.status()} ${await settingsResponse.text()}`)
}
await seedReplies(mockRepo.sessionId)
})
test.afterAll(async () => {
if (api) {
await api.patch('/api/settings', { data: { preferences: { tts: DEFAULT_TTS } } })
await api.dispose()
}
if (mockProvider) {
await mockProvider.close()
}
})
async function recordSynthesis(page: Page, synthTexts: string[]): Promise<void> {
await page.route('**/api/tts/synthesize', async (route) => {
const body = route.request().postDataJSON() as { text: string }
synthTexts.push(body.text)
await route.fulfill({ status: 200, contentType: 'audio/wav', body: SILENT_WAV })
})
}
test('plays the latest reply at the bottom and stops on the next tap', async ({ page }) => {
const synthTexts: string[] = []
await recordSynthesis(page, synthTexts)
await page.goto(`/repos/${mockRepo.id}/sessions/${mockRepo.sessionId}`)
const playButton = page.getByRole('button', { name: /play latest reply\. auto-play disabled/i })
await expect(playButton).toBeVisible()
await playButton.tap()
await expect.poll(() => synthTexts.join('\n')).toContain('CHARLIEMARKER')
expect(synthTexts.join('\n')).not.toContain('ALPHAMARKER')
expect(synthTexts.join('\n')).not.toContain('BRAVOMARKER')
await expect(page.getByRole('button', { name: /stop playback\. auto-play disabled/i })).toBeVisible()
await page.getByRole('button', { name: /stop playback\. auto-play disabled/i }).tap()
await expect(page.getByRole('button', { name: /play latest reply\. auto-play disabled/i })).toBeVisible()
})
test('reads the visible replies when scrolled up and stops on the next tap', async ({ page }) => {
const synthTexts: string[] = []
await recordSynthesis(page, synthTexts)
await page.goto(`/repos/${mockRepo.id}/sessions/${mockRepo.sessionId}`)
await expect(page.getByRole('button', { name: /play latest reply\. auto-play disabled/i })).toBeVisible()
const container = page.getByTestId('session-message-scroll')
await container.evaluate((element) => {
element.scrollTop = 0
element.dispatchEvent(new WheelEvent('wheel', { deltaY: -120, bubbles: true }))
})
const readButton = page.getByRole('button', { name: /read visible replies\. auto-play disabled/i })
await expect(readButton).toBeVisible()
await readButton.tap()
await expect.poll(() => synthTexts.join('\n')).toContain('ALPHAMARKER')
expect(synthTexts.join('\n')).not.toContain('CHARLIEMARKER')
await expect(page.getByRole('button', { name: /stop playback\. auto-play disabled/i })).toBeVisible()
await page.getByRole('button', { name: /stop playback\. auto-play disabled/i }).tap()
await expect(page.getByRole('button', { name: /read visible replies\. auto-play disabled/i })).toBeVisible()
})
@@ -35,12 +35,14 @@ interface MockTTSReturn {
describe('FloatingTTSButton', () => {
const mockSpeakMessage = vi.fn()
const mockStop = vi.fn()
const mockSpeakVisible = vi.fn()
const mockUpdateSettings = vi.fn()
beforeEach(() => {
vi.clearAllMocks()
mockSpeakMessage.mockClear()
mockStop.mockClear()
mockSpeakVisible.mockClear()
mockUpdateSettings.mockClear()
mocks.showToastInfo.mockClear()
})
@@ -84,19 +86,19 @@ describe('FloatingTTSButton', () => {
it('renders pill when content is empty but autoplay is enabled', () => {
setup({ autoPlay: true })
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content="" />)
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content="" isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
expect(screen.getByRole('button', { name: /hold to toggle auto-play/i })).toBeInTheDocument()
})
it('renders pill when content is whitespace but autoplay is enabled', () => {
setup({ autoPlay: true })
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content=" " />)
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content=" " isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
expect(screen.getByRole('button', { name: /hold to toggle auto-play/i })).toBeInTheDocument()
})
it('calls speakMessage on tap when idle', () => {
setup()
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
const button = screen.getByRole('button', { name: /play latest reply/i })
fireEvent.pointerDown(button)
@@ -110,7 +112,7 @@ describe('FloatingTTSButton', () => {
it('calls stop on tap when this message is active', () => {
setup({ activeMessageId: TEST_MESSAGE_ID, isPlaying: true })
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
const button = screen.getByRole('button', { name: /stop playback/i })
fireEvent.pointerDown(button)
@@ -124,7 +126,7 @@ describe('FloatingTTSButton', () => {
it('calls stop when any playback is active, even for a different messageId (stream conflict fix)', () => {
setup({ activeMessageId: 'other-message-id', isPlaying: true })
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
const button = screen.getByRole('button', { name: /stop playback/i })
fireEvent.pointerDown(button)
@@ -139,7 +141,7 @@ describe('FloatingTTSButton', () => {
it('toggles autoplay on long press', async () => {
vi.useFakeTimers()
setup({ autoPlay: false })
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
const button = screen.getByRole('button', { name: /play latest reply/i })
await act(async () => {
@@ -172,7 +174,7 @@ describe('FloatingTTSButton', () => {
it('shows a toast when long press disables autoplay', async () => {
vi.useFakeTimers()
setup({ autoPlay: true })
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
const button = screen.getByRole('button', { name: /auto-play enabled/i })
await act(async () => {
@@ -195,7 +197,7 @@ describe('FloatingTTSButton', () => {
it('does not call speakMessage after long press (race guard)', async () => {
vi.useFakeTimers()
setup()
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
const button = screen.getByRole('button', { name: /play latest reply/i })
await act(async () => {
@@ -212,7 +214,7 @@ describe('FloatingTTSButton', () => {
it('does not call speakMessage if pointer leaves before release after long press fires', async () => {
vi.useFakeTimers()
setup()
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
const button = screen.getByRole('button', { name: /play latest reply/i })
await act(async () => {
@@ -227,7 +229,7 @@ describe('FloatingTTSButton', () => {
it('exposes the gesture hint in the aria-label for accessibility', () => {
setup()
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
const button = screen.getByRole('button', { name: /hold to toggle auto-play/i })
expect(button).toBeInTheDocument()
@@ -235,7 +237,7 @@ describe('FloatingTTSButton', () => {
it('shows stop icon when this message is playing', () => {
setup({ autoPlay: true, activeMessageId: TEST_MESSAGE_ID, isPlaying: true })
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
const button = screen.getByRole('button', { name: /stop playback/i })
@@ -249,14 +251,14 @@ describe('FloatingTTSButton', () => {
it('shows the same stop icon while this message is loading', () => {
setup({ activeMessageId: TEST_MESSAGE_ID, isLoading: true })
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
expect(screen.getByRole('button', { name: /stop playback/i })).toHaveClass('bg-destructive')
})
it('shows autoplay state with button color when autoPlay is enabled', () => {
setup({ autoPlay: true })
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
const button = screen.getByRole('button', { name: /auto-play enabled/i })
@@ -269,7 +271,7 @@ describe('FloatingTTSButton', () => {
it('uses the default play color when autoPlay is disabled', () => {
setup({ autoPlay: false })
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} />)
render(<FloatingTTSButton messageId={TEST_MESSAGE_ID} content={TEST_CONTENT} isScrolledUp={false} onSpeakVisible={mockSpeakVisible} />)
const button = screen.getByRole('button', { name: /play latest reply/i })
@@ -277,4 +279,68 @@ describe('FloatingTTSButton', () => {
expect(button).not.toHaveClass('bg-primary')
expect(screen.queryByText('Play')).not.toBeInTheDocument()
})
it('reads visible replies on tap when scrolled up and idle', () => {
setup()
render(
<FloatingTTSButton
messageId={TEST_MESSAGE_ID}
content={TEST_CONTENT}
isScrolledUp
onSpeakVisible={mockSpeakVisible}
/>
)
const button = screen.getByRole('button', { name: /read visible replies/i })
fireEvent.pointerDown(button)
act(() => {
fireEvent.pointerUp(button)
})
expect(mockSpeakVisible).toHaveBeenCalledTimes(1)
expect(mockSpeakMessage).not.toHaveBeenCalled()
})
it('stops playback on tap when scrolled up and playing', () => {
setup({ activeMessageId: TEST_MESSAGE_ID, isPlaying: true })
render(
<FloatingTTSButton
messageId={TEST_MESSAGE_ID}
content={TEST_CONTENT}
isScrolledUp
onSpeakVisible={mockSpeakVisible}
/>
)
const button = screen.getByRole('button', { name: /stop playback/i })
fireEvent.pointerDown(button)
act(() => {
fireEvent.pointerUp(button)
})
expect(mockStop).toHaveBeenCalledTimes(1)
expect(mockSpeakVisible).not.toHaveBeenCalled()
})
it('speaks the latest reply on tap when not scrolled up and idle', () => {
setup()
render(
<FloatingTTSButton
messageId={TEST_MESSAGE_ID}
content={TEST_CONTENT}
isScrolledUp={false}
onSpeakVisible={mockSpeakVisible}
/>
)
const button = screen.getByRole('button', { name: /play latest reply/i })
fireEvent.pointerDown(button)
act(() => {
fireEvent.pointerUp(button)
})
expect(mockSpeakMessage).toHaveBeenCalledTimes(1)
expect(mockSpeakMessage).toHaveBeenCalledWith(TEST_MESSAGE_ID, TEST_CONTENT)
expect(mockSpeakVisible).not.toHaveBeenCalled()
})
})
@@ -8,11 +8,13 @@ import { DEFAULT_TTS_CONFIG } from '@opencode-manager/shared'
interface FloatingTTSButtonProps {
messageId: string
content: string
isScrolledUp: boolean
onSpeakVisible: () => void
}
const LONG_PRESS_DURATION = 500
export function FloatingTTSButton({ messageId, content }: FloatingTTSButtonProps) {
export function FloatingTTSButton({ messageId, content, isScrolledUp, onSpeakVisible }: FloatingTTSButtonProps) {
const { speakMessage, stop, isPlaying, isLoading } = useTTS()
const { preferences, updateSettings } = useSettings()
@@ -63,10 +65,15 @@ export function FloatingTTSButton({ messageId, content }: FloatingTTSButtonProps
return
}
if (isScrolledUp) {
onSpeakVisible()
return
}
if (hasContent) {
speakMessage(messageId, content)
}
}, [clearLongPressTimer, isAnyPlaybackActive, stop, speakMessage, messageId, content, hasContent])
}, [clearLongPressTimer, isAnyPlaybackActive, stop, isScrolledUp, onSpeakVisible, speakMessage, messageId, content, hasContent])
const handlePointerLeave = useCallback(() => {
clearLongPressTimer()
@@ -77,9 +84,11 @@ export function FloatingTTSButton({ messageId, content }: FloatingTTSButtonProps
const showStop = isAnyPlaybackActive
const pillTitle = showStop
? 'Stop playback'
: hasContent
? 'Play latest reply'
: 'TTS controls'
: isScrolledUp
? 'Read visible replies'
: hasContent
? 'Play latest reply'
: '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'
+2
View File
@@ -776,6 +776,8 @@ export function SessionDetail() {
<FloatingTTSButton
messageId={latestPlayableAssistant.messageId}
content={latestPlayableAssistant.text}
isScrolledUp={showScrollButton}
onSpeakVisible={handleSpeakVisibleMessages}
/>
)}
{hasPromptContent && !isSessionActive && (