feat(opencode): migrate OpenCode Manager to OpenCode 2 (#359)

* feat(opencode): migrate OpenCode Manager to OpenCode 2

Port the backend lifecycle, generated plugins, event aggregation,
schedules, worktrees, provider credentials, MCP, config handling, the
frontend chat model, and the ocm CLI to OpenCode 2.

Adopt @opencode/client 2.0.15 as the single typed V2 API contract,
require OpenCode 2.0.0 or newer (pinned 2.0.15), and delete every
V1-only code path.

* refactor(opencode): reload config in place and drop v1 compatibility shims

Route config/skill/AGENTS.md changes through the OpenCode location reload
API instead of a full server restart, stop auto-resuming interrupted
sessions, remove the restart coordinator and v1 MCP/version shims, and pin
support to OpenCode >=2.0.15 <3.0.0. Adds integration-ready retries,
service-mode launch, ocm-cli repo proxy, and new frontend form/MCP helpers.

* refactor(opencode): consolidate v2 migration helpers and harden install, proxy, and session flows

- extract shared semver and model-ref utilities, reuse across version checks
- share the OpenCode release download script across Docker, entrypoint, dev setup
- unify install/upgrade failure recovery and guard externally managed OPENCODE_BIN
- scope the repo proxy location rewrite and surface ocm proxy errors
- rework frontend session projection, permission lookup, and cache invalidation

* fix(schedules): reject unavailable agents before creating a session

* feat(opencode): add ocm install, schedule agent fallback, and session move guards
This commit is contained in:
Chris Scott authored and GitHub committed 2026-09-26 13:16:45 -04:00
1 parent 6c2ebd764b
commit dacde879d6
383 files changed
+29905 -46566

No files matched your search

+552 -169
View File
@@ -4,16 +4,16 @@ 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 { PermissionRequest, QuestionRequest } from '@/api/types'
import { EventProvider, useEventContext, usePermissions, useQuestions, useSSEHealth } from './EventContext'
import type { FormInfo, PermissionRequest } from '@opencode-manager/shared/opencode'
import { EventProvider, useEventContext, useForms, usePermissions, useSSEHealth } from './EventContext'
const mocks = vi.hoisted(() => ({
listRepos: vi.fn(),
listPendingPermissions: vi.fn(),
listPendingQuestions: vi.fn(),
replyToQuestion: vi.fn(),
rejectQuestion: vi.fn(),
respondToPermission: vi.fn(),
listPendingForms: vi.fn(),
replyPermission: vi.fn(),
replyForm: vi.fn(),
cancelForm: vi.fn(),
subscribeGlobalMonitor: vi.fn(),
getHealth: vi.fn(),
}))
@@ -23,13 +23,11 @@ vi.mock('@/api/repos', () => ({
}))
vi.mock('@/api/opencode', () => ({
OpenCodeClient: vi.fn(() => ({
listPendingPermissions: mocks.listPendingPermissions,
listPendingQuestions: mocks.listPendingQuestions,
replyToQuestion: mocks.replyToQuestion,
rejectQuestion: mocks.rejectQuestion,
respondToPermission: mocks.respondToPermission,
})),
listPendingPermissions: mocks.listPendingPermissions,
listPendingForms: mocks.listPendingForms,
replyPermission: mocks.replyPermission,
replyForm: mocks.replyForm,
cancelForm: mocks.cancelForm,
}))
vi.mock('@/lib/opencode-event-stream', () => ({
@@ -46,72 +44,52 @@ vi.mock('@/lib/toast', () => ({
},
}))
const pendingQuestion: QuestionRequest = {
id: 'question-1',
const pendingForm: FormInfo = {
id: 'form-1',
sessionID: 'session-1',
questions: [
{
question: 'Continue?',
header: 'Confirm',
options: [
{
label: 'Yes',
description: 'Continue',
},
],
multiple: false,
},
title: 'Continue?',
fields: [
{ key: 'q0', title: 'Confirm', type: 'string', options: [{ value: 'Yes', label: 'Yes' }] },
],
}
const secondPendingQuestion: QuestionRequest = {
id: 'question-2',
const secondPendingForm: FormInfo = {
id: 'form-2',
sessionID: 'session-2',
questions: [
{
question: 'Deploy?',
header: 'Deploy',
options: [
{
label: 'Yes',
description: 'Deploy changes',
},
],
multiple: false,
},
title: 'Deploy?',
fields: [
{ key: 'q0', title: 'Deploy', type: 'string', options: [{ value: 'Yes', label: 'Yes' }] },
],
}
const pendingPermission: PermissionRequest = {
id: 'permission-1',
sessionID: 'session-1',
permission: 'bash',
patterns: ['echo hello'],
action: 'shell',
resources: ['echo hello'],
metadata: {},
always: [],
tool: {
messageID: 'message-1',
callID: 'call-1',
},
}
const secondPendingPermission: PermissionRequest = {
id: 'permission-2',
sessionID: 'session-1',
permission: 'write',
patterns: ['/tmp/test.txt'],
action: 'edit',
resources: ['/tmp/test.txt'],
metadata: {},
always: [],
tool: {
messageID: 'message-2',
callID: 'call-2',
},
}
const sourcedPermission: PermissionRequest = {
id: 'permission-3',
sessionID: 'session-1',
action: 'shell',
resources: ['echo hello'],
metadata: {},
source: { type: 'tool', messageID: 'msg_1', id: 'call_1' },
}
function Harness() {
const { current, pendingCount, syncForSession, navigateToCurrent, reject, reply, getForSession } = useQuestions()
const { current, pendingCount, syncForSession, navigateToCurrent, cancel, reply, getForSession } = useForms()
const permissions = usePermissions()
const permissionForCall = permissions.getForCallID('call-1', 'session-1')
const location = useLocation()
return (
@@ -123,25 +101,32 @@ 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-call">{permissionForCall?.id ?? 'none'}</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'}
</div>
<div data-testid="permission-tool-call-other-id">
{permissions.getForToolCall('call_other', 'msg_1')?.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>
<button onClick={() => current && cancel(current.id)}>Dismiss</button>
<button onClick={() => current && reply(current.id, { q0: 'Yes' })}>Reply</button>
<button onClick={() => permissions.current && permissions.respond(permissions.current.id, permissions.current.sessionID, 'reject')}>Reject Permission</button>
<button onClick={() => permissions.current && permissions.respond(permissions.current.id, permissions.current.sessionID, 'reject', 'not allowed')}>Reject Permission With Reason</button>
</div>
)
}
function createWrapper() {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
function createTestQueryClient() {
return new QueryClient({
defaultOptions: { queries: { retry: false } },
})
}
function createWrapper(queryClient = createTestQueryClient()) {
return ({ children }: { children: ReactNode }) => (
<MemoryRouter>
<QueryClientProvider client={queryClient}>
@@ -151,14 +136,26 @@ function createWrapper() {
)
}
describe('EventProvider questions', () => {
function CacheResolutionHarness({ sessionID }: { sessionID: string }) {
const { getRepoIdForSession } = useEventContext()
const repoId = getRepoIdForSession(sessionID)
return (
<div>
<div data-testid="repo-id">{repoId ?? 'none'}</div>
</div>
)
}
describe('EventProvider permissions and forms', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.listRepos.mockResolvedValue([])
mocks.listPendingPermissions.mockResolvedValue([])
mocks.listPendingQuestions.mockResolvedValue([])
mocks.replyToQuestion.mockResolvedValue(undefined)
mocks.rejectQuestion.mockResolvedValue(undefined)
mocks.listPendingForms.mockResolvedValue([])
mocks.replyPermission.mockResolvedValue(undefined)
mocks.replyForm.mockResolvedValue(undefined)
mocks.cancelForm.mockResolvedValue(undefined)
mocks.getHealth.mockReturnValue({ isConnected: false, isHealthy: false, lastEventAt: null, isStalled: false })
mocks.subscribeGlobalMonitor.mockReturnValue({
dispose: vi.fn(),
@@ -168,8 +165,8 @@ describe('EventProvider questions', () => {
})
})
it('syncs missed pending questions for a session', async () => {
mocks.listPendingQuestions.mockResolvedValue([pendingQuestion])
it('syncs missed pending forms for a session', async () => {
mocks.listPendingForms.mockResolvedValue([pendingForm])
render(<Harness />, { wrapper: createWrapper() })
@@ -177,7 +174,7 @@ describe('EventProvider questions', () => {
await waitFor(() => {
expect(screen.getByTestId('count')).toHaveTextContent('1')
expect(screen.getByTestId('current')).toHaveTextContent('question-1')
expect(screen.getByTestId('current')).toHaveTextContent('form-1')
})
})
@@ -191,7 +188,6 @@ describe('EventProvider questions', () => {
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')
})
})
@@ -231,16 +227,32 @@ describe('EventProvider questions', () => {
await userEvent.click(screen.getByRole('button', { name: 'Reject Permission' }))
await waitFor(() => {
expect(mocks.respondToPermission).toHaveBeenCalledTimes(1)
expect(mocks.respondToPermission).toHaveBeenCalledWith('permission-1', 'reject')
expect(mocks.replyPermission).toHaveBeenCalledTimes(1)
expect(mocks.replyPermission).toHaveBeenCalledWith('session-1', 'permission-1', 'reject', undefined)
expect(screen.getByTestId('permission-count')).toHaveTextContent('1')
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-2')
})
})
it('clears stale pending questions for a session', async () => {
mocks.listPendingQuestions
.mockResolvedValueOnce([pendingQuestion])
it('forwards an optional rejection message to the facade', 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'))
await userEvent.click(screen.getByRole('button', { name: 'Reject Permission With Reason' }))
await waitFor(() =>
expect(mocks.replyPermission).toHaveBeenCalledWith('session-1', 'permission-1', 'reject', 'not allowed'),
)
})
it('clears stale pending forms for a session', async () => {
mocks.listPendingForms
.mockResolvedValueOnce([pendingForm])
.mockResolvedValueOnce([])
render(<Harness />, { wrapper: createWrapper() })
@@ -259,10 +271,10 @@ describe('EventProvider questions', () => {
})
})
it('reconciles pending questions for the whole directory', async () => {
mocks.listPendingQuestions
.mockResolvedValueOnce([pendingQuestion, secondPendingQuestion])
.mockResolvedValueOnce([pendingQuestion])
it('reconciles pending forms for the whole directory', async () => {
mocks.listPendingForms
.mockResolvedValueOnce([pendingForm, secondPendingForm])
.mockResolvedValueOnce([pendingForm])
render(<Harness />, { wrapper: createWrapper() })
@@ -276,12 +288,12 @@ describe('EventProvider questions', () => {
await waitFor(() => {
expect(screen.getByTestId('count')).toHaveTextContent('1')
expect(screen.getByTestId('current')).toHaveTextContent('question-1')
expect(screen.getByTestId('current')).toHaveTextContent('form-1')
})
})
it('resolves pending questions per session independently of the global current', async () => {
mocks.listPendingQuestions.mockResolvedValue([pendingQuestion, secondPendingQuestion])
it('resolves pending forms per session independently of the global current', async () => {
mocks.listPendingForms.mockResolvedValue([pendingForm, secondPendingForm])
render(<Harness />, { wrapper: createWrapper() })
@@ -291,16 +303,16 @@ describe('EventProvider questions', () => {
expect(screen.getByTestId('count')).toHaveTextContent('2')
})
expect(screen.getByTestId('current')).toHaveTextContent('question-1')
expect(screen.getByTestId('for-session-1')).toHaveTextContent('question-1')
expect(screen.getByTestId('for-session-2')).toHaveTextContent('question-2')
expect(screen.getByTestId('current')).toHaveTextContent('form-1')
expect(screen.getByTestId('for-session-1')).toHaveTextContent('form-1')
expect(screen.getByTestId('for-session-2')).toHaveTextContent('form-2')
expect(screen.getByTestId('for-session-unknown')).toHaveTextContent('none')
})
it('reconciles stale pending questions after reconnect', async () => {
it('reconciles stale pending forms after reconnect', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listPendingQuestions
.mockResolvedValueOnce([pendingQuestion])
mocks.listPendingForms
.mockResolvedValueOnce([pendingForm])
.mockResolvedValueOnce([])
render(<Harness />, { wrapper: createWrapper() })
@@ -319,16 +331,127 @@ describe('EventProvider questions', () => {
})
})
it('navigates to a synced pending question without session query cache', async () => {
it('clears settled pending actions on an upstream resync while the browser stream stays connected', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listPendingQuestions.mockResolvedValue([pendingQuestion])
mocks.listPendingPermissions.mockResolvedValue([])
mocks.listPendingForms.mockResolvedValue([])
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => {
expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/repo')
expect(mocks.listPendingForms).toHaveBeenCalledWith('/repo')
})
await act(async () => {
await Promise.resolve()
})
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined
act(() => {
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/repo' })
onEvent({ type: 'form.created', data: { form: pendingForm }, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-count')).toHaveTextContent('1')
expect(screen.getByTestId('count')).toHaveTextContent('1')
})
act(() => {
onResync?.()
})
await waitFor(() => {
expect(screen.getByTestId('permission-count')).toHaveTextContent('0')
expect(screen.getByTestId('count')).toHaveTextContent('0')
})
})
it('retains genuinely pending actions on an upstream resync', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listPendingPermissions.mockResolvedValue([pendingPermission])
mocks.listPendingForms.mockResolvedValue([pendingForm])
render(<Harness />, { wrapper: createWrapper() })
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
const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined
act(() => {
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/repo' })
onEvent({ type: 'form.created', data: { form: pendingForm }, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-count')).toHaveTextContent('1')
expect(screen.getByTestId('count')).toHaveTextContent('1')
})
act(() => {
onResync?.()
})
await waitFor(() => {
expect(screen.getByTestId('permission-count')).toHaveTextContent('1')
expect(screen.getByTestId('count')).toHaveTextContent('1')
})
})
it('reconciles tracked worktree session directories on an upstream resync', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listPendingPermissions.mockResolvedValue([])
mocks.listPendingForms.mockResolvedValue([])
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => {
expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/repo')
expect(mocks.listPendingForms).toHaveBeenCalledWith('/repo')
})
await act(async () => {
await Promise.resolve()
})
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined
act(() => {
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/worktrees/wt-1' })
})
await waitFor(() => {
expect(screen.getByTestId('permission-count')).toHaveTextContent('1')
})
act(() => {
onResync?.()
})
await waitFor(() => {
expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/worktrees/wt-1')
expect(screen.getByTestId('permission-count')).toHaveTextContent('0')
})
})
it('navigates to a synced pending form without session query cache', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, 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('question-1')
expect(screen.getByTestId('current')).toHaveTextContent('form-1')
})
await userEvent.click(screen.getByRole('button', { name: 'Navigate' }))
@@ -338,8 +461,8 @@ describe('EventProvider questions', () => {
})
})
it('clears a pending question after dismiss succeeds', async () => {
mocks.listPendingQuestions.mockResolvedValue([pendingQuestion])
it('clears a pending form after dismiss succeeds', async () => {
mocks.listPendingForms.mockResolvedValue([pendingForm])
render(<Harness />, { wrapper: createWrapper() })
@@ -352,13 +475,14 @@ describe('EventProvider questions', () => {
await userEvent.click(screen.getByRole('button', { name: 'Dismiss' }))
await waitFor(() => {
expect(mocks.cancelForm).toHaveBeenCalledWith('session-1', 'form-1')
expect(screen.getByTestId('count')).toHaveTextContent('0')
expect(screen.getByTestId('current')).toHaveTextContent('none')
})
})
it('clears a pending question after reply succeeds', async () => {
mocks.listPendingQuestions.mockResolvedValue([pendingQuestion])
it('clears a pending form after reply succeeds', async () => {
mocks.listPendingForms.mockResolvedValue([pendingForm])
render(<Harness />, { wrapper: createWrapper() })
@@ -371,12 +495,13 @@ describe('EventProvider questions', () => {
await userEvent.click(screen.getByRole('button', { name: 'Reply' }))
await waitFor(() => {
expect(mocks.replyForm).toHaveBeenCalledWith('session-1', 'form-1', { q0: 'Yes' })
expect(screen.getByTestId('count')).toHaveTextContent('0')
expect(screen.getByTestId('current')).toHaveTextContent('none')
})
})
it('adds a pending question received via the global monitor onEvent', async () => {
it('adds a pending form received via the global monitor onEvent', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
render(<Harness />, { wrapper: createWrapper() })
@@ -390,85 +515,299 @@ describe('EventProvider questions', () => {
act(() => {
onEvent({
type: 'question.asked',
properties: pendingQuestion,
type: 'form.created',
data: { form: pendingForm },
directory: '/repo',
})
})
await waitFor(() => {
expect(screen.getByTestId('count')).toHaveTextContent('1')
expect(screen.getByTestId('current')).toHaveTextContent('question-1')
expect(screen.getByTestId('current')).toHaveTextContent('form-1')
})
})
it('handles session.updated event without throwing when cache has infinite-query data', async () => {
it('adds a pending permission received via the global monitor onEvent', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
// Seed infinite-query shaped data into session-list cache
queryClient.setQueryData(
['opencode', 'sessions', 'http://localhost:5551', '/repo', { search: undefined, limit: 25 }],
{
pages: [{
items: [
{ id: 'existing-session', projectID: 'proj-1', title: 'Existing', directory: '/repo', time: { created: 1000, updated: 1000 } },
],
cursors: {},
}],
pageParams: [undefined],
},
)
const wrapper = ({ children }: { children: ReactNode }) => (
<MemoryRouter>
<QueryClientProvider client={queryClient}>
<EventProvider>{children}</EventProvider>
</QueryClientProvider>
</MemoryRouter>
)
render(<Harness />, { wrapper })
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => {
expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()
})
// Trigger session.updated event - should not throw with infinite-query cache data
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
expect(() => {
act(() => {
onEvent({
type: 'session.updated',
properties: {
info: { id: 'new-session', projectID: 'proj-1', title: 'New', directory: '/repo', time: { created: 2000, updated: 2000 } },
},
})
act(() => {
onEvent({
type: 'permission.asked',
data: pendingPermission,
directory: '/repo',
})
}).not.toThrow()
})
it('getClient resolves directory from infinite-query session list cache', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
// Seed infinite-query data with a session that has directory field
await waitFor(() => {
expect(screen.getByTestId('permission-count')).toHaveTextContent('1')
expect(screen.getByTestId('permission-current')).toHaveTextContent('permission-1')
})
act(() => {
onEvent({
type: 'permission.replied',
data: { sessionID: 'session-1', requestID: 'permission-1', reply: 'reject' },
directory: '/repo',
})
})
await waitFor(() => {
expect(screen.getByTestId('permission-count')).toHaveTextContent('0')
})
})
it('resolves a pending permission by its source tool call and message', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
render(<Harness />, { wrapper: createWrapper() })
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: sourcedPermission,
directory: '/repo',
})
})
await waitFor(() => {
expect(screen.getByTestId('permission-tool-call')).toHaveTextContent('permission-3')
})
expect(screen.getByTestId('permission-tool-call-other-message')).toHaveTextContent('none')
expect(screen.getByTestId('permission-tool-call-other-id')).toHaveTextContent('none')
})
it('removes a pending form on a form.cancelled event', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listPendingForms.mockResolvedValue([pendingForm])
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => {
expect(screen.getByTestId('count')).toHaveTextContent('1')
})
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.cancelled',
data: { id: 'form-1', sessionID: 'session-1' },
directory: '/repo',
})
})
await waitFor(() => {
expect(screen.getByTestId('count')).toHaveTextContent('0')
expect(screen.getByTestId('current')).toHaveTextContent('none')
})
})
it('does not invalidate the transcript on form reply or cancel events', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listPendingForms.mockResolvedValue([pendingForm, secondPendingForm])
const queryClient = createTestQueryClient()
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
render(<Harness />, { wrapper: createWrapper(queryClient) })
await waitFor(() => {
expect(screen.getByTestId('count')).toHaveTextContent('2')
})
invalidateQueries.mockClear()
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.replied', data: { id: 'form-1', sessionID: 'session-1', answer: {} }, directory: '/repo' })
onEvent({ type: 'form.cancelled', data: { id: 'form-2', sessionID: 'session-2' }, directory: '/repo' })
})
await waitFor(() => {
expect(screen.getByTestId('count')).toHaveTextContent('0')
})
expect(invalidateQueries).not.toHaveBeenCalled()
})
it.each([
'credential.updated',
'credential.switched',
'integration.updated',
'provider.updated',
'model.updated',
])('invalidates provider caches on a location-less %s event', async (type) => {
const queryClient = createTestQueryClient()
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
render(<Harness />, { wrapper: createWrapper(queryClient) })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
invalidateQueries.mockClear()
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type, data: {} })
})
await waitFor(() => {
for (const queryKey of [
['provider-credentials'],
['provider-auth-methods'],
['providers-with-models'],
['opencode', 'providers'],
]) {
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey })
}
})
expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['providers'] })
expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['providers-for-execution-model'] })
})
it('collapses a burst of provider events into a single provider invalidation flush', async () => {
const queryClient = createTestQueryClient()
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
render(<Harness />, { wrapper: createWrapper(queryClient) })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
invalidateQueries.mockClear()
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'credential.updated', data: {} })
onEvent({ type: 'provider.updated', data: {} })
onEvent({ type: 'model.updated', data: {} })
onEvent({ type: 'integration.updated', data: {} })
onEvent({ type: 'credential.switched', data: {} })
onEvent({ type: 'provider.updated', data: {} })
})
await waitFor(() => {
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'providers'] })
})
expect(invalidateQueries).toHaveBeenCalledTimes(4)
})
it.each<[string, string[]]>([
['agent.updated', ['opencode', 'agents']],
['command.updated', ['opencode', 'commands']],
])('invalidates the %s cache', async (type, queryKey) => {
const queryClient = createTestQueryClient()
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
render(<Harness />, { wrapper: createWrapper(queryClient) })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
invalidateQueries.mockClear()
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type, data: {} })
})
await waitFor(() => {
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey })
})
})
it('invalidates both config caches on config.updated', async () => {
const queryClient = createTestQueryClient()
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
render(<Harness />, { wrapper: createWrapper(queryClient) })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
invalidateQueries.mockClear()
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'config.updated', data: {} })
})
await waitFor(() => {
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'config'] })
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode-config'] })
})
})
it('reconciles every tracked directory concurrently on an upstream resync', async () => {
mocks.listRepos.mockResolvedValue([
{ id: 1, fullPath: '/repo-a' },
{ id: 2, fullPath: '/repo-b' },
])
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => {
expect(mocks.listPendingForms).toHaveBeenCalledWith('/repo-b')
})
await act(async () => {
await Promise.resolve()
})
const pending = new Map<string, () => void>()
mocks.listPendingPermissions.mockImplementation(
(directory: string) =>
new Promise((resolve) => {
pending.set(directory, () => resolve([]))
}),
)
mocks.listPendingPermissions.mockClear()
mocks.listPendingForms.mockClear()
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined
act(() => {
onResync?.()
})
expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/repo-a')
expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/repo-b')
expect(mocks.listPendingForms).toHaveBeenCalledWith('/repo-a')
expect(mocks.listPendingForms).toHaveBeenCalledWith('/repo-b')
await act(async () => {
pending.forEach((resolve) => resolve())
})
})
it('resolves a session directory from the infinite-query session list cache', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
const queryClient = createTestQueryClient()
queryClient.setQueryData(
['opencode', 'sessions', 'http://localhost:5551', '/repo', { search: undefined, limit: 25 }],
['opencode', 'sessions', '/repo', { search: undefined, limit: 25 }],
{
pages: [{
items: [
{ id: 'ses-infinite', projectID: 'proj-1', title: 'From Infinite Query', directory: '/repo', time: { created: 1000, updated: 1000 } },
{ id: 'ses-infinite', projectID: 'proj-1', title: 'From Infinite Query', location: { directory: '/repo' }, time: { created: 1000, updated: 1000 } },
],
cursors: {},
}],
@@ -476,25 +815,69 @@ describe('EventProvider questions', () => {
},
)
// Ensure no single-session cache exists for this session (forces fallback to session-list lookup)
const wrapper = ({ children }: { children: ReactNode }) => (
<MemoryRouter>
<QueryClientProvider client={queryClient}>
<EventProvider>{children}</EventProvider>
</QueryClientProvider>
</MemoryRouter>
)
function ClientHarness() {
const { getClient } = useEventContext()
const client = getClient('ses-infinite')
return <div data-testid="client-result">{client ? 'found' : 'not-found'}</div>
}
render(<ClientHarness />, { wrapper })
render(<CacheResolutionHarness sessionID="ses-infinite" />, { wrapper: createWrapper(queryClient) })
await waitFor(() => {
expect(screen.getByTestId('client-result')).toHaveTextContent('found')
expect(screen.getByTestId('repo-id')).toHaveTextContent('123')
})
})
it('resolves a session directory from the single-session cache without a remembered event directory', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
const queryClient = createTestQueryClient()
queryClient.setQueryData(
['opencode', 'session', 'ses-detail', '/repo'],
{
id: 'ses-detail',
projectID: 'proj-1',
title: 'Session Detail',
location: { directory: '/repo' },
time: { created: 1000, updated: 1000 },
},
)
render(<CacheResolutionHarness sessionID="ses-detail" />, { wrapper: createWrapper(queryClient) })
await waitFor(() => {
expect(screen.getByTestId('repo-id')).toHaveTextContent('123')
})
})
it('resolves a session in the second directory page of the session list cache', async () => {
mocks.listRepos.mockResolvedValue([
{ id: 123, fullPath: '/repo-a' },
{ id: 456, fullPath: '/repo-b' },
])
const queryClient = createTestQueryClient()
queryClient.setQueryData(
['opencode', 'sessions', '/repo-a|/repo-b', { search: undefined, limit: 25 }],
{
pages: [
{
items: [
{ id: 'ses-first', projectID: 'proj-1', title: 'First', location: { directory: '/repo-a' }, time: { created: 1000, updated: 1000 } },
],
cursors: { '/repo-a': 'cursor-a' },
},
{
items: [
{ id: 'ses-second', projectID: 'proj-1', title: 'Second', location: { directory: '/repo-b' }, time: { created: 2000, updated: 2000 } },
],
cursors: {},
},
],
pageParams: [undefined, { '/repo-a': 'cursor-a' }],
},
)
render(<CacheResolutionHarness sessionID="ses-second" />, { wrapper: createWrapper(queryClient) })
await waitFor(() => {
expect(screen.getByTestId('repo-id')).toHaveTextContent('456')
})
})
+211 -304
View File
@@ -2,18 +2,25 @@
import { createContext, useContext, useEffect, useState, useCallback, useMemo, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { useQueryClient, useQuery } from '@tanstack/react-query'
import { OpenCodeClient } from '@/api/opencode'
import {
cancelForm,
listPendingForms,
listPendingPermissions,
replyForm,
replyPermission,
} from '@/api/opencode'
import { listRepos } from '@/api/repos'
import type { PermissionRequest, PermissionResponse, QuestionRequest, SSEEvent, SSHHostKeyRequest, MessageWithParts, Repo } from '@/api/types'
import type { FormAnswer, FormInfo, PermissionRequest, V2Event } from '@opencode-manager/shared/opencode'
import type { PermissionResponse, SSHHostKeyRequest, Repo } from '@/api/types'
import { showToast } from '@/lib/toast'
import { openCodeEventStream, type EventStreamHealthState } from '@/lib/opencode-event-stream'
import { OPENCODE_API_ENDPOINT } from '@/config'
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
import { invalidateRepoGitCachesDebounced } from '@/lib/queryInvalidation'
import { invalidateProviderCachesDebounced, invalidateQueryKeysDebounced, invalidateRepoGitCachesDebounced } from '@/lib/queryInvalidation'
type PermissionsBySession = Record<string, PermissionRequest[]>
type QuestionsBySession = Record<string, QuestionRequest[]>
type FormsBySession = Record<string, FormInfo[]>
type SSEHealthState = Pick<EventStreamHealthState, 'isConnected' | 'isHealthy' | 'isStalled'>
type StreamEvent = (V2Event & { directory?: string }) | { type: 'ssh.host-key-request'; properties: SSHHostKeyRequest }
type SessionScopedItem = { id: string; sessionID: string }
@@ -66,73 +73,6 @@ function reconcileBySessionForDirectory<T extends SessionScopedItem>(
return next
}
function optimisticallyErrorToolPart(
queryClient: ReturnType<typeof useQueryClient>,
sessionID: string,
messageID: string,
callID: string,
errorMessage: string
) {
const cache = queryClient.getQueryCache()
const queries = cache.getAll()
for (const query of queries) {
const key = query.queryKey
if (key[0] === 'opencode' && key[1] === 'messages' && key.length >= 5) {
const querySessionID = key[3] as string
if (querySessionID !== sessionID) continue
const currentData = queryClient.getQueryData<MessageWithParts[]>(key)
if (!currentData) continue
const updatedData = currentData.map(msgWithParts => {
if (msgWithParts.info.id !== messageID) return msgWithParts
const targetPart = msgWithParts.parts.find(p =>
p.type === 'tool' &&
'callID' in p &&
p.callID === callID &&
'state' in p &&
p.state &&
typeof p.state === 'object' &&
'status' in p.state &&
(p.state as { status?: string }).status === 'running'
)
if (!targetPart) {
return msgWithParts
}
const targetPartAny = targetPart as unknown as { state: { status: string; input?: string; time: { start: number } } }
const targetState = targetPartAny.state
const updatedParts = msgWithParts.parts.map(p => {
if (p.id !== targetPart.id) return p
return {
...p,
state: {
status: 'error' as const,
input: targetState.input,
error: errorMessage,
time: {
start: targetState.time.start,
end: Date.now(),
},
},
}
})
return {
...msgWithParts,
parts: updatedParts,
}
})
queryClient.setQueryData(key, updatedData)
break
}
}
}
interface SSHHostKeyState {
request: SSHHostKeyRequest | null
respond: (requestId: string, approved: boolean) => Promise<void>
@@ -143,30 +83,33 @@ interface EventContextValue {
permissions: {
current: PermissionRequest | null
pendingCount: number
respond: (permissionID: string, sessionID: string, response: PermissionResponse) => Promise<void>
respond: (
permissionID: string,
sessionID: string,
response: PermissionResponse,
message?: string,
) => Promise<void>
dismiss: (permissionID: string, sessionID?: string) => void
getForCallID: (callID: string, sessionID: string) => PermissionRequest | null
getForToolCall: (toolCallID: string, messageID?: string) => PermissionRequest | null
hasForSession: (sessionID: string) => boolean
showDialog: boolean
setShowDialog: (show: boolean) => void
navigateToCurrent: () => void
syncForSession: (directory: string, sessionID: string) => Promise<void>
}
questions: {
current: QuestionRequest | null
forms: {
current: FormInfo | null
pendingCount: number
reply: (requestID: string, answers: string[][]) => Promise<void>
reject: (requestID: string) => Promise<void>
dismiss: (requestID: string, sessionID?: string) => void
getForCallID: (callID: string, sessionID: string) => QuestionRequest | null
getForSession: (sessionID: string) => QuestionRequest | null
reply: (formID: string, answer: FormAnswer) => Promise<void>
cancel: (formID: string) => Promise<void>
dismiss: (formID: string, sessionID?: string) => void
getForSession: (sessionID: string) => FormInfo | null
hasForSession: (sessionID: string) => boolean
navigateToCurrent: () => void
syncForSession: (directory: string, sessionID: string) => Promise<void>
}
sseHealth: SSEHealthState
getRepoIdForSession: (sessionID: string) => number | null
getClient: (sessionID: string) => OpenCodeClient | null
}
const EventContext = createContext<EventContextValue | null>(null)
@@ -201,23 +144,14 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
}, [])
const [permissionsBySession, setPermissionsBySession] = useState<PermissionsBySession>({})
const [questionsBySession, setQuestionsBySession] = useState<QuestionsBySession>({})
const [formsBySession, setFormsBySession] = useState<FormsBySession>({})
const [showPermissionDialog, setShowPermissionDialog] = useState(true)
const clientsRef = useRef<Map<string, OpenCodeClient>>(new Map())
const sessionDirectoriesRef = useRef<Map<string, string>>(new Map())
const prevPermissionCountRef = useRef(0)
const initialFetchDoneRef = useRef(false)
const subscriptionRef = useRef<ReturnType<typeof openCodeEventStream.subscribeGlobalMonitor> | null>(null)
const reposRef = useRef<typeof repos>(null)
const MAX_CACHED_CLIENTS = 50
useEffect(() => {
const clients = clientsRef.current
return () => {
clients.clear()
}
}, [])
const { data: repos } = useQuery({
queryKey: ['repos'],
@@ -225,10 +159,10 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
})
const allPermissions = useMemo(() => Object.values(permissionsBySession).flat(), [permissionsBySession])
const allQuestions = useMemo(() => Object.values(questionsBySession).flat(), [questionsBySession])
const allForms = useMemo(() => Object.values(formsBySession).flat(), [formsBySession])
const currentPermission = allPermissions[0] ?? null
const currentQuestion = allQuestions[0] ?? null
const currentForm = allForms[0] ?? null
const rememberSessionDirectory = useCallback((sessionID: string, directory?: string) => {
if (!directory) return
@@ -244,50 +178,35 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
for (const query of queries) {
const key = query.queryKey
if (key[0] === 'opencode' && key[1] === 'session' && key.length >= 5) {
const sessionData = query.state.data as { id: string } | undefined
if (sessionData?.id === sessionID) {
const directory = key[4] as string
if (directory) return directory
}
}
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' && key.length >= 4) {
const sessionsData = query.state.data
if (!sessionsData) continue
if (key[0] !== 'opencode' || key[1] !== 'sessions') continue
if (Array.isArray(sessionsData)) {
const found = sessionsData.find((s: { id: string }) => s.id === sessionID)
if (found) {
const directory = (found as { directory?: string }).directory || (key[3] as string)
if (directory) return directory
}
continue
}
const sessionsData = query.state.data
if (!sessionsData || typeof sessionsData !== 'object' || !('pages' in sessionsData)) continue
if (typeof sessionsData === 'object' && 'pages' in sessionsData) {
const infiniteData = sessionsData as { pages: Array<{ items: Array<{ id: string; directory?: string }> }> }
for (const page of infiniteData.pages) {
if (!page.items) continue
const found = page.items.find(s => s.id === sessionID)
if (found && found.directory) return found.directory
}
}
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
}
}
return null
}, [queryClient])
const findSessionInCache = useCallback((sessionID: string): { url: string; directory: string } | null => {
const directory = findSessionDirectory(sessionID)
if (!directory) return null
return { url: OPENCODE_API_ENDPOINT, directory }
}, [findSessionDirectory])
const getRepoIdForSession = useCallback((sessionID: string): number | null => {
if (!repos) return null
const directory = findSessionDirectory(sessionID)
@@ -296,23 +215,6 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
return repo?.id ?? null
}, [repos, findSessionDirectory])
const getClient = useCallback((sessionID: string): OpenCodeClient | null => {
const result = findSessionInCache(sessionID)
if (!result) return null
const clientKey = `${result.url}|${result.directory}`
let client = clientsRef.current.get(clientKey)
if (!client) {
if (clientsRef.current.size >= MAX_CACHED_CLIENTS) {
const firstKey = clientsRef.current.keys().next().value
if (firstKey) clientsRef.current.delete(firstKey)
}
client = new OpenCodeClient(result.url, result.directory)
clientsRef.current.set(clientKey, client)
}
return client
}, [findSessionInCache])
const addPermission = useCallback((permission: PermissionRequest) => {
addToSessionKeyedState(setPermissionsBySession, permission)
}, [])
@@ -321,12 +223,12 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
removeFromSessionKeyedState(setPermissionsBySession, permissionID, sessionID)
}, [])
const addQuestion = useCallback((question: QuestionRequest) => {
addToSessionKeyedState(setQuestionsBySession, question)
const addForm = useCallback((form: FormInfo) => {
addToSessionKeyedState(setFormsBySession, form)
}, [])
const removeQuestion = useCallback((requestID: string, sessionID?: string) => {
removeFromSessionKeyedState(setQuestionsBySession, requestID, sessionID)
const removeForm = useCallback((formID: string, sessionID?: string) => {
removeFromSessionKeyedState(setFormsBySession, formID, sessionID)
}, [])
const reconcilePermissionsForDirectory = useCallback((directory: string, permissions: PermissionRequest[]) => {
@@ -339,13 +241,13 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
)
}, [rememberSessionDirectory])
const reconcileQuestionsForDirectory = useCallback((directory: string, questions: QuestionRequest[]) => {
questions.forEach(question => {
rememberSessionDirectory(question.sessionID, directory)
const reconcileFormsForDirectory = useCallback((directory: string, forms: FormInfo[]) => {
forms.forEach(form => {
rememberSessionDirectory(form.sessionID, directory)
})
setQuestionsBySession(prev =>
reconcileBySessionForDirectory(prev, directory, questions, sessionDirectoriesRef.current),
setFormsBySession(prev =>
reconcileBySessionForDirectory(prev, directory, forms, sessionDirectoriesRef.current),
)
}, [rememberSessionDirectory])
@@ -363,79 +265,65 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
prevPermissionCountRef.current = permissionCount
}, [allPermissions.length, showPermissionDialog])
const respondToPermission = useCallback(async (permissionID: string, sessionID: string, response: PermissionResponse) => {
const client = getClient(sessionID)
if (!client) throw new Error('No client found for session')
if (response === 'reject') {
const permission = (permissionsBySession[sessionID] ?? []).find(p => p.id === permissionID)
if (permission?.tool) {
optimisticallyErrorToolPart(queryClient, sessionID, permission.tool.messageID, permission.tool.callID, 'Permission denied')
}
}
await client.respondToPermission(permissionID, response)
const replyToPermission = useCallback(async (
permissionID: string,
sessionID: string,
response: PermissionResponse,
message?: string,
) => {
await replyPermission(sessionID, permissionID, response, message)
removePermission(permissionID, sessionID)
}, [getClient, permissionsBySession, queryClient, removePermission])
}, [removePermission])
const replyToQuestion = useCallback(async (requestID: string, answers: string[][]) => {
const question = Object.values(questionsBySession).flat().find(q => q.id === requestID)
if (!question) throw new Error('Question not found')
const client = getClient(question.sessionID)
if (!client) throw new Error('No client found for session')
await client.replyToQuestion(requestID, answers)
removeQuestion(requestID, question.sessionID)
}, [getClient, questionsBySession, removeQuestion])
const replyToForm = useCallback(async (formID: string, answer: FormAnswer) => {
const form = Object.values(formsBySession).flat().find(f => f.id === formID)
if (!form) throw new Error('Form not found')
await replyForm(form.sessionID, formID, answer)
removeForm(formID, form.sessionID)
}, [formsBySession, removeForm])
const rejectQuestion = useCallback(async (requestID: string) => {
const question = Object.values(questionsBySession).flat().find(q => q.id === requestID)
if (!question) throw new Error('Question not found')
const client = getClient(question.sessionID)
if (!client) throw new Error('No client found for session')
if (question.tool) {
optimisticallyErrorToolPart(queryClient, question.sessionID, question.tool.messageID, question.tool.callID, 'Question rejected')
}
await client.rejectQuestion(requestID)
removeQuestion(requestID, question.sessionID)
}, [getClient, questionsBySession, queryClient, removeQuestion])
const getPermissionForCallID = useCallback((callID: string, sessionID: string): PermissionRequest | null => {
const perms = permissionsBySession[sessionID] ?? []
return perms.find(p => {
const metadata = p.metadata as { tool?: { id?: string } } | undefined
return p.tool?.callID === callID || metadata?.tool?.id === callID
}) ?? null
}, [permissionsBySession])
const getQuestionForCallID = useCallback((callID: string, sessionID: string): QuestionRequest | null => {
const questions = questionsBySession[sessionID] ?? []
return questions.find(q => q.tool?.callID === callID) ?? null
}, [questionsBySession])
const cancelPendingForm = useCallback(async (formID: string) => {
const form = Object.values(formsBySession).flat().find(f => f.id === formID)
if (!form) throw new Error('Form not found')
await cancelForm(form.sessionID, formID)
removeForm(formID, form.sessionID)
}, [formsBySession, removeForm])
const hasPermissionsForSession = useCallback((sessionID: string): boolean => {
return (permissionsBySession[sessionID]?.length ?? 0) > 0
}, [permissionsBySession])
const getQuestionForSession = useCallback((sessionID: string): QuestionRequest | null => {
return questionsBySession[sessionID]?.[0] ?? null
}, [questionsBySession])
const getPermissionForToolCall = useCallback((
toolCallID: string,
messageID?: string,
): PermissionRequest | null => {
const match = allPermissions.find(
(permission) =>
permission.source?.type === 'tool' &&
permission.source.id === toolCallID &&
(messageID === undefined || permission.source.messageID === messageID),
)
return match ?? null
}, [allPermissions])
const hasQuestionsForSession = useCallback((sessionID: string): boolean => {
return (questionsBySession[sessionID]?.length ?? 0) > 0
}, [questionsBySession])
const getFormForSession = useCallback((sessionID: string): FormInfo | null => {
return formsBySession[sessionID]?.[0] ?? null
}, [formsBySession])
const navigateToCurrentQuestion = useCallback(() => {
if (!currentQuestion) return
const repoId = getRepoIdForSession(currentQuestion.sessionID)
const hasFormsForSession = useCallback((sessionID: string): boolean => {
return (formsBySession[sessionID]?.length ?? 0) > 0
}, [formsBySession])
const navigateToCurrentForm = useCallback(() => {
if (!currentForm) return
const repoId = getRepoIdForSession(currentForm.sessionID)
if (repoId) {
const targetPath = `/repos/${repoId}/sessions/${currentQuestion.sessionID}`
const targetPath = `/repos/${repoId}/sessions/${currentForm.sessionID}`
if (window.location.pathname !== targetPath) {
navigate(targetPath)
}
}
}, [currentQuestion, getRepoIdForSession, navigate])
}, [currentForm, getRepoIdForSession, navigate])
const navigateToCurrentPermission = useCallback(() => {
if (!currentPermission) return
@@ -448,97 +336,107 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
}
}, [currentPermission, getRepoIdForSession, navigate])
const fetchInitialPendingData = useCallback(async () => {
const reposToUse = reposRef.current
if (!reposToUse || reposToUse.length === 0) return
const uniqueDirectories = [...new Set(reposToUse.map(r => r.fullPath))]
for (const directory of uniqueDirectories) {
const reconcilePendingActionsForDirectories = useCallback(async (directories: string[]) => {
await Promise.all(directories.map(async (directory) => {
try {
const client = new OpenCodeClient(OPENCODE_API_ENDPOINT, directory)
const pendingPermissions = await client.listPendingPermissions()
reconcilePermissionsForDirectory(directory, pendingPermissions ?? [])
const pendingQuestions = await client.listPendingQuestions()
reconcileQuestionsForDirectory(directory, pendingQuestions ?? [])
const [pendingPermissions, pendingForms] = await Promise.all([
listPendingPermissions(directory),
listPendingForms(directory),
])
reconcilePermissionsForDirectory(directory, pendingPermissions)
reconcileFormsForDirectory(directory, pendingForms)
} catch (error) {
if (import.meta.env.DEV) {
console.warn(`Failed to fetch pending actions for ${directory}:`, error)
}
}
}))
}, [reconcilePermissionsForDirectory, reconcileFormsForDirectory])
const collectTrackedDirectories = useCallback((): string[] => {
const directories = new Set<string>()
for (const repo of reposRef.current ?? []) {
if (repo.fullPath) directories.add(repo.fullPath)
}
}, [reconcilePermissionsForDirectory, reconcileQuestionsForDirectory])
for (const directory of sessionDirectoriesRef.current.values()) {
if (directory) directories.add(directory)
}
return [...directories]
}, [])
const fetchInitialPendingData = useCallback(async () => {
const reposToUse = reposRef.current
if (!reposToUse || reposToUse.length === 0) return
await reconcilePendingActionsForDirectories([...new Set(reposToUse.map(r => r.fullPath))])
}, [reconcilePendingActionsForDirectories])
const syncPermissionsForSession = useCallback(async (directory: string, sessionID: string) => {
const client = new OpenCodeClient(OPENCODE_API_ENDPOINT, directory)
const pendingPermissions = await client.listPendingPermissions()
const pendingPermissions = await listPendingPermissions(directory)
rememberSessionDirectory(sessionID, directory)
reconcilePermissionsForDirectory(directory, pendingPermissions ?? [])
reconcilePermissionsForDirectory(directory, pendingPermissions)
}, [rememberSessionDirectory, reconcilePermissionsForDirectory])
const syncQuestionsForSession = useCallback(async (directory: string, sessionID: string) => {
const client = new OpenCodeClient(OPENCODE_API_ENDPOINT, directory)
const pendingQuestions = await client.listPendingQuestions()
const syncFormsForSession = useCallback(async (directory: string, sessionID: string) => {
const pendingForms = await listPendingForms(directory)
rememberSessionDirectory(sessionID, directory)
reconcileQuestionsForDirectory(directory, pendingQuestions ?? [])
}, [rememberSessionDirectory, reconcileQuestionsForDirectory])
reconcileFormsForDirectory(directory, pendingForms)
}, [rememberSessionDirectory, reconcileFormsForDirectory])
useEffect(() => {
const handleSSEMessage = (data: unknown) => {
if (!data || typeof data !== 'object' || !('type' in data)) return
const event = data as SSEEvent
const event = data as StreamEvent
switch (event.type) {
case 'permission.asked':
if ('permission' in event.properties && 'sessionID' in event.properties) {
rememberSessionDirectory(event.properties.sessionID as string, event.directory)
addPermission(event.properties as PermissionRequest)
}
case 'permission.asked': {
const request = event.data
rememberSessionDirectory(request.sessionID, event.directory)
addPermission(request)
break
case 'permission.replied':
if ('requestID' in event.properties && 'sessionID' in event.properties) {
removePermission(
event.properties.requestID as string,
event.properties.sessionID as string
)
}
}
case 'permission.replied': {
const { requestID, sessionID } = event.data
removePermission(requestID, sessionID)
break
case 'question.asked':
if ('questions' in event.properties && 'sessionID' in event.properties && 'id' in event.properties) {
rememberSessionDirectory(event.properties.sessionID as string, event.directory)
addQuestion(event.properties as QuestionRequest)
}
}
case 'form.created': {
const form = event.data.form
rememberSessionDirectory(form.sessionID, event.directory)
addForm(form)
break
}
case 'form.replied':
case 'form.cancelled': {
const { id, sessionID } = event.data
removeForm(id, sessionID)
break
}
case 'credential.updated':
case 'credential.switched':
case 'integration.updated':
case 'provider.updated':
case 'model.updated':
invalidateProviderCachesDebounced(queryClient)
break
case 'agent.updated':
invalidateQueryKeysDebounced(queryClient, [['opencode', 'agents']])
break
case 'command.updated':
invalidateQueryKeysDebounced(queryClient, [['opencode', 'commands']])
break
case 'config.updated':
invalidateQueryKeysDebounced(queryClient, [['opencode', 'config'], ['opencode-config']])
break
case 'ssh.host-key-request':
if ('requestId' in event.properties && 'host' in event.properties) {
setSSHHostKeyRequest(event.properties as SSHHostKeyRequest)
}
break
case 'question.replied':
case 'question.rejected':
if ('requestID' in event.properties && 'sessionID' in event.properties) {
const sessionID = event.properties.sessionID as string
removeQuestion(
event.properties.requestID as string,
sessionID
)
queryClient.invalidateQueries({
queryKey: ['opencode', 'messages'],
predicate: (query) => query.queryKey.includes(sessionID)
})
}
break
case 'lsp.updated':
queryClient.invalidateQueries({
queryKey: ['opencode', 'lsp']
})
setSSHHostKeyRequest(event.properties)
break
case 'vcs.branch.updated': {
const repo = reposRef.current?.find((candidate) => repoMatchesDirectory(candidate, event.directory))
if (!repo) break
const branch = event.properties.branch
const branch = event.data.branch
if (branch) {
const updatedRepo = { ...repo, currentBranch: branch, branch }
queryClient.setQueryData(['repo', repo.id], updatedRepo)
@@ -560,12 +458,17 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
}
}
const handleResync = () => {
void reconcilePendingActionsForDirectories(collectTrackedDirectories())
}
const initialDirectories = [...new Set((reposRef.current ?? []).map(r => r.fullPath))]
const subscription = openCodeEventStream.subscribeGlobalMonitor({
directories: initialDirectories,
onEvent: handleSSEMessage,
onStatusChange: handleStatusChange,
onHealthChange: handleHealthChange,
onResync: handleResync,
})
subscriptionRef.current = subscription
@@ -573,7 +476,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
subscription.dispose()
subscriptionRef.current = null
}
}, [addPermission, removePermission, addQuestion, removeQuestion, rememberSessionDirectory, fetchInitialPendingData, queryClient, handleHealthChange])
}, [addPermission, removePermission, addForm, removeForm, rememberSessionDirectory, fetchInitialPendingData, queryClient, handleHealthChange, reconcilePendingActionsForDirectories, collectTrackedDirectories])
useEffect(() => {
reposRef.current = repos
@@ -599,55 +502,51 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
permissions: {
current: currentPermission,
pendingCount: allPermissions.length,
respond: respondToPermission,
respond: replyToPermission,
dismiss: removePermission,
getForCallID: getPermissionForCallID,
getForToolCall: getPermissionForToolCall,
hasForSession: hasPermissionsForSession,
showDialog: showPermissionDialog,
setShowDialog: setShowPermissionDialog,
navigateToCurrent: navigateToCurrentPermission,
syncForSession: syncPermissionsForSession,
},
questions: {
current: currentQuestion,
pendingCount: allQuestions.length,
reply: replyToQuestion,
reject: rejectQuestion,
dismiss: removeQuestion,
getForCallID: getQuestionForCallID,
getForSession: getQuestionForSession,
hasForSession: hasQuestionsForSession,
navigateToCurrent: navigateToCurrentQuestion,
syncForSession: syncQuestionsForSession,
forms: {
current: currentForm,
pendingCount: allForms.length,
reply: replyToForm,
cancel: cancelPendingForm,
dismiss: removeForm,
getForSession: getFormForSession,
hasForSession: hasFormsForSession,
navigateToCurrent: navigateToCurrentForm,
syncForSession: syncFormsForSession,
},
sseHealth,
getRepoIdForSession,
getClient,
}), [
sshHostKeyRequest,
respondToSSHHostKey,
currentPermission,
allPermissions.length,
respondToPermission,
replyToPermission,
removePermission,
getPermissionForCallID,
hasPermissionsForSession,
getPermissionForToolCall,
showPermissionDialog,
navigateToCurrentPermission,
syncPermissionsForSession,
currentQuestion,
allQuestions.length,
replyToQuestion,
rejectQuestion,
removeQuestion,
getQuestionForCallID,
getQuestionForSession,
hasQuestionsForSession,
navigateToCurrentQuestion,
syncQuestionsForSession,
currentForm,
allForms.length,
replyToForm,
cancelPendingForm,
removeForm,
getFormForSession,
hasFormsForSession,
navigateToCurrentForm,
syncFormsForSession,
sseHealth,
getRepoIdForSession,
getClient,
])
return <EventContext.Provider value={value}>{children}</EventContext.Provider>
@@ -666,9 +565,17 @@ export function usePermissions() {
return permissions
}
export function useQuestions() {
const { questions } = useEventContext()
return questions
export function useToolCallPermission(
toolCallID: string,
messageID?: string,
): PermissionRequest | null {
const context = useContext(EventContext)
return context?.permissions.getForToolCall(toolCallID, messageID) ?? null
}
export function useForms() {
const { forms } = useEventContext()
return forms
}
export function useSSEHealth(): SSEHealthState {