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

@@ -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 />