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

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