mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
feat(frontend): add permission synchronization with React Query polling
Implement syncForSession for permissions alongside questions, using React Query for automatic polling with 30-second intervals when sessions are active. Adds reconcilePermissionsForDirectory to handle stale session cleanup and ensures permissions are removed after response.
This commit is contained in:
1 parent
62c8a41e01
commit
4f43bf9876
3 files changed
+135
-18
No files matched your search
@@ -4,8 +4,8 @@ import userEvent from '@testing-library/user-event'
|
||||
import type { ReactNode } from 'react'
|
||||
import { MemoryRouter, useLocation } from 'react-router-dom'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { QuestionRequest } from '@/api/types'
|
||||
import { EventProvider, useQuestions } from './EventContext'
|
||||
import type { PermissionRequest, QuestionRequest } from '@/api/types'
|
||||
import { EventProvider, usePermissions, useQuestions } from './EventContext'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listRepos: vi.fn(),
|
||||
@@ -80,16 +80,35 @@ const secondPendingQuestion: QuestionRequest = {
|
||||
],
|
||||
}
|
||||
|
||||
const pendingPermission: PermissionRequest = {
|
||||
id: 'permission-1',
|
||||
sessionID: 'session-1',
|
||||
permission: 'bash',
|
||||
patterns: ['echo hello'],
|
||||
metadata: {},
|
||||
always: [],
|
||||
tool: {
|
||||
messageID: 'message-1',
|
||||
callID: 'call-1',
|
||||
},
|
||||
}
|
||||
|
||||
function Harness() {
|
||||
const { current, pendingCount, syncForSession, navigateToCurrent, reject, reply } = useQuestions()
|
||||
const permissions = usePermissions()
|
||||
const permissionForCall = permissions.getForCallID('call-1', 'session-1')
|
||||
const location = useLocation()
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div data-testid="count">{pendingCount}</div>
|
||||
<div data-testid="current">{current?.id ?? 'none'}</div>
|
||||
<div data-testid="permission-count">{permissions.pendingCount}</div>
|
||||
<div data-testid="permission-current">{permissions.current?.id ?? 'none'}</div>
|
||||
<div data-testid="permission-call">{permissionForCall?.id ?? 'none'}</div>
|
||||
<div data-testid="path">{location.pathname}</div>
|
||||
<button onClick={() => syncForSession('/repo', 'session-1')}>Sync</button>
|
||||
<button onClick={() => permissions.syncForSession('/repo', 'session-1')}>Sync Permissions</button>
|
||||
<button onClick={navigateToCurrent}>Navigate</button>
|
||||
<button onClick={() => current && reject(current.id)}>Dismiss</button>
|
||||
<button onClick={() => current && reply(current.id, [['Yes']])}>Reply</button>
|
||||
@@ -139,6 +158,41 @@ describe('EventProvider questions', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('syncs missed pending permissions for a session', async () => {
|
||||
mocks.listPendingPermissions.mockResolvedValue([pendingPermission])
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Sync Permissions' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('permission-count')).toHaveTextContent('1')
|
||||
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-1')
|
||||
expect(screen.getByTestId('permission-call')).toHaveTextContent('permission-1')
|
||||
})
|
||||
})
|
||||
|
||||
it('clears stale pending permissions for a session', async () => {
|
||||
mocks.listPendingPermissions
|
||||
.mockResolvedValueOnce([pendingPermission])
|
||||
.mockResolvedValueOnce([])
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Sync Permissions' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('permission-count')).toHaveTextContent('1')
|
||||
})
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Sync Permissions' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('permission-count')).toHaveTextContent('0')
|
||||
expect(screen.getByTestId('permission-current')).toHaveTextContent('none')
|
||||
})
|
||||
})
|
||||
|
||||
it('clears stale pending questions for a session', async () => {
|
||||
mocks.listPendingQuestions
|
||||
.mockResolvedValueOnce([pendingQuestion])
|
||||
|
||||
@@ -13,6 +13,16 @@ import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessi
|
||||
type PermissionsBySession = Record<string, PermissionRequest[]>
|
||||
type QuestionsBySession = Record<string, QuestionRequest[]>
|
||||
|
||||
function groupPermissionsBySession(permissions: PermissionRequest[]): PermissionsBySession {
|
||||
return permissions.reduce<PermissionsBySession>((grouped, permission) => {
|
||||
const existing = grouped[permission.sessionID] ?? []
|
||||
return {
|
||||
...grouped,
|
||||
[permission.sessionID]: [...existing, permission],
|
||||
}
|
||||
}, {})
|
||||
}
|
||||
|
||||
function groupQuestionsBySession(questions: QuestionRequest[]): QuestionsBySession {
|
||||
return questions.reduce<QuestionsBySession>((grouped, question) => {
|
||||
const existing = grouped[question.sessionID] ?? []
|
||||
@@ -27,6 +37,10 @@ function sortQuestionsById(questions: QuestionRequest[]): QuestionRequest[] {
|
||||
return [...questions].sort((a, b) => a.id.localeCompare(b.id))
|
||||
}
|
||||
|
||||
function sortPermissionsById(permissions: PermissionRequest[]): PermissionRequest[] {
|
||||
return [...permissions].sort((a, b) => a.id.localeCompare(b.id))
|
||||
}
|
||||
|
||||
function optimisticallyErrorToolPart(
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
sessionID: string,
|
||||
@@ -111,6 +125,7 @@ interface EventContextValue {
|
||||
showDialog: boolean
|
||||
setShowDialog: (show: boolean) => void
|
||||
navigateToCurrent: () => void
|
||||
syncForSession: (directory: string, sessionID: string) => Promise<void>
|
||||
}
|
||||
questions: {
|
||||
current: QuestionRequest | null
|
||||
@@ -259,6 +274,31 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
removeFromSessionKeyedState(setQuestionsBySession, requestID, sessionID)
|
||||
}, [])
|
||||
|
||||
const reconcilePermissionsForDirectory = useCallback((directory: string, permissions: PermissionRequest[]) => {
|
||||
const grouped = groupPermissionsBySession(permissions)
|
||||
|
||||
permissions.forEach(permission => {
|
||||
rememberSessionDirectory(permission.sessionID, directory)
|
||||
})
|
||||
|
||||
setPermissionsBySession(prev => {
|
||||
const next = { ...prev }
|
||||
|
||||
for (const sessionID of Object.keys(prev)) {
|
||||
if (grouped[sessionID]) continue
|
||||
if (sessionDirectoriesRef.current.get(sessionID) === directory) {
|
||||
delete next[sessionID]
|
||||
}
|
||||
}
|
||||
|
||||
for (const [sessionID, sessionPermissions] of Object.entries(grouped)) {
|
||||
next[sessionID] = sortPermissionsById(sessionPermissions)
|
||||
}
|
||||
|
||||
return next
|
||||
})
|
||||
}, [rememberSessionDirectory])
|
||||
|
||||
const reconcileQuestionsForDirectory = useCallback((directory: string, questions: QuestionRequest[]) => {
|
||||
const grouped = groupQuestionsBySession(questions)
|
||||
|
||||
@@ -315,7 +355,8 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
|
||||
await client.respondToPermission(sessionID, permissionID, response)
|
||||
}, [getClient, permissionsBySession, queryClient])
|
||||
removePermission(permissionID, sessionID)
|
||||
}, [getClient, permissionsBySession, queryClient, removePermission])
|
||||
|
||||
const replyToQuestion = useCallback(async (requestID: string, answers: string[][]) => {
|
||||
const connected = await ensureSSEConnected()
|
||||
@@ -354,7 +395,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
const perms = permissionsBySession[sessionID] ?? []
|
||||
return perms.find(p => {
|
||||
const metadata = p.metadata as { tool?: { id?: string } } | undefined
|
||||
return metadata?.tool?.id === callID
|
||||
return p.tool?.callID === callID || metadata?.tool?.id === callID
|
||||
}) ?? null
|
||||
}, [permissionsBySession])
|
||||
|
||||
@@ -402,21 +443,23 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
try {
|
||||
const client = new OpenCodeClient(OPENCODE_API_ENDPOINT, directory)
|
||||
const pendingPermissions = await client.listPendingPermissions()
|
||||
if (pendingPermissions && pendingPermissions.length > 0) {
|
||||
pendingPermissions.forEach(permission => {
|
||||
rememberSessionDirectory(permission.sessionID, directory)
|
||||
addPermission(permission)
|
||||
})
|
||||
}
|
||||
reconcilePermissionsForDirectory(directory, pendingPermissions ?? [])
|
||||
const pendingQuestions = await client.listPendingQuestions()
|
||||
reconcileQuestionsForDirectory(directory, pendingQuestions ?? [])
|
||||
} catch (error) {
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn(`Failed to fetch pending questions for ${directory}:`, error)
|
||||
console.warn(`Failed to fetch pending actions for ${directory}:`, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [repos, addPermission, rememberSessionDirectory, reconcileQuestionsForDirectory])
|
||||
}, [repos, reconcilePermissionsForDirectory, reconcileQuestionsForDirectory])
|
||||
|
||||
const syncPermissionsForSession = useCallback(async (directory: string, sessionID: string) => {
|
||||
const client = new OpenCodeClient(OPENCODE_API_ENDPOINT, directory)
|
||||
const pendingPermissions = await client.listPendingPermissions()
|
||||
rememberSessionDirectory(sessionID, directory)
|
||||
reconcilePermissionsForDirectory(directory, pendingPermissions ?? [])
|
||||
}, [rememberSessionDirectory, reconcilePermissionsForDirectory])
|
||||
|
||||
const syncQuestionsForSession = useCallback(async (directory: string, sessionID: string) => {
|
||||
const client = new OpenCodeClient(OPENCODE_API_ENDPOINT, directory)
|
||||
@@ -546,6 +589,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
showDialog: showPermissionDialog,
|
||||
setShowDialog: setShowPermissionDialog,
|
||||
navigateToCurrent: navigateToCurrentPermission,
|
||||
syncForSession: syncPermissionsForSession,
|
||||
},
|
||||
questions: {
|
||||
current: currentQuestion,
|
||||
@@ -571,6 +615,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
hasPermissionsForSession,
|
||||
showPermissionDialog,
|
||||
navigateToCurrentPermission,
|
||||
syncPermissionsForSession,
|
||||
currentQuestion,
|
||||
allQuestions.length,
|
||||
replyToQuestion,
|
||||
|
||||
@@ -40,7 +40,7 @@ import { RepoLspDialog } from "@/components/repo/RepoLspDialog";
|
||||
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog";
|
||||
import { createOpenCodeClient } from "@/api/opencode";
|
||||
import { useSessionStatus, useSessionStatusForSession } from "@/stores/sessionStatusStore";
|
||||
import { useQuestions } from "@/contexts/EventContext";
|
||||
import { usePermissions, useQuestions } from "@/contexts/EventContext";
|
||||
import type { QuestionRequest } from "@/api/types";
|
||||
import { QuestionPrompt } from "@/components/session/QuestionPrompt";
|
||||
import { MinimizedQuestionIndicator } from "@/components/session/MinimizedQuestionIndicator";
|
||||
@@ -57,6 +57,8 @@ const compareMessageIds = (id1: string, id2: string): number => {
|
||||
return id1.localeCompare(id2)
|
||||
}
|
||||
|
||||
const PENDING_ACTION_SYNC_INTERVAL_MS = 30000
|
||||
|
||||
export function SessionDetail() {
|
||||
const { id, sessionId } = useParams<{ id: string; sessionId: string }>();
|
||||
const navigate = useNavigate();
|
||||
@@ -156,6 +158,7 @@ export function SessionDetail() {
|
||||
const isEditingMessage = useUIState((state) => state.isEditingMessage);
|
||||
const { isEnabled: ttsEnabled } = useTTS();
|
||||
const setSessionStatus = useSessionStatus((state) => state.setStatus);
|
||||
const { syncForSession: syncPermissionsForSession } = usePermissions();
|
||||
const { current: currentQuestion, reply: replyToQuestion, reject: rejectQuestion, syncForSession: syncQuestionsForSession } = useQuestions();
|
||||
|
||||
const sessionStatus = useSessionStatusForSession(sessionId);
|
||||
@@ -191,12 +194,27 @@ export function SessionDetail() {
|
||||
}
|
||||
}, [sessionId, minimizedQuestion])
|
||||
|
||||
useEffect(() => {
|
||||
const syncPendingActionsForSession = useCallback(async () => {
|
||||
if (!repoDirectory || !sessionId) return
|
||||
syncQuestionsForSession(repoDirectory, sessionId).catch(() => {
|
||||
showToast.error('Failed to load pending questions')
|
||||
})
|
||||
}, [repoDirectory, sessionId, syncQuestionsForSession])
|
||||
await Promise.all([
|
||||
syncPermissionsForSession(repoDirectory, sessionId),
|
||||
syncQuestionsForSession(repoDirectory, sessionId),
|
||||
])
|
||||
}, [repoDirectory, sessionId, syncPermissionsForSession, syncQuestionsForSession])
|
||||
|
||||
useQuery({
|
||||
queryKey: ['opencode', 'pending-actions', opcodeUrl, sessionId, repoDirectory],
|
||||
queryFn: async () => {
|
||||
await syncPendingActionsForSession()
|
||||
return null
|
||||
},
|
||||
enabled: !!repoDirectory && !!sessionId,
|
||||
refetchOnMount: 'always',
|
||||
refetchOnReconnect: true,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchInterval: isSessionActive || hasIncompleteMessages ? PENDING_ACTION_SYNC_INTERVAL_MS : false,
|
||||
retry: false,
|
||||
})
|
||||
|
||||
const handleNewSession = useCallback(async () => {
|
||||
try {
|
||||
|
||||
Reference in new issue
Block a user