mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Refactor SSE event handling and consolidate notification contexts
This commit is contained in:
1 parent
9851ec06e0
commit
f7fd3176d4
30 files changed
+2226
-988
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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<string>
|
||||
}
|
||||
|
||||
interface DirectoryConnection {
|
||||
eventSource: EventSource | null
|
||||
reconnectTimeout: ReturnType<typeof setTimeout> | null
|
||||
reconnectDelay: number
|
||||
isConnected: boolean
|
||||
}
|
||||
|
||||
interface SSEEvent {
|
||||
type: string
|
||||
properties: Record<string, unknown>
|
||||
}
|
||||
|
||||
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<string, SSEClient> = new Map()
|
||||
private connections: Map<string, DirectoryConnection> = new Map()
|
||||
private activeSessions: Map<string, Set<string>> = new Map()
|
||||
private idleTimeouts: Map<string, ReturnType<typeof setTimeout>> = new Map()
|
||||
private sessionStateVersion: Map<string, number> = 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<string> {
|
||||
const dirs = new Set<string>()
|
||||
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<string, string[]> {
|
||||
const result: Record<string, string[]> = {}
|
||||
this.activeSessions.forEach((sessions, dir) => {
|
||||
result[dir] = Array.from(sessions)
|
||||
})
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
export const sseAggregator = SSEAggregator.getInstance()
|
||||
File renamed without changes.
+10
-1
@@ -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')
|
||||
+16
-21
@@ -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 (
|
||||
<BrowserRouter>
|
||||
return (
|
||||
<>
|
||||
<Routes>
|
||||
<Route path="/" element={<Repos />} />
|
||||
<Route path="/repos/:id" element={<RepoDetail />} />
|
||||
<Route path="/repos/:id/sessions/:sessionId" element={<SessionDetail />} />
|
||||
|
||||
</Routes>
|
||||
<GlobalPermissionNotification />
|
||||
<SettingsDialog open={isOpen} onOpenChange={close} />
|
||||
<Toaster
|
||||
position="bottom-right"
|
||||
@@ -42,43 +38,42 @@ return (
|
||||
richColors
|
||||
closeButton
|
||||
/>
|
||||
</BrowserRouter>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function PermissionDialogWrapper() {
|
||||
const {
|
||||
currentPermission,
|
||||
current: currentPermission,
|
||||
pendingCount,
|
||||
isFromDifferentSession,
|
||||
respondToPermission,
|
||||
respond: respondToPermission,
|
||||
showDialog,
|
||||
setShowDialog,
|
||||
currentRepoDirectory,
|
||||
} = usePermissionContext()
|
||||
} = usePermissions()
|
||||
|
||||
return (
|
||||
<PermissionRequestDialog
|
||||
permission={currentPermission}
|
||||
pendingCount={pendingCount}
|
||||
isFromDifferentSession={isFromDifferentSession}
|
||||
isFromDifferentSession={false}
|
||||
onRespond={respondToPermission}
|
||||
open={showDialog}
|
||||
onOpenChange={setShowDialog}
|
||||
repoDirectory={currentRepoDirectory}
|
||||
repoDirectory={null}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function App() {
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<TTSProvider>
|
||||
<PermissionProvider>
|
||||
<AppContent />
|
||||
<PermissionDialogWrapper />
|
||||
</PermissionProvider>
|
||||
<BrowserRouter>
|
||||
<EventProvider>
|
||||
<RouterContent />
|
||||
<PermissionDialogWrapper />
|
||||
</EventProvider>
|
||||
</BrowserRouter>
|
||||
</TTSProvider>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
@@ -11,6 +11,7 @@ type CommandListResponse = paths['/command']['get']['responses']['200']['content
|
||||
type CommandRequest = NonNullable<paths['/session/{sessionID}/command']['post']['requestBody']>['content']['application/json']
|
||||
type ShellRequest = NonNullable<paths['/session/{sessionID}/shell']['post']['requestBody']>['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<QuestionListResponse>('/question')
|
||||
return response.data
|
||||
}
|
||||
|
||||
async listAgents() {
|
||||
const response = await this.client.get<AgentListResponse>('/agent')
|
||||
return response.data
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<HTMLDivElement>(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
|
||||
</span>
|
||||
) : null
|
||||
})()}
|
||||
<span className="text-muted-foreground text-xs ml-auto">({isWaitingPermission ? 'waiting' : part.state.status})</span>
|
||||
<span className="text-muted-foreground text-xs ml-auto">({isWaitingPermission ? 'awaiting permission' : isWaitingQuestion ? 'awaiting answer' : part.state.status})</span>
|
||||
</button>
|
||||
|
||||
{expanded && (
|
||||
|
||||
@@ -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 (
|
||||
<>
|
||||
<PendingActionBadge
|
||||
count={permissionCount}
|
||||
icon={Bell}
|
||||
color="orange"
|
||||
onClick={() => setShowDialog(true)}
|
||||
label="permission"
|
||||
/>
|
||||
<PendingActionBadge
|
||||
count={questionCount}
|
||||
icon={HelpCircle}
|
||||
color="blue"
|
||||
onClick={navigateToCurrent}
|
||||
label="question"
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<button
|
||||
onClick={() => setShowDialog(true)}
|
||||
className={`fixed z-50 ${
|
||||
isMobile ? 'bottom-20 right-4' : 'top-4 right-4'
|
||||
} bg-gradient-to-br from-orange-500 to-orange-600 hover:from-orange-400 hover:to-orange-500 border-2 border-orange-400/60 hover:border-orange-300 shadow-lg shadow-orange-500/40 hover:shadow-orange-500/60 ring-2 ring-orange-500/20 hover:ring-orange-500/40 text-white rounded-full transition-all duration-200 ${
|
||||
isMobile ? 'w-14 h-14' : 'w-12 h-12'
|
||||
} hover:scale-110 active:scale-95 flex items-center justify-center`}
|
||||
title={`${pendingCount} pending permission${pendingCount > 1 ? 's' : ''}`}
|
||||
>
|
||||
<Bell className="w-6 h-6" />
|
||||
{pendingCount > 0 && (
|
||||
<span
|
||||
className={`absolute -top-1 -right-1 bg-destructive text-destructive-foreground text-xs font-bold rounded-full w-5 h-5 flex items-center justify-center border-2 border-background`}
|
||||
>
|
||||
{pendingCount > 9 ? '9+' : pendingCount}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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<void>
|
||||
onReject: (requestID: string) => Promise<void>
|
||||
}
|
||||
|
||||
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<string[][]>(() => questions.map(() => []))
|
||||
const [customInputs, setCustomInputs] = useState<string[]>(() => questions.map(() => ''))
|
||||
const [confirmedCustoms, setConfirmedCustoms] = useState<string[]>(() => questions.map(() => ''))
|
||||
const [expandedOther, setExpandedOther] = useState<number | null>(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 (
|
||||
<div
|
||||
className="w-full bg-gradient-to-br from-blue-500/10 to-blue-600/5 border-2 border-blue-500/30 rounded-xl shadow-lg shadow-blue-500/10 backdrop-blur-sm mb-3 overflow-hidden"
|
||||
>
|
||||
<div className="flex items-center justify-between px-3 py-2 border-b border-blue-500/20 bg-blue-500/5">
|
||||
<div className="flex items-center gap-2">
|
||||
{totalSteps > 1 && (
|
||||
<button
|
||||
onClick={goToPrev}
|
||||
disabled={currentIndex === 0}
|
||||
className="p-1 rounded hover:bg-blue-500/20 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4 text-blue-600 dark:text-blue-400" />
|
||||
</button>
|
||||
)}
|
||||
<span className="text-sm font-semibold text-blue-400">
|
||||
{isConfirmStep ? 'Review' : (
|
||||
totalSteps > 1
|
||||
? `Question ${currentIndex + 1}/${questions.length}`
|
||||
: (currentQuestion?.header || 'Question')
|
||||
)}
|
||||
</span>
|
||||
{totalSteps > 1 && (
|
||||
<button
|
||||
onClick={goToNext}
|
||||
disabled={currentIndex === totalSteps - 1}
|
||||
className="p-1 rounded hover:bg-blue-500/20 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
<ChevronRight className="w-4 h-4 text-blue-600 dark:text-blue-400" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={handleReject}
|
||||
disabled={isSubmitting}
|
||||
className="p-1.5 rounded-lg hover:bg-red-500/20 text-muted-foreground hover:text-red-500 transition-colors"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="p-3 max-h-[40vh] overflow-y-auto">
|
||||
{isConfirmStep ? (
|
||||
<ConfirmStep
|
||||
questions={questions}
|
||||
answers={answers}
|
||||
onEditQuestion={setCurrentIndex}
|
||||
/>
|
||||
) : currentQuestion && (
|
||||
<QuestionStep
|
||||
question={currentQuestion}
|
||||
answers={answers[currentIndex] ?? []}
|
||||
customInput={customInputs[currentIndex] ?? ''}
|
||||
confirmedCustom={confirmedCustoms[currentIndex] ?? ''}
|
||||
expandedOther={expandedOther === currentIndex}
|
||||
isMultiSelect={isMultiSelect}
|
||||
onSelectOption={(label) => selectOption(currentIndex, label)}
|
||||
onExpandOther={() => setExpandedOther(currentIndex)}
|
||||
onCustomInputChange={(value) => handleCustomInput(currentIndex, value)}
|
||||
onConfirmCustomInput={() => confirmCustomInput(currentIndex)}
|
||||
onCollapseOther={() => setExpandedOther(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{totalSteps > 1 && (
|
||||
<div className="flex justify-center gap-1.5 py-2 border-t border-blue-500/10">
|
||||
{Array.from({ length: totalSteps }).map((_, i) => (
|
||||
<button
|
||||
key={i}
|
||||
onClick={() => {
|
||||
setCurrentIndex(i)
|
||||
setExpandedOther(null)
|
||||
}}
|
||||
className={cn(
|
||||
"w-2 h-2 rounded-full transition-all duration-200",
|
||||
i === currentIndex
|
||||
? "bg-blue-500 scale-125"
|
||||
: i < questions.length && hasAnswerForQuestion(i)
|
||||
? "bg-green-500/70 hover:bg-green-500"
|
||||
: "bg-blue-500/30 hover:bg-blue-500/50"
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2 px-3 pb-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleReject}
|
||||
disabled={isSubmitting}
|
||||
className="flex-1 h-10 border-blue-500/30 hover:bg-blue-500/10 hover:border-blue-500/50"
|
||||
>
|
||||
Dismiss
|
||||
</Button>
|
||||
{!isSingleSelect && (
|
||||
isConfirmStep ? (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting || !allQuestionsAnswered}
|
||||
className="flex-1 h-10 bg-blue-600 hover:bg-blue-700 text-white"
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
'Submit'
|
||||
)}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={goToNext}
|
||||
disabled={currentIndex === totalSteps - 1}
|
||||
className="flex-1 h-10 bg-blue-600 hover:bg-blue-700 text-white"
|
||||
>
|
||||
{currentIndex === questions.length - 1 ? 'Review' : 'Next'}
|
||||
<ChevronRight className="w-4 h-4 ml-1" />
|
||||
</Button>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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<HTMLTextAreaElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (expandedOther && textareaRef.current) {
|
||||
textareaRef.current.focus()
|
||||
}
|
||||
}, [expandedOther])
|
||||
|
||||
const isCustomSelected = confirmedCustom && answers.includes(confirmedCustom)
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm font-semibold text-foreground">
|
||||
{question.question}
|
||||
{isMultiSelect && (
|
||||
<span className="text-foreground/60 font-normal ml-1">(select all that apply)</span>
|
||||
)}
|
||||
</p>
|
||||
|
||||
<div className="space-y-2">
|
||||
{question.options.map((option, i) => {
|
||||
const isSelected = answers.includes(option.label)
|
||||
return (
|
||||
<button
|
||||
key={i}
|
||||
onClick={() => onSelectOption(option.label)}
|
||||
className={cn(
|
||||
"w-full text-left p-3 rounded-lg border-2 transition-all duration-200 active:scale-[0.98]",
|
||||
isSelected
|
||||
? "border-blue-500 bg-blue-500/10"
|
||||
: "border-border hover:border-blue-500/50 hover:bg-blue-500/5"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<div className={cn(
|
||||
"w-5 h-5 rounded-full border-2 flex items-center justify-center flex-shrink-0 transition-colors",
|
||||
isSelected
|
||||
? "border-blue-500 bg-blue-500"
|
||||
: "border-muted-foreground"
|
||||
)}>
|
||||
{isSelected && <Check className="w-3 h-3 text-white" />}
|
||||
</div>
|
||||
<span className={cn(
|
||||
"text-sm font-semibold",
|
||||
isSelected ? "text-blue-400" : "text-foreground"
|
||||
)}>
|
||||
{option.label}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{option.description && (
|
||||
<p className="text-xs text-foreground/70 mt-1 ml-7">
|
||||
{option.description}
|
||||
</p>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
|
||||
<button
|
||||
onClick={() => {
|
||||
if (expandedOther) {
|
||||
onCollapseOther()
|
||||
} else {
|
||||
onExpandOther()
|
||||
}
|
||||
}}
|
||||
className={cn(
|
||||
"w-full text-left p-3 rounded-lg border-2 transition-all duration-200",
|
||||
expandedOther || isCustomSelected
|
||||
? "border-blue-500 bg-blue-500/10"
|
||||
: "border-border hover:border-blue-500/50 hover:bg-blue-500/5"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className={cn(
|
||||
"w-5 h-5 rounded-full border-2 flex items-center justify-center flex-shrink-0 transition-colors",
|
||||
isCustomSelected
|
||||
? "border-blue-500 bg-blue-500"
|
||||
: "border-muted-foreground"
|
||||
)}>
|
||||
{isCustomSelected && <Check className="w-3 h-3 text-white" />}
|
||||
</div>
|
||||
<span className={cn(
|
||||
"text-sm font-semibold",
|
||||
expandedOther || isCustomSelected ? "text-blue-400" : "text-foreground"
|
||||
)}>
|
||||
Other...
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{expandedOther && (
|
||||
<div className="ml-7 space-y-2 animate-in slide-in-from-top-2 duration-200">
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={customInput}
|
||||
onChange={(e) => onCustomInputChange(e.target.value)}
|
||||
placeholder="Type your own answer..."
|
||||
className="min-h-[80px] text-sm resize-none border-blue-500/30 focus:border-blue-500"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
onConfirmCustomInput()
|
||||
}
|
||||
if (e.key === 'Escape') {
|
||||
onCollapseOther()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={onCollapseOther}
|
||||
className="flex-1 h-8"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={onConfirmCustomInput}
|
||||
disabled={!customInput.trim()}
|
||||
className="flex-1 h-8 bg-blue-600 hover:bg-blue-700 text-white"
|
||||
>
|
||||
Confirm
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!expandedOther && isCustomSelected && (
|
||||
<div className="ml-7 text-xs text-muted-foreground">
|
||||
{confirmedCustom}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface ConfirmStepProps {
|
||||
questions: QuestionInfo[]
|
||||
answers: string[][]
|
||||
onEditQuestion: (index: number) => void
|
||||
}
|
||||
|
||||
function ConfirmStep({ questions, answers, onEditQuestion }: ConfirmStepProps) {
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm font-semibold text-foreground">Review your answers</p>
|
||||
|
||||
<div className="space-y-2">
|
||||
{questions.map((q, i) => {
|
||||
const answer = answers[i] ?? []
|
||||
const hasAnswer = answer.length > 0
|
||||
return (
|
||||
<button
|
||||
key={i}
|
||||
onClick={() => onEditQuestion(i)}
|
||||
className={cn(
|
||||
"w-full text-left p-3 rounded-lg border transition-colors",
|
||||
hasAnswer
|
||||
? "border-green-500/40 bg-green-500/10 hover:bg-green-500/15"
|
||||
: "border-red-500/40 bg-red-500/10 hover:bg-red-500/15"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-xs text-foreground/60 truncate">{q.header}</p>
|
||||
<p className={cn(
|
||||
"text-sm font-semibold mt-0.5",
|
||||
hasAnswer ? "text-green-400" : "text-red-400"
|
||||
)}>
|
||||
{hasAnswer ? answer.join(', ') : '(not answered)'}
|
||||
</p>
|
||||
</div>
|
||||
<ChevronRight className="w-4 h-4 text-foreground/50 flex-shrink-0 mt-1" />
|
||||
</div>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Trash2, Clock } from "lucide-react";
|
||||
import { formatDistanceToNow } from "date-fns";
|
||||
import type { Session } from "@/api/types";
|
||||
import { useSessionStatusForSession } from "@/stores/sessionStatusStore";
|
||||
|
||||
interface SessionCardProps {
|
||||
session: Session;
|
||||
@@ -21,6 +22,9 @@ export const SessionCard = ({
|
||||
onToggleSelection,
|
||||
onDelete,
|
||||
}: SessionCardProps) => {
|
||||
const sessionStatus = useSessionStatusForSession(session.id);
|
||||
const isSessionBusy = sessionStatus.type === 'busy' || sessionStatus.type === 'retry' || sessionStatus.type === 'compact';
|
||||
|
||||
return (
|
||||
<Card
|
||||
className={`p-3 cursor-pointer transition-all ${
|
||||
@@ -45,9 +49,17 @@ export const SessionCard = ({
|
||||
className="w-5 h-5 flex-shrink-0 mt-0.5"
|
||||
/>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="text-base font-semibold text-orange-600 dark:text-orange-400 truncate">
|
||||
{session.title || "Untitled Session"}
|
||||
</h3>
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="text-base font-semibold text-orange-600 dark:text-orange-400 truncate">
|
||||
{session.title || "Untitled Session"}
|
||||
</h3>
|
||||
{isSessionBusy && (
|
||||
<span className="relative flex h-2.5 w-2.5 flex-shrink-0">
|
||||
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
|
||||
<span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-green-500"></span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3 mt-1 text-xs text-muted-foreground">
|
||||
<span className="flex items-center gap-1">
|
||||
<Clock className="w-3 h-3" />
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { Settings } from "lucide-react";
|
||||
import { Settings, Bell, HelpCircle, MoreVertical } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { BackButton } from "@/components/ui/back-button";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { useSettingsDialog } from "@/hooks/useSettingsDialog";
|
||||
import { useTheme } from "@/hooks/useTheme";
|
||||
import { EditSessionTitleDialog } from "@/components/session/EditSessionTitleDialog";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||
import { MoreVertical } from "lucide-react";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger, DropdownMenuItem, DropdownMenuSeparator } from "@/components/ui/dropdown-menu";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ReactNode } from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useMobile } from "@/hooks/useMobile";
|
||||
import { Loader2, X } from "lucide-react";
|
||||
import { usePermissions, useQuestions } from "@/contexts/EventContext";
|
||||
|
||||
interface HeaderProps {
|
||||
children: ReactNode;
|
||||
@@ -173,6 +173,10 @@ function HeaderActions({ children, className }: { children: ReactNode; className
|
||||
|
||||
function HeaderMobileDropdown({ children, className }: { children: ReactNode; className?: string }) {
|
||||
const isMobile = useMobile();
|
||||
const { pendingCount: permissionCount, setShowDialog } = usePermissions();
|
||||
const { pendingCount: questionCount, navigateToCurrent } = useQuestions();
|
||||
|
||||
const totalPending = permissionCount + questionCount;
|
||||
|
||||
if (!isMobile) return null;
|
||||
|
||||
@@ -182,13 +186,33 @@ function HeaderMobileDropdown({ children, className }: { children: ReactNode; cl
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className={cn("text-foreground border-border hover:bg-accent transition-all duration-200 h-8 w-8", className)}
|
||||
title="Options"
|
||||
className={cn("text-foreground border-border hover:bg-accent transition-all duration-200 h-8 w-8 relative", className)}
|
||||
title={totalPending > 0 ? `${totalPending} pending notification${totalPending > 1 ? 's' : ''}` : "Options"}
|
||||
>
|
||||
<MoreVertical className="w-4 h-4" />
|
||||
{totalPending > 0 ? (
|
||||
<>
|
||||
<Bell className="w-4 h-4" />
|
||||
<span className="absolute top-1 right-1 w-2 h-2 rounded-full bg-orange-500 animate-pulse" />
|
||||
</>
|
||||
) : (
|
||||
<MoreVertical className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{permissionCount > 0 && (
|
||||
<DropdownMenuItem onClick={() => setShowDialog(true)} className="gap-2">
|
||||
<Bell className="w-4 h-4 text-orange-500" />
|
||||
<span>{permissionCount} pending permission{permissionCount > 1 ? 's' : ''}</span>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{questionCount > 0 && (
|
||||
<DropdownMenuItem onClick={navigateToCurrent} className="gap-2">
|
||||
<HelpCircle className="w-4 h-4 text-blue-500" />
|
||||
<span>{questionCount} pending question{questionCount > 1 ? 's' : ''}</span>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{totalPending > 0 && children && <DropdownMenuSeparator />}
|
||||
{children}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { type LucideIcon } from 'lucide-react'
|
||||
import { Button } from './button'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
type BadgeColor = 'orange' | 'blue'
|
||||
|
||||
const colorStyles: Record<BadgeColor, { bg: string; hover: string; text: string }> = {
|
||||
orange: {
|
||||
bg: 'bg-orange-500/10',
|
||||
hover: 'hover:bg-orange-500/20',
|
||||
text: 'text-orange-500',
|
||||
},
|
||||
blue: {
|
||||
bg: 'bg-blue-500/10',
|
||||
hover: 'hover:bg-blue-500/20',
|
||||
text: 'text-blue-500',
|
||||
},
|
||||
}
|
||||
|
||||
interface PendingActionBadgeProps {
|
||||
count: number
|
||||
icon: LucideIcon
|
||||
color: BadgeColor
|
||||
onClick: () => void
|
||||
label: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function PendingActionBadge({
|
||||
count,
|
||||
icon: Icon,
|
||||
color,
|
||||
onClick,
|
||||
label,
|
||||
className,
|
||||
}: PendingActionBadgeProps) {
|
||||
if (count === 0) return null
|
||||
|
||||
const styles = colorStyles[color]
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
'relative h-8 w-8 transition-all duration-200',
|
||||
styles.bg,
|
||||
styles.hover,
|
||||
styles.text,
|
||||
className
|
||||
)}
|
||||
title={`${count} pending ${label}${count > 1 ? 's' : ''}`}
|
||||
>
|
||||
<Icon className="w-4 h-4" />
|
||||
<span
|
||||
className={cn(
|
||||
'absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full animate-pulse',
|
||||
color === 'orange' ? 'bg-orange-500' : 'bg-blue-500'
|
||||
)}
|
||||
/>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
/* eslint-disable react-refresh/only-export-components */
|
||||
import { createContext, useContext, useEffect, useState, useCallback, useMemo, useRef } from 'react'
|
||||
import { useNavigate, useLocation } from 'react-router-dom'
|
||||
import { useQueryClient, useQuery } from '@tanstack/react-query'
|
||||
import { OpenCodeClient } from '@/api/opencode'
|
||||
import { listRepos } from '@/api/repos'
|
||||
import type { PermissionRequest, PermissionResponse, QuestionRequest, SSEEvent } from '@/api/types'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { subscribeToSSE } from '@/lib/sseManager'
|
||||
import { OPENCODE_API_ENDPOINT } from '@/config'
|
||||
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
|
||||
|
||||
type PermissionsBySession = Record<string, PermissionRequest[]>
|
||||
type QuestionsBySession = Record<string, QuestionRequest[]>
|
||||
|
||||
interface EventContextValue {
|
||||
permissions: {
|
||||
current: PermissionRequest | null
|
||||
pendingCount: number
|
||||
respond: (permissionID: string, sessionID: string, response: PermissionResponse) => Promise<void>
|
||||
dismiss: (permissionID: string, sessionID?: string) => void
|
||||
getForCallID: (callID: string, sessionID: string) => PermissionRequest | null
|
||||
hasForSession: (sessionID: string) => boolean
|
||||
showDialog: boolean
|
||||
setShowDialog: (show: boolean) => void
|
||||
}
|
||||
questions: {
|
||||
current: QuestionRequest | null
|
||||
pendingCount: number
|
||||
reply: (requestID: string, answers: string[][]) => Promise<void>
|
||||
reject: (requestID: string) => Promise<void>
|
||||
dismiss: (requestID: string, sessionID?: string) => void
|
||||
getForCallID: (callID: string, sessionID: string) => QuestionRequest | null
|
||||
hasForSession: (sessionID: string) => boolean
|
||||
navigateToCurrent: () => void
|
||||
}
|
||||
getRepoIdForSession: (sessionID: string) => number | null
|
||||
getClient: (sessionID: string) => OpenCodeClient | null
|
||||
}
|
||||
|
||||
const EventContext = createContext<EventContextValue | null>(null)
|
||||
|
||||
export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
const queryClient = useQueryClient()
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
|
||||
const [permissionsBySession, setPermissionsBySession] = useState<PermissionsBySession>({})
|
||||
const [questionsBySession, setQuestionsBySession] = useState<QuestionsBySession>({})
|
||||
const [showPermissionDialog, setShowPermissionDialog] = useState(true)
|
||||
|
||||
const clientsRef = useRef<Map<string, OpenCodeClient>>(new Map())
|
||||
const prevPermissionCountRef = useRef(0)
|
||||
const MAX_CACHED_CLIENTS = 50
|
||||
|
||||
useEffect(() => {
|
||||
const clients = clientsRef.current
|
||||
return () => {
|
||||
clients.clear()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const { data: repos } = useQuery({
|
||||
queryKey: ['repos'],
|
||||
queryFn: listRepos,
|
||||
})
|
||||
|
||||
const allPermissions = useMemo(() => Object.values(permissionsBySession).flat(), [permissionsBySession])
|
||||
const allQuestions = useMemo(() => Object.values(questionsBySession).flat(), [questionsBySession])
|
||||
|
||||
const currentPermission = allPermissions[0] ?? null
|
||||
const currentQuestion = allQuestions[0] ?? null
|
||||
|
||||
const getRepoIdForSession = useCallback((sessionID: string): number | null => {
|
||||
if (!repos) return null
|
||||
|
||||
const cache = queryClient.getQueryCache()
|
||||
const queries = cache.getAll()
|
||||
|
||||
for (const query of queries) {
|
||||
const key = query.queryKey
|
||||
if (key[0] === 'opencode' && key[1] === 'session' && key.length >= 5) {
|
||||
const sessionData = query.state.data as { id: string } | undefined
|
||||
if (sessionData?.id === sessionID) {
|
||||
const directory = key[4] as string | undefined
|
||||
if (directory) {
|
||||
const repo = repos.find(r => r.fullPath === directory)
|
||||
if (repo) return repo.id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}, [repos, queryClient])
|
||||
|
||||
const getClient = useCallback((sessionID: string): OpenCodeClient | null => {
|
||||
const cache = queryClient.getQueryCache()
|
||||
const queries = cache.getAll()
|
||||
|
||||
for (const query of queries) {
|
||||
const key = query.queryKey
|
||||
if (key[0] === 'opencode' && key[1] === 'session' && key.length >= 5) {
|
||||
const sessionData = query.state.data as { id: string } | undefined
|
||||
if (sessionData?.id === sessionID) {
|
||||
const url = key[2] as string
|
||||
const directory = key[4] as string | undefined
|
||||
|
||||
if (!url || typeof url !== 'string') continue
|
||||
|
||||
const clientKey = `${url}|${directory ?? ''}`
|
||||
let client = clientsRef.current.get(clientKey)
|
||||
if (!client) {
|
||||
if (clientsRef.current.size >= MAX_CACHED_CLIENTS) {
|
||||
const firstKey = clientsRef.current.keys().next().value
|
||||
if (firstKey) clientsRef.current.delete(firstKey)
|
||||
}
|
||||
client = new OpenCodeClient(url, directory)
|
||||
clientsRef.current.set(clientKey, client)
|
||||
}
|
||||
return client
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}, [queryClient])
|
||||
|
||||
const addPermission = useCallback((permission: PermissionRequest) => {
|
||||
addToSessionKeyedState(setPermissionsBySession, permission)
|
||||
}, [])
|
||||
|
||||
const removePermission = useCallback((permissionID: string, sessionID?: string) => {
|
||||
removeFromSessionKeyedState(setPermissionsBySession, permissionID, sessionID)
|
||||
}, [])
|
||||
|
||||
const addQuestion = useCallback((question: QuestionRequest) => {
|
||||
addToSessionKeyedState(setQuestionsBySession, question)
|
||||
}, [])
|
||||
|
||||
const removeQuestion = useCallback((requestID: string, sessionID?: string) => {
|
||||
removeFromSessionKeyedState(setQuestionsBySession, requestID, sessionID)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const permissionCount = allPermissions.length
|
||||
if (permissionCount > prevPermissionCountRef.current && permissionCount > 0 && !showPermissionDialog) {
|
||||
showToast.info(`${permissionCount} pending permission${permissionCount > 1 ? 's' : ''}`, {
|
||||
duration: 5000,
|
||||
action: {
|
||||
label: 'View',
|
||||
onClick: () => setShowPermissionDialog(true),
|
||||
},
|
||||
})
|
||||
}
|
||||
prevPermissionCountRef.current = permissionCount
|
||||
}, [allPermissions.length, showPermissionDialog])
|
||||
|
||||
const respondToPermission = useCallback(async (permissionID: string, sessionID: string, response: PermissionResponse) => {
|
||||
const client = getClient(sessionID)
|
||||
if (!client) throw new Error('No client found for session')
|
||||
await client.respondToPermission(sessionID, permissionID, response)
|
||||
removePermission(permissionID, sessionID)
|
||||
}, [getClient, removePermission])
|
||||
|
||||
const replyToQuestion = useCallback(async (requestID: string, answers: string[][]) => {
|
||||
const question = Object.values(questionsBySession).flat().find(q => q.id === requestID)
|
||||
if (!question) throw new Error('Question not found')
|
||||
const client = getClient(question.sessionID)
|
||||
if (!client) throw new Error('No client found for session')
|
||||
await client.replyToQuestion(requestID, answers)
|
||||
removeQuestion(requestID, question.sessionID)
|
||||
}, [getClient, removeQuestion, questionsBySession])
|
||||
|
||||
const rejectQuestion = useCallback(async (requestID: string) => {
|
||||
const question = Object.values(questionsBySession).flat().find(q => q.id === requestID)
|
||||
if (!question) throw new Error('Question not found')
|
||||
const client = getClient(question.sessionID)
|
||||
if (!client) throw new Error('No client found for session')
|
||||
await client.rejectQuestion(requestID)
|
||||
removeQuestion(requestID, question.sessionID)
|
||||
}, [getClient, removeQuestion, questionsBySession])
|
||||
|
||||
const getPermissionForCallID = useCallback((callID: string, sessionID: string): PermissionRequest | null => {
|
||||
const perms = permissionsBySession[sessionID] ?? []
|
||||
return perms.find(p => {
|
||||
const metadata = p.metadata as { tool?: { id?: string } } | undefined
|
||||
return metadata?.tool?.id === callID
|
||||
}) ?? null
|
||||
}, [permissionsBySession])
|
||||
|
||||
const getQuestionForCallID = useCallback((callID: string, sessionID: string): QuestionRequest | null => {
|
||||
const questions = questionsBySession[sessionID] ?? []
|
||||
return questions.find(q => q.tool?.callID === callID) ?? null
|
||||
}, [questionsBySession])
|
||||
|
||||
const hasPermissionsForSession = useCallback((sessionID: string): boolean => {
|
||||
return (permissionsBySession[sessionID]?.length ?? 0) > 0
|
||||
}, [permissionsBySession])
|
||||
|
||||
const hasQuestionsForSession = useCallback((sessionID: string): boolean => {
|
||||
return (questionsBySession[sessionID]?.length ?? 0) > 0
|
||||
}, [questionsBySession])
|
||||
|
||||
const navigateToCurrentQuestion = useCallback(() => {
|
||||
if (!currentQuestion) return
|
||||
const repoId = getRepoIdForSession(currentQuestion.sessionID)
|
||||
if (repoId) {
|
||||
const targetPath = `/repos/${repoId}/sessions/${currentQuestion.sessionID}`
|
||||
if (location.pathname !== targetPath) {
|
||||
navigate(targetPath)
|
||||
}
|
||||
}
|
||||
}, [currentQuestion, getRepoIdForSession, navigate, location.pathname])
|
||||
|
||||
const fetchInitialPendingData = useCallback(async () => {
|
||||
if (!repos || repos.length === 0) return
|
||||
|
||||
const uniqueDirectories = [...new Set(repos.map(r => r.fullPath))]
|
||||
|
||||
for (const directory of uniqueDirectories) {
|
||||
try {
|
||||
const client = new OpenCodeClient(OPENCODE_API_ENDPOINT, directory)
|
||||
const pendingQuestions = await client.listPendingQuestions()
|
||||
if (pendingQuestions && pendingQuestions.length > 0) {
|
||||
pendingQuestions.forEach(addQuestion)
|
||||
}
|
||||
} catch (error) {
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn(`Failed to fetch pending questions for ${directory}:`, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [repos, addQuestion])
|
||||
|
||||
useEffect(() => {
|
||||
const handleSSEMessage = (data: unknown) => {
|
||||
if (!data || typeof data !== 'object' || !('type' in data)) return
|
||||
|
||||
const event = data as SSEEvent
|
||||
|
||||
switch (event.type) {
|
||||
case 'permission.asked':
|
||||
if ('permission' in event.properties && 'sessionID' in event.properties) {
|
||||
addPermission(event.properties as PermissionRequest)
|
||||
}
|
||||
break
|
||||
case 'permission.replied':
|
||||
if ('requestID' in event.properties && 'sessionID' in event.properties) {
|
||||
removePermission(
|
||||
event.properties.requestID as string,
|
||||
event.properties.sessionID as string
|
||||
)
|
||||
}
|
||||
break
|
||||
case 'question.asked':
|
||||
if ('questions' in event.properties && 'sessionID' in event.properties && 'id' in event.properties) {
|
||||
addQuestion(event.properties as QuestionRequest)
|
||||
}
|
||||
break
|
||||
case 'question.replied':
|
||||
case 'question.rejected':
|
||||
if ('requestID' in event.properties && 'sessionID' in event.properties) {
|
||||
removeQuestion(
|
||||
event.properties.requestID as string,
|
||||
event.properties.sessionID as string
|
||||
)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const handleStatusChange = (connected: boolean) => {
|
||||
if (connected) {
|
||||
fetchInitialPendingData()
|
||||
}
|
||||
}
|
||||
|
||||
const unsubscribe = subscribeToSSE(handleSSEMessage, handleStatusChange)
|
||||
return unsubscribe
|
||||
}, [addPermission, removePermission, addQuestion, removeQuestion, fetchInitialPendingData])
|
||||
|
||||
const value: EventContextValue = useMemo(() => ({
|
||||
permissions: {
|
||||
current: currentPermission,
|
||||
pendingCount: allPermissions.length,
|
||||
respond: respondToPermission,
|
||||
dismiss: removePermission,
|
||||
getForCallID: getPermissionForCallID,
|
||||
hasForSession: hasPermissionsForSession,
|
||||
showDialog: showPermissionDialog,
|
||||
setShowDialog: setShowPermissionDialog,
|
||||
},
|
||||
questions: {
|
||||
current: currentQuestion,
|
||||
pendingCount: allQuestions.length,
|
||||
reply: replyToQuestion,
|
||||
reject: rejectQuestion,
|
||||
dismiss: removeQuestion,
|
||||
getForCallID: getQuestionForCallID,
|
||||
hasForSession: hasQuestionsForSession,
|
||||
navigateToCurrent: navigateToCurrentQuestion,
|
||||
},
|
||||
getRepoIdForSession,
|
||||
getClient,
|
||||
}), [
|
||||
currentPermission,
|
||||
allPermissions.length,
|
||||
respondToPermission,
|
||||
removePermission,
|
||||
getPermissionForCallID,
|
||||
hasPermissionsForSession,
|
||||
showPermissionDialog,
|
||||
currentQuestion,
|
||||
allQuestions.length,
|
||||
replyToQuestion,
|
||||
rejectQuestion,
|
||||
removeQuestion,
|
||||
getQuestionForCallID,
|
||||
hasQuestionsForSession,
|
||||
navigateToCurrentQuestion,
|
||||
getRepoIdForSession,
|
||||
getClient,
|
||||
])
|
||||
|
||||
return <EventContext.Provider value={value}>{children}</EventContext.Provider>
|
||||
}
|
||||
|
||||
export function useEventContext() {
|
||||
const context = useContext(EventContext)
|
||||
if (!context) {
|
||||
throw new Error('useEventContext must be used within EventProvider')
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
export function usePermissions() {
|
||||
const { permissions } = useEventContext()
|
||||
return permissions
|
||||
}
|
||||
|
||||
export function useQuestions() {
|
||||
const { questions } = useEventContext()
|
||||
return questions
|
||||
}
|
||||
@@ -1,395 +0,0 @@
|
||||
/* eslint-disable react-refresh/only-export-components */
|
||||
import { createContext, useContext, useEffect, useState, useCallback, useMemo, useRef } from 'react'
|
||||
import { OpenCodeClient } from '@/api/opencode'
|
||||
import { permissionEvents, usePermissionRequests } from '@/hooks/usePermissionRequests'
|
||||
import type { PermissionRequest, PermissionResponse } from '@/api/types'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
|
||||
type SessionInfo = {
|
||||
id: string
|
||||
directory?: string
|
||||
}
|
||||
|
||||
type ActiveRepo = {
|
||||
url: string
|
||||
directory?: string
|
||||
sessions: SessionInfo[]
|
||||
}
|
||||
|
||||
interface PermissionContextValue {
|
||||
currentPermission: PermissionRequest | null
|
||||
pendingCount: number
|
||||
isFromDifferentSession: boolean
|
||||
respondToPermission: (permissionID: string, sessionID: string, response: PermissionResponse) => Promise<void>
|
||||
dismissPermission: (permissionID: string, sessionID?: string) => void
|
||||
showDialog: boolean
|
||||
setShowDialog: (show: boolean) => void
|
||||
currentSessionId: string | null
|
||||
getPermissionForCallID: (callID: string, sessionID: string) => PermissionRequest | null
|
||||
hasPermissionsForSession: (sessionID: string) => boolean
|
||||
currentRepoDirectory: string | null
|
||||
getRepoForSession: (sessionID: string) => ActiveRepo | null
|
||||
}
|
||||
|
||||
const PermissionContext = createContext<PermissionContextValue | null>(null)
|
||||
|
||||
function useActiveRepos(queryClient: ReturnType<typeof useQueryClient>): ActiveRepo[] {
|
||||
const [activeRepos, setActiveRepos] = useState<ActiveRepo[]>([])
|
||||
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const lastProcessedRef = useRef<string[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
const checkRepos = () => {
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current)
|
||||
}
|
||||
|
||||
timeoutRef.current = setTimeout(() => {
|
||||
const cache = queryClient.getQueryCache()
|
||||
const queries = cache.getAll()
|
||||
const repoMap = new Map<string, { directory?: string, sessionIds: Set<string> }>()
|
||||
|
||||
queries.forEach((query) => {
|
||||
const key = query.queryKey
|
||||
|
||||
if (key[0] === 'opencode' && key[1] === 'sessions' && key.length >= 4) {
|
||||
const url = key[2] as string
|
||||
const directory = key[3] as string | undefined
|
||||
|
||||
if (!url || typeof url !== 'string') return
|
||||
|
||||
const repoKey = `${url}|${directory ?? ''}`
|
||||
if (!repoMap.has(repoKey)) {
|
||||
repoMap.set(repoKey, { directory, sessionIds: new Set() })
|
||||
}
|
||||
|
||||
const sessionsData = query.state.data as Array<{ id: string }> | undefined
|
||||
if (sessionsData) {
|
||||
sessionsData.forEach((session) => {
|
||||
repoMap.get(repoKey)!.sessionIds.add(session.id)
|
||||
})
|
||||
}
|
||||
} else if (key[0] === 'opencode' && key[1] === 'session' && key.length >= 5) {
|
||||
const url = key[2] as string
|
||||
const directory = key[4] as string | undefined
|
||||
const sessionData = query.state.data as { id: string } | undefined
|
||||
|
||||
if (!url || typeof url !== 'string') return
|
||||
|
||||
const repoKey = `${url}|${directory ?? ''}`
|
||||
if (!repoMap.has(repoKey)) {
|
||||
repoMap.set(repoKey, { directory, sessionIds: new Set() })
|
||||
}
|
||||
|
||||
if (sessionData && sessionData.id) {
|
||||
repoMap.get(repoKey)!.sessionIds.add(sessionData.id)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const repos = Array.from(repoMap.entries())
|
||||
.filter(([repoKey]) => {
|
||||
const url = repoKey.split('|')[0]
|
||||
try {
|
||||
new URL(url)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
.map(([repoKey, { directory, sessionIds }]) => ({
|
||||
url: repoKey.split('|')[0],
|
||||
directory,
|
||||
sessions: Array.from(sessionIds).map((id) => ({ id })),
|
||||
}))
|
||||
|
||||
const currentKeys = repos.map(r => `${r.url}|${r.directory ?? ''}`)
|
||||
const prevKeys = lastProcessedRef.current
|
||||
const currentSet = new Set(currentKeys)
|
||||
const prevSet = new Set(prevKeys)
|
||||
|
||||
const hasChanged = currentSet.size !== prevSet.size ||
|
||||
currentKeys.some(k => !prevSet.has(k))
|
||||
|
||||
if (hasChanged) {
|
||||
setActiveRepos(repos)
|
||||
lastProcessedRef.current = currentKeys
|
||||
}
|
||||
}, 100)
|
||||
}
|
||||
|
||||
checkRepos()
|
||||
const unsubscribe = queryClient.getQueryCache().subscribe(checkRepos)
|
||||
|
||||
return () => {
|
||||
unsubscribe()
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current)
|
||||
}
|
||||
}
|
||||
}, [queryClient])
|
||||
|
||||
return activeRepos
|
||||
}
|
||||
|
||||
type SessionRepoInfo = { url: string; directory?: string }
|
||||
|
||||
export function PermissionProvider({ children }: { children: React.ReactNode }) {
|
||||
const [showDialog, setShowDialog] = useState(true)
|
||||
const [currentSessionId, setCurrentSessionId] = useState<string | null>(null)
|
||||
const queryClient = useQueryClient()
|
||||
const activeRepos = useActiveRepos(queryClient)
|
||||
const clientsRef = useRef<Map<string, OpenCodeClient>>(new Map())
|
||||
const eventSourceRefs = useRef<Map<string, EventSource>>(new Map())
|
||||
const prevPendingCountRef = useRef(0)
|
||||
const sessionRepoMapRef = useRef<Map<string, SessionRepoInfo>>(new Map())
|
||||
|
||||
const {
|
||||
currentPermission,
|
||||
pendingCount,
|
||||
isFromDifferentSession,
|
||||
dismissPermission: dismiss,
|
||||
getPermissionForCallID,
|
||||
hasPermissionsForSession,
|
||||
} = usePermissionRequests()
|
||||
|
||||
useEffect(() => {
|
||||
if (currentPermission?.sessionID) {
|
||||
setCurrentSessionId(currentPermission.sessionID)
|
||||
}
|
||||
}, [currentPermission])
|
||||
|
||||
useEffect(() => {
|
||||
if (pendingCount > prevPendingCountRef.current && pendingCount > 0 && !showDialog) {
|
||||
showToast.info(`${pendingCount} pending permission${pendingCount > 1 ? 's' : ''}`, {
|
||||
duration: 5000,
|
||||
action: {
|
||||
label: 'View',
|
||||
onClick: () => setShowDialog(true),
|
||||
},
|
||||
})
|
||||
}
|
||||
prevPendingCountRef.current = pendingCount
|
||||
}, [pendingCount, showDialog])
|
||||
|
||||
const getClient = useCallback((sessionID: string): OpenCodeClient | null => {
|
||||
for (const repo of activeRepos) {
|
||||
if (repo.sessions.some((s) => s.id === sessionID)) {
|
||||
const clientKey = `${repo.url}|${repo.directory ?? ''}`
|
||||
let client = clientsRef.current.get(clientKey)
|
||||
if (!client) {
|
||||
client = new OpenCodeClient(repo.url, repo.directory)
|
||||
clientsRef.current.set(clientKey, client)
|
||||
}
|
||||
return client
|
||||
}
|
||||
}
|
||||
|
||||
const repoInfo = sessionRepoMapRef.current.get(sessionID)
|
||||
if (repoInfo) {
|
||||
const clientKey = `${repoInfo.url}|${repoInfo.directory ?? ''}`
|
||||
let client = clientsRef.current.get(clientKey)
|
||||
if (!client) {
|
||||
client = new OpenCodeClient(repoInfo.url, repoInfo.directory)
|
||||
clientsRef.current.set(clientKey, client)
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
const cache = queryClient.getQueryCache()
|
||||
const queries = cache.getAll()
|
||||
|
||||
for (const query of queries) {
|
||||
const key = query.queryKey
|
||||
|
||||
if (key[0] === 'opencode' && key.length >= 5 && key[1] === 'session') {
|
||||
const sessionData = query.state.data as { id: string } | undefined
|
||||
if (sessionData?.id === sessionID) {
|
||||
const url = key[2] as string
|
||||
const directory = key[4] as string | undefined
|
||||
|
||||
if (!url || typeof url !== 'string') continue
|
||||
|
||||
const clientKey = `${url}|${directory ?? ''}`
|
||||
let client = clientsRef.current.get(clientKey)
|
||||
if (!client) {
|
||||
client = new OpenCodeClient(url, directory)
|
||||
clientsRef.current.set(clientKey, client)
|
||||
}
|
||||
return client
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}, [activeRepos, queryClient])
|
||||
|
||||
useEffect(() => {
|
||||
const currentRefs = eventSourceRefs.current
|
||||
const currentClients = clientsRef.current
|
||||
const newKeys = new Set(activeRepos.map((r) => `${r.url}|${r.directory ?? ''}`))
|
||||
const existingKeys = new Set(currentRefs.keys())
|
||||
|
||||
existingKeys.forEach((key) => {
|
||||
if (!newKeys.has(key)) {
|
||||
const es = currentRefs.get(key)
|
||||
if (es) {
|
||||
es.close()
|
||||
currentRefs.delete(key)
|
||||
}
|
||||
if (currentClients.has(key)) {
|
||||
currentClients.delete(key)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return () => {
|
||||
currentRefs.forEach((es) => es.close())
|
||||
}
|
||||
}, [activeRepos])
|
||||
|
||||
useEffect(() => {
|
||||
const currentRefs = eventSourceRefs.current
|
||||
|
||||
activeRepos.forEach((repo) => {
|
||||
if (!repo.url) return
|
||||
|
||||
const repoKey = `${repo.url}|${repo.directory ?? ''}`
|
||||
const existingES = currentRefs.get(repoKey)
|
||||
if (existingES) return
|
||||
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(repo.url)
|
||||
} catch {
|
||||
console.error('Invalid URL for SSE:', repo.url)
|
||||
return
|
||||
}
|
||||
|
||||
if (url.pathname.endsWith('/')) {
|
||||
url.pathname += 'stream'
|
||||
} else {
|
||||
url.pathname += '/stream'
|
||||
}
|
||||
|
||||
if (repo.directory) {
|
||||
url.searchParams.set('directory', repo.directory)
|
||||
}
|
||||
|
||||
const es = new EventSource(url.toString())
|
||||
currentRefs.set(repoKey, es)
|
||||
|
||||
es.addEventListener('permission.asked', (e) => {
|
||||
try {
|
||||
const event = JSON.parse(e.data)
|
||||
if ('permission' in event.properties && 'sessionID' in event.properties) {
|
||||
sessionRepoMapRef.current.set(event.properties.sessionID, {
|
||||
url: repo.url,
|
||||
directory: repo.directory,
|
||||
})
|
||||
permissionEvents.emit({ type: 'add', permission: event.properties })
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to parse permission.asked event:', err)
|
||||
}
|
||||
})
|
||||
|
||||
es.addEventListener('permission.replied', (e) => {
|
||||
try {
|
||||
const event = JSON.parse(e.data)
|
||||
const requestID = event.properties.requestID || event.properties.permissionID
|
||||
if (requestID && 'sessionID' in event.properties) {
|
||||
permissionEvents.emit({
|
||||
type: 'remove',
|
||||
sessionID: event.properties.sessionID,
|
||||
permissionID: requestID,
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to parse permission.replied event:', err)
|
||||
}
|
||||
})
|
||||
|
||||
es.onerror = (err) => {
|
||||
console.error(`SSE connection error for ${repo.url}:`, err)
|
||||
setTimeout(() => {
|
||||
currentRefs.delete(repoKey)
|
||||
}, 1000)
|
||||
}
|
||||
})
|
||||
|
||||
return () => {
|
||||
currentRefs.forEach((es) => es.close())
|
||||
currentRefs.clear()
|
||||
}
|
||||
}, [activeRepos])
|
||||
|
||||
const respondToPermission = useCallback(
|
||||
async (permissionID: string, sessionID: string, response: PermissionResponse) => {
|
||||
const client = getClient(sessionID)
|
||||
if (!client) {
|
||||
throw new Error('No client found for session')
|
||||
}
|
||||
await client.respondToPermission(sessionID, permissionID, response)
|
||||
dismiss(permissionID, sessionID)
|
||||
},
|
||||
[getClient, dismiss],
|
||||
)
|
||||
|
||||
const getRepoForSession = useCallback((sessionID: string): ActiveRepo | null => {
|
||||
for (const repo of activeRepos) {
|
||||
if (repo.sessions.some((s) => s.id === sessionID)) {
|
||||
return repo
|
||||
}
|
||||
}
|
||||
return null
|
||||
}, [activeRepos])
|
||||
|
||||
const currentRepoDirectory = useMemo(() => {
|
||||
if (!currentPermission) return null
|
||||
const repo = getRepoForSession(currentPermission.sessionID)
|
||||
return repo?.directory ?? null
|
||||
}, [currentPermission, getRepoForSession])
|
||||
|
||||
const value: PermissionContextValue = useMemo(
|
||||
() => ({
|
||||
currentPermission,
|
||||
pendingCount,
|
||||
isFromDifferentSession,
|
||||
respondToPermission,
|
||||
dismissPermission: dismiss,
|
||||
showDialog,
|
||||
setShowDialog,
|
||||
currentSessionId,
|
||||
getPermissionForCallID,
|
||||
hasPermissionsForSession,
|
||||
currentRepoDirectory,
|
||||
getRepoForSession,
|
||||
}),
|
||||
[
|
||||
currentPermission,
|
||||
pendingCount,
|
||||
isFromDifferentSession,
|
||||
respondToPermission,
|
||||
dismiss,
|
||||
showDialog,
|
||||
currentSessionId,
|
||||
getPermissionForCallID,
|
||||
hasPermissionsForSession,
|
||||
currentRepoDirectory,
|
||||
getRepoForSession,
|
||||
],
|
||||
)
|
||||
|
||||
return <PermissionContext.Provider value={value}>{children}</PermissionContext.Provider>
|
||||
}
|
||||
|
||||
export function usePermissionContext() {
|
||||
const context = useContext(PermissionContext)
|
||||
if (!context) {
|
||||
throw new Error('usePermissionContext must be used within PermissionProvider')
|
||||
}
|
||||
return context
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react'
|
||||
import type { PermissionRequest } from '@/api/types'
|
||||
|
||||
type PermissionEventType = 'add' | 'remove'
|
||||
|
||||
interface PermissionEvent {
|
||||
type: PermissionEventType
|
||||
permission?: PermissionRequest
|
||||
sessionID?: string
|
||||
permissionID?: string
|
||||
}
|
||||
|
||||
type PermissionListener = (event: PermissionEvent) => void
|
||||
|
||||
const listeners = new Set<PermissionListener>()
|
||||
|
||||
export const permissionEvents = {
|
||||
emit: (event: PermissionEvent) => {
|
||||
listeners.forEach(listener => listener(event))
|
||||
},
|
||||
subscribe: (listener: PermissionListener) => {
|
||||
listeners.add(listener)
|
||||
return () => {
|
||||
listeners.delete(listener)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type PermissionsBySession = Record<string, PermissionRequest[]>
|
||||
|
||||
export function usePermissionRequests(currentSessionID?: string) {
|
||||
const [permissionsBySession, setPermissionsBySession] = useState<PermissionsBySession>({})
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribe = permissionEvents.subscribe((event) => {
|
||||
if (event.type === 'add' && event.permission) {
|
||||
const permission = event.permission
|
||||
const sessionID = permission.sessionID
|
||||
|
||||
setPermissionsBySession(prev => {
|
||||
const sessionPermissions = prev[sessionID] ?? []
|
||||
const existingIndex = sessionPermissions.findIndex(p => p.id === permission.id)
|
||||
|
||||
if (existingIndex >= 0) {
|
||||
const updated = [...sessionPermissions]
|
||||
updated[existingIndex] = permission
|
||||
return { ...prev, [sessionID]: updated }
|
||||
}
|
||||
|
||||
return { ...prev, [sessionID]: [...sessionPermissions, permission] }
|
||||
})
|
||||
} else if (event.type === 'remove' && event.permissionID && event.sessionID) {
|
||||
const { sessionID, permissionID } = event
|
||||
|
||||
setPermissionsBySession(prev => {
|
||||
const sessionPermissions = prev[sessionID]
|
||||
if (!sessionPermissions) return prev
|
||||
|
||||
const filtered = sessionPermissions.filter(p => p.id !== permissionID)
|
||||
if (filtered.length === 0) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(prev).filter(([key]) => key !== sessionID)
|
||||
)
|
||||
}
|
||||
return { ...prev, [sessionID]: filtered }
|
||||
})
|
||||
}
|
||||
})
|
||||
return unsubscribe
|
||||
}, [])
|
||||
|
||||
const allPermissions = useMemo(() => {
|
||||
return Object.values(permissionsBySession).flat()
|
||||
}, [permissionsBySession])
|
||||
|
||||
const currentPermission = useMemo(() => {
|
||||
if (currentSessionID) {
|
||||
const sessionPerms = permissionsBySession[currentSessionID] ?? []
|
||||
if (sessionPerms.length > 0) return sessionPerms[0]
|
||||
}
|
||||
return allPermissions[0] ?? null
|
||||
}, [permissionsBySession, currentSessionID, allPermissions])
|
||||
|
||||
const isFromDifferentSession = useMemo(() => {
|
||||
if (!currentPermission || !currentSessionID) return false
|
||||
return currentPermission.sessionID !== currentSessionID
|
||||
}, [currentPermission, currentSessionID])
|
||||
|
||||
const dismissPermission = useCallback((permissionID: string, sessionID?: string) => {
|
||||
setPermissionsBySession(prev => {
|
||||
if (sessionID) {
|
||||
const sessionPermissions = prev[sessionID]
|
||||
if (!sessionPermissions) return prev
|
||||
|
||||
const filtered = sessionPermissions.filter(p => p.id !== permissionID)
|
||||
if (filtered.length === 0) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(prev).filter(([key]) => key !== sessionID)
|
||||
)
|
||||
}
|
||||
return { ...prev, [sessionID]: filtered }
|
||||
}
|
||||
|
||||
const newState: PermissionsBySession = {}
|
||||
for (const [sid, perms] of Object.entries(prev)) {
|
||||
const filtered = perms.filter(p => p.id !== permissionID)
|
||||
if (filtered.length > 0) {
|
||||
newState[sid] = filtered
|
||||
}
|
||||
}
|
||||
return newState
|
||||
})
|
||||
}, [])
|
||||
|
||||
const clearAllPermissions = useCallback(() => {
|
||||
setPermissionsBySession({})
|
||||
}, [])
|
||||
|
||||
const getPermissionForCallID = useCallback((callID: string, sessionID: string): PermissionRequest | null => {
|
||||
const sessionPermissions = permissionsBySession[sessionID] ?? []
|
||||
return sessionPermissions.find(p => p.tool?.callID === callID) ?? null
|
||||
}, [permissionsBySession])
|
||||
|
||||
const hasPermissionsForSession = useCallback((sessionID: string): boolean => {
|
||||
const sessionPermissions = permissionsBySession[sessionID] ?? []
|
||||
return sessionPermissions.length > 0
|
||||
}, [permissionsBySession])
|
||||
|
||||
return {
|
||||
currentPermission,
|
||||
pendingCount: allPermissions.length,
|
||||
isFromDifferentSession,
|
||||
dismissPermission,
|
||||
clearAllPermissions,
|
||||
getPermissionForCallID,
|
||||
hasPermissionsForSession
|
||||
}
|
||||
}
|
||||
+287
-381
@@ -2,14 +2,11 @@ import { useEffect, useRef, useState, useCallback } from 'react'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { useOpenCodeClient } from './useOpenCode'
|
||||
import type { SSEEvent, MessageListResponse } from '@/api/types'
|
||||
import { permissionEvents } from './usePermissionRequests'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
import { useSessionTodos } from '@/stores/sessionTodosStore'
|
||||
|
||||
const MAX_RECONNECT_DELAY = 30000
|
||||
const INITIAL_RECONNECT_DELAY = 1000
|
||||
import { subscribeToSSE, reconnectSSE, addSSEDirectory, removeSSEDirectory } from '@/lib/sseManager'
|
||||
|
||||
const handleRestartServer = async () => {
|
||||
showToast.loading('Restarting OpenCode server...', {
|
||||
@@ -44,10 +41,6 @@ const handleRestartServer = async () => {
|
||||
export const useSSE = (opcodeUrl: string | null | undefined, directory?: string) => {
|
||||
const client = useOpenCodeClient(opcodeUrl, directory)
|
||||
const queryClient = useQueryClient()
|
||||
const eventSourceRef = useRef<EventSource | null>(null)
|
||||
const urlRef = useRef<string | null>(null)
|
||||
const reconnectTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const reconnectDelayRef = useRef(INITIAL_RECONNECT_DELAY)
|
||||
const mountedRef = useRef(true)
|
||||
const [isConnected, setIsConnected] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
@@ -55,388 +48,306 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string)
|
||||
const setSessionStatus = useSessionStatus((state) => state.setStatus)
|
||||
const setSessionTodos = useSessionTodos((state) => state.setTodos)
|
||||
|
||||
const scheduleReconnect = useCallback((connectFn: () => void) => {
|
||||
if (!mountedRef.current) return
|
||||
|
||||
if (reconnectTimeoutRef.current) {
|
||||
clearTimeout(reconnectTimeoutRef.current)
|
||||
}
|
||||
|
||||
const delay = reconnectDelayRef.current
|
||||
setIsReconnecting(true)
|
||||
|
||||
reconnectTimeoutRef.current = setTimeout(() => {
|
||||
if (!mountedRef.current) return
|
||||
reconnectDelayRef.current = Math.min(delay * 2, MAX_RECONNECT_DELAY)
|
||||
connectFn()
|
||||
}, delay)
|
||||
}, [])
|
||||
const handleSSEEvent = useCallback((event: SSEEvent) => {
|
||||
switch (event.type) {
|
||||
case 'session.updated':
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'sessions', opcodeUrl, directory] })
|
||||
if ('info' in event.properties) {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['opencode', 'session', opcodeUrl, event.properties.info.id, directory]
|
||||
})
|
||||
}
|
||||
break
|
||||
|
||||
const resetReconnectDelay = useCallback(() => {
|
||||
reconnectDelayRef.current = INITIAL_RECONNECT_DELAY
|
||||
setIsReconnecting(false)
|
||||
}, [])
|
||||
case 'session.deleted':
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'sessions', opcodeUrl, directory] })
|
||||
if ('sessionID' in event.properties) {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['opencode', 'session', opcodeUrl, event.properties.sessionID, directory]
|
||||
})
|
||||
}
|
||||
break
|
||||
|
||||
case 'session.status': {
|
||||
if (!('sessionID' in event.properties && 'status' in event.properties)) break
|
||||
const { sessionID, status } = event.properties
|
||||
setSessionStatus(sessionID, status)
|
||||
break
|
||||
}
|
||||
|
||||
case 'message.part.updated':
|
||||
case 'messagev2.part.updated': {
|
||||
if (!('part' in event.properties)) break
|
||||
|
||||
const { part } = event.properties
|
||||
const sessionID = part.sessionID
|
||||
const messageID = part.messageID
|
||||
|
||||
const currentData = queryClient.getQueryData<MessageListResponse>(['opencode', 'messages', opcodeUrl, sessionID, directory])
|
||||
if (!currentData) return
|
||||
|
||||
const messageExists = currentData.some(msg => msg.info.id === messageID)
|
||||
if (!messageExists) return
|
||||
|
||||
const updated = currentData.map(msg => {
|
||||
if (msg.info.id !== messageID) return msg
|
||||
|
||||
const existingPartIndex = msg.parts.findIndex(p => p.id === part.id)
|
||||
|
||||
if (existingPartIndex >= 0) {
|
||||
const newParts = [...msg.parts]
|
||||
newParts[existingPartIndex] = { ...part }
|
||||
return {
|
||||
info: { ...msg.info },
|
||||
parts: newParts
|
||||
}
|
||||
} else {
|
||||
return {
|
||||
info: { ...msg.info },
|
||||
parts: [...msg.parts, { ...part }]
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
queryClient.setQueryData(['opencode', 'messages', opcodeUrl, sessionID, directory], updated)
|
||||
break
|
||||
}
|
||||
|
||||
case 'message.updated':
|
||||
case 'messagev2.updated': {
|
||||
if (!('info' in event.properties)) break
|
||||
|
||||
const { info } = event.properties
|
||||
const sessionID = info.sessionID
|
||||
|
||||
if (info.role === 'assistant') {
|
||||
const isComplete = 'completed' in info.time && info.time.completed
|
||||
if (!isComplete) {
|
||||
setSessionStatus(sessionID, { type: 'busy' })
|
||||
}
|
||||
}
|
||||
|
||||
const currentData = queryClient.getQueryData<MessageListResponse>(['opencode', 'messages', opcodeUrl, sessionID, directory])
|
||||
if (!currentData) {
|
||||
queryClient.setQueryData(['opencode', 'messages', opcodeUrl, sessionID, directory], [{ info, parts: [] }])
|
||||
return
|
||||
}
|
||||
|
||||
const messageExists = currentData.some(msg => msg.info.id === info.id)
|
||||
|
||||
if (!messageExists) {
|
||||
const filteredData = info.role === 'user'
|
||||
? currentData.filter(msg => !msg.info.id.startsWith('optimistic_'))
|
||||
: currentData
|
||||
queryClient.setQueryData(['opencode', 'messages', opcodeUrl, sessionID, directory], [...filteredData, { info, parts: [] }])
|
||||
return
|
||||
}
|
||||
|
||||
const updated = currentData.map(msg => {
|
||||
if (msg.info.id !== info.id) return msg
|
||||
return {
|
||||
info: { ...info },
|
||||
parts: [...msg.parts]
|
||||
}
|
||||
})
|
||||
|
||||
queryClient.setQueryData(['opencode', 'messages', opcodeUrl, sessionID, directory], updated)
|
||||
break
|
||||
}
|
||||
|
||||
case 'message.removed':
|
||||
case 'messagev2.removed': {
|
||||
if (!('sessionID' in event.properties && 'messageID' in event.properties)) break
|
||||
|
||||
const { sessionID, messageID } = event.properties
|
||||
|
||||
queryClient.setQueryData<MessageListResponse>(
|
||||
['opencode', 'messages', opcodeUrl, sessionID, directory],
|
||||
(old) => {
|
||||
if (!old) return old
|
||||
return old.filter(msg => msg.info.id !== messageID)
|
||||
}
|
||||
)
|
||||
break
|
||||
}
|
||||
|
||||
case 'message.part.removed':
|
||||
case 'messagev2.part.removed': {
|
||||
if (!('sessionID' in event.properties && 'messageID' in event.properties && 'partID' in event.properties)) break
|
||||
|
||||
const { sessionID, messageID, partID } = event.properties
|
||||
|
||||
queryClient.setQueryData<MessageListResponse>(
|
||||
['opencode', 'messages', opcodeUrl, sessionID, directory],
|
||||
(old) => {
|
||||
if (!old) return old
|
||||
|
||||
return old.map(msg => {
|
||||
if (msg.info.id !== messageID) return msg
|
||||
return {
|
||||
...msg,
|
||||
parts: msg.parts.filter(p => p.id !== partID)
|
||||
}
|
||||
})
|
||||
}
|
||||
)
|
||||
break
|
||||
}
|
||||
|
||||
case 'session.compacted': {
|
||||
if (!('sessionID' in event.properties)) break
|
||||
|
||||
const { sessionID } = event.properties
|
||||
setSessionStatus(sessionID, { type: 'idle' })
|
||||
showToast.dismiss(`compact-${sessionID}`)
|
||||
showToast.success('Session compacted')
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['opencode', 'messages', opcodeUrl, sessionID, directory]
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'session.idle': {
|
||||
if (!('sessionID' in event.properties)) break
|
||||
|
||||
const { sessionID } = event.properties
|
||||
|
||||
setSessionStatus(sessionID, { type: 'idle' })
|
||||
|
||||
const currentData = queryClient.getQueryData<MessageListResponse>(['opencode', 'messages', opcodeUrl, sessionID, directory])
|
||||
if (!currentData) break
|
||||
|
||||
const now = Date.now()
|
||||
const updated = currentData.map(msg => {
|
||||
if (msg.info.role !== 'assistant') return msg
|
||||
|
||||
const updatedParts = msg.parts.map(part => {
|
||||
if (part.type !== 'tool') return part
|
||||
if (part.state.status !== 'running' && part.state.status !== 'pending') return part
|
||||
return {
|
||||
...part,
|
||||
state: {
|
||||
...part.state,
|
||||
status: 'completed' as const,
|
||||
output: part.state.status === 'running' ? '[Session ended - output not captured]' : '[Tool was pending when session ended]',
|
||||
title: part.state.status === 'running' ? (part.state as { title?: string }).title || '' : '',
|
||||
metadata: (part.state as { metadata?: Record<string, unknown> }).metadata || {},
|
||||
time: {
|
||||
start: (part.state as { time?: { start: number } }).time?.start || now,
|
||||
end: now
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const msgUpdated = updatedParts !== msg.parts
|
||||
if ('completed' in msg.info.time && msg.info.time.completed && !msgUpdated) return msg
|
||||
|
||||
return {
|
||||
...msg,
|
||||
info: {
|
||||
...msg.info,
|
||||
time: { ...msg.info.time, completed: now }
|
||||
},
|
||||
parts: updatedParts
|
||||
}
|
||||
})
|
||||
|
||||
queryClient.setQueryData(['opencode', 'messages', opcodeUrl, sessionID, directory], updated)
|
||||
break
|
||||
}
|
||||
|
||||
case 'todo.updated':
|
||||
if ('sessionID' in event.properties && 'todos' in event.properties) {
|
||||
const { sessionID, todos } = event.properties
|
||||
setSessionTodos(sessionID, todos)
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['opencode', 'todos', opcodeUrl, sessionID, directory]
|
||||
})
|
||||
}
|
||||
break
|
||||
|
||||
case 'installation.updated':
|
||||
if ('version' in event.properties) {
|
||||
showToast.success(`OpenCode updated to v${event.properties.version}`, {
|
||||
description: 'The server has been successfully upgraded.',
|
||||
duration: 5000,
|
||||
})
|
||||
}
|
||||
break
|
||||
|
||||
case 'installation.update-available':
|
||||
if ('version' in event.properties) {
|
||||
showToast.info(`OpenCode v${event.properties.version} is available`, {
|
||||
description: 'A new version is ready to install.',
|
||||
action: {
|
||||
label: 'Restart to Update',
|
||||
onClick: handleRestartServer
|
||||
},
|
||||
duration: 10000,
|
||||
})
|
||||
}
|
||||
break
|
||||
|
||||
default:
|
||||
break
|
||||
}
|
||||
}, [queryClient, opcodeUrl, directory, setSessionStatus, setSessionTodos])
|
||||
|
||||
const fetchInitialData = useCallback(async () => {
|
||||
if (!client || !mountedRef.current) return
|
||||
|
||||
try {
|
||||
const statuses = await client.getSessionStatuses()
|
||||
if (mountedRef.current && statuses) {
|
||||
Object.entries(statuses).forEach(([sessionID, status]) => {
|
||||
setSessionStatus(sessionID, status)
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof Error && !err.message.includes('aborted')) {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
}, [client, setSessionStatus])
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
|
||||
if (!client) {
|
||||
if (eventSourceRef.current) {
|
||||
eventSourceRef.current.close()
|
||||
eventSourceRef.current = null
|
||||
urlRef.current = null
|
||||
setIsConnected(false)
|
||||
}
|
||||
if (!opcodeUrl) {
|
||||
setIsConnected(false)
|
||||
return
|
||||
}
|
||||
|
||||
const eventSourceUrl = client.getEventSourceURL()
|
||||
|
||||
if (urlRef.current === eventSourceUrl && eventSourceRef.current) {
|
||||
return
|
||||
}
|
||||
|
||||
if (eventSourceRef.current) {
|
||||
eventSourceRef.current.close()
|
||||
}
|
||||
|
||||
urlRef.current = eventSourceUrl
|
||||
|
||||
const handleSSEEvent = (event: SSEEvent) => {
|
||||
switch (event.type) {
|
||||
case 'session.updated':
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'sessions', opcodeUrl, directory] })
|
||||
if ('info' in event.properties) {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['opencode', 'session', opcodeUrl, event.properties.info.id, directory]
|
||||
})
|
||||
}
|
||||
break
|
||||
|
||||
case 'session.deleted':
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'sessions', opcodeUrl, directory] })
|
||||
if ('sessionID' in event.properties) {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['opencode', 'session', opcodeUrl, event.properties.sessionID, directory]
|
||||
})
|
||||
}
|
||||
break
|
||||
|
||||
case 'session.status': {
|
||||
if (!('sessionID' in event.properties && 'status' in event.properties)) break
|
||||
const { sessionID, status } = event.properties
|
||||
setSessionStatus(sessionID, status)
|
||||
break
|
||||
}
|
||||
|
||||
case 'message.part.updated':
|
||||
case 'messagev2.part.updated': {
|
||||
if (!('part' in event.properties)) break
|
||||
|
||||
const { part } = event.properties
|
||||
const sessionID = part.sessionID
|
||||
const messageID = part.messageID
|
||||
|
||||
const currentData = queryClient.getQueryData<MessageListResponse>(['opencode', 'messages', opcodeUrl, sessionID, directory])
|
||||
if (!currentData) return
|
||||
|
||||
const messageExists = currentData.some(msg => msg.info.id === messageID)
|
||||
if (!messageExists) return
|
||||
|
||||
const updated = currentData.map(msg => {
|
||||
if (msg.info.id !== messageID) return msg
|
||||
|
||||
const existingPartIndex = msg.parts.findIndex(p => p.id === part.id)
|
||||
|
||||
if (existingPartIndex >= 0) {
|
||||
const newParts = [...msg.parts]
|
||||
newParts[existingPartIndex] = { ...part }
|
||||
return {
|
||||
info: { ...msg.info },
|
||||
parts: newParts
|
||||
}
|
||||
} else {
|
||||
return {
|
||||
info: { ...msg.info },
|
||||
parts: [...msg.parts, { ...part }]
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
queryClient.setQueryData(['opencode', 'messages', opcodeUrl, sessionID, directory], updated)
|
||||
break
|
||||
}
|
||||
|
||||
case 'message.updated':
|
||||
case 'messagev2.updated': {
|
||||
if (!('info' in event.properties)) break
|
||||
|
||||
const { info } = event.properties
|
||||
const sessionID = info.sessionID
|
||||
|
||||
if (info.role === 'assistant') {
|
||||
const isComplete = 'completed' in info.time && info.time.completed
|
||||
if (!isComplete) {
|
||||
setSessionStatus(sessionID, { type: 'busy' })
|
||||
}
|
||||
}
|
||||
|
||||
const currentData = queryClient.getQueryData<MessageListResponse>(['opencode', 'messages', opcodeUrl, sessionID, directory])
|
||||
if (!currentData) {
|
||||
queryClient.setQueryData(['opencode', 'messages', opcodeUrl, sessionID, directory], [{ info, parts: [] }])
|
||||
return
|
||||
}
|
||||
|
||||
const messageExists = currentData.some(msg => msg.info.id === info.id)
|
||||
|
||||
if (!messageExists) {
|
||||
const filteredData = info.role === 'user'
|
||||
? currentData.filter(msg => !msg.info.id.startsWith('optimistic_'))
|
||||
: currentData
|
||||
queryClient.setQueryData(['opencode', 'messages', opcodeUrl, sessionID, directory], [...filteredData, { info, parts: [] }])
|
||||
return
|
||||
}
|
||||
|
||||
const updated = currentData.map(msg => {
|
||||
if (msg.info.id !== info.id) return msg
|
||||
return {
|
||||
info: { ...info },
|
||||
parts: [...msg.parts]
|
||||
}
|
||||
})
|
||||
|
||||
queryClient.setQueryData(['opencode', 'messages', opcodeUrl, sessionID, directory], updated)
|
||||
break
|
||||
}
|
||||
|
||||
case 'message.removed':
|
||||
case 'messagev2.removed': {
|
||||
if (!('sessionID' in event.properties && 'messageID' in event.properties)) break
|
||||
|
||||
const { sessionID, messageID } = event.properties
|
||||
|
||||
queryClient.setQueryData<MessageListResponse>(
|
||||
['opencode', 'messages', opcodeUrl, sessionID, directory],
|
||||
(old) => {
|
||||
if (!old) return old
|
||||
return old.filter(msg => msg.info.id !== messageID)
|
||||
}
|
||||
)
|
||||
break
|
||||
}
|
||||
|
||||
case 'message.part.removed':
|
||||
case 'messagev2.part.removed': {
|
||||
if (!('sessionID' in event.properties && 'messageID' in event.properties && 'partID' in event.properties)) break
|
||||
|
||||
const { sessionID, messageID, partID } = event.properties
|
||||
|
||||
queryClient.setQueryData<MessageListResponse>(
|
||||
['opencode', 'messages', opcodeUrl, sessionID, directory],
|
||||
(old) => {
|
||||
if (!old) return old
|
||||
|
||||
return old.map(msg => {
|
||||
if (msg.info.id !== messageID) return msg
|
||||
return {
|
||||
...msg,
|
||||
parts: msg.parts.filter(p => p.id !== partID)
|
||||
}
|
||||
})
|
||||
}
|
||||
)
|
||||
break
|
||||
}
|
||||
|
||||
case 'session.compacted': {
|
||||
if (!('sessionID' in event.properties)) break
|
||||
|
||||
const { sessionID } = event.properties
|
||||
setSessionStatus(sessionID, { type: 'idle' })
|
||||
showToast.dismiss(`compact-${sessionID}`)
|
||||
showToast.success('Session compacted')
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['opencode', 'messages', opcodeUrl, sessionID, directory]
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'session.idle': {
|
||||
if (!('sessionID' in event.properties)) break
|
||||
|
||||
const { sessionID } = event.properties
|
||||
|
||||
setSessionStatus(sessionID, { type: 'idle' })
|
||||
|
||||
const currentData = queryClient.getQueryData<MessageListResponse>(['opencode', 'messages', opcodeUrl, sessionID, directory])
|
||||
if (!currentData) break
|
||||
|
||||
const now = Date.now()
|
||||
const updated = currentData.map(msg => {
|
||||
if (msg.info.role !== 'assistant') return msg
|
||||
|
||||
const updatedParts = msg.parts.map(part => {
|
||||
if (part.type !== 'tool') return part
|
||||
if (part.state.status !== 'running' && part.state.status !== 'pending') return part
|
||||
return {
|
||||
...part,
|
||||
state: {
|
||||
...part.state,
|
||||
status: 'completed' as const,
|
||||
output: part.state.status === 'running' ? '[Session ended - output not captured]' : '[Tool was pending when session ended]',
|
||||
title: part.state.status === 'running' ? (part.state as { title?: string }).title || '' : '',
|
||||
metadata: (part.state as { metadata?: Record<string, unknown> }).metadata || {},
|
||||
time: {
|
||||
start: (part.state as { time?: { start: number } }).time?.start || now,
|
||||
end: now
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const msgUpdated = updatedParts !== msg.parts
|
||||
if ('completed' in msg.info.time && msg.info.time.completed && !msgUpdated) return msg
|
||||
|
||||
return {
|
||||
...msg,
|
||||
info: {
|
||||
...msg.info,
|
||||
time: { ...msg.info.time, completed: now }
|
||||
},
|
||||
parts: updatedParts
|
||||
}
|
||||
})
|
||||
|
||||
queryClient.setQueryData(['opencode', 'messages', opcodeUrl, sessionID, directory], updated)
|
||||
break
|
||||
}
|
||||
|
||||
case 'permission.asked':
|
||||
if ('permission' in event.properties && 'sessionID' in event.properties) {
|
||||
permissionEvents.emit({ type: 'add', permission: event.properties })
|
||||
}
|
||||
break
|
||||
|
||||
case 'permission.replied':
|
||||
if ('requestID' in event.properties && 'sessionID' in event.properties) {
|
||||
permissionEvents.emit({
|
||||
type: 'remove',
|
||||
sessionID: event.properties.sessionID as string,
|
||||
permissionID: event.properties.requestID as string
|
||||
})
|
||||
}
|
||||
break
|
||||
|
||||
case 'todo.updated':
|
||||
if ('sessionID' in event.properties && 'todos' in event.properties) {
|
||||
const { sessionID, todos } = event.properties
|
||||
setSessionTodos(sessionID, todos)
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['opencode', 'todos', opcodeUrl, sessionID, directory]
|
||||
})
|
||||
}
|
||||
break
|
||||
|
||||
case 'installation.updated':
|
||||
if ('version' in event.properties) {
|
||||
showToast.success(`OpenCode updated to v${event.properties.version}`, {
|
||||
description: 'The server has been successfully upgraded.',
|
||||
duration: 5000,
|
||||
})
|
||||
}
|
||||
break
|
||||
|
||||
case 'installation.update-available':
|
||||
if ('version' in event.properties) {
|
||||
showToast.info(`OpenCode v${event.properties.version} is available`, {
|
||||
description: 'A new version is ready to install.',
|
||||
action: {
|
||||
label: 'Restart to Update',
|
||||
onClick: handleRestartServer
|
||||
},
|
||||
duration: 10000,
|
||||
})
|
||||
}
|
||||
break
|
||||
|
||||
default:
|
||||
break
|
||||
const handleMessage = (data: unknown) => {
|
||||
if (data && typeof data === 'object' && 'type' in data) {
|
||||
handleSSEEvent(data as SSEEvent)
|
||||
}
|
||||
}
|
||||
|
||||
const connectSSE = () => {
|
||||
|
||||
const handleStatusChange = (connected: boolean) => {
|
||||
if (!mountedRef.current) return
|
||||
setIsConnected(connected)
|
||||
setIsReconnecting(!connected)
|
||||
|
||||
if (reconnectTimeoutRef.current) {
|
||||
clearTimeout(reconnectTimeoutRef.current)
|
||||
reconnectTimeoutRef.current = null
|
||||
}
|
||||
|
||||
if (eventSourceRef.current) {
|
||||
eventSourceRef.current.close()
|
||||
eventSourceRef.current = null
|
||||
}
|
||||
|
||||
try {
|
||||
const eventSource = new EventSource(eventSourceUrl)
|
||||
eventSourceRef.current = eventSource
|
||||
|
||||
eventSource.onopen = async () => {
|
||||
if (!mountedRef.current) return
|
||||
setIsConnected(true)
|
||||
setError(null)
|
||||
resetReconnectDelay()
|
||||
|
||||
try {
|
||||
const statuses = await client.getSessionStatuses()
|
||||
if (statuses && mountedRef.current) {
|
||||
Object.entries(statuses).forEach(([sessionID, status]) => {
|
||||
setSessionStatus(sessionID, status)
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch initial session statuses:', err)
|
||||
}
|
||||
}
|
||||
|
||||
eventSource.onerror = () => {
|
||||
if (!mountedRef.current) return
|
||||
|
||||
setIsConnected(false)
|
||||
setError('Connection lost. Reconnecting...')
|
||||
|
||||
if (eventSourceRef.current) {
|
||||
eventSourceRef.current.close()
|
||||
eventSourceRef.current = null
|
||||
}
|
||||
|
||||
scheduleReconnect(connectSSE)
|
||||
}
|
||||
|
||||
eventSource.onmessage = (event) => {
|
||||
try {
|
||||
const data: SSEEvent = JSON.parse(event.data)
|
||||
handleSSEEvent(data)
|
||||
} catch (err) {
|
||||
console.error('Failed to parse SSE event:', err)
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to connect')
|
||||
setIsConnected(false)
|
||||
scheduleReconnect(connectSSE)
|
||||
if (connected) {
|
||||
setError(null)
|
||||
fetchInitialData()
|
||||
} else {
|
||||
setError('Connection lost. Reconnecting...')
|
||||
}
|
||||
}
|
||||
|
||||
if (directory) {
|
||||
addSSEDirectory(directory)
|
||||
}
|
||||
|
||||
const unsubscribe = subscribeToSSE(handleMessage, handleStatusChange)
|
||||
|
||||
const handleReconnect = () => {
|
||||
if (!eventSourceRef.current || eventSourceRef.current.readyState === EventSource.CLOSED) {
|
||||
resetReconnectDelay()
|
||||
connectSSE()
|
||||
}
|
||||
reconnectSSE()
|
||||
}
|
||||
|
||||
connectSSE()
|
||||
|
||||
window.addEventListener('focus', handleReconnect)
|
||||
window.addEventListener('online', handleReconnect)
|
||||
|
||||
@@ -444,17 +355,12 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string)
|
||||
mountedRef.current = false
|
||||
window.removeEventListener('focus', handleReconnect)
|
||||
window.removeEventListener('online', handleReconnect)
|
||||
if (reconnectTimeoutRef.current) {
|
||||
clearTimeout(reconnectTimeoutRef.current)
|
||||
reconnectTimeoutRef.current = null
|
||||
}
|
||||
if (eventSourceRef.current) {
|
||||
eventSourceRef.current.close()
|
||||
eventSourceRef.current = null
|
||||
setIsConnected(false)
|
||||
unsubscribe()
|
||||
if (directory) {
|
||||
removeSSEDirectory(directory)
|
||||
}
|
||||
}
|
||||
}, [client, queryClient, opcodeUrl, directory, scheduleReconnect, resetReconnectDelay, setSessionStatus, setSessionTodos])
|
||||
}, [opcodeUrl, directory, handleSSEEvent, fetchInitialData])
|
||||
|
||||
return { isConnected, error, isReconnecting }
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
type SessionKeyedItem = { id: string; sessionID: string }
|
||||
type SessionKeyedState<T> = Record<string, T[]>
|
||||
type StateSetter<T> = React.Dispatch<React.SetStateAction<SessionKeyedState<T>>>
|
||||
|
||||
export function addToSessionKeyedState<T extends SessionKeyedItem>(
|
||||
setter: StateSetter<T>,
|
||||
item: T
|
||||
): void {
|
||||
setter(prev => {
|
||||
const sessionID = item.sessionID
|
||||
const existing = prev[sessionID] ?? []
|
||||
const existingIndex = existing.findIndex(i => i.id === item.id)
|
||||
|
||||
if (existingIndex >= 0) {
|
||||
const updated = [...existing]
|
||||
updated[existingIndex] = item
|
||||
return { ...prev, [sessionID]: updated }
|
||||
}
|
||||
return { ...prev, [sessionID]: [...existing, item] }
|
||||
})
|
||||
}
|
||||
|
||||
export function removeFromSessionKeyedState<T extends SessionKeyedItem>(
|
||||
setter: StateSetter<T>,
|
||||
id: string,
|
||||
sessionID?: string
|
||||
): void {
|
||||
setter(prev => {
|
||||
if (sessionID) {
|
||||
const existing = prev[sessionID]
|
||||
if (!existing) return prev
|
||||
const filtered = existing.filter(i => i.id !== id)
|
||||
if (filtered.length === 0) {
|
||||
const { [sessionID]: _removed, ...rest } = prev
|
||||
void _removed
|
||||
return rest
|
||||
}
|
||||
return { ...prev, [sessionID]: filtered }
|
||||
}
|
||||
|
||||
const newState: SessionKeyedState<T> = {}
|
||||
for (const [sid, items] of Object.entries(prev)) {
|
||||
const filtered = items.filter(i => i.id !== id)
|
||||
if (filtered.length > 0) newState[sid] = filtered
|
||||
}
|
||||
return newState
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
import { DEFAULTS } from '@opencode-manager/shared/config'
|
||||
|
||||
type SSEEventHandler = (data: unknown) => void
|
||||
type SSEStatusHandler = (connected: boolean) => void
|
||||
|
||||
interface SSESubscriber {
|
||||
id: string
|
||||
onMessage: SSEEventHandler
|
||||
onStatusChange?: SSEStatusHandler
|
||||
}
|
||||
|
||||
const { RECONNECT_DELAY_MS, MAX_RECONNECT_DELAY_MS } = DEFAULTS.SSE
|
||||
|
||||
class SSEManager {
|
||||
private static instance: SSEManager
|
||||
private eventSource: EventSource | null = null
|
||||
private subscribers: Map<string, SSESubscriber> = new Map()
|
||||
private directories: Set<string> = new Set()
|
||||
private pendingDirectories: Set<string> = new Set()
|
||||
private reconnectTimeout: ReturnType<typeof setTimeout> | null = null
|
||||
private reconnectDelay: number = RECONNECT_DELAY_MS
|
||||
private isConnected = false
|
||||
private subscriberIdCounter = 0
|
||||
private clientId: string | null = null
|
||||
|
||||
private constructor() {}
|
||||
|
||||
static getInstance(): SSEManager {
|
||||
if (!SSEManager.instance) {
|
||||
SSEManager.instance = new SSEManager()
|
||||
}
|
||||
return SSEManager.instance
|
||||
}
|
||||
|
||||
subscribe(
|
||||
onMessage: SSEEventHandler,
|
||||
onStatusChange?: SSEStatusHandler
|
||||
): () => void {
|
||||
const id = `sub_${++this.subscriberIdCounter}`
|
||||
const subscriber: SSESubscriber = {
|
||||
id,
|
||||
onMessage,
|
||||
onStatusChange
|
||||
}
|
||||
|
||||
this.subscribers.set(id, subscriber)
|
||||
|
||||
if (onStatusChange) {
|
||||
onStatusChange(this.isConnected)
|
||||
}
|
||||
|
||||
if (this.subscribers.size === 1) {
|
||||
this.connect()
|
||||
}
|
||||
|
||||
return () => this.unsubscribe(id)
|
||||
}
|
||||
|
||||
private unsubscribe(id: string): void {
|
||||
this.subscribers.delete(id)
|
||||
|
||||
if (this.subscribers.size === 0) {
|
||||
this.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
addDirectory(directory: string): () => void {
|
||||
if (this.directories.has(directory)) {
|
||||
return () => this.cleanupDirectory(directory)
|
||||
}
|
||||
|
||||
this.directories.add(directory)
|
||||
|
||||
if (this.clientId && this.isConnected) {
|
||||
this.subscribeToDirectory(directory)
|
||||
} else {
|
||||
this.pendingDirectories.add(directory)
|
||||
if (!this.eventSource) {
|
||||
this.reconnect()
|
||||
}
|
||||
}
|
||||
|
||||
return () => this.cleanupDirectory(directory)
|
||||
}
|
||||
|
||||
private cleanupDirectory(directory: string): void {
|
||||
this.directories.delete(directory)
|
||||
this.pendingDirectories.delete(directory)
|
||||
|
||||
if (this.clientId && this.isConnected) {
|
||||
fetch('/api/sse/unsubscribe', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ clientId: this.clientId, directories: [directory] })
|
||||
}).catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
private subscribeToDirectory(directory: string): void {
|
||||
fetch('/api/sse/subscribe', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ clientId: this.clientId, directories: [directory] })
|
||||
}).then(res => {
|
||||
if (!res.ok) {
|
||||
this.reconnect()
|
||||
}
|
||||
}).catch(() => {
|
||||
this.reconnect()
|
||||
})
|
||||
}
|
||||
|
||||
private flushPendingDirectories(): void {
|
||||
if (this.pendingDirectories.size === 0) return
|
||||
if (!this.clientId || !this.isConnected) return
|
||||
|
||||
const dirs = Array.from(this.pendingDirectories)
|
||||
this.pendingDirectories.clear()
|
||||
|
||||
fetch('/api/sse/subscribe', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ clientId: this.clientId, directories: dirs })
|
||||
}).then(res => {
|
||||
if (!res.ok) {
|
||||
dirs.forEach(d => this.pendingDirectories.add(d))
|
||||
this.reconnect()
|
||||
}
|
||||
}).catch(() => {
|
||||
dirs.forEach(d => this.pendingDirectories.add(d))
|
||||
this.reconnect()
|
||||
})
|
||||
}
|
||||
|
||||
removeDirectory(directory: string): void {
|
||||
if (!this.directories.has(directory)) return
|
||||
|
||||
this.directories.delete(directory)
|
||||
|
||||
if (this.clientId && this.isConnected) {
|
||||
fetch('/api/sse/unsubscribe', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ clientId: this.clientId, directories: [directory] })
|
||||
}).catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
getDirectories(): string[] {
|
||||
return Array.from(this.directories)
|
||||
}
|
||||
|
||||
private buildUrl(): string {
|
||||
const url = new URL('/api/sse/stream', window.location.origin)
|
||||
if (this.directories.size > 0) {
|
||||
url.searchParams.set('directories', Array.from(this.directories).join(','))
|
||||
}
|
||||
return url.toString()
|
||||
}
|
||||
|
||||
private connect(): void {
|
||||
if (this.eventSource) return
|
||||
|
||||
const url = this.buildUrl()
|
||||
this.eventSource = new EventSource(url)
|
||||
|
||||
this.eventSource.onopen = () => {
|
||||
this.isConnected = true
|
||||
this.reconnectDelay = RECONNECT_DELAY_MS
|
||||
this.notifyStatusChange(true)
|
||||
}
|
||||
|
||||
this.eventSource.onerror = () => {
|
||||
this.isConnected = false
|
||||
this.clientId = null
|
||||
this.notifyStatusChange(false)
|
||||
|
||||
if (this.eventSource) {
|
||||
this.eventSource.close()
|
||||
this.eventSource = null
|
||||
}
|
||||
|
||||
if (this.subscribers.size > 0) {
|
||||
this.scheduleReconnect()
|
||||
}
|
||||
}
|
||||
|
||||
this.eventSource.onmessage = (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data)
|
||||
this.broadcast(data)
|
||||
} catch {
|
||||
// Ignore parse errors
|
||||
}
|
||||
}
|
||||
|
||||
this.eventSource.addEventListener('connected', (event) => {
|
||||
try {
|
||||
const data = JSON.parse((event as MessageEvent).data)
|
||||
if (data.clientId) {
|
||||
this.clientId = data.clientId
|
||||
}
|
||||
this.isConnected = true
|
||||
this.notifyStatusChange(true)
|
||||
this.flushPendingDirectories()
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private disconnect(): void {
|
||||
if (this.reconnectTimeout) {
|
||||
clearTimeout(this.reconnectTimeout)
|
||||
this.reconnectTimeout = null
|
||||
}
|
||||
|
||||
if (this.eventSource) {
|
||||
this.eventSource.close()
|
||||
this.eventSource = null
|
||||
}
|
||||
|
||||
this.isConnected = false
|
||||
this.clientId = null
|
||||
}
|
||||
|
||||
private scheduleReconnect(): void {
|
||||
if (this.reconnectTimeout) return
|
||||
|
||||
this.reconnectTimeout = setTimeout(() => {
|
||||
this.reconnectTimeout = null
|
||||
this.reconnectDelay = Math.min(this.reconnectDelay * 2, MAX_RECONNECT_DELAY_MS)
|
||||
this.connect()
|
||||
}, this.reconnectDelay)
|
||||
}
|
||||
|
||||
private notifyStatusChange(connected: boolean): void {
|
||||
this.subscribers.forEach(sub => {
|
||||
if (sub.onStatusChange) {
|
||||
try {
|
||||
sub.onStatusChange(connected)
|
||||
} catch {
|
||||
// Ignore callback errors
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private broadcast(data: unknown): void {
|
||||
this.subscribers.forEach(sub => {
|
||||
try {
|
||||
sub.onMessage(data)
|
||||
} catch {
|
||||
// Ignore callback errors
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
reconnect(): void {
|
||||
if (this.subscribers.size === 0) return
|
||||
|
||||
this.reconnectDelay = RECONNECT_DELAY_MS
|
||||
this.disconnect()
|
||||
this.connect()
|
||||
}
|
||||
|
||||
getConnectionStatus(): boolean {
|
||||
return this.isConnected
|
||||
}
|
||||
}
|
||||
|
||||
export const sseManager = SSEManager.getInstance()
|
||||
|
||||
export function subscribeToSSE(
|
||||
onMessage: SSEEventHandler,
|
||||
onStatusChange?: SSEStatusHandler
|
||||
): () => void {
|
||||
return sseManager.subscribe(onMessage, onStatusChange)
|
||||
}
|
||||
|
||||
export function addSSEDirectory(directory: string): () => void {
|
||||
return sseManager.addDirectory(directory)
|
||||
}
|
||||
|
||||
export function removeSSEDirectory(directory: string): void {
|
||||
sseManager.removeDirectory(directory)
|
||||
}
|
||||
|
||||
export function reconnectSSE(): void {
|
||||
sseManager.reconnect()
|
||||
}
|
||||
|
||||
export function isSSEConnected(): boolean {
|
||||
return sseManager.getConnectionStatus()
|
||||
}
|
||||
@@ -8,15 +8,15 @@ import { Header } from "@/components/ui/header";
|
||||
import { SwitchConfigDialog } from "@/components/repo/SwitchConfigDialog";
|
||||
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
|
||||
import { useCreateSession } from "@/hooks/useOpenCode";
|
||||
import { useSSE } from "@/hooks/useSSE";
|
||||
import { OPENCODE_API_ENDPOINT, API_BASE_URL } from "@/config";
|
||||
import { useSwipeBack } from "@/hooks/useMobile";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { BranchSwitcher } from "@/components/repo/BranchSwitcher";
|
||||
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
|
||||
import { Plug, FolderOpen, Plus, GitBranch } from "lucide-react";
|
||||
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { Plug, FolderOpen, Plus, GitBranch, Loader2 } from "lucide-react";
|
||||
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
|
||||
|
||||
export function RepoDetail() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
@@ -59,6 +59,8 @@ export function RepoDetail() {
|
||||
|
||||
const repoDirectory = repo?.fullPath;
|
||||
|
||||
useSSE(opcodeUrl, repoDirectory);
|
||||
|
||||
const createSessionMutation = useCreateSession(opcodeUrl, repoDirectory);
|
||||
|
||||
const handleCreateSession = async (options?: {
|
||||
@@ -140,6 +142,9 @@ export function RepoDetail() {
|
||||
) : null}
|
||||
</div>
|
||||
<Header.Actions>
|
||||
<div className="hidden sm:flex items-center gap-1">
|
||||
<PendingActionsGroup />
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setMcpDialogOpen(true)}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
|
||||
import { Header } from "@/components/ui/header";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Plus, FolderOpen } from "lucide-react";
|
||||
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
|
||||
|
||||
export function Repos() {
|
||||
const [addRepoOpen, setAddRepoOpen] = useState(false);
|
||||
@@ -21,6 +22,7 @@ export function Repos() {
|
||||
<Header.Title logo>OpenCode</Header.Title>
|
||||
</div>
|
||||
<Header.Actions>
|
||||
<PendingActionsGroup />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
|
||||
@@ -33,6 +33,9 @@ import { showToast } from "@/lib/toast";
|
||||
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
|
||||
import { createOpenCodeClient } from "@/api/opencode";
|
||||
import { useSessionStatus } from "@/stores/sessionStatusStore";
|
||||
import { useQuestions } from "@/contexts/EventContext";
|
||||
import { QuestionPrompt } from "@/components/session/QuestionPrompt";
|
||||
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
|
||||
|
||||
export function SessionDetail() {
|
||||
const { id, sessionId } = useParams<{ id: string; sessionId: string }>();
|
||||
@@ -112,6 +115,7 @@ export function SessionDetail() {
|
||||
const isEditingMessage = useUIState((state) => state.isEditingMessage);
|
||||
const { isPlaying, stop } = useTTS();
|
||||
const setSessionStatus = useSessionStatus((state) => state.setStatus);
|
||||
const { current: currentQuestion, reply: replyToQuestion, reject: rejectQuestion } = useQuestions();
|
||||
|
||||
const handleNewSession = useCallback(async () => {
|
||||
try {
|
||||
@@ -332,6 +336,9 @@ export function SessionDetail() {
|
||||
/>
|
||||
</div>
|
||||
<Header.Actions className="gap-2 sm:gap-4">
|
||||
<div className="hidden sm:flex items-center gap-1">
|
||||
<PendingActionsGroup />
|
||||
</div>
|
||||
<ContextUsageIndicator
|
||||
opcodeUrl={opcodeUrl}
|
||||
sessionID={sessionId}
|
||||
@@ -458,6 +465,14 @@ export function SessionDetail() {
|
||||
<span className="text-sm font-medium hidden sm:inline">Stop Audio</span>
|
||||
</button>
|
||||
)}
|
||||
{currentQuestion && currentQuestion.sessionID === sessionId && (
|
||||
<QuestionPrompt
|
||||
key={currentQuestion.id}
|
||||
question={currentQuestion}
|
||||
onReply={replyToQuestion}
|
||||
onReject={rejectQuestion}
|
||||
/>
|
||||
)}
|
||||
<PromptInput
|
||||
ref={promptInputRef}
|
||||
opcodeUrl={opcodeUrl}
|
||||
|
||||
Generated
+28
@@ -33,6 +33,9 @@ importers:
|
||||
dotenv:
|
||||
specifier: ^17.2.3
|
||||
version: 17.2.3
|
||||
eventsource:
|
||||
specifier: ^4.1.0
|
||||
version: 4.1.0
|
||||
hono:
|
||||
specifier: ^4.10.1
|
||||
version: 4.11.3
|
||||
@@ -58,6 +61,9 @@ importers:
|
||||
'@types/bun':
|
||||
specifier: latest
|
||||
version: 1.3.5
|
||||
'@types/eventsource':
|
||||
specifier: ^3.0.0
|
||||
version: 3.0.0
|
||||
'@vitest/ui':
|
||||
specifier: ^3.2.4
|
||||
version: 3.2.4(vitest@3.2.4)
|
||||
@@ -1528,6 +1534,10 @@ packages:
|
||||
'@types/estree@1.0.8':
|
||||
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
|
||||
|
||||
'@types/eventsource@3.0.0':
|
||||
resolution: {integrity: sha512-yEhFj31FTD29DtNeqePu+A+lD6loRef6YOM5XfN1kUwBHyy2DySGlA3jJU+FbQSkrfmlBVluf2Dub/OyReFGKA==}
|
||||
deprecated: This is a stub types definition. eventsource provides its own type definitions, so you do not need this installed.
|
||||
|
||||
'@types/geojson@7946.0.16':
|
||||
resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==}
|
||||
|
||||
@@ -2320,6 +2330,14 @@ packages:
|
||||
resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}
|
||||
engines: {node: '>=0.8.x'}
|
||||
|
||||
eventsource-parser@3.0.6:
|
||||
resolution: {integrity: sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==}
|
||||
engines: {node: '>=18.0.0'}
|
||||
|
||||
eventsource@4.1.0:
|
||||
resolution: {integrity: sha512-2GuF51iuHX6A9xdTccMTsNb7VO0lHZihApxhvQzJB5A03DvHDd2FQepodbMaztPBmBcE/ox7o2gqaxGhYB9LhQ==}
|
||||
engines: {node: '>=20.0.0'}
|
||||
|
||||
expect-type@1.3.0:
|
||||
resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==}
|
||||
engines: {node: '>=12.0.0'}
|
||||
@@ -4969,6 +4987,10 @@ snapshots:
|
||||
|
||||
'@types/estree@1.0.8': {}
|
||||
|
||||
'@types/eventsource@3.0.0':
|
||||
dependencies:
|
||||
eventsource: 4.1.0
|
||||
|
||||
'@types/geojson@7946.0.16': {}
|
||||
|
||||
'@types/hast@3.0.4':
|
||||
@@ -5863,6 +5885,12 @@ snapshots:
|
||||
|
||||
events@3.3.0: {}
|
||||
|
||||
eventsource-parser@3.0.6: {}
|
||||
|
||||
eventsource@4.1.0:
|
||||
dependencies:
|
||||
eventsource-parser: 3.0.6
|
||||
|
||||
expect-type@1.3.0: {}
|
||||
|
||||
extend@3.0.2: {}
|
||||
|
||||
@@ -42,6 +42,12 @@ export const DEFAULTS = {
|
||||
DEBUG: false,
|
||||
LOG_LEVEL: 'info',
|
||||
},
|
||||
|
||||
SSE: {
|
||||
RECONNECT_DELAY_MS: 1000,
|
||||
MAX_RECONNECT_DELAY_MS: 30000,
|
||||
IDLE_GRACE_PERIOD_MS: 5000,
|
||||
},
|
||||
} as const
|
||||
|
||||
export const ALLOWED_MIME_TYPES = [
|
||||
|
||||
@@ -3,3 +3,4 @@ export * from './repo'
|
||||
export * from './files'
|
||||
export * from './opencode'
|
||||
export * from './auth'
|
||||
export * from './sse'
|
||||
@@ -0,0 +1,8 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const SSESubscribeSchema = z.object({
|
||||
clientId: z.string().min(1),
|
||||
directories: z.array(z.string()),
|
||||
});
|
||||
|
||||
export type SSESubscribeRequest = z.infer<typeof SSESubscribeSchema>;
|
||||
Reference in new issue
Block a user