feat(sessions): add permission modes, session goals, ocm session tool and multi-run

Per-session permission modes: each root session runs in ask or auto.
Auto answers each permission request once from the backend, child
sessions inherit their root's mode, forks copy the source's mode, and
scheduled runs and agent-created sessions stay on ask. A lock reason
reports why a session's mode cannot change.

Session goals: arm a goal in the composer and a backend audit loop keeps
the session working until an auditor model returns done or blocked. The
loop is bounded by continuation and token limits, survives restarts, and
pushes an outcome notification. Goals cannot start on scheduled-run or
child sessions.

ocm session tool: allow-listed internal routes to list, create, follow up
on, read replies from, and fork sessions. Created and forked sessions are
pinned to ask, listing covers a repo's workspaces, and replies wait for
the session to settle with a capped response.

Multi-run: launch one prompt on up to five models, optionally each in its
own OpenCode workspace, with per-entry status and discard.

Also add the shared owners this group needed (session launcher, session
reply, workspace create/remove, multi-run storage) and update the feature
docs.
This commit is contained in:
Chris Scott committed 2026-10-03 21:16:05 -04:00
1 parent 2af2577af8
commit 96e02e9646
91 files changed
+2140 -688

No files matched your search

@@ -91,6 +91,10 @@ vi.mock('@/hooks/useSessionGoals', () => ({
useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }),
}))
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: () => ({ data: undefined }),
}))
vi.mock('@/components/ui/session-status-indicator', () => ({
SessionStatusIndicator: () => <div>SessionStatus</div>,
}))
@@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => ({
interrupt: vi.fn(),
startGoal: vi.fn(),
useSessionGoal: vi.fn(),
useSessionPermissionMode: vi.fn(),
agents: [] as Array<{ id: string; name: string; description?: string; mode?: string; hidden?: boolean }>,
setAgent: vi.fn(),
cycleVariant: vi.fn(),
@@ -51,6 +52,10 @@ vi.mock('@/hooks/useSessionGoals', () => ({
useStartSessionGoal: () => ({ mutateAsync: mocks.startGoal, isPending: false }),
}))
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: mocks.useSessionPermissionMode,
}))
vi.mock('@/hooks/useSTT', () => ({ useSTT: mocks.useSTT }))
vi.mock('@/hooks/useMobile', () => ({ useMobile: mocks.useMobile }))
vi.mock('@/hooks/useCommands', () => ({ useCommands: mocks.useCommands }))
@@ -118,11 +123,11 @@ describe('PromptInput goal mode', () => {
onPromptChange: vi.fn(),
}
const renderComponent = () => {
const renderComponent = (overrides: Partial<typeof defaultProps> = {}) => {
const queryClient = createTestQueryClient()
return render(
<QueryClientProvider client={queryClient}>
<PromptInput {...defaultProps} />
<PromptInput {...defaultProps} {...overrides} />
</QueryClientProvider>
)
}
@@ -130,6 +135,7 @@ describe('PromptInput goal mode', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useSessionGoal.mockReturnValue({ data: null })
mocks.useSessionPermissionMode.mockReturnValue({ data: undefined })
mocks.startGoal.mockResolvedValue({ id: 1 })
mocks.agents = []
mocks.useMobile.mockReturnValue(false)
@@ -214,6 +220,41 @@ describe('PromptInput goal mode', () => {
expect(mocks.startGoal).not.toHaveBeenCalled()
})
it('starts an armed goal before queueing when the session is busy', async () => {
stubMatchMedia(true)
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).toHaveBeenCalledWith({
sessionId: 'test-session',
directory: '/test',
objective: 'Ship the feature',
}))
await waitFor(() => expect(mocks.sendPrompt).toHaveBeenCalledWith(
expect.objectContaining({ delivery: 'queue' }),
expect.anything(),
))
expect(mocks.startGoal.mock.invocationCallOrder[0]).toBeLessThan(mocks.sendPrompt.mock.invocationCallOrder[0])
})
it('does not start an armed goal for a slash command', async () => {
stubMatchMedia(true)
mocks.useCommands.mockReturnValue({ filterCommands: () => [{ name: 'review' }] })
renderComponent({ isStreamingResponse: true })
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '/review the diff' } })
fireEvent.click(screen.getByRole('button', { name: GOAL_BUTTON }))
fireEvent.click(screen.getByTitle('Queue message'))
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' } })
@@ -222,4 +263,26 @@ describe('PromptInput goal mode', () => {
const button = await screen.findByRole('button', { name: OPEN_GOAL_BUTTON })
expect(button).toBeDisabled()
})
it('disables goal mode with a reason for scheduled-run sessions', async () => {
stubMatchMedia(true)
mocks.useSessionPermissionMode.mockReturnValue({
data: { sessionId: 'test-session', rootSessionId: 'test-session', mode: 'ask', lockedReason: 'schedule' },
})
renderComponent()
const button = await screen.findByRole('button', { name: 'Scheduled runs cannot run goals' })
expect(button).toBeDisabled()
})
it('disables goal mode with a reason for child sessions', async () => {
stubMatchMedia(true)
mocks.useSessionPermissionMode.mockReturnValue({
data: { sessionId: 'test-session', rootSessionId: 'test-session', mode: 'ask', lockedReason: 'child' },
})
renderComponent()
const button = await screen.findByRole('button', { name: 'Goals can only be started on top-level sessions' })
expect(button).toBeDisabled()
})
})
@@ -82,6 +82,10 @@ vi.mock('@/hooks/useSessionGoals', () => ({
useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }),
}))
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: () => ({ data: undefined }),
}))
vi.mock('@/components/ui/session-status-indicator', () => ({
SessionStatusIndicator: () => <div>SessionStatus</div>,
}))
@@ -109,6 +109,10 @@ vi.mock('@/hooks/useSessionGoals', () => ({
useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }),
}))
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: () => ({ data: undefined }),
}))
vi.mock('@/components/ui/session-status-indicator', () => ({
SessionStatusIndicator: () => <div>SessionStatus</div>,
}))
+36 -24
View File
@@ -20,6 +20,7 @@ import { usePermissions } from '@/contexts/EventContext'
import { ArrowDown, Upload, X, Mic, MicOff, Target } from 'lucide-react'
import { SquareFill } from '@/components/ui/square-fill'
import { IconToggleButton } from '@/components/ui/icon-toggle-button'
import { CommandSuggestions } from '@/components/command/CommandSuggestions'
import { MentionSuggestions, type MentionItem } from './MentionSuggestions'
@@ -29,6 +30,7 @@ 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 { useSessionPermissionMode } from '@/hooks/useSessionPermissionMode'
import { detectMentionTrigger, parsePromptToInput, getFilename, filterAgentsByQuery } from '@/lib/promptParser'
import { getNextPrimaryAgentId } from '@/lib/primaryAgents'
import { randomId } from '@/lib/utils'
@@ -233,6 +235,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const interruptSession = useInterruptSession()
const { data: sessionGoal } = useSessionGoal(sessionID)
const startGoal = useStartSessionGoal()
const { data: permissionMode } = useSessionPermissionMode(sessionID)
const { filterCommands } = useCommands({ directory })
const isExactCommandPrompt = (value: string) => {
const commandPrompt = parseCommandPrompt(value)
@@ -295,6 +298,17 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const addUserBashCommand = useUserBash((s) => s.addUserBashCommand)
const startArmedGoal = async (objective: string): Promise<boolean> => {
if (!directory || !objective.trim()) return true
try {
await startGoal.mutateAsync({ sessionId: sessionID, directory, objective })
} catch {
return false
}
setIsGoalArmed(false)
return true
}
const handleSubmit = async () => {
if (!prompt.trim() && imageAttachments.length === 0) return
@@ -307,6 +321,10 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const submittedPrompt = prompt
const submittedAttachedFiles = attachedFiles
const submittedImageAttachments = imageAttachments
if (isGoalArmed && !isBashMode && !isExactCommandPrompt(prompt)) {
const goalStarted = await startArmedGoal(parsed.text)
if (!goalStarted) return
}
sendPrompt.mutate(
{
sessionID,
@@ -389,13 +407,9 @@ 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)
if (isGoalArmed) {
const goalStarted = await startArmedGoal(parsed.text)
if (!goalStarted) return
}
pendingConfirmClearRef.current = {
@@ -1162,27 +1176,25 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
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 lockedReason = permissionMode?.lockedReason ?? null
const goalButtonLabel = lockedReason === 'schedule'
? 'Scheduled runs cannot run goals'
: lockedReason === 'child'
? 'Goals can only be started on top-level sessions'
: hasOpenGoal
? 'A goal is already active for this session'
: isGoalArmed
? 'Goal mode armed: the next message becomes the objective'
: 'Goal mode: the next message becomes the objective'
const goalModeButton = directory ? (
<button
type="button"
<IconToggleButton
active={isGoalArmed}
label={goalButtonLabel}
disabled={lockedReason !== null || hasOpenGoal || isBashMode || startGoal.isPending}
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>
</IconToggleButton>
) : null
const voiceFeedbackState: VoiceStatusOverlayState | null = isTogglingRecording
? 'starting'
@@ -60,6 +60,7 @@ const providers = [
{ id: 'claude-opus', name: 'Claude Opus' },
{ id: 'claude-sonnet', name: 'Claude Sonnet' },
{ id: 'claude-haiku', name: 'Claude Haiku' },
{ id: 'claude-sonnet-4-5', key: 'claude-sonnet-4.5', name: 'Claude Sonnet 4.5' },
],
},
]
@@ -164,6 +165,28 @@ describe('MultiRunDialog', () => {
})
})
it('submits the catalog id for configured model aliases', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockResolvedValue(startedRun)
renderDialog()
await user.type(screen.getByLabelText('Group name'), 'Sweep')
await user.type(screen.getByLabelText('Prompt'), 'go')
await user.click(screen.getByRole('checkbox', { name: 'Claude Sonnet 4.5' }))
await user.click(screen.getByRole('button', { name: 'Launch' }))
await waitFor(() => {
expect(mocks.launchMultiRun).toHaveBeenCalledWith({
repoId: 7,
name: 'Sweep',
prompt: 'go',
models: ['anthropic/claude-sonnet-4.5'],
isolate: true,
baseRef: 'main',
})
})
})
it('lists run entries with Open and Discard actions', async () => {
const user = userEvent.setup()
mocks.listMultiRuns.mockResolvedValue([startedRun])
+53 -32
View File
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useState } from 'react'
import { memo, useCallback, useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Loader2, Trash2, ArrowUpRight } from 'lucide-react'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
@@ -14,6 +14,8 @@ import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-di
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { useProvidersWithModels } from '@/hooks/useProvidersWithModels'
import { useDiscardMultiRunEntry, useLaunchMultiRun, useMultiRuns } from '@/hooks/useMultiRuns'
import { formatModelName, formatProviderName, providerModelRef, type ProviderWithModels } from '@/api/providers'
import { buildSessionPath } from '@opencode-manager/shared/utils'
import {
MULTI_RUN_MAX_MODELS,
type LaunchMultiRunRequest,
@@ -79,7 +81,7 @@ export function MultiRunDialog({
[providers],
)
const toggleModel = (value: string, checked: boolean) => {
const toggleModel = useCallback((value: string, checked: boolean) => {
setSelectedModels((current) => {
if (checked) {
if (current.includes(value) || current.length >= MULTI_RUN_MAX_MODELS) return current
@@ -87,7 +89,7 @@ export function MultiRunDialog({
}
return current.filter((model) => model !== value)
})
}
}, [])
const canSubmit =
name.trim().length > 0 && prompt.trim().length > 0 && selectedModels.length > 0 && !launch.isPending
@@ -108,8 +110,7 @@ export function MultiRunDialog({
const openEntry = (entry: MultiRunEntry) => {
if (!entry.sessionId) return
onOpenChange(false)
const suffix = entry.isolated ? '?repoTab=workspaces' : ''
navigate(`/repos/${repoId}/sessions/${entry.sessionId}${suffix}`)
navigate(buildSessionPath(repoId, entry.sessionId, entry.isolated ? { repoTab: 'workspaces' } : undefined))
}
const confirmDiscard = () => {
@@ -171,33 +172,11 @@ export function MultiRunDialog({
</span>
</div>
<div className="max-h-56 overflow-y-auto rounded-md border border-border divide-y divide-border">
{modelGroups.length === 0 ? (
<p className="p-3 text-sm text-muted-foreground">No models available.</p>
) : (
modelGroups.map((provider) => (
<div key={provider.id} className="p-3 space-y-2">
<p className="text-xs font-medium text-muted-foreground">
{provider.name || provider.id}
</p>
{provider.models.map((model) => {
const value = `${provider.id}/${model.id}`
const checked = selectedModels.includes(value)
const atCapacity = selectedModels.length >= MULTI_RUN_MAX_MODELS && !checked
return (
<label key={value} className="flex items-center gap-2 text-sm">
<Checkbox
aria-label={model.name || model.id}
checked={checked}
disabled={atCapacity}
onCheckedChange={(next) => toggleModel(value, next === true)}
/>
<span className="truncate">{model.name || model.id}</span>
</label>
)
})}
</div>
))
)}
<ModelCheckboxList
providers={modelGroups}
selectedModels={selectedModels}
onToggle={toggleModel}
/>
</div>
</div>
@@ -321,6 +300,48 @@ export function MultiRunDialog({
)
}
interface ModelCheckboxListProps {
providers: ProviderWithModels[]
selectedModels: string[]
onToggle: (value: string, checked: boolean) => void
}
const ModelCheckboxList = memo(function ModelCheckboxList({
providers,
selectedModels,
onToggle,
}: ModelCheckboxListProps) {
if (providers.length === 0) {
return <p className="p-3 text-sm text-muted-foreground">No models available.</p>
}
return (
<>
{providers.map((provider) => (
<div key={provider.id} className="p-3 space-y-2">
<p className="text-xs font-medium text-muted-foreground">{formatProviderName(provider)}</p>
{provider.models.map((model) => {
const value = providerModelRef(provider, model)
const checked = selectedModels.includes(value)
const atCapacity = selectedModels.length >= MULTI_RUN_MAX_MODELS && !checked
return (
<label key={value} className="flex items-center gap-2 text-sm">
<Checkbox
aria-label={formatModelName(model)}
checked={checked}
disabled={atCapacity}
onCheckedChange={(next) => onToggle(value, next === true)}
/>
<span className="truncate">{formatModelName(model)}</span>
</label>
)
})}
</div>
))}
</>
)
})
function EntryStatus({ entry }: { entry: MultiRunEntry }) {
if (entry.status === 'started' && entry.sessionId) {
return (
@@ -21,7 +21,8 @@ vi.mock('@/hooks/usePromptTemplates', () => ({
useDeletePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
}))
vi.mock('@/api/providers', () => ({
vi.mock('@/api/providers', async (importOriginal) => ({
...(await importOriginal<typeof import('@/api/providers')>()),
getProvidersWithModels: mockGetProvidersWithModels,
}))
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import type { CreateScheduleJobRequest, PromptTemplate, ScheduleJob, ScheduleMcpServer } from '@opencode-manager/shared/types'
import { useScheduleModels } from '@/hooks/useScheduleModels'
import { providerModelRef } from '@/api/providers'
import { resolveScheduleModel } from '@/lib/schedules/schedule-model'
import { useAgents } from '@/hooks/useOpenCode'
import { useScheduleTarget } from '@/hooks/useScheduleTarget'
@@ -161,7 +162,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
const providerModel = provider?.models.find((m) => m.key === modelId || m.id === modelId)
configuredValues.add(configDefaultModel)
if (providerModel) {
configuredValues.add(`${providerId}/${providerModel.key ?? providerModel.id}`)
configuredValues.add(providerModelRef({ id: providerId }, providerModel))
configuredValues.add(`${providerId}/${providerModel.id}`)
}
configuredModels.push({
@@ -174,11 +175,11 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
const allModels = providerModels.flatMap((provider) =>
provider.models
.filter((providerModel) => !configuredValues.has(`${provider.id}/${providerModel.key ?? providerModel.id}`))
.filter((providerModel) => !configuredValues.has(providerModelRef(provider, providerModel)))
.map((providerModel) => ({
value: `${provider.id}/${providerModel.key ?? providerModel.id}`,
value: providerModelRef(provider, providerModel),
label: providerModel.name || providerModel.key || providerModel.id,
description: `${provider.id}/${providerModel.key ?? providerModel.id}`,
description: providerModelRef(provider, providerModel),
group: provider.name,
})),
)
@@ -11,7 +11,7 @@ const baseState: SessionPermissionModeState = {
sessionId: 'ses_1',
rootSessionId: 'ses_1',
mode: 'ask',
inherited: false,
lockedReason: null,
}
function mockHooks(overrides: {
@@ -66,14 +66,22 @@ describe('PermissionModeToggle', () => {
expect(mutate).toHaveBeenCalledWith({ directory: '/repo', mode: 'ask' })
})
it('is disabled and labelled as inherited for child sessions', () => {
mockHooks({ state: { inherited: true, mode: 'auto' } })
it('is disabled and labelled as locked for child sessions', () => {
mockHooks({ state: { lockedReason: 'child', mode: 'auto' } })
render(<PermissionModeToggle sessionID="ses_child" directory="/repo" />)
const button = screen.getByRole('button', { name: 'Inherited from parent session' })
expect(button).toBeDisabled()
})
it('is disabled and labelled for schedule-run sessions', () => {
mockHooks({ state: { lockedReason: 'schedule', mode: 'ask' } })
render(<PermissionModeToggle sessionID="ses_sched" directory="/repo" />)
const button = screen.getByRole('button', { name: "Scheduled runs use the schedule's permission configuration" })
expect(button).toBeDisabled()
})
it('cannot mutate while the mode read is still loading', async () => {
const user = userEvent.setup()
const mutate = vi.fn()
@@ -1,5 +1,6 @@
import { Shield, ShieldCheck } from 'lucide-react'
import { useSessionPermissionMode, useSetSessionPermissionMode } from '@/hooks/useSessionPermissionMode'
import { IconToggleButton } from '@/components/ui/icon-toggle-button'
interface PermissionModeToggleProps {
sessionID: string
@@ -12,18 +13,20 @@ export function PermissionModeToggle({ sessionID, directory }: PermissionModeTog
const loaded = data !== undefined
const isAuto = data?.mode === 'auto'
const inherited = data?.inherited ?? false
const disabled = !loaded || inherited || setMode.isPending
const lockedReason = data?.lockedReason ?? null
const disabled = !loaded || lockedReason !== null || setMode.isPending
const label = !loaded
? isError
? 'Permissions: unavailable'
: 'Permissions: loading'
: inherited
: lockedReason === 'child'
? 'Inherited from parent session'
: isAuto
? 'Permissions: accept everything'
: 'Permissions: ask every time'
: lockedReason === 'schedule'
? "Scheduled runs use the schedule's permission configuration"
: isAuto
? 'Permissions: accept everything'
: 'Permissions: ask every time'
const handleClick = () => {
if (disabled) return
@@ -31,19 +34,8 @@ export function PermissionModeToggle({ sessionID, directory }: PermissionModeTog
}
return (
<button
type="button"
onClick={handleClick}
disabled={disabled}
title={label}
aria-label={label}
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 ${
isAuto
? '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'
}`}
>
<IconToggleButton active={isAuto} label={label} disabled={disabled} onClick={handleClick}>
{isAuto ? <ShieldCheck className="w-5 h-5" /> : <Shield className="w-5 h-5" />}
</button>
</IconToggleButton>
)
}
@@ -107,7 +107,7 @@ describe('SessionGoalBar', () => {
render(<SessionGoalBar sessionID="ses_1" />)
expect(screen.getByText('Goal completed')).toBeInTheDocument()
expect(screen.getByText('continuation limit reached')).toBeInTheDocument()
expect(screen.getByText('Continuation limit reached')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Pause' })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Dismiss' }))
@@ -115,6 +115,22 @@ describe('SessionGoalBar', () => {
expect(screen.queryByText('Goal completed')).not.toBeInTheDocument()
})
it('shows the shared stop-reason wording for a user-paused goal', () => {
mockGoals({ ...baseGoal, status: 'stopped', stopReason: 'user_paused' })
render(<SessionGoalBar sessionID="ses_1" />)
expect(screen.getByText('Goal stopped')).toBeInTheDocument()
expect(screen.getByText('Paused by user')).toBeInTheDocument()
})
it('shows the shared stop-reason wording for an audit failure', () => {
mockGoals({ ...baseGoal, status: 'blocked', stopReason: 'audit_failed' })
render(<SessionGoalBar sessionID="ses_1" />)
expect(screen.getByText('Goal blocked')).toBeInTheDocument()
expect(screen.getByText('Audit failed')).toBeInTheDocument()
})
it('cancels the goal through the cancel API', async () => {
const user = userEvent.setup()
const cancel = vi.fn()
@@ -1,32 +1,15 @@
import { useState } from 'react'
import { ChevronDown, ChevronUp, Target } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
useCancelSessionGoal,
usePauseSessionGoal,
useResumeSessionGoal,
useSessionGoal,
} from '@/hooks/useSessionGoals'
import 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',
}
import { getGoalOutcomeTitle, getGoalStopReasonLabel } from '@opencode-manager/shared/notifications'
import type { SessionGoalStatus } from '@opencode-manager/shared/schemas'
const STATUS_CHIP_CLASSES: Record<SessionGoalStatus, string> = {
active: 'bg-highlight text-highlight-foreground border-highlight',
@@ -54,17 +37,18 @@ export function SessionGoalBar({ sessionID }: { sessionID: string }) {
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
const reason = goal.stopReason ? getGoalStopReasonLabel(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]}`}
<Badge
variant="outline"
className={`gap-1 px-2 py-0.5 font-medium ${STATUS_CHIP_CLASSES[goal.status]}`}
>
<Target className="h-3 w-3" />
{STATUS_LABELS[goal.status]}
</span>
{getGoalOutcomeTitle(goal.status)}
</Badge>
{!terminal && (
<span className="text-muted-foreground">
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { act, render, screen, fireEvent } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SessionAutomationSettings } from './SessionAutomationSettings'
import { useSettings } from '@/hooks/useSettings'
@@ -43,7 +43,7 @@ describe('SessionAutomationSettings', () => {
expect(screen.getByRole('combobox', { name: 'Default permission mode for new sessions' })).toHaveTextContent('Ask every time')
})
it('persists the chosen default permission mode', async () => {
it('persists the chosen default permission mode immediately', async () => {
const user = userEvent.setup()
const updateSettings = vi.fn()
mockUseSettings({
@@ -58,7 +58,7 @@ describe('SessionAutomationSettings', () => {
expect(updateSettings).toHaveBeenCalledWith({ sessionDefaults: { permissionMode: 'auto' } })
})
it('persists the goal auditor model', () => {
it('saves the goal auditor model once on blur with the final value', () => {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
@@ -66,10 +66,11 @@ describe('SessionAutomationSettings', () => {
})
render(<SessionAutomationSettings />)
fireEvent.change(screen.getByLabelText('Goal auditor model'), {
target: { value: 'anthropic/claude-sonnet-4' },
})
const input = screen.getByLabelText('Goal auditor model')
fireEvent.change(input, { target: { value: 'anthropic/claude-sonnet-4' } })
fireEvent.blur(input)
expect(updateSettings).toHaveBeenCalledTimes(1)
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: {
permissionMode: 'ask',
@@ -79,7 +80,37 @@ describe('SessionAutomationSettings', () => {
})
})
it('persists the max automatic continuations', () => {
it('saves the goal auditor model after the debounce without blurring', () => {
vi.useFakeTimers()
try {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
updateSettings,
})
render(<SessionAutomationSettings />)
fireEvent.change(screen.getByLabelText('Goal auditor model'), {
target: { value: 'anthropic/claude-sonnet-4' },
})
act(() => {
vi.advanceTimersByTime(800)
})
expect(updateSettings).toHaveBeenCalledTimes(1)
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: {
permissionMode: 'ask',
goalMaxContinuations: 20,
goalAuditorModel: 'anthropic/claude-sonnet-4',
},
})
} finally {
vi.useRealTimers()
}
})
it('saves an in-range max automatic continuations on blur', () => {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
@@ -87,16 +118,16 @@ describe('SessionAutomationSettings', () => {
})
render(<SessionAutomationSettings />)
fireEvent.change(screen.getByLabelText('Max automatic continuations'), {
target: { value: '50' },
})
const input = screen.getByLabelText('Max automatic continuations')
fireEvent.change(input, { target: { value: '50' } })
fireEvent.blur(input)
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 50 },
})
})
it('persists the token budget per goal', () => {
it('does not save out-of-range max automatic continuations', () => {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
@@ -104,9 +135,24 @@ describe('SessionAutomationSettings', () => {
})
render(<SessionAutomationSettings />)
fireEvent.change(screen.getByLabelText('Token budget per goal'), {
target: { value: '5000' },
const input = screen.getByLabelText('Max automatic continuations')
fireEvent.change(input, { target: { value: '500' } })
fireEvent.blur(input)
expect(updateSettings).not.toHaveBeenCalled()
})
it('saves the token budget per goal on blur', () => {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
updateSettings,
})
render(<SessionAutomationSettings />)
const input = screen.getByLabelText('Token budget per goal')
fireEvent.change(input, { target: { value: '5000' } })
fireEvent.blur(input)
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20, goalTokenBudget: 5000 },
@@ -1,26 +1,97 @@
import { useCallback, useEffect, useRef, useState } from 'react'
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 { SessionDefaults, SessionPermissionMode } from '@opencode-manager/shared/schemas'
import {
DEFAULT_SESSION_DEFAULTS,
GOAL_MAX_CONTINUATIONS_MAX,
GOAL_MAX_CONTINUATIONS_MIN,
type SessionDefaults,
type SessionPermissionMode,
} from '@opencode-manager/shared/schemas'
const AUTOSAVE_DELAY_MS = 800
export function SessionAutomationSettings() {
const { preferences, updateSettings } = useSettings()
const sessionDefaults = preferences?.sessionDefaults
const permissionMode = sessionDefaults?.permissionMode ?? 'ask'
const goalMaxContinuations = sessionDefaults?.goalMaxContinuations ?? 20
const goalTokenBudget = sessionDefaults?.goalTokenBudget
const goalAuditorModel = sessionDefaults?.goalAuditorModel ?? ''
const permissionMode = sessionDefaults?.permissionMode ?? DEFAULT_SESSION_DEFAULTS.permissionMode
const updateSessionDefaults = (patch: Partial<SessionDefaults>) => {
updateSettings({
sessionDefaults: {
...sessionDefaults,
permissionMode,
...patch,
},
})
}
const [goalAuditorModel, setGoalAuditorModel] = useState(sessionDefaults?.goalAuditorModel ?? '')
const [goalMaxContinuations, setGoalMaxContinuations] = useState(
String(sessionDefaults?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations),
)
const [goalTokenBudget, setGoalTokenBudget] = useState(
sessionDefaults?.goalTokenBudget !== undefined ? String(sessionDefaults.goalTokenBudget) : '',
)
const committed = useRef({
goalAuditorModel: sessionDefaults?.goalAuditorModel,
goalMaxContinuations: sessionDefaults?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations,
goalTokenBudget: sessionDefaults?.goalTokenBudget,
})
useEffect(() => {
setGoalAuditorModel(sessionDefaults?.goalAuditorModel ?? '')
setGoalMaxContinuations(
String(sessionDefaults?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations),
)
setGoalTokenBudget(
sessionDefaults?.goalTokenBudget !== undefined ? String(sessionDefaults.goalTokenBudget) : '',
)
committed.current = {
goalAuditorModel: sessionDefaults?.goalAuditorModel,
goalMaxContinuations: sessionDefaults?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations,
goalTokenBudget: sessionDefaults?.goalTokenBudget,
}
}, [sessionDefaults])
const updateSessionDefaults = useCallback(
(patch: Partial<SessionDefaults>) => {
updateSettings({
sessionDefaults: {
...sessionDefaults,
permissionMode,
...patch,
},
})
},
[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 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 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])
useEffect(() => {
const timer = setTimeout(() => {
commitGoalAuditorModel()
commitGoalMaxContinuations()
commitGoalTokenBudget()
}, AUTOSAVE_DELAY_MS)
return () => clearTimeout(timer)
}, [commitGoalAuditorModel, commitGoalMaxContinuations, commitGoalTokenBudget])
return (
<div className="space-y-6">
@@ -59,7 +130,8 @@ export function SessionAutomationSettings() {
value={goalAuditorModel}
placeholder="provider/model"
className="w-full shrink-0 sm:w-64"
onChange={(event) => updateSessionDefaults({ goalAuditorModel: event.target.value.trim() || undefined })}
onChange={(event) => setGoalAuditorModel(event.target.value)}
onBlur={commitGoalAuditorModel}
/>
</div>
@@ -73,16 +145,12 @@ export function SessionAutomationSettings() {
<Input
id="goalMaxContinuations"
type="number"
min={1}
max={200}
min={GOAL_MAX_CONTINUATIONS_MIN}
max={GOAL_MAX_CONTINUATIONS_MAX}
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 })
}
}}
onChange={(event) => setGoalMaxContinuations(event.target.value)}
onBlur={commitGoalMaxContinuations}
/>
</div>
@@ -97,20 +165,11 @@ export function SessionAutomationSettings() {
id="goalTokenBudget"
type="number"
min={1}
value={goalTokenBudget ?? ''}
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 })
}
}}
onChange={(event) => setGoalTokenBudget(event.target.value)}
onBlur={commitGoalTokenBudget}
/>
</div>
</div>
@@ -0,0 +1,29 @@
import type { ReactNode } from 'react'
interface IconToggleButtonProps {
active: boolean
label: string
disabled?: boolean
onClick: () => void
children: ReactNode
}
export function IconToggleButton({ active, label, disabled = false, onClick, children }: IconToggleButtonProps) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
aria-pressed={active}
aria-label={label}
title={label}
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 ${
active
? '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'
}`}
>
{children}
</button>
)
}