diff --git a/.github/social-preview.png b/.github/social-preview.png new file mode 100644 index 00000000..06aaaa32 Binary files /dev/null and b/.github/social-preview.png differ diff --git a/backend/src/services/proxy.ts b/backend/src/services/proxy.ts index f97ff8ca..c496c2b8 100644 --- a/backend/src/services/proxy.ts +++ b/backend/src/services/proxy.ts @@ -26,11 +26,14 @@ export async function patchOpenCodeConfig(config: Record): Prom export async function proxyRequest(request: Request) { const url = new URL(request.url) - const path = url.pathname + url.search - // Remove /api/opencode prefix before forwarding to OpenCode server - const cleanPath = path.replace(/^\/api\/opencode/, '') - const targetUrl = `${OPENCODE_SERVER_URL}${cleanPath}` + // Remove /api/opencode prefix from pathname before forwarding + const cleanPathname = url.pathname.replace(/^\/api\/opencode/, '') + const targetUrl = `${OPENCODE_SERVER_URL}${cleanPathname}${url.search}` + + if (url.pathname.includes('/permissions/')) { + logger.info(`Proxying permission request: ${url.pathname}${url.search} -> ${targetUrl}`) + } try { const headers: Record = {} @@ -59,7 +62,7 @@ export async function proxyRequest(request: Request) { headers: responseHeaders, }) } catch (error) { - logger.error(`Proxy request failed for ${path}:`, error) + logger.error(`Proxy request failed for ${url.pathname}${url.search}:`, error) return new Response(JSON.stringify({ error: 'Proxy request failed' }), { status: 502, headers: { 'Content-Type': 'application/json' }, diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 1dd958bb..2de40d46 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -11,6 +11,7 @@ import { TTSProvider } from './contexts/TTSContext' import { PermissionProvider } from '@/contexts/PermissionContext' import { PermissionRequestDialog } from '@/components/session/PermissionRequestDialog' import { usePermissionContext } from '@/contexts/PermissionContext' +import { GlobalPermissionNotification } from '@/components/permissions/GlobalPermissionNotification' const queryClient = new QueryClient({ defaultOptions: { @@ -25,23 +26,24 @@ function AppContent() { const { isOpen, close } = useSettingsDialog() useTheme() - return ( +return ( } /> } /> } /> - + + - -) + ) } function PermissionDialogWrapper() { @@ -50,7 +52,6 @@ function PermissionDialogWrapper() { pendingCount, isFromDifferentSession, respondToPermission, - dismissPermission, showDialog, setShowDialog, } = usePermissionContext() @@ -61,7 +62,6 @@ function PermissionDialogWrapper() { pendingCount={pendingCount} isFromDifferentSession={isFromDifferentSession} onRespond={respondToPermission} - onDismiss={dismissPermission} open={showDialog} onOpenChange={setShowDialog} /> diff --git a/frontend/src/components/layout/Header.tsx b/frontend/src/components/layout/Header.tsx index fe740158..13430f73 100644 --- a/frontend/src/components/layout/Header.tsx +++ b/frontend/src/components/layout/Header.tsx @@ -1,4 +1,4 @@ -import { Settings, Bell } from "lucide-react"; +import { Settings } from "lucide-react"; import { Button } from "@/components/ui/button"; import { BackButton } from "@/components/ui/back-button"; import { useSettingsDialog } from "@/hooks/useSettingsDialog"; @@ -9,11 +9,9 @@ interface HeaderProps { title: string; backTo?: string; action?: ReactNode; - pendingPermissions?: number; - onPendingPermissionsClick?: () => void; } -export function Header({ title, backTo, action, pendingPermissions, onPendingPermissionsClick }: HeaderProps) { +export function Header({ title, backTo, action }: HeaderProps) { const { open: openSettings } = useSettingsDialog(); const theme = useTheme(); @@ -39,22 +37,6 @@ export function Header({ title, backTo, action, pendingPermissions, onPendingPer
{action &&
{action}
} - {pendingPermissions !== undefined && pendingPermissions > 0 && ( - - )}
diff --git a/frontend/src/components/message/ToolCallPart.tsx b/frontend/src/components/message/ToolCallPart.tsx index 2b748f59..65e23e21 100644 --- a/frontend/src/components/message/ToolCallPart.tsx +++ b/frontend/src/components/message/ToolCallPart.tsx @@ -2,6 +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 { detectFileReferences } from '@/lib/fileReferences' import { ExternalLink, Loader2 } from 'lucide-react' import { CopyButton } from '@/components/ui/copy-button' @@ -71,6 +72,7 @@ function parseTodoOutput(output: string): Todo[] | null { export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCallPartProps) { const { preferences } = useSettings() const { userBashCommands } = useUserBash() + const { getPermissionForCallID } = usePermissionContext() const outputRef = useRef(null) const isUserBashCommand = part.tool === 'bash' && part.state.status === 'completed' && @@ -79,6 +81,9 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal const isTodoTool = part.tool === 'todowrite' || part.tool === 'todoread' const [expanded, setExpanded] = useState(isUserBashCommand || isTodoTool || (preferences?.expandToolCalls ?? false)) + const pendingPermission = getPermissionForCallID(part.callID, part.sessionID) + const isWaitingPermission = part.state.status === 'running' && !!pendingPermission + useEffect(() => { if (part.tool === 'bash' && expanded && outputRef.current) { outputRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest' }) @@ -92,7 +97,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal case 'error': return 'text-red-600 dark:text-red-400' case 'running': - return 'text-yellow-600 dark:text-yellow-400' + return isWaitingPermission ? 'text-orange-600 dark:text-orange-400' : 'text-yellow-600 dark:text-yellow-400' default: return 'text-muted-foreground' } @@ -254,7 +259,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal const getBorderStyle = () => { switch (part.state.status) { case 'running': - return 'border-yellow-500/50 shadow-sm shadow-yellow-500/10' + return isWaitingPermission ? 'border-orange-500/50 shadow-sm shadow-orange-500/20' : 'border-yellow-500/50 shadow-sm shadow-yellow-500/10' case 'pending': return 'border-blue-500/30' case 'error': @@ -311,7 +316,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal ) : null })()} - ({part.state.status}) + ({isWaitingPermission ? 'waiting' : part.state.status}) {expanded && ( @@ -341,18 +346,18 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
$ {typeof part.state.input?.command === 'string' ? part.state.input.command : ''}
-
+
- Running... + {isWaitingPermission ? 'Waiting for permission...' : 'Running...'}
) : (
Input:
-
+
- Running... + {isWaitingPermission ? 'Waiting for permission...' : 'Running...'}
)} diff --git a/frontend/src/components/permissions/GlobalPermissionNotification.tsx b/frontend/src/components/permissions/GlobalPermissionNotification.tsx new file mode 100644 index 00000000..0780935b --- /dev/null +++ b/frontend/src/components/permissions/GlobalPermissionNotification.tsx @@ -0,0 +1,32 @@ +import { usePermissionContext } from '@/contexts/PermissionContext' +import { useMobile } from '@/hooks/useMobile' +import { Bell } from 'lucide-react' + +export function GlobalPermissionNotification() { + const { pendingCount, setShowDialog } = usePermissionContext() + const isMobile = useMobile() + + if (pendingCount === 0) return null + + return ( + + ) +} + diff --git a/frontend/src/components/session/PermissionRequestDialog.tsx b/frontend/src/components/session/PermissionRequestDialog.tsx index 0c260dae..e097c841 100644 --- a/frontend/src/components/session/PermissionRequestDialog.tsx +++ b/frontend/src/components/session/PermissionRequestDialog.tsx @@ -10,6 +10,7 @@ import { import { Button } from '@/components/ui/button' import type { Permission, PermissionResponse } from '@/api/types' import { cn } from '@/lib/utils' +import { showToast } from '@/lib/toast' interface PermissionRequestDialogProps { permission: Permission | null @@ -17,7 +18,6 @@ interface PermissionRequestDialogProps { isFromDifferentSession?: boolean sessionTitle?: string onRespond: (permissionID: string, sessionID: string, response: PermissionResponse) => Promise - onDismiss: (permissionID: string, sessionID?: string) => void open?: boolean onOpenChange?: (open: boolean) => void } @@ -114,7 +114,6 @@ export function PermissionRequestDialog({ isFromDifferentSession, sessionTitle, onRespond, - onDismiss, open: parentOpen, onOpenChange, }: PermissionRequestDialogProps) { @@ -131,7 +130,7 @@ export function PermissionRequestDialog({ await onRespond(permission.id, permission.sessionID, response) } catch (error) { console.error('Failed to respond to permission:', error) - onDismiss(permission.id, permission.sessionID) + showToast.error('Failed to respond to permission. Please try again.') } finally { setIsLoading(false) setLoadingAction(null) diff --git a/frontend/src/contexts/PermissionContext.tsx b/frontend/src/contexts/PermissionContext.tsx index 860664c8..f06211df 100644 --- a/frontend/src/contexts/PermissionContext.tsx +++ b/frontend/src/contexts/PermissionContext.tsx @@ -27,6 +27,8 @@ interface PermissionContextValue { showDialog: boolean setShowDialog: (show: boolean) => void currentSessionId: string | null + getPermissionForCallID: (callID: string, sessionID: string) => Permission | null + hasPermissionsForSession: (sessionID: string) => boolean } const PermissionContext = createContext(null) @@ -44,30 +46,49 @@ function useActiveRepos(queryClient: ReturnType): ActiveR timeoutRef.current = setTimeout(() => { const cache = queryClient.getQueryCache() const queries = cache.getAll() - const repoMap = new Map>() + const repoMap = new Map }>() queries.forEach((query) => { const key = query.queryKey - if (key[0] === 'opencode' && key[1] === 'sessions') { + + 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 - if (!repoMap.has(url)) { - repoMap.set(url, new Set()) + 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(url)!.add(session.id) + 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(([url]) => { + .filter(([repoKey]) => { + const url = repoKey.split('|')[0] try { new URL(url) return true @@ -75,8 +96,9 @@ function useActiveRepos(queryClient: ReturnType): ActiveR return false } }) - .map(([url, sessionIds]) => ({ - url, + .map(([repoKey, { directory, sessionIds }]) => ({ + url: repoKey.split('|')[0], + directory, sessions: Array.from(sessionIds).map((id) => ({ id })), })) @@ -112,6 +134,8 @@ export function PermissionProvider({ children }: { children: React.ReactNode }) pendingCount, isFromDifferentSession, dismissPermission: dismiss, + getPermissionForCallID, + hasPermissionsForSession, } = usePermissionRequests() useEffect(() => { @@ -130,34 +154,69 @@ export function PermissionProvider({ children }: { children: React.ReactNode }) }, }) } - prevPendingCountRef.current = pendingCount +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)) { - let client = clientsRef.current.get(repo.url) + const clientKey = `${repo.url}|${repo.directory ?? ''}` + let client = clientsRef.current.get(clientKey) if (!client) { client = new OpenCodeClient(repo.url, repo.directory) - clientsRef.current.set(repo.url, client) + clientsRef.current.set(clientKey, client) } return client } } + + if (activeRepos.length === 0) { + 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) + } + console.log('[PermissionContext] Created client from query cache for fallback') + return client + } + } + } + } + return null -}, [activeRepos]) + }, [activeRepos, queryClient]) useEffect(() => { const currentRefs = eventSourceRefs.current - const newURLs = new Set(activeRepos.map((r) => r.url)) - const existingURLs = new Set(currentRefs.keys()) + const currentClients = clientsRef.current + const newKeys = new Set(activeRepos.map((r) => `${r.url}|${r.directory ?? ''}`)) + const existingKeys = new Set(currentRefs.keys()) - existingURLs.forEach((url) => { - if (!newURLs.has(url)) { - const es = currentRefs.get(url) + existingKeys.forEach((key) => { + if (!newKeys.has(key)) { + const es = currentRefs.get(key) if (es) { es.close() - currentRefs.delete(url) + currentRefs.delete(key) + } + if (currentClients.has(key)) { + currentClients.delete(key) } } }) @@ -173,7 +232,8 @@ export function PermissionProvider({ children }: { children: React.ReactNode }) activeRepos.forEach((repo) => { if (!repo.url) return - const existingES = currentRefs.get(repo.url) + const repoKey = `${repo.url}|${repo.directory ?? ''}` + const existingES = currentRefs.get(repoKey) if (existingES) return let url: URL @@ -189,9 +249,13 @@ export function PermissionProvider({ children }: { children: React.ReactNode }) } else { url.pathname += '/stream' } + + if (repo.directory) { + url.searchParams.set('directory', repo.directory) + } const es = new EventSource(url.toString()) - currentRefs.set(repo.url, es) + currentRefs.set(repoKey, es) es.addEventListener('permission.updated', (e) => { try { @@ -222,7 +286,7 @@ export function PermissionProvider({ children }: { children: React.ReactNode }) es.onerror = (err) => { console.error(`SSE connection error for ${repo.url}:`, err) setTimeout(() => { - currentRefs.delete(repo.url) + currentRefs.delete(repoKey) }, 1000) } }) @@ -255,6 +319,8 @@ export function PermissionProvider({ children }: { children: React.ReactNode }) showDialog, setShowDialog, currentSessionId, + getPermissionForCallID, + hasPermissionsForSession, }), [ currentPermission, @@ -264,6 +330,8 @@ export function PermissionProvider({ children }: { children: React.ReactNode }) dismiss, showDialog, currentSessionId, + getPermissionForCallID, + hasPermissionsForSession, ], ) diff --git a/frontend/src/hooks/useOpenCode.ts b/frontend/src/hooks/useOpenCode.ts index cbcf8378..01b31030 100644 --- a/frontend/src/hooks/useOpenCode.ts +++ b/frontend/src/hooks/useOpenCode.ts @@ -54,7 +54,7 @@ export const useMessages = (opcodeUrl: string | null | undefined, sessionID: str queryKey: ["opencode", "messages", opcodeUrl, sessionID, directory], queryFn: () => client!.listMessages(sessionID!), enabled: !!client && !!sessionID, - refetchOnMount: false, + refetchOnMount: 'always', refetchOnWindowFocus: true, refetchOnReconnect: true, staleTime: 30000, diff --git a/frontend/src/hooks/usePermissionRequests.ts b/frontend/src/hooks/usePermissionRequests.ts index 2a43c901..786e3811 100644 --- a/frontend/src/hooks/usePermissionRequests.ts +++ b/frontend/src/hooks/usePermissionRequests.ts @@ -116,11 +116,23 @@ export function usePermissionRequests(currentSessionID?: string) { setPermissionsBySession({}) }, []) + const getPermissionForCallID = useCallback((callID: string, sessionID: string): Permission | null => { + const sessionPermissions = permissionsBySession[sessionID] ?? [] + return sessionPermissions.find(p => p.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 + clearAllPermissions, + getPermissionForCallID, + hasPermissionsForSession } } diff --git a/frontend/src/pages/Repos.tsx b/frontend/src/pages/Repos.tsx index 96696654..f67440e0 100644 --- a/frontend/src/pages/Repos.tsx +++ b/frontend/src/pages/Repos.tsx @@ -1,6 +1,5 @@ import { useState } from "react"; import { RepoList } from "@/components/repo/RepoList"; -import { usePermissionContext } from "@/contexts/PermissionContext"; import { AddRepoDialog } from "@/components/repo/AddRepoDialog"; import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet"; import { Header } from "@/components/layout/Header"; @@ -10,7 +9,6 @@ import { Plus, FolderOpen } from "lucide-react"; export function Repos() { const [addRepoOpen, setAddRepoOpen] = useState(false); const [fileBrowserOpen, setFileBrowserOpen] = useState(false); - const { pendingCount, setShowDialog } = usePermissionContext(); const handleCloseFileBrowser = () => { setFileBrowserOpen(false); @@ -20,8 +18,6 @@ export function Repos() {
setShowDialog(true)} action={