refactor(goals): replace the Manager session-goal API with OpenCode built-in /goal

This commit is contained in:
Chris Scott committed 2026-10-29 12:38:39 -04:00
1 parent c8647c1eec
commit cbe92c92ad
84 files changed
+2099 -6321

No files matched your search

+18 -1
View File
@@ -1,4 +1,4 @@
import { openCodeLocation, parseOpenCodeModelRef } from '@opencode-manager/shared/opencode'
import { openCodeLocation, parseOpenCodeModelRef, readSessionGoal } from '@opencode-manager/shared/opencode'
import { MANAGER_PROMPT_CLIENT_METADATA_KEY } from '@opencode-manager/shared/schemas'
import { isMobileViewport } from '@/hooks/useMobile'
import { getDirectoryName } from '@/lib/utils'
@@ -11,6 +11,7 @@ import type {
ModelRef,
OpenCodeApi,
PermissionRequest,
SessionGoalRead,
SessionInboxCompaction,
SessionInboxUser,
SessionInfo,
@@ -231,6 +232,22 @@ export async function getSession(sessionID: string, serverId?: string): Promise<
return callOpenCode((api) => api.session.get({ sessionID }), serverId)
}
/**
* Reads a session goal 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.
* @param serverId Server that owns the session, when it is not the local one.
* @returns The goal, or an unsupported result when the server has no goal RPC.
*/
export async function getSessionGoal(
sessionID: string,
directory: string | undefined,
serverId?: string,
): Promise<SessionGoalRead> {
return callOpenCode((api) => readSessionGoal(api, { sessionID, directory }), serverId)
}
export async function createSession(input: CreateSessionInput, serverId?: string): Promise<SessionInfo> {
const model = input.model ? parseOpenCodeModelRef(input.model) : undefined
return callOpenCode(
-46
View File
@@ -1,46 +0,0 @@
import { fetchWrapper } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import {
LOCAL_OPENCODE_SERVER_ID,
type SessionGoal,
type StartSessionGoalRequest,
} from '@opencode-manager/shared/schemas'
export async function getLatestSessionGoal(
sessionId: string,
serverId: string = LOCAL_OPENCODE_SERVER_ID,
): Promise<SessionGoal | null> {
const res = await fetchWrapper<{ goal: SessionGoal | null }>(`${API_BASE_URL}/api/session-goals`, {
params: { sessionId, serverId },
})
return res.goal
}
export async function startSessionGoal(input: StartSessionGoalRequest): Promise<SessionGoal> {
const res = await fetchWrapper<{ goal: SessionGoal }>(`${API_BASE_URL}/api/session-goals`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input),
})
return res.goal
}
async function runGoalAction(id: number, action: 'pause' | 'resume' | 'cancel'): Promise<SessionGoal> {
const res = await fetchWrapper<{ goal: SessionGoal }>(
`${API_BASE_URL}/api/session-goals/${encodeURIComponent(id)}/${action}`,
{ method: 'POST' },
)
return res.goal
}
export function pauseSessionGoal(id: number): Promise<SessionGoal> {
return runGoalAction(id, 'pause')
}
export function resumeSessionGoal(id: number): Promise<SessionGoal> {
return runGoalAction(id, 'resume')
}
export function cancelSessionGoal(id: number): Promise<SessionGoal> {
return runGoalAction(id, 'cancel')
}
@@ -103,7 +103,7 @@ vi.mock('@/components/session/PermissionModeToggle', () => ({
vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: () => ({ data: undefined }),
useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }),
useSessionGoalCommand: () => ({ mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false }),
}))
vi.mock('@/hooks/useSessionPermissionMode', () => ({
@@ -95,7 +95,7 @@ vi.mock('./ComposerToolsMenu', () => ({
vi.mock('./PromptSuggestions', () => ({ PromptSuggestions: () => null }))
vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: () => ({ data: undefined }),
useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }),
useSessionGoalCommand: () => ({ mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false }),
}))
vi.mock('@/hooks/useSessionPermissionMode', () => ({ useSessionPermissionMode: () => ({ data: undefined }) }))
@@ -82,7 +82,7 @@ vi.mock('./ComposerToolsMenu', () => ({ ComposerToolsMenu: () => null }))
vi.mock('./PromptSuggestions', () => ({ PromptSuggestions: () => null }))
vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: () => ({ data: undefined }),
useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }),
useSessionGoalCommand: () => ({ mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false }),
}))
vi.mock('@/hooks/useSessionPermissionMode', () => ({ useSessionPermissionMode: () => ({ data: undefined }) }))
@@ -9,7 +9,9 @@ const mocks = vi.hoisted(() => ({
sendPrompt: vi.fn(),
sendShell: vi.fn(),
interrupt: vi.fn(),
startGoal: vi.fn(),
runCommand: vi.fn(),
syncSelection: vi.fn(),
getSessionGoal: vi.fn(),
useSessionGoal: vi.fn(),
useSessionPermissionMode: vi.fn(),
agents: [] as Array<{ id: string; name: string; description?: string; mode?: string; hidden?: boolean }>,
@@ -48,27 +50,24 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
useAgents: () => ({ data: mocks.agents }),
useSkills: () => ({ data: mocks.skills }),
useSession: () => ({ data: undefined }),
useSyncSessionSelection: () => mocks.syncSelection,
}
})
vi.mock('@/hooks/useSessionGoals', async () => {
const { useState } = await import('react')
vi.mock('@/api/opencode', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/api/opencode')>()
return {
...actual,
runCommand: mocks.runCommand,
getSessionGoal: mocks.getSessionGoal,
}
})
vi.mock('@/hooks/useSessionGoals', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/hooks/useSessionGoals')>()
return {
...actual,
useSessionGoal: mocks.useSessionGoal,
useStartSessionGoal: () => {
const [isPending, setIsPending] = useState(false)
return {
mutateAsync: async (variables: unknown) => {
setIsPending(true)
try {
return await mocks.startGoal(variables)
} finally {
setIsPending(false)
}
},
isPending,
}
},
}
})
@@ -142,6 +141,17 @@ const createTestQueryClient = () => new QueryClient({
const GOAL_BUTTON = 'Goal mode: the next message becomes the objective'
const OPEN_GOAL_BUTTON = 'A goal is already active for this session'
const UNSUPPORTED_GOAL_BUTTON = "This server's OpenCode has no goals"
const goalState = {
id: 'goal_1',
objective: 'Ship the feature',
status: 'active',
rounds: 1,
maxRounds: 50,
boot: 'boot_1',
updatedAt: 1,
}
describe('PromptInput goal mode', () => {
const defaultProps = {
@@ -167,9 +177,11 @@ describe('PromptInput goal mode', () => {
vi.clearAllMocks()
useComposerDraftStore.setState({ drafts: {} })
mocks.useVoiceConversation.mockReturnValue(createVoiceConversationControllerMock())
mocks.useSessionGoal.mockReturnValue({ data: null })
mocks.useSessionGoal.mockReturnValue({ data: { supported: true, goal: null } })
mocks.useSessionPermissionMode.mockReturnValue({ data: undefined })
mocks.startGoal.mockResolvedValue({ id: 1 })
mocks.runCommand.mockResolvedValue(undefined)
mocks.syncSelection.mockResolvedValue(undefined)
mocks.getSessionGoal.mockResolvedValue({ supported: true, goal: null })
mocks.sendPrompt.mockResolvedValue({ id: 'inbox_1' })
mocks.sendShell.mockResolvedValue({ id: 'shell_1' })
mocks.agents = []
@@ -190,6 +202,7 @@ describe('PromptInput goal mode', () => {
mocks.useFileSearch.mockReturnValue({ files: [] })
mocks.useModelSelection.mockReturnValue({
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
modelRef: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
modelString: 'anthropic/claude-sonnet-4',
setModel: vi.fn(),
setActiveAgent: vi.fn(),
@@ -209,7 +222,7 @@ describe('PromptInput goal mode', () => {
Reflect.deleteProperty(window, 'matchMedia')
})
it('starts a goal with the message objective before sending it', async () => {
it('runs the goal command with the message objective instead of sending the prompt', async () => {
stubMatchMedia(true)
renderComponent()
@@ -218,42 +231,19 @@ describe('PromptInput goal mode', () => {
fireEvent.click(screen.getByRole('button', { name: GOAL_BUTTON }))
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.startGoal).toHaveBeenCalledWith({
sessionId: 'test-session',
directory: '/test',
objective: 'Ship the feature',
}))
await waitFor(() => expect(mocks.sendPrompt).toHaveBeenCalled())
expect(mocks.startGoal.mock.invocationCallOrder[0]).toBeLessThan(mocks.sendPrompt.mock.invocationCallOrder[0])
})
it('does not send the message when starting the goal is rejected', async () => {
stubMatchMedia(true)
mocks.startGoal.mockRejectedValue(new Error('This session already has an open goal'))
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: 'Ship the feature' } })
fireEvent.click(screen.getByRole('button', { name: GOAL_BUTTON }))
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.startGoal).toHaveBeenCalled())
await waitFor(() => expect(mocks.runCommand).toHaveBeenCalledTimes(1))
expect(mocks.runCommand).toHaveBeenCalledWith({
sessionID: 'test-session',
name: 'goal',
text: 'Ship the feature',
files: [],
agents: [],
skills: [],
}, 'local')
expect(mocks.sendPrompt).not.toHaveBeenCalled()
})
it('does not start a goal when the mode was not armed', async () => {
stubMatchMedia(true)
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: 'Just a message' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.sendPrompt).toHaveBeenCalled())
expect(mocks.startGoal).not.toHaveBeenCalled()
})
it('starts an armed goal before queueing when the session is busy', async () => {
it('runs the goal command instead of queueing when the session is busy', async () => {
stubMatchMedia(true)
renderComponent({ isStreamingResponse: true })
@@ -262,23 +252,99 @@ describe('PromptInput goal mode', () => {
fireEvent.click(screen.getByRole('button', { name: GOAL_BUTTON }))
fireEvent.click(screen.getByTitle('Queue message'))
await waitFor(() => expect(mocks.startGoal).toHaveBeenCalledWith({
sessionId: 'test-session',
directory: '/test',
objective: 'Ship the feature',
}))
await waitFor(() => expect(mocks.sendPrompt).toHaveBeenCalledWith(
expect.objectContaining({ delivery: 'queue' }),
))
expect(mocks.startGoal.mock.invocationCallOrder[0]).toBeLessThan(mocks.sendPrompt.mock.invocationCallOrder[0])
await waitFor(() => expect(mocks.runCommand).toHaveBeenCalledTimes(1))
expect(mocks.runCommand).toHaveBeenCalledWith({
sessionID: 'test-session',
name: 'goal',
text: 'Ship the feature',
files: [],
agents: [],
skills: [],
}, 'local')
expect(mocks.sendPrompt).not.toHaveBeenCalled()
})
it('does not start the goal again while it is still starting', async () => {
it('does not send the prompt when the goal command is rejected', async () => {
stubMatchMedia(true)
let resolveGoal: (value: unknown) => void = () => {}
mocks.startGoal.mockImplementation(
mocks.runCommand.mockRejectedValue(new Error('goal command failed'))
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: 'Ship the feature' } })
fireEvent.click(screen.getByRole('button', { name: GOAL_BUTTON }))
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.runCommand).toHaveBeenCalledTimes(1))
expect(mocks.sendPrompt).not.toHaveBeenCalled()
})
it('passes the selected model and agent to the goal selection sync', async () => {
stubMatchMedia(true)
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: 'Ship the feature' } })
fireEvent.click(screen.getByRole('button', { name: GOAL_BUTTON }))
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.syncSelection).toHaveBeenCalledWith({
sessionID: 'test-session',
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
agent: 'build',
}))
expect(mocks.runCommand).toHaveBeenCalled()
})
it('keeps the image draft and warns when an armed goal has no objective', async () => {
stubMatchMedia(true)
const { container } = renderComponent()
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement
fireEvent.change(fileInput, { target: { files: [new File(['img'], 'pic.png', { type: 'image/png' })] } })
await screen.findByText('pic.png')
fireEvent.click(screen.getByRole('button', { name: GOAL_BUTTON }))
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.showToast.error).toHaveBeenCalledWith('Enter an objective for the goal'))
expect(mocks.runCommand).not.toHaveBeenCalled()
expect(mocks.sendPrompt).not.toHaveBeenCalled()
expect(screen.getByText('pic.png')).toBeInTheDocument()
})
it('keeps a whitespace-only draft and warns when an armed goal has no objective', async () => {
stubMatchMedia(true)
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: ' ' } })
fireEvent.click(screen.getByRole('button', { name: GOAL_BUTTON }))
fireEvent.keyDown(input, { key: 'Enter', ctrlKey: true })
await waitFor(() => expect(mocks.showToast.error).toHaveBeenCalledWith('Enter an objective for the goal'))
expect(mocks.runCommand).not.toHaveBeenCalled()
expect(mocks.sendPrompt).not.toHaveBeenCalled()
expect(input).toHaveValue(' ')
})
it('sends the prompt without the goal command when the goal mode was not armed', async () => {
stubMatchMedia(true)
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: 'Just a message' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.sendPrompt).toHaveBeenCalled())
expect(mocks.runCommand).not.toHaveBeenCalled()
})
it('does not run the goal command again while it is still pending', async () => {
stubMatchMedia(true)
let resolveCommand: (value: unknown) => void = () => {}
mocks.runCommand.mockImplementation(
() => new Promise((resolve) => {
resolveGoal = resolve
resolveCommand = resolve
}),
)
renderComponent({ isStreamingResponse: true })
@@ -288,19 +354,19 @@ describe('PromptInput goal mode', () => {
fireEvent.click(screen.getByRole('button', { name: GOAL_BUTTON }))
fireEvent.click(screen.getByTitle('Queue message'))
await waitFor(() => expect(mocks.startGoal).toHaveBeenCalledTimes(1))
await waitFor(() => expect(mocks.runCommand).toHaveBeenCalledTimes(1))
fireEvent.click(screen.getByTitle('Queue message'))
expect(mocks.startGoal).toHaveBeenCalledTimes(1)
expect(mocks.runCommand).toHaveBeenCalledTimes(1)
expect(mocks.sendPrompt).not.toHaveBeenCalled()
await act(async () => {
resolveGoal({ id: 1 })
resolveCommand(undefined)
})
})
it('does not start an armed goal for a slash command', async () => {
it('sends an exact slash command without running the goal command', async () => {
stubMatchMedia(true)
mocks.useCommands.mockReturnValue({
searchCommands: () => [],
@@ -315,27 +381,36 @@ describe('PromptInput goal mode', () => {
fireEvent.click(screen.getByTitle('Queue message'))
await waitFor(() => expect(mocks.sendPrompt).toHaveBeenCalled())
expect(mocks.startGoal).not.toHaveBeenCalled()
expect(mocks.runCommand).not.toHaveBeenCalled()
})
it('disables goal mode when the server has no goal support', async () => {
stubMatchMedia(true)
mocks.useSessionGoal.mockReturnValue({ data: { supported: false } })
renderComponent()
const button = await screen.findByRole('button', { name: UNSUPPORTED_GOAL_BUTTON })
expect(button).toBeDisabled()
})
it('disables goal mode while a goal is already active', async () => {
stubMatchMedia(true)
mocks.useSessionGoal.mockReturnValue({ data: { status: 'active' } })
mocks.useSessionGoal.mockReturnValue({ data: { supported: true, goal: goalState } })
renderComponent()
const button = await screen.findByRole('button', { name: OPEN_GOAL_BUTTON })
expect(button).toBeDisabled()
})
it('disables goal mode with a reason for scheduled-run sessions', async () => {
it('keeps goal mode enabled on child sessions', async () => {
stubMatchMedia(true)
mocks.useSessionPermissionMode.mockReturnValue({
data: { sessionId: 'test-session', rootSessionId: 'test-session', mode: 'ask', lockedReason: 'schedule' },
data: { sessionId: 'test-session', rootSessionId: 'test-session', mode: 'ask', lockedReason: 'child' },
})
renderComponent()
const button = await screen.findByRole('button', { name: 'Scheduled runs cannot run goals' })
expect(button).toBeDisabled()
const button = await screen.findByRole('button', { name: GOAL_BUTTON })
expect(button).toBeEnabled()
})
it('keeps permission and goal toggles inline on desktop', async () => {
@@ -358,7 +433,7 @@ describe('PromptInput goal mode', () => {
expect(screen.queryByTestId('permission-mode-toggle')).not.toBeInTheDocument()
})
it('starts a goal armed from the mobile composer options menu', async () => {
it('runs the goal command when armed from the mobile composer options menu', async () => {
stubMatchMedia(true)
mocks.useMobile.mockReturnValue(true)
renderComponent()
@@ -368,32 +443,25 @@ describe('PromptInput goal mode', () => {
fireEvent.click(screen.getByTestId('composer-tools-menu'))
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.startGoal).toHaveBeenCalledWith({
sessionId: 'test-session',
directory: '/test',
objective: 'Ship the feature',
}))
await waitFor(() => expect(mocks.runCommand).toHaveBeenCalledTimes(1))
expect(mocks.runCommand).toHaveBeenCalledWith({
sessionID: 'test-session',
name: 'goal',
text: 'Ship the feature',
files: [],
agents: [],
skills: [],
}, 'local')
})
it('passes the goal lock reason to the mobile composer options menu', async () => {
it('passes the open goal state to the mobile composer options menu', async () => {
stubMatchMedia(true)
mocks.useMobile.mockReturnValue(true)
mocks.useSessionGoal.mockReturnValue({ data: { status: 'active' } })
mocks.useSessionGoal.mockReturnValue({ data: { supported: true, goal: goalState } })
renderComponent()
const menu = await screen.findByTestId('composer-tools-menu')
expect(menu).toHaveAttribute('title', OPEN_GOAL_BUTTON)
expect(menu).toBeDisabled()
})
it('disables goal mode with a reason for child sessions', async () => {
stubMatchMedia(true)
mocks.useSessionPermissionMode.mockReturnValue({
data: { sessionId: 'test-session', rootSessionId: 'test-session', mode: 'ask', lockedReason: 'child' },
})
renderComponent()
const button = await screen.findByRole('button', { name: 'Goals can only be started on top-level sessions' })
expect(button).toBeDisabled()
})
})
@@ -89,7 +89,7 @@ vi.mock('@/components/session/PermissionModeToggle', () => ({
vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: () => ({ data: undefined }),
useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }),
useSessionGoalCommand: () => ({ mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false }),
}))
vi.mock('@/hooks/useSessionPermissionMode', () => ({
@@ -136,7 +136,7 @@ vi.mock('@/components/session/SessionSandboxMenu', () => ({
vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: () => ({ data: undefined }),
useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }),
useSessionGoalCommand: () => ({ mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false }),
}))
vi.mock('@/hooks/useSessionPermissionMode', () => ({
+39 -27
View File
@@ -33,16 +33,14 @@ import { PermissionModeToggle } from '@/components/session/PermissionModeToggle'
import { SessionSandboxMenu } from '@/components/session/SessionSandboxMenu'
import { ComposerModelPill } from './ComposerModelPill'
import { ComposerToolsMenu } from './ComposerToolsMenu'
import { useSessionGoal, useStartSessionGoal } from '@/hooks/useSessionGoals'
import { useSessionPermissionMode } from '@/hooks/useSessionPermissionMode'
import { detectMentionTrigger, parsePromptToInput, getFilename, getDirectory, type MentionItem } from '@/lib/promptParser'
import { useSessionGoal, useSessionGoalCommand } from '@/hooks/useSessionGoals'
import { detectMentionTrigger, parsePromptToInput, getFilename, getDirectory, type MentionItem, type ParsedPromptInput } from '@/lib/promptParser'
import { matchText, rankByMatch, type MatchRange } from '@/lib/fuzzyMatch'
import { getNextPrimaryAgentId } from '@/lib/primaryAgents'
import { getNextFavoriteModel } from '@/lib/favoriteModels'
import { randomId } from '@/lib/utils'
import { showToast } from '@/lib/toast'
import { findModelInfo, isSameModelSelection } from '@opencode-manager/shared/opencode'
import { isOpenSessionGoal } from '@opencode-manager/shared/schemas'
import { findModelInfo, isGoalOpen, isSameModelSelection } from '@opencode-manager/shared/opencode'
import { useProviders } from '@/hooks/useProviders'
@@ -255,11 +253,10 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const setStoredAgent = useSessionAgentStore((s) => s.setAgent)
const sendPrompt = useSendPrompt(directory)
const sendShell = useSendShell(directory)
const startGoal = useStartSessionGoal()
const isPromptSubmitPending = sendPrompt.isPending || sendShell.isPending || startGoal.isPending
const goalCommand = useSessionGoalCommand(directory)
const isPromptSubmitPending = sendPrompt.isPending || sendShell.isPending || goalCommand.isPending
const interruptSession = useInterruptSession()
const { data: sessionGoal } = useSessionGoal(sessionID)
const { data: permissionMode } = useSessionPermissionMode(sessionID)
const { data: goalRead } = useSessionGoal(sessionID, directory)
const { searchCommands, findCommand, recentNames } = useCommands({ directory })
const recordCommand = useRecentCommandsStore((state) => state.recordCommand)
const isExactCommandPrompt = (value: string) => {
@@ -371,10 +368,17 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const addUserBashCommand = useUserBash((s) => s.addUserBashCommand)
const startArmedGoal = async (objective: string): Promise<boolean> => {
if (!directory || !objective.trim()) return true
const startArmedGoal = async (parsed: ParsedPromptInput): Promise<boolean> => {
try {
await startGoal.mutateAsync({ sessionId: sessionID, directory, objective })
await goalCommand.mutateAsync({
sessionID,
text: parsed.text,
files: parsed.files,
agents: parsed.agents,
skills: parsed.skills,
model: modelRef ?? undefined,
agent: currentMode,
})
} catch {
return false
}
@@ -384,16 +388,23 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const handleSubmit = async () => {
if (!isModelReady) return
if (isGoalArmed && prompt.trim().length === 0) {
showToast.error('Enter an objective for the goal')
return
}
if (!prompt.trim() && imageAttachments.length === 0) return
if (startGoal.isPending) return
if (goalCommand.isPending) return
if (isStreamingResponse) {
onScrollToBottom()
const parsed = parsePromptToInput(prompt, attachedFiles, agentNames, skillIds, imageAttachments)
const submitted: ComposerDraft = { prompt, isBashMode, attachedFiles, imageAttachments }
if (isGoalArmed && !isBashMode && !isExactCommandPrompt(prompt)) {
const goalStarted = await startArmedGoal(parsed.text)
const goalStarted = await startArmedGoal(parsed)
if (!goalStarted) return
setStoredAgent(sessionID, currentMode)
completeSubmittedDraft(submitted)
return
}
void runAfterSend(
sendPrompt.mutateAsync({
@@ -465,8 +476,11 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const submitted: ComposerDraft = { prompt, isBashMode, attachedFiles, imageAttachments }
if (isGoalArmed) {
const goalStarted = await startArmedGoal(parsed.text)
const goalStarted = await startArmedGoal(parsed)
if (!goalStarted) return
setStoredAgent(sessionID, currentMode)
completeSubmittedDraft(submitted)
return
}
pendingConfirmClearRef.current = {
@@ -1102,18 +1116,16 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
const composerModeStyle = composerMode ? COMPOSER_MODE_STYLES[composerMode] : null
const isTakeoverOpen = isMobile && isSuggestionListOpen
const showStopButton = isSessionActive
const hasOpenGoal = isOpenSessionGoal(sessionGoal)
const lockedReason = permissionMode?.lockedReason ?? null
const goalButtonLabel = lockedReason === 'schedule'
? 'Scheduled runs cannot run goals'
: lockedReason === 'child'
? 'Goals can only be started on top-level sessions'
: hasOpenGoal
? 'A goal is already active for this session'
: isGoalArmed
? 'Goal mode armed: the next message becomes the objective'
: 'Goal mode: the next message becomes the objective'
const isGoalModeDisabled = lockedReason !== null || hasOpenGoal || isBashMode || startGoal.isPending
const goalUnsupported = goalRead?.supported === false
const hasOpenGoal = goalRead?.supported === true && isGoalOpen(goalRead.goal)
const goalButtonLabel = goalUnsupported
? "This server's OpenCode has no goals"
: hasOpenGoal
? 'A goal is already active for this session'
: isGoalArmed
? 'Goal mode armed: the next message becomes the objective'
: 'Goal mode: the next message becomes the objective'
const isGoalModeDisabled = goalUnsupported || hasOpenGoal || isBashMode || goalCommand.isPending
const toggleGoalArmed = () => setIsGoalArmed((value) => !value)
const sendVoiceTurn = useCallback(
@@ -2,58 +2,34 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SessionGoalBar } from './SessionGoalBar'
import {
useCancelSessionGoal,
usePauseSessionGoal,
useResumeSessionGoal,
useSessionGoal,
} from '@/hooks/useSessionGoals'
import type { SessionGoal } from '@opencode-manager/shared/schemas'
import { useSessionGoal, useSessionGoalCommand } from '@/hooks/useSessionGoals'
import type { GoalState, SessionGoalRead } from '@opencode-manager/shared/opencode'
vi.mock('@/hooks/useSessionGoals')
const baseGoal: SessionGoal = {
id: 1,
sessionId: 'ses_1',
serverId: 'local',
directory: '/repo',
const baseGoal: GoalState = {
id: 'goal_1',
objective: 'Ship the feature',
status: 'active',
stopReason: null,
turnState: 'running',
continuationCount: 2,
maxContinuations: 20,
tokenBudget: null,
tokensUsed: 0,
consecutiveBlocked: 0,
lastVerdict: null,
lastReason: null,
createdAt: 1,
rounds: 3,
maxRounds: 50,
boot: 'boot_1',
updatedAt: 1,
finishedAt: null,
}
function mockGoals(
goal: SessionGoal | null,
overrides: {
pause?: ReturnType<typeof vi.fn>
resume?: ReturnType<typeof vi.fn>
cancel?: ReturnType<typeof vi.fn>
} = {},
function mockGoal(
read: SessionGoalRead,
overrides: { mutate?: ReturnType<typeof vi.fn>; isPending?: boolean } = {},
) {
vi.mocked(useSessionGoal).mockReturnValue({ data: goal } as ReturnType<typeof useSessionGoal>)
vi.mocked(usePauseSessionGoal).mockReturnValue({
mutate: overrides.pause ?? vi.fn(),
isPending: false,
} as unknown as ReturnType<typeof usePauseSessionGoal>)
vi.mocked(useResumeSessionGoal).mockReturnValue({
mutate: overrides.resume ?? vi.fn(),
isPending: false,
} as unknown as ReturnType<typeof useResumeSessionGoal>)
vi.mocked(useCancelSessionGoal).mockReturnValue({
mutate: overrides.cancel ?? vi.fn(),
isPending: false,
} as unknown as ReturnType<typeof useCancelSessionGoal>)
vi.mocked(useSessionGoal).mockReturnValue({ data: read } as ReturnType<typeof useSessionGoal>)
vi.mocked(useSessionGoalCommand).mockReturnValue({
mutate: overrides.mutate ?? vi.fn(),
isPending: overrides.isPending ?? false,
} as unknown as ReturnType<typeof useSessionGoalCommand>)
}
function renderBar() {
return render(<SessionGoalBar sessionID="ses_1" directory="/repo" />)
}
describe('SessionGoalBar', () => {
@@ -61,85 +37,68 @@ describe('SessionGoalBar', () => {
vi.clearAllMocks()
})
it('renders nothing when there is no goal', () => {
mockGoals(null)
const { container } = render(<SessionGoalBar sessionID="ses_1" />)
it('renders nothing when the active goal is empty', () => {
mockGoal({ supported: true, goal: null })
const { container } = renderBar()
expect(container).toBeEmptyDOMElement()
})
it('shows the turn counter and pauses the active goal', async () => {
it('renders nothing when the server does not support goals', () => {
mockGoal({ supported: false })
const { container } = renderBar()
expect(container).toBeEmptyDOMElement()
})
it('shows the active goal and pauses it', async () => {
const user = userEvent.setup()
const pause = vi.fn()
mockGoals({ ...baseGoal }, { pause })
render(<SessionGoalBar sessionID="ses_1" />)
const mutate = vi.fn()
mockGoal({ supported: true, goal: { ...baseGoal } }, { mutate })
renderBar()
expect(screen.getByText('Goal active')).toBeInTheDocument()
expect(screen.getByText('Turn 2/20')).toBeInTheDocument()
expect(screen.getByText('Round 3/50')).toBeInTheDocument()
expect(screen.getByText('Ship the feature')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Pause' }))
expect(mutate).toHaveBeenCalledWith({ sessionID: 'ses_1', text: 'pause' })
expect(pause).toHaveBeenCalledWith(1)
await user.click(screen.getByRole('button', { name: 'Clear' }))
expect(mutate).toHaveBeenCalledWith({ sessionID: 'ses_1', text: 'clear' })
})
it('shows token usage when a budget is set', () => {
mockGoals({ ...baseGoal, tokenBudget: 1000, tokensUsed: 250 })
render(<SessionGoalBar sessionID="ses_1" />)
expect(screen.getByText('250/1,000 tokens')).toBeInTheDocument()
})
it('resumes a paused goal', async () => {
it('resumes a paused goal and shows the pause reason', async () => {
const user = userEvent.setup()
const resume = vi.fn()
mockGoals({ ...baseGoal, status: 'paused' }, { resume })
render(<SessionGoalBar sessionID="ses_1" />)
const mutate = vi.fn()
mockGoal({ supported: true, goal: { ...baseGoal, status: 'paused', reason: 'Paused by the user' } }, { mutate })
renderBar()
expect(screen.getByText('Goal paused')).toBeInTheDocument()
expect(screen.getByText('Paused by the user')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Resume' }))
expect(resume).toHaveBeenCalledWith(1)
expect(mutate).toHaveBeenCalledWith({ sessionID: 'ses_1', text: 'resume' })
})
it('shows a terminal summary and can be dismissed', async () => {
it('shows a completed goal with its reason and clears it', async () => {
const user = userEvent.setup()
mockGoals({ ...baseGoal, status: 'completed', stopReason: 'continuation_limit' })
render(<SessionGoalBar sessionID="ses_1" />)
const mutate = vi.fn()
mockGoal({ supported: true, goal: { ...baseGoal, status: 'complete', reason: 'Objective met' } }, { mutate })
renderBar()
expect(screen.getByText('Goal completed')).toBeInTheDocument()
expect(screen.getByText('Continuation limit reached')).toBeInTheDocument()
expect(screen.getByText('Objective met')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Pause' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Resume' })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Dismiss' }))
expect(screen.queryByText('Goal completed')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Clear' }))
expect(mutate).toHaveBeenCalledWith({ sessionID: 'ses_1', text: 'clear' })
})
it('shows the shared stop-reason wording for a user-paused goal', () => {
mockGoals({ ...baseGoal, status: 'stopped', stopReason: 'user_paused' })
render(<SessionGoalBar sessionID="ses_1" />)
it('disables the goal buttons while the command is pending', () => {
mockGoal({ supported: true, goal: { ...baseGoal } }, { isPending: true })
renderBar()
expect(screen.getByText('Goal stopped')).toBeInTheDocument()
expect(screen.getByText('Paused by user')).toBeInTheDocument()
})
it('shows the shared stop-reason wording for an audit failure', () => {
mockGoals({ ...baseGoal, status: 'blocked', stopReason: 'audit_failed' })
render(<SessionGoalBar sessionID="ses_1" />)
expect(screen.getByText('Goal blocked')).toBeInTheDocument()
expect(screen.getByText('Audit failed')).toBeInTheDocument()
})
it('cancels the goal through the cancel API', async () => {
const user = userEvent.setup()
const cancel = vi.fn()
mockGoals({ ...baseGoal }, { cancel })
render(<SessionGoalBar sessionID="ses_1" />)
await user.click(screen.getByRole('button', { name: 'Cancel' }))
expect(cancel).toHaveBeenCalledWith(1)
expect(screen.getByRole('button', { name: 'Pause' })).toBeDisabled()
expect(screen.getByRole('button', { name: 'Clear' })).toBeDisabled()
})
})
@@ -2,37 +2,28 @@ import { useState } from 'react'
import { ChevronDown, ChevronUp, Target } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
useCancelSessionGoal,
usePauseSessionGoal,
useResumeSessionGoal,
useSessionGoal,
} from '@/hooks/useSessionGoals'
import { getGoalOutcomeTitle, getGoalTokenLabel, getGoalTurnLabel, getGoalOutcomeReason } from '@opencode-manager/shared/notifications'
import { isTerminalSessionGoal, type SessionGoalStatus } from '@opencode-manager/shared/schemas'
import { useSessionGoal, useSessionGoalCommand } from '@/hooks/useSessionGoals'
import { getGoalRoundsLabel, getGoalStatusTitle } from '@opencode-manager/shared/notifications'
import type { GoalStatus } from '@opencode-manager/shared/opencode'
const STATUS_CHIP_CLASSES: Record<SessionGoalStatus, string> = {
const STATUS_CHIP_CLASSES: Record<GoalStatus, string> = {
active: 'bg-highlight text-highlight-foreground border-highlight',
paused: 'bg-warning/15 text-warning border-warning/40',
completed: 'bg-success/15 text-success border-success/40',
blocked: 'bg-destructive/15 text-destructive border-destructive/40',
stopped: 'bg-muted text-muted-foreground border-border',
complete: 'bg-success/15 text-success border-success/40',
}
export function SessionGoalBar({ sessionID }: { sessionID: string }) {
const { data: goal } = useSessionGoal(sessionID)
const pauseGoal = usePauseSessionGoal()
const resumeGoal = useResumeSessionGoal()
const cancelGoal = useCancelSessionGoal()
const GOAL_BUTTON_CLASSES = 'h-6 px-2 text-xs'
/** Renders the session's OpenCode goal with pause, resume and clear controls. */
export function SessionGoalBar({ sessionID, directory }: { sessionID: string; directory: string | undefined }) {
const { data } = useSessionGoal(sessionID, directory)
const goalCommand = useSessionGoalCommand(directory)
const [expanded, setExpanded] = useState(false)
const [dismissedGoalId, setDismissedGoalId] = useState<number | null>(null)
if (!goal) return null
const terminal = isTerminalSessionGoal(goal)
if (terminal && dismissedGoalId === goal.id) return null
if (!data || !data.supported || data.goal === null) return null
const reason = getGoalOutcomeReason(goal)
const tokenLabel = getGoalTokenLabel(goal)
const goal = data.goal
const open = goal.status !== 'complete'
return (
<div className="mb-1 flex flex-col gap-1 rounded-lg border border-border bg-card px-2 py-1.5 text-xs">
@@ -42,74 +33,49 @@ export function SessionGoalBar({ sessionID }: { sessionID: string }) {
className={`gap-1 px-2 py-0.5 font-medium ${STATUS_CHIP_CLASSES[goal.status]}`}
>
<Target className="h-3 w-3" />
{getGoalOutcomeTitle(goal.status)}
{getGoalStatusTitle(goal.status)}
</Badge>
{!terminal && (
<span className="text-muted-foreground">
{getGoalTurnLabel(goal)}
</span>
{goal.status === 'active' && (
<span className="text-muted-foreground">{getGoalRoundsLabel(goal)}</span>
)}
{!terminal && tokenLabel !== null && (
<span className="text-muted-foreground">
{tokenLabel}
</span>
)}
{terminal ? (
<>
{reason && (
<span className="min-w-0 flex-1 truncate text-muted-foreground" title={reason}>
{reason}
</span>
)}
<div className="ml-auto flex items-center gap-1">
{goal.status === 'active' && (
<Button
variant="ghost"
size="sm"
className="ml-auto h-6 px-2 text-xs"
onClick={() => setDismissedGoalId(goal.id)}
className={GOAL_BUTTON_CLASSES}
disabled={goalCommand.isPending}
onClick={() => goalCommand.mutate({ sessionID, text: 'pause' })}
>
Dismiss
Pause
</Button>
</>
) : (
<div className="ml-auto flex items-center gap-1">
{goal.status === 'paused' ? (
<Button
variant="ghost"
size="sm"
className="h-6 px-2 text-xs"
disabled={resumeGoal.isPending}
onClick={() => resumeGoal.mutate(goal.id)}
>
Resume
</Button>
) : (
<Button
variant="ghost"
size="sm"
className="h-6 px-2 text-xs"
disabled={pauseGoal.isPending}
onClick={() => pauseGoal.mutate(goal.id)}
>
Pause
</Button>
)}
)}
{goal.status === 'paused' && (
<Button
variant="ghost"
size="sm"
className="h-6 px-2 text-xs text-destructive hover:text-destructive"
disabled={cancelGoal.isPending}
onClick={() => cancelGoal.mutate(goal.id)}
className={GOAL_BUTTON_CLASSES}
disabled={goalCommand.isPending}
onClick={() => goalCommand.mutate({ sessionID, text: 'resume' })}
>
Cancel
Resume
</Button>
</div>
)}
)}
<Button
variant="ghost"
size="sm"
className={`${GOAL_BUTTON_CLASSES} text-destructive hover:text-destructive`}
disabled={goalCommand.isPending}
onClick={() => goalCommand.mutate({ sessionID, text: 'clear' })}
>
Clear
</Button>
</div>
</div>
{!terminal && (
{open && (
<div className="flex items-start gap-1">
<p className={`min-w-0 flex-1 text-muted-foreground ${expanded ? 'whitespace-pre-wrap break-words' : 'truncate'}`}>
{goal.objective}
@@ -126,9 +92,9 @@ export function SessionGoalBar({ sessionID }: { sessionID: string }) {
</div>
)}
{!terminal && goal.lastReason && (
<p className="truncate text-muted-foreground" title={goal.lastReason}>
{goal.lastReason}
{goal.reason && (
<p className="truncate text-muted-foreground" title={goal.reason}>
{goal.reason}
</p>
)}
</div>
@@ -220,7 +220,7 @@ export function NotificationSettings() {
Goal outcomes
</Label>
<p className="text-sm text-muted-foreground">
When a session goal completes, blocks or stops
When a session goal completes or pauses on its own
</p>
</div>
<Switch
@@ -1,36 +1,13 @@
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
import { act, render, screen, fireEvent } from '@testing-library/react'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SessionAutomationSettings } from './SessionAutomationSettings'
import { useSettings } from '@/hooks/useSettings'
import type { UserPreferences } from '@/api/types/settings'
import type { Provider } from '@/api/providers'
import { createUseSettingsMock } from '@/test/test-utils'
vi.mock('@/hooks/useSettings')
const mocks = vi.hoisted(() => ({
useProviders: vi.fn(),
useOpenCodeModelState: vi.fn(),
useOpenCodeDefaultModel: vi.fn(),
}))
vi.mock('@/hooks/useProviders', () => ({ useProviders: mocks.useProviders }))
vi.mock('@/hooks/useModelSelection', () => ({
useOpenCodeModelState: mocks.useOpenCodeModelState,
useOpenCodeDefaultModel: mocks.useOpenCodeDefaultModel,
}))
const providers: Provider[] = [
{
id: 'anthropic',
name: 'Anthropic',
models: [
{ id: 'claude-sonnet-4', key: 'claude-sonnet-4', name: 'Claude Sonnet 4', released: 0, free: false },
],
},
]
const basePreferences: UserPreferences = {
theme: 'dark',
mode: 'build',
@@ -56,9 +33,6 @@ describe('SessionAutomationSettings', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useProviders.mockReturnValue({ data: { providers, models: [] } })
mocks.useOpenCodeModelState.mockReturnValue({ data: { favorite: [], recent: [], variant: {} } })
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: null })
})
it('defaults the select to ask every time', () => {
@@ -84,179 +58,13 @@ describe('SessionAutomationSettings', () => {
expect(updateSettings).toHaveBeenCalledWith({ sessionDefaults: { permissionMode: 'auto' } })
})
it('saves the goal auditor model chosen from the combobox after the debounce', () => {
vi.useFakeTimers()
try {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
updateSettings,
})
render(<SessionAutomationSettings />)
fireEvent.focus(screen.getByLabelText('Goal auditor model'))
fireEvent.click(screen.getByRole('option', { name: /Claude Sonnet 4/ }))
act(() => {
vi.advanceTimersByTime(800)
})
expect(updateSettings).toHaveBeenCalledTimes(1)
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: {
permissionMode: 'ask',
goalMaxContinuations: 20,
goalAuditorModel: 'anthropic/claude-sonnet-4',
},
})
} finally {
vi.useRealTimers()
}
})
it('clears the goal auditor model', () => {
vi.useFakeTimers()
try {
const updateSettings = vi.fn()
mockUseSettings({
preferences: {
...basePreferences,
sessionDefaults: {
permissionMode: 'ask',
goalMaxContinuations: 20,
goalAuditorModel: 'anthropic/claude-sonnet-4',
},
},
updateSettings,
})
render(<SessionAutomationSettings />)
fireEvent.click(screen.getByRole('button', { name: 'Clear' }))
act(() => {
vi.advanceTimersByTime(800)
})
expect(updateSettings).toHaveBeenCalledTimes(1)
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: {
permissionMode: 'ask',
goalMaxContinuations: 20,
goalAuditorModel: undefined,
},
})
} finally {
vi.useRealTimers()
}
})
it('saves the goal auditor model after the debounce without blurring', () => {
vi.useFakeTimers()
try {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
updateSettings,
})
render(<SessionAutomationSettings />)
fireEvent.change(screen.getByLabelText('Goal auditor model'), {
target: { value: 'anthropic/claude-sonnet-4' },
})
act(() => {
vi.advanceTimersByTime(800)
})
expect(updateSettings).toHaveBeenCalledTimes(1)
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: {
permissionMode: 'ask',
goalMaxContinuations: 20,
goalAuditorModel: 'anthropic/claude-sonnet-4',
},
})
} finally {
vi.useRealTimers()
}
})
it('saves the auditor model and max continuations together after the debounce', () => {
vi.useFakeTimers()
try {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
updateSettings,
})
render(<SessionAutomationSettings />)
fireEvent.change(screen.getByLabelText('Goal auditor model'), {
target: { value: 'anthropic/claude-sonnet-4' },
})
fireEvent.change(screen.getByLabelText('Max automatic continuations'), {
target: { value: '50' },
})
act(() => {
vi.advanceTimersByTime(800)
})
expect(updateSettings).toHaveBeenCalledTimes(1)
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: {
permissionMode: 'ask',
goalAuditorModel: 'anthropic/claude-sonnet-4',
goalMaxContinuations: 50,
},
})
} finally {
vi.useRealTimers()
}
})
it('saves an in-range max automatic continuations on blur', () => {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
updateSettings,
})
it('renders no goal controls', () => {
mockUseSettings({ preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask' } } })
render(<SessionAutomationSettings />)
const input = screen.getByLabelText('Max automatic continuations')
fireEvent.change(input, { target: { value: '50' } })
fireEvent.blur(input)
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 50 },
})
})
it('does not save out-of-range max automatic continuations', () => {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
updateSettings,
})
render(<SessionAutomationSettings />)
const input = screen.getByLabelText('Max automatic continuations')
fireEvent.change(input, { target: { value: '500' } })
fireEvent.blur(input)
expect(updateSettings).not.toHaveBeenCalled()
})
it('saves the token budget per goal on blur', () => {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
updateSettings,
})
render(<SessionAutomationSettings />)
const input = screen.getByLabelText('Token budget per goal')
fireEvent.change(input, { target: { value: '5000' } })
fireEvent.blur(input)
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20, goalTokenBudget: 5000 },
})
expect(screen.getByRole('combobox', { name: 'Default permission mode for new sessions' })).toBeInTheDocument()
expect(screen.queryByLabelText('Goal auditor model')).toBeNull()
expect(screen.queryByLabelText('Max automatic continuations')).toBeNull()
expect(screen.queryByLabelText('Token budget per goal')).toBeNull()
})
})
@@ -1,44 +1,13 @@
import { useCallback } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { useAutosavedSetting } from '@/hooks/useAutosavedSetting'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { ModelCombobox } from '@/components/model/ModelCombobox'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import {
DEFAULT_SESSION_DEFAULTS,
GOAL_MAX_CONTINUATIONS_MAX,
GOAL_MAX_CONTINUATIONS_MIN,
type SessionDefaults,
type SessionPermissionMode,
} from '@opencode-manager/shared/schemas'
interface GoalDraft {
goalAuditorModel: string
goalMaxContinuations: string
goalTokenBudget: string
}
interface GoalCommitted {
goalAuditorModel: string | undefined
goalMaxContinuations: number
goalTokenBudget: number | undefined
}
function maxContinuationsFromInput(value: string): number | null {
const parsed = Number(value)
if (!Number.isInteger(parsed)) return null
if (parsed < GOAL_MAX_CONTINUATIONS_MIN || parsed > GOAL_MAX_CONTINUATIONS_MAX) return null
return parsed
}
function tokenBudgetFromInput(value: string): { valid: boolean; value: number | undefined } {
const trimmed = value.trim()
if (trimmed === '') return { valid: true, value: undefined }
const parsed = Number(trimmed)
return Number.isInteger(parsed) && parsed > 0 ? { valid: true, value: parsed } : { valid: false, value: undefined }
}
export function SessionAutomationSettings() {
const { preferences, updateSettings } = useSettings()
const sessionDefaults = preferences?.sessionDefaults
@@ -57,47 +26,6 @@ export function SessionAutomationSettings() {
[sessionDefaults, permissionMode, updateSettings],
)
const { draft, setDraft, commit: commitGoalFields } = useAutosavedSetting<SessionDefaults | undefined, GoalDraft, GoalCommitted>({
stored: sessionDefaults,
toDraft: (stored) => ({
goalAuditorModel: stored?.goalAuditorModel ?? '',
goalMaxContinuations: String(stored?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations),
goalTokenBudget: stored?.goalTokenBudget !== undefined ? String(stored.goalTokenBudget) : '',
}),
toCommitted: (current, previous) => {
const budget = tokenBudgetFromInput(current.goalTokenBudget)
return {
goalAuditorModel: current.goalAuditorModel.trim() || undefined,
goalMaxContinuations:
maxContinuationsFromInput(current.goalMaxContinuations) ??
previous?.goalMaxContinuations ??
DEFAULT_SESSION_DEFAULTS.goalMaxContinuations,
goalTokenBudget: budget.valid ? budget.value : previous?.goalTokenBudget,
}
},
isEqual: (a, b) =>
a.goalAuditorModel === b.goalAuditorModel &&
a.goalMaxContinuations === b.goalMaxContinuations &&
a.goalTokenBudget === b.goalTokenBudget,
save: (next, previous) => {
const patch: Partial<SessionDefaults> = {}
if (next.goalAuditorModel !== previous?.goalAuditorModel) patch.goalAuditorModel = next.goalAuditorModel
if (next.goalMaxContinuations !== previous?.goalMaxContinuations) {
patch.goalMaxContinuations = next.goalMaxContinuations
}
if (next.goalTokenBudget !== previous?.goalTokenBudget) patch.goalTokenBudget = next.goalTokenBudget
if (Object.keys(patch).length === 0) return
updateSessionDefaults(patch)
},
})
const updateGoalDraft = useCallback(
(patch: Partial<GoalDraft>) => {
setDraft((current) => ({ ...current, ...patch }))
},
[setDraft],
)
return (
<div className="space-y-6">
<h2 className="text-lg font-semibold text-foreground">Sessions</h2>
@@ -122,63 +50,6 @@ export function SessionAutomationSettings() {
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
<div className="min-w-0 space-y-0.5">
<Label htmlFor="goalAuditorModel">Goal auditor model</Label>
<p className="text-sm text-muted-foreground">
Model that decides whether a session goal is done. Leave empty to use the OpenCode default model.
</p>
</div>
<ModelCombobox
id="goalAuditorModel"
ariaLabel="Goal auditor model"
value={draft.goalAuditorModel}
onChange={(value) => updateGoalDraft({ goalAuditorModel: value })}
placeholder="OpenCode default"
allowCustomValue
showClear
className="w-full shrink-0 sm:w-64"
/>
</div>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
<div className="min-w-0 space-y-0.5">
<Label htmlFor="goalMaxContinuations">Max automatic continuations</Label>
<p className="text-sm text-muted-foreground">
How many times a goal may keep the agent working after each audit before it stops.
</p>
</div>
<Input
id="goalMaxContinuations"
type="number"
min={GOAL_MAX_CONTINUATIONS_MIN}
max={GOAL_MAX_CONTINUATIONS_MAX}
value={draft.goalMaxContinuations}
className="w-full shrink-0 sm:w-40"
onChange={(event) => updateGoalDraft({ goalMaxContinuations: event.target.value })}
onBlur={commitGoalFields}
/>
</div>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
<div className="min-w-0 space-y-0.5">
<Label htmlFor="goalTokenBudget">Token budget per goal</Label>
<p className="text-sm text-muted-foreground">
Stop a goal once it has spent this many tokens. Leave empty for no limit.
</p>
</div>
<Input
id="goalTokenBudget"
type="number"
min={1}
value={draft.goalTokenBudget}
placeholder="No limit"
className="w-full shrink-0 sm:w-40"
onChange={(event) => updateGoalDraft({ goalTokenBudget: event.target.value })}
onBlur={commitGoalFields}
/>
</div>
</div>
)
}
+39 -1
View File
@@ -4,7 +4,7 @@ import userEvent from '@testing-library/user-event'
import { useState, type ReactNode } from 'react'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { FormInfo, PermissionRequest } from '@opencode-manager/shared/opencode'
import type { FormInfo, PermissionRequest, GoalState } from '@opencode-manager/shared/opencode'
import { FetchError } from '@opencode-manager/shared'
import { showToast } from '@/lib/toast'
import { useSessionStatus, hasBackgroundActivity } from '@/stores/sessionStatusStore'
@@ -1248,6 +1248,44 @@ describe('EventProvider permissions and forms', () => {
})
})
it('applies a goal change event to the session goal cache', async () => {
const initialGoal: GoalState = {
id: 'goal-1',
objective: 'Ship the goal bar',
status: 'active',
rounds: 0,
maxRounds: 10,
boot: 'boot-1',
updatedAt: 1000,
}
const updatedGoal: GoalState = { ...initialGoal, rounds: 1, updatedAt: 2000 }
const queryClient = createTestQueryClient()
queryClient.setQueryData(['session-goal', 'session-1'], { supported: true, goal: initialGoal })
render(<Harness />, { wrapper: createWrapper(queryClient) })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({
type: 'rpc.opencode.goal.changed',
data: { sessionID: 'session-1', goal: updatedGoal },
directory: '/repo',
})
})
expect(queryClient.getQueryData(['session-goal', 'session-1'])).toEqual({ supported: true, goal: updatedGoal })
act(() => {
onEvent({ type: 'session.idle', data: { sessionID: 'other' }, directory: '/repo' })
})
expect(queryClient.getQueryData(['session-goal', 'session-1'])).toEqual({ supported: true, goal: updatedGoal })
})
it('invalidates the sibling caches when a branch changes outside a repo row', async () => {
mocks.listRepos.mockResolvedValue([])
+6
View File
@@ -28,6 +28,7 @@ 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 { busyStatusesFromActiveSessions, useSessionStatus } from '@/stores/sessionStatusStore'
import {
invalidateChildSessionCaches,
@@ -1051,6 +1052,9 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const event = data as StreamEvent
const serverId = (event as { serverId?: string }).serverId ?? LOCAL_OPENCODE_SERVER_ID
const goalEvent = { type: event.type, data: 'data' in event ? event.data : null }
if (applySessionGoalEvent(queryClient, goalEvent, serverId)) return
switch (event.type) {
case 'permission.asked': {
const request = event.data
@@ -1233,6 +1237,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
void syncRunningShells(collectTrackedDirectories())
invalidateChildSessionCaches(queryClient)
invalidateQueryKeysDebounced(queryClient, LOCATION_CATALOG_QUERY_KEYS)
queryClient.invalidateQueries({ queryKey: [SESSION_GOAL_QUERY_ROOT] })
startStatusPoll()
} else {
streamConnectedRef.current = false
@@ -1244,6 +1249,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
}
const handleResync = (subscribedDirectories: string[], serverId?: string) => {
queryClient.invalidateQueries({ queryKey: [SESSION_GOAL_QUERY_ROOT] })
if (serverId && !isLocalOpenCodeServer(serverId)) {
void reconcileRemoteDirectoryActivity(serverId, subscribedDirectories)
invalidateSessionListCachesDebounced(queryClient, undefined, serverId)
+206 -48
View File
@@ -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'))
})
})
+70 -46
View File
@@ -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')
}
+1 -1
View File
@@ -981,7 +981,7 @@ export function SessionDetail() {
<div className={cn(isFormSheetOpen && "shrink-0 bg-background px-[3%]")}>
<div className={cn(!isFormSheetOpen && "px-[3%] md:px-0")}>
<SessionSendErrorBanner sessionId={sessionId} isConnected={streamConnected} isReconnecting={streamReconnecting} />
<SessionGoalBar sessionID={sessionId} />
<SessionGoalBar sessionID={sessionId} directory={sessionDirectory} />
<BackgroundWorkBar
sessionID={sessionId}
directory={sessionDirectory}
@@ -132,10 +132,7 @@ vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: vi
vi.mock('@/components/session/SessionGoalBar', () => ({ SessionGoalBar: vi.fn(() => null) }))
vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: vi.fn(() => ({ data: undefined })),
useStartSessionGoal: vi.fn(() => ({ mutateAsync: vi.fn(), isPending: false })),
usePauseSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useResumeSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useCancelSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useSessionGoalCommand: vi.fn(() => ({ mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false })),
}))
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: vi.fn(() => ({ data: undefined })),
@@ -201,10 +201,7 @@ vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: vi
vi.mock('@/components/session/SessionGoalBar', () => ({ SessionGoalBar: vi.fn(() => null) }))
vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: vi.fn(() => ({ data: undefined })),
useStartSessionGoal: vi.fn(() => ({ mutateAsync: vi.fn(), isPending: false })),
usePauseSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useResumeSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useCancelSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useSessionGoalCommand: vi.fn(() => ({ mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false })),
}))
vi.mock('@/components/session/SideQuestionDialog', () => ({ SideQuestionDialog: vi.fn(() => null) }))
vi.mock('@/components/session/ChangesWalkthroughSheet', () => ({ ChangesWalkthroughSheet: vi.fn(() => null) }))
@@ -171,10 +171,7 @@ vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: vi
vi.mock('@/components/session/SessionGoalBar', () => ({ SessionGoalBar: vi.fn(() => null) }))
vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: vi.fn(() => ({ data: undefined })),
useStartSessionGoal: vi.fn(() => ({ mutateAsync: vi.fn(), isPending: false })),
usePauseSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useResumeSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useCancelSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useSessionGoalCommand: vi.fn(() => ({ mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false })),
}))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
FileBrowserSheet: vi.fn(() => null),
@@ -133,10 +133,7 @@ vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: vi
vi.mock('@/components/session/SessionGoalBar', () => ({ SessionGoalBar: vi.fn(() => null) }))
vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: vi.fn(() => ({ data: undefined })),
useStartSessionGoal: vi.fn(() => ({ mutateAsync: vi.fn(), isPending: false })),
usePauseSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useResumeSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useCancelSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useSessionGoalCommand: vi.fn(() => ({ mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false })),
}))
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: vi.fn(() => ({ data: undefined })),
@@ -374,7 +374,7 @@ describe('SessionDetail remote server mode', () => {
expect(mocks.SessionGoalBar).toHaveBeenCalled()
expect(mocks.SessionGoalBar.mock.calls.at(-1)?.[0]).toEqual(
expect.objectContaining({ sessionID: 'ses_remote' }),
expect.objectContaining({ sessionID: 'ses_remote', directory: '/home/me/app' }),
)
})
@@ -164,10 +164,7 @@ vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: vi
vi.mock('@/components/session/SessionGoalBar', () => ({ SessionGoalBar: vi.fn(() => null) }))
vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: vi.fn(() => ({ data: undefined })),
useStartSessionGoal: vi.fn(() => ({ mutateAsync: vi.fn(), isPending: false })),
usePauseSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useResumeSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useCancelSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useSessionGoalCommand: vi.fn(() => ({ mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false })),
}))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
FileBrowserSheet: vi.fn(() => null),