mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 21:04:23 +01:00
refactor(goals): replace the Manager session-goal API with OpenCode built-in /goal
This commit is contained in:
1 parent
c8647c1eec
commit
cbe92c92ad
84 files changed
+2099
-6321
No files matched your search
@@ -1,43 +1,47 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { renderHook, waitFor } from '@testing-library/react'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { useSessionGoal } from './useSessionGoals'
|
||||
import { getLatestSessionGoal } from '@/api/sessionGoals'
|
||||
import type { GoalState, SessionGoalRead } from '@opencode-manager/shared/opencode'
|
||||
import { OpenCodeServerProvider } from '@/contexts/OpenCodeServerContext'
|
||||
import type { SessionGoal, SessionGoalStatus } from '@opencode-manager/shared/schemas'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { applySessionGoalEvent, useSessionGoal, useSessionGoalCommand } from './useSessionGoals'
|
||||
|
||||
vi.mock('@/api/sessionGoals', () => ({
|
||||
getLatestSessionGoal: vi.fn(),
|
||||
startSessionGoal: vi.fn(),
|
||||
pauseSessionGoal: vi.fn(),
|
||||
resumeSessionGoal: vi.fn(),
|
||||
cancelSessionGoal: vi.fn(),
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getSessionGoal: vi.fn(),
|
||||
runCommand: vi.fn(),
|
||||
syncSelection: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', () => ({
|
||||
getSessionGoal: mocks.getSessionGoal,
|
||||
runCommand: mocks.runCommand,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCode', () => ({
|
||||
useSyncSessionSelection: () => mocks.syncSelection,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: { error: vi.fn() },
|
||||
}))
|
||||
|
||||
const baseGoal: SessionGoal = {
|
||||
id: 1,
|
||||
sessionId: 'ses_1',
|
||||
serverId: 'local',
|
||||
directory: '/repo',
|
||||
const goal: GoalState = {
|
||||
id: 'goal_1',
|
||||
objective: 'Ship the feature',
|
||||
status: 'active',
|
||||
stopReason: null,
|
||||
turnState: 'running',
|
||||
continuationCount: 0,
|
||||
maxContinuations: 20,
|
||||
tokenBudget: null,
|
||||
tokensUsed: 0,
|
||||
consecutiveBlocked: 0,
|
||||
lastVerdict: null,
|
||||
lastReason: null,
|
||||
createdAt: 1,
|
||||
rounds: 2,
|
||||
maxRounds: 50,
|
||||
boot: 'boot_1',
|
||||
updatedAt: 1,
|
||||
finishedAt: null,
|
||||
}
|
||||
|
||||
const updatedGoal: GoalState = { ...goal, rounds: 3 }
|
||||
|
||||
const supportedGoal: SessionGoalRead = { supported: true, goal }
|
||||
|
||||
function createQueryClient() {
|
||||
return new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
}
|
||||
|
||||
function createWrapper(queryClient: QueryClient, serverId?: string) {
|
||||
@@ -51,36 +55,190 @@ function createWrapper(queryClient: QueryClient, serverId?: string) {
|
||||
describe('useSessionGoal', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.getSessionGoal.mockResolvedValue(supportedGoal)
|
||||
})
|
||||
|
||||
it('polls only while the goal is active', async () => {
|
||||
vi.mocked(getLatestSessionGoal).mockResolvedValue(baseGoal)
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
renderHook(() => useSessionGoal('ses_1'), { wrapper: createWrapper(queryClient) })
|
||||
it('reads the goal from the local server', async () => {
|
||||
const queryClient = createQueryClient()
|
||||
const { result } = renderHook(() => useSessionGoal('ses_1', '/repo'), { wrapper: createWrapper(queryClient) })
|
||||
|
||||
await waitFor(() => expect(getLatestSessionGoal).toHaveBeenCalled())
|
||||
await waitFor(() => expect(result.current.data).toEqual(supportedGoal))
|
||||
|
||||
const query = queryClient.getQueryCache().find({ queryKey: ['session-goal', 'ses_1'] })
|
||||
const refetchInterval = query?.options.refetchInterval as
|
||||
| ((query: { state: { data?: { status: SessionGoalStatus } } }) => number | false)
|
||||
| undefined
|
||||
|
||||
expect(refetchInterval).toBeTypeOf('function')
|
||||
expect(refetchInterval!({ state: { data: { status: 'active' } } })).toBe(3000)
|
||||
expect(refetchInterval!({ state: { data: { status: 'paused' } } })).toBe(false)
|
||||
expect(refetchInterval!({ state: { data: { status: 'completed' } } })).toBe(false)
|
||||
expect(refetchInterval!({ state: { data: { status: 'blocked' } } })).toBe(false)
|
||||
expect(refetchInterval!({ state: { data: { status: 'stopped' } } })).toBe(false)
|
||||
expect(refetchInterval!({ state: {} })).toBe(false)
|
||||
expect(mocks.getSessionGoal).toHaveBeenCalledWith('ses_1', '/repo', 'local')
|
||||
})
|
||||
|
||||
it('reads the goal for the current server and scopes its cache key', async () => {
|
||||
vi.mocked(getLatestSessionGoal).mockResolvedValue({ ...baseGoal, serverId: 'srv_remote' })
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
renderHook(() => useSessionGoal('ses_1'), { wrapper: createWrapper(queryClient, 'srv_remote') })
|
||||
it('reads the goal from the current remote server and scopes its cache key', async () => {
|
||||
const queryClient = createQueryClient()
|
||||
const { result } = renderHook(() => useSessionGoal('ses_1', '/repo'), {
|
||||
wrapper: createWrapper(queryClient, 'srv_remote'),
|
||||
})
|
||||
|
||||
await waitFor(() => expect(getLatestSessionGoal).toHaveBeenCalledWith('ses_1', 'srv_remote'))
|
||||
await waitFor(() => expect(result.current.data).toEqual(supportedGoal))
|
||||
|
||||
expect(mocks.getSessionGoal).toHaveBeenCalledWith('ses_1', '/repo', 'srv_remote')
|
||||
expect(queryClient.getQueryCache().find({ queryKey: ['session-goal', 'ses_1', 'srv_remote'] })).toBeDefined()
|
||||
})
|
||||
|
||||
it('does not poll for goal updates', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const queryClient = createQueryClient()
|
||||
renderHook(() => useSessionGoal('ses_1', '/repo'), { wrapper: createWrapper(queryClient) })
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(10_000)
|
||||
})
|
||||
|
||||
expect(mocks.getSessionGoal).toHaveBeenCalledTimes(1)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('applySessionGoalEvent', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.getSessionGoal.mockResolvedValue(supportedGoal)
|
||||
})
|
||||
|
||||
it('updates the cached goal without refetching', async () => {
|
||||
const queryClient = createQueryClient()
|
||||
const { result } = renderHook(() => useSessionGoal('ses_1', '/repo'), { wrapper: createWrapper(queryClient) })
|
||||
|
||||
await waitFor(() => expect(result.current.data).toEqual(supportedGoal))
|
||||
|
||||
let applied = false
|
||||
await act(async () => {
|
||||
applied = applySessionGoalEvent(
|
||||
queryClient,
|
||||
{ type: 'rpc.opencode.goal.changed', data: { sessionID: 'ses_1', goal: updatedGoal } },
|
||||
'local',
|
||||
)
|
||||
})
|
||||
|
||||
expect(applied).toBe(true)
|
||||
await waitFor(() => expect(result.current.data).toEqual({ supported: true, goal: updatedGoal }))
|
||||
expect(mocks.getSessionGoal).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('ignores unrelated events and leaves the cached goal unchanged', async () => {
|
||||
const queryClient = createQueryClient()
|
||||
const { result } = renderHook(() => useSessionGoal('ses_1', '/repo'), { wrapper: createWrapper(queryClient) })
|
||||
|
||||
await waitFor(() => expect(result.current.data).toEqual(supportedGoal))
|
||||
|
||||
let applied = true
|
||||
await act(async () => {
|
||||
applied = applySessionGoalEvent(queryClient, { type: 'session.idle', data: { sessionID: 'ses_1' } }, 'local')
|
||||
})
|
||||
|
||||
expect(applied).toBe(false)
|
||||
expect(result.current.data).toEqual(supportedGoal)
|
||||
expect(mocks.getSessionGoal).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('writes the change under the event server scoped key', async () => {
|
||||
const queryClient = createQueryClient()
|
||||
|
||||
await act(async () => {
|
||||
applySessionGoalEvent(
|
||||
queryClient,
|
||||
{ type: 'rpc.opencode.goal.changed', data: { sessionID: 'ses_1', goal: updatedGoal } },
|
||||
'srv_remote',
|
||||
)
|
||||
})
|
||||
|
||||
expect(queryClient.getQueryData(['session-goal', 'ses_1', 'srv_remote'])).toEqual({
|
||||
supported: true,
|
||||
goal: updatedGoal,
|
||||
})
|
||||
expect(queryClient.getQueryData(['session-goal', 'ses_1'])).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps the event goal when an in-flight read resolves afterwards', async () => {
|
||||
const queryClient = createQueryClient()
|
||||
let resolveRead: (value: SessionGoalRead) => void = () => {}
|
||||
mocks.getSessionGoal.mockImplementation(
|
||||
() => new Promise<SessionGoalRead>((resolve) => {
|
||||
resolveRead = resolve
|
||||
}),
|
||||
)
|
||||
|
||||
const { result } = renderHook(() => useSessionGoal('ses_1', '/repo'), { wrapper: createWrapper(queryClient) })
|
||||
|
||||
await waitFor(() => expect(mocks.getSessionGoal).toHaveBeenCalledTimes(1))
|
||||
|
||||
act(() => {
|
||||
applySessionGoalEvent(
|
||||
queryClient,
|
||||
{ type: 'rpc.opencode.goal.changed', data: { sessionID: 'ses_1', goal: updatedGoal } },
|
||||
'local',
|
||||
)
|
||||
})
|
||||
|
||||
await waitFor(() => expect(result.current.data).toEqual({ supported: true, goal: updatedGoal }))
|
||||
|
||||
await act(async () => {
|
||||
resolveRead(supportedGoal)
|
||||
await Promise.resolve()
|
||||
})
|
||||
|
||||
expect(result.current.data).toEqual({ supported: true, goal: updatedGoal })
|
||||
})
|
||||
})
|
||||
|
||||
describe('useSessionGoalCommand', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.runCommand.mockResolvedValue(undefined)
|
||||
mocks.syncSelection.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('runs the goal command on the session', async () => {
|
||||
const { result } = renderHook(() => useSessionGoalCommand('/repo'), {
|
||||
wrapper: createWrapper(createQueryClient()),
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
await result.current.mutateAsync({ sessionID: 'ses_1', text: 'Ship it' })
|
||||
})
|
||||
|
||||
expect(mocks.runCommand).toHaveBeenCalledWith({ sessionID: 'ses_1', name: 'goal', text: 'Ship it' }, 'local')
|
||||
})
|
||||
|
||||
it('syncs the session selection before running the goal command', async () => {
|
||||
const calls: string[] = []
|
||||
mocks.syncSelection.mockImplementation(async () => {
|
||||
calls.push('syncSelection')
|
||||
})
|
||||
mocks.runCommand.mockImplementation(async () => {
|
||||
calls.push('runCommand')
|
||||
})
|
||||
const model = { providerID: 'anthropic', modelID: 'claude-sonnet-4' }
|
||||
const { result } = renderHook(() => useSessionGoalCommand('/repo'), {
|
||||
wrapper: createWrapper(createQueryClient()),
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
await result.current.mutateAsync({ sessionID: 'ses_1', text: 'Ship it', model, agent: 'build' })
|
||||
})
|
||||
|
||||
expect(mocks.syncSelection).toHaveBeenCalledWith({ sessionID: 'ses_1', model, agent: 'build' })
|
||||
expect(calls).toEqual(['syncSelection', 'runCommand'])
|
||||
expect(mocks.runCommand).toHaveBeenCalledWith({ sessionID: 'ses_1', name: 'goal', text: 'Ship it' }, 'local')
|
||||
})
|
||||
|
||||
it('reports the command failure message', async () => {
|
||||
mocks.runCommand.mockRejectedValueOnce(new Error('goal command failed'))
|
||||
const { result } = renderHook(() => useSessionGoalCommand('/repo'), {
|
||||
wrapper: createWrapper(createQueryClient()),
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
await result.current.mutateAsync({ sessionID: 'ses_1', text: 'Ship it' }).catch(() => undefined)
|
||||
})
|
||||
|
||||
await waitFor(() => expect(showToast.error).toHaveBeenCalledWith('goal command failed'))
|
||||
})
|
||||
})
|
||||
@@ -1,62 +1,86 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
cancelSessionGoal,
|
||||
getLatestSessionGoal,
|
||||
pauseSessionGoal,
|
||||
resumeSessionGoal,
|
||||
startSessionGoal,
|
||||
} from '@/api/sessionGoals'
|
||||
import { useMutation, useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query'
|
||||
import { getSessionGoal, runCommand, type RunCommandInput } from '@/api/opencode'
|
||||
import { useOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
|
||||
import { useSyncSessionSelection } from '@/hooks/useOpenCode'
|
||||
import { serverScopedKey } from '@/lib/serverScope'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { SESSION_GOAL_POLL_INTERVAL_MS, type SessionGoal, type StartSessionGoalRequest } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
GOAL_COMMAND_NAME,
|
||||
goalChangeFromEvent,
|
||||
type ModelRef,
|
||||
type SessionGoalRead,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
|
||||
function sessionGoalQueryKey(sessionId: string, serverId: string) {
|
||||
return serverScopedKey(['session-goal', sessionId], serverId)
|
||||
/** Root segment shared by every session goal query key. */
|
||||
export const SESSION_GOAL_QUERY_ROOT = 'session-goal'
|
||||
|
||||
function sessionGoalQueryKey(sessionID: string, serverId: string) {
|
||||
return serverScopedKey([SESSION_GOAL_QUERY_ROOT, sessionID], serverId)
|
||||
}
|
||||
|
||||
export function useSessionGoal(sessionId: string, options: { enabled?: boolean } = {}) {
|
||||
/**
|
||||
* Reads the goal of a session through the OpenCode goal RPC.
|
||||
*
|
||||
* @param sessionID The session whose goal is read.
|
||||
* @param directory Directory of the session's project, once it is known.
|
||||
* @returns The query holding the goal, or an unsupported result when the server has no goal RPC.
|
||||
*/
|
||||
export function useSessionGoal(sessionID: string, directory: string | undefined) {
|
||||
const serverId = useOpenCodeServerId()
|
||||
return useQuery({
|
||||
queryKey: sessionGoalQueryKey(sessionId, serverId),
|
||||
queryFn: () => getLatestSessionGoal(sessionId, serverId),
|
||||
enabled: options.enabled ?? true,
|
||||
refetchInterval: (query) => (query.state.data?.status === 'active' ? SESSION_GOAL_POLL_INTERVAL_MS : false),
|
||||
return useQuery<SessionGoalRead>({
|
||||
queryKey: sessionGoalQueryKey(sessionID, serverId),
|
||||
queryFn: () => getSessionGoal(sessionID, directory, serverId),
|
||||
enabled: Boolean(directory),
|
||||
})
|
||||
}
|
||||
|
||||
function useGoalMutation<TInput>(
|
||||
mutationFn: (input: TInput) => Promise<SessionGoal>,
|
||||
errorMessage: string,
|
||||
) {
|
||||
/**
|
||||
* Applies a goal change event to the session's cached goal.
|
||||
*
|
||||
* @param queryClient Cache that holds the session goal.
|
||||
* @param event Event received from the OpenCode server.
|
||||
* @param serverId Server that owns the session.
|
||||
* @returns Whether the event was a goal change and updated the cache.
|
||||
*/
|
||||
export function applySessionGoalEvent(
|
||||
queryClient: QueryClient,
|
||||
event: { type: string; data: unknown },
|
||||
serverId: string,
|
||||
): boolean {
|
||||
const change = goalChangeFromEvent(event)
|
||||
if (!change) return false
|
||||
const nextGoal: SessionGoalRead = { supported: true, goal: change.goal }
|
||||
const queryKey = sessionGoalQueryKey(change.sessionID, serverId)
|
||||
void queryClient.cancelQueries({ queryKey })
|
||||
queryClient.setQueryData<SessionGoalRead>(queryKey, nextGoal)
|
||||
return true
|
||||
}
|
||||
|
||||
type GoalCommandInput = Omit<RunCommandInput, 'name' | 'delivery'> & {
|
||||
model?: ModelRef
|
||||
agent?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the `/goal` command on a session and refreshes the session's goal afterwards.
|
||||
*
|
||||
* @param directory Directory of the session's project, used to sync the session model and agent.
|
||||
* @returns The mutation that sends the goal command.
|
||||
*/
|
||||
export function useSessionGoalCommand(directory: string | undefined) {
|
||||
const serverId = useOpenCodeServerId()
|
||||
const queryClient = useQueryClient()
|
||||
const syncSelection = useSyncSessionSelection(directory)
|
||||
return useMutation({
|
||||
mutationFn,
|
||||
onSuccess: (goal: SessionGoal) => {
|
||||
queryClient.setQueryData(sessionGoalQueryKey(goal.sessionId, goal.serverId), goal)
|
||||
mutationFn: async ({ model, agent, ...command }: GoalCommandInput) => {
|
||||
await syncSelection({ sessionID: command.sessionID, model, agent })
|
||||
await runCommand({ ...command, name: GOAL_COMMAND_NAME }, serverId)
|
||||
},
|
||||
onError: (error: unknown) => {
|
||||
showToast.error(error instanceof Error ? error.message : errorMessage)
|
||||
onSuccess: (_result, input) => {
|
||||
void queryClient.invalidateQueries({ queryKey: sessionGoalQueryKey(input.sessionID, serverId) })
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
showToast.error(error.message ?? 'Goal command failed')
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useStartSessionGoal() {
|
||||
const serverId = useOpenCodeServerId()
|
||||
return useGoalMutation(
|
||||
(input: StartSessionGoalRequest) => startSessionGoal({ ...input, serverId }),
|
||||
'Failed to start goal',
|
||||
)
|
||||
}
|
||||
|
||||
export function usePauseSessionGoal() {
|
||||
return useGoalMutation(pauseSessionGoal, 'Failed to pause goal')
|
||||
}
|
||||
|
||||
export function useResumeSessionGoal() {
|
||||
return useGoalMutation(resumeSessionGoal, 'Failed to resume goal')
|
||||
}
|
||||
|
||||
export function useCancelSessionGoal() {
|
||||
return useGoalMutation(cancelSessionGoal, 'Failed to cancel goal')
|
||||
}
|
||||
Reference in new issue
Block a user