fix(permissions): prioritize the viewed session and add request context to the permission dialog

This commit is contained in:
Chris Scott committed 2026-10-14 01:04:40 -04:00
1 parent 59ffe6c586
commit e6b1fb8138
7 files changed
+862 -79

No files matched your search

+463 -2
View File
@@ -97,6 +97,57 @@ const sourcedPermission: PermissionRequest = {
source: { type: 'tool', messageID: 'msg_1', id: 'call_1' },
}
const viewedSessionPermission: PermissionRequest = {
id: 'permission-view',
sessionID: 'session-view',
action: 'shell',
resources: ['echo view'],
metadata: {},
}
const otherSessionPermission: PermissionRequest = {
id: 'permission-other',
sessionID: 'session-other',
action: 'shell',
resources: ['echo other'],
metadata: {},
}
const childSessionPermission: PermissionRequest = {
id: 'permission-child',
sessionID: 'child-1',
action: 'shell',
resources: ['echo child'],
metadata: {},
}
const viewedSessionForm: FormInfo = {
id: 'form-view',
sessionID: 'session-view',
title: 'Continue view',
fields: [
{ key: 'q0', title: 'Confirm', type: 'string', options: [{ value: 'Yes', label: 'Yes' }] },
],
}
const otherSessionForm: FormInfo = {
id: 'form-other',
sessionID: 'session-other',
title: 'Continue other',
fields: [
{ key: 'q0', title: 'Confirm', type: 'string', options: [{ value: 'Yes', label: 'Yes' }] },
],
}
const childSessionForm: FormInfo = {
id: 'form-child',
sessionID: 'child-1',
title: 'Continue child',
fields: [
{ key: 'q0', title: 'Confirm', type: 'string', options: [{ value: 'Yes', label: 'Yes' }] },
],
}
function Harness() {
const { current, pendingCount, syncForSession, navigateToCurrent, cancel, reply, getForSession } = useForms()
const permissions = usePermissions()
@@ -116,6 +167,8 @@ function Harness() {
<div data-testid="for-session-unknown">{getForSession('session-unknown')?.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-directory">{permissions.currentDirectory ?? 'none'}</div>
<div data-testid="permission-different">{String(permissions.currentIsFromDifferentSession)}</div>
<div data-testid="permission-tool-call">{permissions.getForToolCall('call_1', 'msg_1')?.id ?? 'none'}</div>
<div data-testid="permission-tool-call-other-message">
{permissions.getForToolCall('call_1', 'msg_other')?.id ?? 'none'}
@@ -124,9 +177,12 @@ function Harness() {
{permissions.getForToolCall('call_other', 'msg_1')?.id ?? 'none'}
</div>
<div data-testid="path">{location.pathname}</div>
<div data-testid="search">{location.search}</div>
<div data-testid="location-key">{location.key}</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={permissions.navigateToCurrent}>Navigate Permission</button>
<button onClick={() => current && recordRejection(cancel(current.id))}>Dismiss</button>
<button onClick={() => current && recordRejection(reply(current.id, { q0: 'Yes' }))}>Reply</button>
<button onClick={() => permissions.current && recordRejection(permissions.respond(permissions.current.id, permissions.current.sessionID, 'reject'))}>Reject Permission</button>
@@ -149,9 +205,9 @@ function createDeferred<T>() {
return { promise, resolve }
}
function createWrapper(queryClient = createTestQueryClient()) {
function createWrapper(queryClient = createTestQueryClient(), initialPath = '/') {
return ({ children }: { children: ReactNode }) => (
<MemoryRouter>
<MemoryRouter initialEntries={[initialPath]}>
<QueryClientProvider client={queryClient}>
<EventProvider>{children}</EventProvider>
</QueryClientProvider>
@@ -173,6 +229,7 @@ function CacheResolutionHarness({ sessionID }: { sessionID: string }) {
describe('EventProvider permissions and forms', () => {
beforeEach(() => {
vi.clearAllMocks()
window.history.pushState({}, '', '/')
mocks.listRepos.mockResolvedValue([])
mocks.listPendingPermissions.mockResolvedValue([])
mocks.listPendingForms.mockResolvedValue([])
@@ -570,6 +627,107 @@ describe('EventProvider permissions and forms', () => {
})
})
it('navigates an assistant-session permission to the assistant session path', async () => {
mocks.listRepos.mockResolvedValue([{ id: 0, fullPath: '/assistant' }])
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/assistant'))
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/assistant' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-1')
})
await userEvent.click(screen.getByRole('button', { name: 'Navigate Permission' }))
await waitFor(() => {
expect(screen.getByTestId('path')).toHaveTextContent('/repos/0/sessions/session-1')
expect(screen.getByTestId('search')).toHaveTextContent('?assistant=1')
})
})
it('navigates a normal-repo permission without the assistant query', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/repo'))
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-1')
})
await userEvent.click(screen.getByRole('button', { name: 'Navigate Permission' }))
await waitFor(() => {
expect(screen.getByTestId('path')).toHaveTextContent('/repos/123/sessions/session-1')
})
expect(screen.getByTestId('search').textContent).toBe('')
})
it('does not navigate when already on the target session path', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
window.history.pushState({}, '', '/repos/123/sessions/session-1')
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/session-1'),
})
await waitFor(() => expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/repo'))
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-1')
})
const keyBefore = screen.getByTestId('location-key').textContent
await userEvent.click(screen.getByRole('button', { name: 'Navigate Permission' }))
expect(screen.getByTestId('location-key')).toHaveTextContent(keyBefore ?? '')
expect(screen.getByTestId('path')).toHaveTextContent('/repos/123/sessions/session-1')
})
it('navigates an assistant-session form to the assistant session path', async () => {
mocks.listRepos.mockResolvedValue([{ id: 0, fullPath: '/repo' }])
mocks.listPendingForms.mockResolvedValue([pendingForm])
render(<Harness />, { wrapper: createWrapper() })
await userEvent.click(screen.getByRole('button', { name: 'Sync' }))
await waitFor(() => {
expect(screen.getByTestId('current')).toHaveTextContent('form-1')
})
await userEvent.click(screen.getByRole('button', { name: 'Navigate' }))
await waitFor(() => {
expect(screen.getByTestId('path')).toHaveTextContent('/repos/0/sessions/session-1')
expect(screen.getByTestId('search')).toHaveTextContent('?assistant=1')
})
})
it('clears a pending form after dismiss succeeds', async () => {
mocks.listPendingForms.mockResolvedValue([pendingForm])
@@ -1039,6 +1197,309 @@ describe('EventProvider permissions and forms', () => {
})
})
it('prioritizes the viewed session permission over an earlier unrelated one', async () => {
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/session-view'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'permission.asked', data: otherSessionPermission, directory: '/repo' })
onEvent({ type: 'permission.asked', data: viewedSessionPermission, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-count')).toHaveTextContent('2')
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-view')
})
expect(screen.getByTestId('permission-different')).toHaveTextContent('false')
})
it('prefers a descendant session permission when viewing its parent', async () => {
act(() => {
useSessionStatus.getState().setSessionParent('child-1', 'parent-1')
})
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/parent-1'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'permission.asked', data: otherSessionPermission, directory: '/repo' })
onEvent({ type: 'permission.asked', data: childSessionPermission, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-child')
})
expect(screen.getByTestId('permission-different')).toHaveTextContent('false')
})
it('falls back to the first pending permission when the viewed session has none', async () => {
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/session-view'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'permission.asked', data: otherSessionPermission, directory: '/repo' })
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-count')).toHaveTextContent('2')
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-other')
})
expect(screen.getByTestId('permission-different')).toHaveTextContent('true')
})
it('resolves the current permission directory from the query cache', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
const queryClient = createTestQueryClient()
queryClient.setQueryData(
['opencode', 'session', 'session-1', '/repo'],
{
id: 'session-1',
projectID: 'proj-1',
title: 'Fix permission dialog',
location: { directory: '/repo' },
time: { created: 1000, updated: 1000 },
},
)
render(<Harness />, { wrapper: createWrapper(queryClient) })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-1')
expect(screen.getByTestId('permission-directory')).toHaveTextContent('/repo')
})
})
it('keeps the shown permission when a viewed-session permission arrives, then advances once it is answered', async () => {
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/session-view'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'permission.asked', data: otherSessionPermission, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-other')
})
act(() => {
onEvent({ type: 'permission.asked', data: viewedSessionPermission, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-count')).toHaveTextContent('2')
})
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-other')
act(() => {
onEvent({
type: 'permission.replied',
data: { sessionID: 'session-other', requestID: 'permission-other', reply: 'reject' },
directory: '/repo',
})
})
await waitFor(() => {
expect(screen.getByTestId('permission-count')).toHaveTextContent('1')
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-view')
})
})
it('prioritizes the viewed session form over an earlier unrelated one', async () => {
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/session-view'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'form.created', data: { form: otherSessionForm }, directory: '/repo' })
onEvent({ type: 'form.created', data: { form: viewedSessionForm }, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('count')).toHaveTextContent('2')
expect(screen.getByTestId('current')).toHaveTextContent('form-view')
})
})
it('prefers a descendant session form when viewing its parent', async () => {
act(() => {
useSessionStatus.getState().setSessionParent('child-1', 'parent-1')
})
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/parent-1'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'form.created', data: { form: otherSessionForm }, directory: '/repo' })
onEvent({ type: 'form.created', data: { form: childSessionForm }, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('current')).toHaveTextContent('form-child')
})
})
it('falls back to the first pending form when the viewed session has none', async () => {
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/session-view'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'form.created', data: { form: otherSessionForm }, directory: '/repo' })
onEvent({ type: 'form.created', data: { form: pendingForm }, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('count')).toHaveTextContent('2')
expect(screen.getByTestId('current')).toHaveTextContent('form-other')
})
})
it('keeps the shown form when a viewed-session form arrives, then advances once it is answered', async () => {
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/session-view'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'form.created', data: { form: otherSessionForm }, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('current')).toHaveTextContent('form-other')
})
act(() => {
onEvent({ type: 'form.created', data: { form: viewedSessionForm }, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('count')).toHaveTextContent('2')
})
expect(screen.getByTestId('current')).toHaveTextContent('form-other')
act(() => {
onEvent({
type: 'form.cancelled',
data: { id: 'form-other', sessionID: 'session-other' },
directory: '/repo',
})
})
await waitFor(() => {
expect(screen.getByTestId('count')).toHaveTextContent('1')
expect(screen.getByTestId('current')).toHaveTextContent('form-view')
})
})
it('resolves ancestry when a permission arrives for an unknown session', async () => {
mocks.getSession.mockImplementation((sessionID: string) => {
if (sessionID === 'child-1') return Promise.resolve({ id: 'child-1', parentID: 'parent-1' })
if (sessionID === 'parent-1') return Promise.resolve({ id: 'parent-1' })
return Promise.reject(new Error('Session not found'))
})
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/parent-1'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'permission.asked', data: childSessionPermission, directory: '/repo' })
})
await waitFor(() => {
expect(mocks.getSession).toHaveBeenCalledWith('child-1')
expect(useSessionStatus.getState().parents.get('child-1')).toBe('parent-1')
})
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-child')
expect(screen.getByTestId('permission-different')).toHaveTextContent('false')
})
it('resolves ancestry when a form arrives for an unknown session', async () => {
mocks.getSession.mockImplementation((sessionID: string) => {
if (sessionID === 'child-1') return Promise.resolve({ id: 'child-1', parentID: 'parent-1' })
if (sessionID === 'parent-1') return Promise.resolve({ id: 'parent-1' })
return Promise.reject(new Error('Session not found'))
})
render(<Harness />, {
wrapper: createWrapper(createTestQueryClient(), '/repos/123/sessions/parent-1'),
})
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'form.created', data: { form: childSessionForm }, directory: '/repo' })
})
await waitFor(() => {
expect(mocks.getSession).toHaveBeenCalledWith('child-1')
expect(useSessionStatus.getState().parents.get('child-1')).toBe('parent-1')
})
expect(screen.getByTestId('current')).toHaveTextContent('form-child')
})
it('exposes sseHealth through context', async () => {
mocks.getHealth.mockReturnValue({ isConnected: true, isHealthy: true, lastEventAt: Date.now(), isStalled: false })
mocks.subscribeGlobalMonitor.mockImplementation(({ onHealthChange }) => {
+144 -44
View File
@@ -1,6 +1,6 @@
/* eslint-disable react-refresh/only-export-components */
import { createContext, useContext, useEffect, useState, useCallback, useMemo, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { useLocation, useNavigate } from 'react-router-dom'
import { useQueryClient, useQuery } from '@tanstack/react-query'
import {
cancelForm,
@@ -19,6 +19,7 @@ import type { PermissionResponse, SSHHostKeyRequest, Repo } from '@/api/types'
import { showToast } from '@/lib/toast'
import { openCodeEventStream, type EventStreamHealthState } from '@/lib/opencode-event-stream'
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
import { getSessionPath, parseRepoRoute } from '@/lib/navigation'
import { changeWalkthroughQueryKey } from '@/hooks/useChangeWalkthrough'
import { busyStatusesFromActiveSessions, useSessionStatus } from '@/stores/sessionStatusStore'
import {
@@ -71,6 +72,52 @@ function repoMatchesDirectory(repo: Repo, directory?: string | null) {
.some((path) => normalizeDirectory(path) === normalizedDirectory)
}
function isSessionWithinView(
sessionID: string,
viewedSessionID: string,
parents: Map<string, string | null>,
): boolean {
const visited = new Set<string>()
let currentID: string | null = sessionID
while (currentID !== null && !visited.has(currentID)) {
if (currentID === viewedSessionID) return true
visited.add(currentID)
currentID = parents.get(currentID) ?? null
}
return false
}
/**
* Pins the item currently on screen until it leaves `items`, then advances to the first item whose
* session is the viewed session or one of its descendants, falling back to the first item.
* The selection is derived during render so a newly arriving item never displaces the shown one.
*/
function usePinnedViewedItem<T extends SessionScopedItem>(
items: T[],
viewedSessionId: string | null,
parents: Map<string, string | null>,
): T | null {
const pinnedIdRef = useRef<string | null>(null)
return useMemo(() => {
const pinnedId = pinnedIdRef.current
if (pinnedId) {
const pinned = items.find((item) => item.id === pinnedId)
if (pinned) return pinned
}
const forViewedSession = viewedSessionId
? items.find((item) => isSessionWithinView(item.sessionID, viewedSessionId, parents)) ?? null
: null
const next = forViewedSession ?? items[0] ?? null
pinnedIdRef.current = next?.id ?? null
return next
}, [items, viewedSessionId, parents])
}
function reconcileBySessionForDirectory<T extends SessionScopedItem>(
prev: Record<string, T[]>,
directory: string,
@@ -104,6 +151,19 @@ interface EventContextValue {
permissions: {
current: PermissionRequest | null
pendingCount: number
/**
* Session currently being viewed from the route, or null when no session route is active.
*/
viewedSessionId: string | null
/**
* Directory of the current permission's session, resolved from tracked events and the query cache.
*/
currentDirectory: string | null
/**
* True when a session is being viewed and the current permission belongs to neither that session
* nor one of its descendants.
*/
currentIsFromDifferentSession: boolean
/**
* Replies to a permission request and removes it from the queue. Resolves, after showing an
* "expired" toast, when the server no longer knows the request (`PermissionNotFoundError`);
@@ -169,6 +229,8 @@ const EventContext = createContext<EventContextValue | null>(null)
export function EventProvider({ children }: { children: React.ReactNode }) {
const queryClient = useQueryClient()
const navigate = useNavigate()
const location = useLocation()
const sessionParents = useSessionStatus((state) => state.parents)
const [sshHostKeyRequest, setSSHHostKeyRequest] = useState<SSHHostKeyRequest | null>(null)
const [sseHealth, setSseHealth] = useState<SSEHealthState>(() => {
@@ -217,52 +279,72 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const allPermissions = useMemo(() => Object.values(permissionsBySession).flat(), [permissionsBySession])
const allForms = useMemo(() => Object.values(formsBySession).flat(), [formsBySession])
const currentPermission = allPermissions[0] ?? null
const currentForm = allForms[0] ?? null
const viewedSessionId = useMemo(
() => parseRepoRoute(location.pathname).sessionId,
[location.pathname],
)
const currentPermission = usePinnedViewedItem(allPermissions, viewedSessionId, sessionParents)
const currentForm = usePinnedViewedItem(allForms, viewedSessionId, sessionParents)
const rememberSessionDirectory = useCallback((sessionID: string, directory?: string) => {
if (!directory) return
sessionDirectoriesRef.current.set(sessionID, directory)
}, [])
const findSessionDirectory = useCallback((sessionID: string): string | null => {
const remembered = sessionDirectoriesRef.current.get(sessionID)
if (remembered) return remembered
const findCachedSessionDirectory = useCallback((sessionID: string): string | null => {
const cache = queryClient.getQueryCache()
const queries = cache.getAll()
let directory: string | undefined
for (const query of queries) {
const key = query.queryKey
if (key[0] !== 'opencode' || key[1] !== 'session' || key[2] !== sessionID) continue
const sessionData = query.state.data as { location?: { directory?: string } } | undefined
const directory = sessionData?.location?.directory ?? (typeof key[3] === 'string' ? key[3] : null)
if (directory) return directory
}
for (const query of queries) {
const key = query.queryKey
if (key[0] !== 'opencode' || key[1] !== 'sessions') continue
const sessionsData = query.state.data
if (!sessionsData || typeof sessionsData !== 'object' || !('pages' in sessionsData)) continue
const pages = (sessionsData as {
pages?: Array<{ items?: Array<{ id: string; location?: { directory?: string } }> }>
}).pages
if (!Array.isArray(pages)) continue
for (const page of pages) {
const found = page.items?.find(s => s.id === sessionID)
const directory = found?.location?.directory
if (directory) return directory
const resolvedDirectory = sessionData?.location?.directory
?? (typeof key[3] === 'string' ? key[3] : undefined)
if (resolvedDirectory) {
directory = resolvedDirectory
break
}
}
return null
if (!directory) {
for (const query of queries) {
const key = query.queryKey
if (key[0] !== 'opencode' || key[1] !== 'sessions') continue
const sessionsData = query.state.data
if (!sessionsData || typeof sessionsData !== 'object' || !('pages' in sessionsData)) continue
const pages = (sessionsData as {
pages?: Array<{ items?: Array<{ id: string; location?: { directory?: string } }> }>
}).pages
if (!Array.isArray(pages)) continue
for (const page of pages) {
const found = page.items?.find(s => s.id === sessionID)
if (found?.location?.directory) {
directory = found.location.directory
break
}
}
if (directory) break
}
}
return directory ?? null
}, [queryClient])
const findSessionDirectory = useCallback((sessionID: string): string | null => {
const remembered = sessionDirectoriesRef.current.get(sessionID)
if (remembered) return remembered
return findCachedSessionDirectory(sessionID)
}, [findCachedSessionDirectory])
const getRepoIdForSession = useCallback((sessionID: string): number | null => {
if (!repos) return null
const directory = findSessionDirectory(sessionID)
@@ -271,6 +353,15 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
return repo?.id ?? null
}, [repos, findSessionDirectory])
const currentPermissionDirectory = useMemo(
() => (currentPermission ? findSessionDirectory(currentPermission.sessionID) : null),
[currentPermission, findSessionDirectory],
)
const currentIsFromDifferentSession = viewedSessionId !== null
&& currentPermission !== null
&& !isSessionWithinView(currentPermission.sessionID, viewedSessionId, sessionParents)
const addPermission = useCallback((permission: PermissionRequest) => {
addToSessionKeyedState(setPermissionsBySession, permission)
}, [])
@@ -374,27 +465,24 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
return (formsBySession[sessionID]?.length ?? 0) > 0
}, [formsBySession])
const navigateToSession = useCallback((sessionID: string) => {
const repoId = getRepoIdForSession(sessionID)
if (repoId === null) return
const targetPath = getSessionPath(repoId, sessionID)
if (`${window.location.pathname}${window.location.search}` !== targetPath) {
navigate(targetPath)
}
}, [getRepoIdForSession, navigate])
const navigateToCurrentForm = useCallback(() => {
if (!currentForm) return
const repoId = getRepoIdForSession(currentForm.sessionID)
if (repoId) {
const targetPath = `/repos/${repoId}/sessions/${currentForm.sessionID}`
if (window.location.pathname !== targetPath) {
navigate(targetPath)
}
}
}, [currentForm, getRepoIdForSession, navigate])
navigateToSession(currentForm.sessionID)
}, [currentForm, navigateToSession])
const navigateToCurrentPermission = useCallback(() => {
if (!currentPermission) return
const repoId = getRepoIdForSession(currentPermission.sessionID)
if (repoId) {
const targetPath = `/repos/${repoId}/sessions/${currentPermission.sessionID}`
if (window.location.pathname !== targetPath) {
navigate(targetPath)
}
}
}, [currentPermission, getRepoIdForSession, navigate])
navigateToSession(currentPermission.sessionID)
}, [currentPermission, navigateToSession])
const reconcilePendingActionsForDirectories = useCallback(async (directories: string[]) => {
await Promise.all(directories.map(async (directory) => {
@@ -557,6 +645,9 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const request = event.data
rememberSessionDirectory(request.sessionID, event.directory)
addPermission(request)
if (!useSessionStatus.getState().parents.has(request.sessionID)) {
void resolveSessionAncestry([request.sessionID])
}
break
}
case 'permission.replied': {
@@ -568,6 +659,9 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const form = event.data.form
rememberSessionDirectory(form.sessionID, event.directory)
addForm(form)
if (!useSessionStatus.getState().parents.has(form.sessionID)) {
void resolveSessionAncestry([form.sessionID])
}
break
}
case 'form.replied':
@@ -766,6 +860,9 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
permissions: {
current: currentPermission,
pendingCount: allPermissions.length,
viewedSessionId,
currentDirectory: currentPermissionDirectory,
currentIsFromDifferentSession,
respond: replyToPermission,
dismiss: removePermission,
getForToolCall: getPermissionForToolCall,
@@ -793,6 +890,9 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
respondToSSHHostKey,
currentPermission,
allPermissions.length,
viewedSessionId,
currentPermissionDirectory,
currentIsFromDifferentSession,
replyToPermission,
removePermission,
hasPermissionsForSession,