feat(walkthrough): plan-then-explain generation with selectable diff sources

This commit is contained in:
Chris Scott committed 2026-10-08 15:53:49 -04:00
1 parent aeea96b466
commit 88b3543dc1
35 files changed
+2583 -609

No files matched your search

@@ -188,7 +188,7 @@ export function ToolSidePanel({
<>
{panelContent ? (
activeTool === 'walkthrough' && sessionId ? (
<ChangesWalkthroughProvider sessionId={sessionId} active>
<ChangesWalkthroughProvider key={sessionId} sessionId={sessionId} active>
{panelContent}
</ChangesWalkthroughProvider>
) : (
@@ -63,6 +63,53 @@ const walkthrough: ChangeWalkthrough = {
createdAt: 1,
}
const mechanicalWalkthrough: ChangeWalkthrough = {
...walkthrough,
stops: [
{
id: 's_mech',
title: 'Mechanical changes',
explanation: 'Lock files, snapshots and generated files.',
hunkIds: ['m_lock', 'm_snap', 'm_map'],
status: 'ready',
explanationKey: null,
},
],
hunks: [
{
id: 'm_lock',
file: 'pnpm-lock.yaml',
status: 'modified',
header: '@@ -1 +1 @@',
text: '@@ -1 +1 @@\n-old-lock\n+new-lock',
truncated: false,
additions: 120,
deletions: 80,
},
{
id: 'm_snap',
file: 'src/__snapshots__/a.ts.snap',
status: 'added',
header: '',
text: '',
truncated: true,
additions: 5,
deletions: 0,
},
{
id: 'm_map',
file: 'dist/app.js.map',
status: 'deleted',
header: '',
text: '',
truncated: true,
additions: 0,
deletions: 7,
},
],
omittedFiles: [],
}
function state(overrides: Partial<ChangeWalkthroughState> = {}): ChangeWalkthroughState {
return { walkthrough, currentDiffHash: 'hash-1', stale: false, generating: false, error: null, ...overrides }
}
@@ -223,7 +270,7 @@ describe('ChangesWalkthroughSheet', () => {
})
})
it('ignores an invalid pull request number', async () => {
it('prompts for a pull request number and withholds the actions until it is valid', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
mocks.generateChangeWalkthrough.mockResolvedValue(state())
@@ -236,17 +283,54 @@ describe('ChangesWalkthroughSheet', () => {
await user.type(number, '0')
await user.tab()
await user.click(screen.getByRole('button', { name: 'Generate walkthrough' }))
await waitFor(() => {
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', { source: { kind: 'session' } })
})
expect(await screen.findByText('Enter a pull request number')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Generate walkthrough' })).not.toBeInTheDocument()
expect(mocks.generateChangeWalkthrough).not.toHaveBeenCalled()
expect(mocks.getChangeWalkthrough).not.toHaveBeenCalledWith(
'ses_1',
expect.objectContaining({ kind: 'pullRequest' }),
)
})
it('commits a valid pull request number and restores the generate action', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
mocks.generateChangeWalkthrough.mockResolvedValue(state())
renderSheet()
await user.click(screen.getByRole('combobox', { name: 'Changes to walk through' }))
await user.click(await screen.findByRole('option', { name: 'Pull request' }))
const number = await screen.findByLabelText('Pull request number')
await user.type(number, '12')
await user.tab()
await waitFor(() => {
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'pullRequest', number: 12 })
})
expect(screen.queryByText('Enter a pull request number')).not.toBeInTheDocument()
expect(await screen.findByRole('button', { name: 'Generate walkthrough' })).toBeEnabled()
})
it('resets the source before querying a new session', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
const { rerender, onOpenChange } = renderSheet()
await user.click(screen.getByRole('combobox', { name: 'Changes to walk through' }))
await user.click(await screen.findByRole('option', { name: 'Staged' }))
await waitFor(() => {
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'staged' })
})
rerender(<ChangesWalkthroughSheet sessionId="ses_2" open onOpenChange={onOpenChange} />)
await waitFor(() => {
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_2', { kind: 'session' })
})
expect(mocks.getChangeWalkthrough).not.toHaveBeenCalledWith('ses_2', { kind: 'staged' })
})
it('clears a generation error when the source changes', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
@@ -381,6 +465,77 @@ describe('ChangesWalkthroughSheet', () => {
expect(screen.getByText('assets/logo.png — binary file')).toBeInTheDocument()
})
it('labels renamed and mode-change omitted files', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(
state({
walkthrough: {
...walkthrough,
omittedFiles: [
{ file: 'src/old.ts', reason: 'renamed' },
{ file: 'script.sh', reason: 'modeChange' },
],
},
}),
)
renderSheet()
expect(await screen.findByText('src/old.ts — renamed')).toBeInTheDocument()
expect(screen.getByText('script.sh — mode change')).toBeInTheDocument()
})
it('renders mechanical files as a compact summary list with counts and diff text for budgeted hunks', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: mechanicalWalkthrough }))
renderSheet()
expect(
await screen.findByRole('list', { name: 'Mechanical file summaries' }),
).toBeInTheDocument()
expect(screen.getByText('pnpm-lock.yaml')).toBeInTheDocument()
expect(screen.getByText('src/__snapshots__/a.ts.snap')).toBeInTheDocument()
expect(screen.getByText('dist/app.js.map')).toBeInTheDocument()
expect(screen.getByText('+120')).toBeInTheDocument()
expect(screen.getByText('-80')).toBeInTheDocument()
expect(screen.getByText('+5')).toBeInTheDocument()
expect(screen.getByText('-7')).toBeInTheDocument()
expect(screen.getByText('new-lock')).toBeInTheDocument()
})
it('renders a stored mechanical stop whose hunks predate hunk counts', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(
state({
walkthrough: {
...walkthrough,
stops: [
{
id: 's_mech',
title: 'Mechanical changes',
explanation: 'Lock files',
hunkIds: ['m_lock'],
status: 'ready',
explanationKey: null,
},
],
hunks: [
{
id: 'm_lock',
file: 'pnpm-lock.yaml',
status: 'modified',
header: '@@ -1 +1 @@',
text: '@@ -1 +1 @@\n-old-lock\n+new-lock',
truncated: false,
},
],
omittedFiles: [],
},
}),
)
renderSheet()
expect(await screen.findByText('pnpm-lock.yaml')).toBeInTheDocument()
expect(screen.getByText('new-lock')).toBeInTheDocument()
expect(screen.queryByRole('list', { name: 'Mechanical file summaries' })).not.toBeInTheDocument()
})
it('renders raw HTML in the summary and stop explanation as inert text', async () => {
const payload =
'<iframe srcdoc="&lt;script&gt;parent.document.documentElement.dataset.walkthroughProbe = 1&lt;/script&gt;"></iframe>'
@@ -14,9 +14,9 @@ import { cn } from '@/lib/utils'
import {
DEFAULT_WALKTHROUGH_SOURCE,
describeWalkthroughSource,
toWalkthroughSource,
walkthroughSourceKey,
WalkthroughOmittedFileSchema,
WalkthroughSourceSchema,
} from '@opencode-manager/shared/schemas'
import type {
ChangeWalkthrough,
@@ -64,6 +64,8 @@ function walkthroughErrorMessage(error: unknown): string {
const OMITTED_REASON_LABELS: Record<WalkthroughOmittedFile['reason'], string> = {
binary: 'binary file',
budget: 'over the diff budget',
renamed: 'renamed',
modeChange: 'mode change',
}
function OmittedFiles({ files }: { files: WalkthroughOmittedFile[] }) {
@@ -79,6 +81,36 @@ function OmittedFiles({ files }: { files: WalkthroughOmittedFile[] }) {
)
}
function isMechanicalHunk(hunk: WalkthroughHunk): boolean {
return hunk.additions !== undefined || hunk.deletions !== undefined
}
function MechanicalHunks({ hunks }: { hunks: WalkthroughHunk[] }) {
return (
<ul aria-label="Mechanical file summaries" className="space-y-3">
{hunks.map((hunk) => (
<li key={hunk.id} className="overflow-hidden rounded-md border border-border">
<div className="flex items-center gap-2 px-3 py-1.5">
<span className="min-w-0 flex-1 truncate text-xs font-medium text-foreground" title={hunk.file}>
{hunk.file}
</span>
<span className={`text-xs ${GIT_STATUS_COLORS[hunk.status]}`}>
{GIT_STATUS_LABELS[hunk.status]}
</span>
<span className="text-xs text-diff-add">+{hunk.additions ?? 0}</span>
<span className="text-xs text-diff-delete">-{hunk.deletions ?? 0}</span>
</div>
{hunk.text.length > 0 ? (
<div className="overflow-x-auto border-t border-border">
<DiffLines diff={hunk.text} />
</div>
) : null}
</li>
))}
</ul>
)
}
interface ChangesWalkthroughContextValue {
isLoading: boolean
walkthrough: ChangeWalkthrough | null
@@ -97,6 +129,13 @@ interface ChangesWalkthroughContextValue {
failedStopCount: number
source: WalkthroughSource
setSource: (source: WalkthroughSource) => void
sourceKind: WalkthroughSource['kind']
setSourceKind: (kind: WalkthroughSource['kind']) => void
baseInput: string
setBaseInput: (base: string) => void
numberInput: string
setNumberInput: (number: string) => void
sourcePending: boolean
}
const ChangesWalkthroughContext = createContext<ChangesWalkthroughContextValue | null>(null)
@@ -116,76 +155,37 @@ const WALKTHROUGH_SOURCE_OPTIONS: { value: WalkthroughSource['kind']; label: str
{ value: 'pullRequest', label: 'Pull request' },
]
function walkthroughSourceLabel(source: WalkthroughSource): string {
return source.kind === 'session' ? 'the changes in this session' : describeWalkthroughSource(source)
}
function sourceBase(source: WalkthroughSource): string {
return source.kind === 'branch' || source.kind === 'pullRequest' ? source.base ?? '' : ''
}
function sourceNumber(source: WalkthroughSource): string {
return source.kind === 'pullRequest' ? String(source.number) : ''
}
/** Chooses which set of changes the walkthrough covers; git sources commit as soon as they are valid. */
const WalkthroughSourcePicker = memo(function WalkthroughSourcePicker() {
const { source, setSource } = useChangesWalkthrough()
const [kind, setKind] = useState<WalkthroughSource['kind']>(source.kind)
const [baseInput, setBaseInput] = useState(sourceBase(source))
const [numberInput, setNumberInput] = useState(sourceNumber(source))
const {
sourceKind,
setSourceKind,
baseInput,
setBaseInput,
numberInput,
setNumberInput,
setSource,
} = useChangesWalkthrough()
useEffect(() => {
setKind(source.kind)
setBaseInput(sourceBase(source))
setNumberInput(sourceNumber(source))
}, [source])
const commit = useCallback(
(candidate: unknown) => {
const parsed = WalkthroughSourceSchema.safeParse(candidate)
if (parsed.success) setSource(parsed.data)
},
[setSource],
)
const branchSource = useCallback((): WalkthroughSource => {
const base = baseInput.trim()
return base ? { kind: 'branch', base } : { kind: 'branch' }
}, [baseInput])
const pullRequestSource = useCallback((): WalkthroughSource => {
const base = baseInput.trim()
return base
? { kind: 'pullRequest', number: Number(numberInput), base }
: { kind: 'pullRequest', number: Number(numberInput) }
}, [baseInput, numberInput])
const commitBase = useCallback(() => {
if (kind === 'branch') {
commit(branchSource())
} else if (kind === 'pullRequest') {
commit(pullRequestSource())
}
}, [kind, commit, branchSource, pullRequestSource])
const commitNumber = useCallback(() => {
commit(pullRequestSource())
}, [commit, pullRequestSource])
const commitInputs = useCallback(() => {
const next = toWalkthroughSource({ kind: sourceKind, base: baseInput, number: Number(numberInput) })
if (next) setSource(next)
}, [sourceKind, baseInput, numberInput, setSource])
const handleKindChange = useCallback(
(next: WalkthroughSource['kind']) => {
setKind(next)
setSourceKind(next)
if (next === 'pullRequest') return
commit(next === 'branch' ? branchSource() : { kind: next })
const nextSource = toWalkthroughSource({ kind: next, base: baseInput })
if (nextSource) setSource(nextSource)
},
[commit, branchSource],
[baseInput, setSourceKind, setSource],
)
return (
<div className="space-y-2">
<Select
value={kind}
value={sourceKind}
onValueChange={(value) => handleKindChange(value as WalkthroughSource['kind'])}
>
<SelectTrigger aria-label="Changes to walk through">
@@ -200,28 +200,28 @@ const WalkthroughSourcePicker = memo(function WalkthroughSourcePicker() {
</SelectContent>
</Select>
{kind === 'branch' || kind === 'pullRequest' ? (
{sourceKind === 'branch' || sourceKind === 'pullRequest' ? (
<Input
aria-label="Base branch"
placeholder="Default branch"
value={baseInput}
onChange={(event) => setBaseInput(event.target.value)}
onBlur={commitBase}
onBlur={commitInputs}
onKeyDown={(event) => {
if (event.key === 'Enter') commitBase()
if (event.key === 'Enter') commitInputs()
}}
/>
) : null}
{kind === 'pullRequest' ? (
{sourceKind === 'pullRequest' ? (
<Input
type="number"
aria-label="Pull request number"
value={numberInput}
onChange={(event) => setNumberInput(event.target.value)}
onBlur={commitNumber}
onBlur={commitInputs}
onKeyDown={(event) => {
if (event.key === 'Enter') commitNumber()
if (event.key === 'Enter') commitInputs()
}}
/>
) : null}
@@ -238,6 +238,9 @@ interface ChangesWalkthroughProviderProps {
/** Loads a session's change walkthrough and shares its state with the surrounding chrome and body. */
export function ChangesWalkthroughProvider({ sessionId, active, children }: ChangesWalkthroughProviderProps) {
const [source, setSource] = useState<WalkthroughSource>(DEFAULT_WALKTHROUGH_SOURCE)
const [sourceKind, setSourceKind] = useState<WalkthroughSource['kind']>(DEFAULT_WALKTHROUGH_SOURCE.kind)
const [baseInput, setBaseInput] = useState('')
const [numberInput, setNumberInput] = useState('')
const sourceKey = walkthroughSourceKey(source)
const stateQuery = useChangeWalkthrough(sessionId, active, source)
const generate = useGenerateChangeWalkthrough(sessionId, source)
@@ -252,14 +255,15 @@ export function ChangesWalkthroughProvider({ sessionId, active, children }: Chan
const error = generate.error ?? stateQuery.error ?? (generating ? null : state?.error ?? null)
const contextLimitFiles = isContextLimitError(error) ? omittedFilesFromError(error) : []
const selectedSource = toWalkthroughSource({ kind: sourceKind, base: baseInput, number: Number(numberInput) })
const sourcePending =
sourceKind === 'pullRequest' &&
(selectedSource === null || walkthroughSourceKey(selectedSource) !== sourceKey)
useEffect(() => {
resetGenerate()
}, [active, sessionId, sourceKey, resetGenerate])
useEffect(() => {
setSource(DEFAULT_WALKTHROUGH_SOURCE)
}, [sessionId])
useEffect(() => {
setStopIndex(0)
}, [active, sessionId, sourceKey, walkthrough?.createdAt])
@@ -299,6 +303,13 @@ export function ChangesWalkthroughProvider({ sessionId, active, children }: Chan
failedStopCount,
source,
setSource,
sourceKind,
setSourceKind,
baseInput,
setBaseInput,
numberInput,
setNumberInput,
sourcePending,
}
return <ChangesWalkthroughContext.Provider value={value}>{children}</ChangesWalkthroughContext.Provider>
@@ -339,7 +350,7 @@ export const ChangesWalkthroughNav = memo(function ChangesWalkthroughNav() {
/** Regenerates the current walkthrough from the chrome; renders nothing until one exists. */
export const ChangesWalkthroughRegenerate = memo(function ChangesWalkthroughRegenerate() {
const { walkthrough, generating, regenerate } = useChangesWalkthrough()
const { walkthrough, generating, regenerate, sourcePending } = useChangesWalkthrough()
if (!walkthrough) return null
@@ -349,7 +360,7 @@ export const ChangesWalkthroughRegenerate = memo(function ChangesWalkthroughRege
size="icon-sm"
aria-label="Regenerate walkthrough"
onClick={regenerate}
disabled={generating}
disabled={generating || sourcePending}
>
<RefreshCw className={generating ? 'animate-spin' : undefined} />
</Button>
@@ -374,9 +385,21 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
detailRef,
failedStopCount,
source,
sourcePending,
} = useChangesWalkthrough()
const readyStopCount = stops.filter((stop) => stop.status === 'ready').length
const mechanicalHunks = selectedHunks.filter(isMechanicalHunk)
const diffHunks = selectedHunks.filter((hunk) => !isMechanicalHunk(hunk))
if (sourcePending) {
return (
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto p-4">
<WalkthroughSourcePicker />
<p className="text-sm text-muted-foreground">Enter a pull request number</p>
</div>
)
}
return (
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto p-4">
@@ -408,7 +431,7 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
generating ? null : (
<div className="space-y-4">
<p className="text-sm text-muted-foreground">
Generate a step-by-step walkthrough of {walkthroughSourceLabel(source)}.
Generate a step-by-step walkthrough of {describeWalkthroughSource(source)}.
</p>
<Button onClick={generate}>Generate walkthrough</Button>
</div>
@@ -481,7 +504,8 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
{generating ? 'Explaining this stop…' : 'This stop could not be explained.'}
</p>
)}
{selectedHunks.map((hunk) => (
{mechanicalHunks.length > 0 ? <MechanicalHunks hunks={mechanicalHunks} /> : null}
{diffHunks.map((hunk) => (
<div key={hunk.id} className="overflow-hidden rounded-md border border-border">
<div className="flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5">
<span className="min-w-0 flex-1 truncate text-xs font-medium text-foreground" title={hunk.file}>
@@ -519,7 +543,7 @@ export function ChangesWalkthroughSheet({ sessionId, open, onOpenChange }: Chang
return (
<SideDrawer isOpen={open} onClose={close} side="right" widthClass="w-full sm:w-[min(640px,92vw)]" ariaLabel="Change walkthrough">
<ChangesWalkthroughProvider sessionId={sessionId} active={open}>
<ChangesWalkthroughProvider key={sessionId} sessionId={sessionId} active={open}>
<SideDrawerHeader
title="Change walkthrough"
onClose={close}
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { useCallback } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { useAutosavedSetting } from '@/hooks/useAutosavedSetting'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { ModelCombobox } from '@/components/model/ModelCombobox'
@@ -12,42 +13,37 @@ import {
type SessionPermissionMode,
} from '@opencode-manager/shared/schemas'
const AUTOSAVE_DELAY_MS = 800
interface GoalDraft {
goalAuditorModel: string
goalMaxContinuations: string
goalTokenBudget: string
}
interface GoalCommitted {
goalAuditorModel: string | undefined
goalMaxContinuations: number
goalTokenBudget: number | undefined
}
function maxContinuationsFromInput(value: string): number | null {
const parsed = Number(value)
if (!Number.isInteger(parsed)) return null
if (parsed < GOAL_MAX_CONTINUATIONS_MIN || parsed > GOAL_MAX_CONTINUATIONS_MAX) return null
return parsed
}
function tokenBudgetFromInput(value: string): { valid: boolean; value: number | undefined } {
const trimmed = value.trim()
if (trimmed === '') return { valid: true, value: undefined }
const parsed = Number(trimmed)
return Number.isInteger(parsed) && parsed > 0 ? { valid: true, value: parsed } : { valid: false, value: undefined }
}
export function SessionAutomationSettings() {
const { preferences, updateSettings } = useSettings()
const sessionDefaults = preferences?.sessionDefaults
const permissionMode = sessionDefaults?.permissionMode ?? DEFAULT_SESSION_DEFAULTS.permissionMode
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({
@@ -61,44 +57,46 @@ export function SessionAutomationSettings() {
[sessionDefaults, permissionMode, updateSettings],
)
const commitGoalFields = useCallback(() => {
const patch: Partial<SessionDefaults> = {}
const { draft, setDraft, commit: commitGoalFields } = useAutosavedSetting<SessionDefaults | undefined, GoalDraft, GoalCommitted>({
stored: sessionDefaults,
toDraft: (stored) => ({
goalAuditorModel: stored?.goalAuditorModel ?? '',
goalMaxContinuations: String(stored?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations),
goalTokenBudget: stored?.goalTokenBudget !== undefined ? String(stored.goalTokenBudget) : '',
}),
toCommitted: (current, previous) => {
const budget = tokenBudgetFromInput(current.goalTokenBudget)
return {
goalAuditorModel: current.goalAuditorModel.trim() || undefined,
goalMaxContinuations:
maxContinuationsFromInput(current.goalMaxContinuations) ??
previous?.goalMaxContinuations ??
DEFAULT_SESSION_DEFAULTS.goalMaxContinuations,
goalTokenBudget: budget.valid ? budget.value : previous?.goalTokenBudget,
}
},
isEqual: (a, b) =>
a.goalAuditorModel === b.goalAuditorModel &&
a.goalMaxContinuations === b.goalMaxContinuations &&
a.goalTokenBudget === b.goalTokenBudget,
save: (next, previous) => {
const patch: Partial<SessionDefaults> = {}
if (next.goalAuditorModel !== previous?.goalAuditorModel) patch.goalAuditorModel = next.goalAuditorModel
if (next.goalMaxContinuations !== previous?.goalMaxContinuations) {
patch.goalMaxContinuations = next.goalMaxContinuations
}
if (next.goalTokenBudget !== previous?.goalTokenBudget) patch.goalTokenBudget = next.goalTokenBudget
if (Object.keys(patch).length === 0) return
updateSessionDefaults(patch)
},
})
const nextAuditorModel = goalAuditorModel.trim() || undefined
if (nextAuditorModel !== committed.current.goalAuditorModel) {
committed.current.goalAuditorModel = nextAuditorModel
patch.goalAuditorModel = nextAuditorModel
}
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(() => {
commitGoalFields()
}, AUTOSAVE_DELAY_MS)
return () => clearTimeout(timer)
}, [commitGoalFields])
const updateGoalDraft = useCallback(
(patch: Partial<GoalDraft>) => {
setDraft((current) => ({ ...current, ...patch }))
},
[setDraft],
)
return (
<div className="space-y-6">
@@ -135,8 +133,8 @@ export function SessionAutomationSettings() {
<ModelCombobox
id="goalAuditorModel"
ariaLabel="Goal auditor model"
value={goalAuditorModel}
onChange={setGoalAuditorModel}
value={draft.goalAuditorModel}
onChange={(value) => updateGoalDraft({ goalAuditorModel: value })}
placeholder="OpenCode default"
allowCustomValue
showClear
@@ -156,9 +154,9 @@ export function SessionAutomationSettings() {
type="number"
min={GOAL_MAX_CONTINUATIONS_MIN}
max={GOAL_MAX_CONTINUATIONS_MAX}
value={goalMaxContinuations}
value={draft.goalMaxContinuations}
className="w-full shrink-0 sm:w-40"
onChange={(event) => setGoalMaxContinuations(event.target.value)}
onChange={(event) => updateGoalDraft({ goalMaxContinuations: event.target.value })}
onBlur={commitGoalFields}
/>
</div>
@@ -174,10 +172,10 @@ export function SessionAutomationSettings() {
id="goalTokenBudget"
type="number"
min={1}
value={goalTokenBudget}
value={draft.goalTokenBudget}
placeholder="No limit"
className="w-full shrink-0 sm:w-40"
onChange={(event) => setGoalTokenBudget(event.target.value)}
onChange={(event) => updateGoalDraft({ goalTokenBudget: event.target.value })}
onBlur={commitGoalFields}
/>
</div>
@@ -138,4 +138,17 @@ describe('WalkthroughSettings', () => {
vi.useRealTimers()
}
})
it('keeps the OpenCode default as a selectable model when the field is unset', () => {
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: 'anthropic/claude-sonnet-4' })
mockUseSettings()
render(<WalkthroughSettings />)
const input = screen.getByLabelText('Walkthrough model')
expect(input).toHaveValue('')
fireEvent.focus(input)
expect(screen.getByRole('option', { name: /Claude Sonnet 4/ })).toBeInTheDocument()
expect(screen.queryByRole('option', { name: /^Default:/ })).not.toBeInTheDocument()
})
})
@@ -1,36 +1,19 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { useAutosavedSetting } from '@/hooks/useAutosavedSetting'
import { Label } from '@/components/ui/label'
import { ModelCombobox } from '@/components/model/ModelCombobox'
const AUTOSAVE_DELAY_MS = 800
export function WalkthroughSettings() {
const { preferences, updateSettings } = useSettings()
const storedWalkthroughModel = preferences?.walkthroughModel
const [walkthroughModel, setWalkthroughModel] = useState(storedWalkthroughModel ?? '')
const committed = useRef(storedWalkthroughModel)
useEffect(() => {
setWalkthroughModel(storedWalkthroughModel ?? '')
committed.current = storedWalkthroughModel
}, [storedWalkthroughModel])
const commitWalkthroughModel = useCallback(() => {
const next = walkthroughModel.trim()
if (next === (committed.current ?? '')) return
committed.current = next
updateSettings({ walkthroughModel: next })
}, [walkthroughModel, updateSettings])
useEffect(() => {
const timer = setTimeout(() => {
commitWalkthroughModel()
}, AUTOSAVE_DELAY_MS)
return () => clearTimeout(timer)
}, [commitWalkthroughModel])
const { draft: walkthroughModel, setDraft: setWalkthroughModel } = useAutosavedSetting({
stored: storedWalkthroughModel,
toDraft: (stored) => stored ?? '',
toCommitted: (draft) => draft.trim(),
isEqual: (a, b) => a === b,
save: (next) => updateSettings({ walkthroughModel: next }),
})
return (
<div className="space-y-6">
@@ -51,6 +34,7 @@ export function WalkthroughSettings() {
placeholder="Session model"
allowCustomValue
showClear
emptyMeansDefault={false}
className="w-full shrink-0 sm:w-64"
/>
</div>