section 8: Phase 8: Goal mode in the composer, goal status bar and goal

This commit is contained in:
Chris Scott committed 2026-10-03 10:29:46 -04:00
1 parent 4e9f27ab0b
commit 8cd00e1a8a
19 files changed
+877 -11

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
import { fetchWrapper } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type { SessionGoal, StartSessionGoalRequest } from '@opencode-manager/shared/schemas'
export async function getLatestSessionGoal(sessionId: string): Promise<SessionGoal | null> {
const res = await fetchWrapper<{ goal: SessionGoal | null }>(`${API_BASE_URL}/api/session-goals`, {
params: { sessionId },
})
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')
}
@@ -86,6 +86,11 @@ vi.mock('@/components/session/PermissionModeToggle', () => ({
PermissionModeToggle: () => null,
}))
vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: () => ({ data: undefined }),
useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }),
}))
vi.mock('@/components/ui/session-status-indicator', () => ({
SessionStatusIndicator: () => <div>SessionStatus</div>,
}))
@@ -0,0 +1,225 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput } from './PromptInput'
import { useUIState } from '@/stores/uiStateStore'
import { createCommandActionsMock, stubMatchMedia } from '@/test/test-utils'
const mocks = vi.hoisted(() => ({
sendPrompt: vi.fn(),
sendShell: vi.fn(),
interrupt: vi.fn(),
startGoal: vi.fn(),
useSessionGoal: vi.fn(),
agents: [] as Array<{ id: string; name: string; description?: string; mode?: string; hidden?: boolean }>,
setAgent: vi.fn(),
cycleVariant: vi.fn(),
showToast: {
success: vi.fn(),
error: vi.fn(),
info: vi.fn(),
warning: vi.fn(),
loading: vi.fn(),
promise: vi.fn(),
dismiss: vi.fn(),
},
useSTT: vi.fn(),
useMobile: vi.fn(),
useCommands: vi.fn(),
useFileSearch: vi.fn(),
useModelSelection: vi.fn(),
useVariants: vi.fn(),
useSessionAgent: vi.fn(),
useUserBash: vi.fn(),
useSessionAgentStore: vi.fn(),
useSendErrorStore: vi.fn(),
}))
vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/hooks/useOpenCode')>()
return {
...actual,
useSendPrompt: () => ({ mutate: mocks.sendPrompt, isPending: false }),
useSendShell: () => ({ mutate: mocks.sendShell, isPending: false }),
useInterruptSession: () => ({ mutate: mocks.interrupt }),
useAgents: () => ({ data: mocks.agents }),
}
})
vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: mocks.useSessionGoal,
useStartSessionGoal: () => ({ mutateAsync: mocks.startGoal, isPending: false }),
}))
vi.mock('@/hooks/useSTT', () => ({ useSTT: mocks.useSTT }))
vi.mock('@/hooks/useMobile', () => ({ useMobile: mocks.useMobile }))
vi.mock('@/hooks/useCommands', () => ({ useCommands: mocks.useCommands }))
vi.mock('@/hooks/useFileSearch', () => ({ useFileSearch: mocks.useFileSearch }))
vi.mock('@/hooks/useModelSelection', () => ({ useModelSelection: mocks.useModelSelection }))
vi.mock('@/hooks/useVariants', () => ({ useVariants: mocks.useVariants }))
vi.mock('@/hooks/useSessionAgent', () => ({ useSessionAgent: mocks.useSessionAgent }))
vi.mock('@/stores/userBashStore', () => ({ useUserBash: mocks.useUserBash }))
vi.mock('@/stores/sessionAgentStore', () => ({ useSessionAgentStore: mocks.useSessionAgentStore }))
vi.mock('@/stores/sendErrorStore', () => ({ useSendErrorStore: mocks.useSendErrorStore }))
vi.mock('@/lib/toast', () => ({ showToast: mocks.showToast }))
vi.mock('@/contexts/EventContext', () => ({
usePermissions: () => ({
hasForSession: vi.fn().mockReturnValue(false),
setShowDialog: vi.fn(),
}),
}))
vi.mock('@/components/agent/AgentQuickSelect', () => ({
AgentQuickSelect: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}))
vi.mock('@/components/model/ModelQuickSelect', () => ({
ModelQuickSelect: ({ children, open }: { children?: React.ReactNode; open?: boolean }) => (
<div data-testid="model-quick-select" data-open={open ? 'true' : 'false'}>{children}</div>
),
}))
vi.mock('@/components/session/PermissionModeToggle', () => ({
PermissionModeToggle: () => null,
}))
vi.mock('@/components/ui/session-status-indicator', () => ({
SessionStatusIndicator: () => <div>SessionStatus</div>,
}))
vi.mock('@/components/command/CommandSuggestions', () => ({
CommandSuggestions: () => <div>CommandSuggestions</div>,
}))
vi.mock('./MentionSuggestions', () => ({
MentionSuggestions: () => <div>MentionSuggestions</div>,
}))
const createTestQueryClient = () => new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
const GOAL_BUTTON = 'Goal mode: the next message becomes the objective'
const OPEN_GOAL_BUTTON = 'A goal is already active for this session'
describe('PromptInput goal mode', () => {
const defaultProps = {
directory: '/test',
sessionID: 'test-session',
showScrollButton: false,
isSessionActive: false,
isStreamingResponse: false,
onScrollToBottom: vi.fn(),
commandActions: createCommandActionsMock(),
onPromptChange: vi.fn(),
}
const renderComponent = () => {
const queryClient = createTestQueryClient()
return render(
<QueryClientProvider client={queryClient}>
<PromptInput {...defaultProps} />
</QueryClientProvider>
)
}
beforeEach(() => {
vi.clearAllMocks()
mocks.useSessionGoal.mockReturnValue({ data: null })
mocks.startGoal.mockResolvedValue({ id: 1 })
mocks.agents = []
mocks.useMobile.mockReturnValue(false)
mocks.useSTT.mockReturnValue({
isRecording: false,
isProcessing: false,
isSupported: false,
isEnabled: false,
interimTranscript: '',
transcript: '',
startRecording: vi.fn(),
stopRecording: vi.fn(),
abortRecording: vi.fn(),
clear: vi.fn(),
})
mocks.useCommands.mockReturnValue({ filterCommands: () => [] })
mocks.useFileSearch.mockReturnValue({ files: [] })
mocks.useModelSelection.mockReturnValue({
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
modelString: 'anthropic/claude-sonnet-4',
setModel: vi.fn(),
setActiveModel: vi.fn(),
recentModels: [],
favoriteModels: [],
toggleFavorite: vi.fn(),
isModelStateLoading: false,
})
mocks.useVariants.mockReturnValue({ hasVariants: false, currentVariant: null, cycleVariant: mocks.cycleVariant })
mocks.useSessionAgent.mockReturnValue({ agent: 'build' })
mocks.useUserBash.mockImplementation((selector: (state: unknown) => unknown) => selector({ addUserBashCommand: vi.fn() }))
mocks.useSessionAgentStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ setAgent: mocks.setAgent }))
mocks.useSendErrorStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ errors: {} }))
useUIState.getState().clearPendingPromptCommand()
useUIState.getState().clearPendingPromptFile()
})
afterEach(() => {
Reflect.deleteProperty(window, 'matchMedia')
})
it('starts a goal with the message objective before sending it', 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.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())
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('disables goal mode while a goal is already active', async () => {
stubMatchMedia(true)
mocks.useSessionGoal.mockReturnValue({ data: { status: 'active' } })
renderComponent()
const button = await screen.findByRole('button', { name: OPEN_GOAL_BUTTON })
expect(button).toBeDisabled()
})
})
@@ -77,6 +77,11 @@ vi.mock('@/components/session/PermissionModeToggle', () => ({
PermissionModeToggle: () => null,
}))
vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: () => ({ data: undefined }),
useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }),
}))
vi.mock('@/components/ui/session-status-indicator', () => ({
SessionStatusIndicator: () => <div>SessionStatus</div>,
}))
@@ -104,6 +104,11 @@ vi.mock('@/components/session/PermissionModeToggle', () => ({
PermissionModeToggle: () => null,
}))
vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: () => ({ data: undefined }),
useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }),
}))
vi.mock('@/components/ui/session-status-indicator', () => ({
SessionStatusIndicator: () => <div>SessionStatus</div>,
}))
@@ -17,7 +17,7 @@ import { useMobile } from '@/hooks/useMobile'
import { FINE_POINTER_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery'
import { usePermissions } from '@/contexts/EventContext'
import { ArrowDown, Upload, X, Mic, MicOff } from 'lucide-react'
import { ArrowDown, Upload, X, Mic, MicOff, Target } from 'lucide-react'
import { SquareFill } from '@/components/ui/square-fill'
@@ -28,6 +28,7 @@ import { ModelQuickSelect } from '@/components/model/ModelQuickSelect'
import { AgentQuickSelect } from '@/components/agent/AgentQuickSelect'
import { VoiceStatusOverlay, type VoiceStatusOverlayState } from './VoiceStatusOverlay'
import { PermissionModeToggle } from '@/components/session/PermissionModeToggle'
import { useSessionGoal, useStartSessionGoal } from '@/hooks/useSessionGoals'
import { detectMentionTrigger, parsePromptToInput, getFilename, filterAgentsByQuery } from '@/lib/promptParser'
import { getNextPrimaryAgentId } from '@/lib/primaryAgents'
import { randomId } from '@/lib/utils'
@@ -93,6 +94,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
}, ref) {
const [prompt, setPrompt] = useState('')
const [isBashMode, setIsBashMode] = useState(false)
const [isGoalArmed, setIsGoalArmed] = useState(false)
const [showSuggestions, setShowSuggestions] = useState(false)
const [suggestionQuery, setSuggestionQuery] = useState('')
const [attachedFiles, setAttachedFiles] = useState(new Map<string, FileAttachmentInfo>())
@@ -229,6 +231,8 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const sendShell = useSendShell(directory)
const isPromptSubmitPending = sendPrompt.isPending || sendShell.isPending
const interruptSession = useInterruptSession()
const { data: sessionGoal } = useSessionGoal(sessionID)
const startGoal = useStartSessionGoal()
const { filterCommands } = useCommands({ directory })
const isExactCommandPrompt = (value: string) => {
const commandPrompt = parseCommandPrompt(value)
@@ -291,7 +295,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const addUserBashCommand = useUserBash((s) => s.addUserBashCommand)
const handleSubmit = () => {
const handleSubmit = async () => {
if (!prompt.trim() && imageAttachments.length === 0) return
pendingVoiceAutoSubmitRef.current = false
@@ -385,6 +389,15 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const submittedAttachedFiles = attachedFiles
const submittedImageAttachments = imageAttachments
if (isGoalArmed && directory && parsed.text.trim()) {
try {
await startGoal.mutateAsync({ sessionId: sessionID, directory, objective: parsed.text })
} catch {
return
}
setIsGoalArmed(false)
}
pendingConfirmClearRef.current = {
prompt: submittedPrompt,
files: submittedAttachedFiles,
@@ -1148,6 +1161,29 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
const showStopButton = isSessionActive
const hideSecondaryButtons = isMobile && isSessionActive
const showMobileScrollButton = isMobile && showScrollButton
const hasOpenGoal = sessionGoal?.status === 'active' || sessionGoal?.status === 'paused'
const goalButtonLabel = 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 goalModeButton = directory ? (
<button
type="button"
onClick={() => setIsGoalArmed((value) => !value)}
disabled={hasOpenGoal || isBashMode || startGoal.isPending}
aria-pressed={isGoalArmed}
aria-label={goalButtonLabel}
title={goalButtonLabel}
className={`p-2 rounded-lg transition-all duration-200 active:scale-95 hover:scale-105 shadow-md border disabled:opacity-50 disabled:cursor-not-allowed disabled:active:scale-100 disabled:hover:scale-100 ${
isGoalArmed
? 'bg-highlight hover:bg-highlight/90 text-highlight-foreground border-highlight'
: 'bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border'
}`}
>
<Target className="w-5 h-5" />
</button>
) : null
const voiceFeedbackState: VoiceStatusOverlayState | null = isTogglingRecording
? 'starting'
: isProcessing
@@ -1261,6 +1297,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
lastAddedTranscriptRef.current = ''
setIsTogglingRecording(false)
setLocalMode(null)
setIsGoalArmed(false)
// eslint-disable-next-line react-hooks/exhaustive-deps -- Intentionally only run on sessionID change to avoid clearing transcript when recording state changes
}, [sessionID])
@@ -1347,6 +1384,7 @@ return (
onOpenChange={setIsModelPickerOpen}
/>
{directory && <PermissionModeToggle sessionID={sessionID} directory={directory} />}
{goalModeButton}
</>
) : (
<>
@@ -1357,6 +1395,7 @@ return (
isBashMode={isBashMode}
/>
{directory && <PermissionModeToggle sessionID={sessionID} directory={directory} />}
{goalModeButton}
{isSessionActive && (
<div className="px-2.5 py-1.5 md:px-3 md:py-2 rounded-lg text-xs md:text-sm font-medium text-muted-foreground max-w-[120px] md:max-w-[180px]">
<SessionStatusIndicator sessionID={sessionID} showLabel />
@@ -0,0 +1,128 @@
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'
vi.mock('@/hooks/useSessionGoals')
const baseGoal: SessionGoal = {
id: 1,
sessionId: 'ses_1',
directory: '/repo',
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,
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>
} = {},
) {
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>)
}
describe('SessionGoalBar', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('renders nothing when there is no goal', () => {
mockGoals(null)
const { container } = render(<SessionGoalBar sessionID="ses_1" />)
expect(container).toBeEmptyDOMElement()
})
it('shows the turn counter and pauses the active goal', async () => {
const user = userEvent.setup()
const pause = vi.fn()
mockGoals({ ...baseGoal }, { pause })
render(<SessionGoalBar sessionID="ses_1" />)
expect(screen.getByText('Goal active')).toBeInTheDocument()
expect(screen.getByText('Turn 2/20')).toBeInTheDocument()
expect(screen.getByText('Ship the feature')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Pause' }))
expect(pause).toHaveBeenCalledWith(1)
})
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 () => {
const user = userEvent.setup()
const resume = vi.fn()
mockGoals({ ...baseGoal, status: 'paused' }, { resume })
render(<SessionGoalBar sessionID="ses_1" />)
expect(screen.getByText('Goal paused')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Resume' }))
expect(resume).toHaveBeenCalledWith(1)
})
it('shows a terminal summary and can be dismissed', async () => {
const user = userEvent.setup()
mockGoals({ ...baseGoal, status: 'completed', stopReason: 'continuation_limit' })
render(<SessionGoalBar sessionID="ses_1" />)
expect(screen.getByText('Goal completed')).toBeInTheDocument()
expect(screen.getByText('continuation limit reached')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Pause' })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Dismiss' }))
expect(screen.queryByText('Goal completed')).not.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)
})
})
@@ -0,0 +1,157 @@
import { useState } from 'react'
import { ChevronDown, ChevronUp, Target } from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
useCancelSessionGoal,
usePauseSessionGoal,
useResumeSessionGoal,
useSessionGoal,
} from '@/hooks/useSessionGoals'
import type { SessionGoalStatus, SessionGoalStopReason } from '@opencode-manager/shared/schemas'
const STATUS_LABELS: Record<SessionGoalStatus, string> = {
active: 'Goal active',
paused: 'Goal paused',
completed: 'Goal completed',
blocked: 'Goal blocked',
stopped: 'Goal stopped',
}
const STOP_REASON_LABELS: Record<SessionGoalStopReason, string> = {
cancelled: 'cancelled',
user_paused: 'paused by you',
continuation_limit: 'continuation limit reached',
token_budget: 'token budget reached',
turn_error: 'turn failed',
interrupted: 'interrupted',
audit_failed: 'auditor failed',
session_deleted: 'session deleted',
}
const STATUS_CHIP_CLASSES: Record<SessionGoalStatus, 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',
}
const TERMINAL_STATUSES: SessionGoalStatus[] = ['completed', 'blocked', 'stopped']
function isTerminal(status: SessionGoalStatus): boolean {
return TERMINAL_STATUSES.includes(status)
}
export function SessionGoalBar({ sessionID }: { sessionID: string }) {
const { data: goal } = useSessionGoal(sessionID)
const pauseGoal = usePauseSessionGoal()
const resumeGoal = useResumeSessionGoal()
const cancelGoal = useCancelSessionGoal()
const [expanded, setExpanded] = useState(false)
const [dismissedGoalId, setDismissedGoalId] = useState<number | null>(null)
if (!goal) return null
if (isTerminal(goal.status) && dismissedGoalId === goal.id) return null
const terminal = isTerminal(goal.status)
const reason = goal.stopReason ? STOP_REASON_LABELS[goal.stopReason] : goal.lastReason
return (
<div className="mb-1 flex flex-col gap-1 rounded-lg border border-border bg-card/70 px-2 py-1.5 text-xs">
<div className="flex flex-wrap items-center gap-2">
<span
className={`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 font-medium ${STATUS_CHIP_CLASSES[goal.status]}`}
>
<Target className="h-3 w-3" />
{STATUS_LABELS[goal.status]}
</span>
{!terminal && (
<span className="text-muted-foreground">
Turn {goal.continuationCount}/{goal.maxContinuations}
</span>
)}
{!terminal && goal.tokenBudget !== null && (
<span className="text-muted-foreground">
{goal.tokensUsed.toLocaleString()}/{goal.tokenBudget.toLocaleString()} tokens
</span>
)}
{terminal ? (
<>
{reason && (
<span className="min-w-0 flex-1 truncate text-muted-foreground" title={reason}>
{reason}
</span>
)}
<Button
variant="ghost"
size="sm"
className="ml-auto h-6 px-2 text-xs"
onClick={() => setDismissedGoalId(goal.id)}
>
Dismiss
</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>
)}
<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)}
>
Cancel
</Button>
</div>
)}
</div>
{!terminal && (
<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}
</p>
<button
type="button"
onClick={() => setExpanded((value) => !value)}
aria-expanded={expanded}
aria-label={expanded ? 'Collapse goal objective' : 'Expand goal objective'}
className="shrink-0 rounded p-0.5 text-muted-foreground hover:text-foreground"
>
{expanded ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
</button>
</div>
)}
{!terminal && goal.lastReason && (
<p className="truncate text-muted-foreground" title={goal.lastReason}>
{goal.lastReason}
</p>
)}
</div>
)
}
@@ -170,4 +170,18 @@ describe('NotificationSettings', () => {
render(<NotificationSettings />)
expect(screen.getByText(/not supported in this browser/i)).toBeInTheDocument()
})
it('writes the goal outcome preference and defaults it on', async () => {
const user = userEvent.setup()
const updateEventPreference = vi.fn()
mockNotifications({ updateEventPreference })
render(<NotificationSettings />)
const toggle = screen.getByRole('switch', { name: 'Goal outcomes' })
expect(toggle).toBeChecked()
await user.click(toggle)
expect(updateEventPreference).toHaveBeenCalledWith('goalOutcome', false)
})
})
@@ -213,6 +213,24 @@ export function NotificationSettings() {
}
/>
</div>
<div className="flex items-start justify-between gap-4 py-3">
<div className="min-w-0 space-y-0.5">
<Label htmlFor="notifGoalOutcome" className="text-base">
Goal outcomes
</Label>
<p className="text-sm text-muted-foreground">
When a session goal completes, blocks or stops
</p>
</div>
<Switch
id="notifGoalOutcome"
checked={preferences.events.goalOutcome ?? true}
onCheckedChange={(checked) =>
updateEventPreference("goalOutcome", checked)
}
/>
</div>
</>
)}
</div>
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import { render, screen, fireEvent } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SessionAutomationSettings } from './SessionAutomationSettings'
import { useSettings } from '@/hooks/useSettings'
@@ -57,4 +57,59 @@ describe('SessionAutomationSettings', () => {
expect(updateSettings).toHaveBeenCalledWith({ sessionDefaults: { permissionMode: 'auto' } })
})
it('persists the goal auditor model', () => {
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' },
})
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: {
permissionMode: 'ask',
goalMaxContinuations: 20,
goalAuditorModel: 'anthropic/claude-sonnet-4',
},
})
})
it('persists the max automatic continuations', () => {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
updateSettings,
})
render(<SessionAutomationSettings />)
fireEvent.change(screen.getByLabelText('Max automatic continuations'), {
target: { value: '50' },
})
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 50 },
})
})
it('persists the token budget per goal', () => {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
updateSettings,
})
render(<SessionAutomationSettings />)
fireEvent.change(screen.getByLabelText('Token budget per goal'), {
target: { value: '5000' },
})
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20, goalTokenBudget: 5000 },
})
})
})
@@ -1,11 +1,26 @@
import { useSettings } from '@/hooks/useSettings'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import type { SessionPermissionMode } from '@opencode-manager/shared/schemas'
import type { SessionDefaults, SessionPermissionMode } from '@opencode-manager/shared/schemas'
export function SessionAutomationSettings() {
const { preferences, updateSettings } = useSettings()
const permissionMode = preferences?.sessionDefaults?.permissionMode ?? 'ask'
const sessionDefaults = preferences?.sessionDefaults
const permissionMode = sessionDefaults?.permissionMode ?? 'ask'
const goalMaxContinuations = sessionDefaults?.goalMaxContinuations ?? 20
const goalTokenBudget = sessionDefaults?.goalTokenBudget
const goalAuditorModel = sessionDefaults?.goalAuditorModel ?? ''
const updateSessionDefaults = (patch: Partial<SessionDefaults>) => {
updateSettings({
sessionDefaults: {
...sessionDefaults,
permissionMode,
...patch,
},
})
}
return (
<div className="space-y-6">
@@ -20,12 +35,7 @@ export function SessionAutomationSettings() {
</div>
<Select
value={permissionMode}
onValueChange={(value) => updateSettings({
sessionDefaults: {
...preferences?.sessionDefaults,
permissionMode: value as SessionPermissionMode,
},
})}
onValueChange={(value) => updateSessionDefaults({ permissionMode: value as SessionPermissionMode })}
>
<SelectTrigger id="sessionPermissionMode" className="w-full shrink-0 sm:w-40">
<SelectValue placeholder="Select a mode" />
@@ -36,6 +46,73 @@ 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, as provider/model. Leave empty to use the OpenCode default model.
</p>
</div>
<Input
id="goalAuditorModel"
value={goalAuditorModel}
placeholder="provider/model"
className="w-full shrink-0 sm:w-64"
onChange={(event) => updateSessionDefaults({ goalAuditorModel: event.target.value.trim() || undefined })}
/>
</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={1}
max={200}
value={goalMaxContinuations}
className="w-full shrink-0 sm:w-40"
onChange={(event) => {
const value = Number(event.target.value)
if (Number.isInteger(value) && value >= 1 && value <= 200) {
updateSessionDefaults({ goalMaxContinuations: value })
}
}}
/>
</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={goalTokenBudget ?? ''}
placeholder="No limit"
className="w-full shrink-0 sm:w-40"
onChange={(event) => {
const raw = event.target.value
if (raw === '') {
updateSessionDefaults({ goalTokenBudget: undefined })
return
}
const value = Number(raw)
if (Number.isInteger(value) && value > 0) {
updateSessionDefaults({ goalTokenBudget: value })
}
}}
/>
</div>
</div>
)
}
+57
View File
@@ -0,0 +1,57 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
cancelSessionGoal,
getLatestSessionGoal,
pauseSessionGoal,
resumeSessionGoal,
startSessionGoal,
} from '@/api/sessionGoals'
import { showToast } from '@/lib/toast'
import type { SessionGoal, StartSessionGoalRequest } from '@opencode-manager/shared/schemas'
export function sessionGoalQueryKey(sessionId: string) {
return ['session-goal', sessionId] as const
}
export function useSessionGoal(sessionId: string) {
return useQuery({
queryKey: sessionGoalQueryKey(sessionId),
queryFn: () => getLatestSessionGoal(sessionId),
refetchInterval: (query) => {
const status = query.state.data?.status
return status === 'active' || status === 'paused' ? 3000 : false
},
})
}
function useGoalMutation<TInput>(
mutationFn: (input: TInput) => Promise<SessionGoal>,
errorMessage: string,
) {
const queryClient = useQueryClient()
return useMutation({
mutationFn,
onSuccess: (goal: SessionGoal) => {
queryClient.setQueryData(sessionGoalQueryKey(goal.sessionId), goal)
},
onError: (error: unknown) => {
showToast.error(error instanceof Error ? error.message : errorMessage)
},
})
}
export function useStartSessionGoal() {
return useGoalMutation((input: StartSessionGoalRequest) => startSessionGoal(input), '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')
}
+2
View File
@@ -52,6 +52,7 @@ import { PendingActionsGroup } from "@/components/notifications/PendingActionsGr
import { SourceControlPanel } from "@/components/source-control";
import { SessionSendErrorBanner } from "@/components/session/SessionSendErrorBanner";
import { BackgroundWorkBar } from "@/components/session/BackgroundWorkBar";
import { SessionGoalBar } from "@/components/session/SessionGoalBar";
import { useDialogParam } from "@/hooks/useDialogParam";
import { SessionMoreButton } from "@/components/navigation/SessionMoreButton";
import { SideQuestionDialog } from "@/components/session/SideQuestionDialog";
@@ -759,6 +760,7 @@ export function SessionDetail() {
/>
)}
<SessionSendErrorBanner sessionId={sessionId} isConnected={isConnected} isReconnecting={isReconnecting} />
<SessionGoalBar sessionID={sessionId} />
<BackgroundWorkBar
sessionID={sessionId}
directory={sessionDirectory}
@@ -120,6 +120,14 @@ vi.mock('@/api/repos', () => ({
}))
vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: vi.fn(() => null) }))
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 })),
}))
vi.mock('@/components/session/SessionList', () => ({
SessionList: vi.fn(() => null),
}))
@@ -193,6 +193,14 @@ vi.mock('@/api/repos', () => ({
}))
vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: vi.fn(() => null) }))
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 })),
}))
vi.mock('@/components/session/SideQuestionDialog', () => ({ SideQuestionDialog: vi.fn(() => null) }))
vi.mock('@/components/session/SessionList', () => ({ SessionList: vi.fn(() => null) }))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) }))
@@ -151,6 +151,14 @@ vi.mock('@/api/repos', () => ({
}))
vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: vi.fn(() => null) }))
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 })),
}))
vi.mock('@/components/session/SessionList', () => ({
SessionList: vi.fn(() => null),
}))
@@ -126,6 +126,14 @@ vi.mock('@/api/repos', () => ({
}))
vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: vi.fn(() => null) }))
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 })),
}))
vi.mock('@/components/session/SessionList', () => ({ SessionList: vi.fn(() => null) }))
vi.mock('@/components/session/PermissionModeToggle', () => ({ PermissionModeToggle: vi.fn(() => null) }))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) }))
@@ -145,6 +145,14 @@ vi.mock('@/api/repos', () => ({
}))
vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: vi.fn(() => null) }))
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 })),
}))
vi.mock('@/components/session/SessionList', () => ({
SessionList: vi.fn(() => null),
}))