Refresh Goal reads on plugin.updated, with recovery coverage

This commit is contained in:
Chris Scott committed 2026-11-17 14:44:25 -05:00
1 parent 47066b33b2
commit edd083e417
6 files changed
+295 -6

No files matched your search

+12
View File
@@ -118,6 +118,18 @@ describe('readSessionGoal', () => {
await expect(readSessionGoal(createApi(call), { sessionID: SESSION_ID })).resolves.toEqual({ supported: false })
})
it('reads the goal again after an unavailable rpc', async () => {
const call = vi
.fn<OpenCodeApi['rpc']['call']>()
.mockRejectedValueOnce(rpcError('rpc.unavailable', 'RPC is unavailable: opencode.goal'))
.mockResolvedValueOnce({ output: null })
const api = createApi(call)
await expect(readSessionGoal(api, { sessionID: SESSION_ID })).resolves.toEqual({ supported: false })
await expect(readSessionGoal(api, { sessionID: SESSION_ID })).resolves.toEqual({ supported: true, goal: null })
expect(call).toHaveBeenCalledTimes(2)
})
it('rethrows every other error unchanged', async () => {
const error = rpcError('rpc.failed', 'boom')
const call = vi.fn<OpenCodeApi['rpc']['call']>().mockRejectedValue(error)
+132 -2
View File
@@ -1,6 +1,6 @@
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { useState, type ReactElement } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useLocation } from 'react-router-dom'
import type { FormInfo, GoalState, PermissionRequest } from '@opencode-manager/shared/opencode'
@@ -11,6 +11,7 @@ import type { Repo } from '@/api/types'
import type { OpenCodeServer } from '@opencode-manager/shared/schemas'
import { hasBackgroundActivity, useSessionStatus } from '@/stores/sessionStatusStore'
import { changeWalkthroughQueryKey } from '@/hooks/useChangeWalkthrough'
import { useSessionGoal } from '@/hooks/useSessionGoals'
import type { TestEventStreamTransport } from '@/lib/opencode-event-stream'
import type { FetchFake, FetchRoute, FetchRouteResult, RecordedFetchRequest } from '@/test/fetchFake'
import type { JsonObject } from '@opencode-manager/shared/utils'
@@ -24,6 +25,7 @@ import {
goalChanged,
permissionAsked,
permissionReplied,
pluginUpdated,
sessionCompactionEnded,
sessionCompactionFailed,
sessionCompactionStarted,
@@ -209,6 +211,11 @@ function CacheResolutionHarness({ sessionID }: { sessionID: string }) {
)
}
function GoalReadHarness({ sessionID, directory }: { sessionID: string; directory: string }) {
useSessionGoal(sessionID, directory)
return null
}
interface ApiState {
repos: Repo[]
projects: OpenCodeProject[]
@@ -227,6 +234,7 @@ interface ApiState {
activeResponder: FetchRoute['respond'] | null
sessionResponder: FetchRoute['respond'] | null
serversResponder: FetchRoute['respond'] | null
goalResponder: FetchRoute['respond'] | null
}
function createApiState(overrides: Partial<ApiState> = {}): ApiState {
@@ -248,6 +256,7 @@ function createApiState(overrides: Partial<ApiState> = {}): ApiState {
activeResponder: null,
sessionResponder: null,
serversResponder: null,
goalResponder: null,
...overrides,
}
}
@@ -285,6 +294,8 @@ function providerRoutes(state: ApiState): FetchRoute[] {
{ method: 'POST', path: `${localApi}/session/:sessionID/permission/:permissionID/reply`, respond: () => state.permissionReply },
{ method: 'POST', path: `${localApi}/session/:sessionID/form/:formID/reply`, respond: () => state.formReply },
{ method: 'DELETE', path: `${localApi}/session/:sessionID/form/:formID`, respond: () => state.formCancel },
{ method: 'POST', path: `${localApi}/rpc/opencode.goal/get`, respond: () => state.goalResponder ? state.goalResponder(emptyRequest, {}, undefined) : ({ json: { output: null } }) },
{ method: 'POST', path: `${remoteApi}/rpc/opencode.goal/get`, respond: () => state.goalResponder ? state.goalResponder(emptyRequest, {}, undefined) : ({ json: { output: null } }) },
]
}
@@ -309,6 +320,7 @@ interface RenderProviderOptions {
queryClient?: ReturnType<typeof createTestQueryClient>
auth?: 'anonymous' | 'authenticated'
fakeTimers?: boolean
ui?: ReactElement
}
interface Deferred<T> {
@@ -357,7 +369,7 @@ interface ProviderHarness {
async function renderProvider(options: RenderProviderOptions = {}): Promise<ProviderHarness> {
const api = createApiState(options.api)
const queryClient = options.queryClient ?? createTestQueryClient()
const result = renderWithProviders(<Harness />, {
const result = renderWithProviders(options.ui ?? <Harness />, {
events: true,
route: options.route ?? '/',
auth: options.auth ?? 'authenticated',
@@ -1202,6 +1214,124 @@ describe('EventProvider permissions and forms', () => {
expect(queryClient.getQueryData(['session-goal', 'session-1', '/repo'])).toEqual({ supported: true, goal: updatedGoal })
})
it('refreshes an unavailable goal read on plugin.updated for its directory', async () => {
const goal: GoalState = {
id: 'goal-1',
objective: 'Ship the goal bar',
status: 'active',
rounds: 0,
maxRounds: 10,
boot: 'boot-1',
updatedAt: 1000,
}
let registered = false
const goalResponder: FetchRoute['respond'] = () =>
registered
? { json: { output: goal } }
: {
status: 400,
json: {
_tag: 'RpcError',
type: 'rpc.unavailable',
message: 'RPC is unavailable: opencode.goal',
},
}
const queryClient = createTestQueryClient()
const goalKey = ['session-goal', 'session-1', '/repo']
const harness = await renderProvider({
queryClient,
ui: <GoalReadHarness sessionID="session-1" directory="/repo" />,
api: { goalResponder },
})
await waitFor(() => expect(queryClient.getQueryData(goalKey)).toEqual({ supported: false }))
await waitFor(() => expect(queryClient.getQueryState(goalKey)?.fetchStatus).toBe('idle'))
registered = true
harness.push(pluginUpdated({ directory: '/repo' }))
await waitFor(() => expect(queryClient.getQueryData(goalKey)).toEqual({ supported: true, goal }))
expect(
harness.fetchFake
.findRequests('POST', '/api/opencode/api/rpc/opencode.goal/get')
.every((request) => request.searchParams.get('location[directory]') === '/repo'),
).toBe(true)
})
it('invalidates only goal reads for the event directory on the local server', async () => {
const harness = await renderProvider()
const repoKey = ['session-goal', 'session-1', '/repo']
const otherKey = ['session-goal', 'session-1', '/other']
const remoteKey = ['session-goal', 'session-1', '/repo', 'srv_remote']
harness.queryClient.setQueryData(repoKey, { supported: true, goal: null })
harness.queryClient.setQueryData(otherKey, { supported: true, goal: null })
harness.queryClient.setQueryData(remoteKey, { supported: true, goal: null })
harness.push(pluginUpdated({ directory: '/repo' }))
await waitFor(() => expect(harness.queryClient.getQueryState(repoKey)?.isInvalidated).toBe(true))
expect(harness.queryClient.getQueryState(otherKey)?.isInvalidated).toBe(false)
expect(harness.queryClient.getQueryState(remoteKey)?.isInvalidated).toBe(false)
})
it('invalidates only goal reads for the event server when the event names one', async () => {
const harness = await renderProvider()
const repoKey = ['session-goal', 'session-1', '/repo']
const otherKey = ['session-goal', 'session-1', '/other']
const remoteKey = ['session-goal', 'session-1', '/repo', 'srv_remote']
harness.queryClient.setQueryData(repoKey, { supported: true, goal: null })
harness.queryClient.setQueryData(otherKey, { supported: true, goal: null })
harness.queryClient.setQueryData(remoteKey, { supported: true, goal: null })
harness.push(pluginUpdated({ directory: '/repo', serverId: 'srv_remote' }))
await waitFor(() => expect(harness.queryClient.getQueryState(remoteKey)?.isInvalidated).toBe(true))
expect(harness.queryClient.getQueryState(repoKey)?.isInvalidated).toBe(false)
expect(harness.queryClient.getQueryState(otherKey)?.isInvalidated).toBe(false)
})
it('invalidates every local goal read for a location-less plugin.updated', async () => {
const harness = await renderProvider()
const repoKey = ['session-goal', 'session-1', '/repo']
const otherKey = ['session-goal', 'session-1', '/other']
const remoteKey = ['session-goal', 'session-1', '/repo', 'srv_remote']
harness.queryClient.setQueryData(repoKey, { supported: true, goal: null })
harness.queryClient.setQueryData(otherKey, { supported: true, goal: null })
harness.queryClient.setQueryData(remoteKey, { supported: true, goal: null })
harness.push(pluginUpdated())
await waitFor(() => {
expect(harness.queryClient.getQueryState(repoKey)?.isInvalidated).toBe(true)
expect(harness.queryClient.getQueryState(otherKey)?.isInvalidated).toBe(true)
})
expect(harness.queryClient.getQueryState(remoteKey)?.isInvalidated).toBe(false)
})
it('invalidates cached goal reads when the browser stream connects', async () => {
const queryClient = createTestQueryClient()
queryClient.setQueryData(['session-goal', 'session-1', '/repo'], { supported: false })
await renderProvider({ queryClient })
await waitFor(() =>
expect(queryClient.getQueryState(['session-goal', 'session-1', '/repo'])?.isInvalidated).toBe(true),
)
})
it('invalidates cached goal reads on an upstream resync', async () => {
const harness = await renderProvider()
const goalKey = ['session-goal', 'session-1', '/repo']
harness.queryClient.setQueryData(goalKey, { supported: true, goal: null })
expect(harness.queryClient.getQueryState(goalKey)?.isInvalidated).toBe(false)
await harness.resync()
await waitFor(() => expect(harness.queryClient.getQueryState(goalKey)?.isInvalidated).toBe(true))
})
it('invalidates the sibling caches when a branch changes outside a repo row', async () => {
const harness = await renderProvider()
const invalidateQueries = vi.spyOn(harness.queryClient, 'invalidateQueries')
+8 -1
View File
@@ -41,7 +41,11 @@ import { getServerSessionPath, getSessionPath, parseRepoRoute, parseServerProjec
import { serverScopedKey } from '@/lib/serverScope'
import { repoMatchesDirectory } from '@/components/navigation/sidebar-session-tree'
import { changeWalkthroughQueryKey } from '@/hooks/useChangeWalkthrough'
import { applySessionGoalEvent, SESSION_GOAL_QUERY_ROOT } from '@/hooks/useSessionGoals'
import {
applySessionGoalEvent,
invalidateSessionGoalsForLocation,
SESSION_GOAL_QUERY_ROOT,
} from '@/hooks/useSessionGoals'
import { busyStatusesFromActiveSessions, useSessionStatus } from '@/stores/sessionStatusStore'
import {
invalidateChildSessionCaches,
@@ -1106,6 +1110,9 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
invalidateQueryKeysDebounced(queryClient, [['opencode', 'config'], ['opencode-config']])
invalidateProviderCachesDebounced(queryClient)
break
case 'plugin.updated':
void invalidateSessionGoalsForLocation(queryClient, serverId, event.directory ?? null)
break
case 'ssh.host-key-request':
setSSHHostKeyRequest(event.properties)
break
+121 -1
View File
@@ -1,8 +1,15 @@
import { QueryClient, focusManager } from '@tanstack/react-query'
import { act, screen, waitFor } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { applySessionGoalEvent, useSessionGoal, useSessionGoalCommand } from './useSessionGoals'
import {
applySessionGoalEvent,
invalidateSessionGoalsForLocation,
useSessionGoal,
useSessionGoalCommand,
} from './useSessionGoals'
import { renderHookWithProviders } from '@/test/render'
import { makeSession } from '@/test/fixtures/api'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import type { GoalState, SessionGoalRead } from '@opencode-manager/shared/opencode'
import type { FetchRoute, FetchRouteResult } from '@/test/fetchFake'
@@ -31,6 +38,22 @@ function goalRoute(respond: FetchRoute['respond'] = () => ({ json: { output: goa
return { method: 'POST', path: goalReadPath, respond }
}
const unavailableGoalBody = {
_tag: 'RpcError',
type: 'rpc.unavailable',
message: 'RPC is unavailable: opencode.goal',
}
function unavailableThenGoalRoute(): FetchRoute {
let calls = 0
return goalRoute(() => {
calls += 1
return calls === 1
? { status: 400, json: unavailableGoalBody }
: { json: { output: goal } }
})
}
const commandRoute: FetchRoute = {
method: 'POST',
path: '/api/opencode/api/session/ses_1/command',
@@ -105,6 +128,103 @@ describe('useSessionGoal', () => {
})
})
describe('invalidateSessionGoalsForLocation', () => {
it('recovers an unavailable goal read for the invalidated location', async () => {
const { result, fetchFake, queryClient } = renderHookWithProviders(() => useSessionGoal('ses_1', '/repo'), {
...hookProviders,
fetchRoutes: [unavailableThenGoalRoute()],
})
await waitFor(() => expect(result.current.data).toEqual({ supported: false }))
await act(async () => {
await invalidateSessionGoalsForLocation(queryClient, LOCAL_OPENCODE_SERVER_ID, '/repo')
})
await waitFor(() => expect(result.current.data).toEqual(supportedGoal))
expect(fetchFake.findRequests('POST', goalReadPath)).toHaveLength(2)
})
it('keeps an always-unavailable goal unsupported without retrying', async () => {
const { result, fetchFake, queryClient } = renderHookWithProviders(() => useSessionGoal('ses_1', '/repo'), {
...hookProviders,
fetchRoutes: [goalRoute(() => ({ status: 400, json: unavailableGoalBody }))],
})
await waitFor(() => expect(result.current.data).toEqual({ supported: false }))
await act(async () => {
await invalidateSessionGoalsForLocation(queryClient, LOCAL_OPENCODE_SERVER_ID, '/repo')
})
await waitFor(() => expect(fetchFake.findRequests('POST', goalReadPath)).toHaveLength(2))
expect(result.current.data).toEqual({ supported: false })
vi.useFakeTimers()
try {
await act(async () => {
await vi.advanceTimersByTimeAsync(10_000)
})
expect(fetchFake.findRequests('POST', goalReadPath)).toHaveLength(2)
} finally {
vi.useRealTimers()
}
})
it('recovers an unavailable goal read on window focus', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false, staleTime: 0, refetchOnWindowFocus: true, gcTime: Infinity },
mutations: { retry: false },
},
})
const { result } = renderHookWithProviders(() => useSessionGoal('ses_1', '/repo'), {
...hookProviders,
queryClient,
fetchRoutes: [unavailableThenGoalRoute()],
})
await waitFor(() => expect(result.current.data).toEqual({ supported: false }))
try {
act(() => {
focusManager.setFocused(false)
focusManager.setFocused(true)
})
await waitFor(() => expect(result.current.data).toEqual(supportedGoal))
} finally {
focusManager.setFocused(undefined)
}
})
it('does not refetch or leak data for an inactive query after unmount', async () => {
const pending = deferred()
const { unmount, fetchFake, queryClient } = renderHookWithProviders(() => useSessionGoal('ses_1', '/repo'), {
...hookProviders,
fetchRoutes: [goalRoute(() => pending.promise)],
})
await waitFor(() =>
expect(queryClient.getQueryState(['session-goal', 'ses_1', '/repo'])?.fetchStatus).toBe('fetching'),
)
unmount()
await act(async () => {
await invalidateSessionGoalsForLocation(queryClient, LOCAL_OPENCODE_SERVER_ID, '/repo')
await invalidateSessionGoalsForLocation(queryClient, LOCAL_OPENCODE_SERVER_ID, '/other')
})
expect(fetchFake.findRequests('POST', goalReadPath)).toHaveLength(1)
await act(async () => {
pending.resolve({ json: { output: goal } })
})
expect(queryClient.getQueryData(['session-goal', 'ses_1', '/other'])).toBeUndefined()
})
})
describe('applySessionGoalEvent', () => {
afterEach(() => {
vi.useRealTimers()
+18 -2
View File
@@ -19,9 +19,9 @@ function sessionGoalQueryKey(sessionID: string, directory: string | undefined, s
return serverScopedKey([SESSION_GOAL_QUERY_ROOT, sessionID, directory], serverId)
}
function isSessionGoalQueryFor(query: Query, sessionID: string, serverId: string): boolean {
function isSessionGoalQueryOnServer(query: Query, serverId: string): boolean {
const { queryKey } = query
if (queryKey[0] !== SESSION_GOAL_QUERY_ROOT || queryKey[1] !== sessionID) return false
if (queryKey[0] !== SESSION_GOAL_QUERY_ROOT) return false
if (isLocalOpenCodeServer(serverId)) return queryKey.length === SESSION_GOAL_KEY_BASE_LENGTH
return (
queryKey.length === SESSION_GOAL_KEY_BASE_LENGTH + 1
@@ -29,6 +29,10 @@ function isSessionGoalQueryFor(query: Query, sessionID: string, serverId: string
)
}
function isSessionGoalQueryFor(query: Query, sessionID: string, serverId: string): boolean {
return isSessionGoalQueryOnServer(query, serverId) && query.queryKey[1] === sessionID
}
function sessionGoalQueryPredicate(sessionID: string, serverId: string) {
return (query: Query) => isSessionGoalQueryFor(query, sessionID, serverId)
}
@@ -56,6 +60,18 @@ export function applySessionGoalEvent(
return true
}
export async function invalidateSessionGoalsForLocation(
queryClient: QueryClient,
serverId: string,
directory: string | null,
): Promise<void> {
await queryClient.invalidateQueries({
predicate: (query) =>
isSessionGoalQueryOnServer(query, serverId)
&& (directory === null || query.queryKey[2] === directory),
})
}
type GoalCommandInput = Omit<RunCommandInput, 'name' | 'delivery'> & {
model?: ModelRef
agent?: string
+4
View File
@@ -330,6 +330,10 @@ export function goalChanged(
return withContext(payload, context)
}
export function pluginUpdated(context: StreamEventContext = {}): JsonObject {
return streamEvent('plugin.updated', {}, context)
}
export function sshHostKeyRequest(properties: SSHHostKeyRequest): JsonObject {
return { type: 'ssh.host-key-request', properties }
}