diff --git a/backend/test/services/notification-format.test.ts b/backend/test/services/notification-format.test.ts index c83e30f7..e7c72a45 100644 --- a/backend/test/services/notification-format.test.ts +++ b/backend/test/services/notification-format.test.ts @@ -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', () => { diff --git a/e2e/background-activity.spec.ts b/e2e/background-activity.spec.ts index ddd6d44a..8bdeaa9f 100644 --- a/e2e/background-activity.spec.ts +++ b/e2e/background-activity.spec.ts @@ -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 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 { @@ -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 { + 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() + }) }) diff --git a/e2e/inline-images.spec.ts b/e2e/inline-images.spec.ts index 88d29402..4af10b54 100644 --- a/e2e/inline-images.spec.ts +++ b/e2e/inline-images.spec.ts @@ -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 { .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 { - 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((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((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}`) diff --git a/e2e/mockProvider.ts b/e2e/mockProvider.ts new file mode 100644 index 00000000..7ad5bff9 --- /dev/null +++ b/e2e/mockProvider.ts @@ -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 +} + +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 { + let mockReply = '' + const server = http.createServer((request, response) => { + handleMockRequest(request, response, () => mockReply) + }) + await new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(port, '127.0.0.1', () => resolve()) + }) + return { + setReply: (text) => { + mockReply = text + }, + close: () => + new Promise((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 { + 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 { + 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() + } +} diff --git a/e2e/tts-floating-button.spec.ts b/e2e/tts-floating-button.spec.ts new file mode 100644 index 00000000..567584f5 --- /dev/null +++ b/e2e/tts-floating-button.spec.ts @@ -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 { + 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 { + 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 { + 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() +}) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 3cd9d97b..ba389943 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -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 ( ) } diff --git a/frontend/src/components/message/FloatingTTSButton.test.tsx b/frontend/src/components/message/FloatingTTSButton.test.tsx index 0e50d4e7..dca77b91 100644 --- a/frontend/src/components/message/FloatingTTSButton.test.tsx +++ b/frontend/src/components/message/FloatingTTSButton.test.tsx @@ -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() + render() 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() + render() expect(screen.getByRole('button', { name: /hold to toggle auto-play/i })).toBeInTheDocument() }) it('calls speakMessage on tap when idle', () => { setup() - render() + render() 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() + render() 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() + render() 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() + render() 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() + render() 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() + render() 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() + render() 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() + render() 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() + render() 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() + render() 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() + render() 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() + render() 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( + + ) + + 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( + + ) + + 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( + + ) + + 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() + }) }) diff --git a/frontend/src/components/message/FloatingTTSButton.tsx b/frontend/src/components/message/FloatingTTSButton.tsx index 5d4198bb..2f67df55 100644 --- a/frontend/src/components/message/FloatingTTSButton.tsx +++ b/frontend/src/components/message/FloatingTTSButton.tsx @@ -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' diff --git a/frontend/src/components/message/MessageThread.tsx b/frontend/src/components/message/MessageThread.tsx index 3045f167..021ff1e5 100644 --- a/frontend/src/components/message/MessageThread.tsx +++ b/frontend/src/components/message/MessageThread.tsx @@ -496,7 +496,7 @@ const MessageRow = memo(function MessageRow({ : 0 return ( -
+
diff --git a/frontend/src/components/session/PermissionRequestDialog.test.tsx b/frontend/src/components/session/PermissionRequestDialog.test.tsx index 0fed0cff..ac99e2b9 100644 --- a/frontend/src/components/session/PermissionRequestDialog.test.tsx +++ b/frontend/src/components/session/PermissionRequestDialog.test.tsx @@ -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() 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( + , + ) + + 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( + , + ) + + expect(screen.getByText('This command modifies tracked files.')).toBeInTheDocument() + }) + + it('describes a wildcard always scope', () => { + render( + , + ) + + expect(screen.getByText('This will always allow shell for this project.')).toBeInTheDocument() + }) + + it('lists the patterns an always decision approves', () => { + render( + , + ) + + 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( + , + ) + + 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( + , + ) + + await userEvent.click(screen.getByRole('button', { name: 'Open session' })) + + expect(onOpenSession).toHaveBeenCalledTimes(1) + }) + + it('omits the open session control without a handler', () => { + render() + + 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() diff --git a/frontend/src/components/session/PermissionRequestDialog.tsx b/frontend/src/components/session/PermissionRequestDialog.tsx index 9389ab40..43b2670d 100644 --- a/frontend/src/components/session/PermissionRequestDialog.tsx +++ b/frontend/src/components/session/PermissionRequestDialog.tsx @@ -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}
- + + {permission.message && ( +

{permission.message}

+ )} + {details.primary && ( -
-
-                {details.primary}
-              
+
+ {details.label && ( + {details.label} + )} +
+
+                  {details.primary}
+                
+
)} - + {details.secondary && (
@@ -114,19 +130,32 @@ export function PermissionRequestDialog({
 
           
{repoDirectory && ( -
+
Repo: {repoDirectory.split('/').pop() ?? repoDirectory}
)} - {isFromDifferentSession ? ( -
- From another session: {displaySessionName} -
- ) : ( -
- Session: {displaySessionName} -
- )} +
+ {isFromDifferentSession ? ( +
+ From another session: {displaySessionName} +
+ ) : ( +
+ Session: {displaySessionName} +
+ )} + {onOpenSession && ( + + )} +
@@ -144,6 +173,19 @@ export function PermissionRequestDialog({ />
+ {alwaysScope && ( +
+

{alwaysScope.summary}

+ {alwaysScope.patterns.length > 0 && ( +
    + {alwaysScope.patterns.map((pattern) => ( +
  • {pattern}
  • + ))} +
+ )} +
+ )} + - + {alwaysScope && ( + + )} + @@ -149,9 +205,9 @@ function createDeferred() { return { promise, resolve } } -function createWrapper(queryClient = createTestQueryClient()) { +function createWrapper(queryClient = createTestQueryClient(), initialPath = '/') { return ({ children }: { children: ReactNode }) => ( - + {children} @@ -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(, { 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(, { 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(, { + 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(, { 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(, { + 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(, { + 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(, { + 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(, { 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(, { + 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(, { + 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(, { + 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(, { + 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(, { + 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(, { + 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(, { + 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(, { 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(, { 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(, { 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>() 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(, { 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(, { 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(, { 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') + }) }) diff --git a/frontend/src/contexts/EventContext.tsx b/frontend/src/contexts/EventContext.tsx index 30745182..10bd23f4 100644 --- a/frontend/src/contexts/EventContext.tsx +++ b/frontend/src/contexts/EventContext.tsx @@ -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, +): boolean { + const visited = new Set() + 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( + items: T[], + viewedSessionId: string | null, + parents: Map, +): T | null { + const [pinnedId, setPinnedId] = useState(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( prev: Record, 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(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(null) const [sseHealth, setSseHealth] = useState(() => { @@ -206,7 +269,6 @@ export function EventProvider({ children }: { children: React.ReactNode }) { const statusPollIntervalRef = useRef | null>(null) const subscriptionRef = useRef | null>(null) const reposRef = useRef(null) - const trackedRepoDirectoriesRef = useRef>(new Set()) const ancestryInFlightRef = useRef>(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, diff --git a/frontend/src/hooks/__tests__/useAutoPlayLastResponse.test.tsx b/frontend/src/hooks/__tests__/useAutoPlayLastResponse.test.tsx index 7f9dbcb7..e2b2996c 100644 --- a/frontend/src/hooks/__tests__/useAutoPlayLastResponse.test.tsx +++ b/frontend/src/hooks/__tests__/useAutoPlayLastResponse.test.tsx @@ -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() diff --git a/frontend/src/hooks/__tests__/useSpeakVisibleMessages.test.tsx b/frontend/src/hooks/__tests__/useSpeakVisibleMessages.test.tsx new file mode 100644 index 00000000..94accd0f --- /dev/null +++ b/frontend/src/hooks/__tests__/useSpeakVisibleMessages.test.tsx @@ -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 + stop: ReturnType + 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 = {}) => { + 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 = { 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 = { 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 = { 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 = { 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 = { 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 = { 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() + }) +}) diff --git a/frontend/src/hooks/useAutoPlayLastResponse.ts b/frontend/src/hooks/useAutoPlayLastResponse.ts index fe8e6d91..33b1894d 100644 --- a/frontend/src/hooks/useAutoPlayLastResponse.ts +++ b/frontend/src/hooks/useAutoPlayLastResponse.ts @@ -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>({}) const hasSeenIncompleteRef = useRef(false) const previousSessionIdRef = useRef(null) + const isUnattributedPlaybackActiveRef = useRef(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, diff --git a/frontend/src/hooks/useSSE.test.tsx b/frontend/src/hooks/useSSE.test.tsx index d014d512..a5997fa3 100644 --- a/frontend/src/hooks/useSSE.test.tsx +++ b/frontend/src/hooks/useSSE.test.tsx @@ -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: { diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.ts index 5d9f18d8..2448b463 100644 --- a/frontend/src/hooks/useSSE.ts +++ b/frontend/src/hooks/useSSE.ts @@ -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 diff --git a/frontend/src/hooks/useSpeakVisibleMessages.ts b/frontend/src/hooks/useSpeakVisibleMessages.ts new file mode 100644 index 00000000..a957110e --- /dev/null +++ b/frontend/src/hooks/useSpeakVisibleMessages.ts @@ -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, + 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]) +} diff --git a/frontend/src/lib/opencode-event-stream/__tests__/openCodeEventStream.test.ts b/frontend/src/lib/opencode-event-stream/__tests__/openCodeEventStream.test.ts index 5d41f0bf..1e4fbb3a 100644 --- a/frontend/src/lib/opencode-event-stream/__tests__/openCodeEventStream.test.ts +++ b/frontend/src/lib/opencode-event-stream/__tests__/openCodeEventStream.test.ts @@ -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 { + this.posts.push({ path, body }) + return false + } +} + +class DeferredSubscribeTransport extends TestEventStreamTransport { + private resolvers: Array<(value: boolean) => void> = [] + + override post(path: string, body: unknown): Promise { + this.posts.push({ path, body }) + return new Promise((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() + }) }) diff --git a/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts b/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts index 715f058a..32598c26 100644 --- a/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts +++ b/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts @@ -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 } +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 { 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 { diff --git a/frontend/src/lib/visibleMessageTexts.test.ts b/frontend/src/lib/visibleMessageTexts.test.ts new file mode 100644 index 00000000..68c57f01 --- /dev/null +++ b/frontend/src/lib/visibleMessageTexts.test.ts @@ -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']) + }) +}) diff --git a/frontend/src/lib/visibleMessageTexts.ts b/frontend/src/lib/visibleMessageTexts.ts new file mode 100644 index 00000000..df251942 --- /dev/null +++ b/frontend/src/lib/visibleMessageTexts.ts @@ -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('[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) +} diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index 325efade..6ae9795e 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -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() { )} {hasPromptContent && !isSessionActive && ( diff --git a/shared/src/notifications/format.ts b/shared/src/notifications/format.ts index 379bb5a1..910c391f 100644 --- a/shared/src/notifications/format.ts +++ b/shared/src/notifications/format.ts @@ -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 = { + 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 { diff --git a/shared/src/schemas/settings.ts b/shared/src/schemas/settings.ts index 6e4efe58..9d4f6dda 100644 --- a/shared/src/schemas/settings.ts +++ b/shared/src/schemas/settings.ts @@ -89,6 +89,7 @@ export const DEFAULT_KEYBOARD_SHORTCUTS = { exportSession: 'X', halfPageUp: 'Ctrl+U', halfPageDown: 'Ctrl+D', + speakVisible: 'S', } satisfies Record; export type KeyboardShortcutAction = keyof typeof DEFAULT_KEYBOARD_SHORTCUTS;