Merge remote-tracking branch 'origin/main' into feat/session-picker-projects-tab

# Conflicts:
#	frontend/src/components/settings/KeyboardShortcuts.tsx
This commit is contained in:
Chris Scott committed 2026-10-15 14:20:32 -04:00
commit 87f28fbc6d
27 files changed
+2242 -302

No files matched your search

@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest'
import {
getPermissionLabel,
getPermissionDetail,
getPermissionAlwaysScope,
getFormText,
getGoalOutcomeTitle,
getGoalStopReasonLabel,
@@ -94,6 +95,42 @@ describe('getPermissionDetail', () => {
it('returns empty primary when no detail is available', () => {
expect(getPermissionDetail({ action: 'shell' }).primary).toBe('')
})
it('labels shell resources as commands', () => {
expect(getPermissionDetail({ action: 'shell', resources: ['ls'] }).label).toBe('Command')
expect(getPermissionDetail({ action: 'shell', resources: ['ls', 'pwd'] }).label).toBe('Commands')
})
it('labels search patterns', () => {
expect(getPermissionDetail({ action: 'grep', resources: ['TODO'] }).label).toBe('Pattern')
})
it('labels paths for read actions', () => {
expect(getPermissionDetail({ action: 'read', resources: ['/a', '/b'] }).label).toBe('Paths')
})
it('labels edit and webfetch details', () => {
expect(getPermissionDetail({ action: 'edit', metadata: { filepath: 'a.ts' } }).label).toBe('File')
expect(getPermissionDetail({ action: 'webfetch', metadata: { url: 'https://example.com' } }).label).toBe('URL')
})
it('falls back to a generic resource label for unknown actions', () => {
expect(getPermissionDetail({ action: 'frobnicate', resources: ['a'] }).label).toBe('Resource')
})
})
describe('getPermissionAlwaysScope', () => {
it('returns null when no save patterns are present', () => {
expect(getPermissionAlwaysScope({ action: 'shell' })).toBeNull()
expect(getPermissionAlwaysScope({ action: 'shell', save: [] })).toBeNull()
})
it('describes a wildcard scope', () => {
expect(getPermissionAlwaysScope({ action: 'shell', save: ['*'] })).toEqual({
summary: 'This will always allow shell for this project.',
patterns: [],
})
})
it('lists the saved patterns', () => {
expect(getPermissionAlwaysScope({ action: 'shell', save: ['printf *', 'echo *'] })).toEqual({
summary: 'This will always allow the following patterns for this project.',
patterns: ['printf *', 'echo *'],
})
})
})
describe('getFormText', () => {
+113 -1
View File
@@ -1,5 +1,9 @@
import { execFileSync } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
import type { APIRequestContext, Page } from '@playwright/test'
import { test, expect } from './fixtures'
import { E2E_TMP } from './env'
const SHELL_COMMAND = 'sleep 300'
@@ -19,7 +23,7 @@ async function requireOk(response: Awaited<ReturnType<APIRequestContext['post']>
if (!response.ok()) {
throw new Error(`${label} failed: ${response.status()} ${await response.text()}`)
}
return response.json()
return response.status() === 204 ? null : response.json()
}
async function createSession(request: APIRequestContext, directory: string, parentID?: string): Promise<string> {
@@ -54,12 +58,44 @@ async function removeShell(request: APIRequestContext, directory: string, shellI
}
const createdShells: Array<{ directory: string; id: string }> = []
const createdDirectories: string[] = []
let directoryCounter = 0
function createUnregisteredDirectory(name: string): string {
directoryCounter += 1
const directory = path.join(E2E_TMP, `background-${name}-${process.pid}-${directoryCounter}`)
fs.mkdirSync(directory, { recursive: true })
fs.writeFileSync(path.join(directory, 'README.md'), '# background activity fixture\n')
const git = (...args: string[]) => execFileSync('git', args, { cwd: directory, stdio: 'pipe' })
git('-c', 'init.defaultBranch=main', 'init', '-q')
git('-c', 'user.name=e2e', '-c', 'user.email=e2e@example.com', 'add', '-A')
git('-c', 'user.name=e2e', '-c', 'user.email=e2e@example.com', 'commit', '-q', '-m', 'init')
createdDirectories.push(directory)
return directory
}
function waitForDirectorySubscription(page: Page, directory: string, endpoint = '/api/sse/subscribe') {
return page.waitForResponse((response) =>
response.url().includes(endpoint) && (response.request().postData() ?? '').includes(directory),
)
}
async function navigateWithinApp(page: Page, url: string): Promise<void> {
await page.evaluate((target) => {
window.history.pushState({}, '', target)
window.dispatchEvent(new PopStateEvent('popstate'))
}, url)
}
test.afterEach(async ({ request }) => {
const shells = createdShells.splice(0)
const results = await Promise.allSettled(shells.map(({ directory, id }) => removeShell(request, directory, id)))
const failures = results.flatMap((result) => (result.status === 'rejected' ? [String(result.reason)] : []))
expect(failures, 'background shell cleanup failed').toEqual([])
createdDirectories.splice(0).forEach((directory) => fs.rmSync(directory, { recursive: true, force: true }))
})
test.describe('session background activity', () => {
@@ -138,4 +174,80 @@ test.describe('session background activity', () => {
await expect(backgroundIndicator(page)).toHaveCount(0)
await expect(backgroundStatus(page)).toHaveCount(0)
})
test('shows the indicator for a shell started in an unregistered session directory before page load', async ({
page,
request,
repo,
}) => {
const directory = createUnregisteredDirectory('preload')
const sessionId = await createSession(request, directory)
const shellId = await startBackgroundShell(request, directory, sessionId)
createdShells.push({ directory, id: shellId })
await page.goto(`/repos/${repo.id}/sessions/${sessionId}`)
await expect(page.getByPlaceholder('Send a message...')).toBeVisible()
await expect(backgroundIndicator(page)).toBeVisible()
await removeShell(request, directory, shellId)
await expect(backgroundIndicator(page)).toBeHidden()
})
test('clears the indicator for a shell that exits while an unregistered session directory is unsubscribed', async ({
page,
request,
repo,
}) => {
const directory = createUnregisteredDirectory('stale')
const sessionId = await createSession(request, directory)
const subscribed = waitForDirectorySubscription(page, directory)
await page.goto(`/repos/${repo.id}/sessions/${sessionId}`)
await expect(page.getByPlaceholder('Send a message...')).toBeVisible()
expect((await subscribed).ok()).toBe(true)
const shellId = await startBackgroundShell(request, directory, sessionId)
createdShells.push({ directory, id: shellId })
await expect(backgroundIndicator(page)).toBeVisible()
const unsubscribed = waitForDirectorySubscription(page, directory, '/api/sse/unsubscribe')
await navigateWithinApp(page, '/')
expect((await unsubscribed).ok()).toBe(true)
await removeShell(request, directory, shellId)
await page.waitForTimeout(3_000)
await navigateWithinApp(page, `/repos/${repo.id}/sessions/${sessionId}`)
await expect(page.getByPlaceholder('Send a message...')).toBeVisible()
await expect(backgroundIndicator(page)).toBeHidden({ timeout: 20_000 })
})
test('follows a session moved to another directory without a reload', async ({ page, request, repo }) => {
const source = createUnregisteredDirectory('move-source')
const target = createUnregisteredDirectory('move-target')
const sessionId = await createSession(request, source)
const subscribedToSource = waitForDirectorySubscription(page, source)
await page.goto(`/repos/${repo.id}/sessions/${sessionId}`)
await expect(page.getByPlaceholder('Send a message...')).toBeVisible()
expect((await subscribedToSource).ok()).toBe(true)
const subscribedToTarget = waitForDirectorySubscription(page, target)
await requireOk(
await request.post(`/api/opencode/api/session/${sessionId}/move`, { data: { directory: target } }),
'move session',
)
expect((await subscribedToTarget).ok()).toBe(true)
const shellId = await startBackgroundShell(request, target, sessionId)
createdShells.push({ directory: target, id: shellId })
await expect(backgroundIndicator(page)).toBeVisible()
await removeShell(request, target, shellId)
await expect(backgroundIndicator(page)).toBeHidden()
})
})
+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()
}
}
+186
View File
@@ -0,0 +1,186 @@
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 })
})
}
async function waitForSynthesisSettled(synthTexts: string[], lastExpectedText: string): Promise<void> {
await expect.poll(() => synthTexts.join('\n')).toContain(lastExpectedText)
let previousCount = -1
await expect
.poll(
() => {
const isSettled = synthTexts.length === previousCount
previousCount = synthTexts.length
return isSettled
},
{ intervals: [500] },
)
.toBe(true)
}
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 waitForSynthesisSettled(synthTexts, 'CHARLIEMARKER paragraph 30')
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 waitForSynthesisSettled(synthTexts, 'ALPHAMARKER paragraph 30')
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()
})
+15 -2
View File
@@ -36,6 +36,7 @@ import { useAuth } from '@/hooks/useAuth'
import { useOpenCodeFailureToast } from '@/hooks/useOpenCodeFailureToast'
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
import { useGlobalShortcutActions } from '@/hooks/useGlobalShortcutActions'
import { useSession } from '@/hooks/useOpenCode'
import { RestartServerDialog } from '@/components/settings/RestartServerDialog'
const queryClient = new QueryClient({
@@ -103,17 +104,29 @@ function PermissionDialogWrapper() {
respond: replyToPermission,
showDialog,
setShowDialog,
navigateToCurrent,
viewedSessionId,
currentDirectory,
currentIsFromDifferentSession,
} = usePermissions()
const { getRepoIdForSession } = useEventContext()
const { data: session } = useSession(currentPermission?.sessionID, currentDirectory ?? undefined)
const canOpenCurrentSession = currentPermission !== null
&& getRepoIdForSession(currentPermission.sessionID) !== null
&& (currentIsFromDifferentSession || viewedSessionId === null)
return (
<PermissionRequestDialog
permission={currentPermission}
pendingCount={pendingCount}
isFromDifferentSession={false}
isFromDifferentSession={currentIsFromDifferentSession}
sessionTitle={session?.title ?? undefined}
repoDirectory={currentDirectory}
onOpenSession={canOpenCurrentSession ? navigateToCurrent : undefined}
onRespond={replyToPermission}
open={showDialog}
onOpenChange={setShowDialog}
repoDirectory={null}
/>
)
}
@@ -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'
@@ -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' : ''}`}
>
@@ -15,6 +15,7 @@ const permission: PermissionRequest = {
sessionID: 'session-1',
action: 'shell',
resources: ['rm -rf node_modules'],
save: ['rm *'],
metadata: {},
}
@@ -29,9 +30,99 @@ describe('PermissionRequestDialog', () => {
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={vi.fn()} />)
expect(screen.getByText('Run Command')).toBeInTheDocument()
expect(screen.getByText('Command')).toBeInTheDocument()
expect(screen.getByText('rm -rf node_modules')).toBeInTheDocument()
})
it('labels multiple shell resources as commands', () => {
render(
<PermissionRequestDialog
permission={{ ...permission, resources: ['git status', 'git push origin main'] }}
pendingCount={1}
onRespond={vi.fn()}
/>,
)
expect(screen.getByText('Commands')).toBeInTheDocument()
expect(screen.getByText(/git status/)).toBeInTheDocument()
expect(screen.getByText(/git push origin main/)).toBeInTheDocument()
})
it('shows the request message when present', () => {
render(
<PermissionRequestDialog
permission={{ ...permission, message: 'This command modifies tracked files.' }}
pendingCount={1}
onRespond={vi.fn()}
/>,
)
expect(screen.getByText('This command modifies tracked files.')).toBeInTheDocument()
})
it('describes a wildcard always scope', () => {
render(
<PermissionRequestDialog
permission={{ ...permission, save: ['*'] }}
pendingCount={1}
onRespond={vi.fn()}
/>,
)
expect(screen.getByText('This will always allow shell for this project.')).toBeInTheDocument()
})
it('lists the patterns an always decision approves', () => {
render(
<PermissionRequestDialog
permission={{ ...permission, save: ['printf *', 'echo *'] }}
pendingCount={1}
onRespond={vi.fn()}
/>,
)
expect(
screen.getByText('This will always allow the following patterns for this project.'),
).toBeInTheDocument()
expect(screen.getByText('printf *')).toBeInTheDocument()
expect(screen.getByText('echo *')).toBeInTheDocument()
})
it('omits the always option when no save patterns are provided', () => {
render(
<PermissionRequestDialog
permission={{ ...permission, save: undefined }}
pendingCount={1}
onRespond={vi.fn()}
/>,
)
expect(screen.queryByRole('button', { name: 'Allow Always' })).not.toBeInTheDocument()
expect(screen.queryByText(/This will always allow/)).not.toBeInTheDocument()
})
it('renders an open session control that triggers the handler', async () => {
const onOpenSession = vi.fn()
render(
<PermissionRequestDialog
permission={permission}
pendingCount={1}
onRespond={vi.fn()}
onOpenSession={onOpenSession}
/>,
)
await userEvent.click(screen.getByRole('button', { name: 'Open session' }))
expect(onOpenSession).toHaveBeenCalledTimes(1)
})
it('omits the open session control without a handler', () => {
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={vi.fn()} />)
expect(screen.queryByRole('button', { name: 'Open session' })).not.toBeInTheDocument()
})
it('replies with the selected decision for the permission request', async () => {
const onRespond = vi.fn().mockResolvedValue(undefined)
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={onRespond} />)
@@ -11,7 +11,11 @@ import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import type { PermissionResponse } from '@/api/types'
import type { PermissionRequest } from '@opencode-manager/shared/opencode'
import { getPermissionLabel, getPermissionDetail } from '@opencode-manager/shared/notifications'
import {
getPermissionLabel,
getPermissionDetail,
getPermissionAlwaysScope,
} from '@opencode-manager/shared/notifications'
import { cn } from '@/lib/utils'
import { showToast } from '@/lib/toast'
@@ -21,6 +25,7 @@ interface PermissionRequestDialogProps {
isFromDifferentSession?: boolean
sessionTitle?: string
repoDirectory?: string | null
onOpenSession?: () => void
onRespond: (
permissionID: string,
sessionID: string,
@@ -37,6 +42,7 @@ export function PermissionRequestDialog({
isFromDifferentSession,
sessionTitle,
repoDirectory,
onOpenSession,
onRespond,
open: parentOpen,
onOpenChange,
@@ -69,6 +75,7 @@ export function PermissionRequestDialog({
const typeLabel = getPermissionLabel(permission.action)
const details = getPermissionDetail(permission)
const alwaysScope = getPermissionAlwaysScope(permission)
const hasMultiple = pendingCount > 1
const displaySessionName = sessionTitle || `Session ${permission.sessionID.slice(0, 8)}...`
@@ -95,15 +102,24 @@ export function PermissionRequestDialog({
{typeLabel}
</span>
</div>
{permission.message && (
<p className="text-xs sm:text-sm break-words">{permission.message}</p>
)}
{details.primary && (
<div className="bg-muted/50 border rounded-md p-2 sm:p-3 max-h-32 overflow-y-auto overflow-x-hidden">
<pre className="text-xs sm:text-sm font-mono whitespace-pre-wrap break-all w-full">
{details.primary}
</pre>
<div className="space-y-1">
{details.label && (
<span className="block text-xs font-medium text-muted-foreground">{details.label}</span>
)}
<div className="bg-muted/50 border rounded-md p-2 sm:p-3 max-h-32 overflow-y-auto overflow-x-hidden">
<pre className="text-xs sm:text-sm font-mono whitespace-pre-wrap break-all w-full">
{details.primary}
</pre>
</div>
</div>
)}
{details.secondary && (
<div className="bg-muted/30 border rounded-md p-2 sm:p-3 max-h-24 overflow-y-auto overflow-x-hidden">
<pre className="text-xs font-mono whitespace-pre-wrap break-all w-full text-muted-foreground">
@@ -114,19 +130,32 @@ export function PermissionRequestDialog({
<div className="text-xs text-muted-foreground space-y-1">
{repoDirectory && (
<div className="truncate">
<div className="truncate" title={repoDirectory}>
Repo: <span className="font-medium">{repoDirectory.split('/').pop() ?? repoDirectory}</span>
</div>
)}
{isFromDifferentSession ? (
<div className="bg-warning/10 text-warning border border-warning/20 rounded-md px-2 py-1.5 truncate">
From another session: <span className="font-medium">{displaySessionName}</span>
</div>
) : (
<div className="truncate">
Session: <span className="font-medium">{displaySessionName}</span>
</div>
)}
<div className="flex items-center gap-2">
{isFromDifferentSession ? (
<div className="bg-warning/10 text-warning border border-warning/20 rounded-md px-2 py-1.5 truncate min-w-0 flex-1">
From another session: <span className="font-medium">{displaySessionName}</span>
</div>
) : (
<div className="truncate min-w-0 flex-1">
Session: <span className="font-medium">{displaySessionName}</span>
</div>
)}
{onOpenSession && (
<Button
type="button"
variant="link"
size="sm"
onClick={onOpenSession}
className="h-auto shrink-0 p-0 text-xs"
>
Open session
</Button>
)}
</div>
</div>
</div>
@@ -144,6 +173,19 @@ export function PermissionRequestDialog({
/>
</div>
{alwaysScope && (
<div className="rounded-md border bg-muted/30 px-2 py-1.5 text-xs text-muted-foreground space-y-1">
<p>{alwaysScope.summary}</p>
{alwaysScope.patterns.length > 0 && (
<ul className="list-disc pl-4 space-y-0.5 font-mono break-all">
{alwaysScope.patterns.map((pattern) => (
<li key={pattern}>{pattern}</li>
))}
</ul>
)}
</div>
)}
<DialogFooter className="flex-col-reverse gap-2 sm:flex-row sm:gap-2 mt-2">
<Button
variant="outline"
@@ -156,17 +198,19 @@ export function PermissionRequestDialog({
>
{loadingAction === 'reject' ? 'Denying...' : 'Deny'}
</Button>
<Button
variant="secondary"
onClick={() => handleResponse('always')}
disabled={isLoading}
className={cn(
"w-full sm:flex-1 text-sm h-9 sm:h-10",
loadingAction === 'always' && "opacity-70"
)}
>
{loadingAction === 'always' ? 'Allowing...' : 'Allow Always'}
</Button>
{alwaysScope && (
<Button
variant="secondary"
onClick={() => handleResponse('always')}
disabled={isLoading}
className={cn(
"w-full sm:flex-1 text-sm h-9 sm:h-10",
loadingAction === 'always' && "opacity-70"
)}
>
{loadingAction === 'always' ? 'Allowing...' : 'Allow Always'}
</Button>
)}
<Button
variant="default"
onClick={() => handleResponse('once')}
@@ -7,7 +7,7 @@ import { formatEventModifiers, formatShortcutEvent, formatShortcutLabel, isModif
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', 'switchPickerTab', 'newSession', 'closeSession', 'toggleSidebar', 'toggleTerminal', 'toggleSourceControl']
const formatActionLabel = (action: string): string => {
+567 -17
View File
@@ -97,6 +97,57 @@ const sourcedPermission: PermissionRequest = {
source: { type: 'tool', messageID: 'msg_1', id: 'call_1' },
}
const viewedSessionPermission: PermissionRequest = {
id: 'permission-view',
sessionID: 'session-view',
action: 'shell',
resources: ['echo view'],
metadata: {},
}
const otherSessionPermission: PermissionRequest = {
id: 'permission-other',
sessionID: 'session-other',
action: 'shell',
resources: ['echo other'],
metadata: {},
}
const childSessionPermission: PermissionRequest = {
id: 'permission-child',
sessionID: 'child-1',
action: 'shell',
resources: ['echo child'],
metadata: {},
}
const viewedSessionForm: FormInfo = {
id: 'form-view',
sessionID: 'session-view',
title: 'Continue view',
fields: [
{ key: 'q0', title: 'Confirm', type: 'string', options: [{ value: 'Yes', label: 'Yes' }] },
],
}
const otherSessionForm: FormInfo = {
id: 'form-other',
sessionID: 'session-other',
title: 'Continue other',
fields: [
{ key: 'q0', title: 'Confirm', type: 'string', options: [{ value: 'Yes', label: 'Yes' }] },
],
}
const childSessionForm: FormInfo = {
id: 'form-child',
sessionID: 'child-1',
title: 'Continue child',
fields: [
{ key: 'q0', title: 'Confirm', type: 'string', options: [{ value: 'Yes', label: 'Yes' }] },
],
}
function Harness() {
const { current, pendingCount, syncForSession, navigateToCurrent, cancel, reply, getForSession } = useForms()
const permissions = usePermissions()
@@ -116,6 +167,8 @@ function Harness() {
<div data-testid="for-session-unknown">{getForSession('session-unknown')?.id ?? 'none'}</div>
<div data-testid="permission-count">{permissions.pendingCount}</div>
<div data-testid="permission-current">{permissions.current?.id ?? 'none'}</div>
<div data-testid="permission-directory">{permissions.currentDirectory ?? 'none'}</div>
<div data-testid="permission-different">{String(permissions.currentIsFromDifferentSession)}</div>
<div data-testid="permission-tool-call">{permissions.getForToolCall('call_1', 'msg_1')?.id ?? 'none'}</div>
<div data-testid="permission-tool-call-other-message">
{permissions.getForToolCall('call_1', 'msg_other')?.id ?? 'none'}
@@ -124,9 +177,12 @@ function Harness() {
{permissions.getForToolCall('call_other', 'msg_1')?.id ?? 'none'}
</div>
<div data-testid="path">{location.pathname}</div>
<div data-testid="search">{location.search}</div>
<div data-testid="location-key">{location.key}</div>
<button onClick={() => syncForSession('/repo', 'session-1')}>Sync</button>
<button onClick={() => permissions.syncForSession('/repo', 'session-1')}>Sync Permissions</button>
<button onClick={navigateToCurrent}>Navigate</button>
<button onClick={permissions.navigateToCurrent}>Navigate Permission</button>
<button onClick={() => current && recordRejection(cancel(current.id))}>Dismiss</button>
<button onClick={() => current && recordRejection(reply(current.id, { q0: 'Yes' }))}>Reply</button>
<button onClick={() => permissions.current && recordRejection(permissions.respond(permissions.current.id, permissions.current.sessionID, 'reject'))}>Reject Permission</button>
@@ -149,9 +205,9 @@ function createDeferred<T>() {
return { promise, resolve }
}
function createWrapper(queryClient = createTestQueryClient()) {
function createWrapper(queryClient = createTestQueryClient(), initialPath = '/') {
return ({ children }: { children: ReactNode }) => (
<MemoryRouter>
<MemoryRouter initialEntries={[initialPath]}>
<QueryClientProvider client={queryClient}>
<EventProvider>{children}</EventProvider>
</QueryClientProvider>
@@ -173,6 +229,7 @@ function CacheResolutionHarness({ sessionID }: { sessionID: string }) {
describe('EventProvider permissions and forms', () => {
beforeEach(() => {
vi.clearAllMocks()
window.history.pushState({}, '', '/')
mocks.listRepos.mockResolvedValue([])
mocks.listPendingPermissions.mockResolvedValue([])
mocks.listPendingForms.mockResolvedValue([])
@@ -457,7 +514,7 @@ describe('EventProvider permissions and forms', () => {
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined
const onResync = lastSubscribeCall[0].onResync as ((directories: string[]) => void) | undefined
act(() => {
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/repo' })
@@ -470,7 +527,7 @@ describe('EventProvider permissions and forms', () => {
})
act(() => {
onResync?.()
onResync?.([])
})
await waitFor(() => {
@@ -492,7 +549,7 @@ describe('EventProvider permissions and forms', () => {
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined
const onResync = lastSubscribeCall[0].onResync as ((directories: string[]) => void) | undefined
act(() => {
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/repo' })
@@ -505,7 +562,7 @@ describe('EventProvider permissions and forms', () => {
})
act(() => {
onResync?.()
onResync?.([])
})
await waitFor(() => {
@@ -531,7 +588,7 @@ describe('EventProvider permissions and forms', () => {
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined
const onResync = lastSubscribeCall[0].onResync as ((directories: string[]) => void) | undefined
act(() => {
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/worktrees/wt-1' })
@@ -542,7 +599,7 @@ describe('EventProvider permissions and forms', () => {
})
act(() => {
onResync?.()
onResync?.([])
})
await waitFor(() => {
@@ -570,6 +627,107 @@ describe('EventProvider permissions and forms', () => {
})
})
it('navigates an assistant-session permission to the assistant session path', async () => {
mocks.listRepos.mockResolvedValue([{ id: 0, fullPath: '/assistant' }])
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/assistant'))
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/assistant' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-1')
})
await userEvent.click(screen.getByRole('button', { name: 'Navigate Permission' }))
await waitFor(() => {
expect(screen.getByTestId('path')).toHaveTextContent('/repos/0/sessions/session-1')
expect(screen.getByTestId('search')).toHaveTextContent('?assistant=1')
})
})
it('navigates a normal-repo permission without the assistant query', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/repo'))
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-1')
})
await userEvent.click(screen.getByRole('button', { name: 'Navigate Permission' }))
await waitFor(() => {
expect(screen.getByTestId('path')).toHaveTextContent('/repos/123/sessions/session-1')
})
expect(screen.getByTestId('search').textContent).toBe('')
})
it('does not navigate when already on the target session path', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
window.history.pushState({}, '', '/repos/123/sessions/session-1')
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/session-1'),
})
await waitFor(() => expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/repo'))
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-1')
})
const keyBefore = screen.getByTestId('location-key').textContent
await userEvent.click(screen.getByRole('button', { name: 'Navigate Permission' }))
expect(screen.getByTestId('location-key')).toHaveTextContent(keyBefore ?? '')
expect(screen.getByTestId('path')).toHaveTextContent('/repos/123/sessions/session-1')
})
it('navigates an assistant-session form to the assistant session path', async () => {
mocks.listRepos.mockResolvedValue([{ id: 0, fullPath: '/repo' }])
mocks.listPendingForms.mockResolvedValue([pendingForm])
render(<Harness />, { wrapper: createWrapper() })
await userEvent.click(screen.getByRole('button', { name: 'Sync' }))
await waitFor(() => {
expect(screen.getByTestId('current')).toHaveTextContent('form-1')
})
await userEvent.click(screen.getByRole('button', { name: 'Navigate' }))
await waitFor(() => {
expect(screen.getByTestId('path')).toHaveTextContent('/repos/0/sessions/session-1')
expect(screen.getByTestId('search')).toHaveTextContent('?assistant=1')
})
})
it('clears a pending form after dismiss succeeds', async () => {
mocks.listPendingForms.mockResolvedValue([pendingForm])
@@ -852,10 +1010,10 @@ describe('EventProvider permissions and forms', () => {
invalidateQueries.mockClear()
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined
const onResync = lastSubscribeCall[0].onResync as ((directories: string[]) => void) | undefined
act(() => {
onResync?.()
onResync?.([])
})
await waitFor(() => {
@@ -939,10 +1097,10 @@ describe('EventProvider permissions and forms', () => {
mocks.listPendingForms.mockClear()
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined
const onResync = lastSubscribeCall[0].onResync as ((directories: string[]) => void) | undefined
act(() => {
onResync?.()
onResync?.([])
})
expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/repo-a')
@@ -1039,6 +1197,309 @@ describe('EventProvider permissions and forms', () => {
})
})
it('prioritizes the viewed session permission over an earlier unrelated one', async () => {
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/session-view'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'permission.asked', data: otherSessionPermission, directory: '/repo' })
onEvent({ type: 'permission.asked', data: viewedSessionPermission, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-count')).toHaveTextContent('2')
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-view')
})
expect(screen.getByTestId('permission-different')).toHaveTextContent('false')
})
it('prefers a descendant session permission when viewing its parent', async () => {
act(() => {
useSessionStatus.getState().setSessionParent('child-1', 'parent-1')
})
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/parent-1'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'permission.asked', data: otherSessionPermission, directory: '/repo' })
onEvent({ type: 'permission.asked', data: childSessionPermission, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-child')
})
expect(screen.getByTestId('permission-different')).toHaveTextContent('false')
})
it('falls back to the first pending permission when the viewed session has none', async () => {
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/session-view'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'permission.asked', data: otherSessionPermission, directory: '/repo' })
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-count')).toHaveTextContent('2')
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-other')
})
expect(screen.getByTestId('permission-different')).toHaveTextContent('true')
})
it('resolves the current permission directory from the query cache', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
const queryClient = createTestQueryClient()
queryClient.setQueryData(
['opencode', 'session', 'session-1', '/repo'],
{
id: 'session-1',
projectID: 'proj-1',
title: 'Fix permission dialog',
location: { directory: '/repo' },
time: { created: 1000, updated: 1000 },
},
)
render(<Harness />, { wrapper: createWrapper(queryClient) })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-1')
expect(screen.getByTestId('permission-directory')).toHaveTextContent('/repo')
})
})
it('keeps the shown permission when a viewed-session permission arrives, then advances once it is answered', async () => {
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/session-view'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'permission.asked', data: otherSessionPermission, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-other')
})
act(() => {
onEvent({ type: 'permission.asked', data: viewedSessionPermission, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-count')).toHaveTextContent('2')
})
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-other')
act(() => {
onEvent({
type: 'permission.replied',
data: { sessionID: 'session-other', requestID: 'permission-other', reply: 'reject' },
directory: '/repo',
})
})
await waitFor(() => {
expect(screen.getByTestId('permission-count')).toHaveTextContent('1')
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-view')
})
})
it('prioritizes the viewed session form over an earlier unrelated one', async () => {
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/session-view'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'form.created', data: { form: otherSessionForm }, directory: '/repo' })
onEvent({ type: 'form.created', data: { form: viewedSessionForm }, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('count')).toHaveTextContent('2')
expect(screen.getByTestId('current')).toHaveTextContent('form-view')
})
})
it('prefers a descendant session form when viewing its parent', async () => {
act(() => {
useSessionStatus.getState().setSessionParent('child-1', 'parent-1')
})
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/parent-1'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'form.created', data: { form: otherSessionForm }, directory: '/repo' })
onEvent({ type: 'form.created', data: { form: childSessionForm }, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('current')).toHaveTextContent('form-child')
})
})
it('falls back to the first pending form when the viewed session has none', async () => {
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/session-view'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'form.created', data: { form: otherSessionForm }, directory: '/repo' })
onEvent({ type: 'form.created', data: { form: pendingForm }, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('count')).toHaveTextContent('2')
expect(screen.getByTestId('current')).toHaveTextContent('form-other')
})
})
it('keeps the shown form when a viewed-session form arrives, then advances once it is answered', async () => {
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/session-view'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'form.created', data: { form: otherSessionForm }, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('current')).toHaveTextContent('form-other')
})
act(() => {
onEvent({ type: 'form.created', data: { form: viewedSessionForm }, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('count')).toHaveTextContent('2')
})
expect(screen.getByTestId('current')).toHaveTextContent('form-other')
act(() => {
onEvent({
type: 'form.cancelled',
data: { id: 'form-other', sessionID: 'session-other' },
directory: '/repo',
})
})
await waitFor(() => {
expect(screen.getByTestId('count')).toHaveTextContent('1')
expect(screen.getByTestId('current')).toHaveTextContent('form-view')
})
})
it('resolves ancestry when a permission arrives for an unknown session', async () => {
mocks.getSession.mockImplementation((sessionID: string) => {
if (sessionID === 'child-1') return Promise.resolve({ id: 'child-1', parentID: 'parent-1' })
if (sessionID === 'parent-1') return Promise.resolve({ id: 'parent-1' })
return Promise.reject(new Error('Session not found'))
})
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/parent-1'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'permission.asked', data: childSessionPermission, directory: '/repo' })
})
await waitFor(() => {
expect(mocks.getSession).toHaveBeenCalledWith('child-1')
expect(useSessionStatus.getState().parents.get('child-1')).toBe('parent-1')
})
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-child')
expect(screen.getByTestId('permission-different')).toHaveTextContent('false')
})
it('resolves ancestry when a form arrives for an unknown session', async () => {
mocks.getSession.mockImplementation((sessionID: string) => {
if (sessionID === 'child-1') return Promise.resolve({ id: 'child-1', parentID: 'parent-1' })
if (sessionID === 'parent-1') return Promise.resolve({ id: 'parent-1' })
return Promise.reject(new Error('Session not found'))
})
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/parent-1'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'form.created', data: { form: childSessionForm }, directory: '/repo' })
})
await waitFor(() => {
expect(mocks.getSession).toHaveBeenCalledWith('child-1')
expect(useSessionStatus.getState().parents.get('child-1')).toBe('parent-1')
})
expect(screen.getByTestId('current')).toHaveTextContent('form-child')
})
it('exposes sseHealth through context', async () => {
mocks.getHealth.mockReturnValue({ isConnected: true, isHealthy: true, lastEventAt: Date.now(), isStalled: false })
mocks.subscribeGlobalMonitor.mockImplementation(({ onHealthChange }) => {
@@ -1210,7 +1671,7 @@ describe('EventProvider permissions and forms', () => {
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined
const onResync = lastSubscribeCall[0].onResync as ((directories: string[]) => void) | undefined
act(() => {
onEvent({ type: 'session.execution.started', data: { sessionID: 'child-1' }, directory: '/repo' })
@@ -1218,7 +1679,7 @@ describe('EventProvider permissions and forms', () => {
expect(useSessionStatus.getState().getStatus('child-1')).toEqual({ type: 'busy' })
act(() => {
onResync?.()
onResync?.([])
})
await waitFor(() => {
@@ -1865,11 +2326,18 @@ describe('EventProvider permissions and forms', () => {
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.listShells).toHaveBeenCalledWith('/repo'))
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onDirectoriesSubscribed = lastSubscribeCall[0].onDirectoriesSubscribed as (directories: string[]) => void
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onDirectoriesSubscribed(['/repo'])
})
await waitFor(() => expect(mocks.listShells).toHaveBeenCalledWith('/repo'))
act(() => {
onEvent({ type: 'shell.exited', data: { id: 'shell-1', status: 'exited' }, directory: '/repo' })
})
@@ -1889,11 +2357,18 @@ describe('EventProvider permissions and forms', () => {
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.listShells).toHaveBeenCalledWith('/repo'))
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onDirectoriesSubscribed = lastSubscribeCall[0].onDirectoriesSubscribed as (directories: string[]) => void
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onDirectoriesSubscribed(['/repo'])
})
await waitFor(() => expect(mocks.listShells).toHaveBeenCalledWith('/repo'))
act(() => {
onEvent({
type: 'shell.created',
@@ -1913,7 +2388,7 @@ describe('EventProvider permissions and forms', () => {
})
})
it('resolves ancestry for a shell owner from the directory snapshot', async () => {
it('resolves ancestry for a shell owner from a newly subscribed directory snapshot', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listShells.mockResolvedValue([
{ id: 'shell-1', status: 'running', metadata: { sessionID: 'child-1' } },
@@ -1926,6 +2401,15 @@ describe('EventProvider permissions and forms', () => {
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onDirectoriesSubscribed = lastSubscribeCall[0].onDirectoriesSubscribed as (directories: string[]) => void
act(() => {
onDirectoriesSubscribed(['/repo'])
})
await waitFor(() => {
expect(useSessionStatus.getState().parents.get('child-1')).toBe('parent-1')
})
@@ -1967,6 +2451,12 @@ describe('EventProvider permissions and forms', () => {
it('syncs running shells for a directory whose repo arrives after connect', async () => {
const reposDeferred = createDeferred<Array<{ id: number; fullPath: string }>>()
mocks.listRepos.mockReturnValueOnce(reposDeferred.promise)
mocks.subscribeGlobalMonitor.mockImplementation((input: { onDirectoriesSubscribed?: (directories: string[]) => void }) => ({
dispose: vi.fn(),
updateDirectories: (directories: string[]) => input.onDirectoriesSubscribed?.(directories),
reconnect: vi.fn(),
reportVisibility: vi.fn(),
}))
render(<Harness />, { wrapper: createWrapper() })
@@ -1988,4 +2478,64 @@ describe('EventProvider permissions and forms', () => {
await waitFor(() => expect(mocks.listShells).toHaveBeenCalledWith('/repo'))
})
it('reconciles newly subscribed directories reported by the stream', async () => {
mocks.listPendingPermissions.mockResolvedValue([pendingPermission])
mocks.listPendingForms.mockResolvedValue([pendingForm])
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onDirectoriesSubscribed = lastSubscribeCall[0].onDirectoriesSubscribed as (directories: string[]) => void
act(() => {
useSessionStatus.getState().setShellRunning('shell-stale', 'session-1', '/session-dir')
})
expect(useSessionStatus.getState().runningShells.has('shell-stale')).toBe(true)
await act(async () => {
onDirectoriesSubscribed(['/session-dir'])
})
await waitFor(() => {
expect(mocks.listShells).toHaveBeenCalledWith('/session-dir')
expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/session-dir')
expect(mocks.listPendingForms).toHaveBeenCalledWith('/session-dir')
})
expect(useSessionStatus.getState().runningShells.has('shell-stale')).toBe(false)
expect(screen.getByTestId('permission-count').textContent).toBe('1')
expect(screen.getByTestId('count').textContent).toBe('1')
})
it('reconciles subscribed directories reported by a resync even when they are not tracked', async () => {
mocks.listPendingPermissions.mockResolvedValue([pendingPermission])
mocks.listPendingForms.mockResolvedValue([pendingForm])
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onResync = lastSubscribeCall[0].onResync as ((directories: string[]) => void) | undefined
act(() => {
useSessionStatus.getState().setShellRunning('shell-stale', 'session-1', '/unregistered-dir')
})
expect(useSessionStatus.getState().runningShells.has('shell-stale')).toBe(true)
await act(async () => {
onResync?.(['/unregistered-dir'])
})
await waitFor(() => {
expect(mocks.listShells).toHaveBeenCalledWith('/unregistered-dir')
expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/unregistered-dir')
expect(mocks.listPendingForms).toHaveBeenCalledWith('/unregistered-dir')
})
expect(useSessionStatus.getState().runningShells.has('shell-stale')).toBe(false)
expect(screen.getByTestId('permission-count').textContent).toBe('1')
expect(screen.getByTestId('count').textContent).toBe('1')
})
})
+155 -58
View File
@@ -1,6 +1,6 @@
/* eslint-disable react-refresh/only-export-components */
import { createContext, useContext, useEffect, useState, useCallback, useMemo, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { useLocation, useNavigate } from 'react-router-dom'
import { useQueryClient, useQuery } from '@tanstack/react-query'
import {
cancelForm,
@@ -19,6 +19,7 @@ import type { PermissionResponse, SSHHostKeyRequest, Repo } from '@/api/types'
import { showToast } from '@/lib/toast'
import { openCodeEventStream, type EventStreamHealthState } from '@/lib/opencode-event-stream'
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
import { getSessionPath, parseRepoRoute } from '@/lib/navigation'
import { changeWalkthroughQueryKey } from '@/hooks/useChangeWalkthrough'
import { busyStatusesFromActiveSessions, useSessionStatus } from '@/stores/sessionStatusStore'
import {
@@ -71,6 +72,53 @@ function repoMatchesDirectory(repo: Repo, directory?: string | null) {
.some((path) => normalizeDirectory(path) === normalizedDirectory)
}
function isSessionWithinView(
sessionID: string,
viewedSessionID: string,
parents: Map<string, string | null>,
): boolean {
const visited = new Set<string>()
let currentID: string | null = sessionID
while (currentID !== null && !visited.has(currentID)) {
if (currentID === viewedSessionID) return true
visited.add(currentID)
currentID = parents.get(currentID) ?? null
}
return false
}
/**
* Pins the item currently on screen until it leaves `items`, then advances to the first item whose
* session is the viewed session or one of its descendants, falling back to the first item.
* The selection is derived during render so a newly arriving item never displaces the shown one.
*/
function usePinnedViewedItem<T extends SessionScopedItem>(
items: T[],
viewedSessionId: string | null,
parents: Map<string, string | null>,
): T | null {
const [pinnedId, setPinnedId] = useState<string | null>(null)
const selected = useMemo(() => {
if (pinnedId) {
const pinned = items.find((item) => item.id === pinnedId)
if (pinned) return pinned
}
const forViewedSession = viewedSessionId
? items.find((item) => isSessionWithinView(item.sessionID, viewedSessionId, parents)) ?? null
: null
return forViewedSession ?? items[0] ?? null
}, [items, viewedSessionId, parents, pinnedId])
const selectedId = selected?.id ?? null
if (selectedId !== pinnedId) setPinnedId(selectedId)
return selected
}
function reconcileBySessionForDirectory<T extends SessionScopedItem>(
prev: Record<string, T[]>,
directory: string,
@@ -104,6 +152,19 @@ interface EventContextValue {
permissions: {
current: PermissionRequest | null
pendingCount: number
/**
* Session currently being viewed from the route, or null when no session route is active.
*/
viewedSessionId: string | null
/**
* Directory of the current permission's session, resolved from tracked events and the query cache.
*/
currentDirectory: string | null
/**
* True when a session is being viewed and the current permission belongs to neither that session
* nor one of its descendants.
*/
currentIsFromDifferentSession: boolean
/**
* Replies to a permission request and removes it from the queue. Resolves, after showing an
* "expired" toast, when the server no longer knows the request (`PermissionNotFoundError`);
@@ -169,6 +230,8 @@ const EventContext = createContext<EventContextValue | null>(null)
export function EventProvider({ children }: { children: React.ReactNode }) {
const queryClient = useQueryClient()
const navigate = useNavigate()
const location = useLocation()
const sessionParents = useSessionStatus((state) => state.parents)
const [sshHostKeyRequest, setSSHHostKeyRequest] = useState<SSHHostKeyRequest | null>(null)
const [sseHealth, setSseHealth] = useState<SSEHealthState>(() => {
@@ -206,7 +269,6 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const statusPollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
const subscriptionRef = useRef<ReturnType<typeof openCodeEventStream.subscribeGlobalMonitor> | null>(null)
const reposRef = useRef<typeof repos>(null)
const trackedRepoDirectoriesRef = useRef<Set<string>>(new Set())
const ancestryInFlightRef = useRef<Set<string>>(new Set())
const { data: repos } = useQuery({
@@ -217,52 +279,72 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const allPermissions = useMemo(() => Object.values(permissionsBySession).flat(), [permissionsBySession])
const allForms = useMemo(() => Object.values(formsBySession).flat(), [formsBySession])
const currentPermission = allPermissions[0] ?? null
const currentForm = allForms[0] ?? null
const viewedSessionId = useMemo(
() => parseRepoRoute(location.pathname).sessionId,
[location.pathname],
)
const currentPermission = usePinnedViewedItem(allPermissions, viewedSessionId, sessionParents)
const currentForm = usePinnedViewedItem(allForms, viewedSessionId, sessionParents)
const rememberSessionDirectory = useCallback((sessionID: string, directory?: string) => {
if (!directory) return
sessionDirectoriesRef.current.set(sessionID, directory)
}, [])
const findSessionDirectory = useCallback((sessionID: string): string | null => {
const remembered = sessionDirectoriesRef.current.get(sessionID)
if (remembered) return remembered
const findCachedSessionDirectory = useCallback((sessionID: string): string | null => {
const cache = queryClient.getQueryCache()
const queries = cache.getAll()
let directory: string | undefined
for (const query of queries) {
const key = query.queryKey
if (key[0] !== 'opencode' || key[1] !== 'session' || key[2] !== sessionID) continue
const sessionData = query.state.data as { location?: { directory?: string } } | undefined
const directory = sessionData?.location?.directory ?? (typeof key[3] === 'string' ? key[3] : null)
if (directory) return directory
}
for (const query of queries) {
const key = query.queryKey
if (key[0] !== 'opencode' || key[1] !== 'sessions') continue
const sessionsData = query.state.data
if (!sessionsData || typeof sessionsData !== 'object' || !('pages' in sessionsData)) continue
const pages = (sessionsData as {
pages?: Array<{ items?: Array<{ id: string; location?: { directory?: string } }> }>
}).pages
if (!Array.isArray(pages)) continue
for (const page of pages) {
const found = page.items?.find(s => s.id === sessionID)
const directory = found?.location?.directory
if (directory) return directory
const resolvedDirectory = sessionData?.location?.directory
?? (typeof key[3] === 'string' ? key[3] : undefined)
if (resolvedDirectory) {
directory = resolvedDirectory
break
}
}
return null
if (!directory) {
for (const query of queries) {
const key = query.queryKey
if (key[0] !== 'opencode' || key[1] !== 'sessions') continue
const sessionsData = query.state.data
if (!sessionsData || typeof sessionsData !== 'object' || !('pages' in sessionsData)) continue
const pages = (sessionsData as {
pages?: Array<{ items?: Array<{ id: string; location?: { directory?: string } }> }>
}).pages
if (!Array.isArray(pages)) continue
for (const page of pages) {
const found = page.items?.find(s => s.id === sessionID)
if (found?.location?.directory) {
directory = found.location.directory
break
}
}
if (directory) break
}
}
return directory ?? null
}, [queryClient])
const findSessionDirectory = useCallback((sessionID: string): string | null => {
const remembered = sessionDirectoriesRef.current.get(sessionID)
if (remembered) return remembered
return findCachedSessionDirectory(sessionID)
}, [findCachedSessionDirectory])
const getRepoIdForSession = useCallback((sessionID: string): number | null => {
if (!repos) return null
const directory = findSessionDirectory(sessionID)
@@ -271,6 +353,15 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
return repo?.id ?? null
}, [repos, findSessionDirectory])
const currentPermissionDirectory = useMemo(
() => (currentPermission ? findSessionDirectory(currentPermission.sessionID) : null),
[currentPermission, findSessionDirectory],
)
const currentIsFromDifferentSession = viewedSessionId !== null
&& currentPermission !== null
&& !isSessionWithinView(currentPermission.sessionID, viewedSessionId, sessionParents)
const addPermission = useCallback((permission: PermissionRequest) => {
addToSessionKeyedState(setPermissionsBySession, permission)
}, [])
@@ -374,27 +465,24 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
return (formsBySession[sessionID]?.length ?? 0) > 0
}, [formsBySession])
const navigateToSession = useCallback((sessionID: string) => {
const repoId = getRepoIdForSession(sessionID)
if (repoId === null) return
const targetPath = getSessionPath(repoId, sessionID)
if (`${window.location.pathname}${window.location.search}` !== targetPath) {
navigate(targetPath)
}
}, [getRepoIdForSession, navigate])
const navigateToCurrentForm = useCallback(() => {
if (!currentForm) return
const repoId = getRepoIdForSession(currentForm.sessionID)
if (repoId) {
const targetPath = `/repos/${repoId}/sessions/${currentForm.sessionID}`
if (window.location.pathname !== targetPath) {
navigate(targetPath)
}
}
}, [currentForm, getRepoIdForSession, navigate])
navigateToSession(currentForm.sessionID)
}, [currentForm, navigateToSession])
const navigateToCurrentPermission = useCallback(() => {
if (!currentPermission) return
const repoId = getRepoIdForSession(currentPermission.sessionID)
if (repoId) {
const targetPath = `/repos/${repoId}/sessions/${currentPermission.sessionID}`
if (window.location.pathname !== targetPath) {
navigate(targetPath)
}
}
}, [currentPermission, getRepoIdForSession, navigate])
navigateToSession(currentPermission.sessionID)
}, [currentPermission, navigateToSession])
const reconcilePendingActionsForDirectories = useCallback(async (directories: string[]) => {
await Promise.all(directories.map(async (directory) => {
@@ -557,6 +645,9 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const request = event.data
rememberSessionDirectory(request.sessionID, event.directory)
addPermission(request)
if (!useSessionStatus.getState().parents.has(request.sessionID)) {
void resolveSessionAncestry([request.sessionID])
}
break
}
case 'permission.replied': {
@@ -568,6 +659,9 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const form = event.data.form
rememberSessionDirectory(form.sessionID, event.directory)
addForm(form)
if (!useSessionStatus.getState().parents.has(form.sessionID)) {
void resolveSessionAncestry([form.sessionID])
}
break
}
case 'form.replied':
@@ -710,10 +804,11 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
}
}
const handleResync = () => {
void reconcilePendingActionsForDirectories(collectTrackedDirectories())
const handleResync = (subscribedDirectories: string[]) => {
const directories = [...new Set([...collectTrackedDirectories(), ...subscribedDirectories])]
void reconcilePendingActionsForDirectories(directories)
void fetchInitialSessionStatuses()
void syncRunningShells(collectTrackedDirectories())
void syncRunningShells(directories)
invalidateChildSessionCaches(queryClient)
invalidateQueryKeysDebounced(queryClient, LOCATION_CATALOG_QUERY_KEYS)
}
@@ -725,6 +820,10 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
onStatusChange: handleStatusChange,
onHealthChange: handleHealthChange,
onResync: handleResync,
onDirectoriesSubscribed: (directories) => {
void reconcilePendingActionsForDirectories(directories)
void syncRunningShells(directories)
},
})
subscriptionRef.current = subscription
@@ -739,16 +838,8 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
reposRef.current = repos
const directories = [...new Set((repos ?? []).map(r => r.fullPath))]
const previousDirectories = trackedRepoDirectoriesRef.current
const addedDirectories = directories.filter((directory) => !previousDirectories.has(directory))
trackedRepoDirectoriesRef.current = new Set(directories)
const sub = subscriptionRef.current
if (!sub) return
sub.updateDirectories(directories)
if (addedDirectories.length > 0) {
void syncRunningShells(addedDirectories)
}
}, [repos, syncRunningShells])
subscriptionRef.current?.updateDirectories(directories)
}, [repos])
useEffect(() => {
if (!repos || repos.length === 0) return
@@ -766,6 +857,9 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
permissions: {
current: currentPermission,
pendingCount: allPermissions.length,
viewedSessionId,
currentDirectory: currentPermissionDirectory,
currentIsFromDifferentSession,
respond: replyToPermission,
dismiss: removePermission,
getForToolCall: getPermissionForToolCall,
@@ -793,6 +887,9 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
respondToSSHHostKey,
currentPermission,
allPermissions.length,
viewedSessionId,
currentPermissionDirectory,
currentIsFromDifferentSession,
replyToPermission,
removePermission,
hasPermissionsForSession,
@@ -111,6 +111,8 @@ describe('useAutoPlayLastResponse', () => {
},
updateSettings: mockUpdateSettings,
})
return mockTTS
}
it('does NOT call speakMessage when tts.enabled is false', () => {
@@ -191,6 +193,77 @@ describe('useAutoPlayLastResponse', () => {
expect(mockSpeakMessage).toHaveBeenCalledWith('1', 'Test text')
})
it('does NOT call speakMessage when unattributed playback is active, and does not speak it after playback ends', () => {
const mockTTS = setup()
const incompleteMessage = createMessage('1')
const { rerender } = renderHook(
(props) => useAutoPlayLastResponse(props),
{
initialProps: {
sessionId: 'test-session',
lastAssistantMessage: incompleteMessage,
lastAssistantText: 'Test text',
isStreamingResponse: false,
},
}
)
mockTTS.isPlaying = true
mockTTS.activeMessageId = null
const completedMessage = createMessage('1', Date.now())
rerender({
sessionId: 'test-session',
lastAssistantMessage: completedMessage,
lastAssistantText: 'Test text',
isStreamingResponse: false,
})
expect(mockSpeakMessage).not.toHaveBeenCalled()
mockTTS.isPlaying = false
rerender({
sessionId: 'test-session',
lastAssistantMessage: completedMessage,
lastAssistantText: 'Test text',
isStreamingResponse: false,
})
expect(mockSpeakMessage).not.toHaveBeenCalled()
})
it('CALLS speakMessage when a message-attributed playback is active', () => {
const mockTTS = setup()
const incompleteMessage = createMessage('1')
const { rerender } = renderHook(
(props) => useAutoPlayLastResponse(props),
{
initialProps: {
sessionId: 'test-session',
lastAssistantMessage: incompleteMessage,
lastAssistantText: 'Test text',
isStreamingResponse: false,
},
}
)
mockTTS.isPlaying = true
mockTTS.activeMessageId = 'other-message'
const completedMessage = createMessage('1', Date.now())
rerender({
sessionId: 'test-session',
lastAssistantMessage: completedMessage,
lastAssistantText: 'Test text',
isStreamingResponse: false,
})
expect(mockSpeakMessage).toHaveBeenCalledTimes(1)
expect(mockSpeakMessage).toHaveBeenCalledWith('1', 'Test text')
})
it('does NOT call speakMessage twice for the same message id across multiple rerenders', () => {
setup()
@@ -0,0 +1,202 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook } from '@testing-library/react'
import type { RefObject } from 'react'
import type { SessionMessageAssistant, SessionMessageInfo } from '@opencode-manager/shared/opencode'
import type { TTSState } from '@/hooks/useTTS'
const mocks = vi.hoisted(() => ({
useTTS: vi.fn(),
showToastError: vi.fn(),
}))
vi.mock('@/hooks/useTTS', () => ({
useTTS: mocks.useTTS,
}))
vi.mock('@/lib/toast', () => ({
showToast: { error: mocks.showToastError },
}))
import { useSpeakVisibleMessages } from '../useSpeakVisibleMessages'
interface MockTTSReturn {
speak: ReturnType<typeof vi.fn>
stop: ReturnType<typeof vi.fn>
isEnabled: boolean
isPlaying: boolean
isLoading: boolean
state: TTSState
error: string | null
activeMessageId: string | null
}
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 buildContainer = (messageId: string): HTMLDivElement => {
const container = document.createElement('div')
container.getBoundingClientRect = () => rect(0, 100)
const element = document.createElement('div')
element.dataset.messageId = messageId
element.getBoundingClientRect = () => rect(10, 30)
container.appendChild(element)
return container
}
const assistantMessage = (id: string, text: string): SessionMessageAssistant => ({
id,
type: 'assistant',
agent: 'test-agent',
model: { providerID: 'test-provider', id: 'test-model' },
content: [{ type: 'text', text }],
time: { created: 1, completed: 2 },
})
describe('useSpeakVisibleMessages', () => {
const mockSpeak = vi.fn()
const mockStop = vi.fn()
const setupTTS = (overrides: Partial<MockTTSReturn> = {}) => {
const value: MockTTSReturn = {
speak: mockSpeak,
stop: mockStop,
isEnabled: true,
isPlaying: false,
isLoading: false,
state: 'idle',
error: null,
activeMessageId: null,
...overrides,
}
mocks.useTTS.mockReturnValue(value)
}
beforeEach(() => {
vi.clearAllMocks()
mockSpeak.mockResolvedValue(true)
})
it('stops playback while playing', () => {
setupTTS({ isPlaying: true })
const containerRef: RefObject<HTMLElement | null> = { current: null }
const { result } = renderHook(() =>
useSpeakVisibleMessages(containerRef, [], 0)
)
result.current()
expect(mockStop).toHaveBeenCalledTimes(1)
expect(mockSpeak).not.toHaveBeenCalled()
})
it('speaks the visible assistant texts joined by a blank line', () => {
setupTTS()
const container = buildContainer('a1')
const containerRef: RefObject<HTMLElement | null> = { current: container }
const messages: SessionMessageInfo[] = [assistantMessage('a1', 'hello world')]
const { result } = renderHook(() =>
useSpeakVisibleMessages(containerRef, messages, 0)
)
result.current()
expect(mockSpeak).toHaveBeenCalledTimes(1)
expect(mockSpeak).toHaveBeenCalledWith('hello world')
})
it('does nothing when TTS is disabled', () => {
setupTTS({ isEnabled: false })
const container = buildContainer('a1')
const containerRef: RefObject<HTMLElement | null> = { current: container }
const messages: SessionMessageInfo[] = [assistantMessage('a1', 'hello world')]
const { result } = renderHook(() =>
useSpeakVisibleMessages(containerRef, messages, 0)
)
result.current()
expect(mockSpeak).not.toHaveBeenCalled()
})
it('shows an error toast once after shortcut-started playback fails', () => {
setupTTS()
const container = buildContainer('a1')
const containerRef: RefObject<HTMLElement | null> = { current: container }
const messages: SessionMessageInfo[] = [assistantMessage('a1', 'hello world')]
const { result, rerender } = renderHook(() =>
useSpeakVisibleMessages(containerRef, messages, 0)
)
result.current()
expect(mockSpeak).toHaveBeenCalledTimes(1)
setupTTS({ state: 'error', error: 'network failure' })
rerender()
expect(mocks.showToastError).toHaveBeenCalledTimes(1)
expect(mocks.showToastError).toHaveBeenCalledWith('network failure')
setupTTS({ state: 'error', error: 'another failure' })
rerender()
expect(mocks.showToastError).toHaveBeenCalledTimes(1)
})
it('does not toast when shortcut-started playback returns to idle', () => {
setupTTS()
const container = buildContainer('a1')
const containerRef: RefObject<HTMLElement | null> = { current: container }
const messages: SessionMessageInfo[] = [assistantMessage('a1', 'hello world')]
const { result, rerender } = renderHook(() =>
useSpeakVisibleMessages(containerRef, messages, 0)
)
result.current()
setupTTS({ state: 'playing' })
rerender()
setupTTS({ state: 'idle' })
rerender()
setupTTS({ state: 'error', error: 'late failure' })
rerender()
expect(mocks.showToastError).not.toHaveBeenCalled()
})
it('does not toast when playback becomes message-attributed', () => {
setupTTS()
const container = buildContainer('a1')
const containerRef: RefObject<HTMLElement | null> = { current: container }
const messages: SessionMessageInfo[] = [assistantMessage('a1', 'hello world')]
const { result, rerender } = renderHook(() =>
useSpeakVisibleMessages(containerRef, messages, 0)
)
result.current()
setupTTS({ state: 'playing', activeMessageId: 'a1' })
rerender()
setupTTS({ state: 'error', error: 'late failure', activeMessageId: 'a1' })
rerender()
expect(mocks.showToastError).not.toHaveBeenCalled()
})
})
+16 -4
View File
@@ -37,7 +37,7 @@ export function useAutoPlayLastResponse({
lastAssistantText,
isStreamingResponse,
}: UseAutoPlayLastResponseParams): void {
const { speakMessage, isEnabled: ttsEnabled } = useTTS()
const { speakMessage, isEnabled: ttsEnabled, isPlaying, isLoading, activeMessageId } = useTTS()
const { preferences } = useSettings()
const autoPlayEnabled = preferences?.tts?.autoPlay ?? false
@@ -47,6 +47,13 @@ export function useAutoPlayLastResponse({
const lastKnownCompletedRef = useRef<Record<string, boolean>>({})
const hasSeenIncompleteRef = useRef<boolean>(false)
const previousSessionIdRef = useRef<string | null>(null)
const isUnattributedPlaybackActiveRef = useRef<boolean>(false)
const isUnattributedPlaybackActive = (isPlaying || isLoading) && activeMessageId === null
useEffect(() => {
isUnattributedPlaybackActiveRef.current = isUnattributedPlaybackActive
}, [isUnattributedPlaybackActive])
useEffect(() => {
const isSessionChange = previousSessionIdRef.current !== null && previousSessionIdRef.current !== sessionId
@@ -76,6 +83,7 @@ export function useAutoPlayLastResponse({
const messageId = lastAssistantMessage.id
const isCompleted = isMessageCompleted(lastAssistantMessage)
const wasCompleted = lastKnownCompletedRef.current[messageId] ?? false
const shouldAutoSpeak = !isUnattributedPlaybackActiveRef.current
if (!isCompleted) {
lastKnownCompletedRef.current[messageId] = false
@@ -91,7 +99,7 @@ export function useAutoPlayLastResponse({
hasInitializedRef.current = true
lastSpokenIdRef.current = messageId
lastKnownCompletedRef.current[messageId] = true
if (hasSeenIncompleteRef.current) {
if (hasSeenIncompleteRef.current && shouldAutoSpeak) {
speakMessage(messageId, lastAssistantText)
}
return
@@ -99,14 +107,18 @@ export function useAutoPlayLastResponse({
if (!wasCompleted && messageId === lastSpokenIdRef.current) {
lastKnownCompletedRef.current[messageId] = true
speakMessage(messageId, lastAssistantText)
if (shouldAutoSpeak) {
speakMessage(messageId, lastAssistantText)
}
return
}
if (messageId !== lastSpokenIdRef.current) {
lastSpokenIdRef.current = messageId
lastKnownCompletedRef.current[messageId] = true
speakMessage(messageId, lastAssistantText)
if (shouldAutoSpeak) {
speakMessage(messageId, lastAssistantText)
}
}
}, [
ttsEnabled,
+34
View File
@@ -174,6 +174,40 @@ describe('useSSE', () => {
unmount()
})
it('invalidates the cached session query on session.moved so the page follows the new directory', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
queryClient.setQueryData(['opencode', 'session', 'session-1', '/repo'], { id: 'session-1' })
const { result, unmount } = renderHook(
() => useSSE('/repo', 'session-1'),
{ wrapper: createWrapper(queryClient) }
)
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
await connect(0, 'client-1')
await waitFor(() => expect(result.current.isConnected).toBe(true))
invalidateQueries.mockClear()
act(() => {
MockEventSource.instances[0].emit('message', {
type: 'session.moved',
directory: '/repo',
data: { sessionID: 'session-1', projectID: 'proj-1', subpath: '', location: { directory: '/elsewhere' } },
})
})
await waitFor(() => {
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'session', 'session-1'] })
})
unmount()
})
it('invalidates the cached session query on session.renamed', async () => {
const queryClient = new QueryClient({
defaultOptions: {
+1
View File
@@ -80,6 +80,7 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
break
case 'session.renamed':
case 'session.moved':
invalidateSessionQueryIfCached(queryClient, event.data.sessionID)
break
@@ -0,0 +1,41 @@
import { useCallback, useEffect, useRef, type RefObject } from 'react'
import type { SessionMessageInfo } from '@opencode-manager/shared/opencode'
import { useTTS } from './useTTS'
import { collectVisibleAssistantTexts } from '@/lib/visibleMessageTexts'
import { showToast } from '@/lib/toast'
export function useSpeakVisibleMessages(
containerRef: RefObject<HTMLElement | null>,
messages: SessionMessageInfo[],
bottomInset: number,
): () => void {
const { speak, stop, isPlaying, isLoading, isEnabled, state, error, activeMessageId } = useTTS()
const pendingRef = useRef(false)
useEffect(() => {
if (!pendingRef.current) return
if (activeMessageId !== null || state === 'idle') {
pendingRef.current = false
return
}
if (state === 'error') {
showToast.error(error ?? 'Text-to-speech failed')
pendingRef.current = false
}
}, [state, error, activeMessageId])
return useCallback(() => {
if (!isEnabled) return
if (isPlaying || isLoading) {
pendingRef.current = false
stop()
return
}
const container = containerRef.current
if (!container) return
const texts = collectVisibleAssistantTexts(container, messages, bottomInset)
if (texts.length === 0) return
pendingRef.current = true
void speak(texts.join('\n\n'))
}, [isEnabled, isPlaying, isLoading, stop, speak, messages, containerRef, bottomInset])
}
@@ -2,6 +2,30 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { OpenCodeEventStream, TestEventStreamTransport } from '..'
import type { EventStreamHealthState } from '..'
class RejectingSubscribeTransport extends TestEventStreamTransport {
override async post(path: string, body: unknown): Promise<boolean> {
this.posts.push({ path, body })
return false
}
}
class DeferredSubscribeTransport extends TestEventStreamTransport {
private resolvers: Array<(value: boolean) => void> = []
override post(path: string, body: unknown): Promise<boolean> {
this.posts.push({ path, body })
return new Promise<boolean>((resolve) => {
this.resolvers.push(resolve)
})
}
resolvePosts(success = true): void {
const resolvers = this.resolvers
this.resolvers = []
resolvers.forEach((resolve) => resolve(success))
}
}
describe('OpenCodeEventStream', () => {
beforeEach(() => {
vi.useFakeTimers()
@@ -169,6 +193,7 @@ describe('OpenCodeEventStream', () => {
transport.resync()
expect(onResync).toHaveBeenCalledTimes(1)
expect(onResync).toHaveBeenCalledWith(['/repo'])
})
it('reports visibility through the transport adapter', async () => {
@@ -186,4 +211,100 @@ describe('OpenCodeEventStream', () => {
body: { clientId: 'client-1', visible: true, activeSessionId: 'session-1' },
})
})
it('notifies the global monitor with directories subscribed mid-connection', async () => {
const transport = new TestEventStreamTransport()
const stream = new OpenCodeEventStream({ transport })
const onDirectoriesSubscribed = vi.fn()
const subscription = stream.subscribeGlobalMonitor({
directories: ['/repo-a'],
onEvent: vi.fn(),
onDirectoriesSubscribed,
})
transport.openConnection()
transport.connected('client-1')
await vi.advanceTimersByTimeAsync(0)
onDirectoriesSubscribed.mockClear()
subscription.updateDirectories(['/repo-a', '/repo-b'])
await vi.advanceTimersByTimeAsync(0)
expect(onDirectoriesSubscribed).toHaveBeenCalledWith(['/repo-b'])
})
it('notifies the global monitor for pending directories flushed after connect', async () => {
const transport = new TestEventStreamTransport()
const stream = new OpenCodeEventStream({ transport })
const onDirectoriesSubscribed = vi.fn()
stream.subscribeGlobalMonitor({ directories: ['/repo'], onEvent: vi.fn(), onDirectoriesSubscribed })
expect(onDirectoriesSubscribed).not.toHaveBeenCalled()
transport.openConnection()
transport.connected('client-1')
await vi.advanceTimersByTimeAsync(0)
expect(onDirectoriesSubscribed).toHaveBeenCalledWith(['/repo'])
})
it('does not notify the global monitor when the subscribe request fails', async () => {
const transport = new RejectingSubscribeTransport()
const stream = new OpenCodeEventStream({ transport })
const onDirectoriesSubscribed = vi.fn()
stream.subscribeGlobalMonitor({ directories: ['/repo'], onEvent: vi.fn(), onDirectoriesSubscribed })
transport.openConnection()
transport.connected('client-1')
await vi.advanceTimersByTimeAsync(0)
expect(onDirectoriesSubscribed).not.toHaveBeenCalled()
})
it('ignores a subscribe response that resolves after the stream reconnected', async () => {
const transport = new DeferredSubscribeTransport()
const stream = new OpenCodeEventStream({ transport })
const onDirectoriesSubscribed = vi.fn()
stream.subscribeGlobalMonitor({ directories: ['/repo'], onEvent: vi.fn(), onDirectoriesSubscribed })
transport.openConnection()
transport.connected('client-1')
await vi.advanceTimersByTimeAsync(0)
expect(transport.posts).toContainEqual({
path: '/api/sse/subscribe',
body: { clientId: 'client-1', directories: ['/repo'] },
})
transport.fail()
transport.openConnection()
transport.connected('client-2')
transport.resolvePosts()
await vi.advanceTimersByTimeAsync(0)
expect(onDirectoriesSubscribed).not.toHaveBeenCalled()
})
it('does not notify a directory removed while its subscribe request is in flight', async () => {
const transport = new DeferredSubscribeTransport()
const stream = new OpenCodeEventStream({ transport })
const onDirectoriesSubscribed = vi.fn()
const subscription = stream.subscribeGlobalMonitor({
directories: ['/repo'],
onEvent: vi.fn(),
onDirectoriesSubscribed,
})
transport.openConnection()
transport.connected('client-1')
await vi.advanceTimersByTimeAsync(0)
subscription.updateDirectories([])
transport.resolvePosts()
await vi.advanceTimersByTimeAsync(0)
expect(onDirectoriesSubscribed).not.toHaveBeenCalled()
})
})
@@ -14,10 +14,20 @@ interface Subscriber {
onEvent: OpenCodeEventHandler
onStatusChange?: EventStreamStatusHandler
onHealthChange?: (state: EventStreamHealthState) => void
onResync?: () => void
onResync?: (subscribedDirectories: string[]) => void
onDirectoriesSubscribed?: (directories: string[]) => void
directories: Set<string>
}
interface SubscriberInput {
onEvent: OpenCodeEventHandler
onStatusChange?: EventStreamStatusHandler
onHealthChange?: (state: EventStreamHealthState) => void
directories: string[]
onResync?: (subscribedDirectories: string[]) => void
onDirectoriesSubscribed?: (directories: string[]) => void
}
interface OpenCodeEventStreamOptions {
transport?: EventStreamTransport
}
@@ -45,14 +55,8 @@ export class OpenCodeEventStream {
this.transport = options.transport ?? createBrowserEventStreamTransport()
}
subscribeGlobalMonitor(input: {
directories: string[]
onEvent: OpenCodeEventHandler
onStatusChange?: EventStreamStatusHandler
onHealthChange?: (state: EventStreamHealthState) => void
onResync?: () => void
}): GlobalMonitorSubscription {
const id = this.addSubscriber(input.onEvent, input.onStatusChange, input.onHealthChange, input.directories, input.onResync)
subscribeGlobalMonitor(input: SubscriberInput): GlobalMonitorSubscription {
const id = this.addSubscriber(input)
return {
updateDirectories: (directories) => this.updateSubscriberDirectories(id, directories),
@@ -66,13 +70,8 @@ export class OpenCodeEventStream {
return this.buildHealth()
}
private addSubscriber(
onEvent: OpenCodeEventHandler,
onStatusChange?: EventStreamStatusHandler,
onHealthChange?: (state: EventStreamHealthState) => void,
directories: string[] = [],
onResync?: () => void,
): string {
private addSubscriber(input: SubscriberInput): string {
const { onEvent, onStatusChange, onHealthChange, directories, onResync, onDirectoriesSubscribed } = input
const id = `sub_${++this.subscriberIdCounter}`
const initialDirectories = new Set(directories.filter(Boolean))
@@ -96,6 +95,7 @@ export class OpenCodeEventStream {
onStatusChange,
onHealthChange,
onResync,
onDirectoriesSubscribed,
directories: initialDirectories,
})
@@ -400,9 +400,10 @@ export class OpenCodeEventStream {
private handleResync(): void {
this.markActivity()
const directories = Array.from(this.directoryRefCounts.keys())
this.subscribers.forEach((subscriber) => {
try {
subscriber.onResync?.()
subscriber.onResync?.(directories)
} catch {
void 0
}
@@ -422,15 +423,35 @@ export class OpenCodeEventStream {
private async subscribeToRemoteDirectories(directories: string[]): Promise<void> {
if (!this.clientId || directories.length === 0) return
const clientId = this.clientId
const success = await this.transport.post('/api/sse/subscribe', {
clientId: this.clientId,
clientId,
directories,
})
if (this.clientId !== clientId) return
if (!success) {
directories.forEach((directory) => this.pendingDirectories.add(directory))
this.reconnect()
return
}
const subscribedDirectories = directories.filter((directory) => this.directoryRefCounts.has(directory))
if (subscribedDirectories.length === 0) return
this.notifyDirectoriesSubscribed(subscribedDirectories)
}
private notifyDirectoriesSubscribed(directories: string[]): void {
this.subscribers.forEach((subscriber) => {
try {
subscriber.onDirectoriesSubscribed?.(directories)
} catch {
void 0
}
})
}
private flushPendingDirectories(): void {
@@ -0,0 +1,118 @@
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, 0)).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, 0)).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, 0)).toEqual([])
})
it('excludes messages hidden within the bottom inset and includes messages straddling it', () => {
const container = buildContainer()
appendMessageElement(container, 'hidden', 85, 95)
appendMessageElement(container, 'straddling', 75, 95)
const messages: SessionMessageInfo[] = [
assistantMessage('hidden', ['hidden']),
assistantMessage('straddling', ['straddling']),
]
expect(collectVisibleAssistantTexts(container, messages, 20)).toEqual(['straddling'])
})
})
+22
View File
@@ -0,0 +1,22 @@
import { type SessionMessageInfo } from '@opencode-manager/shared/opencode'
import { getAssistantText } from '@/hooks/useAutoPlayLastResponse'
export function collectVisibleAssistantTexts(
container: HTMLElement,
messages: SessionMessageInfo[],
bottomInset: number,
): string[] {
const containerRect = container.getBoundingClientRect()
const textById = new Map(
messages
.filter((message) => message.type === 'assistant')
.map((message) => [message.id, getAssistantText(message).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 - bottomInset
})
.map((element) => textById.get(element.dataset.messageId ?? '') ?? '')
.filter((text) => text.length > 0)
}
+10
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 { useSpeakVisibleMessages } from "@/hooks/useSpeakVisibleMessages";
import { showToast } from "@/lib/toast";
import { getWorkspaceFilePath } from "@/lib/markdownLinks";
import { getRepoDisplayName } from "@/lib/utils";
@@ -614,6 +615,12 @@ export function SessionDetail() {
scrollByUser((direction * container.clientHeight) / 2);
}, [scrollByUser]);
const handleSpeakVisibleMessages = useSpeakVisibleMessages(
messageContainerRef,
messages,
promptOverlayHeight + inputBottomOffset,
);
useShortcutActions({
selectModel: handleOpenModelDialog,
sessions: handleShowSessionsDialog,
@@ -633,6 +640,7 @@ export function SessionDetail() {
clearPrompt: handleClearPrompt,
halfPageUp: () => scrollMessagesByHalfPage(-1),
halfPageDown: () => scrollMessagesByHalfPage(1),
speakVisible: handleSpeakVisibleMessages,
});
const handleUndoMessage = useCallback((restoredPrompt: string) => {
@@ -768,6 +776,8 @@ export function SessionDetail() {
<FloatingTTSButton
messageId={latestPlayableAssistant.messageId}
content={latestPlayableAssistant.text}
isScrolledUp={showScrollButton}
onSpeakVisible={handleSpeakVisibleMessages}
/>
)}
{hasPromptContent && !isSessionActive && (
+40 -3
View File
@@ -75,11 +75,29 @@ interface PermissionLike {
action?: unknown
metadata?: unknown
resources?: unknown
save?: unknown
}
export interface PermissionDetail {
primary: string
secondary?: string
label?: string
}
const PERMISSION_RESOURCE_LABELS: Record<string, { one: string; many: string }> = {
shell: { one: 'Command', many: 'Commands' },
glob: { one: 'Pattern', many: 'Patterns' },
grep: { one: 'Pattern', many: 'Patterns' },
read: { one: 'Path', many: 'Paths' },
list: { one: 'Path', many: 'Paths' },
edit: { one: 'File', many: 'Files' },
external_directory: { one: 'Path', many: 'Paths' },
webfetch: { one: 'URL', many: 'URLs' },
}
function getPermissionResourceLabel(action: string, count: number): string {
const labels = PERMISSION_RESOURCE_LABELS[action] ?? { one: 'Resource', many: 'Resources' }
return count > 1 ? labels.many : labels.one
}
export function getPermissionDetail(input: PermissionLike): PermissionDetail {
@@ -95,18 +113,37 @@ export function getPermissionDetail(input: PermissionLike): PermissionDetail {
const filePath = str(first.file) ?? str(metadata.filepath)
if (filePath) {
const diff = str(first.patch) ?? str(metadata.diff)
return { primary: filePath, secondary: diff ? diff.slice(0, 500) + (diff.length > 500 ? '\n...' : '') : undefined }
return {
primary: filePath,
secondary: diff ? diff.slice(0, 500) + (diff.length > 500 ? '\n...' : '') : undefined,
label: getPermissionResourceLabel('edit', 1),
}
}
break
}
case 'webfetch': {
const url = str(metadata.url)
if (url) return { primary: url }
if (url) return { primary: url, label: getPermissionResourceLabel('webfetch', 1) }
break
}
}
return { primary: resources.join('\n') }
return { primary: resources.join('\n'), label: getPermissionResourceLabel(action, resources.length) }
}
export interface PermissionAlwaysScope {
summary: string
patterns: string[]
}
export function getPermissionAlwaysScope(input: PermissionLike): PermissionAlwaysScope | null {
const action = typeof input.action === 'string' ? input.action : ''
const save = Array.isArray(input.save) ? input.save.filter((item): item is string => typeof item === 'string') : []
if (save.length === 0) return null
if (save.length === 1 && save[0] === '*') {
return { summary: `This will always allow ${action} for this project.`, patterns: [] }
}
return { summary: 'This will always allow the following patterns for this project.', patterns: save }
}
interface FormLike {
+1
View File
@@ -89,6 +89,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;