diff --git a/frontend/src/api/sessionGoals.ts b/frontend/src/api/sessionGoals.ts new file mode 100644 index 00000000..e0d402a5 --- /dev/null +++ b/frontend/src/api/sessionGoals.ts @@ -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 { + 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 { + 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 { + 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 { + return runGoalAction(id, 'pause') +} + +export function resumeSessionGoal(id: number): Promise { + return runGoalAction(id, 'resume') +} + +export function cancelSessionGoal(id: number): Promise { + return runGoalAction(id, 'cancel') +} diff --git a/frontend/src/components/message/PromptInput.command.test.tsx b/frontend/src/components/message/PromptInput.command.test.tsx index ddbb1ee5..40bd405a 100644 --- a/frontend/src/components/message/PromptInput.command.test.tsx +++ b/frontend/src/components/message/PromptInput.command.test.tsx @@ -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: () =>
SessionStatus
, })) diff --git a/frontend/src/components/message/PromptInput.goal.test.tsx b/frontend/src/components/message/PromptInput.goal.test.tsx new file mode 100644 index 00000000..2a4917e1 --- /dev/null +++ b/frontend/src/components/message/PromptInput.goal.test.tsx @@ -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() + 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 }) =>
{children}
, +})) + +vi.mock('@/components/model/ModelQuickSelect', () => ({ + ModelQuickSelect: ({ children, open }: { children?: React.ReactNode; open?: boolean }) => ( +
{children}
+ ), +})) + +vi.mock('@/components/session/PermissionModeToggle', () => ({ + PermissionModeToggle: () => null, +})) + +vi.mock('@/components/ui/session-status-indicator', () => ({ + SessionStatusIndicator: () =>
SessionStatus
, +})) + +vi.mock('@/components/command/CommandSuggestions', () => ({ + CommandSuggestions: () =>
CommandSuggestions
, +})) + +vi.mock('./MentionSuggestions', () => ({ + MentionSuggestions: () =>
MentionSuggestions
, +})) + +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( + + + + ) + } + + 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() + }) +}) diff --git a/frontend/src/components/message/PromptInput.mention.test.tsx b/frontend/src/components/message/PromptInput.mention.test.tsx index 76419973..444e9b5a 100644 --- a/frontend/src/components/message/PromptInput.mention.test.tsx +++ b/frontend/src/components/message/PromptInput.mention.test.tsx @@ -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: () =>
SessionStatus
, })) diff --git a/frontend/src/components/message/PromptInput.stt.test.tsx b/frontend/src/components/message/PromptInput.stt.test.tsx index 555d658e..1badd860 100644 --- a/frontend/src/components/message/PromptInput.stt.test.tsx +++ b/frontend/src/components/message/PromptInput.stt.test.tsx @@ -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: () =>
SessionStatus
, })) diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index bf734a90..5b21fd6d 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -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( }, 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()) @@ -229,6 +231,8 @@ export const PromptInput = memo(forwardRef( 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( 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( 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 ? ( + + ) : 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 && } + {goalModeButton} ) : ( <> @@ -1357,6 +1395,7 @@ return ( isBashMode={isBashMode} /> {directory && } + {goalModeButton} {isSessionActive && (
diff --git a/frontend/src/components/session/SessionGoalBar.test.tsx b/frontend/src/components/session/SessionGoalBar.test.tsx new file mode 100644 index 00000000..a8339d28 --- /dev/null +++ b/frontend/src/components/session/SessionGoalBar.test.tsx @@ -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 + resume?: ReturnType + cancel?: ReturnType + } = {}, +) { + vi.mocked(useSessionGoal).mockReturnValue({ data: goal } as ReturnType) + vi.mocked(usePauseSessionGoal).mockReturnValue({ + mutate: overrides.pause ?? vi.fn(), + isPending: false, + } as unknown as ReturnType) + vi.mocked(useResumeSessionGoal).mockReturnValue({ + mutate: overrides.resume ?? vi.fn(), + isPending: false, + } as unknown as ReturnType) + vi.mocked(useCancelSessionGoal).mockReturnValue({ + mutate: overrides.cancel ?? vi.fn(), + isPending: false, + } as unknown as ReturnType) +} + +describe('SessionGoalBar', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('renders nothing when there is no goal', () => { + mockGoals(null) + const { container } = render() + 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() + + 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() + + 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() + + 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() + + 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() + + await user.click(screen.getByRole('button', { name: 'Cancel' })) + + expect(cancel).toHaveBeenCalledWith(1) + }) +}) diff --git a/frontend/src/components/session/SessionGoalBar.tsx b/frontend/src/components/session/SessionGoalBar.tsx new file mode 100644 index 00000000..a9dd9194 --- /dev/null +++ b/frontend/src/components/session/SessionGoalBar.tsx @@ -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 = { + active: 'Goal active', + paused: 'Goal paused', + completed: 'Goal completed', + blocked: 'Goal blocked', + stopped: 'Goal stopped', +} + +const STOP_REASON_LABELS: Record = { + 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 = { + 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(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 ( +
+
+ + + {STATUS_LABELS[goal.status]} + + + {!terminal && ( + + Turn {goal.continuationCount}/{goal.maxContinuations} + + )} + + {!terminal && goal.tokenBudget !== null && ( + + {goal.tokensUsed.toLocaleString()}/{goal.tokenBudget.toLocaleString()} tokens + + )} + + {terminal ? ( + <> + {reason && ( + + {reason} + + )} + + + ) : ( +
+ {goal.status === 'paused' ? ( + + ) : ( + + )} + +
+ )} +
+ + {!terminal && ( +
+

+ {goal.objective} +

+ +
+ )} + + {!terminal && goal.lastReason && ( +

+ {goal.lastReason} +

+ )} +
+ ) +} diff --git a/frontend/src/components/settings/NotificationSettings.test.tsx b/frontend/src/components/settings/NotificationSettings.test.tsx index 26b42314..420330bb 100644 --- a/frontend/src/components/settings/NotificationSettings.test.tsx +++ b/frontend/src/components/settings/NotificationSettings.test.tsx @@ -170,4 +170,18 @@ describe('NotificationSettings', () => { render() 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() + + const toggle = screen.getByRole('switch', { name: 'Goal outcomes' }) + expect(toggle).toBeChecked() + + await user.click(toggle) + + expect(updateEventPreference).toHaveBeenCalledWith('goalOutcome', false) + }) }) diff --git a/frontend/src/components/settings/NotificationSettings.tsx b/frontend/src/components/settings/NotificationSettings.tsx index 479140d9..ab876109 100644 --- a/frontend/src/components/settings/NotificationSettings.tsx +++ b/frontend/src/components/settings/NotificationSettings.tsx @@ -213,6 +213,24 @@ export function NotificationSettings() { } />
+ +
+
+ +

+ When a session goal completes, blocks or stops +

+
+ + updateEventPreference("goalOutcome", checked) + } + /> +
)} diff --git a/frontend/src/components/settings/SessionAutomationSettings.test.tsx b/frontend/src/components/settings/SessionAutomationSettings.test.tsx index 36296dd9..12f2be9a 100644 --- a/frontend/src/components/settings/SessionAutomationSettings.test.tsx +++ b/frontend/src/components/settings/SessionAutomationSettings.test.tsx @@ -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() + + 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() + + 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() + + fireEvent.change(screen.getByLabelText('Token budget per goal'), { + target: { value: '5000' }, + }) + + expect(updateSettings).toHaveBeenCalledWith({ + sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20, goalTokenBudget: 5000 }, + }) + }) }) diff --git a/frontend/src/components/settings/SessionAutomationSettings.tsx b/frontend/src/components/settings/SessionAutomationSettings.tsx index fae9986d..c00f016f 100644 --- a/frontend/src/components/settings/SessionAutomationSettings.tsx +++ b/frontend/src/components/settings/SessionAutomationSettings.tsx @@ -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) => { + updateSettings({ + sessionDefaults: { + ...sessionDefaults, + permissionMode, + ...patch, + }, + }) + } return (
@@ -20,12 +35,7 @@ export function SessionAutomationSettings() {
+ +
+
+ +

+ Model that decides whether a session goal is done, as provider/model. Leave empty to use the OpenCode default model. +

+
+ updateSessionDefaults({ goalAuditorModel: event.target.value.trim() || undefined })} + /> +
+ +
+
+ +

+ How many times a goal may keep the agent working after each audit before it stops. +

+
+ { + const value = Number(event.target.value) + if (Number.isInteger(value) && value >= 1 && value <= 200) { + updateSessionDefaults({ goalMaxContinuations: value }) + } + }} + /> +
+ +
+
+ +

+ Stop a goal once it has spent this many tokens. Leave empty for no limit. +

+
+ { + const raw = event.target.value + if (raw === '') { + updateSessionDefaults({ goalTokenBudget: undefined }) + return + } + const value = Number(raw) + if (Number.isInteger(value) && value > 0) { + updateSessionDefaults({ goalTokenBudget: value }) + } + }} + /> +
) } diff --git a/frontend/src/hooks/useSessionGoals.ts b/frontend/src/hooks/useSessionGoals.ts new file mode 100644 index 00000000..b9c32da2 --- /dev/null +++ b/frontend/src/hooks/useSessionGoals.ts @@ -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( + mutationFn: (input: TInput) => Promise, + 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') +} diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index e130c60f..a1ed0eb0 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -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() { /> )} + ({ })) 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), })) diff --git a/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx b/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx index fba20fc5..fc4b37ea 100644 --- a/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx @@ -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) })) diff --git a/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx b/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx index 762afecd..0353e649 100644 --- a/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx @@ -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), })) diff --git a/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx b/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx index 5cf9ad1b..c98a23d3 100644 --- a/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx @@ -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) })) diff --git a/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx b/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx index 0772e469..c5786f8a 100644 --- a/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx @@ -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), }))