Fix/permission request directory (#31)

* Fix permission response by including directory parameter

Extract directory from query key in useActiveRepos hook and pass it
to OpenCodeClient when responding to permissions. Use composite keys
for client and SSE connection tracking to support multiple repos with
the same URL but different directories.

* Keep permission dialog open on response failure and show error toast

* Fix permission request proxying to preserve query parameters

The backend proxy was incorrectly handling URL query parameters when stripping the /api/opencode prefix. This caused the directory parameter to not be passed correctly to the OpenCode server, breaking the permission request/response flow.

Changes:
- Separate pathname and search parameters explicitly
- Only strip /api/opencode from pathname, preserve search params
- Add logging for permission requests to aid debugging
- Update error logging to use correct variables

This fix ensures that permission responses are properly forwarded to the OpenCode server with all necessary query parameters, allowing the session to proceed correctly when users grant permissions.

* Fix permission client lookup when only individual sessions are loaded

The PermissionContext failed to find a client when responding to permissions because it only scanned the sessions list query, but SessionDetail and other pages only load individual sessions via useSession.

Changes:
- Update useActiveRepos to also scan individual session queries
- Match query keys like ['opencode', 'session', url, sessionId, directory]
- Extract session ID from individual session query data
- Build active repos map from both sessions list and individual session queries

This ensures permission dialogs can find the appropriate client to send responses, even when viewing a single session without loading the full sessions list.

* Fix permission client lookup with fallback to query cache

The activeRepos state was often empty when permission dialogs appeared due to timing issues with the React Query cache subscription. This caused No client found for session errors.

Changes:
- Add fallback scan of query cache directly in getClient when activeRepos is empty
- Remove excessive debug logging that was spamming console
- Add minimal log only when fallback is actually used
- Fix query key length checks to be more robust

This ensures permission responses work correctly even if the useActiveRepos hook hasn't yet populated the state, by falling back to scanning the query cache directly to find the session and creating the appropriate OpenCodeClient.

* Add directory-based permission requests with global notification and message auto-refresh

---------

Co-authored-by: OpenCode Agent <agent@opencode.ai>
Co-authored-by: Chris Scott <chris@cstech.dev>
This commit is contained in:
authored and GitHub committed 2025-12-27 09:21:45 -05:00
1 parent 87f79c63af
commit b28f069576
14 files changed
+208 -82

No files matched your search

Binary file not shown.

After

Width:  |  Height:  |  Size: 414 KiB

+8 -5
View File
@@ -26,11 +26,14 @@ export async function patchOpenCodeConfig(config: Record<string, unknown>): 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<string, string> = {}
@@ -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' },
+6 -6
View File
@@ -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 (
<BrowserRouter>
<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
<Toaster
position="bottom-right"
expand={false}
richColors
closeButton
/>
</BrowserRouter>
)
)
}
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}
/>
+2 -20
View File
@@ -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
</div>
<div className="flex items-center gap-2">
{action && <div>{action}</div>}
{pendingPermissions !== undefined && pendingPermissions > 0 && (
<Button
variant="ghost"
size="icon"
onClick={onPendingPermissionsClick}
className="text-muted-foreground hover:text-foreground hover:bg-accent transition-all duration-200 relative"
title={`${pendingPermissions} pending permission${pendingPermissions > 1 ? 's' : ''}`}
>
<Bell className="w-10 h-10" />
{pendingPermissions > 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">
{pendingPermissions > 9 ? '9+' : pendingPermissions}
</span>
)}
</Button>
)}
<Button
variant="ghost"
size="icon"
@@ -9,6 +9,7 @@ import { useModelSelection } from '@/hooks/useModelSelection'
import { useUserBash } from '@/stores/userBashStore'
import { useMobile } from '@/hooks/useMobile'
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
import { usePermissionContext } from '@/contexts/PermissionContext'
import { ChevronDown, Square } from 'lucide-react'
import { CommandSuggestions } from '@/components/command/CommandSuggestions'
@@ -464,12 +465,13 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
}
}
const isMessageStreaming = (msg: MessageWithParts): boolean => {
const isMessageIncomplete = (msg: MessageWithParts): boolean => {
if (msg.info.role !== 'assistant') return false
return !('completed' in msg.info.time && msg.info.time.completed)
}
const hasIncompleteMessages = messages?.some(msg => isMessageStreaming(msg)) || false
const lastAssistantMessage = messages?.filter(msg => msg.info.role === 'assistant').at(-1)
const hasIncompleteMessages = lastAssistantMessage ? isMessageIncomplete(lastAssistantMessage) : false
const currentMode = preferences?.mode || 'build'
const modeColor = currentMode === 'plan' ? 'text-yellow-600 dark:text-yellow-500' : 'text-green-600 dark:text-green-500'
@@ -480,10 +482,12 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
const currentModel = modelString || ''
const displayModelName = model?.modelID || currentModel
const isMobile = useMobile()
const { setShowDialog, hasPermissionsForSession } = usePermissionContext()
const hasPendingPermissionForSession = hasPermissionsForSession(sessionID)
const sessionStatus = useSessionStatusForSession(sessionID)
const isSessionActive = sessionStatus.type === 'busy' || sessionStatus.type === 'retry'
const hasActiveStream = hasIncompleteMessages && isSessionActive
const showStopButton = isSessionActive
const showStopButton = isSessionActive && hasIncompleteMessages
const hideSecondaryButtons = isMobile && hasActiveStream
@@ -499,7 +503,7 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
return (
<div className="relative backdrop-blur-md bg-background opacity-95 border border-border dark:border-white/30 rounded-xl p-2 md:p-3 mb-4 md:mb-1 w-full">
<div className={`relative backdrop-blur-md bg-background opacity-95 border border-border dark:border-white/30 rounded-xl p-2 md:p-3 mb-4 md:mb-1 w-full transition-all ${hasPendingPermissionForSession ? 'border-orange-500/50 ring-1 ring-orange-500/30' : ''}`}>
{showStopButton && (
<button
onClick={handleStop}
@@ -578,12 +582,16 @@ return (
)}
<button
data-submit-prompt
onClick={handleSubmit}
disabled={!prompt.trim() || disabled}
className="px-4 md:px-5 py-1.5 md:py-2 rounded-lg text-sm font-medium transition-colors bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground disabled:cursor-not-allowed text-primary-foreground dark:border dark:border-white/30 flex-shrink-0 min-w-[52px]"
title={hasActiveStream ? 'Queue message' : 'Send'}
onClick={hasPendingPermissionForSession ? () => setShowDialog(true) : handleSubmit}
disabled={hasPendingPermissionForSession ? false : (!prompt.trim() || disabled)}
className={`px-4 md:px-5 py-1.5 md:py-2 rounded-lg text-sm font-medium transition-colors dark:border flex-shrink-0 min-w-[52px] ${
hasPendingPermissionForSession
? 'bg-orange-500 hover:bg-orange-600 border-orange-400 text-primary-foreground ring-orange-500/20'
: 'bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground disabled:cursor-not-allowed text-primary-foreground border-white/30'
}`}
title={hasPendingPermissionForSession ? 'View pending permission' : (hasActiveStream ? 'Queue message' : 'Send')}
>
<span className="whitespace-nowrap">{hasActiveStream ? 'Queue' : 'Send'}</span>
<span className="whitespace-nowrap">{hasPendingPermissionForSession ? 'View' : (hasActiveStream ? 'Queue' : 'Send')}</span>
</button>
</div>
</div>
@@ -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<HTMLDivElement>(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
</span>
) : null
})()}
<span className="text-muted-foreground text-xs ml-auto">({part.state.status})</span>
<span className="text-muted-foreground text-xs ml-auto">({isWaitingPermission ? 'waiting' : part.state.status})</span>
</button>
{expanded && (
@@ -341,18 +346,18 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
<div className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words">
<span className="text-green-600 dark:text-green-400">$</span> {typeof part.state.input?.command === 'string' ? part.state.input.command : ''}
</div>
<div className="flex items-center gap-2 mt-2 text-xs text-yellow-600 dark:text-yellow-400">
<div className={`flex items-center gap-2 mt-2 text-xs ${isWaitingPermission ? 'text-orange-600 dark:text-orange-400' : 'text-yellow-600 dark:text-yellow-400'}`}>
<Loader2 className="w-3 h-3 animate-spin" />
<span>Running...</span>
<span>{isWaitingPermission ? 'Waiting for permission...' : 'Running...'}</span>
</div>
</div>
) : (
<div className="text-sm">
<div className="text-muted-foreground mb-1">Input:</div>
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
<div className="flex items-center gap-2 mt-2 text-xs text-yellow-600 dark:text-yellow-400">
<div className={`flex items-center gap-2 mt-2 text-xs ${isWaitingPermission ? 'text-orange-600 dark:text-orange-400' : 'text-yellow-600 dark:text-yellow-400'}`}>
<Loader2 className="w-3 h-3 animate-spin" />
<span>Running...</span>
<span>{isWaitingPermission ? 'Waiting for permission...' : 'Running...'}</span>
</div>
</div>
)}
@@ -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 (
<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>
)
}
@@ -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<void>
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)
+89 -21
View File
@@ -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<PermissionContextValue | null>(null)
@@ -44,30 +46,49 @@ function useActiveRepos(queryClient: ReturnType<typeof useQueryClient>): ActiveR
timeoutRef.current = setTimeout(() => {
const cache = queryClient.getQueryCache()
const queries = cache.getAll()
const repoMap = new Map<string, Set<string>>()
const repoMap = new Map<string, { directory?: string, sessionIds: Set<string> }>()
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<typeof useQueryClient>): 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,
],
)
+1 -1
View File
@@ -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,
+13 -1
View File
@@ -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
}
}
-4
View File
@@ -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() {
<div className="min-h-screen bg-gradient-to-br from-background via-background to-background">
<Header
title="OpenCode"
pendingPermissions={pendingCount}
onPendingPermissionsClick={() => setShowDialog(true)}
action={
<div className="flex items-center gap-2">
<Button
+25 -1
View File
@@ -11,10 +11,11 @@ import { SessionList } from "@/components/session/SessionList";
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { useSession, useAbortSession, useUpdateSession, useMessages } from "@/hooks/useOpenCode";
import { useSession, useAbortSession, useUpdateSession, useMessages, useOpenCodeClient } from "@/hooks/useOpenCode";
import { OPENCODE_API_ENDPOINT, API_BASE_URL } from "@/config";
import { useSSE } from "@/hooks/useSSE";
import { useUIState } from "@/stores/uiStateStore";
import { useSessionStatus } from "@/stores/sessionStatusStore";
import { useSettings } from "@/hooks/useSettings";
import { useModelSelection } from "@/hooks/useModelSelection";
import { useKeyboardShortcuts } from "@/hooks/useKeyboardShortcuts";
@@ -103,6 +104,29 @@ export function SessionDetail() {
const { modelString } = useModelSelection(opcodeUrl, repoDirectory);
const isEditingMessage = useUIState((state) => state.isEditingMessage);
const { isPlaying, stop } = useTTS();
const clearSessionStatus = useSessionStatus((state) => state.clearStatus);
const setSessionStatus = useSessionStatus((state) => state.setStatus);
const client = useOpenCodeClient(opcodeUrl, repoDirectory);
useEffect(() => {
if (client && sessionId) {
client.getSessionStatuses().then((statuses) => {
if (statuses && sessionId in statuses) {
setSessionStatus(sessionId, statuses[sessionId]);
} else {
setSessionStatus(sessionId, { type: 'idle' });
}
}).catch(() => {
setSessionStatus(sessionId, { type: 'idle' });
});
}
return () => {
if (sessionId) {
clearSessionStatus(sessionId);
}
};
}, [client, sessionId, setSessionStatus, clearSessionStatus]);
useKeyboardShortcuts({
openModelDialog: () => setModelDialogOpen(true),
+1 -4
View File
@@ -3,14 +3,11 @@ import { Header } from '@/components/layout/Header'
import { GeneralSettings } from '@/components/settings/GeneralSettings'
import { KeyboardShortcuts } from '@/components/settings/KeyboardShortcuts'
import { OpenCodeConfigManager } from '@/components/settings/OpenCodeConfigManager'
import { usePermissionContext } from '@/contexts/PermissionContext'
export function Settings() {
const { pendingCount, setShowDialog } = usePermissionContext()
return (
<div className="min-h-screen bg-gradient-to-br from-[#0a0a0a] via-[#0d0d0d] to-[#0a0a0a]">
<Header title="Settings" backTo="/" pendingPermissions={pendingCount} onPendingPermissionsClick={() => setShowDialog(true)} />
<Header title="Settings" backTo="/" />
<div className="max-w-4xl mx-auto p-6">
<Tabs defaultValue="general" className="w-full">