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

@@ -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>
)
}