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

+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,
],
)