diff --git a/backend/package.json b/backend/package.json index 3815229e..bc190bdb 100644 --- a/backend/package.json +++ b/backend/package.json @@ -19,6 +19,7 @@ "@opencode-manager/shared": "workspace:*", "archiver": "^7.0.1", "dotenv": "^17.2.3", + "eventsource": "^4.1.0", "hono": "^4.10.1", "strip-json-comments": "^3.1.1", "zod": "^4.1.12" @@ -28,6 +29,7 @@ "@types/archiver": "^7.0.0", "@types/better-sqlite3": "^7.6.13", "@types/bun": "latest", + "@types/eventsource": "^3.0.0", "@vitest/ui": "^3.2.4", "eslint": "^9.39.1", "typescript-eslint": "^8.45.0", diff --git a/backend/src/index.ts b/backend/src/index.ts index ccfc31fb..8cc1d77c 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -13,6 +13,8 @@ import { createFileRoutes } from './routes/files' import { createProvidersRoutes } from './routes/providers' import { createOAuthRoutes } from './routes/oauth' import { createTitleRoutes } from './routes/title' +import { createSSERoutes } from './routes/sse' +import { sseAggregator } from './services/sse-aggregator' import { ensureDirectoryExists, writeFileContent, fileExists, readFileContent } from './services/file-operations' import { SettingsService } from './services/settings' import { opencodeServerManager } from './services/opencode-single-server' @@ -230,6 +232,7 @@ app.route('/api/providers', createProvidersRoutes()) app.route('/api/oauth', createOAuthRoutes()) app.route('/api/tts', createTTSRoutes(db)) app.route('/api/generate-title', createTitleRoutes()) +app.route('/api/sse', createSSERoutes()) app.all('/api/opencode/*', async (c) => { const request = c.req.raw @@ -302,10 +305,12 @@ const shutdown = async (signal: string) => { logger.info(`${signal} received, shutting down gracefully...`) try { + sseAggregator.shutdown() + logger.info('SSE Aggregator stopped') await opencodeServerManager.stop() logger.info('OpenCode server stopped') } catch (error) { - logger.error('Error stopping OpenCode server:', error) + logger.error('Error during shutdown:', error) } process.exit(0) } diff --git a/backend/src/routes/sse.ts b/backend/src/routes/sse.ts new file mode 100644 index 00000000..0e595c56 --- /dev/null +++ b/backend/src/routes/sse.ts @@ -0,0 +1,78 @@ +import { Hono } from 'hono' +import { streamSSE } from 'hono/streaming' +import { sseAggregator } from '../services/sse-aggregator' +import { SSESubscribeSchema } from '@opencode-manager/shared/schemas' +import { logger } from '../utils/logger' + +export function createSSERoutes() { + const app = new Hono() + + app.get('/stream', async (c) => { + const directoriesParam = c.req.query('directories') + const directories = directoriesParam ? directoriesParam.split(',').filter(Boolean) : [] + + return streamSSE(c, async (stream) => { + const clientId = `client_${Date.now()}_${Math.random().toString(36).slice(2)}` + + const cleanup = sseAggregator.addClient( + clientId, + (event, data) => { + stream.writeSSE({ event, data }) + }, + directories + ) + + stream.onAbort(() => { + cleanup() + }) + + try { + await stream.writeSSE({ + event: 'connected', + data: JSON.stringify({ clientId, directories, ...sseAggregator.getConnectionStatus() }) + }) + } catch (err) { + logger.error(`Failed to send SSE connected event for ${clientId}:`, err) + } + + await new Promise(() => {}) + }) + }) + + app.post('/subscribe', async (c) => { + const body = await c.req.json() + const result = SSESubscribeSchema.safeParse(body) + if (!result.success) { + return c.json({ success: false, error: 'Invalid request', details: result.error.issues }, 400) + } + const success = sseAggregator.addDirectories(result.data.clientId, result.data.directories) + if (!success) { + return c.json({ success: false, error: 'Client not found' }, 404) + } + return c.json({ success: true }) + }) + + app.post('/unsubscribe', async (c) => { + const body = await c.req.json() + const result = SSESubscribeSchema.safeParse(body) + if (!result.success) { + return c.json({ success: false, error: 'Invalid request', details: result.error.issues }, 400) + } + const success = sseAggregator.removeDirectories(result.data.clientId, result.data.directories) + if (!success) { + return c.json({ success: false, error: 'Client not found' }, 404) + } + return c.json({ success: true }) + }) + + app.get('/status', (c) => { + return c.json({ + ...sseAggregator.getConnectionStatus(), + clients: sseAggregator.getClientCount(), + directories: sseAggregator.getActiveDirectories(), + activeSessions: sseAggregator.getActiveSessions() + }) + }) + + return app +} diff --git a/backend/src/services/sse-aggregator.ts b/backend/src/services/sse-aggregator.ts new file mode 100644 index 00000000..91c24d3c --- /dev/null +++ b/backend/src/services/sse-aggregator.ts @@ -0,0 +1,378 @@ +import { EventSource } from 'eventsource' +import { logger } from '../utils/logger' +import { ENV } from '@opencode-manager/shared/config/env' +import { DEFAULTS } from '@opencode-manager/shared/config' + +type SSEClientCallback = (event: string, data: string) => void + +interface SSEClient { + id: string + callback: SSEClientCallback + directories: Set +} + +interface DirectoryConnection { + eventSource: EventSource | null + reconnectTimeout: ReturnType | null + reconnectDelay: number + isConnected: boolean +} + +interface SSEEvent { + type: string + properties: Record +} + +const OPENCODE_PORT = ENV.OPENCODE.PORT +const { RECONNECT_DELAY_MS, MAX_RECONNECT_DELAY_MS, IDLE_GRACE_PERIOD_MS } = DEFAULTS.SSE + +class SSEAggregator { + private static instance: SSEAggregator + private clients: Map = new Map() + private connections: Map = new Map() + private activeSessions: Map> = new Map() + private idleTimeouts: Map> = new Map() + private sessionStateVersion: Map = new Map() + + private constructor() {} + + static getInstance(): SSEAggregator { + if (!SSEAggregator.instance) { + SSEAggregator.instance = new SSEAggregator() + } + return SSEAggregator.instance + } + + addClient(id: string, callback: SSEClientCallback, directories: string[]): () => void { + const client: SSEClient = { + id, + callback, + directories: new Set(directories) + } + this.clients.set(id, client) + + logger.info(`Client ${id} connected with directories: ${directories.length > 0 ? directories.join(', ') : '(none)'}`) + this.syncConnections() + + return () => this.removeClient(id) + } + + removeClient(id: string): void { + this.clients.delete(id) + this.syncConnections() + } + + addDirectories(clientId: string, directories: string[]): boolean { + const client = this.clients.get(clientId) + if (!client) { + logger.warn(`addDirectories: client ${clientId} not found`) + return false + } + directories.forEach(dir => client.directories.add(dir)) + logger.info(`Client ${clientId} subscribed to: ${directories.join(', ')}`) + this.syncConnections() + return true + } + + removeDirectories(clientId: string, directories: string[]): boolean { + const client = this.clients.get(clientId) + if (!client) { + logger.warn(`removeDirectories: client ${clientId} not found`) + return false + } + directories.forEach(dir => client.directories.delete(dir)) + logger.info(`Client ${clientId} unsubscribed from: ${directories.join(', ')}`) + this.syncConnections() + return true + } + + private getRequiredDirectories(): Set { + const dirs = new Set() + this.clients.forEach(client => { + client.directories.forEach(dir => dirs.add(dir)) + }) + return dirs + } + + private syncConnections(): void { + const required = this.getRequiredDirectories() + + this.connections.forEach((_, dir) => { + if (!required.has(dir)) { + this.disconnectDirectory(dir) + } + }) + + required.forEach(dir => { + if (!this.connections.has(dir)) { + this.connectDirectory(dir) + } + }) + } + + private connectDirectory(directory: string): void { + if (this.connections.has(directory)) return + + const conn: DirectoryConnection = { + eventSource: null, + reconnectTimeout: null, + reconnectDelay: RECONNECT_DELAY_MS, + isConnected: false + } + this.connections.set(directory, conn) + + this.establishConnection(directory) + } + + private establishConnection(directory: string): void { + const conn = this.connections.get(directory) + if (!conn) return + + if (conn.eventSource) { + conn.eventSource.close() + conn.eventSource = null + } + + const url = new URL(`http://127.0.0.1:${OPENCODE_PORT}/event`) + url.searchParams.set('directory', directory) + + logger.info(`SSE connecting to OpenCode: ${directory}`) + + const eventSource = new EventSource(url.toString()) + conn.eventSource = eventSource + + eventSource.onopen = () => { + logger.info(`SSE connected: ${directory}`) + conn.isConnected = true + conn.reconnectDelay = RECONNECT_DELAY_MS + } + + eventSource.onerror = () => { + conn.isConnected = false + + if (conn.eventSource) { + conn.eventSource.close() + conn.eventSource = null + } + + if (this.connections.has(directory)) { + this.scheduleReconnect(directory) + } + } + + eventSource.onmessage = (event) => { + this.broadcastToDirectory(directory, 'message', event.data) + } + } + + private disconnectDirectory(directory: string): void { + const conn = this.connections.get(directory) + if (!conn) return + + if (conn.reconnectTimeout) { + clearTimeout(conn.reconnectTimeout) + } + + if (conn.eventSource) { + conn.eventSource.close() + } + + this.connections.delete(directory) + logger.info(`SSE disconnected: ${directory}`) + } + + private scheduleReconnect(directory: string): void { + const conn = this.connections.get(directory) + if (!conn || conn.reconnectTimeout) return + + conn.reconnectTimeout = setTimeout(() => { + conn.reconnectTimeout = null + conn.reconnectDelay = Math.min(conn.reconnectDelay * 2, MAX_RECONNECT_DELAY_MS) + this.establishConnection(directory) + }, conn.reconnectDelay) + } + + private broadcastToDirectory(directory: string, event: string, data: string): void { + try { + const parsed = JSON.parse(data) as SSEEvent + this.handleEvent(directory, parsed) + } catch { + // Ignore parse errors + } + + this.clients.forEach((client) => { + if (client.directories.has(directory)) { + try { + client.callback(event, data) + } catch (error) { + logger.error(`Failed to send to client ${client.id}:`, error) + } + } + }) + } + + private handleEvent(directory: string, event: SSEEvent): void { + const { type, properties } = event + + if (type === 'session.status') { + const sessionID = properties.sessionID as string + const status = properties.status as { type: string } + + if (!sessionID || !status) return + + const isActive = status.type === 'busy' || status.type === 'retry' || status.type === 'compact' + + if (isActive) { + this.markSessionActive(directory, sessionID) + } else if (status.type === 'idle') { + this.markSessionIdle(directory, sessionID) + } + } else if (type === 'session.idle') { + const sessionID = properties.sessionID as string + if (sessionID) { + this.markSessionIdle(directory, sessionID) + } + } + } + + private getStateVersion(directory: string): number { + return this.sessionStateVersion.get(directory) ?? 0 + } + + private incrementStateVersion(directory: string): number { + const newVersion = this.getStateVersion(directory) + 1 + this.sessionStateVersion.set(directory, newVersion) + return newVersion + } + + private markSessionActive(directory: string, sessionID: string): void { + this.incrementStateVersion(directory) + + const existingTimeout = this.idleTimeouts.get(directory) + if (existingTimeout) { + clearTimeout(existingTimeout) + this.idleTimeouts.delete(directory) + } + + let sessions = this.activeSessions.get(directory) + if (!sessions) { + sessions = new Set() + this.activeSessions.set(directory, sessions) + } + sessions.add(sessionID) + + logger.info(`Session active: ${sessionID} in ${directory} (${sessions.size} active)`) + } + + private markSessionIdle(directory: string, sessionID: string): void { + const existingTimeout = this.idleTimeouts.get(directory) + if (existingTimeout) { + clearTimeout(existingTimeout) + this.idleTimeouts.delete(directory) + } + + const sessions = this.activeSessions.get(directory) + if (sessions) { + sessions.delete(sessionID) + logger.info(`Session idle: ${sessionID} in ${directory} (${sessions.size} active)`) + + if (sessions.size === 0) { + this.activeSessions.delete(directory) + this.scheduleIdleDisconnect(directory) + } + } + } + + private hasActiveViewers(directory: string): boolean { + for (const client of this.clients.values()) { + if (client.directories.has(directory)) { + return true + } + } + return false + } + + private scheduleIdleDisconnect(directory: string): void { + if (this.hasActiveViewers(directory)) { + logger.info(`Skipping idle disconnect for ${directory} - has active viewers`) + return + } + + const existingTimeout = this.idleTimeouts.get(directory) + if (existingTimeout) { + clearTimeout(existingTimeout) + } + + const versionAtSchedule = this.getStateVersion(directory) + logger.info(`Scheduling idle disconnect for ${directory} in ${IDLE_GRACE_PERIOD_MS}ms (version: ${versionAtSchedule})`) + + const timeout = setTimeout(() => { + this.idleTimeouts.delete(directory) + + const currentVersion = this.getStateVersion(directory) + if (currentVersion !== versionAtSchedule) { + logger.info(`Cancelled idle disconnect for ${directory} - state changed (${versionAtSchedule} -> ${currentVersion})`) + return + } + + const sessions = this.activeSessions.get(directory) + const hasViewers = this.hasActiveViewers(directory) + + if ((!sessions || sessions.size === 0) && !hasViewers) { + logger.info(`Idle disconnect: ${directory}`) + this.disconnectDirectory(directory) + } else if (hasViewers) { + logger.info(`Cancelled idle disconnect for ${directory} - has active viewers`) + } + }, IDLE_GRACE_PERIOD_MS) + + this.idleTimeouts.set(directory, timeout) + } + + getConnectionStatus(): { connected: number; total: number } { + let connected = 0 + this.connections.forEach(conn => { + if (conn.isConnected) connected++ + }) + return { connected, total: this.connections.size } + } + + getClientCount(): number { + return this.clients.size + } + + getActiveDirectories(): string[] { + return Array.from(this.connections.keys()) + } + + shutdown(): void { + this.idleTimeouts.forEach((timeout) => { + clearTimeout(timeout) + }) + this.idleTimeouts.clear() + this.activeSessions.clear() + this.sessionStateVersion.clear() + + this.connections.forEach((conn, dir) => { + if (conn.reconnectTimeout) { + clearTimeout(conn.reconnectTimeout) + } + if (conn.eventSource) { + conn.eventSource.close() + } + logger.info(`SSE closed: ${dir}`) + }) + this.connections.clear() + this.clients.clear() + } + + getActiveSessions(): Record { + const result: Record = {} + this.activeSessions.forEach((sessions, dir) => { + result[dir] = Array.from(sessions) + }) + return result + } +} + +export const sseAggregator = SSEAggregator.getInstance() diff --git a/backend/tests/fixtures/git-helpers.ts b/backend/test/fixtures/git-helpers.ts similarity index 100% rename from backend/tests/fixtures/git-helpers.ts rename to backend/test/fixtures/git-helpers.ts diff --git a/backend/tests/services/git-operations.test.ts b/backend/test/services/git-operations.test.ts similarity index 92% rename from backend/tests/services/git-operations.test.ts rename to backend/test/services/git-operations.test.ts index 6c5ccff2..589f9d41 100644 --- a/backend/tests/services/git-operations.test.ts +++ b/backend/test/services/git-operations.test.ts @@ -1,5 +1,14 @@ -import { describe, it, expect, beforeAll, afterAll } from 'bun:test' +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest' import { gitReuseDir, setupGitTestRepo, cleanupTestRepo, createTestFile, stageAndCommitTestFile } from '../fixtures/git-helpers' + +vi.mock('bun:sqlite', () => ({ + Database: vi.fn() +})) + +vi.mock('../../src/services/settings', () => ({ + SettingsService: vi.fn() +})) + import { getFileDiff } from '../../src/services/git-operations' const testRepoPath = gitReuseDir('git-operations-test') diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 296d9b79..e5ded40e 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -8,10 +8,8 @@ import { SettingsDialog } from './components/settings/SettingsDialog' import { useSettingsDialog } from './hooks/useSettingsDialog' import { useTheme } from './hooks/useTheme' import { TTSProvider } from './contexts/TTSContext' -import { PermissionProvider } from '@/contexts/PermissionContext' +import { EventProvider, usePermissions } from '@/contexts/EventContext' import { PermissionRequestDialog } from './components/session/PermissionRequestDialog' -import { usePermissionContext } from './contexts/PermissionContext' -import { GlobalPermissionNotification } from './components/permissions/GlobalPermissionNotification' const queryClient = new QueryClient({ defaultOptions: { @@ -22,19 +20,17 @@ const queryClient = new QueryClient({ }, }) -function AppContent() { +function RouterContent() { const { isOpen, close } = useSettingsDialog() useTheme() -return ( - + return ( + <> } /> } /> } /> - - - + ) } function PermissionDialogWrapper() { const { - currentPermission, + current: currentPermission, pendingCount, - isFromDifferentSession, - respondToPermission, + respond: respondToPermission, showDialog, setShowDialog, - currentRepoDirectory, - } = usePermissionContext() + } = usePermissions() return ( ) } function App() { - return ( - - - - + + + + + + ) diff --git a/frontend/src/api/opencode.ts b/frontend/src/api/opencode.ts index 1444993e..780f5ac3 100644 --- a/frontend/src/api/opencode.ts +++ b/frontend/src/api/opencode.ts @@ -11,6 +11,7 @@ type CommandListResponse = paths['/command']['get']['responses']['200']['content type CommandRequest = NonNullable['content']['application/json'] type ShellRequest = NonNullable['content']['application/json'] type AgentListResponse = paths['/agent']['get']['responses']['200']['content']['application/json'] +type QuestionListResponse = paths['/question']['get']['responses']['200']['content']['application/json'] export class OpenCodeClient { private client: AxiosInstance @@ -130,6 +131,21 @@ export class OpenCodeClient { return result.data } + async replyToQuestion(requestID: string, answers: string[][]) { + const result = await this.client.post(`/question/${requestID}/reply`, { answers }) + return result.data + } + + async rejectQuestion(requestID: string) { + const result = await this.client.post(`/question/${requestID}/reject`) + return result.data + } + + async listPendingQuestions() { + const response = await this.client.get('/question') + return response.data + } + async listAgents() { const response = await this.client.get('/agent') return response.data diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index f305f2c1..164694c7 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -21,6 +21,11 @@ export type Session = components['schemas']['Session'] export type PermissionRequest = components['schemas']['PermissionRequest'] export type PermissionResponse = 'once' | 'always' | 'reject' +export type QuestionOption = components['schemas']['QuestionOption'] +export type QuestionInfo = components['schemas']['QuestionInfo'] +export type QuestionRequest = components['schemas']['QuestionRequest'] +export type QuestionAnswer = components['schemas']['QuestionAnswer'] + export type MessageWithParts = { info: Message parts: Part[] @@ -102,6 +107,28 @@ export interface SSEPermissionRepliedEvent { } } +export interface SSEQuestionAskedEvent { + type: 'question.asked' + properties: QuestionRequest +} + +export interface SSEQuestionRepliedEvent { + type: 'question.replied' + properties: { + sessionID: string + requestID: string + answers: QuestionAnswer[] + } +} + +export interface SSEQuestionRejectedEvent { + type: 'question.rejected' + properties: { + sessionID: string + requestID: string + } +} + export interface SSEInstallationUpdatedEvent { type: 'installation.updated' properties: { @@ -153,6 +180,9 @@ export type SSEEvent = | SSETodoUpdatedEvent | SSEPermissionAskedEvent | SSEPermissionRepliedEvent + | SSEQuestionAskedEvent + | SSEQuestionRepliedEvent + | SSEQuestionRejectedEvent | SSEInstallationUpdatedEvent | SSEInstallationUpdateAvailableEvent diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index e43d5c87..00f0f381 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -10,7 +10,7 @@ import { useVariants } from '@/hooks/useVariants' import { useUserBash } from '@/stores/userBashStore' import { useMobile } from '@/hooks/useMobile' import { useSessionStatusForSession } from '@/stores/sessionStatusStore' -import { usePermissionContext } from '@/contexts/PermissionContext' +import { usePermissions } from '@/contexts/EventContext' import { ChevronDown, Upload, X } from 'lucide-react' import { CommandSuggestions } from '@/components/command/CommandSuggestions' @@ -680,7 +680,7 @@ const { model, modelString } = useModelSelection(opcodeUrl, directory) const currentModel = modelString || '' const displayModelName = model?.modelID || currentModel const isMobile = useMobile() - const { setShowDialog, hasPermissionsForSession } = usePermissionContext() + const { setShowDialog, hasForSession: hasPermissionsForSession } = usePermissions() const hasPendingPermissionForSession = hasPermissionsForSession(sessionID) const { hasVariants, currentVariant, cycleVariant } = useVariants(opcodeUrl, directory) const sessionStatus = useSessionStatusForSession(sessionID) diff --git a/frontend/src/components/message/ToolCallPart.tsx b/frontend/src/components/message/ToolCallPart.tsx index 811db5bf..d3d774b7 100644 --- a/frontend/src/components/message/ToolCallPart.tsx +++ b/frontend/src/components/message/ToolCallPart.tsx @@ -2,7 +2,7 @@ import { useState, useRef, useEffect } from 'react' import type { components } from '@/api/opencode-types' import { useSettings } from '@/hooks/useSettings' import { useUserBash } from '@/stores/userBashStore' -import { usePermissionContext } from '@/contexts/PermissionContext' +import { usePermissions, useQuestions } from '@/contexts/EventContext' import { detectFileReferences } from '@/lib/fileReferences' import { ExternalLink, Loader2 } from 'lucide-react' import { CopyButton } from '@/components/ui/copy-button' @@ -72,7 +72,8 @@ function parseTodoOutput(output: string): Todo[] | null { export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCallPartProps) { const { preferences } = useSettings() const { userBashCommands } = useUserBash() - const { getPermissionForCallID } = usePermissionContext() + const { getForCallID: getPermissionForCallID } = usePermissions() + const { getForCallID: getQuestionForCallID } = useQuestions() const outputRef = useRef(null) const isUserBashCommand = part.tool === 'bash' && part.state.status === 'completed' && @@ -83,6 +84,8 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal const pendingPermission = getPermissionForCallID(part.callID, part.sessionID) const isWaitingPermission = part.state.status === 'running' && !!pendingPermission + const pendingQuestion = getQuestionForCallID(part.callID, part.sessionID) + const isWaitingQuestion = part.state.status === 'running' && !!pendingQuestion useEffect(() => { if (part.tool === 'bash' && expanded && outputRef.current) { @@ -97,7 +100,9 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal case 'error': return 'text-red-600 dark:text-red-400' case 'running': - return isWaitingPermission ? 'text-orange-600 dark:text-orange-400' : 'text-yellow-600 dark:text-yellow-400' + if (isWaitingPermission) return 'text-orange-600 dark:text-orange-400' + if (isWaitingQuestion) return 'text-blue-600 dark:text-blue-400' + return 'text-yellow-600 dark:text-yellow-400' default: return 'text-muted-foreground' } @@ -255,7 +260,9 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal const getBorderStyle = () => { switch (part.state.status) { case 'running': - return isWaitingPermission ? 'border-orange-500/50 shadow-sm shadow-orange-500/20' : 'border-yellow-500/50 shadow-sm shadow-yellow-500/10' + if (isWaitingPermission) return 'border-orange-500/50 shadow-sm shadow-orange-500/20' + if (isWaitingQuestion) return 'border-blue-500/50 shadow-sm shadow-blue-500/20' + return 'border-yellow-500/50 shadow-sm shadow-yellow-500/10' case 'pending': return 'border-blue-500/30' case 'error': @@ -312,7 +319,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal ) : null })()} - ({isWaitingPermission ? 'waiting' : part.state.status}) + ({isWaitingPermission ? 'awaiting permission' : isWaitingQuestion ? 'awaiting answer' : part.state.status}) {expanded && ( diff --git a/frontend/src/components/notifications/PendingActionsGroup.tsx b/frontend/src/components/notifications/PendingActionsGroup.tsx new file mode 100644 index 00000000..4fc472d7 --- /dev/null +++ b/frontend/src/components/notifications/PendingActionsGroup.tsx @@ -0,0 +1,27 @@ +import { Bell, HelpCircle } from 'lucide-react' +import { PendingActionBadge } from '@/components/ui/pending-action-badge' +import { usePermissions, useQuestions } from '@/contexts/EventContext' + +export function PendingActionsGroup() { + const { pendingCount: permissionCount, setShowDialog } = usePermissions() + const { pendingCount: questionCount, navigateToCurrent } = useQuestions() + + return ( + <> + setShowDialog(true)} + label="permission" + /> + + + ) +} diff --git a/frontend/src/components/permissions/GlobalPermissionNotification.tsx b/frontend/src/components/permissions/GlobalPermissionNotification.tsx deleted file mode 100644 index 0780935b..00000000 --- a/frontend/src/components/permissions/GlobalPermissionNotification.tsx +++ /dev/null @@ -1,32 +0,0 @@ -import { usePermissionContext } from '@/contexts/PermissionContext' -import { useMobile } from '@/hooks/useMobile' -import { Bell } from 'lucide-react' - -export function GlobalPermissionNotification() { - const { pendingCount, setShowDialog } = usePermissionContext() - const isMobile = useMobile() - - if (pendingCount === 0) return null - - return ( - - ) -} - diff --git a/frontend/src/components/session/QuestionPrompt.tsx b/frontend/src/components/session/QuestionPrompt.tsx new file mode 100644 index 00000000..73f2e3d1 --- /dev/null +++ b/frontend/src/components/session/QuestionPrompt.tsx @@ -0,0 +1,499 @@ +import { useState, useEffect, useRef, useCallback } from 'react' +import { X, ChevronLeft, ChevronRight, Check, Loader2 } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Textarea } from '@/components/ui/textarea' +import type { QuestionRequest, QuestionInfo } from '@/api/types' +import { cn } from '@/lib/utils' +import { showToast } from '@/lib/toast' + +interface QuestionPromptProps { + question: QuestionRequest + onReply: (requestID: string, answers: string[][]) => Promise + onReject: (requestID: string) => Promise +} + +export function QuestionPrompt({ question, onReply, onReject }: QuestionPromptProps) { + const questions = question.questions + const isSingleSelect = questions.length === 1 && !questions[0]?.multiple + const totalSteps = isSingleSelect ? 1 : questions.length + 1 + + const [currentIndex, setCurrentIndex] = useState(0) + const [answers, setAnswers] = useState(() => questions.map(() => [])) + const [customInputs, setCustomInputs] = useState(() => questions.map(() => '')) + const [confirmedCustoms, setConfirmedCustoms] = useState(() => questions.map(() => '')) + const [expandedOther, setExpandedOther] = useState(null) + const [isSubmitting, setIsSubmitting] = useState(false) + + const isConfirmStep = !isSingleSelect && currentIndex === questions.length + const currentQuestion = isConfirmStep ? null : questions[currentIndex] + const isMultiSelect = currentQuestion?.multiple === true + + const goToNext = useCallback(() => { + if (currentIndex < totalSteps - 1) { + setCurrentIndex(prev => prev + 1) + setExpandedOther(null) + } + }, [currentIndex, totalSteps]) + + const goToPrev = useCallback(() => { + if (currentIndex > 0) { + setCurrentIndex(prev => prev - 1) + setExpandedOther(null) + } + }, [currentIndex]) + + const handleSubmitSingle = useCallback(async (label: string) => { + setIsSubmitting(true) + try { + await onReply(question.id, [[label]]) + } catch { + showToast.error('Failed to submit answer') + } finally { + setIsSubmitting(false) + } + }, [onReply, question.id]) + + const selectOption = useCallback((questionIndex: number, label: string) => { + const isMultiple = questions[questionIndex]?.multiple + + setAnswers(prev => { + const updated = [...prev] + const current = updated[questionIndex] ?? [] + + if (isMultiple) { + const exists = current.includes(label) + updated[questionIndex] = exists + ? current.filter(l => l !== label) + : [...current, label] + } else { + updated[questionIndex] = [label] + } + return updated + }) + + if (!isMultiple) { + if (isSingleSelect) { + handleSubmitSingle(label) + } else { + setTimeout(() => goToNext(), 150) + } + } + }, [questions, isSingleSelect, goToNext, handleSubmitSingle]) + + const handleCustomInput = useCallback((questionIndex: number, value: string) => { + setCustomInputs(prev => { + const updated = [...prev] + updated[questionIndex] = value + return updated + }) + }, []) + + const confirmCustomInput = useCallback((questionIndex: number) => { + const value = customInputs[questionIndex]?.trim() + if (!value) { + setExpandedOther(null) + return + } + + const oldCustom = confirmedCustoms[questionIndex] + + setAnswers(prev => { + const updated = [...prev] + const current = updated[questionIndex] ?? [] + + if (questions[questionIndex]?.multiple) { + const withoutOld = oldCustom ? current.filter(l => l !== oldCustom) : current + updated[questionIndex] = [...withoutOld, value] + } else { + updated[questionIndex] = [value] + if (!isSingleSelect) { + setTimeout(() => goToNext(), 150) + } + } + return updated + }) + + setConfirmedCustoms(prev => { + const updated = [...prev] + updated[questionIndex] = value + return updated + }) + setExpandedOther(null) + + if (isSingleSelect) { + handleSubmitSingle(value) + } + }, [customInputs, confirmedCustoms, questions, isSingleSelect, goToNext, handleSubmitSingle]) + + const handleSubmit = async () => { + setIsSubmitting(true) + try { + await onReply(question.id, answers) + } catch { + showToast.error('Failed to submit answers') + } finally { + setIsSubmitting(false) + } + } + + const handleReject = async () => { + setIsSubmitting(true) + try { + await onReject(question.id) + } catch { + showToast.error('Failed to dismiss question') + } finally { + setIsSubmitting(false) + } + } + + const hasAnswerForQuestion = (index: number) => { + return (answers[index]?.length ?? 0) > 0 + } + + const allQuestionsAnswered = questions.every((_, i) => hasAnswerForQuestion(i)) + + return ( +
+
+
+ {totalSteps > 1 && ( + + )} + + {isConfirmStep ? 'Review' : ( + totalSteps > 1 + ? `Question ${currentIndex + 1}/${questions.length}` + : (currentQuestion?.header || 'Question') + )} + + {totalSteps > 1 && ( + + )} +
+ +
+ +
+ {isConfirmStep ? ( + + ) : currentQuestion && ( + selectOption(currentIndex, label)} + onExpandOther={() => setExpandedOther(currentIndex)} + onCustomInputChange={(value) => handleCustomInput(currentIndex, value)} + onConfirmCustomInput={() => confirmCustomInput(currentIndex)} + onCollapseOther={() => setExpandedOther(null)} + /> + )} +
+ + {totalSteps > 1 && ( +
+ {Array.from({ length: totalSteps }).map((_, i) => ( +
+ )} + +
+ + {!isSingleSelect && ( + isConfirmStep ? ( + + ) : ( + + ) + )} +
+ + +
+ ) +} + +interface QuestionStepProps { + question: QuestionInfo + answers: string[] + customInput: string + confirmedCustom: string + expandedOther: boolean + isMultiSelect: boolean + onSelectOption: (label: string) => void + onExpandOther: () => void + onCustomInputChange: (value: string) => void + onConfirmCustomInput: () => void + onCollapseOther: () => void +} + +function QuestionStep({ + question, + answers, + customInput, + confirmedCustom, + expandedOther, + isMultiSelect, + onSelectOption, + onExpandOther, + onCustomInputChange, + onConfirmCustomInput, + onCollapseOther, +}: QuestionStepProps) { + const textareaRef = useRef(null) + + useEffect(() => { + if (expandedOther && textareaRef.current) { + textareaRef.current.focus() + } + }, [expandedOther]) + + const isCustomSelected = confirmedCustom && answers.includes(confirmedCustom) + + return ( +
+

+ {question.question} + {isMultiSelect && ( + (select all that apply) + )} +

+ +
+ {question.options.map((option, i) => { + const isSelected = answers.includes(option.label) + return ( + + ) + })} + + + + {expandedOther && ( +
+