fix(sessions): prevent duplicate goal starts and lost autosave updates

- Block prompt submission while an armed goal is starting.
- Launch multi-runs with mutate so a failed launch is not an
  unhandled rejection.
- Save changed session automation fields in one update so concurrent
  autosaves cannot overwrite each other.
This commit is contained in:
Chris Scott committed 2026-10-03 22:51:03 -04:00
1 parent 96e02e9646
commit 2072fae1b6
6 files changed
+137 -38

No files matched your search

@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput } from './PromptInput'
import { useUIState } from '@/stores/uiStateStore'
@@ -47,10 +47,26 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
}
})
vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: mocks.useSessionGoal,
useStartSessionGoal: () => ({ mutateAsync: mocks.startGoal, isPending: false }),
}))
vi.mock('@/hooks/useSessionGoals', async () => {
const { useState } = await import('react')
return {
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,
}
},
}
})
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: mocks.useSessionPermissionMode,
@@ -241,6 +257,33 @@ describe('PromptInput goal mode', () => {
expect(mocks.startGoal.mock.invocationCallOrder[0]).toBeLessThan(mocks.sendPrompt.mock.invocationCallOrder[0])
})
it('does not start the goal again while it is still starting', async () => {
stubMatchMedia(true)
let resolveGoal: (value: unknown) => void = () => {}
mocks.startGoal.mockImplementation(
() => new Promise((resolve) => {
resolveGoal = resolve
}),
)
renderComponent({ isStreamingResponse: true })
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('Queue message'))
await waitFor(() => expect(mocks.startGoal).toHaveBeenCalledTimes(1))
fireEvent.click(screen.getByTitle('Queue message'))
expect(mocks.startGoal).toHaveBeenCalledTimes(1)
expect(mocks.sendPrompt).not.toHaveBeenCalled()
await act(async () => {
resolveGoal({ id: 1 })
})
})
it('does not start an armed goal for a slash command', async () => {
stubMatchMedia(true)
mocks.useCommands.mockReturnValue({ filterCommands: () => [{ name: 'review' }] })
@@ -231,10 +231,10 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const setStoredAgent = useSessionAgentStore((s) => s.setAgent)
const sendPrompt = useSendPrompt(directory)
const sendShell = useSendShell(directory)
const isPromptSubmitPending = sendPrompt.isPending || sendShell.isPending
const startGoal = useStartSessionGoal()
const isPromptSubmitPending = sendPrompt.isPending || sendShell.isPending || startGoal.isPending
const interruptSession = useInterruptSession()
const { data: sessionGoal } = useSessionGoal(sessionID)
const startGoal = useStartSessionGoal()
const { data: permissionMode } = useSessionPermissionMode(sessionID)
const { filterCommands } = useCommands({ directory })
const isExactCommandPrompt = (value: string) => {
@@ -311,6 +311,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const handleSubmit = async () => {
if (!prompt.trim() && imageAttachments.length === 0) return
if (startGoal.isPending) return
pendingVoiceAutoSubmitRef.current = false
setIsVoiceAutoSendPending(false)
@@ -165,6 +165,23 @@ describe('MultiRunDialog', () => {
})
})
it('keeps the launch tab when the launch request fails', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockRejectedValue(new Error('launch failed'))
renderDialog()
await user.type(screen.getByLabelText('Group name'), 'Sweep')
await user.type(screen.getByLabelText('Prompt'), 'go')
await user.click(screen.getByRole('checkbox', { name: 'GPT-4o' }))
await user.click(screen.getByRole('button', { name: 'Launch' }))
await waitFor(() => {
expect(mocks.launchMultiRun).toHaveBeenCalled()
})
expect(screen.getByLabelText('Group name')).toBeInTheDocument()
expect(screen.queryByText('No runs yet.')).not.toBeInTheDocument()
})
it('submits the catalog id for configured model aliases', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockResolvedValue(startedRun)
@@ -94,7 +94,7 @@ export function MultiRunDialog({
const canSubmit =
name.trim().length > 0 && prompt.trim().length > 0 && selectedModels.length > 0 && !launch.isPending
const handleLaunch = async () => {
const handleLaunch = () => {
const request: LaunchMultiRunRequest = {
repoId,
name: name.trim(),
@@ -103,8 +103,7 @@ export function MultiRunDialog({
isolate,
...(baseRef.trim() ? { baseRef: baseRef.trim() } : {}),
}
await launch.mutateAsync(request)
setActiveTab('runs')
launch.mutate(request, { onSuccess: () => setActiveTab('runs') })
}
const openEntry = (entry: MultiRunEntry) => {
@@ -200,7 +199,7 @@ export function MultiRunDialog({
</div>
<div className="flex justify-end">
<Button onClick={() => { void handleLaunch() }} disabled={!canSubmit}>
<Button onClick={handleLaunch} disabled={!canSubmit}>
{launch.isPending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
@@ -110,6 +110,39 @@ describe('SessionAutomationSettings', () => {
}
})
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({
@@ -60,38 +60,44 @@ export function SessionAutomationSettings() {
[sessionDefaults, permissionMode, updateSettings],
)
const commitGoalAuditorModel = useCallback(() => {
const next = goalAuditorModel.trim() || undefined
if (next === committed.current.goalAuditorModel) return
committed.current.goalAuditorModel = next
updateSessionDefaults({ goalAuditorModel: next })
}, [goalAuditorModel, updateSessionDefaults])
const commitGoalFields = useCallback(() => {
const patch: Partial<SessionDefaults> = {}
const commitGoalMaxContinuations = useCallback(() => {
const value = Number(goalMaxContinuations)
if (!Number.isInteger(value) || value < GOAL_MAX_CONTINUATIONS_MIN || value > GOAL_MAX_CONTINUATIONS_MAX) return
if (value === committed.current.goalMaxContinuations) return
committed.current.goalMaxContinuations = value
updateSessionDefaults({ goalMaxContinuations: value })
}, [goalMaxContinuations, updateSessionDefaults])
const nextAuditorModel = goalAuditorModel.trim() || undefined
if (nextAuditorModel !== committed.current.goalAuditorModel) {
committed.current.goalAuditorModel = nextAuditorModel
patch.goalAuditorModel = nextAuditorModel
}
const commitGoalTokenBudget = useCallback(() => {
const next = goalTokenBudget.trim() === '' ? undefined : Number(goalTokenBudget)
if (next !== undefined && (!Number.isInteger(next) || next <= 0)) return
if (next === committed.current.goalTokenBudget) return
committed.current.goalTokenBudget = next
updateSessionDefaults({ goalTokenBudget: next })
}, [goalTokenBudget, updateSessionDefaults])
const nextMaxContinuations = Number(goalMaxContinuations)
if (
Number.isInteger(nextMaxContinuations) &&
nextMaxContinuations >= GOAL_MAX_CONTINUATIONS_MIN &&
nextMaxContinuations <= GOAL_MAX_CONTINUATIONS_MAX &&
nextMaxContinuations !== committed.current.goalMaxContinuations
) {
committed.current.goalMaxContinuations = nextMaxContinuations
patch.goalMaxContinuations = nextMaxContinuations
}
const nextTokenBudget = goalTokenBudget.trim() === '' ? undefined : Number(goalTokenBudget)
const tokenBudgetValid = nextTokenBudget === undefined || (Number.isInteger(nextTokenBudget) && nextTokenBudget > 0)
if (tokenBudgetValid && nextTokenBudget !== committed.current.goalTokenBudget) {
committed.current.goalTokenBudget = nextTokenBudget
patch.goalTokenBudget = nextTokenBudget
}
if (Object.keys(patch).length === 0) return
updateSessionDefaults(patch)
}, [goalAuditorModel, goalMaxContinuations, goalTokenBudget, updateSessionDefaults])
useEffect(() => {
const timer = setTimeout(() => {
commitGoalAuditorModel()
commitGoalMaxContinuations()
commitGoalTokenBudget()
commitGoalFields()
}, AUTOSAVE_DELAY_MS)
return () => clearTimeout(timer)
}, [commitGoalAuditorModel, commitGoalMaxContinuations, commitGoalTokenBudget])
}, [commitGoalFields])
return (
<div className="space-y-6">
@@ -131,7 +137,7 @@ export function SessionAutomationSettings() {
placeholder="provider/model"
className="w-full shrink-0 sm:w-64"
onChange={(event) => setGoalAuditorModel(event.target.value)}
onBlur={commitGoalAuditorModel}
onBlur={commitGoalFields}
/>
</div>
@@ -150,7 +156,7 @@ export function SessionAutomationSettings() {
value={goalMaxContinuations}
className="w-full shrink-0 sm:w-40"
onChange={(event) => setGoalMaxContinuations(event.target.value)}
onBlur={commitGoalMaxContinuations}
onBlur={commitGoalFields}
/>
</div>
@@ -169,7 +175,7 @@ export function SessionAutomationSettings() {
placeholder="No limit"
className="w-full shrink-0 sm:w-40"
onChange={(event) => setGoalTokenBudget(event.target.value)}
onBlur={commitGoalTokenBudget}
onBlur={commitGoalFields}
/>
</div>
</div>