diff --git a/.env.example b/.env.example index 193b2654..a1a29a26 100644 --- a/.env.example +++ b/.env.example @@ -17,6 +17,11 @@ LOG_LEVEL=info OPENCODE_SERVER_PORT=5551 OPENCODE_HOST=127.0.0.1 +# Optional - bearer password required to talk to the spawned OpenCode server. +# When set, the backend spawns OpenCode with this password and attaches it to +# every proxied request. Leave unset to disable OpenCode-level auth. +# OPENCODE_SERVER_PASSWORD= + # Optional - import an existing standalone OpenCode install on first startup # Useful for Docker when your host OpenCode data is bind-mounted into the container # OPENCODE_IMPORT_CONFIG_PATH=/import/opencode-config/opencode.json @@ -123,3 +128,10 @@ PASSKEY_ORIGIN=http://localhost:5003 # VITE_OPENCODE_PORT=5551 # VITE_MAX_FILE_SIZE_MB=50 # VITE_MAX_UPLOAD_SIZE_MB=50 + +# ============================================ +# Workspace Plugin Configuration +# For connecting OpenCode TUI to opencode-manager +# ============================================ +# OPENCODE_MANAGER_URL=http://localhost:5003 +# OPENCODE_MANAGER_TOKEN= diff --git a/README.md b/README.md index 410cff26..54c4130a 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ For local development setup, see the [Development Guide](https://chriswritescode - **AI** — Model selection, provider config, OAuth for Anthropic/GitHub Copilot, custom agents with system prompts - **MCP** — Local and remote MCP server support with pre-built templates - **Memory** — Persistent project knowledge with semantic search ([plugin repo](https://github.com/chriswritescode-dev/opencode-memory)) and compaction awareness +- **Workspace Plugin** — Connect OpenCode TUI to opencode-manager for remote workspace access - **Mobile** — Responsive UI, PWA installable, iOS-optimized with proper keyboard handling and swipe navigation ## Configuration diff --git a/backend/package.json b/backend/package.json index 9589e2f6..959b97e0 100644 --- a/backend/package.json +++ b/backend/package.json @@ -26,6 +26,7 @@ "hono": "^4.11.7", "jsonc-parser": "^3.3.1", "web-push": "^3.6.7", + "ws": "^8.20.0", "zod": "^4.1.12" }, "devDependencies": { @@ -35,6 +36,7 @@ "@types/bun": "latest", "@types/eventsource": "^3.0.0", "@types/web-push": "^3.6.4", + "@types/ws": "^8.18.1", "@vitest/coverage-v8": "^3.2.4", "@vitest/ui": "^3.2.4", "eslint": "^9.39.1", diff --git a/backend/src/auth/middleware.ts b/backend/src/auth/middleware.ts index 544f8bdd..d3663c04 100644 --- a/backend/src/auth/middleware.ts +++ b/backend/src/auth/middleware.ts @@ -1,28 +1,72 @@ import { createMiddleware } from 'hono/factory' +import type { Database } from 'bun:sqlite' import type { AuthInstance, Session } from './index' +import { ApiTokenService } from '../services/api-tokens' import { logger } from '../utils/logger' -export function createAuthMiddleware(auth: AuthInstance) { +interface UserRow { + id: string + name: string + email: string + emailVerified: number | boolean | null + image: string | null + createdAt: string | number | null + updatedAt: string | number | null + role: string | null +} + +function loadUserById(db: Database, userId: string): Session['user'] | null { + const row = db + .prepare('SELECT id, name, email, emailVerified, image, createdAt, updatedAt, role FROM "user" WHERE id = ?') + .get(userId) as UserRow | undefined + + if (!row) return null + + const toDate = (value: string | number | null): Date => { + if (!value) return new Date() + const d = new Date(value) + return Number.isNaN(d.getTime()) ? new Date() : d + } + + return { + id: row.id, + name: row.name, + email: row.email, + emailVerified: Boolean(row.emailVerified), + image: row.image, + createdAt: toDate(row.createdAt), + updatedAt: toDate(row.updatedAt), + role: row.role ?? undefined, + } +} + +export function createAuthMiddleware( + auth: AuthInstance, + apiTokenService?: ApiTokenService, + db?: Database, +) { return createMiddleware<{ Variables: { session: Session['session'] user: Session['user'] + tokenScope?: string } }>(async (c, next) => { const cookies = c.req.header('cookie') const origin = c.req.header('origin') - + logger.debug(`Auth check - Path: ${c.req.path}, Origin: ${origin}, Has cookies: ${!!cookies}`) if (cookies) { const cookieNames = cookies.split(';').map(c => c.trim().split('=')[0]).join(', ') logger.debug(`Cookie names: ${cookieNames}`) } - - let session + + let session: Session | null = null try { - session = await auth.api.getSession({ + const result = await auth.api.getSession({ headers: c.req.raw.headers, }) + session = (result as Session | null) ?? null } catch (error) { logger.error('Session lookup failed', { error }) return c.json({ error: 'Internal Server Error' }, 500) @@ -30,14 +74,47 @@ export function createAuthMiddleware(auth: AuthInstance) { logger.debug(`Session result: ${session ? 'found' : 'not found'}`) + let tokenScope: string | undefined + + if (!session && apiTokenService) { + const authHeader = c.req.header('authorization') + if (authHeader?.startsWith('Bearer ')) { + const raw = authHeader.slice(7).trim() + const verified = apiTokenService.verify(raw) + if (verified) { + tokenScope = verified.scope + + const realUser = db ? loadUserById(db, verified.userId) : null + if (!realUser) { + logger.warn(`Bearer token references unknown user ${verified.userId}`) + return c.json({ error: 'Unauthorized' }, 401) + } + + session = { + session: { + id: `token-${verified.id}`, + userId: verified.userId, + token: 'bearer', + expiresAt: new Date(), + createdAt: new Date(), + updatedAt: new Date(), + }, + user: realUser, + } + logger.debug(`Bearer token verified for user ${verified.userId} (scope: ${verified.scope})`) + } + } + } + if (!session) { return c.json({ error: 'Unauthorized' }, 401) } - c.set('session', session.session as Session['session']) - c.set('user', session.user as Session['user']) + c.set('session', session.session) + c.set('user', session.user) + if (tokenScope !== undefined) { + c.set('tokenScope', tokenScope) + } await next() }) } - - diff --git a/backend/src/db/migrations/012-api-tokens.ts b/backend/src/db/migrations/012-api-tokens.ts new file mode 100644 index 00000000..97f03a70 --- /dev/null +++ b/backend/src/db/migrations/012-api-tokens.ts @@ -0,0 +1,30 @@ +import type { Migration } from '../migration-runner' + +const migration: Migration = { + version: 12, + name: 'api-tokens', + + up(db) { + db.run(` + CREATE TABLE IF NOT EXISTS api_tokens ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + name TEXT NOT NULL, + token_hash TEXT NOT NULL UNIQUE, + scope TEXT NOT NULL DEFAULT 'workspace-plugin', + last_used_at INTEGER, + created_at INTEGER NOT NULL, + expires_at INTEGER + ) + `) + + db.run('CREATE INDEX IF NOT EXISTS idx_api_tokens_hash ON api_tokens(token_hash)') + db.run('CREATE INDEX IF NOT EXISTS idx_api_tokens_user ON api_tokens(user_id)') + }, + + down(db) { + db.run('DROP TABLE IF EXISTS api_tokens') + }, +} + +export default migration diff --git a/backend/src/db/migrations/index.ts b/backend/src/db/migrations/index.ts index d2ae1e91..3f6d7470 100644 --- a/backend/src/db/migrations/index.ts +++ b/backend/src/db/migrations/index.ts @@ -10,6 +10,7 @@ import migration008 from './008-schedule-cron-support' import migration009 from './009-repo-source-path' import migration010 from './009-prompt-templates' import migration011 from './011-repo-last-accessed' +import migration012 from './012-api-tokens' export const allMigrations: Migration[] = [ migration001, @@ -23,4 +24,5 @@ export const allMigrations: Migration[] = [ migration009, migration010, migration011, + migration012, ] diff --git a/backend/src/index.ts b/backend/src/index.ts index 87f6d9d3..6c63fc04 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -26,7 +26,6 @@ async function getAppVersion(): Promise { } import { createProvidersRoutes } from './routes/providers' import { createOAuthRoutes } from './routes/oauth' -import { createTitleRoutes } from './routes/title' import { createSSERoutes } from './routes/sse' import { createSSHRoutes } from './routes/ssh' import { createNotificationRoutes } from './routes/notifications' @@ -47,6 +46,12 @@ import { migrateGlobalSkills } from './services/skills' import { getOpenCodeImportStatus, syncOpenCodeImport } from './services/opencode-import' import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas' import { parse as parseJsonc } from 'jsonc-parser' +import { ApiTokenService } from './services/api-tokens' +import { createApiTokenRoutes } from './routes/api-tokens' +import { createWorkspacePluginRoutes } from './routes/workspace-plugin' +import { attachWorkspacePluginWs } from './services/proxy-ws' +import type { Server } from 'node:http' +import { listRepos } from './db/queries' import { logger } from './utils/logger' import { @@ -79,7 +84,8 @@ app.use('/*', cors({ const db = initializeDatabase(DB_PATH) const auth = createAuth(db) -const requireAuth = createAuthMiddleware(auth) +const apiTokenService = new ApiTokenService(db) +const requireAuth = createAuthMiddleware(auth, apiTokenService, db) import { DEFAULT_AGENTS_MD } from './constants' @@ -261,12 +267,13 @@ protectedApi.use('/*', requireAuth) protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService)) protectedApi.route('/settings', createSettingsRoutes(db, gitAuthService)) +protectedApi.route('/settings/tokens', createApiTokenRoutes(apiTokenService)) +protectedApi.route('/workspace-plugin', createWorkspacePluginRoutes(db)) protectedApi.route('/files', createFileRoutes()) protectedApi.route('/providers', createProvidersRoutes()) protectedApi.route('/oauth', createOAuthRoutes()) protectedApi.route('/tts', createTTSRoutes(db)) protectedApi.route('/stt', createSTTRoutes(db)) -protectedApi.route('/generate-title', createTitleRoutes()) protectedApi.route('/sse', createSSERoutes()) protectedApi.route('/ssh', createSSHRoutes(gitAuthService)) protectedApi.route('/notifications', createNotificationRoutes(notificationService)) @@ -288,9 +295,19 @@ app.post('/api/opencode/mcp/:name/auth/authenticate', requireAuth, async (c) => return proxyMcpAuthAuthenticate(serverName, directory) }) +const projectService: import('./services/proxy').ProxyProjectService = { + getBySlug: (slug: string) => { + const settings = new SettingsService(db).getSettings() + const repos = listRepos(db, settings.preferences.repoOrder) + const repo = repos.find((r) => r.id.toString() === slug) + if (!repo) return null + return { directory: repo.fullPath } + }, +} + app.all('/api/opencode/*', requireAuth, async (c) => { const request = c.req.raw - return proxyRequest(request) + return proxyRequest(request, projectService) }) const isProduction = ENV.SERVER.NODE_ENV === 'production' @@ -388,10 +405,28 @@ const shutdown = async (signal: string) => { process.on('SIGTERM', () => shutdown('SIGTERM')) process.on('SIGINT', () => shutdown('SIGINT')) -serve({ +const server = serve({ fetch: app.fetch, port: PORT, hostname: HOST, +}) as unknown as Server + +import { OPENCODE_SERVER_URL } from './services/proxy' + +attachWorkspacePluginWs(server, { + upstreamBaseUrl: OPENCODE_SERVER_URL, + verifyAuth: async (headers) => { + const authHeader = headers.get('authorization') + if (authHeader?.startsWith('Bearer ')) { + const raw = authHeader.slice(7).trim() + const verified = apiTokenService.verify(raw) + if (verified) { + return { userId: verified.userId, scope: verified.scope } + } + } + return null + }, + projectService, }) logger.info(`🚀 OpenCode WebUI API running on http://${HOST}:${PORT}`) diff --git a/backend/src/routes/api-tokens.ts b/backend/src/routes/api-tokens.ts new file mode 100644 index 00000000..7089725d --- /dev/null +++ b/backend/src/routes/api-tokens.ts @@ -0,0 +1,102 @@ +import { Hono } from 'hono' +import { z } from 'zod' +import { ApiTokenService } from '../services/api-tokens' +import { logger } from '../utils/logger' +import type { Session } from '../auth' + +type AppVariables = { + session: Session['session'] + user: Session['user'] +} + +const CreateTokenSchema = z.object({ + name: z.string().min(1).max(255), + scope: z.string().optional().default('workspace-plugin'), + expiresAt: z.number().optional(), +}) + +export function createApiTokenRoutes(apiTokenService: ApiTokenService) { + const app = new Hono<{ Variables: AppVariables }>() + + app.get('/', async (c) => { + try { + const session = c.get('session') + if (!session) { + return c.json({ error: 'Unauthorized' }, 401) + } + + const tokens = apiTokenService.list(session.userId) + return c.json({ + tokens: tokens.map(t => ({ + id: t.id, + name: t.name, + scope: t.scope, + lastUsedAt: t.lastUsedAt, + createdAt: t.createdAt, + expiresAt: t.expiresAt, + })), + }) + } catch (error) { + logger.error('Failed to list API tokens:', error) + return c.json({ error: 'Failed to list API tokens' }, 500) + } + }) + + app.post('/', async (c) => { + try { + const session = c.get('session') + if (!session) { + return c.json({ error: 'Unauthorized' }, 401) + } + + const body = await c.req.json() + const validated = CreateTokenSchema.parse(body) + + const result = apiTokenService.create( + session.userId, + validated.name, + validated.scope, + validated.expiresAt, + ) + + logger.info(`Created API token '${result.name}' for user ${session.userId}`) + + return c.json({ + id: result.id, + name: result.name, + token: result.token, + }) + } catch (error) { + logger.error('Failed to create API token:', error) + if (error instanceof z.ZodError) { + return c.json({ error: 'Invalid token data', details: error.issues }, 400) + } + return c.json({ error: 'Failed to create API token' }, 500) + } + }) + + app.delete('/:id', async (c) => { + try { + const session = c.get('session') + if (!session) { + return c.json({ error: 'Unauthorized' }, 401) + } + + const id = c.req.param('id') + const revoked = apiTokenService.revoke(session.userId, id) + + if (!revoked) { + return c.json({ error: 'Token not found' }, 404) + } + + logger.info(`Revoked API token '${id}' for user ${session.userId}`) + + return c.json({ success: true }) + } catch (error) { + logger.error('Failed to revoke API token:', error) + return c.json({ error: 'Failed to revoke API token' }, 500) + } + }) + + return app +} diff --git a/backend/src/routes/mcp-oauth-proxy.ts b/backend/src/routes/mcp-oauth-proxy.ts index 9850f6dd..a193a649 100644 --- a/backend/src/routes/mcp-oauth-proxy.ts +++ b/backend/src/routes/mcp-oauth-proxy.ts @@ -6,7 +6,7 @@ import { readFile, writeFile, mkdir } from 'fs/promises' import { storeMcpOAuthFlow, consumeMcpOAuthFlow, deleteMcpOAuthFlow, markMcpOAuthFlowCompleted, markMcpOAuthFlowFailed, getMcpOAuthFlowResult } from '../services/mcp-oauth-state' import { logger } from '../utils/logger' import { getWorkspacePath } from '@opencode-manager/shared/config/env' -import { OPENCODE_SERVER_URL } from '../services/proxy' +import { OPENCODE_SERVER_URL, withOpenCodeAuth } from '../services/proxy' const StartSchema = z.object({ serverName: z.string(), @@ -300,11 +300,13 @@ export function createMcpOauthProxyRoutes(requireAuth?: any) { } await fetch(reconnectUrl, { method: 'POST', + headers: withOpenCodeAuth(), }) if (flow.directory) { const globalReconnectUrl = `${OPENCODE_SERVER_URL}/mcp/${encodeURIComponent(flow.serverName)}/connect` await fetch(globalReconnectUrl, { method: 'POST', + headers: withOpenCodeAuth(), }) } } catch { diff --git a/backend/src/routes/memory.ts b/backend/src/routes/memory.ts index e41fad0b..68f75576 100644 --- a/backend/src/routes/memory.ts +++ b/backend/src/routes/memory.ts @@ -8,7 +8,7 @@ import { resolveProjectId } from '../services/project-id-resolver' import { getRepoById } from '../db/queries' import { getWorkspacePath, getConfigPath } from '@opencode-manager/shared/config/env' import { parseJsonc } from '@opencode-manager/shared/utils' -import { OPENCODE_SERVER_URL } from '../services/proxy' +import { OPENCODE_SERVER_URL, withOpenCodeAuth } from '../services/proxy' import { CreateMemoryRequestSchema, UpdateMemoryRequestSchema, @@ -640,7 +640,7 @@ export function createMemoryRoutes(db: Database): Hono { try { const abortUrl = new URL(`${OPENCODE_SERVER_URL}/session/${state.sessionId}/abort`) abortUrl.searchParams.set('directory', repo.fullPath) - await fetch(abortUrl.toString(), { method: 'POST' }) + await fetch(abortUrl.toString(), { method: 'POST', headers: withOpenCodeAuth() }) } catch { // Session may already be idle } diff --git a/backend/src/routes/title.ts b/backend/src/routes/title.ts deleted file mode 100644 index 25c17f10..00000000 --- a/backend/src/routes/title.ts +++ /dev/null @@ -1,228 +0,0 @@ -import { Hono } from 'hono' -import { z } from 'zod' -import { logger } from '../utils/logger' -import { resolveOpenCodeModel } from '../services/opencode-models' -import { OPENCODE_SERVER_URL } from '../services/proxy' - -const TitleRequestSchema = z.object({ - text: z.string().min(1).max(5000), - sessionID: z.string().min(1) -}) -const TITLE_POLL_INTERVAL_MS = 1_000 -const TITLE_POLL_TIMEOUT_MS = 30_000 - -interface PromptResponse { - parts?: Array<{ type?: string; text?: string }> -} - -interface SessionMessage { - info?: { - role?: string - time?: { - completed?: number - } - error?: { - name?: string - data?: { - message?: string - } - } - } - parts?: Array<{ type?: string; text?: string }> -} - -function buildUrl(path: string, directory?: string): string { - const url = `${OPENCODE_SERVER_URL}${path}` - return directory ? `${url}${url.includes('?') ? '&' : '?'}directory=${encodeURIComponent(directory)}` : url -} - -function parsePromptResponse(responseText: string): PromptResponse | null { - if (!responseText.trim()) { - return null - } - - try { - return JSON.parse(responseText) as PromptResponse - } catch { - return null - } -} - -function extractText(parts: Array<{ type?: string; text?: string }> | undefined): string { - return (parts ?? []) - .filter((part) => part.type === 'text' && typeof part.text === 'string') - .map((part) => part.text?.replace(/[\s\S]*?<\/think>\s*/g, '').trim() ?? '') - .filter(Boolean) - .join('\n') -} - -function extractTitle(result: PromptResponse | SessionMessage): string { - const text = extractText(result.parts) - const title = text - .split('\n') - .map((line) => line.trim()) - .find((line) => line.length > 0) || '' - - if (title.length > 100) { - return title.substring(0, 97) + '...' - } - - return title -} - -async function waitForTitleResponse(sessionID: string, directory: string): Promise { - const startedAt = Date.now() - - while (Date.now() - startedAt < TITLE_POLL_TIMEOUT_MS) { - const messagesResponse = await fetch(buildUrl(`/session/${sessionID}/message`, directory)) - - if (!messagesResponse.ok) { - const errorText = await messagesResponse.text() - throw new Error(errorText || 'Failed to fetch title generation messages') - } - - const messages = await messagesResponse.json() as SessionMessage[] - const assistantMessage = [...messages] - .reverse() - .find((message) => message.info?.role === 'assistant') - - if (assistantMessage) { - const errorText = assistantMessage.info?.error?.data?.message ?? assistantMessage.info?.error?.name - if (errorText) { - throw new Error(errorText) - } - - if (assistantMessage.info?.time?.completed) { - return assistantMessage - } - } - - await Bun.sleep(TITLE_POLL_INTERVAL_MS) - } - - throw new Error('Timed out waiting for title generation') -} - -const TITLE_PROMPT = `You are a title generator. You output ONLY a thread title. Nothing else. - - -Generate a brief title that would help the user find this conversation later. - -Follow all rules in -Use the so you know what a good title looks like. -Your output must be: -- A single line -- ≤50 characters -- No explanations - - - -- Focus on the main topic or question the user needs to retrieve -- Use -ing verbs for actions (Debugging, Implementing, Analyzing) -- Keep exact: technical terms, numbers, filenames, HTTP codes -- Remove: the, this, my, a, an -- Never assume tech stack -- Never use tools -- NEVER respond to questions, just generate a title for the conversation -- The title should NEVER include "summarizing" or "generating" when generating a title -- DO NOT SAY YOU CANNOT GENERATE A TITLE OR COMPLAIN ABOUT THE INPUT -- Always output something meaningful, even if the input is minimal. -- If the user message is short or conversational (e.g. "hello", "lol", "whats up", "hey"): - → create a title that reflects the user's tone or intent (such as Greeting, Quick check-in, Light chat, Intro message, etc.) - - - -"debug 500 errors in production" → Debugging production 500 errors -"refactor user service" → Refactoring user service -"why is app.js failing" → Analyzing app.js failure -"implement rate limiting" → Implementing rate limiting -"how do I connect postgres to my API" → Connecting Postgres to API -"best practices for React hooks" → React hooks best practices -` - -export function createTitleRoutes() { - const app = new Hono() - - app.post('/', async (c) => { - try { - const body = await c.req.json() - const { text, sessionID } = TitleRequestSchema.parse(body) - const directory = c.req.header('directory') || '' - - logger.info('Generating session title via LLM', { sessionID, textLength: text.length }) - - const model = await resolveOpenCodeModel(directory || undefined, { - preferSmallModel: true, - }) - - const titleSessionResponse = await fetch(buildUrl('/session', directory), { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ title: 'Title Generation' }) - }) - - if (!titleSessionResponse.ok) { - logger.error('Failed to create title generation session') - return c.json({ error: 'Failed to create session' }, 500) - } - - const titleSession = await titleSessionResponse.json() as { id: string } - const titleSessionID = titleSession.id - - try { - const promptResponse = await fetch(buildUrl(`/session/${titleSessionID}/message`, directory), { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - parts: [ - { - type: 'text', - text: `${TITLE_PROMPT}\n\nGenerate a title for this conversation:\n\n${text.substring(0, 2000)}\n` - } - ], - model: { - providerID: model.providerID, - modelID: model.modelID, - } - }) - }) - - if (!promptResponse.ok) { - const errorText = await promptResponse.text() - logger.error('Failed to generate title via LLM', { error: errorText }) - return c.json({ error: 'LLM request failed' }, 500) - } - - const promptBody = await promptResponse.text() - const promptResult = parsePromptResponse(promptBody) - const title = extractTitle(promptResult ?? await waitForTitleResponse(titleSessionID, directory)) - - if (title) { - const updateResponse = await fetch(buildUrl(`/session/${sessionID}`, directory), { - method: 'PATCH', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ title }) - }) - - if (!updateResponse.ok) { - logger.error('Failed to update session title') - } - } - - logger.info('Session title generated', { sessionID, title }) - return c.json({ title }) - - } finally { - fetch(buildUrl(`/session/${titleSessionID}`, directory), { - method: 'DELETE' - }).catch(() => {}) - } - - } catch (error) { - logger.error('Failed to generate session title:', error) - return c.json({ error: error instanceof Error ? error.message : 'Failed to generate title' }, 500) - } - }) - - return app -} diff --git a/backend/src/routes/workspace-plugin.ts b/backend/src/routes/workspace-plugin.ts new file mode 100644 index 00000000..616dbe68 --- /dev/null +++ b/backend/src/routes/workspace-plugin.ts @@ -0,0 +1,64 @@ +import { Hono } from 'hono' +import type { Database } from 'bun:sqlite' +import { listRepos } from '../db/queries' +import { SettingsService } from '../services/settings' +import { logger } from '../utils/logger' +import type { Session } from '../auth' + +type AppVariables = { + session: Session['session'] + user: Session['user'] + tokenScope?: string +} + +export interface ProjectInfo { + slug: string + name: string + directory: string + description?: string +} + +const ALLOWED_WORKSPACE_PLUGIN_SCOPES = new Set(['*', 'workspace-plugin']) + +export function createWorkspacePluginRoutes(db: Database) { + const app = new Hono<{ Variables: AppVariables }>() + + app.get('/projects', async (c) => { + try { + const session = c.get('session') + if (!session) { + return c.json({ error: 'Unauthorized' }, 401) + } + + const tokenScope = c.get('tokenScope') + if (tokenScope !== undefined && !ALLOWED_WORKSPACE_PLUGIN_SCOPES.has(tokenScope)) { + logger.warn(`Token with scope '${tokenScope}' attempted to access workspace-plugin endpoint`) + return c.json({ error: 'Forbidden: insufficient token scope' }, 403) + } + + const settingsService = new SettingsService(db) + const settings = settingsService.getSettings() + const repos = listRepos(db, settings.preferences.repoOrder) + + const projects: ProjectInfo[] = repos.map(repo => { + const slug = repo.id.toString() + const name = repo.localPath.split('/').pop() ?? `repo-${repo.id}` + const directory = repo.fullPath + + return { + slug, + name, + directory, + description: repo.repoUrl ?? undefined, + } + }) + + return c.json({ projects }) + } catch (error) { + logger.error('Failed to list projects for workspace plugin:', error) + return c.json({ error: 'Failed to list projects' }, 500) + } + }) + + return app +} diff --git a/backend/src/services/api-tokens.ts b/backend/src/services/api-tokens.ts new file mode 100644 index 00000000..aa54752c --- /dev/null +++ b/backend/src/services/api-tokens.ts @@ -0,0 +1,150 @@ +import { Database } from 'bun:sqlite' +import crypto from 'crypto' + +export interface ApiToken { + id: string + userId: string + name: string + tokenHash: string + scope: string + lastUsedAt: number | null + createdAt: number + expiresAt: number | null +} + +export interface ApiTokenCreateResult { + id: string + name: string + token: string +} + +export interface ApiTokenVerifyResult { + userId: string + scope: string + id: string +} + +export class ApiTokenService { + constructor(private db: Database) {} + + create(userId: string, name: string, scope = 'workspace-plugin', expiresAt?: number): ApiTokenCreateResult { + const id = crypto.randomUUID() + const rawToken = crypto.randomBytes(32).toString('base64url') + const tokenHash = crypto.createHash('sha256').update(rawToken).digest('hex') + const createdAt = Date.now() + + const stmt = this.db.prepare(` + INSERT INTO api_tokens (id, user_id, name, token_hash, scope, created_at, expires_at) + VALUES (?, ?, ?, ?, ?, ?, ?) + `) + + stmt.run(id, userId, name, tokenHash, scope, createdAt, expiresAt ?? null) + + return { id, name, token: rawToken } + } + + list(userId: string): Omit[] { + const stmt = this.db.prepare(` + SELECT id, user_id, name, scope, last_used_at, created_at, expires_at + FROM api_tokens + WHERE user_id = ? + ORDER BY created_at DESC, rowid DESC + `) + + const rows = stmt.all(userId) as Array<{ + id: string + user_id: string + name: string + scope: string + last_used_at: number | null + created_at: number + expires_at: number | null + }> + + return rows.map(row => ({ + id: row.id, + userId: row.user_id, + name: row.name, + scope: row.scope, + lastUsedAt: row.last_used_at, + createdAt: row.created_at, + expiresAt: row.expires_at, + })) + } + + revoke(userId: string, id: string): boolean { + const stmt = this.db.prepare(` + DELETE FROM api_tokens + WHERE id = ? AND user_id = ? + `) + + const result = stmt.run(id, userId) + return result.changes > 0 + } + + verify(rawToken: string): ApiTokenVerifyResult | null { + const tokenHash = crypto.createHash('sha256').update(rawToken).digest('hex') + + const stmt = this.db.prepare(` + SELECT id, user_id, scope, expires_at + FROM api_tokens + WHERE token_hash = ? + `) + + const row = stmt.get(tokenHash) as { id: string; user_id: string; scope: string; expires_at: number | null } | undefined + + if (!row) { + return null + } + + if (row.expires_at && row.expires_at < Date.now()) { + return null + } + + const updateStmt = this.db.prepare(` + UPDATE api_tokens + SET last_used_at = ? + WHERE id = ? + `) + + updateStmt.run(Date.now(), row.id) + + return { + userId: row.user_id, + scope: row.scope, + id: row.id, + } + } + + getById(userId: string, id: string): Omit | null { + const stmt = this.db.prepare(` + SELECT id, user_id, name, scope, last_used_at, created_at, expires_at + FROM api_tokens + WHERE id = ? AND user_id = ? + `) + + const row = stmt.get(id, userId) as { + id: string + user_id: string + name: string + scope: string + last_used_at: number | null + created_at: number + expires_at: number | null + } | undefined + + if (!row) { + return null + } + + return { + id: row.id, + userId: row.user_id, + name: row.name, + scope: row.scope, + lastUsedAt: row.last_used_at, + createdAt: row.created_at, + expiresAt: row.expires_at, + } + } +} diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index 64daf632..c87af2fd 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -24,6 +24,11 @@ import { patchOpenCodeConfig } from './proxy' const OPENCODE_SERVER_PORT = ENV.OPENCODE.PORT const OPENCODE_SERVER_HOST = ENV.OPENCODE.HOST const OPENCODE_SERVER_PUBLIC_URL = ENV.OPENCODE.PUBLIC_URL +const OPENCODE_SERVER_PASSWORD = ENV.OPENCODE.SERVER_PASSWORD +const OPENCODE_SERVER_USERNAME = ENV.OPENCODE.SERVER_USERNAME +const OPENCODE_BASIC_AUTH = OPENCODE_SERVER_PASSWORD + ? `Basic ${Buffer.from(`${OPENCODE_SERVER_USERNAME}:${OPENCODE_SERVER_PASSWORD}`).toString('base64')}` + : '' const MIN_OPENCODE_VERSION = '1.0.137' const MAX_STDERR_SIZE = 10240 @@ -234,6 +239,13 @@ class OpenCodeServerManager { let stderrOutput = '' + const cleanEnv = { ...process.env } + delete cleanEnv.OPENCODE_SERVER_PASSWORD + delete cleanEnv.OPENCODE_RUN_ID + delete cleanEnv.OPENCODE_PROCESS_ROLE + delete cleanEnv.OPENCODE_PID + delete cleanEnv.OPENCODE + this.serverProcess = spawn( 'opencode', ['serve', '--port', OPENCODE_SERVER_PORT.toString(), '--hostname', OPENCODE_SERVER_HOST], @@ -242,13 +254,19 @@ class OpenCodeServerManager { detached: !isDevelopment, stdio: isDevelopment ? 'inherit' : ['ignore', 'pipe', 'pipe'], env: { - ...process.env, + ...cleanEnv, ...gitEnv, ...gitIdentityEnv, GIT_SSH_COMMAND: gitSshCommand, XDG_DATA_HOME: path.join(openCodeServerDirectory, '.opencode/state'), XDG_CONFIG_HOME: path.join(openCodeServerDirectory, '.config'), ...(OPENCODE_SERVER_PUBLIC_URL ? { OPENCODE_PUBLIC_URL: OPENCODE_SERVER_PUBLIC_URL } : {}), + ...(OPENCODE_SERVER_PASSWORD + ? { + OPENCODE_SERVER_PASSWORD, + OPENCODE_SERVER_USERNAME, + } + : {}), OPENCODE_CONFIG: openCodeConfigPath, } } @@ -450,8 +468,13 @@ class OpenCodeServerManager { async checkHealth(): Promise { try { + const headers: Record = {} + if (OPENCODE_BASIC_AUTH) { + headers.Authorization = OPENCODE_BASIC_AUTH + } const response = await fetch(`http://${OPENCODE_SERVER_HOST}:${OPENCODE_SERVER_PORT}/doc`, { - signal: AbortSignal.timeout(3000) + signal: AbortSignal.timeout(3000), + headers }) return response.ok } catch { diff --git a/backend/src/services/proxy-ws.ts b/backend/src/services/proxy-ws.ts new file mode 100644 index 00000000..9bcdb1b6 --- /dev/null +++ b/backend/src/services/proxy-ws.ts @@ -0,0 +1,150 @@ +import type { Server, IncomingMessage } from 'node:http' +import type { Duplex } from 'node:stream' +import { WebSocketServer, WebSocket } from 'ws' +import { logger } from '../utils/logger' +import { OPENCODE_SERVER_URL, withOpenCodeAuth } from './proxy' + +interface AuthResult { + userId: string + scope: string +} + +interface ProjectService { + getBySlug: (slug: string) => { directory: string } | null +} + +export interface WebSocketProxyOptions { + upstreamBaseUrl: string + verifyAuth: (headers: Headers) => Promise + projectService?: ProjectService + pathPrefix?: string +} + +const DEFAULT_PATH_PREFIX = '/api/opencode' + +function rejectUpgrade(socket: Duplex, status: number, reason: string): void { + try { + socket.write(`HTTP/1.1 ${status} ${reason}\r\nConnection: close\r\n\r\n`) + } catch (error) { + logger.debug('Failed to write upgrade rejection:', error) + } + socket.destroy() +} + +function headersFromIncoming(req: IncomingMessage): Headers { + const headers = new Headers() + for (const [key, value] of Object.entries(req.headers)) { + if (value === undefined) continue + headers.set(key, Array.isArray(value) ? value.join(',') : String(value)) + } + return headers +} + +function bridge(client: WebSocket, upstream: WebSocket): void { + const closeBoth = (code = 1000, reason = ''): void => { + if (client.readyState === WebSocket.OPEN || client.readyState === WebSocket.CONNECTING) { + try { client.close(code, reason) } catch { /* ignore */ } + } + if (upstream.readyState === WebSocket.OPEN || upstream.readyState === WebSocket.CONNECTING) { + try { upstream.close(code, reason) } catch { /* ignore */ } + } + } + + client.on('message', (data, isBinary) => { + if (upstream.readyState !== WebSocket.OPEN) return + upstream.send(data, { binary: isBinary }) + }) + + upstream.on('message', (data, isBinary) => { + if (client.readyState !== WebSocket.OPEN) return + client.send(data, { binary: isBinary }) + }) + + client.on('close', (code, reason) => closeBoth(code, reason.toString())) + upstream.on('close', (code, reason) => closeBoth(code, reason.toString())) + + client.on('error', (error) => { + logger.error('Client WebSocket error:', error) + closeBoth(1011, 'client error') + }) + + upstream.on('error', (error) => { + logger.error('Upstream WebSocket error:', error) + closeBoth(1011, 'upstream error') + }) +} + +export function attachWorkspacePluginWs(server: Server, options: WebSocketProxyOptions): void { + const wss = new WebSocketServer({ noServer: true }) + const pathPrefix = options.pathPrefix ?? DEFAULT_PATH_PREFIX + + server.on('upgrade', (req, socket, head) => { + let url: URL + try { + url = new URL(req.url ?? '', OPENCODE_SERVER_URL) + } catch (error) { + logger.debug('Invalid upgrade URL:', error) + rejectUpgrade(socket, 400, 'Bad Request') + return + } + + if (!url.pathname.startsWith(pathPrefix)) { + return + } + + const headers = headersFromIncoming(req) + + void (async () => { + const auth = await options.verifyAuth(headers).catch((error) => { + logger.error('verifyAuth threw:', error) + return null + }) + + if (!auth) { + rejectUpgrade(socket, 401, 'Unauthorized') + return + } + + const remainingPath = url.pathname.slice(pathPrefix.length) || '/' + let targetUrl = `${options.upstreamBaseUrl}${remainingPath}${url.search}` + + const slugHeader = headers.get('x-opencode-manager-project') + if (slugHeader && options.projectService) { + const project = options.projectService.getBySlug(slugHeader) + if (!project) { + rejectUpgrade(socket, 404, 'Not Found') + return + } + const targetUrlObj = new URL(targetUrl) + if (!targetUrlObj.searchParams.has('directory')) { + targetUrlObj.searchParams.set('directory', project.directory) + } + targetUrl = targetUrlObj.toString() + } + + const upstreamWsUrl = (() => { + const u = new URL(targetUrl) + u.protocol = u.protocol === 'https:' ? 'wss:' : 'ws:' + return u.toString() + })() + + logger.info(`Proxying WebSocket upgrade to ${upstreamWsUrl}`) + + const upstreamHeaders = withOpenCodeAuth({}) + const upstream = new WebSocket(upstreamWsUrl, { headers: upstreamHeaders }) + + const onUpstreamError = (error: Error): void => { + logger.error('Upstream WebSocket connect error:', error) + rejectUpgrade(socket, 502, 'Bad Gateway') + } + + upstream.once('error', onUpstreamError) + upstream.once('open', () => { + upstream.off('error', onUpstreamError) + wss.handleUpgrade(req, socket, head, (clientWs) => { + bridge(clientWs, upstream) + }) + }) + })() + }) +} diff --git a/backend/src/services/proxy.ts b/backend/src/services/proxy.ts index 633609f8..06c9e116 100644 --- a/backend/src/services/proxy.ts +++ b/backend/src/services/proxy.ts @@ -3,12 +3,25 @@ import { ENV } from '@opencode-manager/shared/config/env' import { parseJsonc } from '@opencode-manager/shared/utils' export const OPENCODE_SERVER_URL = `http://${ENV.OPENCODE.HOST}:${ENV.OPENCODE.PORT}` +const OPENCODE_SERVER_PASSWORD = ENV.OPENCODE.SERVER_PASSWORD +const OPENCODE_SERVER_USERNAME = ENV.OPENCODE.SERVER_USERNAME + +const OPENCODE_BASIC_AUTH = OPENCODE_SERVER_PASSWORD + ? `Basic ${Buffer.from(`${OPENCODE_SERVER_USERNAME}:${OPENCODE_SERVER_PASSWORD}`).toString('base64')}` + : '' + +export function withOpenCodeAuth(headers: Record = {}): Record { + if (OPENCODE_BASIC_AUTH) { + return { ...headers, Authorization: OPENCODE_BASIC_AUTH } + } + return headers +} export async function setOpenCodeAuth(providerId: string, apiKey: string): Promise { try { const response = await fetch(`${OPENCODE_SERVER_URL}/auth/${providerId}`, { method: 'PUT', - headers: { 'Content-Type': 'application/json' }, + headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }), body: JSON.stringify({ type: 'api', key: apiKey }), }) @@ -29,6 +42,7 @@ export async function deleteOpenCodeAuth(providerId: string): Promise { try { const response = await fetch(`${OPENCODE_SERVER_URL}/auth/${providerId}`, { method: 'DELETE', + headers: withOpenCodeAuth(), }) if (response.ok) { @@ -67,6 +81,15 @@ function getIssuePath(value: unknown): string { } if (typeof value === 'string' && value.length > 0) { + if (value.startsWith('/')) { + const pointerPath = value + .split('/') + .filter(Boolean) + .map((part) => part.replace(/~1/g, '/').replace(/~0/g, '~')) + .join('.') + return pointerPath || 'root' + } + return value } @@ -187,7 +210,7 @@ export async function patchOpenCodeConfig(config: Record): Prom try { const response = await fetch(`${OPENCODE_SERVER_URL}/config`, { method: 'PATCH', - headers: { 'Content-Type': 'application/json' }, + headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }), body: JSON.stringify(config), }) @@ -233,7 +256,7 @@ export async function patchOpenCodeConfig(config: Record): Prom logger.info(`Retrying config patch after removing ${removedFields.length} problematic field(s): ${removedFields.join(', ')}`) const retryResponse = await fetch(`${OPENCODE_SERVER_URL}/config`, { method: 'PATCH', - headers: { 'Content-Type': 'application/json' }, + headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }), body: JSON.stringify(cleanedConfig), }) @@ -264,41 +287,73 @@ export async function patchOpenCodeConfig(config: Record): Prom } } -export async function proxyRequest(request: Request) { +export interface ProxyProjectService { + getBySlug: (slug: string) => { directory: string } | null +} + +const HOP_BY_HOP_REQUEST_HEADERS = new Set(['host', 'connection', 'authorization']) +const HOP_BY_HOP_RESPONSE_HEADERS = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length']) + +export async function proxyRequest(request: Request, projectService?: ProxyProjectService) { const url = new URL(request.url) - + // Remove /api/opencode prefix from pathname before forwarding const cleanPathname = url.pathname.replace(/^\/api\/opencode/, '') - const targetUrl = `${OPENCODE_SERVER_URL}${cleanPathname}${url.search}` - + let targetUrl = `${OPENCODE_SERVER_URL}${cleanPathname}${url.search}` + if (url.pathname.includes('/permissions/')) { logger.info(`Proxying permission request: ${url.pathname}${url.search} -> ${targetUrl}`) } - + + // Handle project slug header translation + const slugHeader = request.headers.get('x-opencode-manager-project') + if (slugHeader && projectService) { + const project = projectService.getBySlug(slugHeader) + if (!project) { + return new Response('Unknown project', { status: 404 }) + } + const targetUrlObj = new URL(targetUrl) + if (!targetUrlObj.searchParams.has('directory')) { + targetUrlObj.searchParams.set('directory', project.directory) + } + targetUrl = targetUrlObj.toString() + } + try { const headers: Record = {} request.headers.forEach((value, key) => { - if (!['host', 'connection'].includes(key.toLowerCase())) { + if (!HOP_BY_HOP_REQUEST_HEADERS.has(key.toLowerCase())) { headers[key] = value } }) - const response = await fetch(targetUrl, { + const fetchOptions: RequestInit & { duplex?: string } = { method: request.method, - headers, - body: request.method !== 'GET' && request.method !== 'HEAD' ? await request.text() : undefined, - }) + headers: withOpenCodeAuth(headers), + } + + if (request.method !== 'GET' && request.method !== 'HEAD') { + // Buffer the request body before forwarding. Streaming with `duplex: 'half'` + // is unreliable across runtimes (Bun vs Node) and breaks when upstream + // middleware has already touched the body. Buffering is safe for typical + // OpenCode payloads (JSON commands, small uploads). + const bodyBuffer = await request.arrayBuffer() + if (bodyBuffer.byteLength > 0) { + fetchOptions.body = bodyBuffer + } + } + + const response = await fetch(targetUrl, fetchOptions) const responseHeaders: Record = {} - const skipHeaders = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length']) response.headers.forEach((value, key) => { - if (!skipHeaders.has(key.toLowerCase())) { + if (!HOP_BY_HOP_RESPONSE_HEADERS.has(key.toLowerCase())) { responseHeaders[key] = value } }) - const body = await response.text() - return new Response(body, { + // Stream the response body for SSE support + return new Response(response.body, { status: response.status, statusText: response.statusText, headers: responseHeaders, @@ -328,7 +383,7 @@ export async function proxyToOpenCodeWithDirectory( try { const response = await fetch(url.toString(), { method, - headers: headers || { 'Content-Type': 'application/json' }, + headers: withOpenCodeAuth(headers || { 'Content-Type': 'application/json' }), body, }) @@ -369,7 +424,7 @@ export async function proxyMcpAuthStart( try { const response = await fetch(url.toString(), { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }), }) const responseBody = await response.text() @@ -400,7 +455,7 @@ export async function proxyMcpAuthAuthenticate( try { const response = await fetch(url.toString(), { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }), }) const responseBody = await response.text() diff --git a/backend/src/utils/git-auth.ts b/backend/src/utils/git-auth.ts index 3a7f338b..7f470fb9 100644 --- a/backend/src/utils/git-auth.ts +++ b/backend/src/utils/git-auth.ts @@ -116,17 +116,6 @@ export function findGitHubCredential(credentials: GitCredential[]): GitCredentia }) || null } -export function getCredentialForHost(credentials: GitCredential[], host: string): GitCredential | undefined { - return credentials.find(cred => { - try { - const parsed = new URL(cred.host) - return parsed.hostname.toLowerCase() === host.toLowerCase() - } catch { - return false - } - }) -} - export function getSSHCredentialsForHost(credentials: GitCredential[], host: string): GitCredential[] { return credentials.filter(cred => { if (cred.type !== 'ssh') return false diff --git a/backend/test/auth/middleware.test.ts b/backend/test/auth/middleware.test.ts new file mode 100644 index 00000000..606ce2f9 --- /dev/null +++ b/backend/test/auth/middleware.test.ts @@ -0,0 +1,155 @@ +import { describe, it, expect, beforeEach } from 'vitest' +import { Hono } from 'hono' +import { Database } from 'bun:sqlite' +import { createAuth } from '../../src/auth' +import { createAuthMiddleware } from '../../src/auth/middleware' +import { ApiTokenService } from '../../src/services/api-tokens' +import { migrate } from '../../src/db/migration-runner' +import { allMigrations } from '../../src/db/migrations' +import type { Session } from '../../src/auth' + +type AppVariables = { + session: Session['session'] + user: Session['user'] + tokenScope?: string +} + +function seedUser(db: Database, id: string, email = `${id}@example.com`, name = `User ${id}`) { + const now = new Date().toISOString() + db.prepare( + `INSERT INTO "user" (id, name, email, emailVerified, createdAt, updatedAt, role) + VALUES (?, ?, ?, ?, ?, ?, ?)` + ).run(id, name, email, 1, now, now, 'user') +} + +describe('Auth Middleware', () => { + let db: Database + let auth: ReturnType + let apiTokenService: ApiTokenService + + beforeEach(() => { + db = new Database(':memory:') + migrate(db, allMigrations) + auth = createAuth(db) + apiTokenService = new ApiTokenService(db) + }) + + describe('Bearer token authentication', () => { + it('accepts valid bearer token and loads real user', async () => { + seedUser(db, 'user-123', 'alice@example.com', 'Alice') + const tokenResult = apiTokenService.create('user-123', 'test-token') + + const requireAuth = createAuthMiddleware(auth, apiTokenService, db) + const app = new Hono<{ Variables: AppVariables }>() + app.use('/*', requireAuth) + app.get('/test', (c) => c.json({ + success: true, + user: c.get('user'), + tokenScope: c.get('tokenScope') ?? null, + })) + + const res = await app.request('http://localhost/test', { + headers: { Authorization: `Bearer ${tokenResult.token}` }, + }) + + expect(res.status).toBe(200) + const json = await res.json() as { success: boolean; user: { id: string; email: string; name: string }; tokenScope: string | null } + expect(json.success).toBe(true) + expect(json.user.id).toBe('user-123') + expect(json.user.email).toBe('alice@example.com') + expect(json.user.name).toBe('Alice') + expect(json.tokenScope).toBe('workspace-plugin') + }) + + it('rejects bearer token whose user no longer exists', async () => { + const tokenResult = apiTokenService.create('ghost-user', 'test-token') + + const requireAuth = createAuthMiddleware(auth, apiTokenService, db) + const app = new Hono() + app.use('/*', requireAuth) + app.get('/test', (c) => c.json({ success: true })) + + const res = await app.request('http://localhost/test', { + headers: { Authorization: `Bearer ${tokenResult.token}` }, + }) + + expect(res.status).toBe(401) + }) + + it('rejects invalid bearer token', async () => { + const requireAuth = createAuthMiddleware(auth, apiTokenService, db) + const app = new Hono() + app.use('/*', requireAuth) + app.get('/test', (c) => c.json({ success: true })) + + const res = await app.request('http://localhost/test', { + headers: { Authorization: 'Bearer invalid-token' }, + }) + + expect(res.status).toBe(401) + }) + + it('rejects expired bearer token', async () => { + seedUser(db, 'user-123') + const expiredAt = Date.now() - 3600000 + const tokenResult = apiTokenService.create('user-123', 'test-token', 'workspace-plugin', expiredAt) + + const requireAuth = createAuthMiddleware(auth, apiTokenService, db) + const app = new Hono() + app.use('/*', requireAuth) + app.get('/test', (c) => c.json({ success: true })) + + const res = await app.request('http://localhost/test', { + headers: { Authorization: `Bearer ${tokenResult.token}` }, + }) + + expect(res.status).toBe(401) + }) + + it('rejects revoked bearer token', async () => { + seedUser(db, 'user-123') + const tokenResult = apiTokenService.create('user-123', 'test-token') + apiTokenService.revoke('user-123', tokenResult.id) + + const requireAuth = createAuthMiddleware(auth, apiTokenService, db) + const app = new Hono() + app.use('/*', requireAuth) + app.get('/test', (c) => c.json({ success: true })) + + const res = await app.request('http://localhost/test', { + headers: { Authorization: `Bearer ${tokenResult.token}` }, + }) + + expect(res.status).toBe(401) + }) + + it('rejects request without auth when bearer service not provided', async () => { + const requireAuth = createAuthMiddleware(auth) + const app = new Hono() + app.use('/*', requireAuth) + app.get('/test', (c) => c.json({ success: true })) + + const res = await app.request('http://localhost/test') + + expect(res.status).toBe(401) + }) + + it('propagates custom token scope to downstream handlers', async () => { + seedUser(db, 'user-scope') + const tokenResult = apiTokenService.create('user-scope', 'custom', 'custom-scope') + + const requireAuth = createAuthMiddleware(auth, apiTokenService, db) + const app = new Hono<{ Variables: AppVariables }>() + app.use('/*', requireAuth) + app.get('/scope', (c) => c.json({ scope: c.get('tokenScope') ?? null })) + + const res = await app.request('http://localhost/scope', { + headers: { Authorization: `Bearer ${tokenResult.token}` }, + }) + + expect(res.status).toBe(200) + const json = await res.json() as { scope: string | null } + expect(json.scope).toBe('custom-scope') + }) + }) +}) diff --git a/backend/test/helpers/bun-sqlite-shim.ts b/backend/test/helpers/bun-sqlite-shim.ts new file mode 100644 index 00000000..c8936ec7 --- /dev/null +++ b/backend/test/helpers/bun-sqlite-shim.ts @@ -0,0 +1,22 @@ +import { DatabaseSync } from 'node:sqlite' + +export class Database extends DatabaseSync { + constructor(path: string) { + super(path) + } + + run(sql: string, ...params: unknown[]): void { + if (params.length === 0) { + this.exec(sql) + return + } + const stmt = this.prepare(sql) + stmt.run(...(params as never[])) + } + + query(sql: string): ReturnType { + return this.prepare(sql) + } +} + +export default { Database } diff --git a/backend/test/routes/api-tokens.test.ts b/backend/test/routes/api-tokens.test.ts new file mode 100644 index 00000000..d51a0eae --- /dev/null +++ b/backend/test/routes/api-tokens.test.ts @@ -0,0 +1,138 @@ +import { describe, it, expect, beforeEach } from 'vitest' +import { Hono } from 'hono' +import { Database } from 'bun:sqlite' +import { createApiTokenRoutes } from '../../src/routes/api-tokens' +import { ApiTokenService } from '../../src/services/api-tokens' +import { migrate } from '../../src/db/migration-runner' +import { allMigrations } from '../../src/db/migrations' +import type { Session } from '../../src/auth' + +type AppVariables = { + session: Session['session'] + user: Session['user'] +} + +const TEST_USER_ID = 'test-user-123' + +const testSession: { session: Session['session']; user: Session['user'] } = { + session: { + id: 'test-session', + userId: TEST_USER_ID, + token: 'test-token', + expiresAt: new Date(), + createdAt: new Date(), + updatedAt: new Date(), + }, + user: { + id: TEST_USER_ID, + name: 'Test User', + email: 'test@example.com', + emailVerified: true, + createdAt: new Date(), + updatedAt: new Date(), + }, +} + +function buildAuthedApp(apiTokenService: ApiTokenService, authed: boolean): Hono<{ Variables: AppVariables }> { + const app = new Hono<{ Variables: AppVariables }>() + app.use('/*', async (c, next) => { + if (authed) { + c.set('session', testSession.session) + c.set('user', testSession.user) + } + await next() + }) + app.route('/tokens', createApiTokenRoutes(apiTokenService)) + return app +} + +describe('API Tokens Routes', () => { + let db: Database + let apiTokenService: ApiTokenService + + beforeEach(() => { + db = new Database(':memory:') + migrate(db, allMigrations) + apiTokenService = new ApiTokenService(db) + }) + + describe('GET /tokens', () => { + it('returns list of tokens for authenticated user', async () => { + apiTokenService.create(TEST_USER_ID, 'token1') + apiTokenService.create(TEST_USER_ID, 'token2') + + const app = buildAuthedApp(apiTokenService, true) + const res = await app.request('http://localhost/tokens') + + expect(res.status).toBe(200) + const json = await res.json() as { tokens: Array<{ id: string; name: string }> } + expect(json.tokens.length).toBe(2) + }) + }) + + describe('POST /tokens', () => { + it('creates new token with valid request', async () => { + const app = buildAuthedApp(apiTokenService, true) + const res = await app.request('http://localhost/tokens', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: 'new-token' }), + }) + + expect(res.status).toBe(200) + const json = await res.json() as { id: string; name: string; token: string } + expect(json.id).toBeTruthy() + expect(json.name).toBe('new-token') + expect(json.token).toBeTruthy() + }) + + it('returns raw token only once on creation', async () => { + const app = buildAuthedApp(apiTokenService, true) + + const createRes = await app.request('http://localhost/tokens', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: 'new-token' }), + }) + + const created = await createRes.json() as { id: string; token: string } + expect(created.token).toBeTruthy() + + const listRes = await app.request('http://localhost/tokens') + const listJson = await listRes.json() as { tokens: Array<{ id: string; token?: string }> } + const found = listJson.tokens.find((t) => t.id === created.id) + expect(found).toBeDefined() + expect(found?.token).toBeUndefined() + }) + + it('returns 400 with invalid data', async () => { + const app = buildAuthedApp(apiTokenService, true) + const res = await app.request('http://localhost/tokens', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: '' }), + }) + + expect(res.status).toBe(400) + }) + }) + + describe('DELETE /tokens/:id', () => { + it('revokes existing token', async () => { + const token = apiTokenService.create(TEST_USER_ID, 'token1') + const app = buildAuthedApp(apiTokenService, true) + + const res = await app.request(`http://localhost/tokens/${token.id}`, { method: 'DELETE' }) + + expect(res.status).toBe(200) + expect(apiTokenService.list(TEST_USER_ID).length).toBe(0) + }) + + it('returns 404 for non-existent token', async () => { + const app = buildAuthedApp(apiTokenService, true) + const res = await app.request('http://localhost/tokens/non-existent-id', { method: 'DELETE' }) + + expect(res.status).toBe(404) + }) + }) +}) diff --git a/backend/test/routes/title.test.ts b/backend/test/routes/title.test.ts deleted file mode 100644 index 4bcc4761..00000000 --- a/backend/test/routes/title.test.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = vi.hoisted(() => ({ - resolveOpenCodeModel: vi.fn(), - fetch: vi.fn(), - sleep: vi.fn(), -})) - -vi.mock('../../src/services/opencode-models', () => ({ - resolveOpenCodeModel: mocks.resolveOpenCodeModel, -})) - -vi.mock('../../src/utils/logger', () => ({ - logger: { - info: vi.fn(), - error: vi.fn(), - warn: vi.fn(), - }, -})) - -vi.mock('@opencode-manager/shared/config/env', () => ({ - ENV: { - OPENCODE: { PORT: 5551, HOST: '127.0.0.1' }, - }, -})) - -import { createTitleRoutes } from '../../src/routes/title' - -function jsonResponse(body: unknown, status: number = 200): Response { - return new Response(JSON.stringify(body), { - status, - headers: { 'content-type': 'application/json' }, - }) -} - -function textResponse(body: string, status: number = 200): Response { - return new Response(body, { status }) -} - -describe('Title Routes', () => { - beforeEach(() => { - vi.clearAllMocks() - mocks.resolveOpenCodeModel.mockResolvedValue({ providerID: 'openai', modelID: 'gpt-5-mini' }) - vi.stubGlobal('fetch', mocks.fetch) - vi.stubGlobal('Bun', { sleep: mocks.sleep }) - mocks.sleep.mockResolvedValue(undefined) - }) - - it('updates the session title from an immediate JSON prompt response', async () => { - const app = createTitleRoutes() - - mocks.fetch - .mockResolvedValueOnce(jsonResponse({ id: 'title-session-1' })) - .mockResolvedValueOnce(textResponse(JSON.stringify({ - parts: [{ type: 'text', text: 'Refactoring background jobs' }], - }))) - .mockResolvedValueOnce(textResponse('', 200)) - .mockResolvedValueOnce(textResponse('', 200)) - - const response = await app.request('http://localhost/', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - directory: '/workspace/repos/sample-project', - }, - body: JSON.stringify({ - text: 'Refactor recurring background jobs and improve observability.', - sessionID: 'session-main-1', - }), - }) - const body = await response.json() as { title: string } - - expect(response.status).toBe(200) - expect(body.title).toBe('Refactoring background jobs') - expect(mocks.fetch).toHaveBeenCalledWith( - 'http://127.0.0.1:5551/session/session-main-1?directory=%2Fworkspace%2Frepos%2Fsample-project', - expect.objectContaining({ method: 'PATCH' }), - ) - }) - - it('polls session messages when the prompt endpoint returns an empty body', async () => { - const app = createTitleRoutes() - - mocks.fetch - .mockResolvedValueOnce(jsonResponse({ id: 'title-session-2' })) - .mockResolvedValueOnce(textResponse('')) - .mockResolvedValueOnce(jsonResponse([ - { - info: { role: 'assistant', time: { completed: Date.now() } }, - parts: [{ type: 'text', text: 'Analyzing recurring job setup' }], - }, - ])) - .mockResolvedValueOnce(textResponse('', 200)) - .mockResolvedValueOnce(textResponse('', 200)) - - const response = await app.request('http://localhost/', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - directory: '/workspace/repos/sample-project', - }, - body: JSON.stringify({ - text: 'Why do recurring jobs stop after a restart?', - sessionID: 'session-main-2', - }), - }) - const body = await response.json() as { title: string } - - expect(response.status).toBe(200) - expect(body.title).toBe('Analyzing recurring job setup') - expect(mocks.fetch).toHaveBeenNthCalledWith( - 3, - 'http://127.0.0.1:5551/session/title-session-2/message?directory=%2Fworkspace%2Frepos%2Fsample-project', - ) - }) - - it('returns a 500 when the polled assistant message reports an error', async () => { - const app = createTitleRoutes() - - mocks.fetch - .mockResolvedValueOnce(jsonResponse({ id: 'title-session-3' })) - .mockResolvedValueOnce(textResponse('')) - .mockResolvedValueOnce(jsonResponse([ - { - info: { - role: 'assistant', - error: { data: { message: 'Model unavailable' } }, - }, - parts: [], - }, - ])) - .mockResolvedValueOnce(textResponse('', 200)) - - const response = await app.request('http://localhost/', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - directory: '/workspace/repos/sample-project', - }, - body: JSON.stringify({ - text: 'Generate a title for this broken run.', - sessionID: 'session-main-3', - }), - }) - const body = await response.json() as { error: string } - - expect(response.status).toBe(500) - expect(body.error).toBe('Model unavailable') - }) -}) diff --git a/backend/test/services/api-tokens.test.ts b/backend/test/services/api-tokens.test.ts new file mode 100644 index 00000000..9cde790d --- /dev/null +++ b/backend/test/services/api-tokens.test.ts @@ -0,0 +1,170 @@ +import { describe, it, expect, beforeEach } from 'vitest' +import { Database } from 'bun:sqlite' +import { ApiTokenService } from '../../src/services/api-tokens' +import { migrate } from '../../src/db/migration-runner' +import { allMigrations } from '../../src/db/migrations' + +describe('ApiTokenService', () => { + let db: Database + let service: ApiTokenService + const testUserId = 'test-user-123' + + beforeEach(() => { + db = new Database(':memory:') + migrate(db, allMigrations) + service = new ApiTokenService(db) + }) + + describe('create', () => { + it('returns raw token on creation', () => { + const result = service.create(testUserId, 'test-token') + + expect(result.id).toBeDefined() + expect(result.name).toBe('test-token') + expect(result.token).toBeDefined() + expect(result.token.length).toBeGreaterThan(0) + }) + + it('generates different tokens on identical calls', () => { + const result1 = service.create(testUserId, 'test-token') + const result2 = service.create(testUserId, 'test-token') + + expect(result1.token).not.toBe(result2.token) + expect(result1.id).not.toBe(result2.id) + }) + + it('stores token with correct scope', () => { + const result = service.create(testUserId, 'test-token', 'custom-scope') + + const tokens = service.list(testUserId) + const created = tokens.find(t => t.id === result.id) + + expect(created).toBeDefined() + expect(created?.scope).toBe('custom-scope') + }) + + it('stores expiration time when provided', () => { + const expiresAt = Date.now() + 3600000 + const result = service.create(testUserId, 'test-token', 'workspace-plugin', expiresAt) + + const tokens = service.list(testUserId) + const created = tokens.find(t => t.id === result.id) + + expect(created?.expiresAt).toBe(expiresAt) + }) + }) + + describe('verify', () => { + it('returns userId and scope for valid token', () => { + const createResult = service.create(testUserId, 'test-token', 'workspace-plugin') + + const verified = service.verify(createResult.token) + + expect(verified).toBeDefined() + expect(verified?.userId).toBe(testUserId) + expect(verified?.scope).toBe('workspace-plugin') + expect(verified?.id).toBe(createResult.id) + }) + + it('returns null for unknown token', () => { + const verified = service.verify('unknown-token') + + expect(verified).toBeNull() + }) + + it('returns null for expired token', () => { + const expiredAt = Date.now() - 3600000 + const createResult = service.create(testUserId, 'test-token', 'workspace-plugin', expiredAt) + + const verified = service.verify(createResult.token) + + expect(verified).toBeNull() + }) + + it('returns null for revoked token', () => { + const createResult = service.create(testUserId, 'test-token') + + service.revoke(testUserId, createResult.id) + const verified = service.verify(createResult.token) + + expect(verified).toBeNull() + }) + + it('updates last_used_at on successful verify', () => { + const createResult = service.create(testUserId, 'test-token') + const beforeTokens = service.list(testUserId) + const beforeToken = beforeTokens.find(t => t.id === createResult.id) + const beforeLastUsed = beforeToken?.lastUsedAt + + service.verify(createResult.token) + + const afterTokens = service.list(testUserId) + const afterToken = afterTokens.find(t => t.id === createResult.id) + + expect(afterToken?.lastUsedAt).toBeDefined() + expect(afterToken?.lastUsedAt).toBeGreaterThan(beforeLastUsed ?? 0) + }) + }) + + describe('list', () => { + it('returns empty array when no tokens exist', () => { + const tokens = service.list(testUserId) + + expect(tokens).toEqual([]) + }) + + it('returns tokens for user ordered by creation date', () => { + service.create(testUserId, 'token1') + service.create(testUserId, 'token2') + + const tokens = service.list(testUserId) + + expect(tokens.length).toBe(2) + expect(tokens[0]?.name).toBe('token2') + expect(tokens[1]?.name).toBe('token1') + }) + + it('does not expose token hash in list results', () => { + service.create(testUserId, 'test-token') + + const tokens = service.list(testUserId) + + expect(tokens[0]).not.toHaveProperty('tokenHash') + expect(tokens[0]).not.toHaveProperty('token') + }) + }) + + describe('revoke', () => { + it('returns true when revoking existing token', () => { + const result = service.create(testUserId, 'test-token') + + const revoked = service.revoke(testUserId, result.id) + + expect(revoked).toBe(true) + }) + + it('returns false when revoking non-existent token', () => { + const revoked = service.revoke(testUserId, 'non-existent-id') + + expect(revoked).toBe(false) + }) + + it('prevents subsequent verify of revoked token', () => { + const createResult = service.create(testUserId, 'test-token') + + service.revoke(testUserId, createResult.id) + const verified = service.verify(createResult.token) + + expect(verified).toBeNull() + }) + + it('only revokes tokens belonging to the user', () => { + const user1Token = service.create('user1', 'token1') + service.create('user2', 'token2') + + const revoked = service.revoke('user2', user1Token.id) + + expect(revoked).toBe(false) + }) + }) +}) diff --git a/backend/test/services/opencode-single-server.test.ts b/backend/test/services/opencode-single-server.test.ts index c291caf1..7be27b67 100644 --- a/backend/test/services/opencode-single-server.test.ts +++ b/backend/test/services/opencode-single-server.test.ts @@ -254,6 +254,8 @@ describe('OpenCodeServerManager - reloadConfig', () => { const mockPatchResult = { success: true } vi.mocked(patchOpenCodeConfig).mockResolvedValue(mockPatchResult) + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 200 })) + const { opencodeServerManager } = await import('../../src/services/opencode-single-server') await opencodeServerManager.reloadConfig() @@ -263,5 +265,7 @@ describe('OpenCodeServerManager - reloadConfig', () => { 'utf-8' ) expect(patchOpenCodeConfig).toHaveBeenCalled() + + fetchSpy.mockRestore() }) }) diff --git a/backend/vitest.config.ts b/backend/vitest.config.ts index 2425b4fa..fffcd78c 100644 --- a/backend/vitest.config.ts +++ b/backend/vitest.config.ts @@ -1,10 +1,14 @@ import { defineConfig } from 'vitest/config' +import { fileURLToPath } from 'node:url' export default defineConfig({ test: { globals: true, environment: 'node', setupFiles: ['./test/setup.ts'], + alias: { + 'bun:sqlite': fileURLToPath(new URL('./test/helpers/bun-sqlite-shim.ts', import.meta.url)), + }, coverage: { provider: 'v8', reporter: ['text', 'html'], diff --git a/docs/features/workspace-plugin.md b/docs/features/workspace-plugin.md new file mode 100644 index 00000000..5b0048db --- /dev/null +++ b/docs/features/workspace-plugin.md @@ -0,0 +1,187 @@ +# Workspace Plugin + +The workspace plugin allows you to connect your local OpenCode TUI to a running opencode-manager instance and use its projects as remote workspaces. + +## Overview + +The workspace plugin consists of two main components: + +1. **Manager-side**: Backend endpoints and authentication for serving project information +2. **Plugin**: An OpenCode plugin that connects to the manager and registers remote workspaces + +## Features + +- **Bearer Token Authentication**: Secure API tokens for external access +- **Project Discovery**: Automatically discover and register all manager projects +- **Remote Workspace Support**: Use manager projects as remote workspaces in OpenCode TUI +- **SSE Streaming**: Server-sent events are properly streamed (not buffered) +- **WebSocket Support**: WebSocket connections are proxied correctly + +## Setup + +### 1. Create an API Token + +1. Open your opencode-manager web UI +2. Navigate to Settings → API Tokens +3. Click "Create Token" +4. Give it a descriptive name (e.g., "OpenCode TUI") +5. **Copy the token immediately** - it won't be shown again +6. Store the token securely + +### 2. Install the Plugin + +In your OpenCode configuration (`opencode.json`), add: + +```json +{ + "plugin": [ + ["@opencode-manager/workspace-plugin", { + "url": "http://localhost:5003", + "token": "" + }] + ] +} +``` + +Or use environment variables: + +```bash +export OPENCODE_MANAGER_URL="http://localhost:5003" +export OPENCODE_MANAGER_TOKEN="" +``` + +### 3. Start OpenCode TUI + +Launch the OpenCode TUI. You should see your manager projects appear in the workspace picker as `manager:`. + +## How It Works + +1. **Plugin Initialization**: When OpenCode starts, the plugin calls `GET /api/workspace-plugin/projects` on the manager +2. **Project Registration**: For each project returned, the plugin registers a `WorkspaceAdaptor` with type `manager:` +3. **Workspace Selection**: When you select a workspace in the TUI, the adaptor provides: + - Remote target URL: `/api/opencode` + - Authorization header: `Bearer ` + - Project slug header: `x-opencode-manager-project: ` +4. **Request Proxying**: The manager proxies requests to the embedded OpenCode server with the appropriate `?directory=` parameter + +## API Reference + +### `GET /api/workspace-plugin/projects` + +Returns a list of projects available in the manager. + +**Authentication**: Bearer token or session cookie + +**Response**: +```json +{ + "projects": [ + { + "slug": "1", + "name": "my-project", + "directory": "/path/to/project", + "description": "https://github.com/user/repo.git" + } + ] +} +``` + +### `GET /api/settings/tokens` + +List all API tokens for the current user. + +**Response**: +```json +{ + "tokens": [ + { + "id": "uuid", + "name": "token-name", + "scope": "workspace-plugin", + "lastUsedAt": 1234567890, + "createdAt": 1234567890, + "expiresAt": null + } + ] +} +``` + +### `POST /api/settings/tokens` + +Create a new API token. + +**Request**: +```json +{ + "name": "token-name", + "scope": "workspace-plugin", + "expiresAt": 1234567890 +} +``` + +**Response**: +```json +{ + "id": "uuid", + "name": "token-name", + "token": "raw-token-shown-once" +} +``` + +### `DELETE /api/settings/tokens/:id` + +Revoke an API token. + +## Security Considerations + +- **Token Storage**: Tokens are stored as SHA-256 hashes in the database +- **One-Time Display**: Raw tokens are shown only once on creation +- **Token Revocation**: Tokens can be revoked at any time from the Settings UI +- **Scope Restriction**: Tokens have a `workspace-plugin` scope by default +- **CORS Bypass**: Bearer tokens bypass CORS origin requirements (explicit opt-in) + +## Token Scopes + +- `workspace-plugin`: Access to workspace plugin endpoints (default) +- `*`: Full access to all protected endpoints + +## Troubleshooting + +### Plugin fails to connect + +1. Verify the manager URL is correct and accessible +2. Check that the token is valid and not expired +3. Ensure the token has the correct scope (`workspace-plugin`) +4. Check the manager logs for authentication errors + +### Projects don't appear + +1. Verify the manager has projects configured +2. Check that the token has not been revoked +3. Look for errors in the OpenCode TUI console + +### SSE events not streaming + +The proxy has been updated to stream response bodies instead of buffering. If you experience issues: + +1. Check that the manager is running the latest version +2. Verify the upstream OpenCode server is sending proper SSE headers +3. Look for buffering in network inspection tools + +## Development + +### Testing the Plugin + +```bash +cd packages/workspace-plugin +pnpm test +pnpm typecheck +``` + +### Testing the Manager + +```bash +cd backend +pnpm test test/services/api-tokens.test.ts +pnpm test test/routes/workspace-plugin.test.ts +``` diff --git a/docs/index.md b/docs/index.md index 860a2ab7..63c89470 100644 --- a/docs/index.md +++ b/docs/index.md @@ -39,6 +39,7 @@ OpenCode Manager provides a web-based interface for OpenCode AI agents, allowing - **AI Configuration** - Configure models, providers, OAuth, and custom agents - **MCP Servers** - Add local or remote MCP servers with OAuth support - **Memory Plugin (Optional)** — Persistent project knowledge with semantic search ([GitHub](https://github.com/chriswritescode-dev/opencode-memory)) +- **Workspace Plugin** - Connect OpenCode TUI to opencode-manager for remote workspace access !!! tip "Memory Plugin — Persistent Project Knowledge" Store and retrieve project knowledge across sessions using vector embeddings and semantic search. Works as a standalone plugin with any OpenCode installation. @@ -52,4 +53,5 @@ OpenCode Manager provides a web-based interface for OpenCode AI agents, allowing - [Features Overview](features/overview.md) - Explore all features - [Schedules & Recurring Jobs](features/schedules.md) - Automate recurring repo reviews and follow-ups - [Memory Plugin](features/memory.md) - Persistent project knowledge with semantic search ([GitHub](https://github.com/chriswritescode-dev/opencode-memory)) +- [Workspace Plugin](features/workspace-plugin.md) - Connect OpenCode TUI to opencode-manager - [Configuration](configuration/environment.md) - Environment variables and setup diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 8908e653..20ff59a6 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,7 +1,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' -import { createBrowserRouter, RouterProvider, Outlet, useNavigate } from 'react-router-dom' -import { useEffect } from 'react' +import { createBrowserRouter, RouterProvider, Outlet, useNavigate, useLocation } from 'react-router-dom' +import { useEffect, useRef } from 'react' import { Toaster } from 'sonner' import { Repos } from './pages/Repos' import { RepoDetail } from './pages/RepoDetail' @@ -15,14 +15,16 @@ import { Setup } from './pages/Setup' import { SettingsDialog } from './components/settings/SettingsDialog' import { VersionNotifier } from './components/VersionNotifier' import { PwaUpdatePrompt } from '@/components/PwaUpdatePrompt' +import { MobileTabBar } from '@/components/navigation/MobileTabBar' +import { MobileSheetHost } from '@/components/navigation/MobileSheetHost' import { useTheme } from './hooks/useTheme' +import { useSwipeBack } from './hooks/useMobile' import { TTSProvider } from './contexts/TTSContext' import { AuthProvider } from './contexts/AuthContext' import { EventProvider, usePermissions, useEventContext } from '@/contexts/EventContext' +import { SwipeNavigationProvider } from '@/contexts/SwipeNavigationContext' import { PermissionRequestDialog } from './components/session/PermissionRequestDialog' import { SSHHostKeyDialog } from './components/ssh/SSHHostKeyDialog' -import { PageTransition } from './components/ui/PageTransition' -import { useNavigationDirection } from './hooks/useNavigationDirection' import { loginLoader, setupLoader, registerLoader, protectedLoader } from './lib/auth-loaders' const queryClient = new QueryClient({ @@ -70,8 +72,61 @@ function PermissionDialogWrapper() { function AppShell() { const navigate = useNavigate() + const location = useLocation() + const rootRef = useRef(null) useTheme() - useNavigationDirection() + + const getSwipeBackTarget = () => { + const path = location.pathname + if (path.match(/^\/repos\/[^/]+\/sessions\/[^/]+$/)) { + const repoId = path.split('/')[2] + return `/repos/${repoId}` + } + if (path.match(/^\/repos\/[^/]+$/)) { + return '/' + } + if (path.match(/^\/repos\/[^/]+\/memories$/)) { + const repoId = path.split('/')[2] + return `/repos/${repoId}` + } + if (path.match(/^\/repos\/[^/]+\/schedules$/)) { + const repoId = path.split('/')[2] + return `/repos/${repoId}` + } + if (path === '/schedules') { + return '/' + } + return null + } + + const canSwipeBack = () => { + const path = location.pathname + return !['/login', '/setup', '/register', '/'].includes(path) && getSwipeBackTarget() !== null + } + + const handleSwipeBack = () => { + const target = getSwipeBackTarget() + if (target) { + navigate(target) + } + } + + const { bind: bindRouteSwipe } = useSwipeBack( + () => {}, + { + enabled: true, + suspendsRouteSwipe: false, + canBack: canSwipeBack, + onBack: handleSwipeBack, + } + ) + + useEffect(() => { + const cleanup = bindRouteSwipe(rootRef.current) + return () => { + cleanup?.() + } + }, [bindRouteSwipe]) useEffect(() => { const channel = new BroadcastChannel('notification-click') @@ -87,9 +142,11 @@ function AppShell() { return ( - +
- +
+ + @@ -164,7 +221,9 @@ function App() { return ( - + + + ) diff --git a/frontend/src/components/file-browser/FileBrowserSheet.test.tsx b/frontend/src/components/file-browser/FileBrowserSheet.test.tsx index 3dda39ef..af322b0a 100644 --- a/frontend/src/components/file-browser/FileBrowserSheet.test.tsx +++ b/frontend/src/components/file-browser/FileBrowserSheet.test.tsx @@ -662,11 +662,11 @@ describe('FileBrowserSheet swipe decision integration', () => { expect(parentPath).toBe('test') }) - it('FileBrowserSheet wires useSwipeToClose with canSwipeBack and onSwipeBack callbacks', () => { + it('FileBrowserSheet wires useSwipeBack with canBack and onBack callbacks', () => { const mockOnClose = vi.fn() - const mockUseSwipeToClose = vi.spyOn(useMobile, 'useSwipeToClose') - mockUseSwipeToClose.mockReturnValue({ + const mockUseSwipeBack = vi.spyOn(useMobile, 'useSwipeBack') + mockUseSwipeBack.mockReturnValue({ bind: vi.fn(), swipeProgress: 0, swipeStyles: { transform: undefined, transition: 'transform 0.2s ease-out' }, @@ -681,18 +681,18 @@ describe('FileBrowserSheet swipe decision integration', () => { { wrapper: createWrapper() } ) - expect(mockUseSwipeToClose).toHaveBeenCalled() + expect(mockUseSwipeBack).toHaveBeenCalled() - const callArgs = mockUseSwipeToClose.mock.calls[0] + const callArgs = mockUseSwipeBack.mock.calls[0] expect(callArgs).toBeDefined() expect(callArgs![0]).toBe(mockOnClose) const options = callArgs![1]! expect(options.enabled).toBe(true) - expect(typeof options.canSwipeBack).toBe('function') - expect(typeof options.onSwipeBack).toBe('function') + expect(typeof options.canBack).toBe('function') + expect(typeof options.onBack).toBe('function') - mockUseSwipeToClose.mockRestore() + mockUseSwipeBack.mockRestore() }) it('FileBrowserSheet swipe completion: path decision logic for nested path', () => { @@ -726,13 +726,13 @@ describe('FileBrowserSheet swipe decision integration', () => { expect(parentPath).toBe('test/deep') }) - it('FileBrowserSheet swipe completion calls onSwipeBack for nested path', () => { + it('FileBrowserSheet swipe completion calls onBack for nested path', () => { const mockOnClose = vi.fn() - const mockUseSwipeToClose = vi.spyOn(useMobile, 'useSwipeToClose') - mockUseSwipeToClose.mockImplementation((onClose, _options) => { - if (_options?.canSwipeBack && _options.canSwipeBack()) { - _options.onSwipeBack?.() + const mockUseSwipeBack = vi.spyOn(useMobile, 'useSwipeBack') + mockUseSwipeBack.mockImplementation((onClose, _options) => { + if (_options?.canBack && _options.canBack()) { + _options.onBack?.() } return { bind: vi.fn(), @@ -758,29 +758,30 @@ describe('FileBrowserSheet swipe decision integration', () => { expect(canGoBack).toBe(true) expect(mockOnClose).not.toHaveBeenCalled() - mockUseSwipeToClose.mockRestore() + mockUseSwipeBack.mockRestore() }) it('FileBrowserSheet swipe completion calls onClose for base path', () => { const mockOnClose = vi.fn() - const mockOnSwipeBack = vi.fn() + const mockOnBack = vi.fn() const basePath = 'test' const currentPath = basePath + const pathParts = currentPath.split('/').filter(Boolean) const joinedPath = pathParts.join('/') const canGoBack = joinedPath !== basePath expect(canGoBack).toBe(false) expect(mockOnClose).not.toHaveBeenCalled() - expect(mockOnSwipeBack).not.toHaveBeenCalled() + expect(mockOnBack).not.toHaveBeenCalled() }) it('FileBrowserSheet back-vs-close outcome: verifies swipe completion calls correct action', () => { const mockOnClose = vi.fn() - const mockUseSwipeToClose = vi.spyOn(useMobile, 'useSwipeToClose') - mockUseSwipeToClose.mockReturnValue({ + const mockUseSwipeBack = vi.spyOn(useMobile, 'useSwipeBack') + mockUseSwipeBack.mockReturnValue({ bind: vi.fn(), swipeProgress: 0, swipeStyles: { transform: undefined, transition: 'transform 0.2s ease-out' }, @@ -796,16 +797,16 @@ describe('FileBrowserSheet swipe decision integration', () => { ) - expect(mockUseSwipeToClose).toHaveBeenCalled() + expect(mockUseSwipeBack).toHaveBeenCalled() - const callArgs = mockUseSwipeToClose.mock.calls[0] + const callArgs = mockUseSwipeBack.mock.calls[0] expect(callArgs).toBeDefined() expect(callArgs![0]).toBe(mockOnClose) const options = callArgs![1]! expect(options.enabled).toBe(true) - expect(options.canSwipeBack).toBeDefined() - expect(options.onSwipeBack).toBeDefined() + expect(options.canBack).toBeDefined() + expect(options.onBack).toBeDefined() const nestedPath = 'test/deep' const nestedPathParts = nestedPath.split('/').filter(Boolean) @@ -821,17 +822,17 @@ describe('FileBrowserSheet swipe decision integration', () => { expect(canGoBackBase).toBe(false) - mockUseSwipeToClose.mockRestore() + mockUseSwipeBack.mockRestore() }) it('FileBrowserSheet back-vs-close: swipe completion decision is wired correctly', () => { const mockOnClose = vi.fn() - const mockUseSwipeToClose = vi.spyOn(useMobile, 'useSwipeToClose') - mockUseSwipeToClose.mockImplementation((onClose, options) => { - const canBack = options?.canSwipeBack?.() + const mockUseSwipeBack = vi.spyOn(useMobile, 'useSwipeBack') + mockUseSwipeBack.mockImplementation((onClose, options) => { + const canBack = options?.canBack?.() if (canBack) { - options?.onSwipeBack?.() + options?.onBack?.() } else { onClose() } @@ -852,11 +853,11 @@ describe('FileBrowserSheet swipe decision integration', () => { ) - const callArgs = mockUseSwipeToClose.mock.calls[0] + const callArgs = mockUseSwipeBack.mock.calls[0] const options = callArgs![1]! - expect(options.canSwipeBack).toBeDefined() - expect(options.onSwipeBack).toBeDefined() + expect(options.canBack).toBeDefined() + expect(options.onBack).toBeDefined() const currentPath = 'test/deep' const pathParts = currentPath.split('/').filter(Boolean) @@ -865,7 +866,229 @@ describe('FileBrowserSheet swipe decision integration', () => { expect(canGoBack).toBe(true) - mockUseSwipeToClose.mockRestore() + mockUseSwipeBack.mockRestore() + }) + + it('FileBrowserSheet swipe decision integration: callback chain verification', () => { + const basePath = 'test' + const nestedPath = 'test/deep' + + const pathParts = nestedPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = pathParts.length > 0 && joinedPath !== basePath + + expect(canGoBack).toBe(true) + expect(joinedPath).toBe('test/deep') + + const parentPath = pathParts.slice(0, -1).join('/') + expect(parentPath).toBe('test') + }) + + it('FileBrowserSheet wires useSwipeBack with canBack and onBack callbacks', () => { + const mockOnClose = vi.fn() + + const mockUseSwipeBack = vi.spyOn(useMobile, 'useSwipeBack') + mockUseSwipeBack.mockReturnValue({ + bind: vi.fn(), + swipeProgress: 0, + swipeStyles: { transform: undefined, transition: 'transform 0.2s ease-out' }, + }) + + render( + , + { wrapper: createWrapper() } + ) + + expect(mockUseSwipeBack).toHaveBeenCalled() + + const callArgs = mockUseSwipeBack.mock.calls[0] + expect(callArgs).toBeDefined() + expect(callArgs![0]).toBe(mockOnClose) + + const options = callArgs![1]! + expect(options.enabled).toBe(true) + expect(typeof options.canBack).toBe('function') + expect(typeof options.onBack).toBe('function') + + mockUseSwipeBack.mockRestore() + }) + + it('FileBrowserSheet swipe completion: path decision logic for nested path', () => { + const basePath = 'test' + const currentPath = 'test/deep/nested' + + const pathParts = currentPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = pathParts.length > 0 && joinedPath !== basePath + + expect(canGoBack).toBe(true) + }) + + it('FileBrowserSheet swipe completion: path decision logic for base path', () => { + const basePath = 'test' + const currentPath = basePath + + const pathParts = currentPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = pathParts.length > 0 && joinedPath !== basePath + + expect(canGoBack).toBe(false) + }) + + it('FileBrowserSheet swipe completion: parent path computation', () => { + const currentPath = 'test/deep/nested' + const pathParts = currentPath.split('/').filter(Boolean) + pathParts.pop() + const parentPath = pathParts.join('/') + + expect(parentPath).toBe('test/deep') + }) + + it('FileBrowserSheet swipe completion calls onBack for nested path', () => { + const mockOnClose = vi.fn() + + const mockUseSwipeBack = vi.spyOn(useMobile, 'useSwipeBack') + mockUseSwipeBack.mockImplementation((onClose, _options) => { + if (_options?.canBack && _options.canBack()) { + _options.onBack?.() + } + return { + bind: vi.fn(), + swipeProgress: 0, + swipeStyles: { transform: undefined, transition: 'transform 0.2s ease-out' }, + } + }) + + render( + , + { wrapper: createWrapper() } + ) + + const testPath = 'test/deep' + const pathParts = testPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = joinedPath !== 'test' + + expect(canGoBack).toBe(true) + expect(mockOnClose).not.toHaveBeenCalled() + + mockUseSwipeBack.mockRestore() + }) + + it('FileBrowserSheet swipe completion calls onClose for base path', () => { + const mockOnClose = vi.fn() + const mockOnBack = vi.fn() + + const basePath = 'test' + const currentPath = basePath + + const pathParts = currentPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = joinedPath !== basePath + + expect(canGoBack).toBe(false) + expect(mockOnClose).not.toHaveBeenCalled() + expect(mockOnBack).not.toHaveBeenCalled() + }) + + it('FileBrowserSheet back-vs-close outcome: verifies swipe completion calls correct action', () => { + const mockOnClose = vi.fn() + + const mockUseSwipeBack = vi.spyOn(useMobile, 'useSwipeBack') + mockUseSwipeBack.mockReturnValue({ + bind: vi.fn(), + swipeProgress: 0, + swipeStyles: { transform: undefined, transition: 'transform 0.2s ease-out' }, + }) + + render( + + + + ) + + expect(mockUseSwipeBack).toHaveBeenCalled() + + const callArgs = mockUseSwipeBack.mock.calls[0] + expect(callArgs).toBeDefined() + expect(callArgs![0]).toBe(mockOnClose) + + const options = callArgs![1]! + expect(options.enabled).toBe(true) + expect(options.canBack).toBeDefined() + expect(options.onBack).toBeDefined() + + const nestedPath = 'test/deep' + const nestedPathParts = nestedPath.split('/').filter(Boolean) + const nestedJoinedPath = nestedPathParts.join('/') + const canGoBackNested = nestedJoinedPath !== 'test' + + expect(canGoBackNested).toBe(true) + + const basePath = 'test' + const basePathParts = basePath.split('/').filter(Boolean) + const baseJoinedPath = basePathParts.join('/') + const canGoBackBase = baseJoinedPath !== 'test' + + expect(canGoBackBase).toBe(false) + + mockUseSwipeBack.mockRestore() + }) + + it('FileBrowserSheet back-vs-close: swipe completion decision is wired correctly', () => { + const mockOnClose = vi.fn() + + const mockUseSwipeBack = vi.spyOn(useMobile, 'useSwipeBack') + mockUseSwipeBack.mockImplementation((onClose, options) => { + const canBack = options?.canBack?.() + if (canBack) { + options?.onBack?.() + } else { + onClose() + } + return { + bind: vi.fn(), + swipeProgress: 0, + swipeStyles: { transform: undefined, transition: 'transform 0.2s ease-out' }, + } + }) + + render( + + + + ) + + const callArgs = mockUseSwipeBack.mock.calls[0] + const options = callArgs![1]! + + expect(options.canBack).toBeDefined() + expect(options.onBack).toBeDefined() + + const currentPath = 'test/deep' + const pathParts = currentPath.split('/').filter(Boolean) + const joinedPath = pathParts.join('/') + const canGoBack = joinedPath !== 'test' + + expect(canGoBack).toBe(true) + + mockUseSwipeBack.mockRestore() }) }) diff --git a/frontend/src/components/file-browser/FileBrowserSheet.tsx b/frontend/src/components/file-browser/FileBrowserSheet.tsx index f4d08d29..cc5e2caf 100644 --- a/frontend/src/components/file-browser/FileBrowserSheet.tsx +++ b/frontend/src/components/file-browser/FileBrowserSheet.tsx @@ -6,7 +6,7 @@ import { FullscreenSheet, FullscreenSheetHeader, FullscreenSheetContent } from ' import { DownloadDialog } from '@/components/ui/download-dialog' import { X, Download } from 'lucide-react' import { GPU_ACCELERATED_STYLE, MODAL_TRANSITION_MS } from '@/lib/utils' -import { useSwipeToClose } from '@/hooks/useMobile' +import { useSwipeBack } from '@/hooks/useMobile' import { downloadDirectoryAsZip } from '@/api/files' import { downloadRepo } from '@/api/repos' import { @@ -36,10 +36,10 @@ export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose const containerRef = useRef(null) const fileBrowserRef = useRef(null) - const { bind, swipeStyles } = useSwipeToClose(onClose, { + const { bind, swipeStyles } = useSwipeBack(onClose, { enabled: isOpen && !isEditing && !isPreviewOpen, - canSwipeBack: () => fileBrowserRef.current?.canGoBack() ?? false, - onSwipeBack: () => fileBrowserRef.current?.goBack(), + canBack: () => fileBrowserRef.current?.canGoBack() ?? false, + onBack: () => fileBrowserRef.current?.goBack(), }) useEffect(() => { diff --git a/frontend/src/components/file-browser/MobileFilePreviewModal.tsx b/frontend/src/components/file-browser/MobileFilePreviewModal.tsx index d0b97473..9e70cd7f 100644 --- a/frontend/src/components/file-browser/MobileFilePreviewModal.tsx +++ b/frontend/src/components/file-browser/MobileFilePreviewModal.tsx @@ -3,7 +3,7 @@ import { FilePreview } from "./FilePreview"; import { FullscreenSheet } from "@/components/ui/fullscreen-sheet"; import type { FileInfo } from "@/types/files"; import { GPU_ACCELERATED_STYLE, MODAL_TRANSITION_MS } from "@/lib/utils"; -import { useSwipeToClose } from "@/hooks/useMobile"; +import { useSwipeBack } from "@/hooks/useMobile"; interface MobileFilePreviewModalProps { isOpen: boolean; @@ -32,7 +32,7 @@ export const MobileFilePreviewModal = memo(function MobileFilePreviewModal({ }, MODAL_TRANSITION_MS); }, [onClose]); - const { bind, swipeStyles } = useSwipeToClose(handleClose, { + const { bind, swipeStyles } = useSwipeBack(handleClose, { enabled: isOpen, }); diff --git a/frontend/src/components/message/FloatingTTSButton.test.tsx b/frontend/src/components/message/FloatingTTSButton.test.tsx new file mode 100644 index 00000000..b2d60d0f --- /dev/null +++ b/frontend/src/components/message/FloatingTTSButton.test.tsx @@ -0,0 +1,280 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { render, screen, fireEvent, act } from '@testing-library/react' +import { FloatingTTSButton } from './FloatingTTSButton' +import type { TTSConfig } from '@opencode-manager/shared' + +const mocks = vi.hoisted(() => ({ + useTTS: vi.fn(), + useSettings: vi.fn(), + showToastInfo: vi.fn(), +})) + +vi.mock('@/hooks/useTTS', () => ({ + useTTS: mocks.useTTS, +})) + +vi.mock('@/hooks/useSettings', () => ({ + useSettings: mocks.useSettings, +})) + +vi.mock('@/lib/toast', () => ({ + showToast: { + info: mocks.showToastInfo, + }, +})) + +interface MockTTSReturn { + speakMessage: ReturnType + stop: ReturnType + activeMessageId: string | null + isPlaying: boolean + isLoading: boolean + isEnabled: boolean +} + +describe('FloatingTTSButton', () => { + const mockSpeakMessage = vi.fn() + const mockStop = vi.fn() + const mockUpdateSettings = vi.fn() + + beforeEach(() => { + vi.clearAllMocks() + mockSpeakMessage.mockClear() + mockStop.mockClear() + mockUpdateSettings.mockClear() + mocks.showToastInfo.mockClear() + }) + + const setup = (options: { + ttsEnabled?: boolean + autoPlay?: boolean + activeMessageId?: string | null + isPlaying?: boolean + isLoading?: boolean + } = {}) => { + const mockTTS: MockTTSReturn = { + speakMessage: mockSpeakMessage, + stop: mockStop, + activeMessageId: options.activeMessageId ?? null, + isPlaying: options.isPlaying ?? false, + isLoading: options.isLoading ?? false, + isEnabled: options.ttsEnabled ?? true, + } + mocks.useTTS.mockReturnValue(mockTTS) + + mocks.useSettings.mockReturnValue({ + preferences: { + tts: { + enabled: options.ttsEnabled ?? true, + autoPlay: options.autoPlay ?? false, + provider: 'external', + endpoint: 'https://api.openai.com', + apiKey: 'test-key', + voice: 'alloy', + model: 'tts-1', + speed: 1.0, + } as TTSConfig, + }, + updateSettings: mockUpdateSettings, + }) + } + + const TEST_MESSAGE_ID = 'test-message-1' + const TEST_CONTENT = 'Test content' + + it('renders pill when content is empty but autoplay is enabled', () => { + setup({ autoPlay: true }) + 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() + expect(screen.getByRole('button', { name: /hold to toggle auto-play/i })).toBeInTheDocument() + }) + + it('calls speakMessage on tap when 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) + }) + + it('calls stop on tap when this message is active', () => { + 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(mockSpeakMessage).not.toHaveBeenCalled() + }) + + it('calls stop when any playback is active, even for a different messageId (stream conflict fix)', () => { + setup({ activeMessageId: 'other-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(mockSpeakMessage).not.toHaveBeenCalled() + }) + + it('toggles autoplay on long press', async () => { + vi.useFakeTimers() + setup({ autoPlay: false }) + render() + + const button = screen.getByRole('button', { name: /play latest reply/i }) + await act(async () => { + fireEvent.pointerDown(button) + await vi.advanceTimersByTimeAsync(500) + fireEvent.pointerUp(button) + }) + + expect(mockUpdateSettings).toHaveBeenCalledTimes(1) + expect(mockUpdateSettings).toHaveBeenCalledWith({ + tts: { + autoPlay: true, + enabled: true, + provider: 'external', + endpoint: 'https://api.openai.com', + apiKey: 'test-key', + voice: 'alloy', + model: 'tts-1', + speed: 1.0, + }, + }) + expect(mocks.showToastInfo).toHaveBeenCalledWith('Auto-play enabled', { + id: 'tts-autoplay-toggle', + duration: 1800, + }) + + vi.useRealTimers() + }) + + it('shows a toast when long press disables autoplay', async () => { + vi.useFakeTimers() + setup({ autoPlay: true }) + render() + + const button = screen.getByRole('button', { name: /auto-play enabled/i }) + await act(async () => { + fireEvent.pointerDown(button) + await vi.advanceTimersByTimeAsync(500) + fireEvent.pointerUp(button) + }) + + expect(mockUpdateSettings).toHaveBeenCalledWith( + expect.objectContaining({ tts: expect.objectContaining({ autoPlay: false }) }) + ) + expect(mocks.showToastInfo).toHaveBeenCalledWith('Auto-play disabled', { + id: 'tts-autoplay-toggle', + duration: 1800, + }) + + vi.useRealTimers() + }) + + it('does not call speakMessage after long press (race guard)', async () => { + vi.useFakeTimers() + setup() + render() + + const button = screen.getByRole('button', { name: /play latest reply/i }) + await act(async () => { + fireEvent.pointerDown(button) + await vi.advanceTimersByTimeAsync(500) + fireEvent.pointerUp(button) + }) + + expect(mockSpeakMessage).not.toHaveBeenCalled() + expect(mockStop).not.toHaveBeenCalled() + vi.useRealTimers() + }) + + it('does not call speakMessage if pointer leaves before release after long press fires', async () => { + vi.useFakeTimers() + setup() + render() + + const button = screen.getByRole('button', { name: /play latest reply/i }) + await act(async () => { + fireEvent.pointerDown(button) + await vi.advanceTimersByTimeAsync(500) + fireEvent.pointerLeave(button) + }) + + expect(mockSpeakMessage).not.toHaveBeenCalled() + vi.useRealTimers() + }) + + it('exposes the gesture hint in the aria-label for accessibility', () => { + setup() + render() + + const button = screen.getByRole('button', { name: /hold to toggle auto-play/i }) + expect(button).toBeInTheDocument() + }) + + it('shows stop icon when this message is playing', () => { + setup({ autoPlay: true, activeMessageId: TEST_MESSAGE_ID, isPlaying: true }) + render() + + const button = screen.getByRole('button', { name: /stop playback/i }) + + expect(button).toHaveClass('from-red-600') + expect(button).toHaveClass('rounded-lg') + expect(button).not.toHaveClass('rounded-full') + expect(button).not.toHaveClass('hidden') + expect(screen.queryByText('Stop')).not.toBeInTheDocument() + expect(screen.queryByLabelText('Autoplay enabled')).not.toBeInTheDocument() + }) + + it('shows the same stop icon while this message is loading', () => { + setup({ activeMessageId: TEST_MESSAGE_ID, isLoading: true }) + render() + + expect(screen.getByRole('button', { name: /stop playback/i })).toHaveClass('from-red-600') + }) + + it('shows autoplay state with button color when autoPlay is enabled', () => { + setup({ autoPlay: true }) + render() + + const button = screen.getByRole('button', { name: /auto-play enabled/i }) + + expect(button).toHaveClass('from-blue-500') + expect(button).toHaveClass('rounded-lg') + expect(screen.queryByText('Play')).not.toBeInTheDocument() + expect(screen.queryByText('Auto')).not.toBeInTheDocument() + expect(screen.queryByLabelText('Autoplay enabled')).not.toBeInTheDocument() + }) + + it('uses the default play color when autoPlay is disabled', () => { + setup({ autoPlay: false }) + render() + + const button = screen.getByRole('button', { name: /play latest reply/i }) + + expect(button).toHaveClass('from-amber-500') + expect(button).not.toHaveClass('from-blue-500') + expect(screen.queryByText('Play')).not.toBeInTheDocument() + }) +}) diff --git a/frontend/src/components/message/FloatingTTSButton.tsx b/frontend/src/components/message/FloatingTTSButton.tsx index bba58661..b3c9aa3a 100644 --- a/frontend/src/components/message/FloatingTTSButton.tsx +++ b/frontend/src/components/message/FloatingTTSButton.tsx @@ -1,49 +1,107 @@ -import { Volume2, VolumeX, Loader2 } from 'lucide-react' +import { useState, useCallback, useRef } from 'react' +import { Volume2, VolumeX } from 'lucide-react' import { useTTS } from '@/hooks/useTTS' +import { useSettings } from '@/hooks/useSettings' +import { showToast } from '@/lib/toast' +import { DEFAULT_TTS_CONFIG } from '@opencode-manager/shared' interface FloatingTTSButtonProps { + messageId: string content: string } -export function FloatingTTSButton({ content }: FloatingTTSButtonProps) { - const { speak, stop, isEnabled, isPlaying, isLoading, originalText } = useTTS() - - if (!isEnabled || !content.trim()) { - return null - } - - const isThisPlaying = (isPlaying || isLoading) && originalText === content - - const handleClick = () => { - if (isThisPlaying) { - stop() - } else { - speak(content) +const LONG_PRESS_DURATION = 500 + +export function FloatingTTSButton({ messageId, content }: FloatingTTSButtonProps) { + const { speakMessage, stop, isPlaying, isLoading } = useTTS() + const { preferences, updateSettings } = useSettings() + + const autoPlay = preferences?.tts?.autoPlay ?? false + const [isLongPressVisual, setIsLongPressVisual] = useState(false) + const longPressTimerRef = useRef | null>(null) + const didLongPressFireRef = useRef(false) + + const isAnyPlaybackActive = isPlaying || isLoading + const hasContent = content.trim().length > 0 + + const clearLongPressTimer = useCallback(() => { + if (longPressTimerRef.current) { + clearTimeout(longPressTimerRef.current) + longPressTimerRef.current = null } - } - + }, []) + + const handlePointerDown = useCallback(() => { + clearLongPressTimer() + didLongPressFireRef.current = false + longPressTimerRef.current = setTimeout(() => { + const nextAutoPlay = !autoPlay + + didLongPressFireRef.current = true + setIsLongPressVisual(true) + updateSettings({ tts: { ...(preferences?.tts ?? DEFAULT_TTS_CONFIG), autoPlay: nextAutoPlay } }) + showToast.info(nextAutoPlay ? 'Auto-play enabled' : 'Auto-play disabled', { + id: 'tts-autoplay-toggle', + duration: 1800, + }) + }, LONG_PRESS_DURATION) + }, [autoPlay, updateSettings, preferences?.tts, clearLongPressTimer]) + + const handlePointerUp = useCallback(() => { + clearLongPressTimer() + + if (didLongPressFireRef.current) { + didLongPressFireRef.current = false + setIsLongPressVisual(false) + return + } + + setIsLongPressVisual(false) + + if (isAnyPlaybackActive) { + stop() + return + } + + if (hasContent) { + speakMessage(messageId, content) + } + }, [clearLongPressTimer, isAnyPlaybackActive, stop, speakMessage, messageId, content, hasContent]) + + const handlePointerLeave = useCallback(() => { + clearLongPressTimer() + didLongPressFireRef.current = false + setIsLongPressVisual(false) + }, [clearLongPressTimer]) + + const showStop = isAnyPlaybackActive + const pillTitle = showStop + ? 'Stop playback' + : 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-gradient-to-br from-red-600 to-red-700 border border-red-500/60 shadow-red-500/30 ring-red-500/20 hover:ring-red-500/40 text-white' + : autoPlay + ? 'justify-center px-3 py-1.5 rounded-lg bg-gradient-to-br from-blue-500 to-blue-600 border border-blue-400/60 shadow-blue-500/30 ring-blue-500/20 hover:ring-blue-500/40 text-white' + : 'justify-center px-3 py-1.5 rounded-lg bg-gradient-to-br from-amber-500 to-orange-600 border border-amber-400/60 shadow-amber-500/30 ring-amber-500/20 hover:ring-amber-500/40 text-white' + return ( - + ) } diff --git a/frontend/src/components/message/MessagePart.test.tsx b/frontend/src/components/message/MessagePart.test.tsx new file mode 100644 index 00000000..99f5b5d5 --- /dev/null +++ b/frontend/src/components/message/MessagePart.test.tsx @@ -0,0 +1,226 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { render, screen, fireEvent } from '@testing-library/react' +import { MessagePart } from './MessagePart' +import type { MessagePart as MessagePartType } from '@/api/types' + +const mocks = vi.hoisted(() => ({ + useTTS: vi.fn(), +})) + +vi.mock('@/hooks/useTTS', () => ({ + useTTS: mocks.useTTS, +})) + +interface MockTTSReturn { + speakMessage: ReturnType + stop: ReturnType + activeMessageId: string | null + isPlaying: boolean + isLoading: boolean + isEnabled: boolean +} + +describe('MessagePart', () => { + const mockSpeakMessage = vi.fn() + const mockStop = vi.fn() + + beforeEach(() => { + mockSpeakMessage.mockClear() + mockStop.mockClear() + }) + + const setup = (options: { + ttsEnabled?: boolean + autoPlay?: boolean + activeMessageId?: string | null + isPlaying?: boolean + isLoading?: boolean + } = {}) => { + const mockTTS: MockTTSReturn = { + speakMessage: mockSpeakMessage, + stop: mockStop, + activeMessageId: options.activeMessageId ?? null, + isPlaying: options.isPlaying ?? false, + isLoading: options.isLoading ?? false, + isEnabled: options.ttsEnabled ?? true, + } + mocks.useTTS.mockReturnValue(mockTTS) + } + + const createStepFinishPart = (messageID: string): MessagePartType => ({ + type: 'step-finish', + messageID, + sessionID: 'test-session', + cost: 0.01, + tokens: { + input: 100, + output: 50, + cache: { read: 0, write: 0 }, + }, + time: { + start: Date.now(), + end: Date.now() + 100, + }, + }) + + const TEST_MESSAGE_ID = 'message-1' + const TEST_CONTENT = 'Test message content' + + it('renders TTS button for step-finish part with message text', () => { + setup() + const part = createStepFinishPart(TEST_MESSAGE_ID) + + render( + + ) + + expect(screen.getByRole('button')).toBeInTheDocument() + expect(screen.getByTitle('Read aloud')).toBeInTheDocument() + }) + + it('does not render TTS button when message text is empty', () => { + setup() + const part = createStepFinishPart(TEST_MESSAGE_ID) + + render( + + ) + + expect(screen.queryByRole('button')).not.toBeInTheDocument() + }) + + it('does not render TTS button when TTS is disabled', () => { + setup({ ttsEnabled: false }) + const part = createStepFinishPart(TEST_MESSAGE_ID) + + render( + + ) + + expect(screen.queryByRole('button')).not.toBeInTheDocument() + }) + + it('calls speakMessage with message id on tap when idle', () => { + setup() + const part = createStepFinishPart(TEST_MESSAGE_ID) + + render( + + ) + + const button = screen.getByRole('button') + fireEvent.click(button) + + expect(mockSpeakMessage).toHaveBeenCalledTimes(1) + expect(mockSpeakMessage).toHaveBeenCalledWith(TEST_MESSAGE_ID, TEST_CONTENT) + }) + + it('calls stop on tap when this message is active', () => { + const mockTTSForTest: MockTTSReturn = { + speakMessage: mockSpeakMessage, + stop: mockStop, + activeMessageId: TEST_MESSAGE_ID, + isPlaying: true, + isLoading: false, + isEnabled: true, + } + mocks.useTTS.mockReturnValue(mockTTSForTest) + + const part = createStepFinishPart(TEST_MESSAGE_ID) + + render( + + ) + + const button = screen.getByRole('button') + fireEvent.click(button) + + expect(mockStop).toHaveBeenCalledTimes(1) + expect(mockSpeakMessage).not.toHaveBeenCalled() + }) + + it('shows active state when this message is playing', () => { + setup({ activeMessageId: TEST_MESSAGE_ID, isPlaying: true }) + const part = createStepFinishPart(TEST_MESSAGE_ID) + + render( + + ) + + const button = screen.getByRole('button') + expect(button).toHaveClass('bg-red-500/20') + expect(button).toHaveClass('text-red-500') + }) + + it('shows active state when this message is loading', () => { + setup({ activeMessageId: TEST_MESSAGE_ID, isLoading: true }) + const part = createStepFinishPart(TEST_MESSAGE_ID) + + render( + + ) + + const button = screen.getByRole('button') + expect(button).toHaveClass('bg-red-500/20') + }) + + it('does not show active state when different message is playing', () => { + setup({ activeMessageId: 'other-message', isPlaying: true }) + const part = createStepFinishPart(TEST_MESSAGE_ID) + + render( + + ) + + const button = screen.getByRole('button') + expect(button).not.toHaveClass('bg-red-500/20') + }) + + it('tracks playback by message id not text', () => { + setup({ activeMessageId: TEST_MESSAGE_ID, isPlaying: true }) + const part1 = createStepFinishPart(TEST_MESSAGE_ID) + const part2 = createStepFinishPart('message-2') + + const { rerender } = render( + + ) + + expect(screen.getByRole('button')).toHaveClass('bg-red-500/20') + + rerender( + + ) + + expect(screen.getByRole('button')).not.toHaveClass('bg-red-500/20') + }) +}) diff --git a/frontend/src/components/message/MessagePart.tsx b/frontend/src/components/message/MessagePart.tsx index 15931ea2..25be72b6 100644 --- a/frontend/src/components/message/MessagePart.tsx +++ b/frontend/src/components/message/MessagePart.tsx @@ -59,24 +59,25 @@ function getCopyableContent(part: Part, allParts?: Part[]): string { } interface TTSButtonProps { + messageId: string content: string className?: string } -function TTSButton({ content, className = "" }: TTSButtonProps) { - const { speak, stop, isEnabled, isPlaying, isLoading, originalText } = useTTS() +function TTSButton({ messageId, content, className = "" }: TTSButtonProps) { + const { speakMessage, stop, isEnabled, isPlaying, isLoading, activeMessageId } = useTTS() if (!isEnabled || !content.trim()) { return null } - const isThisPlaying = (isPlaying || isLoading) && originalText === content + const isThisPlaying = (isPlaying || isLoading) && activeMessageId === messageId const handleClick = () => { if (isThisPlaying) { stop() } else { - speak(content) + speakMessage(messageId, content) } } @@ -85,7 +86,7 @@ function TTSButton({ content, className = "" }: TTSButtonProps) { onClick={handleClick} className={`p-1.5 rounded ${isThisPlaying ? 'bg-red-500/20 text-red-500 hover:bg-red-500/30' : 'bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground'} ${className}`} title={isThisPlaying ? "Stop playback" : "Read aloud"} - disabled={isLoading && originalText !== content} + disabled={isLoading && !isThisPlaying} > {isLoading && isThisPlaying ? ( @@ -146,7 +147,7 @@ export const MessagePart = memo(function MessagePart({ part, role, allParts, par
{costText} - {messageTextContent && } + {messageTextContent && part.messageID && }
) } diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index 6c32c83d..f463c643 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -1,4 +1,4 @@ -import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, memo, type KeyboardEvent } from 'react' +import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, memo, useCallback, type KeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react' import { useSendPrompt, useAbortSession, useSendShell, useAgents } from '@/hooks/useOpenCode' import { useCommands } from '@/hooks/useCommands' import { useCommandHandler } from '@/hooks/useCommandHandler' @@ -44,6 +44,8 @@ const revokeBlobUrls = (attachments: ImageAttachment[]) => { const ACCEPTED_FILE_TYPES = [...ACCEPTED_IMAGE_TYPES, "application/pdf"] +const VOICE_SEND_SWIPE_THRESHOLD = 48 + type CommandType = components['schemas']['Command'] @@ -102,7 +104,16 @@ export const PromptInput = memo(forwardRef( const [localMode, setLocalMode] = useState(null) const [isFocused, setIsFocused] = useState(false) const [isTogglingRecording, setIsTogglingRecording] = useState(false) + const [isVoiceHoldActive, setIsVoiceHoldActive] = useState(false) + const [isVoiceSwipeArmed, setIsVoiceSwipeArmed] = useState(false) + const [isVoiceAutoSendPending, setIsVoiceAutoSendPending] = useState(false) const lastAddedTranscriptRef = useRef('') + const voiceHoldStartYRef = useRef(null) + const voiceSwipeArmedRef = useRef(false) + const voicePendingReleaseRef = useRef(false) + const pendingVoiceAutoSubmitRef = useRef(false) + const ignoreVoiceClickUntilRef = useRef(0) + const handleSubmitRef = useRef<() => void>(() => {}) const { isRecording, @@ -119,6 +130,16 @@ export const PromptInput = memo(forwardRef( const textareaRef = useRef(null) const fileInputRef = useRef(null) + const resetVoiceGestureState = useCallback(() => { + voiceHoldStartYRef.current = null + voiceSwipeArmedRef.current = false + voicePendingReleaseRef.current = false + pendingVoiceAutoSubmitRef.current = false + ignoreVoiceClickUntilRef.current = 0 + setIsVoiceHoldActive(false) + setIsVoiceSwipeArmed(false) + setIsVoiceAutoSendPending(false) + }, []) useImperativeHandle(ref, () => ({ setPromptValue: (value: string) => { @@ -131,6 +152,7 @@ export const PromptInput = memo(forwardRef( revokeBlobUrls(imageAttachments) setImageAttachments([]) setSelectedAgent(null) + resetVoiceGestureState() if (isRecording) { abortRecording() } else { @@ -141,7 +163,7 @@ export const PromptInput = memo(forwardRef( triggerFileUpload: () => { fileInputRef.current?.click() } - }), [imageAttachments, clearSTT, isRecording, abortRecording]) + }), [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState]) const sendPrompt = useSendPrompt(opcodeUrl, directory) const sendShell = useSendShell(opcodeUrl, directory) const abortSession = useAbortSession(opcodeUrl, directory, sessionID, repoId) @@ -197,6 +219,9 @@ export const PromptInput = memo(forwardRef( if (disabled) return if (!prompt.trim() && imageAttachments.length === 0) return + pendingVoiceAutoSubmitRef.current = false + setIsVoiceAutoSendPending(false) + if (hasActiveStream) { const parts = parsePromptToParts(prompt, attachedFiles, imageAttachments) const agentUsed = selectedAgent || currentMode @@ -273,6 +298,8 @@ export const PromptInput = memo(forwardRef( clearSTT() } + handleSubmitRef.current = handleSubmit + const handleStop = () => { abortSession.mutate(sessionID) } @@ -381,6 +408,10 @@ export const PromptInput = memo(forwardRef( } const handleVoiceToggle = async () => { + pendingVoiceAutoSubmitRef.current = false + setIsVoiceAutoSendPending(false) + setIsVoiceSwipeArmed(false) + voiceSwipeArmedRef.current = false if (isRecording) { stopRecording() } else { @@ -388,7 +419,7 @@ export const PromptInput = memo(forwardRef( try { await startRecording() if (textareaRef.current) { - textareaRef.current.blur() + textareaRef.current?.blur() } } catch { setIsTogglingRecording(false) @@ -396,6 +427,101 @@ export const PromptInput = memo(forwardRef( } } + const handleVoiceClick = async () => { + if (Date.now() < ignoreVoiceClickUntilRef.current) { + return + } + + await handleVoiceToggle() + } + + const handleVoiceHoldStart = async () => { + if (!isRecording && !isProcessing) { + pendingVoiceAutoSubmitRef.current = false + setIsVoiceAutoSendPending(false) + setIsTogglingRecording(true) + try { + if (typeof navigator !== 'undefined' && navigator.vibrate) { + navigator.vibrate(10) + } + await startRecording() + if (textareaRef.current) { + textareaRef.current?.blur() + } + } catch { + setIsTogglingRecording(false) + } + } + } + + const handleVoiceHoldEnd = (shouldAutoSend: boolean) => { + setIsVoiceHoldActive(false) + setIsVoiceSwipeArmed(false) + voiceHoldStartYRef.current = null + voiceSwipeArmedRef.current = false + pendingVoiceAutoSubmitRef.current = shouldAutoSend + setIsVoiceAutoSendPending(shouldAutoSend) + + if (isRecording) { + if (typeof navigator !== 'undefined' && navigator.vibrate) { + navigator.vibrate([10, 20, 10]) + } + stopRecording() + } else if (isTogglingRecording) { + voicePendingReleaseRef.current = true + } + } + + const handleVoicePointerDown = async (event: ReactPointerEvent) => { + if ((event.pointerType === 'mouse' && event.button !== 0) || disabled || isProcessing) { + return + } + + ignoreVoiceClickUntilRef.current = Date.now() + 400 + voiceHoldStartYRef.current = event.clientY + voiceSwipeArmedRef.current = false + voicePendingReleaseRef.current = false + pendingVoiceAutoSubmitRef.current = false + setIsVoiceHoldActive(true) + setIsVoiceSwipeArmed(false) + setIsVoiceAutoSendPending(false) + + if (event.currentTarget.setPointerCapture) { + event.currentTarget.setPointerCapture(event.pointerId) + } + + await handleVoiceHoldStart() + } + + const handleVoicePointerMove = (event: ReactPointerEvent) => { + if (!isVoiceHoldActive || voiceHoldStartYRef.current === null) { + return + } + + const nextIsSwipeArmed = voiceHoldStartYRef.current - event.clientY >= VOICE_SEND_SWIPE_THRESHOLD + + if (nextIsSwipeArmed !== voiceSwipeArmedRef.current) { + voiceSwipeArmedRef.current = nextIsSwipeArmed + setIsVoiceSwipeArmed(nextIsSwipeArmed) + + if (nextIsSwipeArmed && typeof navigator !== 'undefined' && navigator.vibrate) { + navigator.vibrate(10) + } + } + } + + const handleVoicePointerEnd = (event: ReactPointerEvent, canceled = false) => { + if (event.currentTarget.releasePointerCapture && event.currentTarget.hasPointerCapture(event.pointerId)) { + event.currentTarget.releasePointerCapture(event.pointerId) + } + + if (!isVoiceHoldActive && !isTogglingRecording && !isRecording) { + return + } + + handleVoiceHoldEnd(canceled ? false : voiceSwipeArmedRef.current) + } + useEffect(() => { const textToUse = transcript || interimTranscript if (!isRecording && textToUse && textToUse !== 'Processing...' && textToUse !== 'Recording...') { @@ -407,7 +533,10 @@ export const PromptInput = memo(forwardRef( setPrompt(prev => `${prev} ${trimmedTranscript}`) } lastAddedTranscriptRef.current = trimmedTranscript - textareaRef.current?.focus() + + if (!pendingVoiceAutoSubmitRef.current) { + textareaRef.current?.focus() + } } } }, [isRecording, interimTranscript, transcript, prompt]) @@ -424,6 +553,35 @@ export const PromptInput = memo(forwardRef( } }, [isTogglingRecording]) + useEffect(() => { + if (isRecording && voicePendingReleaseRef.current) { + voicePendingReleaseRef.current = false + + if (typeof navigator !== 'undefined' && navigator.vibrate) { + navigator.vibrate([10, 20, 10]) + } + + stopRecording() + } + }, [isRecording, stopRecording]) + + useEffect(() => { + if (!pendingVoiceAutoSubmitRef.current || isRecording || isProcessing || !prompt.trim()) { + return + } + + pendingVoiceAutoSubmitRef.current = false + setIsVoiceAutoSendPending(false) + handleSubmitRef.current() + }, [prompt, isRecording, isProcessing]) + + useEffect(() => { + if (pendingVoiceAutoSubmitRef.current && !isRecording && !isProcessing && !transcript.trim() && !interimTranscript.trim()) { + pendingVoiceAutoSubmitRef.current = false + setIsVoiceAutoSendPending(false) + } + }, [isRecording, isProcessing, transcript, interimTranscript]) + const addImageAttachment = (file: File) => { const generateId = () => { if (typeof crypto !== 'undefined' && crypto.randomUUID) { @@ -680,6 +838,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read) setPrompt('') revokeBlobUrls(imageAttachments) setImageAttachments([]) + resetVoiceGestureState() clearSTT() } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 't') { e.preventDefault() @@ -768,6 +927,47 @@ const { model, modelString, setModel: setStoredModel } = useModelSelection(opcod const { hasVariants, currentVariant, cycleVariant } = useVariants(opcodeUrl, directory) const showStopButton = hasActiveStream const hideSecondaryButtons = isMobile && hasActiveStream + const showVoiceFeedback = isVoiceHoldActive || isRecording || isTogglingRecording || isProcessing || isVoiceAutoSendPending + const voiceFeedbackLabel = isProcessing + ? isVoiceAutoSendPending + ? 'Transcribing and sending...' + : 'Transcribing...' + : isRecording + ? isVoiceSwipeArmed + ? 'Release to send' + : 'Recording... swipe up to send' + : isTogglingRecording || isVoiceHoldActive + ? 'Starting microphone...' + : null + const voiceFeedbackToneClasses = isVoiceSwipeArmed || isVoiceAutoSendPending + ? 'border-blue-400/60 bg-blue-500/90 text-white shadow-blue-500/30' + : 'border-red-500/60 bg-red-600/90 text-white shadow-red-500/30' + const voiceFeedbackGlowClasses = isVoiceSwipeArmed || isVoiceAutoSendPending ? 'bg-blue-500/30' : 'bg-red-500/25' + const voiceButtonTitle = isProcessing + ? 'Transcribing speech' + : isRecording + ? isVoiceSwipeArmed + ? 'Release to send' + : 'Release to transcribe' + : 'Hold to speak' + + const renderVoiceStatusOverlay = () => { + if (!showVoiceFeedback || !voiceFeedbackLabel) { + return null + } + + return ( + <> +
+
+ {voiceFeedbackLabel} +
+ + ) + } @@ -779,11 +979,12 @@ const { model, modelString, setModel: setStoredModel } = useModelSelection(opcod onPromptChange?.(prompt.trim().length > 0) }, [prompt, onPromptChange]) - useEffect(() => { + useEffect(() => { if (isRecording) { abortRecording() } clearSTT() + resetVoiceGestureState() lastAddedTranscriptRef.current = '' setIsTogglingRecording(false) setLocalMode(null) @@ -930,49 +1131,63 @@ return ( {sttEnabled && sttSupported && ( - +
+ {renderVoiceStatusOverlay()} + +
)} {isMobile && !showScrollButton && sttEnabled && sttSupported && !hasPendingPermissionForSession && ( - +
+ {renderVoiceStatusOverlay()} + +
)} + ) + })} +
+ ) +}) + +export const MobileTabBar = memo(function MobileTabBar() { + const { pathname } = useLocation() + const navigate = useNavigate() + const { openSheet, open } = useMobileTabBar() + const { scheduleTab, setScheduleTab } = useScheduleTab() + const hasPending = usePendingAlerts() + + const isOnRepoSchedules = /^\/repos\/\d+\/schedules$/.test(pathname) + const isRepoMemories = /^\/repos\/\d+\/memories$/.test(pathname) + const isMobile = useMobile() + const isRoot = pathname === '/' + const isGlobalSchedules = pathname === '/schedules' + const isRepoDetail = /^\/repos\/\d+$/.test(pathname) + const isInsideRepo = isRepoDetail || isOnRepoSchedules || isRepoMemories + const isRepoSession = /^\/repos\/\d+\/sessions\/\w+/.test(pathname) + const allow = isRoot || isGlobalSchedules || (isInsideRepo && !isRepoSession) + + const repoIdMatch = pathname.match(/^\/repos\/(\d+)/) + const repoId = repoIdMatch ? repoIdMatch[1] : null + + const tabs = useMemo( + () => (isOnRepoSchedules + ? buildScheduleTabs(scheduleTab, setScheduleTab) + : buildGlobalTabs({ + pathname, + openSheet, + open, + navigate, + hasPending, + isInsideRepo, + repoId, + })), + [isOnRepoSchedules, scheduleTab, setScheduleTab, pathname, openSheet, open, navigate, hasPending, isInsideRepo, repoId], + ) + + if (!isMobile) return null + if (!allow) return null + + return +}) diff --git a/frontend/src/components/navigation/MoreDrawer.test.tsx b/frontend/src/components/navigation/MoreDrawer.test.tsx new file mode 100644 index 00000000..7ceea994 --- /dev/null +++ b/frontend/src/components/navigation/MoreDrawer.test.tsx @@ -0,0 +1,160 @@ +import { render, screen, fireEvent } from '@testing-library/react' +import { describe, it, expect, vi } from 'vitest' +import { MemoryRouter, useNavigate } from 'react-router-dom' +import { MoreDrawer } from './MoreDrawer' +import { useAuth } from '@/hooks/useAuth' +import { useServerHealth } from '@/hooks/useServerHealth' + +vi.mock('@/hooks/useAuth') +vi.mock('@/hooks/useServerHealth') +vi.mock('@/hooks/useMemoryPluginStatus', () => ({ + useMemoryPluginStatus: () => ({ memoryPluginEnabled: false }), +})) +vi.mock('react-router-dom', async () => { + const actual = await vi.importActual('react-router-dom') + return { + ...actual, + useNavigate: vi.fn(), + } +}) + +const mockAuth = (logout = vi.fn()) => { + vi.mocked(useAuth).mockReturnValue({ + user: null, + isAuthenticated: false, + isLoading: false, + config: null, + signInWithEmail: vi.fn(), + signInWithProvider: vi.fn(), + signInWithPasskey: vi.fn(), + signUpWithEmail: vi.fn(), + addPasskey: vi.fn(), + logout, + refreshSession: vi.fn(), + }) +} + +const mockServerHealth = (health?: Partial['data']>) => { + const baseHealth = { + status: 'healthy' as const, + timestamp: new Date().toISOString(), + database: 'connected' as const, + opencode: 'healthy' as const, + opencodePort: 5551, + opencodeVersion: null, + opencodeMinVersion: '1.0.0', + opencodeManagerVersion: null, + error: undefined, + } + + vi.mocked(useServerHealth).mockReturnValue({ + data: { + ...baseHealth, + ...health, + }, + isLoading: false, + error: null, + refetch: vi.fn(), + restartMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false }, + rollbackMutation: { mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false }, + }) +} + +describe('MoreDrawer', () => { + beforeEach(() => { + vi.clearAllMocks() + vi.mocked(useNavigate).mockReturnValue(vi.fn()) + }) + + it('renders Settings and Logout menu items', () => { + mockAuth() + mockServerHealth() + const handleClose = vi.fn() + render( + , + { wrapper: ({ children }) => {children} }, + ) + expect(screen.getByText('OpenCode')).toBeInTheDocument() + expect(screen.getByText('Settings')).toBeInTheDocument() + expect(screen.getByText('Logout')).toBeInTheDocument() + }) + + it('does not render theme controls', () => { + mockAuth() + mockServerHealth() + const handleClose = vi.fn() + render( + , + { wrapper: ({ children }) => {children} }, + ) + expect(screen.queryByText('Theme')).not.toBeInTheDocument() + expect(screen.queryByText('Light')).not.toBeInTheDocument() + expect(screen.queryByText('Dark')).not.toBeInTheDocument() + expect(screen.queryByText('System')).not.toBeInTheDocument() + }) + + it('navigates to settings URL when Settings is clicked', () => { + const navigateMock = vi.fn() + vi.mocked(useNavigate).mockReturnValue(navigateMock) + mockAuth() + mockServerHealth() + const handleClose = vi.fn() + render( + , + { wrapper: ({ children }) => {children} }, + ) + fireEvent.click(screen.getByText('Settings')) + expect(navigateMock).toHaveBeenCalledWith( + { search: 'settings=open&tab=account' }, + { replace: true }, + ) + }) + + it('calls logout when Logout is clicked', () => { + const logoutMock = vi.fn().mockResolvedValue(undefined) + mockAuth(logoutMock) + mockServerHealth() + const handleClose = vi.fn() + render( + , + { wrapper: ({ children }) => {children} }, + ) + fireEvent.click(screen.getByText('Logout')) + expect(logoutMock).toHaveBeenCalled() + }) + + it('displays OpenCode and Manager versions when available', () => { + mockAuth() + mockServerHealth({ opencodeVersion: '1.4.11', opencodeManagerVersion: '0.9.16' }) + const handleClose = vi.fn() + render( + , + { wrapper: ({ children }) => {children} }, + ) + expect(screen.getByText('OpenCode v1.4.11')).toBeInTheDocument() + expect(screen.getByText('Manager v0.9.16')).toBeInTheDocument() + }) + + it('shows unhealthy server status when server is unhealthy', () => { + mockAuth() + mockServerHealth({ opencode: 'unhealthy' as const, opencodeVersion: '1.4.11' }) + const handleClose = vi.fn() + render( + , + { wrapper: ({ children }) => {children} }, + ) + expect(screen.getByText('OpenCode v1.4.11')).toBeInTheDocument() + }) + + it('shows fallback text when version is not available', () => { + mockAuth() + mockServerHealth({ opencodeVersion: null, opencodeManagerVersion: null }) + const handleClose = vi.fn() + render( + , + { wrapper: ({ children }) => {children} }, + ) + expect(screen.getByText('OpenCode')).toBeInTheDocument() + }) + +}) diff --git a/frontend/src/components/navigation/MoreDrawer.tsx b/frontend/src/components/navigation/MoreDrawer.tsx new file mode 100644 index 00000000..129e3277 --- /dev/null +++ b/frontend/src/components/navigation/MoreDrawer.tsx @@ -0,0 +1,86 @@ +import { useNavigate, useLocation } from 'react-router-dom' +import { useAuth } from '@/hooks/useAuth' +import { useServerHealth } from '@/hooks/useServerHealth' +import { useMemoryPluginStatus } from '@/hooks/useMemoryPluginStatus' +import { SideDrawer, SideDrawerHeader, SideDrawerContent } from '@/components/ui/side-drawer' +import { buildMoreItems } from './moreDrawerItems' + +interface MoreDrawerProps { + isOpen: boolean + onClose: () => void +} + +export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) { + const navigate = useNavigate() + const location = useLocation() + const { logout } = useAuth() + const { data: health } = useServerHealth() + const { memoryPluginEnabled } = useMemoryPluginStatus() + + const handleSettingsClick = () => { + const newParams = new URLSearchParams(location.search) + newParams.delete('mobileTab') + newParams.set('settings', 'open') + newParams.set('tab', 'account') + navigate({ search: newParams.toString() }, { replace: true }) + } + + const handleLogoutClick = async () => { + try { + await logout() + } finally { + onClose() + } + } + + const handleItemClick = (item: ReturnType[0]) => { + if (item.to) { + navigate(item.to) + } else if (item.dialog) { + const newParams = new URLSearchParams(location.search) + newParams.set('dialog', item.dialog) + newParams.delete('mobileTab') + navigate({ search: newParams.toString() }, { replace: true }) + } + } + + const items = buildMoreItems(location.pathname, { memoryPluginEnabled }) + + const opencodeVersion = health?.opencodeVersion + const managerVersion = health?.opencodeManagerVersion + + return ( + + Manager v{managerVersion} + ) : null + } + /> + + {items.map((item) => ( + + ))} + + + ) +} diff --git a/frontend/src/components/navigation/NotificationsSheet.test.tsx b/frontend/src/components/navigation/NotificationsSheet.test.tsx new file mode 100644 index 00000000..a01e7c7b --- /dev/null +++ b/frontend/src/components/navigation/NotificationsSheet.test.tsx @@ -0,0 +1,214 @@ +import { render, screen, fireEvent } from '@testing-library/react' +import { describe, it, expect, vi } from 'vitest' +import { MemoryRouter } from 'react-router-dom' +import { NotificationsSheet } from './NotificationsSheet' +import { usePermissions, useQuestions } from '@/contexts/EventContext' + +vi.mock('@/contexts/EventContext') + +describe('NotificationsSheet', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('renders empty state when both counts are 0', () => { + vi.mocked(usePermissions).mockReturnValue({ + pendingCount: 0, + setShowDialog: vi.fn(), + navigateToCurrent: vi.fn(), + current: null, + respond: vi.fn(), + dismiss: vi.fn(), + getForCallID: vi.fn(), + hasForSession: vi.fn(), + }) + vi.mocked(useQuestions).mockReturnValue({ + pendingCount: 0, + navigateToCurrent: vi.fn(), + current: null, + reply: vi.fn(), + reject: vi.fn(), + dismiss: vi.fn(), + getForCallID: vi.fn(), + hasForSession: vi.fn(), + }) + const handleClose = vi.fn() + render( + , + { wrapper: ({ children }) => {children} }, + ) + expect(screen.getAllByText("You're all caught up").length).toBe(2) + }) + + it('renders permission section with pending count', () => { + vi.mocked(usePermissions).mockReturnValue({ + pendingCount: 2, + setShowDialog: vi.fn(), + navigateToCurrent: vi.fn(), + current: { + id: 'perm-1', + sessionID: 'session-1', + permission: 'write', + patterns: ['/test/pattern'], + metadata: {}, + always: [], + tool: { + messageID: 'msg-1', + callID: 'call-1', + }, + }, + respond: vi.fn(), + dismiss: vi.fn(), + getForCallID: vi.fn(), + hasForSession: vi.fn(), + }) + vi.mocked(useQuestions).mockReturnValue({ + pendingCount: 0, + navigateToCurrent: vi.fn(), + current: null, + reply: vi.fn(), + reject: vi.fn(), + dismiss: vi.fn(), + getForCallID: vi.fn(), + hasForSession: vi.fn(), + }) + const handleClose = vi.fn() + render( + , + { wrapper: ({ children }) => {children} }, + ) + expect(screen.getByText('Pending permissions')).toBeInTheDocument() + expect(screen.getByText('+1 more')).toBeInTheDocument() + }) + + it('renders question section with pending count', () => { + vi.mocked(usePermissions).mockReturnValue({ + pendingCount: 0, + setShowDialog: vi.fn(), + navigateToCurrent: vi.fn(), + current: null, + respond: vi.fn(), + dismiss: vi.fn(), + getForCallID: vi.fn(), + hasForSession: vi.fn(), + }) + vi.mocked(useQuestions).mockReturnValue({ + pendingCount: 1, + navigateToCurrent: vi.fn(), + current: { + id: 'q-1', + sessionID: 'session-1', + questions: [{ + question: 'Test question', + options: [], + }], + metadata: {}, + tool: { + messageID: 'msg-1', + callID: 'call-1', + }, + }, + reply: vi.fn(), + reject: vi.fn(), + dismiss: vi.fn(), + getForCallID: vi.fn(), + hasForSession: vi.fn(), + }) + const handleClose = vi.fn() + render( + , + { wrapper: ({ children }) => {children} }, + ) + expect(screen.getByText('Pending questions')).toBeInTheDocument() + expect(screen.getByText('Test question')).toBeInTheDocument() + }) + + it('calls setShowDialog and onClose when permission is clicked', () => { + const setShowDialogMock = vi.fn() + const navigateToPermissionMock = vi.fn() + const handleClose = vi.fn() + vi.mocked(usePermissions).mockReturnValue({ + pendingCount: 1, + setShowDialog: setShowDialogMock, + navigateToCurrent: navigateToPermissionMock, + current: { + id: 'perm-1', + sessionID: 'session-1', + permission: 'write', + patterns: ['/test/pattern'], + metadata: {}, + always: [], + tool: { + messageID: 'msg-1', + callID: 'call-1', + }, + }, + respond: vi.fn(), + dismiss: vi.fn(), + getForCallID: vi.fn(), + hasForSession: vi.fn(), + }) + vi.mocked(useQuestions).mockReturnValue({ + pendingCount: 0, + navigateToCurrent: vi.fn(), + current: null, + reply: vi.fn(), + reject: vi.fn(), + dismiss: vi.fn(), + getForCallID: vi.fn(), + hasForSession: vi.fn(), + }) + render( + , + { wrapper: ({ children }) => {children} }, + ) + fireEvent.click(screen.getByText('/test/pattern')) + expect(navigateToPermissionMock).toHaveBeenCalled() + expect(setShowDialogMock).toHaveBeenCalled() + expect(handleClose).toHaveBeenCalled() + }) + + it('calls navigateToCurrent and onClose when question is clicked', () => { + const navigateToQuestionMock = vi.fn() + const handleClose = vi.fn() + vi.mocked(usePermissions).mockReturnValue({ + pendingCount: 0, + setShowDialog: vi.fn(), + navigateToCurrent: vi.fn(), + current: null, + respond: vi.fn(), + dismiss: vi.fn(), + getForCallID: vi.fn(), + hasForSession: vi.fn(), + }) + vi.mocked(useQuestions).mockReturnValue({ + pendingCount: 1, + navigateToCurrent: navigateToQuestionMock, + current: { + id: 'q-1', + sessionID: 'session-1', + questions: [{ + question: 'Test question', + options: [], + }], + metadata: {}, + tool: { + messageID: 'msg-1', + callID: 'call-1', + }, + }, + reply: vi.fn(), + reject: vi.fn(), + dismiss: vi.fn(), + getForCallID: vi.fn(), + hasForSession: vi.fn(), + }) + render( + , + { wrapper: ({ children }) => {children} }, + ) + fireEvent.click(screen.getByText('Test question')) + expect(navigateToQuestionMock).toHaveBeenCalled() + expect(handleClose).toHaveBeenCalled() + }) +}) diff --git a/frontend/src/components/navigation/NotificationsSheet.tsx b/frontend/src/components/navigation/NotificationsSheet.tsx new file mode 100644 index 00000000..1529084d --- /dev/null +++ b/frontend/src/components/navigation/NotificationsSheet.tsx @@ -0,0 +1,108 @@ +import { BottomSheet, BottomSheetHeader, BottomSheetContent } from '@/components/ui/bottom-sheet' +import { usePermissions, useQuestions } from '@/contexts/EventContext' +import { Bell, HelpCircle } from 'lucide-react' + +interface NotificationsSheetProps { + isOpen: boolean + onClose: () => void +} + +export function NotificationsSheet({ isOpen, onClose }: NotificationsSheetProps) { + const { + current: currentPermission, + pendingCount: permissionCount, + setShowDialog, + navigateToCurrent: navigateToPermission, + } = usePermissions() + const { + current: currentQuestion, + pendingCount: questionCount, + navigateToCurrent: navigateToQuestion, + } = useQuestions() + + const handlePermissionClick = () => { + navigateToPermission() + setShowDialog(true) + onClose() + } + + const handleQuestionClick = () => { + navigateToQuestion() + onClose() + } + + return ( + + + +
+
+ +

Pending permissions

+
+ {permissionCount === 0 ? ( +
+ You're all caught up +
+ ) : ( +
+ {currentPermission && ( + + )} + {permissionCount > 1 && ( +
+ +{permissionCount - 1} more +
+ )} +
+ )} +
+ +
+
+ +

Pending questions

+
+ {questionCount === 0 ? ( +
+ You're all caught up +
+ ) : ( +
+ {currentQuestion && ( + + )} + {questionCount > 1 && ( +
+ +{questionCount - 1} more +
+ )} +
+ )} +
+
+
+ ) +} diff --git a/frontend/src/components/navigation/RepoQuickSwitchSheet.test.tsx b/frontend/src/components/navigation/RepoQuickSwitchSheet.test.tsx new file mode 100644 index 00000000..dc9616cd --- /dev/null +++ b/frontend/src/components/navigation/RepoQuickSwitchSheet.test.tsx @@ -0,0 +1,120 @@ +import { render, screen, fireEvent, waitFor } from '@testing-library/react' +import { describe, it, expect, vi } from 'vitest' +import { MemoryRouter } from 'react-router-dom' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { RepoQuickSwitchSheet } from './RepoQuickSwitchSheet' +import { listRepos } from '@/api/repos' + +vi.mock('@/api/repos') + +function createWrapper() { + const queryClient = new QueryClient({ + defaultOptions: { + queries: { + retry: false, + }, + }, + }) + return ({ children }: { children: React.ReactNode }) => ( + + + {children} + + + ) +} + +describe('RepoQuickSwitchSheet', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('renders with loading state', async () => { + vi.mocked(listRepos).mockImplementation(() => new Promise(() => {})) + const handleClose = vi.fn() + render( + , + { wrapper: createWrapper() }, + ) + await waitFor(() => { + expect(screen.getByPlaceholderText('Search projects...')).toBeInTheDocument() + }) + }) + + it('renders empty state when no repos', async () => { + vi.mocked(listRepos).mockResolvedValue([]) + const handleClose = vi.fn() + render( + , + { wrapper: createWrapper() }, + ) + await waitFor(() => { + expect(screen.getByText('No repos found')).toBeInTheDocument() + }) + }) + + it('renders repo list and filters on search', async () => { + vi.mocked(listRepos).mockResolvedValue([ + { + id: 1, + repoUrl: 'https://github.com/test/repo1.git', + localPath: '/path/to/repo1', + sourcePath: null, + currentBranch: 'main', + isLocal: false, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }, + { + id: 2, + repoUrl: 'https://github.com/test/repo2.git', + localPath: '/path/to/repo2', + sourcePath: null, + currentBranch: 'develop', + isLocal: false, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }, + ]) + const handleClose = vi.fn() + render( + , + { wrapper: createWrapper() }, + ) + await waitFor(() => { + expect(screen.getByText('repo1')).toBeInTheDocument() + expect(screen.getByText('repo2')).toBeInTheDocument() + }) + const input = screen.getByPlaceholderText('Search projects...') + fireEvent.change(input, { target: { value: 'repo1' } }) + await waitFor(() => { + expect(screen.getByText('repo1')).toBeInTheDocument() + expect(screen.queryByText('repo2')).not.toBeInTheDocument() + }) + }) + + it('navigates on repo click without calling onClose', async () => { + vi.mocked(listRepos).mockResolvedValue([ + { + id: 1, + repoUrl: 'https://github.com/test/repo1.git', + localPath: '/path/to/repo1', + sourcePath: null, + currentBranch: 'main', + isLocal: false, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }, + ]) + const handleClose = vi.fn() + render( + , + { wrapper: createWrapper() }, + ) + await waitFor(() => { + expect(screen.getByText('repo1')).toBeInTheDocument() + }) + fireEvent.click(screen.getByText('repo1')) + expect(handleClose).not.toHaveBeenCalled() + }) +}) diff --git a/frontend/src/components/navigation/RepoQuickSwitchSheet.tsx b/frontend/src/components/navigation/RepoQuickSwitchSheet.tsx new file mode 100644 index 00000000..73b24505 --- /dev/null +++ b/frontend/src/components/navigation/RepoQuickSwitchSheet.tsx @@ -0,0 +1,112 @@ +import { useState, useMemo } from 'react' +import { useNavigate, useLocation } from 'react-router-dom' +import { useQuery } from '@tanstack/react-query' +import { Input } from '@/components/ui/input' +import { BottomSheet, BottomSheetHeader, BottomSheetContent } from '@/components/ui/bottom-sheet' +import { cn, getRepoDisplayName } from '@/lib/utils' +import { listRepos } from '@/api/repos' +import { FolderGit2, Check } from 'lucide-react' + +interface RepoQuickSwitchSheetProps { + isOpen: boolean + onClose: () => void +} + +export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetProps) { + const navigate = useNavigate() + const location = useLocation() + const [searchQuery, setSearchQuery] = useState('') + + const activeRepoId = useMemo(() => { + const match = location.pathname.match(/^\/repos\/(\d+)/) + return match ? Number(match[1]) : null + }, [location.pathname]) + + const { data: repos, isLoading } = useQuery({ + queryKey: ['repos'], + queryFn: listRepos, + enabled: isOpen, + }) + + const filteredRepos = useMemo(() => { + if (!repos) return [] + const sorted = [...repos].sort((a, b) => (b.lastAccessedAt ?? 0) - (a.lastAccessedAt ?? 0)) + if (!searchQuery.trim()) return sorted + const query = searchQuery.toLowerCase() + return sorted.filter((repo) => + getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath).toLowerCase().includes(query) + ) + }, [repos, searchQuery]) + + const handleClick = (id: number) => { + if (id === activeRepoId) { + onClose() + return + } + navigate(`/repos/${id}`, { replace: true }) + } + + return ( + + + setSearchQuery(e.target.value)} + autoFocus + className="flex-shrink-0" + /> + + + {isLoading ? ( +
+ {Array.from({ length: 5 }).map((_, i) => ( +
+ ))} +
+ ) : filteredRepos.length === 0 ? ( +
+ +

No repos found

+
+ ) : ( +
+ {filteredRepos.map((repo) => { + const isActive = repo.id === activeRepoId + return ( + + ) + })} +
+ )} + + + ) +} diff --git a/frontend/src/components/navigation/SessionMoreButton.tsx b/frontend/src/components/navigation/SessionMoreButton.tsx new file mode 100644 index 00000000..41a56b8f --- /dev/null +++ b/frontend/src/components/navigation/SessionMoreButton.tsx @@ -0,0 +1,19 @@ +import { MoreVertical } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { useMobileTabBar } from '@/hooks/useMobileTabBar' + +export function SessionMoreButton() { + const { open } = useMobileTabBar() + + return ( + + ) +} diff --git a/frontend/src/components/navigation/moreDrawerItems.test.ts b/frontend/src/components/navigation/moreDrawerItems.test.ts new file mode 100644 index 00000000..df3dd50c --- /dev/null +++ b/frontend/src/components/navigation/moreDrawerItems.test.ts @@ -0,0 +1,92 @@ +import { describe, it, expect } from 'vitest' +import { buildMoreItems } from './moreDrawerItems' + +describe('buildMoreItems', () => { + it('returns only Settings + Logout for root path', () => { + const items = buildMoreItems('/') + expect(items).toHaveLength(2) + expect(items[0].key).toBe('settings') + expect(items[1].key).toBe('logout') + }) + + it('returns repo-specific items with memory when plugin enabled for /repos/:id', () => { + const items = buildMoreItems('/repos/42', { memoryPluginEnabled: true }) + expect(items).toHaveLength(9) + expect(items[0].key).toBe('files') + expect(items[0].dialog).toBe('files') + expect(items[1].key).toBe('memory') + expect(items[1].to).toBe('/repos/42/memories') + expect(items[2].key).toBe('mcp') + expect(items[2].dialog).toBe('mcp') + expect(items[3].key).toBe('skills') + expect(items[3].dialog).toBe('skills') + expect(items[4].key).toBe('reset-permissions') + expect(items[4].dialog).toBe('resetPermissions') + expect(items[4].danger).toBe(true) + expect(items[5].key).toBe('schedules') + expect(items[5].to).toBe('/repos/42/schedules') + expect(items[6].key).toBe('source-control') + expect(items[6].dialog).toBe('sourceControl') + expect(items[7].key).toBe('settings') + expect(items[8].key).toBe('logout') + }) + + it('omits memory item for /repos/:id when plugin disabled', () => { + const items = buildMoreItems('/repos/42') + expect(items).toHaveLength(8) + expect(items.some((item) => item.key === 'memory')).toBe(false) + expect(items[0].key).toBe('files') + expect(items[1].key).toBe('mcp') + }) + + it('returns session-specific items with memory when plugin enabled for /repos/:id/sessions/:sid', () => { + const items = buildMoreItems('/repos/42/sessions/abc', { memoryPluginEnabled: true }) + expect(items).toHaveLength(9) + expect(items[0].key).toBe('files') + expect(items[1].key).toBe('memory') + expect(items[2].key).toBe('mcp') + expect(items[3].key).toBe('skills') + expect(items[4].key).toBe('lsp') + expect(items[4].dialog).toBe('lsp') + expect(items[5].key).toBe('reset-permissions') + expect(items[6].key).toBe('source-control') + expect(items[7].key).toBe('settings') + expect(items[8].key).toBe('logout') + }) + + it('omits memory item for /repos/:id/sessions/:sid when plugin disabled', () => { + const items = buildMoreItems('/repos/42/sessions/abc') + expect(items).toHaveLength(8) + expect(items.some((item) => item.key === 'memory')).toBe(false) + expect(items[0].key).toBe('files') + expect(items[1].key).toBe('mcp') + }) + + it('returns only Settings + Logout for /repos/:id/memories', () => { + const items = buildMoreItems('/repos/42/memories') + expect(items).toHaveLength(2) + expect(items[0].key).toBe('settings') + expect(items[1].key).toBe('logout') + }) + + it('returns only Settings + Logout for /schedules', () => { + const items = buildMoreItems('/schedules') + expect(items).toHaveLength(2) + expect(items[0].key).toBe('settings') + expect(items[1].key).toBe('logout') + }) + + it('returns only Settings + Logout for /repos/:id/schedules', () => { + const items = buildMoreItems('/repos/42/schedules') + expect(items).toHaveLength(2) + expect(items[0].key).toBe('settings') + expect(items[1].key).toBe('logout') + }) + + it('returns only Settings + Logout for unknown paths', () => { + const items = buildMoreItems('/unknown/path') + expect(items).toHaveLength(2) + expect(items[0].key).toBe('settings') + expect(items[1].key).toBe('logout') + }) +}) diff --git a/frontend/src/components/navigation/moreDrawerItems.ts b/frontend/src/components/navigation/moreDrawerItems.ts new file mode 100644 index 00000000..a996a47f --- /dev/null +++ b/frontend/src/components/navigation/moreDrawerItems.ts @@ -0,0 +1,77 @@ +import type { LucideIcon } from 'lucide-react' +import { FolderOpen, Brain, Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, Code2, Settings, LogOut } from 'lucide-react' + +export interface MoreDrawerItem { + key: string + label: string + icon: LucideIcon + to?: string + dialog?: string + danger?: boolean +} + +export interface BuildMoreItemsOptions { + memoryPluginEnabled?: boolean +} + +export function buildMoreItems(pathname: string, options: BuildMoreItemsOptions = {}): MoreDrawerItem[] { + const { memoryPluginEnabled = false } = options + const baseItems: MoreDrawerItem[] = [ + { key: 'settings', label: 'Settings', icon: Settings }, + { key: 'logout', label: 'Logout', icon: LogOut }, + ] + + // Root path - no route-specific items + if (pathname === '/') { + return baseItems + } + + // RepoDetail: /repos/:id + const repoDetailMatch = /^\/repos\/(\d+)$/.exec(pathname) + if (repoDetailMatch) { + const id = repoDetailMatch[1] + return [ + { key: 'files', label: 'Files', icon: FolderOpen, dialog: 'files' }, + ...(memoryPluginEnabled + ? [{ key: 'memory', label: 'Memory', icon: Brain, to: `/repos/${id}/memories` }] + : []), + { key: 'mcp', label: 'MCP', icon: Plug, dialog: 'mcp' }, + { key: 'skills', label: 'Skills', icon: Sparkles, dialog: 'skills' }, + { key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true }, + { key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${id}/schedules` }, + { key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' }, + ...baseItems, + ] + } + + // SessionDetail: /repos/:id/sessions/:sid + const sessionDetailMatch = /^\/repos\/(\d+)\/sessions\/[^/]+$/.exec(pathname) + if (sessionDetailMatch) { + const id = sessionDetailMatch[1] + return [ + { key: 'files', label: 'Files', icon: FolderOpen, dialog: 'files' }, + ...(memoryPluginEnabled + ? [{ key: 'memory', label: 'Memory', icon: Brain, to: `/repos/${id}/memories` }] + : []), + { key: 'mcp', label: 'MCP', icon: Plug, dialog: 'mcp' }, + { key: 'skills', label: 'Skills', icon: Sparkles, dialog: 'skills' }, + { key: 'lsp', label: 'LSP', icon: Code2, dialog: 'lsp' }, + { key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true }, + { key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' }, + ...baseItems, + ] + } + + // Memories: /repos/:id/memories - no extra items + if (/^\/repos\/\d+\/memories$/.test(pathname)) { + return baseItems + } + + // Schedules routes - no extra items + if (pathname === '/schedules' || /^\/repos\/\d+\/schedules$/.test(pathname)) { + return baseItems + } + + // Unknown path - return base items only + return baseItems +} diff --git a/frontend/src/components/repo/RepoCard.test.tsx b/frontend/src/components/repo/RepoCard.test.tsx index 162e2142..41440e10 100644 --- a/frontend/src/components/repo/RepoCard.test.tsx +++ b/frontend/src/components/repo/RepoCard.test.tsx @@ -1,6 +1,7 @@ import { describe, it, expect, vi } from 'vitest' import { render, screen, fireEvent } from '@testing-library/react' import { BrowserRouter } from 'react-router-dom' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { RepoCard } from './RepoCard' const mockNavigate = vi.fn() @@ -15,7 +16,7 @@ vi.mock('react-router-dom', async () => { const defaultProps = { repo: { id: 1, - repoUrl: 'https://github.com/test/repo', + repoUrl: 'https://github.com/test/test-repo', localPath: 'repos/test-repo', fullPath: '/Users/test/repos/test-repo', branch: 'main', @@ -31,7 +32,14 @@ const defaultProps = { } const renderWithRouter = (ui: React.ReactElement) => { - return render({ui}) + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }) + return render( + + {ui} + + ) } describe('RepoCard', () => { @@ -50,8 +58,10 @@ describe('RepoCard', () => { expect(mockNavigate).not.toHaveBeenCalled() }) - it('should not show checkbox when manageMode is false', () => { - renderWithRouter() + it('should not show checkbox when onSelect is not provided', () => { + const { onSelect, ...propsWithoutSelect } = defaultProps + void onSelect + renderWithRouter() expect(screen.queryByRole('checkbox')).not.toBeInTheDocument() }) @@ -88,9 +98,9 @@ describe('RepoCard', () => { hasChanges: true, }, } - renderWithRouter() + const { container } = renderWithRouter() - const indicator = screen.getByTestId('dirty-indicator') || screen.container.querySelector('.bg-orange-500') + const indicator = container.querySelector('.bg-orange-500') expect(indicator).toBeTruthy() }) @@ -107,8 +117,8 @@ describe('RepoCard', () => { } renderWithRouter() - expect(screen.getByText('↑2')).toBeInTheDocument() - expect(screen.getByText('↓1')).toBeInTheDocument() + expect(screen.getByText(/↑2/)).toBeInTheDocument() + expect(screen.getByText(/↓1/)).toBeInTheDocument() }) it('should display activity label when provided', () => { diff --git a/frontend/src/components/repo/RepoListControls.tsx b/frontend/src/components/repo/RepoListControls.tsx index 5397d5f4..c4d13b56 100644 --- a/frontend/src/components/repo/RepoListControls.tsx +++ b/frontend/src/components/repo/RepoListControls.tsx @@ -1,5 +1,5 @@ import { useState } from 'react' -import { Search, SlidersHorizontal, Trash2 } from 'lucide-react' +import { Search, SlidersHorizontal, Trash2, X } from 'lucide-react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { @@ -99,11 +99,11 @@ export function RepoListControls({
diff --git a/frontend/src/components/repo/repo-list-state.test.ts b/frontend/src/components/repo/repo-list-state.test.ts index 1685962b..9f38dc7c 100644 --- a/frontend/src/components/repo/repo-list-state.test.ts +++ b/frontend/src/components/repo/repo-list-state.test.ts @@ -149,22 +149,22 @@ describe('repo-list-state', () => { it('should filter by display name', () => { const repos = [ - createMockRepo({ id: 1, localPath: 'repos/test-repo' }), - createMockRepo({ id: 2, localPath: 'repos/other-repo' }), + createMockRepo({ id: 1, repoUrl: 'https://github.com/org/test-repo', localPath: 'repos/test-repo' }), + createMockRepo({ id: 2, repoUrl: 'https://github.com/org/other-repo', localPath: 'repos/other-repo' }), ] const viewModels = repos.map(r => ({ ...r, attentionState: getAttentionState(r), activityTimestamp: getActivityTimestamp(r) })) - const result = filterReposBySearch(viewModels, 'test') + const result = filterReposBySearch(viewModels, 'test-repo') expect(result).toHaveLength(1) expect(result[0].id).toBe(1) }) it('should filter case-insensitively', () => { const repos = [ - createMockRepo({ id: 1, localPath: 'repos/test-repo' }), - createMockRepo({ id: 2, localPath: 'repos/other-repo' }), + createMockRepo({ id: 1, repoUrl: 'https://github.com/org/test-repo', localPath: 'repos/test-repo' }), + createMockRepo({ id: 2, repoUrl: 'https://github.com/org/other-repo', localPath: 'repos/other-repo' }), ] const viewModels = repos.map(r => ({ ...r, attentionState: getAttentionState(r), activityTimestamp: getActivityTimestamp(r) })) - const result = filterReposBySearch(viewModels, 'TEST') + const result = filterReposBySearch(viewModels, 'TEST-REPO') expect(result).toHaveLength(1) }) }) @@ -253,9 +253,9 @@ describe('repo-list-state', () => { it('should sort alphabetically by name', () => { const repos = [ - createViewModel(1, { localPath: 'repos/zebra' }), - createViewModel(2, { localPath: 'repos/alpha' }), - createViewModel(3, { localPath: 'repos/middle' }), + createViewModel(1, { repoUrl: 'https://github.com/org/zebra', localPath: 'repos/zebra' }), + createViewModel(2, { repoUrl: 'https://github.com/org/alpha', localPath: 'repos/alpha' }), + createViewModel(3, { repoUrl: 'https://github.com/org/middle', localPath: 'repos/middle' }), ] const result = sortRepos(repos, 'name') expect(result[0].id).toBe(2) @@ -315,15 +315,17 @@ describe('repo-list-state', () => { it('should return attention section for attention filter', () => { const now = Date.now() - const repos = [ - createViewModel(1, { + const repos: RepoViewModel[] = [ + { + ...createMockRepo({ id: 1 }), activityTimestamp: now, attentionState: { hasChanges: true, ahead: 0, behind: 0, isCloneStatusReady: true } - }), - createViewModel(2, { + }, + { + ...createMockRepo({ id: 2 }), activityTimestamp: now, attentionState: { hasChanges: false, ahead: 0, behind: 0, isCloneStatusReady: true } - }), + }, ] const result = groupReposIntoSections(repos, 'attention', 'recent') expect(result).toHaveLength(1) diff --git a/frontend/src/components/schedules/RunHistoryCards.tsx b/frontend/src/components/schedules/RunHistoryCards.tsx index 18fd7106..a9f1cee9 100644 --- a/frontend/src/components/schedules/RunHistoryCards.tsx +++ b/frontend/src/components/schedules/RunHistoryCards.tsx @@ -73,7 +73,7 @@ export function RunHistoryCards({ return (
-
+
{runs.map((run, index) => { const isExpanded = expandedRunId === run.id const displayRun = isExpanded && runDetail ? runDetail : run diff --git a/frontend/src/components/schedules/ScheduleTabMenu.tsx b/frontend/src/components/schedules/ScheduleTabMenu.tsx index 613ddc69..d81358b4 100644 --- a/frontend/src/components/schedules/ScheduleTabMenu.tsx +++ b/frontend/src/components/schedules/ScheduleTabMenu.tsx @@ -15,41 +15,41 @@ export function ScheduleTabMenu({ activeTab, onTabChange, className }: ScheduleT
) diff --git a/frontend/src/components/session/SessionCard.tsx b/frontend/src/components/session/SessionCard.tsx index 6d3a89ab..09732f43 100644 --- a/frontend/src/components/session/SessionCard.tsx +++ b/frontend/src/components/session/SessionCard.tsx @@ -70,7 +70,11 @@ export const SessionCard = ({ } hover:shadow-lg`} onClick={() => { if (!isOpen) { - onSelect(session.id); + if (manageMode) { + onToggleSelection(!isSelected); + } else { + onSelect(session.id); + } } }} > diff --git a/frontend/src/components/session/SessionList.tsx b/frontend/src/components/session/SessionList.tsx index 93920d62..d63e7647 100644 --- a/frontend/src/components/session/SessionList.tsx +++ b/frontend/src/components/session/SessionList.tsx @@ -1,9 +1,11 @@ import { useState, useMemo } from "react"; import { useSessions, useDeleteSession, useCreateSession } from "@/hooks/useOpenCode"; -import { ListToolbar } from "@/components/ui/list-toolbar"; import { DeleteSessionDialog } from "./DeleteSessionDialog"; import { SessionCard } from "./SessionCard"; import { Card } from "@/components/ui/card"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Search, Trash2, Pencil, X } from "lucide-react"; interface SessionListProps { opcodeUrl: string; @@ -24,13 +26,9 @@ export const SessionList = ({ onSelectSession(newSession.id); }); const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); - const [sessionToDelete, setSessionToDelete] = useState< - string | string[] | null - >(null); + const [sessionToDelete, setSessionToDelete] = useState(null); const [searchQuery, setSearchQuery] = useState(""); - const [selectedSessions, setSelectedSessions] = useState>( - new Set(), - ); + const [selectedSessions, setSelectedSessions] = useState>(new Set()); const [manageMode, setManageMode] = useState(false); const filteredSessions = useMemo(() => { @@ -53,14 +51,12 @@ export const SessionList = ({ }, [sessions, searchQuery, directory]); const todaySessions = useMemo(() => { - if (!filteredSessions) return []; const today = new Date(); today.setHours(0, 0, 0, 0); return filteredSessions.filter((session) => new Date(session.time.updated) >= today); }, [filteredSessions]); const olderSessions = useMemo(() => { - if (!filteredSessions) return []; const today = new Date(); today.setHours(0, 0, 0, 0); return filteredSessions.filter((session) => new Date(session.time.updated) < today); @@ -88,10 +84,7 @@ export const SessionList = ({ ); } - const handleDelete = ( - sessionId: string, - e: React.MouseEvent, - ) => { + const handleDelete = (sessionId: string, e: React.MouseEvent) => { e.stopPropagation(); setSessionToDelete(sessionId); setDeleteDialogOpen(true); @@ -103,6 +96,7 @@ export const SessionList = ({ setDeleteDialogOpen(false); setSessionToDelete(null); setSelectedSessions(new Set()); + setManageMode(false); } }; @@ -110,6 +104,7 @@ export const SessionList = ({ setDeleteDialogOpen(false); setSessionToDelete(null); setSelectedSessions(new Set()); + setManageMode(false); }; const toggleSessionSelection = (sessionId: string, selected: boolean) => { @@ -122,29 +117,15 @@ export const SessionList = ({ setSelectedSessions(newSelected); }; - const toggleManageMode = () => { - setManageMode((prev) => { - if (!prev) { - return true; - } else { - setSelectedSessions(new Set()); - return false; - } - }); - }; + const allVisibleSelected = + filteredSessions.length > 0 && + filteredSessions.every((s) => selectedSessions.has(s.id)); const toggleSelectAll = () => { - if (!filteredSessions || filteredSessions.length === 0) return; - - const allFilteredSelected = filteredSessions.every((session) => - selectedSessions.has(session.id), - ); - - if (allFilteredSelected) { + if (allVisibleSelected) { setSelectedSessions(new Set()); } else { - const filteredIds = filteredSessions.map((s) => s.id); - setSelectedSessions(new Set(filteredIds)); + setSelectedSessions(new Set(filteredSessions.map((s) => s.id))); } }; @@ -155,30 +136,60 @@ export const SessionList = ({ } }; - const handleDeleteAll = () => { - if (!filteredSessions || filteredSessions.length === 0) return; - setSessionToDelete(filteredSessions.map((s) => s.id)); - setDeleteDialogOpen(true); - }; - return (
- 0 && - filteredSessions.every((session) => selectedSessions.has(session.id)) - } - onToggleSelectAll={toggleSelectAll} - onDelete={handleBulkDelete} - onDeleteAll={handleDeleteAll} - manageMode={manageMode} - onToggleManageMode={toggleManageMode} - /> + {manageMode ? ( +
+ + {selectedSessions.size} selected + + + + +
+ ) : ( +
+
+ + setSearchQuery(e.target.value)} + className="pl-9 h-9" + /> +
+ +
+ )}
@@ -202,9 +213,7 @@ export const SessionList = ({ isActive={activeSessionID === session.id} manageMode={manageMode} onSelect={onSelectSession} - onToggleSelection={(selected) => { - toggleSessionSelection(session.id, selected); - }} + onToggleSelection={(selected) => toggleSessionSelection(session.id, selected)} onDelete={(e) => handleDelete(session.id, e)} /> ))} @@ -222,9 +231,7 @@ export const SessionList = ({ isActive={activeSessionID === session.id} manageMode={manageMode} onSelect={onSelectSession} - onToggleSelection={(selected) => { - toggleSessionSelection(session.id, selected); - }} + onToggleSelection={(selected) => toggleSessionSelection(session.id, selected)} onDelete={(e) => handleDelete(session.id, e)} /> ))} @@ -239,9 +246,7 @@ export const SessionList = ({ onConfirm={confirmDelete} onCancel={cancelDelete} isDeleting={deleteSession.isPending} - sessionCount={ - Array.isArray(sessionToDelete) ? sessionToDelete.length : 1 - } + sessionCount={Array.isArray(sessionToDelete) ? sessionToDelete.length : 1} />
); diff --git a/frontend/src/components/settings/ApiTokensPanel.tsx b/frontend/src/components/settings/ApiTokensPanel.tsx new file mode 100644 index 00000000..5c192880 --- /dev/null +++ b/frontend/src/components/settings/ApiTokensPanel.tsx @@ -0,0 +1,180 @@ +import { useState, useEffect } from 'react' +import { useApiTokens } from '@/hooks/useApiTokens' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from '@/components/ui/dialog' +import { Alert, AlertDescription } from '@/components/ui/alert' +import { Card, CardContent } from '@/components/ui/card' +import { Key, Trash2, Copy, Check, X } from 'lucide-react' + +const NEW_TOKEN_AUTO_DISMISS_MS = 60_000 + +export function ApiTokensPanel() { + const { + tokens, + isLoading, + createToken, + revokeToken, + showNewToken, + clearNewToken, + isCreating, + isRevoking, + } = useApiTokens() + const [newTokenName, setNewTokenName] = useState('') + const [copied, setCopied] = useState(false) + const [createDialogOpen, setCreateDialogOpen] = useState(false) + + useEffect(() => { + if (!showNewToken) return + const timer = window.setTimeout(clearNewToken, NEW_TOKEN_AUTO_DISMISS_MS) + return () => window.clearTimeout(timer) + }, [showNewToken, clearNewToken]) + + const handleCreate = () => { + const trimmed = newTokenName.trim() + if (!trimmed) return + createToken({ name: trimmed }) + setNewTokenName('') + setCreateDialogOpen(false) + } + + const handleCopy = async () => { + if (!showNewToken) return + try { + await navigator.clipboard.writeText(showNewToken) + setCopied(true) + window.setTimeout(() => setCopied(false), 2000) + } catch { + setCopied(false) + } + } + + const formatDate = (timestamp: number | null) => { + if (!timestamp) return 'Never' + return new Date(timestamp).toLocaleDateString() + } + + return ( +
+
+
+

API Tokens

+

+ Manage API tokens for external access +

+
+ + + + + + + Create API Token + + Create a new API token for workspace plugin access. The token will be shown once and cannot be retrieved again. + + +
+ + setNewTokenName(e.target.value)} + placeholder="e.g., OpenCode TUI" + className="mt-2" + /> +
+ + + + +
+
+
+ + {showNewToken && ( + + +
+
+ {showNewToken} +
+
+ + +
+
+

+ Copy this token now. It will not be shown again and will auto-dismiss shortly. +

+
+
+ )} + + {isLoading ? ( +
Loading tokens...
+ ) : tokens.length === 0 ? ( +
+ No API tokens yet. Create one to get started. +
+ ) : ( +
+ {tokens.map((token) => ( + + +
+
{token.name}
+
+ Scope: {token.scope} + Created: {formatDate(token.createdAt)} + Last used: {formatDate(token.lastUsedAt)} +
+
+ +
+
+ ))} +
+ )} +
+ ) +} diff --git a/frontend/src/components/settings/OAuthAuthorizeDialog.tsx b/frontend/src/components/settings/OAuthAuthorizeDialog.tsx index 4decf2b2..f9d5085f 100644 --- a/frontend/src/components/settings/OAuthAuthorizeDialog.tsx +++ b/frontend/src/components/settings/OAuthAuthorizeDialog.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react' +import { useState, useMemo, useEffect, useCallback } from 'react' import { Button } from '@/components/ui/button' import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { Input } from '@/components/ui/input' @@ -61,10 +61,22 @@ export function OAuthAuthorizeDialog({ const [error, setError] = useState(null) const [selectedMethodIndex, setSelectedMethodIndex] = useState(null) const [promptInputs, setPromptInputs] = useState>>({}) + const [autoStarted, setAutoStarted] = useState(false) - const getMethodInputs = (methodIndex: number) => promptInputs[methodIndex] || {} + const getMethodInputs = useCallback((methodIndex: number) => promptInputs[methodIndex] || {}, [promptInputs]) - const handleAuthorize = async (methodIndex: number) => { + const oauthMethods = useMemo(() => { + return methods + .flatMap((method, index) => method.type === 'oauth' ? [{ method, index }] : []) + .filter(({ method }: { method: ProviderAuthMethod }) => { + if (providerId === 'openai' && isBrowserLocalMethod(method)) { + return false + } + return true + }) + }, [methods, providerId]) + + const handleAuthorize = useCallback(async (methodIndex: number) => { const method = methods[methodIndex] const methodInputs = getMethodInputs(methodIndex) const visiblePrompts = getVisiblePrompts(method, methodInputs) @@ -93,7 +105,18 @@ export function OAuthAuthorizeDialog({ } finally { setIsLoading(false) } - } + }, [methods, providerId, onSuccess, getMethodInputs]) + + useEffect(() => { + if (open && oauthMethods.length === 1 && !autoStarted && !isLoading) { + const { index } = oauthMethods[0] + setAutoStarted(true) + setSelectedMethodIndex(index) + if (!hasPrompts(methods[index])) { + void handleAuthorize(index) + } + } + }, [open, oauthMethods, autoStarted, isLoading, methods, handleAuthorize]) const handleMethodSelection = (methodIndex: number) => { setError(null) @@ -121,11 +144,9 @@ export function OAuthAuthorizeDialog({ onOpenChange(false) } - const oauthMethods = methods.flatMap((method, index) => method.type === 'oauth' ? [{ method, index }] : []) - return ( - + Connect to {providerName} @@ -148,25 +169,25 @@ export function OAuthAuthorizeDialog({ return (
-
+
{isBrowserLocal && ( - + Localhost only )}
{selectedMethodIndex === index && hasPrompts(method) && ( -
+
{visiblePrompts.map((prompt) => ( prompt.type === 'text' ? (
@@ -214,7 +235,7 @@ export function OAuthAuthorizeDialog({ )} {isBrowserLocal && ( -

+

This method relies on a callback server started by OpenCode and may not work when OCM is remote.

)} diff --git a/frontend/src/components/settings/OAuthCallbackDialog.tsx b/frontend/src/components/settings/OAuthCallbackDialog.tsx index d6ea704e..edee18ea 100644 --- a/frontend/src/components/settings/OAuthCallbackDialog.tsx +++ b/frontend/src/components/settings/OAuthCallbackDialog.tsx @@ -4,6 +4,8 @@ import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { Loader2, ExternalLink, CheckCircle } from 'lucide-react' +import { CopyButton } from '@/components/ui/copy-button' +import { showToast } from '@/lib/toast' import { oauthApi, type OAuthAuthorizeResponse } from '@/api/oauth' import { mapOAuthError } from '@/lib/oauthErrors' @@ -66,6 +68,10 @@ export function OAuthCallbackDialog({ const isAutoMethod = authResponse.method === 'auto' + // Extract device/user code from instructions (e.g., "Enter code: 596A-E304") + const codeMatch = authResponse.instructions.match(/(?:Enter code|User code|Device code)[:\s]+([A-Z0-9-]+)/i) + const deviceCode = codeMatch ? codeMatch[1] : '' + return ( @@ -89,20 +95,57 @@ export function OAuthCallbackDialog({

{authResponse.instructions}

- + + {deviceCode && ( +
+ + {deviceCode} + + showToast.success('Code copied to clipboard')} + /> +
+ )} + +
+ + showToast.success('URL copied to clipboard')} + /> +
{!isAutoMethod && (
- +
+ + showToast.success('Code copied to clipboard')} + /> +
- c.isDefault)?.content?.plugin as string[] | undefined) ?? []).includes('@opencode-manager/memory')} - onToggle={async (enabled) => { - const defaultConfig = configs.find(c => c.isDefault) - if (!defaultConfig) return - - const currentPlugins = (defaultConfig.content?.plugin as string[] | undefined) ?? [] - const memoryPlugin = '@opencode-manager/memory' - const newPlugins = enabled - ? currentPlugins.includes(memoryPlugin) - ? currentPlugins - : [...currentPlugins, memoryPlugin] - : currentPlugins.filter(p => p !== memoryPlugin) - - await updateConfigContent(defaultConfig.name, { - ...defaultConfig.content, - plugin: newPlugins.length > 0 ? newPlugins : undefined - }, true) - - queryClient.invalidateQueries({ queryKey: ['memory-plugin-status'] }) - }} - /> + = { }, } +const findTrashButton = (): HTMLButtonElement | null => { + const buttons = Array.from(document.querySelectorAll('button')) + for (const btn of buttons) { + const svg = btn.querySelector('svg') + if (svg && svg.getAttribute('class')?.includes('trash')) { + return btn + } + } + return null +} + describe('OpenCodeModelsEditor', () => { describe('rendering', () => { it('should render empty state when no providers configured', () => { @@ -68,15 +79,7 @@ describe('OpenCodeModelsEditor', () => { const onChange = vi.fn() render() - const deleteButtons = document.querySelectorAll('button') - let deleteButton: HTMLButtonElement | null = null - deleteButtons.forEach(btn => { - const svg = btn.querySelector('svg') - if (svg && svg.className.baseVal.includes('Trash2')) { - deleteButton = btn as HTMLButtonElement - } - }) - + const deleteButton = findTrashButton() expect(deleteButton).not.toBeNull() if (deleteButton) { fireEvent.click(deleteButton) @@ -107,15 +110,7 @@ describe('OpenCodeModelsEditor', () => { render() - const deleteButtons = document.querySelectorAll('button') - let deleteButton: HTMLButtonElement | null = null - deleteButtons.forEach(btn => { - const svg = btn.querySelector('svg') - if (svg && svg.className.baseVal.includes('Trash2')) { - deleteButton = btn as HTMLButtonElement - } - }) - + const deleteButton = findTrashButton() if (deleteButton) { fireEvent.click(deleteButton) } @@ -155,15 +150,13 @@ describe('OpenCodeModelDialog', () => { }) }) - it('should require display name when submitting empty form', async () => { + it('should disable create button when required fields are empty', async () => { const { OpenCodeModelDialog } = await import('./OpenCodeModelDialog') render() - const createButton = screen.getByRole('button', { name: /create/i }) - fireEvent.click(createButton) - await waitFor(() => { - expect(screen.getByText(/display name is required/i)).toBeInTheDocument() + const createButton = screen.getByRole('button', { name: /create/i }) + expect(createButton).toBeDisabled() }) }) @@ -172,15 +165,12 @@ describe('OpenCodeModelDialog', () => { render() const modelIdInput = document.querySelector('input[name="modelId"]') as HTMLInputElement - if (modelIdInput) { - fireEvent.change(modelIdInput, { target: { value: 'invalid model id!' } }) - const createButton = screen.getByRole('button', { name: /create/i }) - fireEvent.click(createButton) + expect(modelIdInput).not.toBeNull() + fireEvent.change(modelIdInput, { target: { value: 'invalid model id!' } }) - await waitFor(() => { - expect(screen.getByText(/alphanumeric/i)).toBeInTheDocument() - }) - } + await waitFor(() => { + expect(screen.getByText(/must use only letters, numbers/i)).toBeInTheDocument() + }) }) }) @@ -191,15 +181,18 @@ describe('OpenCodeModelDialog', () => { render() const modelIdInput = document.querySelector('input[name="modelId"]') as HTMLInputElement - const nameInput = document.querySelector('input[name="name"]') as HTMLInputElement + const displayNameInput = document.querySelector('input[name="displayName"]') as HTMLInputElement - if (modelIdInput && nameInput) { - fireEvent.change(modelIdInput, { target: { value: 'gpt-5' } }) - fireEvent.change(nameInput, { target: { value: 'GPT-5' } }) - } + expect(modelIdInput).not.toBeNull() + expect(displayNameInput).not.toBeNull() + fireEvent.change(modelIdInput, { target: { value: 'gpt-5' } }) + fireEvent.change(displayNameInput, { target: { value: 'GPT-5' } }) - const createButton = screen.getByRole('button', { name: /create/i }) - fireEvent.click(createButton) + await waitFor(() => { + expect(screen.getByRole('button', { name: /create/i })).not.toBeDisabled() + }) + + fireEvent.click(screen.getByRole('button', { name: /create/i })) await waitFor(() => { expect(onSubmit).toHaveBeenCalledWith( @@ -218,19 +211,25 @@ describe('OpenCodeModelDialog', () => { render() const modelIdInput = document.querySelector('input[name="modelId"]') as HTMLInputElement - const nameInput = document.querySelector('input[name="name"]') as HTMLInputElement + const displayNameInput = document.querySelector('input[name="displayName"]') as HTMLInputElement const contextLimitInput = document.querySelector('input[name="contextLimit"]') as HTMLInputElement const outputLimitInput = document.querySelector('input[name="outputLimit"]') as HTMLInputElement - if (modelIdInput && nameInput && contextLimitInput && outputLimitInput) { - fireEvent.change(modelIdInput, { target: { value: 'gpt-5' } }) - fireEvent.change(nameInput, { target: { value: 'GPT-5' } }) - fireEvent.change(contextLimitInput, { target: { value: '256000' } }) - fireEvent.change(outputLimitInput, { target: { value: '8192' } }) - } + expect(modelIdInput).not.toBeNull() + expect(displayNameInput).not.toBeNull() + expect(contextLimitInput).not.toBeNull() + expect(outputLimitInput).not.toBeNull() - const createButton = screen.getByRole('button', { name: /create/i }) - fireEvent.click(createButton) + fireEvent.change(modelIdInput, { target: { value: 'gpt-5' } }) + fireEvent.change(displayNameInput, { target: { value: 'GPT-5' } }) + fireEvent.change(contextLimitInput, { target: { value: '256000' } }) + fireEvent.change(outputLimitInput, { target: { value: '8192' } }) + + await waitFor(() => { + expect(screen.getByRole('button', { name: /create/i })).not.toBeDisabled() + }) + + fireEvent.click(screen.getByRole('button', { name: /create/i })) await waitFor(() => { expect(onSubmit).toHaveBeenCalledWith( @@ -300,6 +299,7 @@ describe('OpenCodeModelDialog', () => { providerId: 'openai', modelId: 'gpt-4o', model: { + id: 'gpt-4o', name: 'GPT-4o', limit: { context: 128000, output: 4096 }, reasoning: true, @@ -321,6 +321,10 @@ describe('OpenCodeModelDialog', () => { target: { value: 'my-friendly-model' }, }) + await waitFor(() => { + expect(screen.getByRole('button', { name: /update/i })).not.toBeDisabled() + }) + fireEvent.click(screen.getByRole('button', { name: /update/i })) await waitFor(() => { diff --git a/frontend/src/components/settings/SettingsDialog.tsx b/frontend/src/components/settings/SettingsDialog.tsx index c204a6f3..e2fcff2d 100644 --- a/frontend/src/components/settings/SettingsDialog.tsx +++ b/frontend/src/components/settings/SettingsDialog.tsx @@ -1,4 +1,4 @@ -import { useState, useRef, useEffect, useCallback } from 'react' +import { useState, useRef, useEffect } from 'react' import { GeneralSettings } from '@/components/settings/GeneralSettings' import { GitSettings } from '@/components/settings/GitSettings' import { KeyboardShortcuts } from '@/components/settings/KeyboardShortcuts' @@ -7,31 +7,25 @@ import { ProviderSettings } from '@/components/settings/ProviderSettings' import { AccountSettings } from '@/components/settings/AccountSettings' import { VoiceSettings } from '@/components/settings/VoiceSettings' import { NotificationSettings } from '@/components/settings/NotificationSettings' +import { ApiTokensPanel } from '@/components/settings/ApiTokensPanel' import { Dialog, DialogContent } from '@/components/ui/dialog' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' -import { Settings2, Keyboard, Code, ChevronLeft, Key, GitBranch, User, Volume2, Bell, X } from 'lucide-react' +import { Settings2, Keyboard, Code, ChevronLeft, Key, GitBranch, User, Volume2, Bell, X, ShieldCheck } from 'lucide-react' import { Button } from '@/components/ui/button' -import { useSwipeToClose } from '@/hooks/useMobile' +import { useSwipeBack } from '@/hooks/useMobile' import { useSettingsDialog } from '@/hooks/useSettingsDialog' -type SettingsView = 'menu' | 'general' | 'git' | 'shortcuts' | 'opencode' | 'providers' | 'account' | 'voice' | 'notifications' +type SettingsView = 'menu' | 'general' | 'git' | 'shortcuts' | 'opencode' | 'providers' | 'account' | 'voice' | 'notifications' | 'tokens' export function SettingsDialog() { const { isOpen, close, activeTab, setActiveTab } = useSettingsDialog() const [mobileView, setMobileView] = useState('menu') const contentRef = useRef(null) - const handleSwipeBack = useCallback(() => { - if (mobileView === 'menu') { - setMobileView('menu') - close() - } else { - setMobileView('menu') - } - }, [mobileView, close]) - - const { bind: bindSwipe, swipeStyles } = useSwipeToClose(handleSwipeBack, { + const { bind: bindSwipe, swipeStyles } = useSwipeBack(close, { enabled: isOpen, + canBack: () => mobileView !== 'menu', + onBack: () => setMobileView('menu'), }) useEffect(() => { @@ -59,6 +53,7 @@ export function SettingsDialog() { { id: 'shortcuts', icon: Keyboard, label: 'Keyboard Shortcuts', description: 'Customize keyboard shortcuts' }, { id: 'opencode', icon: Code, label: 'OpenCode Config', description: 'Manage OpenCode configurations, commands, and agents' }, { id: 'providers', icon: Key, label: 'Providers', description: 'Manage AI provider API keys' }, + { id: 'tokens', icon: ShieldCheck, label: 'API Tokens', description: 'Manage API tokens for external access' }, ] const handleTabChange = (tab: string) => { @@ -89,46 +84,50 @@ export function SettingsDialog() {
- - - Account - - - General - - - Notify - - - Voice - - - Git - - - Shortcuts - - - OpenCode - - - Providers - - + + + Account + + + General + + + Notify + + + Voice + + + Git + + + Shortcuts + + + OpenCode + + + Providers + + + Tokens + +
-
-
- - - - - - - - -
-
+
+
+ + + + + + + + + +
+
@@ -185,14 +184,15 @@ export function SettingsDialog() {
)} - {mobileView === 'account' &&
} - {mobileView === 'general' &&
} - {mobileView === 'notifications' &&
} - {mobileView === 'voice' &&
} - {mobileView === 'git' &&
} - {mobileView === 'shortcuts' &&
} - {mobileView === 'opencode' &&
} - {mobileView === 'providers' &&
} + {mobileView === 'account' &&
} + {mobileView === 'general' &&
} + {mobileView === 'notifications' &&
} + {mobileView === 'voice' &&
} + {mobileView === 'git' &&
} + {mobileView === 'shortcuts' &&
} + {mobileView === 'opencode' &&
} + {mobileView === 'providers' &&
} + {mobileView === 'tokens' &&
}
diff --git a/frontend/src/components/settings/TTSSettings.tsx b/frontend/src/components/settings/TTSSettings.tsx index fa8923ca..86bc1f97 100644 --- a/frontend/src/components/settings/TTSSettings.tsx +++ b/frontend/src/components/settings/TTSSettings.tsx @@ -31,6 +31,7 @@ function isKokoroStyleVoice(voice: string): boolean { const ttsFormSchema = z.object({ enabled: z.boolean(), provider: z.enum(['external', 'builtin']), + autoPlay: z.boolean(), endpoint: z.string(), apiKey: z.string(), voice: z.string(), @@ -175,6 +176,7 @@ export function TTSSettings() { reset({ enabled: preferences.tts.enabled ?? DEFAULT_TTS_CONFIG.enabled, provider: preferences.tts.provider ?? DEFAULT_TTS_CONFIG.provider, + autoPlay: preferences.tts.autoPlay ?? DEFAULT_TTS_CONFIG.autoPlay, endpoint: preferences.tts.endpoint ?? DEFAULT_TTS_CONFIG.endpoint, apiKey: preferences.tts.apiKey ?? DEFAULT_TTS_CONFIG.apiKey, voice: preferences.tts.voice ?? DEFAULT_TTS_CONFIG.voice, @@ -288,6 +290,29 @@ export function TTSSettings() { )} /> + {watchEnabled && ( + ( + +
+ Auto-play replies + + Automatically speak new assistant replies when they complete. + +
+ + + +
+ )} + /> + )} + {watchEnabled && ( <>
diff --git a/frontend/src/components/ui/PageTransition.tsx b/frontend/src/components/ui/PageTransition.tsx deleted file mode 100644 index 4f8d85aa..00000000 --- a/frontend/src/components/ui/PageTransition.tsx +++ /dev/null @@ -1,68 +0,0 @@ -import { useRef, useEffect, useState, type ReactNode } from 'react' -import { useLocation } from 'react-router-dom' -import { useNavigationStore } from '@/stores/navigationStore' -import { useSwipeBack, useMobile } from '@/hooks/useMobile' - -interface PageTransitionProps { - children: ReactNode -} - -export function PageTransition({ children }: PageTransitionProps) { - const isMobile = useMobile() - const location = useLocation() - const pageRef = useRef(null) - const direction = useNavigationStore((s) => s.direction) - const phase = useNavigationStore((s) => s.phase) - const { bindSwipe, pageStyles, underlayStyles, isSwiping } = useSwipeBack() - - useEffect(() => { - return bindSwipe(pageRef.current) - }, [bindSwipe]) - - const isAnimating = isMobile && phase === 'entering' && direction !== 'none' - const isActive = isSwiping || isAnimating - - const animationClass = isAnimating - ? direction === 'push' - ? 'page-slide-in-push' - : 'page-slide-in-pop' - : '' - - const [reducedMotion, setReducedMotion] = useState(false) - - useEffect(() => { - const mql = window.matchMedia('(prefers-reduced-motion: reduce)') - setReducedMotion(mql.matches) - const handler = (e: MediaQueryListEvent) => setReducedMotion(e.matches) - mql.addEventListener('change', handler) - return () => mql.removeEventListener('change', handler) - }, []) - - return ( - <> - {isMobile && isActive && !reducedMotion && ( -
- )} -
- {children} -
- - ) -} diff --git a/frontend/src/components/ui/bottom-sheet.test.tsx b/frontend/src/components/ui/bottom-sheet.test.tsx new file mode 100644 index 00000000..a880fe90 --- /dev/null +++ b/frontend/src/components/ui/bottom-sheet.test.tsx @@ -0,0 +1,165 @@ +import { render, screen, fireEvent, waitFor } from '@testing-library/react' +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { BottomSheet, BottomSheetHeader, BottomSheetContent } from './bottom-sheet' +import { useSwipeDismiss } from '@/hooks/useMobile' + +vi.mock('@/hooks/useMobile', () => ({ + useSwipeDismiss: vi.fn(() => ({ + bind: vi.fn(), + swipeProgress: 0, + swipeStyles: {}, + })), +})) + +describe('BottomSheet', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('renders when isOpen is true', () => { + render( + {}} ariaLabel="Test sheet"> +
Test content
+
, + ) + expect(screen.getByText('Test content')).toBeInTheDocument() + }) + + it('does not render when isOpen is false', async () => { + const { container } = render( + {}} ariaLabel="Test sheet"> +
Test content
+
, + ) + await waitFor(() => { + expect(container.querySelector('[role="dialog"]')).not.toBeInTheDocument() + }) + }) + + it('calls onClose when backdrop is clicked', () => { + const handleClose = vi.fn() + render( + +
Test content
+
, + ) + const backdrop = document.querySelector('.bg-black\\/40') + if (backdrop) { + fireEvent.click(backdrop) + } + expect(handleClose).toHaveBeenCalled() + }) + + it('calls onClose when Escape key is pressed', () => { + const handleClose = vi.fn() + render( + +
Test content
+
, + ) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(handleClose).toHaveBeenCalled() + }) + + it('applies pb-safe class', () => { + render( + {}} ariaLabel="Test sheet"> +
Test content
+
, + ) + const dialog = document.querySelector('[role="dialog"]') + expect(dialog).toHaveClass('pb-safe') + }) + + it('applies custom heightClass', () => { + render( + {}} heightClass="h-[50dvh]" ariaLabel="Test sheet"> +
Test content
+
, + ) + const dialog = document.querySelector('[role="dialog"]') + expect(dialog).toHaveClass('h-[50dvh]') + }) + + it('passes correct options to useSwipeDismiss', () => { + const mockBind = vi.fn() + vi.mocked(useSwipeDismiss).mockReturnValue({ + bind: mockBind, + swipeProgress: 0, + swipeStyles: {}, + }) + + render( + {}} ariaLabel="Test sheet"> +
Test content
+
, + ) + + expect(useSwipeDismiss).toHaveBeenCalledWith(expect.any(Function), { + enabled: true, + threshold: 80, + }) + }) + + it('binds gesture to the panel element with aria-modal', () => { + const mockBind = vi.fn() + vi.mocked(useSwipeDismiss).mockReturnValue({ + bind: mockBind, + swipeProgress: 0, + swipeStyles: {}, + }) + + render( + {}} ariaLabel="Test sheet"> +
Test content
+
, + ) + + const panelElement = document.querySelector('[aria-modal="true"]') + expect(panelElement).toBeInTheDocument() + + expect(mockBind).toHaveBeenCalled() + }) +}) + +describe('BottomSheetHeader', () => { + it('renders with title', () => { + render( + +
Header content
+
, + ) + expect(screen.getByText('Test Title')).toBeInTheDocument() + expect(screen.getByText('Header content')).toBeInTheDocument() + }) + + it('renders without title', () => { + render( + +
Header content only
+
, + ) + expect(screen.getByText('Header content only')).toBeInTheDocument() + }) +}) + +describe('BottomSheetContent', () => { + it('renders children with default padding', () => { + render( + +
Content
+
, + ) + expect(screen.getByText('Content')).toBeInTheDocument() + }) + + it('applies custom className', () => { + render( + +
Content
+
, + ) + const content = screen.getByText('Content').parentElement + expect(content).toHaveClass('custom-class') + }) +}) diff --git a/frontend/src/components/ui/bottom-sheet.tsx b/frontend/src/components/ui/bottom-sheet.tsx new file mode 100644 index 00000000..ec3978d1 --- /dev/null +++ b/frontend/src/components/ui/bottom-sheet.tsx @@ -0,0 +1,126 @@ +import { useEffect, useState, useRef } from 'react' +import { cn } from '@/lib/utils' +import { MODAL_TRANSITION_MS } from '@/lib/utils' +import { useSwipeDismiss } from '@/hooks/useMobile' + +export interface BottomSheetProps { + isOpen: boolean + onClose: () => void + heightClass?: string + className?: string + children: React.ReactNode + ariaLabel?: string +} + +export function BottomSheet({ + isOpen, + onClose, + heightClass = 'h-[70dvh]', + className, + children, + ariaLabel, +}: BottomSheetProps) { + const [shouldRender, setShouldRender] = useState(false) + const panelRef = useRef(null) + + const { bind, swipeStyles } = useSwipeDismiss(onClose, { + enabled: isOpen, + threshold: 80, + }) + + useEffect(() => { + return bind(panelRef.current) + }, [bind]) + + useEffect(() => { + if (isOpen) { + setShouldRender(true) + } else { + const timer = setTimeout(() => setShouldRender(false), MODAL_TRANSITION_MS) + return () => clearTimeout(timer) + } + }, [isOpen]) + + useEffect(() => { + const handleEscape = (e: KeyboardEvent) => { + if (e.key === 'Escape' && isOpen) { + onClose() + } + } + + if (isOpen) { + document.addEventListener('keydown', handleEscape) + document.body.style.overflow = 'hidden' + } + + return () => { + document.removeEventListener('keydown', handleEscape) + document.body.style.overflow = 'unset' + } + }, [isOpen, onClose]) + + if (!isOpen && !shouldRender) return null + + return ( +
+